Monday, February 25, 2019

Cgroups


Basic Information
-----------------

- Kernel feature that limits CPU, memory, Disk I/O and network usage of
  processes.
- More sophisticated than `ulimit`.
- Some resources that can be controlled via cgroups:
    a. cpu share
    b. cpu number to use
    c. memory
    d. and many more

Controllers
-----------

memory
limits memory usage
cpuacct
monitors cpu usage

Tutorials
---------

Commands to check
# Check process cgroup membership
ps -o cgroup <PID>
Creating cgroups manually (not persistent)
1. Install packages
yum install libcgroup libcgroup-tools
 
2. Create group under memory controller
mkdir /sys/fs/cgroup/memory/foo

3. Create this shell script
#!/bin/bash

while true; do
  echo hello > /dev/null
  sleep 1
done

4. Run script in background to emulate memory consuming process
bash test.sh &

5. Apply memory limit under "foo" group
echo 5 > /sys/fs/cgroup/memory/memory.limit_in_bytes

6. Get PID of script and include it under "foo" group
echo (pgrep -f test.sh) > /sys/fs/cgroup/memory/foo/cgroup.procs

7. Notice that script was killed by OOM
journalctl | tail
Creating cgroups using "libcgroup" (not persistent)
1. Install packages
yum install libcgroup libcgroup-tools
 
2. Create group under memory controller
cgcreate -g memory:foo

3. Create this shell script
#!/bin/bash

while true; do
  echo hello > /dev/null
  sleep 1
done

4. Run script in background to emulate memory consuming process
cgexec -g memory:foo test.sh &

5. Apply memory limit under "foo" group
echo 5 > /sys/fs/cgroup/memory/memory.limit_in_bytes

6. Notice that script was killed by OOM
journalctl | tail
Enabling persistent configurations
1. Update /etc/cgconfig.conf
 
group foo {
  cpu {
    cpu.shares = 100;
  }
  memory {
    memory.limit_in_bytes = 5;
  }
}

2. Enable service
systemctl enable --now cgconfig

3. Run a program under cgroup control
cgexec -g memory:foo test.sh &


No comments:

Post a Comment