#!/bin/sh
# minc-cage: cgroup setup script
#
# Copyright (C) 2015 Masami Hiramatsu <masami.hiramatsu@gmail.com>
# This program is released under the MIT License, see LICENSE.

CGROOT=/sys/fs/cgroup
MEMCG=$CGROOT/memory/mincs/`basename $MINC_TMPDIR`
CPUCG=$CGROOT/cpu/mincs/`basename $MINC_TMPDIR`
PIDCG=$CGROOT/pids/mincs/`basename $MINC_TMPDIR`
CGDIRS=

set -e

cleanup_cages() { # dirs
  [ "$MINC_MEM_LIMIT" ] && echo $$ > $CGROOT/memory/tasks
  [ "$MINC_CPU_SHARES" -o "$MINC_CPU_QUOTA" ] && echo $$ > $CGROOT/cpu/tasks
  [ "$MINC_PID_MAX" ] && echo $$ > $CGROOT/pids/tasks
  rmdir $@
}

# with --prepare option, this sets up the cgroups and returns cleanup command
if [ "x$1" = "x--prepare" ]; then
  :;: "Prepare Cgroups if needed";:
  [ "$MINC_MEM_LIMIT" ] && CGDIRS="$CGDIRS $MEMCG"
  [ "$MINC_CPU_SHARES" -o "$MINC_CPU_QUOTA" ] && CGDIRS="$CGDIRS $CPUCG"
  [ "$MINC_PID_MAX" ] && CGDIRS="$CGDIRS $PIDCG"
  if [ "$CGDIRS" ]; then
    mkdir -p $CGDIRS
    echo "cleanup_cages $CGDIRS"
  fi
  exit 0;
fi

# MINC_MEM_LIMIT - memory limit in bytes
# MINC_MEM_SWAP - swap+memory limit in bytes

if [ "$MINC_MEM_LIMIT" ]; then
  :;: 'Set cgroups memory limit';:
  test -d $MEMCG
  echo $MINC_MEM_LIMIT > $MEMCG/memory.limit_in_bytes
  [ "$MINC_MEM_SWAP" ] && \
    echo $MINC_MEM_SWAP > $MEMCG/memory.memsw.limit_in_bytes
  [ "$MINC_MEM_KMEM" ] &&
    echo $MINC_MEM_KMEM > $MEMCG/memory.kmem.limit_in_bytes
  echo $$ > $MEMCG/tasks
fi

# MINC_CPU_SHARES - CPU shares of the container (default: 1024)
# MINC_CPU_QUOTA - CPU quota of the container in usec (default: 100000)

if [ "$MINC_CPU_SHARES" ]; then
  :;: 'Set cgroups CPU share limit';:
  test -d $CPUCG
  echo $MINC_CPU_SHARES > $CPUCG/cpu.shares
  echo $$ > $CPUCG/tasks
fi

if [ "$MINC_CPU_QUOTA" ]; then
  :;: 'Set cgroups CPU quota limit';:
  test -d $CPUCG
  echo $MINC_CPU_QUOTA > $CPUCG/cpu.cfs_quota_us
  echo $$ > $CPUCG/tasks
fi

# MINC_PID_MAX - The max number of PID
if [ "$MINC_PID_MAX" ]; then
  :;: 'Set cgroups max PID limit';:
  test -d $PIDCG
  echo $MINC_PID_MAX > $PIDCG/pids.max
  echo $$ > $PIDCG/cgroup.procs
fi
