Centos 7 资源限制方式

cgroup资源限制

yum install libcgroup libcgroup-tools
安装好了后 服务
systemctl restart cgconfig.service
systemctl restart cgred.service
Linux Cgroups(Linux Control Groups)提供了对一组进程及将来子进程的资源限制、控制、统计的能力。这些资源包括cpu、内存、存储、网络 等。通过Cgroups,可以方便的控制某个进程占用的资源,并可以实施监控和统计信息。
cgcreate -hUsage: cgcreate [-h] [-f mode] [-d mode] [-s mode] [-t :] [-a :] -g : [-g …]Create control group(s)-a : Owner of the group and all its files-d, –dperm=mode Group directory permissions-f, –fperm=mode Group file permissions-g : Control group which should be added-h, –help Display this help-s, –tperm=mode Tasks file permissions-t : Owner of the tasks file
cgroup 是对进程分组管理的一种机制,一个cgroup包含一组进程,并可以在这个cgroup上增加Linux subsystem的各种参数配置,将一组进程和一 组subsystem的系统参数关联起来。
subsystem 是一组资源控制的模块。包含以下几项。
blkio 设置对块设备输入输出的访问控制。例如磁盘cpu 设置cgroup中进程的cpu被调度策略。cpuacct 可以统计cgroup中进程的cpu占用。cpuset 在多核机器上,设置cgroup中进程可以使用的cpu和内存。此处仅限于NUMA架构。devices 控制cgroup对设备的访问。freezer 挂起(suspend)和恢复(resue) cgroup中的进程。memory 用于控制cgroup中进程的内存占用。net_cls 将cgroup中进程产生的网络包分类,便于linux tc(traffic controller)可以根据分类区分出来自某个cgroup包并做监控。net_prio 设置cgroup中进程产生的网络流量的优先级。ns 使cgroup中的进程在新的Namespace中fork新进程时,创建一个新的cgroup,这个cgroup包含新的Namespace中的进程。

cgcreate -g cpu:/large # 具体命令使用cgcreate -hcgcreate -g cpu:/small
可以到/sys/fs/cgroup/cpu目录下查看,默认值是1024,值越大,能获得更多的cpu时间
cpu.shares是cpu控制的一个属性,更多的属性
cgset -r cpu.shares=512 small
cgexec启动一个cgroup任务
cgexec -g cpu:small /usr/local/bin/matho-primes 0 999999999 > /dev/null & # 后台

下载测试工具
git clone https://github.com/mfillpot/mathomatic
cd primes/
make
make install
/usr/local/bin/matho-primes

cpulimit资源限制
wget https://download-ib01.fedoraproject.org/pub/epel/7/x86_64/Packages/c/cpulimit-0.2-1.20151118gitf4d2682.el7.x86_64.rpm
wget -O cpulimit.zip https://github.com/opsengine/cpulimit/archive/master.zip
unzip cpulimit.zip
cd cpulimit-master
make
sudo cp src/cpulimit /usr/bin
上面的命令行,会先从从 GitHub 上将源码下载到本地,然后再解压、编译、并安装到 /usr/bin 目录下。
cpulimit 的使用方式和 nice 命令类似,但是需要用户使用 -l 选项显式地定义进程的 cpu 使用率上限值。举例说明:
代码如下:
cpulimit -l 50 matho-primes 0 9999999999 > /dev/null &
从上面的例子可以看出 matho-primes 只使用了50%的 cpu 资源,剩余的 cpu 时间都在 idle。
cpulimit 还可以在运行时对进程进行动态限制,使用 -p 选项来指定进程的 PID,下面是一个实例:
代码如下:
cpulimit -l 50 -p 1234
其中,1234是进程的 PID。

nice命令
nice -n 值 命令
默认不带nice的时候 top可以看到ni值是0 带nice 不写值的时候 默认是10.
[root@localhost ~]# nice –helpUsage: nice [OPTION] [COMMAND [ARG]…]Run COMMAND with an adjusted niceness, which affects process scheduling.With no COMMAND, print the current niceness. Niceness values range from-20 (most favorable to the process) to 19 (least favorable to the process).
Mandatory arguments to long options are mandatory for short options too.-n, –adjustment=N add integer N to the niceness (default 10)–help display this help and exit–version output version information and exit
NOTE: your shell may have its own version of nice, which usually supersedesthe version described here. Please refer to your shell’s documentationfor details about the options it supports.
GNU coreutils online help: http://www.gnu.org/software/coreutils/For complete documentation, run: info coreutils ‘nice invocation’

cgroup可以做按用户来限制资源
/etc/cgconfig.d/ 创建个配置文件conf
group orange_limitmem{
memory {
memory.limit_in_bytes=200m;
memory.memsw.limit_in_bytes=200m;
}
}
在文件/etc/cgrules.conf中添加对 orange 用户的规则,关联步骤2的控制组
echo “orange memory orange_limitmem/”>> /etc/cgrules.conf
centos7中进行资源限制,使用的仍然是cgroup,只是配置接口使用的systemd。下文将介绍如何使用systemd进行资源限制。

Step1 编写unit文件命令为my-demo.service
整个文件如下:
[Unit]
Description=My-demo Service
[Service]Type=simple
User=orange
ExecStart=/bin/bash /home/orange/test.sh
MemoryAccounting=trueMemoryLimit=200M
[Install]
WantedBy=multi-user.target
关于Type的定义
simple 默认类型,这是最简单的服务类型。意思就是说启动的程序就是主体程序,这个程序要是退出那么一切都退出。forking 标准Unix Daemon 使用的启动方式。启动程序后会调用 fork() 函数,父进程退出,留下变成Deamon精灵的子进程。oneshot 表示服务类型就是启动,执行完成后,没进程存在。User字段表示指定用户启动程序。
MemoryLimit字段表示限制服务的物理内存占用,如果超过会被系统自动Kill。另外,test.sh的脚本定义如下,作用是耗内存:
!/bin/bash
tmp=”a”
while [ True ]
do
tmp=$tmp$tmp
done

Step2
将上述的文件拷贝到/usr/lib/systemd/system/目录下
cp my-demo.service /usr/lib/systemd/system/

Step3 配置开机启动
systemctl enable my-demo.service
ln -s’/usr/lib/systemd/system/my-demo.service’ ‘/etc/systemd/system/multi-user.target.wants/my-demo.service’输出表明,注册的过程实际上就是将服务链接到/etc/systemd/system/目录下。

Step4 测试启动服务
systemctl start my-demo.service
查看服务是否已经启动
systemctl status my-demo.service

查看进程占用内存
top
可以看到内存占用在上升,大约不到1分钟,就会看到进程由于内存超出限制而被Kill。可以在/var/log/message中看到被Kill的记录。

我们已经知道,centos7上建议使用sytemd进行资源限制。
本文主要介绍如何使用systemd进行用户级资源限制。以orange用户为例。
方案一 临时有效配置如下:
systemctl set-property user-1000.slice MemoryLimit=200M
systemctl daemon-reload
一般情况下,以上设置就可以了。但有时还是会遇到以下问题:
systemctl set-property user-1000.slice MemoryLimit=200M
Failed to set unit properties on user-1000.slice: Unit user-1000.slice is not loaded.
User with id 1007 not logged in. First login as that user then set limits解决办法首先使用
systemctl start user-1000.slice
再进行设置
systemctl set-property user-1000.slice MemoryLimit=200M
systemctl daemon-reload

方案二 永久生效首先,编写slice文件user-1000.slice
其中1000是orange用户的uid,可用命令查看
id -u username
文件内容如下
[Unit]
Description=orange user.slice
[Slice]
MemoryAccounting=trueMemoryLimit=200M
其次,拷贝到指定位置
cp user-1000.slice /usr/lib/systemd/system
启用
systemctl start user-1000.slice
重新加载配置
systemctl daemon-reload
查看系统中的slice
systemctl -t slice
UNIT LOAD ACTIVE SUB DESCRIPTION-.slice loaded active active Root Slicesystem-getty.slice loaded active active system-getty.slicesystem-selinux\x2dpolicy\x2dmigrate\x2dlocal\x2dchanges.slice loaded active active system-selinux\x2dpolicy\x2dmigrate\x2dlocal\x2dchanges.slicesystem.slice loaded active active System Sliceuser-0.slice loaded active active User Slice of rootuser-1000.slice loaded active active orange user.sliceuser.slice loaded active active User and Session Slice
LOAD = Reflects whether the unit definition was properly loaded.ACTIVE = The high-level unit activation state, i.e. generalization of SUB.SUB = The low-level unit activation state, values depend on unit type.
7 loaded units listed. Pass –all to see loaded but inactive units, too.To show all installed unit files use ‘systemctl list-unit-files’.查看某个具体的slice
systemctl status user-1000.slice -l
● user-1000.slice – orange user.sliceLoaded: loaded (/usr/lib/systemd/system/user-1000.slice; static; vendor preset: disabled)Drop-In: /etc/systemd/system/user-1000.slice.d└─50-MemoryLimit.confActive: active since 四 2018-08-02 15:17:01 CST; 1min 40s agoMemory: 1.5M (limit: 200.0M)CGroup: /user.slice/user-1000.slice└─session-14973.scope└─56361 /export/servers/orange-agent/orange-guard/orange-guard -c cfg.json
8月 02 15:17:01 A02-R05-I79-201-3V98WK2.ORANGE.LOCAL systemd[1]: Created slice orange user.slice.8月 02 15:17:01 A02-R05-I79-201-3V98WK2.ORANGE.LOCAL systemd[1]: Starting orange user.slice.8月 02 15:17:01 A02-R05-I79-201-3V98WK2.ORANGE.LOCAL CROND[56324]: (orange) CMD (which taskset -c source /export/servers/orange-agent/run_cpus.sh && cpus /export/servers/orange-agent/super_guard.sh >> /export/servers/orange-agent/orange-agent/var/app.log 2>&1 &)8月 02 15:18:01 A02-R05-I79-201-3V98WK2.ORANGE.LOCAL CROND[56925]: (orange) CMD (which taskset -c source /export/servers/orange-agent/run_cpus.sh && cpus /export/servers/orange-agent/super_guard.sh >> /export/servers/orange-agent/orange-agent/var/app.log 2>&1 &)经过以上设置后,orange用户启动的所有进程占用的物理内存之和不能超过200M,如果超过,进程机会被kill。

如果进程因为OOM被kill,会在/var/log/message中发现记录。
如何查看某个进程受哪些资源限制条件
cat /proc/PID/cgroup
11:memory:/user-1000.slice10:perf_event:/9:devices:/user.slice8:hugetlb:/7:blkio:/user.slice6:cpuset:/5:freezer:/4:pids:/3:cpuacct,cpu:/user.slice2:net_prio,net_cls:/1:name=systemd:/user.slice/user-1000.slice/session-8569.scope

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注