I'm trying to write init_cgroup.sh script, that will create container with specified in args limitations. As I understood, I need to find out the cgroup version at first, mount it, and then apply options to corresponding files
Here is how I tried to do it:
#!/bin/sh
# args:
# $1 - mem_limit (not used at the moment)
# $2 - core usage percentage (e.g. 0.1)
# $3 - container name
GROUP_ID=$3
GROUP_PATH="/sys/fs/cgroup"
mount -t tmpfs -o rw,nosuid,nodev,noexec,relatime,size=0k cgroup_root $GROUP_PATH
mount -t cgroup2 none $GROUP_PATH
if [ $? != "0" ]; then
mkdir "$GROUP_PATH/$GROUP_ID"
mount -t cgroup -o cpu,cpuset,cpuacct,memory cgroup_cpu "$GROUP_PATH/$GROUP_ID"
echo 100000 > "$GROUP_PATH/$GROUP_ID/cpu.cfs_quota_us"
echo "100000*$2" > "$GROUP_PATH/$GROUP_ID/cpu.cpu.cfs_period_us"
cpus_count=$(grep -c processor /proc/cpuinfo)
rand_cpu=$RANDOM%cpus_count
echo $rand_cpu > "$GROUP_PATH/$GROUP_ID/cpuset.cpus"
else
{
echo "+cpu"
echo "+cpuset"
echo "+memory"
} >> "$GROUP_PATH/cgroup.subtree_control"
mkdir "$GROUP_PATH/$GROUP_ID"
cpus_count=$(grep -c processor /proc/cpuinfo)
rand_cpu=$RANDOM%$cpus_count
echo "$rand_cpu" > "$GROUP_PATH/$GROUP_ID/cpuset.cpus"
fi
P.S.: I should get as a result that the tasks in my group were executed on only one core, so I assigned it to a random cpu (temporary solution)
When running the script with sudo, it creates folders in
/sys/fs/cgroup, but outputs an error:
> sudo ./init_cgroup.sh 0 0.1 testt
> ./init_cgroup.sh: 29: echo: echo: I/O error
I figured out that I/O error causes because it hasn't have enough rights to write in system folder, even if I run it with sudo.
What should I do with it, and did I do it properly at all?
As @Cyrus mentioned sh
is not an bash
, so the first one isn't containing $RANDOM
variable, and echo
tried to write some trash in file. The solution was just change #!/bin/sh
to #!/bin/bash