Control Group v2(cgroupv2 权威指南)
转载 https://arthurchiao.art/blog/cgroupv2-zh/
Control Group v2(cgroupv2 权威指南)(KernelDoc, 2021)
译者序
本文翻译自 2021 年 Linux 5.10 内核文档: Control Group v2, 它是描述 cgroupv2 用户空间侧的设计、接口和规范的权威文档。
原文非常全面详细,本文只翻译了目前感兴趣的部分,其他部分保留原文。 另外,由于技术规范的描述比较抽象,因此翻译时加了一些系统测试输出、内核代码片段和 链接,便于更好理解。
由于译者水平有限,本文不免存在遗漏或错误之处。如有疑问,请查阅原文。
以下是译文。
- 译者序
- 1 引言
- 1.1 术语
- 1.2 cgroup 是什么?
- 1.2.1 cgroup 组成部分
- 1.2.2 进程/线程与 cgroup 关系
- 1.2.3 控制器
- 2 基础操作
- 2.1 挂载(mounting)
- 2.1.1 控制器与 v1/v2 绑定关系
- 2.1.2 示例:ubuntu 20.04 同时挂载 cgroupv1/cgroupv2(译注)
- 2.1.3 控制器在 v1 和 v2 之间切换
- 2.1.4 cgroupv2 mount 选项
- 2.2 组织(organizing)进程和线程2.3 [Un]populated Notification(进程退出通知)
- 2.2.1 进程:创建/删除/移动/查看 cgroup
- 2.2.2 线程
- 将 cgroup 改成 theaded 模式(单向/不可逆操作)
- 2.3 管理控制器(controlling controllers)
- 2.3.1 启用和禁用
- 2.3.2 自顶向下启用(top-down constraint)
- 2.3.3 将资源分给 children 时,parent cgroup 内不能有进程(no internal process)
- 2.4 Delegation(委派)2.5 指导原则
- 2.4.1 Model of Delegation
- 2.4.2 Delegation Containment
-
- 2.5.1 避免频繁在 cgroup 之间迁移进程(Organize once and control)
- 2.5.2 避免文件名冲突(Avoid Name Collisions)
- 2.1 挂载(mounting)
- 3 资源分配模型(Resource distribution models)
- 3.1 Weights(资源量权重)
- 3.2 Limits(资源量上限,可超分)
- 3.3 Protections(资源量保护,可超分)
- 3.4 Allocations(独占资源量,不可超分)
- 4 接口文件(Interface Files)
- 4.1 文件格式
- 4.2 一些惯例(conventions)
- 4.3 核心接口文件(core interface files)
- 5 Controllers(控制器)
- 5.1 CPU
- CPU Interface Files
- 5.2 Memory
- Memory Interface Files
- 使用建议
- Memory Ownership
- 5.3 IO
- IO Interface Files
- Writeback
- IO Latency
- How IO Latency Throttling Works
- IO Latency Interface Files
- 5.4 PID
- 5.4.1 PID 接口文件:
pids.current/pids.max - 5.4.2 绕开 cgroup PID 限制,实现
pids.current > pids.max
- 5.4.1 PID 接口文件:
- 5.5 Cpuset
- Cpuset Interface Files
- 5.6 Device controller
- 5.6.1 控制方式:基于 cgroup BPF 而非接口文件
- 5.6.2 cgroup BPF 程序上下文和返回值
- 5.6.3 cgroup BPF 程序示例
- 5.7 RDMA
- RDMA Interface Files
- 5.8 HugeTLB
- HugeTLB Interface Files
- 5.9 Misc
- perf_event
- 5.10 规范外(non-normative)的一些信息
- CPU controller root cgroup 处理行为
- IO controller root cgroup 处理行为
- 5.1 CPU
- 6 cgroup 命名空间(cgroupns)
- 6.1 基础6.2 进一步解释 cgroupns root 和视图
- 6.1.1 功能:对
/proc/PID/cgroup和 cgroup mount 进行虚拟化 - 6.1.2 新建 cgroup namespace
- 6.1.3 多线程进程:线程 unshare 后的行为
- 6.1.4 cgroupns 生命周期
- 6.1.1 功能:对
- 6.3 在 cgroupns 之间迁移进程
- 6.4 与其他 cgroupns 交互
- 6.1 基础6.2 进一步解释 cgroupns root 和视图
- 7 内核编程相关信息8
v1 core已弃用特性- 文件系统对 writeback 的支持
- 9
v1存在的问题及v2的设计考虑(rationales)- 9.1
v1多 hierarchy 带来的问题 - 9.2 线程粒度(thread granularity)
- 9.3 内部节点(inner nodes)与线程之间竞争
- 9.4 其他 cgroup 接口相关的问题
- 9.4.1 核心接口
- 9.4.2 控制器接口
- 9.4.3 控制器行为
- 9.5 一些 controller 相关的问题及解决方式
- Memory
- 9.1
本文(指英文原文) 是描述 cgroup v2 设计、接口和规范的权威文档。 未来所有改动/变化都需反应到本文档中。v1 的文档见 cgroup-v1。
本文描述 cgroup v2 所有用户空间可见的部分,包括 cgroup core 和各 controller。
1 引言
1.1 术语
“cgroup” 是 “control group” 的缩写,并且首字母永远不大写(never capitalized)。
- 单数形式(cgroup)指这个特性,或用于 “cgroup controllers” 等术语中的修饰词。
- 复数形式(cgroups)显式地指多个 cgroup。
1.2 cgroup 是什么?
cgroup 是一种以 hierarchical(树形层级)方式组织进程的机制(a mechanism to organize processes hierarchically),以及在层级中以受控和 可配置的方式(controlled and configurable manner)分发系统资源 (distribute system resources)。
1.2.1 cgroup 组成部分
cgroup 主要由两部分组成:
- 核心(core):主要负责层级化地组织进程;
- 控制器(controllers):大部分控制器负责 cgroup 层级中 特定类型的系统资源的分配,少部分 utility 控制器用于其他目的。
1.2.2 进程/线程与 cgroup 关系
所有 cgroup 组成一个树形结构(tree structure),
- 系统中的每个进程都属于且只属于某一个 cgroup;
- 一个进程的所有线程属于同一个 cgroup;
- 创建子进程时,继承其父进程的 cgroup;
- 一个进程可以被迁移到其他 cgroup;
- 迁移一个进程时,子进程(后代进程)不会自动跟着一起迁移;
1.2.3 控制器
- 遵循特定的结构规范(structural constraints),可以选择性地 针对一个 cgroup 启用或禁用某些控制器;
-
控制器的所有行为都是 hierarchical 的。
- 如果一个 cgroup 启用了某个控制器,那这个 cgroup 的 sub-hierarchy 中所有进程都会受控制。
- 如果在更接近 root 的节点上设置了资源限制(restrictions set closer to the root),那在下面的 sub-hierarchy 是无法覆盖的。
2 基础操作
2.1 挂载(mounting)
与 v1 不同,cgroup v2 只有单个层级树(single hierarchy)。 用如下命令挂载 v2 hierarchy:
# mount -t
$ mount -t cgroup2 none $MOUNT_POINT
cgroupv2 文件系统 的 magic number 是 0x63677270 (“cgrp”)。
2.1.1 控制器与 v1/v2 绑定关系
- 所有支持 v2 且未绑定到 v1 的控制器,会被自动绑定到 v2 hierarchy,出现在 root 层级中。
- v2 中未在使用的控制器(not in active use),可以绑定到其他 hierarchies。
这说明我们能以完全后向兼容的方式,混用 v2 和 v1 hierarchy。
下面通过实际例子理解以上是什么意思。
2.1.2 示例:ubuntu 20.04 同时挂载 cgroupv1/cgroupv2(译注)
查看 ubuntu 20.04 (5.11 内核)cgroup 相关的挂载点:
$ mount | grep cgroup
tmpfs on /sys/fs/cgroup type tmpfs (ro,nosuid,nodev,noexec,mode=755,inode64)
cgroup2 on /sys/fs/cgroup/unified type cgroup2 (rw,nosuid,nodev,noexec,relatime,nsdelegate)
cgroup on /sys/fs/cgroup/systemd type cgroup (rw,nosuid,nodev,noexec,relatime,xattr,name=systemd)
cgroup on /sys/fs/cgroup/cpuset type cgroup (rw,nosuid,nodev,noexec,relatime,cpuset)
cgroup on /sys/fs/cgroup/cpu,cpuacct type cgroup (rw,nosuid,nodev,noexec,relatime,cpu,cpuacct)
cgroup on /sys/fs/cgroup/hugetlb type cgroup (rw,nosuid,nodev,noexec,relatime,hugetlb)
cgroup on /sys/fs/cgroup/blkio type cgroup (rw,nosuid,nodev,noexec,relatime,blkio)
cgroup on /sys/fs/cgroup/pids type cgroup (rw,nosuid,nodev,noexec,relatime,pids)
cgroup on /sys/fs/cgroup/rdma type cgroup (rw,nosuid,nodev,noexec,relatime,rdma)
cgroup on /sys/fs/cgroup/net_cls,net_prio type cgroup (rw,nosuid,nodev,noexec,relatime,net_cls,net_prio)
cgroup on /sys/fs/cgroup/freezer type cgroup (rw,nosuid,nodev,noexec,relatime,freezer)
cgroup on /sys/fs/cgroup/devices type cgroup (rw,nosuid,nodev,noexec,relatime,devices)
cgroup on /sys/fs/cgroup/memory type cgroup (rw,nosuid,nodev,noexec,relatime,memory)
cgroup on /sys/fs/cgroup/perf_event type cgroup (rw,nosuid,nodev,noexec,relatime,perf_event)
可以看到,系统同时挂载了 cgroup 和 cgroup2:
- cgroup v2 是单一层级树,因此只有一个挂载点(第二行)
/sys/fs/cgroup/unified,这就是上一小节所说的 root 层级。 - cgroup v1 根据控制器类型(
cpuset/cpu,cpuacct/hugetlb/...),挂载到不同位置。
接下来看哪些控制绑定到了 cgroup v2:
$ ls -ahlp /sys/fs/cgroup/unified/
total 0
-r--r--r-- 1 root root 0 cgroup.controllers
-rw-r--r-- 1 root root 0 cgroup.max.depth
-rw-r--r-- 1 root root 0 cgroup.max.descendants
-rw-r--r-- 1 root root 0 cgroup.procs
-r--r--r-- 1 root root 0 cgroup.stat
-rw-r--r-- 1 root root 0 cgroup.subtree_control
-rw-r--r-- 1 root root 0 cgroup.threads
-rw-r--r-- 1 root root 0 cpu.pressure
-r--r--r-- 1 root root 0 cpu.stat
drwxr-xr-x 2 root root 0 init.scope/
-rw-r--r-- 1 root root 0 io.pressure
-rw-r--r-- 1 root root 0 memory.pressure
drwxr-xr-x 121 root root 0 system.slice/
drwxr-xr-x 3 root root 0 user.slice/
只有 cpu/io/memory 等少量控制器(大部分还在 cgroup v1 中,系统默认使用 v1)。
最后看几个控制器文件的内容,加深一点直观印象,后面章节会详细解释这些分别表示什么意思:
$ cd /sys/fs/cgroup/unified
$ cat cpu.pressure
some avg10=0.00 avg60=0.00 avg300=0.00 total=2501067303
$ cat cpu.stat
usage_usec 44110960000
user_usec 29991256000
system_usec 14119704000
$ cat io.pressure
some avg10=0.00 avg60=0.00 avg300=0.00 total=299044042
full avg10=0.00 avg60=0.00 avg300=0.00 total=271257559
$ cat memory.pressure
some avg10=0.00 avg60=0.00 avg300=0.00 total=298215
full avg10=0.00 avg60=0.00 avg300=0.00 total=229843
2.1.3 控制器在 v1 和 v2 之间切换
- 控制器在当前 hierarchy 中已经不再被引用(no longer referenced), 才能移动到其他 hierarchy。
- 由于 per-cgroup 控制器状态是异步销毁的,从 v1 umount 之后 可能会有 linger reference,因此可能不会立即出现在 v2 hierarchy 中。
- 类似地,一个控制器只有被完全禁用之后,才能被移出 v2 hierarchy,且可能 过一段时间才能在 v1 hierarchy 中可用;
- 此外,由于控制器间的依赖,其他控制器也可能需要被禁用。
在 v2 和 v1 之间动态移动控制器对开发和手动配置很有用,但 强烈建议不要在生产环境这么做。建议在系统启动、控制器开始使用之后, 就不要再修改 hierarchy 和控制器的关联关系了。
另外,迁移到 v2 时,系统管理软件可能仍然会自动 mount v1 cgroup 文件系统, 因此需要在系统启动过程中劫持所有的控制器,因为启动之后就晚了。 为方便测试,内核提供了 cgroup_no_v1=allows 配置, 可完全禁用 v1 控制器(强制使用 v2)。
2.1.4 cgroupv2 mount 选项
前面 mount 命令没指定任何特殊参数。目前支持如下 mount 选项:
-
nsdelegate:将 cgroup namespaces (cgroupns)作为 delegation 边界。系统层选项,只能在 init namespace 通过 mount/unmount 来修改这个配置。在 non-init namespace 中,这个选项会被忽略。详见下面的 Delegation 小结。
-
memory_localevents:只为当前 cgroup populatememory.events,不统计任何 subtree。这是 legacy 行为,如果没配置这个参数,默认行为会统计所有的 subtree。
系统层选项,只能在 init namespace 通过 mount/unmount 来修改这个配置。在 non-init namespace 中,这个选项会被忽略。详见下面的 Delegation 小结。
-
memory_recursiveprotRecursively apply memory.min and memory.low protection to entire subtrees, without requiring explicit downward propagation into leaf cgroups. This allows protecting entire subtrees from one another, while retaining free competition within those subtrees. This should have been the default behavior but is a mount-option to avoid regressing setups relying on the original semantics (e.g. specifying bogusly high ‘bypass’ protection values at higher tree levels).
2.2 组织(organizing)进程和线程
2.2.1 进程:创建/删除/移动/查看 cgroup
初始状态下,只有 root cgroup,所有进程都属于这个 cgroup。
-
创建 sub-cgroup:只需创建一个子目录,
$ mkdir $CGROUP_NAME- 一个 cgroup 可以有多个子 cgroup,形成一个树形结构;
-
每个 cgroup 都有一个可读写的接口文件
cgroup.procs:- 读该文件会列出这个 cgroup 内的所有 PID,每行一个;
- PID 并未排序;
- 同一 PID 可能出现多次:进程先移出再移入该 cgroup,或读文件期间 PID 被重用了,都可能发生这种情况。
-
将进程移动到指定 cgroup:将 PID 写到相应 cgroup 的
cgroup.procs文件即可。- 每次
write(2)只能迁移一个进程; - 如果进程有多个线程,那将任意线程的 PID 写到文件,都会将该进程的所有线程迁移到相应 cgroup。
- 如果进程 fork 出一个子进程,那子进程属于执行 fork 操作时父进程所属的 cgroup。
- 进程退出(exit)后,仍然留在退出时它所属的 cgroup,直到这个进程被收割(reap);
- 僵尸进程不会出现在 cgroup.procs 中,因此无法对僵尸进程执行 cgroup 迁移操作。
- 每次
-
删除 cgroup/sub-cgroup
- 如果一个 cgroup 已经没有任何 children 或活进程,那直接 删除对应的文件夹就删除该 cgroup 了。
- 如果一个 cgroup 已经没有 children,虽然其中还有进程但全是僵尸进程 (zombie processes),那认为这个 cgroup 是空的,也可以直接删除。
-
查看进程的 cgroup 信息:
cat /proc/$PID/cgroup会列出该进程的 cgroup membership。如果系统启用了 v1,这个文件可能会包含多行,每个 hierarchy 一行。 v2 对应的行永远是
0::$PATH格式:$ cat /proc/$$/cgroup # ubuntu 20.04 上的输出,$$ 是当前 shell 的进程 ID 12:devices:/user.slice 11:freezer:/ 10:memory:/user.slice/user-1000.slice/session-1.scope 9:hugetlb:/ 8:cpuset:/ 7:perf_event:/ 6:rdma:/ 5:pids:/user.slice/user-1000.slice/session-1.scope 4:cpu,cpuacct:/user.slice 3:blkio:/user.slice 2:net_cls,net_prio:/ 1:name=systemd:/user.slice/user-1000.slice/session-1.scope 0::/user.slice/user-1000.slice/session-1.scope如果一个进程变成僵尸进程(zombie),并且与它关联的 cgroup 随后被删掉了,那行尾会出现
(deleted)字样:$ cat /proc/842/cgroup ... 0::/test-cgroup/test-cgroup-nested (deleted)
2.2.2 线程
-
cgroup v2 的一部分控制器支持线程粒度的资源控制, 这种控制器称为 threaded controllers。
- 默认情况下,一个进程的所有线程属于同一个 cgroup,
- 线程模型使我们能将不同线程放到 subtree 的不同位置,而同时还能保持二者在同一 资源域(resource domain)内。
-
不支持线程模式的控制器称为 domain controllers。
将一个 cgroup 标记为 threaded,那它将作为 threaded cgroup 将加入 parent 的资源域 。而 parent 可能也是一个 threaded cgroup,它所属的资源域在 hierarchy 层级中的更 上面。一个 threaded subtree 的 root,即第一个不是 threaded 的祖先,称为 threaded domain 或 threaded root,作为整个 subtree 的资源域。
Inside a threaded subtree, threads of a process can be put in different cgroups and are not subject to the no internal process constraint - threaded controllers can be enabled on non-leaf cgroups whether they have threads in them or not.
As the threaded domain cgroup hosts all the domain resource consumptions of the subtree, it is considered to have internal resource consumptions whether there are processes in it or not and can’t have populated child cgroups which aren’t threaded. Because the root cgroup is not subject to no internal process constraint, it can serve both as a threaded domain and a parent to domain cgroups.
The current operation mode or type of the cgroup is shown in the “cgroup.type” file which indicates whether the cgroup is a normal domain, a domain which is serving as the domain of a threaded subtree, or a threaded cgroup.
将 cgroup 改成 theaded 模式(单向/不可逆操作)
cgroup 创建之后都是 domain cgroup,可以通过下面的命令将其改成 threaded 模式:
$ echo threaded > cgroup.type
但注意:这个操作是单向的,一旦设置成 threaded 模式之后,就无法再切回 domain 模式了。
开启 thread 模型必须先满足如下条件:
- As the cgroup will join the parent’s resource domain. The parent must either be a valid (threaded) domain or a threaded cgroup.
- When the parent is an unthreaded domain, it must not have any domain controllers enabled or populated domain children. The root is exempt from this requirement.
Topology-wise, a cgroup can be in an invalid state. Please consider the following topology:
A (threaded domain) - B (threaded) - C (domain, just created)
C is created as a domain but isn’t connected to a parent which can host child domains. C can’t be used until it is turned into a threaded cgroup. “cgroup.type” file will report “domain (invalid)” in these cases. Operations which fail due to invalid topology use EOPNOTSUPP as the errno.
A domain cgroup is turned into a threaded domain when one of its child cgroup becomes threaded or threaded controllers are enabled in the “cgroup.subtree_control” file while there are processes in the cgroup. A threaded domain reverts to a normal domain when the conditions clear.
When read, “cgroup.threads” contains the list of the thread IDs of all threads in the cgroup. Except that the operations are per-thread instead of per-process, “cgroup.threads” has the same format and behaves the same way as “cgroup.procs”. While “cgroup.threads” can be written to in any cgroup, as it can only move threads inside the same threaded domain, its operations are confined inside each threaded subtree.
The threaded domain cgroup serves as the resource domain for the whole subtree, and, while the threads can be scattered across the subtree, all the processes are considered to be in the threaded domain cgroup. “cgroup.procs” in a threaded domain cgroup contains the PIDs of all processes in the subtree and is not readable in the subtree proper. However, “cgroup.procs” can be written to from anywhere in the subtree to migrate all threads of the matching process to the cgroup.
Only threaded controllers can be enabled in a threaded subtree. When a threaded controller is enabled inside a threaded subtree, it only accounts for and controls resource consumptions associated with the threads in the cgroup and its descendants. All consumptions which aren’t tied to a specific thread belong to the threaded domain cgroup.
Because a threaded subtree is exempt from no internal process constraint, a threaded controller must be able to handle competition between threads in a non-leaf cgroup and its child cgroups. Each threaded controller defines how such competitions are handled.
2.3 [Un]populated Notification(进程退出通知)
每个 non-root cgroup 都有一个 cgroup.events 文件, 其中包含了 populated 字段,描述这个 cgroup 的 sub-hierarchy 中是否存在活进程(live processes)。
- 如果值是 0,表示 cgroup 及其 sub-cgroup 中没有活进程;
- 如果值是 1:那这个值变为 0 时,会触发 poll 和 [id]notify 事件。
这可以用来,例如,在一个 sub-hierarchy 内的所有进程退出之后触发执行清理操作。
The populated 状态更新和通知是递归的。以下图为例,括号中的数字表示该 cgroup 中的进程数量:
A(4) - B(0) - C(1)
\ D(0)
- A、B 和 C 的
populated字段都应该是1,而 D 的是0。 - 当 C 中唯一的进程退出之后,B 和 C 的
populated字段将变成0,将 在这两个 cgroup 内触发一次 cgroup.events 文件的文件修改事件。
2.3 管理控制器(controlling controllers)
2.3.1 启用和禁用
每个 cgroup 都有一个 cgroup.controllers 文件, 其中列出了这个 cgroup 可用的所有控制器:
$ cat cgroup.controllers
cpu io memory
默认没有启用任何控制。启用或禁用是通过写 cgroup.subtree_control 文件完成的:
$ echo "+cpu +memory -io" > cgroup.subtree_control
只有出现在 cgroup.controllers 中的控制器才能被启用。
- 如果像上面的命令一样,一次指定多个操作,那它们要么全部功能,要么全部失败;
- 如果对同一个控制器指定了多个操作,最后一个是有效的。
启用 cgroup 的某个控制器,意味着控制它在子节点之间分配目标资源(target resource)的行为。 考虑下面的 sub-hierarchy,括号中是已经启用的控制器:
A(cpu,memory) - B(memory) - C()
\ D()
- A 启用了
cpu和memory,因此会控制它的 child(即 B)的 CPU 和 memory 使用; - B 只启用了
memory,因此 C 和 D 的 memory 使用量会受 B 控制,但 CPU 可以随意竞争(compete freely)。
控制器限制 children 的资源使用方式,是创建或写入 children cgroup 的接口文件。 还是以上面的拓扑为例:
- 在 B 上启用
cpu将会在 C 和 D 的 cgroup 目录中创建cpu.开头的接口文件; - 同理,禁用
memory时会删除对应的memory.开头的文件。
这也意味着cgroup 目录中所有不以 cgroup.开头的 控制器接口文件 —— 在管理上 都属于 parent cgroup 而非当前 cgroup 自己。
2.3.2 自顶向下启用(top-down constraint)
资源是自顶向下(top-down)分配的,只有当一个 cgroup 从 parent 获得了某种资源,它 才可以继续向下分发。这意味着
- 只有父节点启用了某个控制器,子节点才能启用;
- 对应到实现上,所有非根节点(non-root)的
cgroup.subtree_control文件中, 只能包含它的父节点的cgroup.subtree_control中有的控制器; - 另一方面,只要有子节点还在使用某个控制器,父节点就无法禁用之。
2.3.3 将资源分给 children 时,parent cgroup 内不能有进程(no internal process)
只有当一个 non-root cgroup 中没有任何进程时,才能将其 domain resource 分配给它的 children。换句话说,只有那些没有任何进程的 domain cgroup, 才能将它们的 domain controllers 写到其 children 的 cgroup.subtree_control 文件中。
这种方式保证了在给定的 domain controller 范围内,所有进程都位于叶子节点上, 因而避免了 child cgroup 内的进程与 parent 内的进程竞争的情况,便于 domain controller 扫描 hierarchy。
但 root cgroup 不受此限制。
- 对大部分类型的控制器来说,root 中包含了一些没有与任何 cgroup 相关联的进程和匿名资源占用 (anonymous resource consumption),需要特殊对待。
- root cgroup 的资源占用是如何管理的,因控制器而异(更多信息可参考 Controllers 小结)。
注意,在 parent 的 cgroup.subtree_control 启用控制器之前,这些限制不会生效。 这非常重要,因为它决定了创建 populated cgroup children 的方式。 要控制一个 cgroup 的资源分配,这个 cgroup 需要:
- 创建 children cgroup,
- 将自己所有的进程转移到 children cgroup 中,
- 在它自己的
cgroup.subtree_control中启用控制器。
tools/testing/selftests/bpf/progs/dev_cgroup.c
5.7 RDMA
The “rdma” controller regulates the distribution and accounting of RDMA resources.
RDMA Interface Files
-
rdma.max
A readwrite nested-keyed file that exists for all the cgroups except root that describes current configured resource limit for a RDMA/IB device.
Lines are keyed by device name and are not ordered. Each line contains space separated resource name and its configured limit that can be distributed.
The following nested keys are defined.
========== ============================= hca_handle Maximum number of HCA Handles hca_object Maximum number of HCA Objects ========== =============================An example for mlx4 and ocrdma device follows::
mlx4_0 hca_handle=2 hca_object=2000 ocrdma1 hca_handle=3 hca_object=max -
rdma.current
A read-only file that describes current resource usage. It exists for all the cgroup except root.
An example for mlx4 and ocrdma device follows::
mlx4_0 hca_handle=1 hca_object=20 ocrdma1 hca_handle=1 hca_object=23
5.8 HugeTLB
The HugeTLB controller allows to limit the HugeTLB usage per control group and enforces the controller limit during page fault.
HugeTLB Interface Files
-
hugetlb..current
Show current usage for “hugepagesize” hugetlb. It exists for all the cgroup except root.
-
hugetlb..max
Set/show the hard limit of “hugepagesize” hugetlb usage. The default value is “max”. It exists for all the cgroup except root.
-
hugetlb..events
A read-only flat-keyed file which exists on non-root cgroups.
max The number of allocation failure due to HugeTLB limit -
hugetlb..events.local
Similar to hugetlb..events but the fields in the file are local to the cgroup i.e. not hierarchical. The file modified event generated on this file reflects only the local events.
5.9 Misc
perf_event
perf_event controller, if not mounted on a legacy hierarchy, is automatically enabled on the v2 hierarchy so that perf events can always be filtered by cgroup v2 path. The controller can still be moved to a legacy hierarchy after v2 hierarchy is populated.
5.10 规范外(non-normative)的一些信息
本节内容不属于 stable kernel API,随时可能变化。
CPU controller root cgroup 处理行为
When distributing CPU cycles in the root cgroup each thread in this cgroup is treated as if it was hosted in a separate child cgroup of the root cgroup. This child cgroup weight is dependent on its thread nice level.
For details of this mapping see sched_prio_to_weight array in kernel/sched/core.c file (values from this array should be scaled appropriately so the neutral - nice 0 - value is 100 instead of 1024).
IO controller root cgroup 处理行为
Root cgroup processes are hosted in an implicit leaf child node. When distributing IO resources this implicit child node is taken into account as if it was a normal child cgroup of the root cgroup with a weight value of 200.
6 cgroup 命名空间(cgroupns)
容器环境中用 cgroup 和其他一些 namespace 来隔离进程,但 /proc/$PID/cgroup 文件 可能会泄露潜在的系统层信息。例如:
$ cat /proc/self/cgroup
0::/batchjobs/container_id1 # <-- cgroup 的绝对路径,属于系统层信息,不希望暴露给隔离的进程
因此引入了 cgroup namespace,以下简写为 cgroupns (类似于 network namespace 简写为 netns)。
6.1 基础
6.1.1 功能:对 /proc/PID/cgroup 和 cgroup mount 进行虚拟化
cgroupns 对/proc/$PID/cgroup 文件和 cgroup 挂载视角进行了虚拟化。
- 如果没有 cgroupns,
cat /proc/$PID/cgroup看到的是进程所属 cgroup 的绝对路径; - 有了 cgroupns 之后,看到的将是 cgroupns root 范围内的路径。
下面具体来看。
6.1.2 新建 cgroup namespace
可以用 clone(2)/unshare(2) 指定 CLONE_NEWCGROUP flag 来创建一个新的 cgroupns。
- 创建该 cgroupns 时,
unshare/clone所在的 cgroup namespace 称为 cgroupns root; - 该 cgroupns 内的进程查看
/proc/$PID/cgroup时,只能看到其 cgroupns root 范围内的 cgroup 文件路径。
也就是说,cgroupns 限制了 cgroup 文件路径的可见性。例如,没有创建 cgroup namespace 时的视图:
$ ls -l /proc/self/ns/cgroup
lrwxrwxrwx 1 root root 0 2014-07-15 10:37 /proc/self/ns/cgroup -> cgroup:[4026531835]
$ cat /proc/self/cgroup
0::/batchjobs/container_id1 # <-- 绝对路径
用 unshare 创建一个新 cgroupns 之后的视图:
$ ls -l /proc/self/ns/cgroup
lrwxrwxrwx 1 root root 0 2014-07-15 10:35 /proc/self/ns/cgroup -> cgroup:[4026532183]
$ cat /proc/self/cgroup
0::/ # <-- cgroupns root 限制范围内的路径
6.1.3 多线程进程:线程 unshare 后的行为
对于多线程的进程,任何一个线程通过 unshare 创建新 cgroupns 时,整个进程(所有线程) 都会进入到新的 cgroupns。这对 v2 hierarchy 是很自然的事情,但对 v1 来说,可能是 不期望的行为。
6.1.4 cgroupns 生命周期
只要以下条件之一满足,cgroupns 就会活着:
- 该 cgroup 中还有活着的进程,
- 挂载的文件系统中,还有对象 pin 在这个 cgroupns 上。
当最后一个还在使用 cgroupns 的进程退出或文件系统 unmount 之后,这个 cgroupns 就销毁了。 但 cgroupns root 和真正的 cgroups 还是继续存在的。
6.2 进一步解释 cgroupns root 和视图
前面提到,cgroupns root 是指 unshare(2) 创建 cgroupns 时所在的 cgroup。 例如,如果 /batchjobs/container_id1 cgroup 中的一个进程调用 unshare,那 /batchjobs/container_id1 就成了 cgroupns root。For the init_cgroup_ns, this is the real root (‘/’) cgroup.
即便创建这个 cgroupns 的进程后面移动到其他 cgroup,这个 cgroupns root 也是不会变的:
$ ~/unshare -c # 在当前 cgroup 中通过 unshare 命令创建一个 cgroupns
# 以下命令都在刚创建的 cgroupns 中执行的
$ cat /proc/self/cgroup
0::/
$ mkdir sub_cgrp_1 # 创建一个 sub-cgroup
$ echo 0 > sub_cgrp_1/cgroup.procs # 将当前 shell 进程迁移到新创建的 cgroup sub_cgrp_1
$ cat /proc/self/cgroup # 查看当前 shell 进程的 cgroup 信息
0::/sub_cgrp_1 # 可以看到是相对路径
每个进程获得了它自己的 namespace-specific /proc/$PID/cgroup。
运行在 cgroupns 中的进程,在 /proc/self/cgroup 中只能看到它们的 root cgroup 内的 cgroup 路径。 例如,还是在刚才 unshare 创建的 cgroupns 中:
# 接着上面的窗口,现在还是在创建出的 cgroupns 中执行命令
$ sleep 100000 & # 创建一个进程,放在后台执行
[1] 7353
$ echo 7353 > sub_cgrp_1/cgroup.procs # 将进程迁移到前面创建的 sub-cgroup 中
$ cat /proc/7353/cgroup # 查看这个进程的 cgroup 信息,会看到是相对路径
0::/sub_cgrp_1
在默认 cgroupns 中,真实 cgroup path 还是可见的:
$ cat /proc/7353/cgroup
0::/batchjobs/container_id1/sub_cgrp_1 # 绝对路径,说明没有在新建的 cgroupns 中
在 sibling(兄弟)cgroupns (a namespace rooted at a different cgroup) 中,会显示 相对 cgroup path(相对于它自己的cgroupns root)。例如,如果 PID 7353 的 cgroupns root 是 /batchjobs/container_id2,那它将看到:
$ cat /proc/7353/cgroup
0::/../container_id2/sub_cgrp_1
注意:相对路径永远以 / 开头,以提醒用户这是相对于调用者的 cgroupns root 的路径。
6.3 在 cgroupns 之间迁移进程
cgroupns 内的进程,可以移出或移入 ns root,只要有对外部 cgroup 的访问权限 (proper access to external cgroups)。例如,在 cgroupns root 是 /batchjobs/container_id1 的某 cgroupns 内,假设能访问全局 hierarchy,那可以通 过如下命令迁移进程:
$ cat /proc/7353/cgroup
0::/sub_cgrp_1
$ echo 7353 > batchjobs/container_id2/cgroup.procs
$ cat /proc/7353/cgroup
0::/../container_id2
注意,这种迁移方式并不推荐。cgroupns 内的进程只应当被暴露到它 自己的 cgroupns hierarchy 内。
还可以使用 setns(2) 将进程移动到其他 cgroupns,前提条件:
- 有 CAP_SYS_ADMIN against its current user namespace
- 有 CAP_SYS_ADMIN against the target cgroupns’s userns
当 attach 到其他 cgroupns 时,不会有隐式的 cgroup changes。 It is expected that the someone moves the attaching process under the target cgroupns root.
6.4 与其他 cgroupns 交互
Namespace 相关的 cgroup hierarchy 可以在 non-init cgroupns 内以如下方式挂载:
# mount -t
$ mount -t cgroup2 none $MOUNT_POINT
这会挂载默认的 unified cgroup hierarchy,并将 cgroupns root 作为 filesystem root。 这个操作需要 CAP_SYS_ADMIN 权限。
/proc/self/cgroup 的虚拟化,以及通过 namespace-private cgroupfs mount 来限制 进程能看到的 cgroup hierarchy,提供了容器的隔离的 cgroup 视角。
7 内核编程相关信息
一些与 cgroup 交互相关的内核编程信息。
文件系统对 writeback 的支持
A filesystem can support cgroup writeback by updating address_space_operations->writepage[s]() to annotate bio’s using the following two functions.
wbc_init_bio(@wbc, @bio)
Should be called for each bio carrying writeback data and
associates the bio with the inode's owner cgroup and the
corresponding request queue. This must be called after
a queue (device) has been associated with the bio and
before submission.
wbc_account_cgroup_owner(@wbc, @page, @bytes)
Should be called for each data segment being written out.
While this function doesn't care exactly when it's called
during the writeback session, it's the easiest and most
natural to call it as data segments are added to a bio.
With writeback bio’s annotated, cgroup support can be enabled per super_block by setting SB_I_CGROUPWB in ->s_iflags. This allows for selective disabling of cgroup writeback support which is helpful when certain filesystem features, e.g. journaled data mode, are incompatible.
wbc_init_bio() binds the specified bio to its cgroup. Depending on the configuration, the bio may be executed at a lower priority and if the writeback session is holding shared resources, e.g. a journal entry, may lead to priority inversion. There is no one easy solution for the problem. Filesystems can try to work around specific problem cases by skipping wbc_init_bio() and using bio_associate_blkg() directly.
8 v1 core 已弃用特性
- Multiple hierarchies including named ones are not supported.
- All v1 mount options are not supported.
- The “tasks” file is removed and “cgroup.procs” is not sorted.
- “cgroup.clone_children” is removed.
- /proc/cgroups is meaningless for v2. Use “cgroup.controllers” file at the root instead.
9 v1 存在的问题及 v2 的设计考虑(rationales)
9.1 v1 多 hierarchy 带来的问题
v1 允许任意数量的 hierarchy,每个 hierarchy 可以启用任意数量的 controller。 这种方式看上去高度灵活,但在实际中并不是很有用。例如,
- utility 类型的 controller(例如 freezer)本可用于多个 hierarchy,而 由于 v1 中每个 controller 只有一个实例,utility controller 的作用就大打折扣; 而 hierarchy 一旦被 populated 之后,控制器就不能移动到其他 hierarchy 的事实, 更是加剧了这个问题。
- 另一个问题是,关联到某个 hierarchy 的所有控制器,只能拥有相同的 hierarchy 视图。 无法在 controller 粒度改变这种视图。
在实际中,这些问题严重制约着每个 hierarchy 能启用哪些控制器,导致的结果就是: 大部分 hierarchy 都启用了所有控制器。而实际上只有联系非常紧密的 控制器 —— 例如 cpu 和 cpuacct —— 放到同一个 hierarchy 中才有意义。 因此最终的结果就是:
- 用户空间最后管理着多个非常类似的 hierarchy,
- 在执行 hierarchy 管理操作时,每个 hierarchy 上都重复着相同的操作。
此外,支持多个 hierarchy 代价也非常高。它使得 cgroup core 的实现更加复杂,更重要的是, 限制了 cgroup 如何使用以及每个控制器能做什么。
-
由于未限制 hierarchy 数量,因此一个线程的 cgroup membership 无法用有限长度来描述。
cgroup 文件可能包含任意数量(行数)的 entry,长度是没有限制的,使得管理非常棘手, 最终不得不加一些特殊的控制器,而这些控制器的唯一目的就是识 别 membership,这反过来又加剧了最初的问题:hierarchy 数量不断增加。
-
由于 controller 无法对其他 controller 所在的 hierarchy 拓扑做出预测,每个 controller 只能假设所有控制器都 attach 到了完全正交的 hierarchies。 这使得无法 —— 或至少非常困难 —— 实现控制器之间的协作。
在大部分场景下,将控制器放到多个完全正交的 hierarchy 都是没必要的。大家更 希望的是不同控制器能有不同层级的控制粒度。换句话说,从某个具体的 controller 角 度来看时,hierarchy 能够自底向上(from leaf towards root)collapse。例如 ,某个配置能不关心内存是否已经超过限制,而只关心 CPU cycle 的分配是否符合设置。
9.2 线程粒度(thread granularity)
cgroup v1 allowed threads of a process to belong to different cgroups. This didn’t make sense for some controllers and those controllers ended up implementing different ways to ignore such situations but much more importantly it blurred the line between API exposed to individual applications and system management interface.
Generally, in-process knowledge is available only to the process itself; thus, unlike service-level organization of processes, categorizing threads of a process requires active participation from the application which owns the target process.
cgroup v1 had an ambiguously defined delegation model which got abused in combination with thread granularity. cgroups were delegated to individual applications so that they can create and manage their own sub-hierarchies and control resource distributions along them. This effectively raised cgroup to the status of a syscall-like API exposed to lay programs.
First of all, cgroup has a fundamentally inadequate interface to be exposed this way. For a process to access its own knobs, it has to extract the path on the target hierarchy from /proc/self/cgroup, construct the path by appending the name of the knob to the path, open and then read and/or write to it. This is not only extremely clunky and unusual but also inherently racy. There is no conventional way to define transaction across the required steps and nothing can guarantee that the process would actually be operating on its own sub-hierarchy.
cgroup controllers implemented a number of knobs which would never be accepted as public APIs because they were just adding control knobs to system-management pseudo filesystem. cgroup ended up with interface knobs which were not properly abstracted or refined and directly revealed kernel internal details. These knobs got exposed to individual applications through the ill-defined delegation mechanism effectively abusing cgroup as a shortcut to implementing public APIs without going through the required scrutiny.
This was painful for both userland and kernel. Userland ended up with misbehaving and poorly abstracted interfaces and kernel exposing and locked into constructs inadvertently.
9.3 内部节点(inner nodes)与线程之间竞争
cgroup v1 允许线程在任意 cgroup,这导致了一个很有趣的问题: threads belonging to a parent cgroup and its children cgroups competed for resources. This was nasty as two different types of entities competed and there was no obvious way to settle it. Different controllers did different things.
The cpu controller considered threads and cgroups as equivalents and mapped nice levels to cgroup weights. This worked for some cases but fell flat when children wanted to be allocated specific ratios of CPU cycles and the number of internal threads fluctuated - the ratios constantly changed as the number of competing entities fluctuated. There also were other issues. The mapping from nice level to weight wasn’t obvious or universal, and there were various other knobs which simply weren’t available for threads.
The io controller implicitly created a hidden leaf node for each cgroup to host the threads. The hidden leaf had its own copies of all the knobs with leaf_ prefixed. While this allowed equivalent control over internal threads, it was with serious drawbacks. It always added an extra layer of nesting which wouldn’t be necessary otherwise, made the interface messy and significantly complicated the implementation.
The memory controller didn’t have a way to control what happened between internal tasks and child cgroups and the behavior was not clearly defined. There were attempts to add ad-hoc behaviors and knobs to tailor the behavior to specific workloads which would have led to problems extremely difficult to resolve in the long term.
Multiple controllers struggled with internal tasks and came up with different ways to deal with it; unfortunately, all the approaches were severely flawed and, furthermore, the widely different behaviors made cgroup as a whole highly inconsistent.
This clearly is a problem which needs to be addressed from cgroup core in a uniform way.
9.4 其他 cgroup 接口相关的问题
v1 的设计并没有前瞻性,因此后面引入了大量的怪异特性和不一致性。
9.4.1 核心接口
cgroup core 中的问题,例如:
- 如何通知一个 empty cgroup。v1 的实现非常粗暴: 对于每个事件都 fork 执行一个用户空间 helper binary。
- event delivery 也是不可递归或 delegatable 的。这也使内核中的事件 delivery 过滤机制让 cgroup 接口变得更复杂。
9.4.2 控制器接口
控制器接口也有问题。
- 一个极端的例子:控制器完全不管 hierarchical organization,认为所有 cgroup 都直接位于 root cgroup 下面。
- 一些控制器暴露了大量的、不一致的实现细节给用户空间。
9.4.3 控制器行为
控制器行为也有不一致。
创建一个新 cgroup 之后,某些控制器默认不会施加限制,而另一些控制器则会直接禁用 资源,需要用户显式配置来解除禁用。 Configuration knobs for the same type of control used widely differing naming schemes and formats. Statistics and information knobs were named arbitrarily and used different formats and units even in the same controller.
v2 建立了通用约定,并更新了控制器设计,以使得它们只需暴露最少且一致的接口。
9.5 一些 controller 相关的问题及解决方式
Memory
The original lower boundary, the soft limit, is defined as a limit that is per default unset. As a result, the set of cgroups that global reclaim prefers is opt-in, rather than opt-out. The costs for optimizing these mostly negative lookups are so high that the implementation, despite its enormous size, does not even provide the basic desirable behavior. First off, the soft limit has no hierarchical meaning. All configured groups are organized in a global rbtree and treated like equal peers, regardless where they are located in the hierarchy. This makes subtree delegation impossible. Second, the soft limit reclaim pass is so aggressive that it not just introduces high allocation latencies into the system, but also impacts system performance due to overreclaim, to the point where the feature becomes self-defeating.
The memory.low boundary on the other hand is a top-down allocated reserve. A cgroup enjoys reclaim protection when it’s within its effective low, which makes delegation of subtrees possible. It also enjoys having reclaim pressure proportional to its overage when above its effective low.
The original high boundary, the hard limit, is defined as a strict limit that can not budge, even if the OOM killer has to be called. But this generally goes against the goal of making the most out of the available memory. The memory consumption of workloads varies during runtime, and that requires users to overcommit. But doing that with a strict upper limit requires either a fairly accurate prediction of the working set size or adding slack to the limit. Since working set size estimation is hard and error prone, and getting it wrong results in OOM kills, most users tend to err on the side of a looser limit and end up wasting precious resources.
The memory.high boundary on the other hand can be set much more conservatively. When hit, it throttles allocations by forcing them into direct reclaim to work off the excess, but it never invokes the OOM killer. As a result, a high boundary that is chosen too aggressively will not terminate the processes, but instead it will lead to gradual performance degradation. The user can monitor this and make corrections until the minimal memory footprint that still gives acceptable performance is found.
In extreme cases, with many concurrent allocations and a complete breakdown of reclaim progress within the group, the high boundary can be exceeded. But even then it’s mostly better to satisfy the allocation from the slack available in other groups or the rest of the system than killing the group. Otherwise, memory.max is there to limit this type of spillover and ultimately contain buggy or even malicious applications.
Setting the original memory.limit_in_bytes below the current usage was subject to a race condition, where concurrent charges could cause the limit setting to fail. memory.max on the other hand will first set the limit to prevent new charges, and then reclaim and OOM kill until the new limit is met - or the task writing to memory.max is killed.
The combined memory+swap accounting and limiting is replaced by real control over swap space.
The main argument for a combined memory+swap facility in the original cgroup design was that global or parental pressure would always be able to swap all anonymous memory of a child group, regardless of the child’s own (possibly untrusted) configuration. However, untrusted groups can sabotage swapping by other means - such as referencing its anonymous memory in a tight loop - and an admin can not assume full swappability when overcommitting untrusted jobs.
For trusted jobs, on the other hand, a combined counter is not an intuitive userspace interface, and it flies in the face of the idea that cgroup controllers should account and limit specific physical resources. Swap space is a resource like all others in the system, and that’s why unified hierarchy allows distributing it separately.
? [译] LINUX 异步 I/O 框架 IO_URING:基本原理、程序示例与性能压测(2020)[译] 基于角色的访问控制(RBAC):演进历史、设计理念及简洁实现(TAILSCALE, 2021) ?? 2016-2022 Arthur Chiao, Powered by Jekyll , Theme originated from Long Haul. Site visits: 524782, powered by busuanzi