How to control resource (cgroup) with systemd for user process group in CentOS/RHEL 7

kevin.Zhu 发布于:2022-11-20 17:26 分类:文摘  有 20 人浏览,获得评论 0 条  

https://www.thegeekdiary.com/how-to-control-resource-cgroup-with-systemd-for-user-process-group-in-centos-rhel-7/


The Basics

RHEL7 moves the resource management settings from the process level to the application level by binding the system of cgroup hierarchies with the systemd unit tree. The old way of configuring cgroup, by means of editing several /etc/cg*.conf files is still available but no longer recommended.

Systemd provides three unit types(slicescopeservice) that are used for the purpose of resource control.

Handling cgroup with service unit of systemd

1. Customize a service unit for your service in /etc/systemd/system, if your service don’t have systemd service unit. You need to make a start/stop script to manage your service.

# cat /etc/systemd/system/mytask.service
[Unit]
Description= **
After=remote-fs.target nss-lookup.target

[Service]
ExecStart=/root/start_process.sh
ExecStop=/root/stop_process.sh

[Install]
WantedBy=multi-user.target

2. Control the resource via command line(take control the cpu quota 60% as sample)

# systemctl set-property mytask CPUQuota=60%

By default, it only support following attributes via command set-property.

AccuracySec=            CPUQuota=               KillMode=               LimitLOCKS=             LimitRTPRIO=            SendSIGHUP=
BlockIOAccounting=      CPUShares=              KillSignal=             LimitMEMLOCK=           LimitRTTIME=            SendSIGKILL=
BlockIODeviceWeight=    DefaultDependencies=    LimitAS=                LimitMSGQUEUE=          LimitSIGPENDING=        User=
BlockIOReadBandwidth=   DeviceAllow=            LimitCORE=              LimitNICE=              LimitSTACK=             WakeSystem=
BlockIOWeight=          DevicePolicy=           LimitCPU=               LimitNOFILE=            MemoryAccounting=       
BlockIOWriteBandwidth=  Environment=            LimitDATA=              LimitNPROC=             MemoryLimit=            
CPUAccounting=          Group=                  LimitFSIZE=             LimitRSS=               Nice=      

3. If you want to set the attribute which is not listed as above, you can use the following method.

# echo 70 > /sys/fs/cgroup/memory/system.slice/httpd.service/memory.swappiness

Or control the resource via modifying the service unit files

# cat /etc/systemd/system/mytask.service
[Unit]
Description= **
After=remote-fs.target nss-lookup.target

[Service]
CPUQuota=90%
MemoryLimit=1500000
ExecStartPre=/bin/bash -c '/bin/echo 70 > /sys/fs/cgroup/memory/system.slice/httpd.service/memory.swappiness'
#ExecStartPost
ExecStart=/root/start_process.sh
ExecStop=/root/stop_process.sh

[Install]
WantedBy=multi-user.target

4. Reload systemd manager configuration and start your service

# systemctl daemon-reload   
# systemctl start mytask