3 # Resource limiting wrapper for command execution
5 # Why is this in shell script? Because bash has a setrlimit() wrapper
6 # and is available on most Linux systems. If Perl was distributed with
7 # BSD::Resource included, we would happily use that instead, but it isn't.
11 # First we have to move the current task into a "garbage" group, otherwise
12 # the cgroup will not be empty, and attempting to remove it will fail with
13 # "Device or resource busy"
14 if [ -w "$MW_CGROUP"/tasks
]; then
17 GARBAGE
="$MW_CGROUP"/garbage-
`id -un`
18 if [ ! -e "$GARBAGE" ]; then
19 mkdir
-m 0700 "$GARBAGE"
22 echo $BASHPID > "$GARBAGE"/tasks
24 # Suppress errors in case the cgroup has disappeared due to a release script
25 rmdir "$MW_CGROUP"/$$
2>/dev
/null
29 # There are lots of ways to count lines in a file in shell script, but this
30 # is one of the few that doesn't create another process, which would
31 # increase the returned number of tasks.
32 readarray
< "$MW_CGROUP"/$$
/tasks
33 NUM_TASKS
=${#MAPFILE[*]}
37 echo limit.sh
: "$*" >&3
38 echo limit.sh
: "$*" >&2
52 if [ -n "$MW_INCLUDE_STDERR" ]; then
55 if [ -z "$MW_USE_LOG_PIPE" ]; then
60 if [ "$MW_CPU_LIMIT" -gt 0 ]; then
61 ulimit -t "$MW_CPU_LIMIT"
63 if [ "$MW_MEM_LIMIT" -gt 0 ]; then
64 if [ -n "$MW_CGROUP" ]; then
66 if ! mkdir
-m 0700 "$MW_CGROUP"/$$
; then
67 log
"failed to create the cgroup."
71 if [ -n "$MW_CGROUP" ]; then
72 echo $$
> "$MW_CGROUP"/$$
/tasks
73 if [ -n "$MW_CGROUP_NOTIFY" ]; then
74 echo "1" > "$MW_CGROUP"/$$
/notify_on_release
77 echo $
(($MW_MEM_LIMIT*1024)) > "$MW_CGROUP"/$$
/memory.limit_in_bytes
79 # This will be missing if there is no swap
80 if [ -e "$MW_CGROUP"/$$
/memory.memsw.limit_in_bytes
]; then
81 echo $
(($MW_MEM_LIMIT*1024)) > "$MW_CGROUP"/$$
/memory.memsw.limit_in_bytes
84 ulimit -v "$MW_MEM_LIMIT"
89 if [ "$MW_FILE_SIZE_LIMIT" -gt 0 ]; then
90 ulimit -f "$MW_FILE_SIZE_LIMIT"
92 if [ "$MW_WALL_CLOCK_LIMIT" -gt 0 -a -x "/usr/bin/timeout" ]; then
93 /usr
/bin
/timeout
$MW_WALL_CLOCK_LIMIT /bin
/bash
-c "$1" 3>&-
95 if [ "$STATUS" == 124 ]; then
96 log
"timed out executing command \"$1\""
103 if [ -n "$MW_CGROUP" ]; then
106 if [ $NUM_TASKS -gt 1 ]; then
107 # Spawn a monitor process which will continue to poll for completion
108 # of all processes in the cgroup after termination of the parent shell
110 while [ $NUM_TASKS -gt 1 ]; do
115 ) >&/dev
/null
< /dev
/null
3>&- &