cloudpods 中的 libcontainer 深度解析:基于 runc 的 Go 容器运行时构建与生命周期管理
cloudpods 中的 libcontainer 深度解析:基于 runc 的 Go 容器运行时构建与生命周期管理
本篇技术文章以 cloudpods 仓库中内置(vendor)的 github.com/opencontainers/runc v1.1.5 版本的 libcontainer 官方文档 libcontainer/README.md 为核心,完整讲解 libcontainer 的容器创建模型(两步 bootstrap)、configs.Config 配置结构、Factory/Container/Process 三大核心 API 的完整用法,以及基于 CRIU 的 Checkpoint/Restore 机制;并结合 factory_linux.go、container.go 等真实源码,以及 cloudpods 中 Pod 统计模块的实际引用,说明这套库在多云平台 host agent 中的定位与落地方式。读完本文,你将掌握用 Go 语言直接驱动 Linux 命名空间、cgroup 与 capabilities 构建容器的完整方法。
libcontainer 在 cloudpods 仓库中的定位
cloudpods 的 host 侧(pkg/util/pod)通过 containerd/nerdctl 管理 Pod,libcontainer 本身并非被云控制面直接调用的组件。在 go.mod 中可以看到该依赖以间接方式引入:
github.com/opencontainers/runc v1.1.5 // indirect
vendored 源码位于 vendor/github.com/opencontainers/runc/libcontainer/,vendor/modules.txt 中记录了模块版本 v1.1.5(## explicit; go 1.16)及其被引入的包清单,包括 libcontainer/cgroups/fs、libcontainer/cgroups/fs2、libcontainer/cgroups/systemd、libcontainer/configs、libcontainer/seccomp 等。从源码结构看,runc 是经 kubelet/cadvisor 血统的代码链路作为传递依赖进入构建的,cloudpods 中有两处代码与 libcontainer 存在直接关系:
- Pod 容器统计模块 cadvisor_stats_provider.go:定义了
libcontainerCgroupManagerType(取值cgroupfs与systemd),用于识别 libcontainer 的 cgroup 管理方式,并按两种 driver 的命名规则解析 cgroup 名称:
// libcontainerCgroupManagerType defines how to interface with libcontainer
type libcontainerCgroupManagerType string
const (
// libcontainerCgroupfs means use libcontainer with cgroupfs
libcontainerCgroupfs libcontainerCgroupManagerType = "cgroupfs"
// libcontainerSystemd means use libcontainer with systemd
libcontainerSystemd libcontainerCgroupManagerType = "systemd"
// systemdSuffix is the cgroup name suffix for systemd
systemdSuffix string = ".slice"
)
cadvisor_stats_provider.go#L64-L74 同文件中还提供 ParseCgroupfsToCgroupName(按路径组件拆分)与 ParseSystemdToCgroupName(按 - 拆分并去掉 .slice 后缀、_ 转回 -)两个解析函数,这正是 libcontainer 两种 cgroup driver(cgroupfs / systemd)落到监控采集时的命名转换规则。
- cgroup v2 设备过滤参考实现 ebpf.go:其中保留了从 runc
libcontainer/cgroups/fs/devices_v2.go借鉴的判断逻辑canSkipEBPFError(源文件注释明确标注 "the logic is from runc"),用于判断设备 cgroup 规则是否允许跳过 eBPF 附加失败的错误。ebpf.go#L71-L80
因此,理解 libcontainer 的工作原理,既能读懂 runc 官方文档,也能理解 cloudpods 中 Pod 资源统计与设备过滤等模块的底层约定。
什么是 libcontainer:Go 原生的容器实现
文档对 "container" 给出了与运行时无关的经典定义:
A container is a self contained execution environment that shares the kernel of the host system and which is (optionally) isolated from other containers in the system.
libcontainer 提供的是原生 Go 实现的容器创建库,核心能力有四类:
- namespaces:用 Linux 命名空间把容器与宿主机的进程、网络、IPC、挂载等视图隔离;
- cgroups:把容器放入 cgroup 以限制 CPU、内存、IO、设备等资源;
- capabilities:裁剪容器内进程持有的 Linux 能力集合;
- filesystem access controls:通过只读路径、掩码路径、挂载控制等手段约束容器对文件系统的访问。
与"只负责把容器跑起来"不同,libcontainer 还承担容器生命周期管理:容器创建之后,可以对其执行暂停、恢复、发信号、改资源约束、采集统计等操作。这对应 vendored 源码中的包结构:configs/(配置模型)、cgroups/fs、cgroups/fs2、cgroups/systemd(三种 cgroup 管理实现)、seccomp/、capabilities/、apparmor/、intelrdt/、userns/、user/ 等,根目录则是 factory_linux.go、container_linux.go、process_linux.go、standard_init_linux.go、mount_linux.go、network_linux.go 等运行时主流程文件。
两步式 bootstrap:init 进程与 nsenter 引导
容器创建是"两步走"的过程:第一步在宿主机上下文中准备并 clone 出初始进程,第二步在容器命名空间内完成初始化(挂载 rootfs、设置 cgroup/namespace、exec 用户进程)。因此你的程序必须提供一个能被当作容器 init 进程执行的二进制。文档给出的约定是:
- 使用当前二进制(
/proc/self/exe)并追加参数"init"来触发 init 分支; - 必须存在名为
init的函数作为该 bootstrap 阶段的入口; - Go 的 init 函数之外,早期 bootstrap 由
libcontainer/nsenter包的导入副作用完成。
文档中的引导代码(完整保留):
import (
_ "github.com/opencontainers/runc/libcontainer/nsenter"
)
func init() {
if len(os.Args) > 1 && os.Args[1] == "init" {
runtime.GOMAXPROCS(1)
runtime.LockOSThread()
factory, _ := libcontainer.New("")
if err := factory.StartInitialization(); err != nil {
logrus.Fatal(err)
}
panic("--this line should have never been executed, congratulations--")
}
}
这段代码在 vendored 源码中可以得到逐行印证:
libcontainer.New("")传空 root 是合法的:factory_linux.go#L90-L113 中只有root != ""时才os.MkdirAll;- 默认
InitPath就是"/proc/self/exe",默认InitArgs就是<a href="https://link.gitcode.com/i/2b47a6f1336a6441edacd078884464ac" target="_blank">]string{os.Args[0], "init"}(见 [factory_linux.go#L96-L102),这正是文档要求"用当前二进制 +init参数"的底层原因——LinuxFactory会把自己的可执行文件 reexec 出来充当容器 init; StartInitialization()是 bootstrap 阶段真正读取配置并进入初始化的低层入口(文档也强调它属于"内部实现细节,不应被外部消费"),其实现见 factory_linux.go#L277-L357。它依次从环境变量中取回父进程通过 fd 传递的通道:_LIBCONTAINER_INITPIPE(父进程同步管道)、_LIBCONTAINER_INITTYPE与_LIBCONTAINER_FIFOFD(仅 standard init 有 exec FIFO)、_LIBCONTAINER_CONSOLE(控制台 socket fd)、_LIBCONTAINER_LOGPIPE,以及_LIBCONTAINER_MOUNT_FDS(O_PATH 挂载文件句柄),随后os.Clearenv()清掉所有 libcontainer 专属环境变量,最后newContainerInit(...).Init()——注释明确写道"If Init succeeds, syscall.Exec will not return",即成功后进程被 exec 掉,这就是panic兜底行永远不会被执行的原因。
另外需要注意一个环境事实:cloudpods 的 vendor/modules.txt 只登记了 libcontainer 及其子包(cgroups、configs、seccomp 等),并未包含 libcontainer/nsenter,说明当前依赖链路只在最终二进制内部完成 bootstrap,不会单独以模块形式引入 nsenter 包。
创建 Factory:从 README 示例到 v1.1.5 实际 API
文档给出的 factory 初始化示例是:
factory, err := libcontainer.New("/var/lib/container", libcontainer.Cgroupfs, libcontainer.InitArgs(os.Args[0], "init"))
if err != nil {
logrus.Fatal(err)
return
}
这里有一个版本差异值得特别留意:文档示例使用的是旧版三参数签名(root、cgroup driver 枚举、init 参数),而本仓库内置的 v1.1.5 已改为函数式选项风格:
// New returns a linux based container factory based in the root directory and
// configures the factory with the provided option funcs.
func New(root string, options ...func(*LinuxFactory) error) (Factory, error)
见 factory_linux.go#L88-L113。LinuxFactory 结构(factory_linux.go#L116-L142)字段与可用选项如下:
| 字段 / 选项函数 | 作用 |
|---|---|
Root |
存放容器状态(state.json 等)的根目录,Create 前会 MkdirAll(root, 0700) |
InitPath |
容器 init 的可执行路径,默认 /proc/self/exe |
InitArgs(InitArgs 选项) |
init 的调用参数,默认 [<当前二进制> "init"],相对路径会被解析为绝对路径 |
CriuPath(CriuPath 选项) |
Checkpoint/Restore 所用 criu 二进制路径,默认 "criu" |
NewuidmapPath / NewgidmapPath(对应选项函数) |
rootless 场景做 UID/GID 映射的 newuidmap/newgidmap 路径 |
Validator |
配置校验器,默认 validate.New() |
NewIntelRdtManager(IntelRdtFs 选项) |
启用 Intel RDT(L3 缓存、内存带宽)资源控制;若 CPU 不支持则置空 |
——(TmpfsRoot 选项) |
若 Root 未挂载则自动以 tmpfs 挂载,用于无盘/内存盘场景 |
cgroup driver 的选择(cgroupfs 或 systemd)在 v1.1.5 中不再由 factory 构造参数决定,而是在 Create 内部由 manager.New(config.Cgroups) 根据配置与系统状态协商(libcontainer/cgroups/manager/new.go)。
Create 的前置校验在 factory_linux.go#L144-L220 中值得逐条关注:
- ID 校验:必须匹配
^<a href="https://link.gitcode.com/i/7c4fdb37ea62fdee0bf8113e0a9aefc9" target="_blank">\w+-\.]+$且不允许逃逸出 root 目录(idRegex,[factory_linux.go#L30),防止路径穿越; - 配置校验:
Validator.Validate(config)对 namespace、capability、cgroup 配置做合法性检查; - 容器根目录:
securejoin.SecureJoin(l.Root, id),已存在则返回ErrExist; - cgroup 检查:目标 cgroup 已存在且非空会告警(并提示该用法将在 runc 1.2 移除);cgroup 处于 frozen 状态则直接报错 "container's cgroup unexpectedly frozen";
- 状态文件:每个容器目录下保存
state.json,standard init 流程还依赖exec.fifo(常量见 factory_linux.go#L25-L28)。
解剖 configs.Config:一份完整可用的容器配置
Config 是描述"容器如何被创建"的核心结构,定义于 configs/config.go#L90 起:Rootfs(根文件系统路径)、Namespaces、Capabilities、Cgroups、Mounts、Devices、Hostname、Networks、Routes、Rlimits、AppArmorProfile、ProcessLabel(SELinux)、Seccomp、UidMappings/GidMappings(user namespace)、MaskPaths/ReadonlyPaths 等。文档给出的完整示例如下(保留全部字段,并补充关键注释):
defaultMountFlags := unix.MS_NOEXEC | unix.MS_NOSUID | unix.MS_NODEV
var devices []*configs.DeviceRule
for _, device := range specconv.AllowedDevices {
devices = append(devices, &device.Rule)
}
config := &configs.Config{
Rootfs: "/your/path/to/rootfs", // 容器根文件系统目录
Capabilities: &configs.Capabilities{
// Bounding/Effective/Permitted/Ambient 四套能力集合;
// 未列出的能力会被全部 drop
Bounding: []string{
"CAP_CHOWN", "CAP_DAC_OVERRIDE", "CAP_FSETID", "CAP_FOWNER",
"CAP_MKNOD", "CAP_NET_RAW", "CAP_SETGID", "CAP_SETUID",
"CAP_SETFCAP", "CAP_SETPCAP", "CAP_NET_BIND_SERVICE",
"CAP_SYS_CHROOT", "CAP_KILL", "CAP_AUDIT_WRITE",
},
Effective: []string{ /* 同上 14 项 */ },
Permitted: []string{ /* 同上 14 项 */ },
Ambient: []string{ /* 同上 14 项 */ },
},
// 声明容器要新建哪些命名空间;未列出的命名空间与父进程共享
Namespaces: configs.Namespaces([]configs.Namespace{
{Type: configs.NEWNS},
{Type: configs.NEWUTS},
{Type: configs.NEWIPC},
{Type: configs.NEWPID},
{Type: configs.NEWUSER},
{Type: configs.NEWNET},
{Type: configs.NEWCGROUP},
}),
// cgroup 归属与资源约束;Resources.Devices 是设备 cgroup 的允许规则
Cgroups: &configs.Cgroup{
Name: "test-container",
Parent: "system",
Resources: &configs.Resources{
MemorySwappiness: nil,
Devices: devices,
},
},
// 用只读文件掩蔽这些路径,防止访问宿主敏感信息
MaskPaths: []string{
"/proc/kcore",
"/sys/firmware",
},
// 强制只读的 /proc 子路径
ReadonlyPaths: []string{
"/proc/sys", "/proc/sysrq-trigger", "/proc/irq", "/proc/bus",
},
Devices: specconv.AllowedDevices,
Hostname: "testing",
Mounts: []*configs.Mount{
{ // 容器内 /proc,带 noexec/nosuid/nodev
Source: "proc",
Destination: "/proc",
Device: "proc",
Flags: defaultMountFlags,
},
{ // /dev 用 tmpfs 隔离,mode=755
Source: "tmpfs",
Destination: "/dev",
Device: "tmpfs",
Flags: unix.MS_NOSUID | unix.MS_STRICTATIME,
Data: "mode=755",
},
{ // 独立的 devpts 实例
Source: "devpts",
Destination: "/dev/pts",
Device: "devpts",
Flags: unix.MS_NOSUID | unix.MS_NOEXEC,
Data: "newinstance,ptmxmode=0666,mode=0620,gid=5",
},
{ // POSIX 共享内存,64MB
Device: "tmpfs",
Source: "shm",
Destination: "/dev/shm",
Data: "mode=1777,size=65536k",
Flags: defaultMountFlags,
},
{ // POSIX 消息队列
Source: "mqueue",
Destination: "/dev/mqueue",
Device: "mqueue",
Flags: defaultMountFlags,
},
{ // /sys 只读
Source: "sysfs",
Destination: "/sys",
Device: "sysfs",
Flags: defaultMountFlags | unix.MS_RDONLY,
},
},
// user namespace 映射:容器 root(0) <-> 宿主 uid 1000,映射 65536 个 ID
UidMappings: []configs.IDMap{
{ContainerID: 0, HostID: 1000, Size: 65536},
},
GidMappings: []configs.IDMap{
{ContainerID: 0, HostID: 1000, Size: 65536},
},
Networks: []*configs.Network{
{Type: "loopback", Address: "127.0.0.1/0", Gateway: "localhost"},
},
Rlimits: []configs.Rlimit{
{Type: unix.RLIMIT_NOFILE, Hard: uint64(1025), Soft: uint64(1025)},
},
}
几个值得注意的语义(均可在 configs/config.go 的字段注释中确认):
- Capabilities 的注释很关键:"All capabilities not specified will be dropped from the processes capability mask"——这是白名单式配置,漏写即剥夺;
- Namespaces 的默认行为是共享父进程命名空间,示例中显式新建了除 mnt 之外的全部类型(mount namespace 通常由 init 流程自动建立);
Devices与Cgroups.Resources.Devices是两套东西:前者是启动时在容器内自动创建的字符/块设备节点(注释提醒"make sure that the node is marked as allowed in the cgroup as well"),后者是设备 cgroup 的允许规则;Rlimits(configs/config.go#L16-L20)用于设置打开文件数等资源上限,示例把RLIMIT_NOFILE软/硬限都设为 1025;- user namespace 场景下必须同时给出
NEWUSERnamespace 与UidMappings/GidMappings,二者缺一不可;rootless 运行时还会用到 factory 层的NewuidmapPath/NewgidmapPath选项调用newuidmap/newgidmap完成映射。
创建容器并启动 init 进程
配置就绪后,通过 factory 创建容器:
container, err := factory.Create("container-id", config)
if err != nil {
logrus.Fatal(err)
return
}
然后以 libcontainer.Process 描述容器内要启动的初始进程,示例中是 /bin/bash:
process := &libcontainer.Process{
Args: []string{"/bin/bash"},
Env: []string{"PATH=/bin"},
User: "daemon",
Stdin: os.Stdin,
Stdout: os.Stdout,
Stderr: os.Stderr,
Init: true, // true 表示这是容器的 init 进程
}
err := container.Run(process)
if err != nil {
container.Destroy()
logrus.Fatal(err)
return
}
// wait for the process to finish.
_, err := process.Wait()
if err != nil {
logrus.Fatal(err)
}
// destroy the container.
container.Destroy()
Process 的 Args/Env/User/Stdin/Stdout/Stderr/Init 字段分别对应命令行、环境变量、运行用户(可用 libcontainer/user 包做用户名到 UID 的解析)、标准三向流以及"是否为 init"。这里要区分两个启动语义(container.go#L103-L110):
Start(process):启动进程并返回,不等待 exec FIFO——standard init 的 FIFO 机制会暂停 init 直到外部写入,用于把父进程 fd、控制台等资源准备好再放行;Run(process):Start 之后立即打开 exec FIFO 放行,"returns immediately after start",是文档示例采用的方式。
process.Wait() 返回退出状态后,container.Destroy() 销毁容器:接口注释(container.go#L112-L120)明确了前置条件——running 容器必须先 Signal 停止,paused 容器必须先 Resume,且已销毁的容器再次 Destroy 不报错。
与运行中容器交互:完整生命周期 API
文档列出了创建之外的全部交互方式(完整保留):
// return all the pids for all processes running inside the container.
processes, err := container.Processes()
// get detailed cpu, memory, io, and network statistics for the container and
// it's processes.
stats, err := container.Stats()
// pause all processes inside the container.
container.Pause()
// resume all paused processes.
container.Resume()
// send signal to container's init process.
container.Signal(signal)
// update container resource constraints.
container.Set(config)
// get current status of the container.
status, err := container.Status()
// get current container's state information.
state, err := container.State()
这些操作与 BaseContainer 接口一一对应(container.go#L72-L130),补充两点源码级细节:
Processes()的返回语义:接口注释说明"部分 PID 可能已不在容器内",除非容器处于 PAUSED 状态——只有冻结的 cgroup 才能保证 PID 列表稳定,这正是 freezer(cgroups/fs/freezer.go、cgroups/fs2/freezer.go)存在的原因;Signal(s, all)支持发给全部进程:文档简写为container.Signal(signal),实际签名带all bool,true 时向容器内所有进程(含 init)发信号。
状态机方面,Status 枚举定义了五个状态(container.go#L18-L29):created(已创建未运行)→ running → pausing/paused(暂停中/已暂停)→ stopped。State() 返回的 BaseState 包含 ID、宿主命名空间下的 InitProcessPid、InitProcessStartTime(用于与 state.json 做进程身份比对)、创建时间与完整 Config(container.go#L50-L65);factory.Load(id) 则读取 state.json 恢复出一个 loadedState 容器句柄(factory_linux.go#L222-L269),这是跨进程管理同一容器的基础。Set(config) 则对应 cgroup manager 的 Apply/Set 路径,实现运行中修改 CPU、内存等约束。
Checkpoint & Restore:CRIU 集成
文档最后介绍了 C/R 能力:libcontainer 集成 CRIU,可以把容器内正在运行的进程状态保存到磁盘,并在本机或另一台机器上恢复为新进程。前提与约束:
criu版本要求 ≥ 1.5.2;未安装时需从源码构建,或随构建环境安装;- factory 通过
CriuPath选项指定criu可执行文件路径,默认值为"criu"(factory_linux.go#L79-L86、factory_linux.go#L101); - 恢复流程由
restored_process.go与criu_opts_linux.go支撑:linuxContainer持有criuPath(见 factory_linux.go#L204-L214 中c.criuPath = l.CriuPath),恢复出的容器通过Load加载状态并绑定 CRIU 生成的镜像。
从源码结构看,Checkpoint/Restore 是叠加在标准生命周期之上的能力:先 Pause 冻结全部进程,再由 criu dump 出内存与文件描述符镜像,最后在新的 init 流程中 restore;这依赖内核的 ptrace、userfaultfd 等能力,实际部署时需按 CRIU 自身要求配置内核模块与权限。
对 cloudpods 开发者的实战参考
把上述机制放回 cloudpods 仓库,可以得到三条实用线索:
- Pod 容器统计的 cgroup 命名:host agent 通过 cadvisor_stats_provider.go 采集容器 CPU/内存时,需要按 libcontainer 的两种 cgroup driver 解析 cgroup 名(
cgroupfs的层级路径 vs systemd 的xxx.slice命名,_是-的转义)。如果自定义采集逻辑,应复用ParseCgroupfsToCgroupName/ParseSystemdToCgroupName的约定; - cgroup v2 设备过滤:ebpf.go 中保留的
canSkipEBPFError逻辑直接借鉴自 runcdevices_v2.go——当设备规则全是 deny(非 r/w/m 全开)时 eBPF 附加失败可被忽略,这是判断"设备 cgroup 降级"的关键判据; - 版本约束:仓库内置的是 runc v1.1.5 的 libcontainer API(函数式
New(root, options...)、configs.Config字段语义),编写或审查涉及 libcontainer 的代码时,应以vendor/github.com/opencontainers/runc/libcontainer/下的实际源码为准,而不是本文引用的 README 中的旧式示例签名。
小结
libcontainer 是 runc 的核心库,也是理解"Linux 容器到底是什么"的最佳代码入口:一个 Factory 负责状态与校验,一份 configs.Config 声明全部隔离与约束,两个进程阶段(bootstrap + init)完成从宿主机到容器的跨越,之后 Process/Container API 覆盖运行、暂停、恢复、信号、资源热更新与销毁的全生命周期,CRIU 则在其上叠加 Checkpoint/Restore。cloudpods 通过 vendor 该库支撑了 Pod 资源统计与设备过滤等 host 侧能力;掌握本文覆盖的 API 与源码路径,即可在这套多云平台中读懂并扩展一切与"容器如何被创建和管理"相关的实现。