Run command in a temporary cgroup
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
set -e | |
MYNAME=$(basename $0) | |
usage() { | |
echo "${MYNAME} runs a command in a temporary cgroup with cpu and/or memory limits." | |
echo "Usage: ${MYNAME} [-c <cpu_shares>] [-m <mem_limit>] [-s <swmem_limit>] [-h] command args..." | |
exit 1 | |
} | |
debug_msg() { | |
if [ "$CGROUP_LOGLEVEL" = "DEBUG" ]; then | |
echo "${MYNAME}: $@" >&2 | |
fi | |
} | |
CGID="${MYNAME}_$(uuidgen)" | |
CGPATH="cpu,memory:${CGID}" | |
while getopts ":c:m:s:h" o; do | |
case "$o" in | |
c) CPU_LIMIT="$OPTARG";; | |
m) MEM_LIMIT="$OPTARG";; | |
s) SWP_LIMIT="$OPTARG";; | |
h) usage;; | |
?) break;; | |
esac | |
done | |
shift "$(($OPTIND-1))" | |
if [ $# -eq 0 ]; then | |
usage | |
fi | |
sudo cgcreate -a $USER:root -t $USER:root -g "${CGPATH}" | |
cleanup() { | |
sudo cgdelete "${CGPATH}" | |
} | |
trap cleanup EXIT | |
if [ -n "$CPU_LIMIT" ]; then | |
debug_msg "setting CPU shares to $CPU_LIMIT" | |
cgset -r "cpu.shares=$CPU_LIMIT" "$CGID" | |
fi | |
if [ -n "$MEM_LIMIT" ]; then | |
debug_msg "setting memory limit to $MEM_LIMIT" | |
cgset -r "memory.limit_in_bytes=$MEM_LIMIT" "$CGID" | |
fi | |
if [ -n "$SWP_LIMIT" ]; then | |
debug_msg "setting memory+swap limit to $SWP_LIMIT" | |
cgset -r "memory.memsw.limit_in_bytes=$SWP_LIMIT" "$CGID" | |
fi | |
cgexec --sticky -g "$CGPATH" $@ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment