Skip to content

Instantly share code, notes, and snippets.

@mvollrath
Last active August 30, 2021 21:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mvollrath/bd15599fdcaa6949f01ba6db66119196 to your computer and use it in GitHub Desktop.
Save mvollrath/bd15599fdcaa6949f01ba6db66119196 to your computer and use it in GitHub Desktop.
Run command in a temporary cgroup
#!/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