Systemd资源配额使用案例
背景
服务运行在一台混合实例中,为保证资源的公平性质,需要针对将不同的服务资源进行资源配额--确保不会因一个服务的而影响所有。
示例
CPU
假设 openresty 运行在一台8C的节点上,需要针对 openresty 服务进程不会超过1C的50%,同时将Openresty的服务优先级提高--即使CPU资源不足也要优先保证Openresty服务。假设openresty 服务控制文件在/etc/systemd/system/openresty.service操作如下:
mkdir /etc/systemd/system/openresty.service.d/
cat >/etc/systemd/system/openresty.service.d/cpu.conf<<EOF
[Service]
CPUAccounting=true
CPUShares=2048
CPUQuota=50%
EOF- CPUAccounting: 开启记录 CPU 使用情况;
- CPUShares: 相对优先级,默认为1024,值越高优先级也随之越高;
- CPUQuota:需要限制CPU的上限,值为百分比,如:CPUQuota=50% ,确保进程在一个 CPU 上占用的 CPU 时间永远不会超过 50%
服务重启
systemctl daemon-reload
systemctl restart openresty
如何验证?
# systemctl show openresty.service | grep -i cpu
CPUUsageNSec=48977955
CPUAccounting=yes
CPUShares=2048
CPUQuotaPerSecUSec=250ms
...<省略若干行>...
还可以查看/sys目录下的cgroup状态文件
cat /sys/fs/cgroup/cpu/system.slice/openresty.service/cpu.cfs_quota_us内存
还是以openresty 服务为例,节点整体资源为32G,我们允许Openresty服务最大使用2G。
mkdir /etc/systemd/system/openresty.service.d/
cat >/etc/systemd/system/openresty.service.d/memory.conf<<EOF
[Service]
MemoryLimit=2G
EOF- MemoryLimit:服务能最大使用内在的上限值。
服务重启
systemctl daemon-reload
systemctl restart openresty
如何验证?
# systemctl show openresty.service | grep -i memory
MemoryCurrent=21016576
...<省略若干行>...
还可以查看/sys目录下的cgroup状态文件
# cat /sys/fs/cgroup/memory/system.slice/openresty.service/memory.limit_in_bytes
2147483648测试
CPU
systemd-run --unit=cpu-stress -p "CPUQuota=200%" -p "CPUAccounting=true" stress --cpu 8参数注解:
- 使用stress工具模拟8个CPU核心的满载负载
- 限制stress最多只能分能分配两个核心
cgtop状态
Control Group Tasks %CPU Memory Input/s Output/s
/ 220 203.0 5.2G - -
system.slice 57 199.0 399.0M - -
system.slice/cpu-stress.service 5 198.9 192.0K - -
TOP查看更为直观