Skip to content

Instantly share code, notes, and snippets.

@JayGoldberg
Created April 11, 2017 15:25
Show Gist options
  • Save JayGoldberg/8822f0ac524435979c7d62e7088382fd to your computer and use it in GitHub Desktop.
Save JayGoldberg/8822f0ac524435979c7d62e7088382fd to your computer and use it in GitHub Desktop.
Constrain an applications resources using cgroups
#!/usr/bin/env bash
## @author Jay Goldberg
## @email jaymgoldberg@gmail.com
## @license Apache 2.0
## @description constrains an execution to memory and cpu limits using cgroups
## @usage heifer.sh <cpushares_limit> <mem_limit> <command -args>
## @require cgcreate
## @require cgexec
## @require sudo
#=======================================================================
require=(cgcreate cgexec sudo)
# TODO check that all args present
# TODO check that first 2 args are integers
cpulimit=${1:-768} # 0-1024
memlimit=${2:-4096} # in MB
usage () {
# TODO HEREDOC
echo "incorrect usage"
exit 1
}
# TODO not sure what this is, I wrote it a bit ago
processname="${3? $(usage)}"
shift
shift
u=$(id -un)
g=$(id -gn)
cleanup () {
# delete the cgroup when script exits
# this can also be handled by ????
echo Calling cleanup
sudo cgdelete memory,cpu:${processname}
}
trap cleanup EXIT
# create cgroup with -a (parameter owner) and -t (tasks file owner)
# if not exists, create
echo Opening sudo to create user-managed cgroup space
sudo cgcreate -a "$u:$g" -t "$u:$g" -g cpu,memory:${processname}
# can also use `cgset`
echo Setting CPU limit...
echo $cpulimit > /sys/fs/cgroup/cpu/${processname}/cpu.shares
echo Setting memory limit...
echo $(($memlimit*1024*1024)) > /sys/fs/cgroup/memory/${processname}/memory.limit_in_bytes
echo Executing the target binary \"${processname}\" using bash
cgexec -g cpu,memory:${processname} --sticky bash -c "$@"
# Bessie the heifer the queen of all cows
# She gave more milk than any law allows
# In the mornin' she gave pasteurized
# At nite she gave homogenized
# Bessie the heifer the queen of all the cows.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment