容器如何读取文件:从 VFS、Page Cache 到 OverlayFS、Nydus 与 gVisor
沿容器进程读取文件的路径,理解 VFS、Page Cache、OverlayFS、Nydus 与 gVisor 的分工。
Contents
本文沿着容器进程打开和读取文件的路径,解释 VFS、Page Cache 和不同文件系统如何协作。OverlayFS 的挂载与写入细节见 容器中的 OverlayFS:分层挂载、Copy-up 与 Whiteout。
0. 总体心智模型
本文用一条主线贯穿:容器进程执行 cat /etc/os-release 时,内核到底在看什么对象、走什么路径、读到的数据从哪里来。
先看总图:
runc/containerd + overlayfs 常见路径:
container process
|
| openat("/etc/os-release")
v
fd table
|
v
struct file <-- “一次打开”
|
v
struct path { vfsmount, dentry } <-- “在哪个挂载树上,哪个名字节点”
|
v
overlayfs dentry/inode/file ops <-- 容器 rootfs 的 merged 视图
|
+--> upperdir real dentry/inode /var/lib/containerd/.../snapshots/<active>/fs/...
|
+--> lowerdir real dentry/inode /var/lib/containerd/.../snapshots/<layer>/fs/...
|
v
ext4/xfs/btrfs inode
|
v
address_space / page cache
|
cache hit? yes -> copy_to_user()
|
no
v
filesystem maps file offset -> blocks
|
v
block layer -> NVMe/SSD/HDD
Linux VFS 是内核中给用户态提供统一文件系统接口的层,同时让 ext4、xfs、tmpfs、procfs、overlayfs、fuse、erofs 等不同文件系统实现共存。open(2)、stat(2)、read(2)、write(2) 等系统调用会进入 VFS,再由 VFS 分派到具体文件系统的方法。
你可以把 Linux 文件访问拆成五层:
进程局部对象
fd: int,只在当前进程 fd table 中有意义
打开文件对象
struct file: 一次 open 的状态,包含 offset、flags、f_op、f_path
路径解析对象
struct path = { struct vfsmount *mnt, struct dentry *dentry }
dentry: “这个目录项名字是什么,它的 parent 是谁,它指向哪个 inode”
文件实体对象
inode: 文件对象本体,包含 mode/uid/gid/size/timestamps/i_mapping/i_op/i_fop
super_block: 一个已挂载 filesystem instance
数据缓存对象
address_space / page cache: 文件内容页缓存,通常挂在 inode->i_mapping 上
注意:严格说,vfsmount / struct mount 也非常关键,尤其在容器里。同一个 dentry / inode 可以通过不同 mount 出现在不同路径;容器的 / 本质上是某个 mount namespace 中的 root mount + root dentry。
1. 什么是 VFS,为什么 Linux 需要 VFS
没有 VFS 时,用户态程序可能需要知道:
read_ext4()
read_xfs()
read_tmpfs()
read_procfs()
read_fuse()
read_overlayfs()
...
有了 VFS,用户态只需要:
fd = open("/etc/os-release", O_RDONLY);
read(fd, buf, sizeof(buf));
close(fd);
VFS 做的事是:
统一 syscall 入口
open/read/write/stat/mmap/chmod/rename/unlink/...
统一对象模型
super_block / inode / dentry / file / address_space
统一路径解析
"/a/b/c" -> mount tree + dentry tree + inode
统一分派接口
inode_operations
file_operations
super_operations
address_space_operations
让具体文件系统实现自己的方法
ext4_file_read_iter()
xfs_file_read_iter()
fuse_file_read_iter()
ovl_open()
tmpfs_file_read_iter()
...
VFS 的一个关键能力是 dcache。Linux VFS 使用 pathname 在 directory entry cache,也就是 dentry cache / dcache 中快速把路径名转换成具体 dentry。dentry 只在 RAM 中存在,不会保存到磁盘。
从容器角度看,VFS 的意义更大:
容器中的 /etc/os-release
不是一个特殊的“容器文件”
而是某个 mount namespace 中
overlayfs / fuse / erofs / bind mount / tmpfs
共同组成的 VFS 路径树上的一个 dentry/inode
2. file / dentry / inode / super_block 分别是什么
2.1 super_block:一个已挂载文件系统实例
super_block 代表一个 mounted filesystem。可以把它理解成:
super_block
|
+-- 文件系统类型: ext4 / xfs / overlay / fuse / tmpfs / proc / erofs
+-- 这个 FS 的根 dentry
+-- block size / mount flags / fs-specific state
+-- super_operations: statfs, sync_fs, remount_fs, put_super...
+-- inode cache
例子:
/dev/nvme0n1p3 mounted as ext4 at /
-> 一个 ext4 super_block
overlay mounted at /run/containerd/.../rootfs
-> 一个 overlayfs super_block
proc mounted at /proc inside container
-> 一个 procfs super_block
tmpfs mounted at /dev/shm
-> 一个 tmpfs super_block
但是要区分:
super_block: 文件系统实例
vfsmount: 这个文件系统实例挂到某个 mount namespace 的某个位置
bind mount 通常不会创建新的底层文件系统实例,而是创建另一个 mount attachment,指向已有 super_block 的某个子树。
2.2 inode:文件对象本体,不等于路径名
inode 是文件系统对象的核心表示。普通文件、目录、FIFO、socket、设备节点都可以有 inode。
inode 里面关心的是:
inode
|
+-- i_ino inode number
+-- i_mode file type + permission
+-- i_uid/i_gid owner
+-- i_size file size
+-- timestamps atime/mtime/ctime
+-- i_sb belongs to which super_block
+-- i_mapping address_space,page cache 入口
+-- i_op inode operations: lookup, mkdir, unlink, rename...
+-- i_fop default file operations: read_iter, write_iter, mmap...
inode 不包含路径名。路径名属于 dentry。
一个文件有多个 hard link 时:
/path/a dentry ----+
+---- inode #12345
/path/b dentry ----+
所以你用 stat 看 inode 时,真正唯一标识通常是:
(st_dev, st_ino)
也就是:
哪个 filesystem instance 上的哪个 inode
2.3 dentry:路径名组件缓存
dentry 是 directory entry 的内核对象,表示路径树中的一个名字节点:
dentry
|
+-- name: "os-release"
+-- parent: dentry("etc")
+-- d_inode: inode*
+-- d_sb: super_block*
+-- d_op: dentry operations
路径 /etc/os-release 不是一个字符串直接对应 inode,而是路径解析的结果:
/ root dentry
└── etc dentry("etc")
└── os-release dentry("os-release") -> inode
dcache 中还会有 negative dentry:
lookup("/no/such/file")
-> 发现不存在
-> 缓存一个 “no such file” 的 negative dentry
-> 下次再查可以更快返回 ENOENT
这对容器很重要,因为容器启动、动态链接器加载、应用扫描配置目录,会产生大量 pathname lookup。dcache 命中能显著减少底层文件系统 lookup。
2.4 struct file:一次 open 的状态
file 不是“磁盘上的文件”,而是 一次打开文件的内核对象。
可以理解成:
struct file
|
+-- f_path { vfsmount, dentry }
+-- f_inode inode*
+-- f_op file_operations*
+-- f_mapping address_space*
+-- f_pos current file offset
+-- f_flags O_RDONLY/O_APPEND/O_NONBLOCK/...
+-- private_data
fd 和 file 的关系:
process A fd table
fd 0 -> struct file for stdin
fd 1 -> struct file for stdout
fd 2 -> struct file for stderr
fd 3 -> struct file for /etc/os-release
process B fd table
fd 3 -> another struct file, or maybe shared one via fork/dup
open() 返回的是一个小的非负整数 fd,它是进程 fd table 的索引;open() 会创建一个 system-wide open file description,记录 file offset 和 file status flags,fd 是对这个 open file description 的引用。
这解释了一个常见现象:
int fd1 = open("/tmp/a", O_RDONLY);
int fd2 = dup(fd1);
read(fd1, buf, 10);
read(fd2, buf, 10); // 从 offset=10 后继续,因为共享同一个 struct file/open file description
但:
int fd1 = open("/tmp/a", O_RDONLY);
int fd2 = open("/tmp/a", O_RDONLY);
read(fd1, buf, 10);
read(fd2, buf, 10); // fd2 仍从 offset=0 开始,因为是另一个 struct file
3. 从 fd 到 file,再到 dentry / inode 的访问路径
以容器内:
cat /etc/os-release
为例,先发生 openat,再发生 read。
3.1 openat("/etc/os-release") 的路径解析
简化伪代码:
int sys_openat(int dirfd, const char *pathname, int flags) {
struct path start;
if (pathname starts with "/") {
start = current->fs->root; // 容器进程看到的 /
} else {
start = dirfd or current->fs->pwd;
}
struct path path = path_lookup(start, pathname);
struct inode *inode = path.dentry->d_inode;
struct file *file = alloc_file(path, flags, inode->i_fop);
file->f_op->open(inode, file); // 具体 FS 可实现自己的 open
int fd = get_unused_fd();
current->files->fdtable[fd] = file;
return fd;
}
路径解析过程大概是:
current->fs->root
|
v
"/" in container mount namespace
|
v
lookup "etc"
|
+-- dcache hit? use dentry
|
+-- dcache miss? call parent_inode->i_op->lookup()
|
v
lookup "os-release"
|
v
final dentry -> inode
路径 lookup 不只是 dentry 树,还会穿越 mount tree:
/path reaches mountpoint?
|
v
jump from current vfsmount to mounted vfsmount root
这就是为什么容器里的 /proc、/dev/shm、/var/run/secrets/... 可以是不同文件系统。
3.2 read(fd) 的访问路径
open 之后,后续 read(fd) 不再解析路径名,而是直接从 fd table 找 struct file:
ssize_t sys_read(int fd, void *buf, size_t count) {
struct file *file = current->files->fdtable[fd];
// VFS 层
return vfs_read(file, buf, count, &file->f_pos);
}
再往下:
fd
|
v
struct file
|
+-- f_op->read_iter()
|
v
generic_file_read_iter() or filesystem-specific read
|
v
file->f_mapping
|
v
address_space / page cache
|
+-- cache hit: copy page cache -> user buffer
|
+-- cache miss:
allocate folio/page
call mapping->a_ops->read_folio() or ->readahead()
filesystem reads data
fill page cache
copy_to_user()
address_space 可以理解为 cacheable、mappable object 的内容;它的 host 是 inode 或 block device,i_pages 是 cached pages。
3.3 关系图
task_struct
|
+-- files_struct
| |
| +-- fdtable[3] ----------------------+
| |
| v
| struct file
| |
| +-- f_pos
| +-- f_flags
| +-- f_op
| +-- f_path
| |
| v
| struct path
| { mnt, dentry }
| |
| v
| dentry
| |
| v
| inode
| |
| v
| super_block
|
+-- fs_struct
|
+-- root: struct path // 容器进程的 /
+-- pwd: struct path
一个很重要的结论:
路径名只在 open/stat/unlink/rename 等 pathname syscall 中重要。
open 成功后,fd 直接引用 struct file。
即使路径被 unlink,fd 仍然可以继续读写,因为 file pin 住了 dentry/inode。
4. Page Cache 是什么,read / write / mmap 和 Page Cache 的关系
4.1 Page Cache 的本质
Page Cache 是 Linux 用内存缓存文件内容的机制。现代内核里很多地方用 folio 概念,但你先把它理解成“按页缓存文件数据”即可:
address_space
|
+-- i_pages:
page index 0 -> folio/page containing file offset 0..4095
page index 1 -> folio/page containing file offset 4096..8191
page index 2 -> folio/page containing file offset 8192..12287
key 通常是:
(inode->i_mapping, page_index)
也就是:
某个文件的某个 offset range
不是:
某个进程的缓存
某个容器的缓存
某个 fd 的缓存
因此在普通 runc 容器里,page cache 是宿主机内核全局的。两个容器如果最终读的是同一个底层 lower inode,它们可能共享 page cache。
4.2 read() 和 Page Cache
默认 buffered I/O 路径:
read(fd, buf, 4096)
|
v
fd -> struct file -> inode->i_mapping
|
v
查 page cache
|
+-- hit:
| copy page cache -> user buf
|
+-- miss:
filesystem -> storage/remote backend 读入
放入 page cache
copy page cache -> user buf
Buffered I/O 是 Linux 默认 file I/O 路径,文件内容缓存在 memory page cache 中以满足 reads 和 writes。dirty cache 会在之后写回磁盘,也可以通过 fsync 等强制写回。
4.3 write() 和 Page Cache
默认 buffered write:
write(fd, "abc", 3)
|
v
copy user buffer -> page cache
|
v
mark page dirty
|
v
return to userspace
|
v
later:
writeback dirty pages -> filesystem -> block layer/device
所以 write() 返回成功通常不等于数据已经落盘。你需要:
fsync(fd);
或者依赖内核后台 writeback。
简化伪代码:
ssize_t buffered_write(struct file *f, const char *user, size_t len) {
mapping = f->f_mapping;
for each page_index touched:
page = grab_cache_page(mapping, page_index);
copy_from_user(page, user);
set_page_dirty(page);
return len;
}
对应到容器 overlayfs:
write lower-only file
|
v
overlayfs copy_up lower -> upper
|
v
write upper inode page cache
|
v
dirty upper page
|
v
writeback to host filesystem upperdir
4.4 mmap() 和 Page Cache
mmap() 创建的是虚拟内存映射,不是立刻把整个文件读进内存。
fd = open("/lib/libc.so.6", O_RDONLY);
p = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
close(fd); // mapping 仍然有效
file mapping 的内容来自 fd 指向的文件;并且 mmap() 返回后,fd 可以立刻关闭而不会使 mapping 失效。
实际读数据发生在 page fault:
CPU load p[1234]
|
v
page fault
|
v
VMA says: file-backed mapping
|
v
find page in file page cache
|
+-- hit: map page into process page table
|
+-- miss: filesystem read_folio -> fill page cache -> map page
MAP_SHARED 和 MAP_PRIVATE 的差异:
MAP_SHARED
写 mmap 区域
-> 修改 file-backed page cache
-> mark dirty
-> msync/fsync/writeback 后进入底层文件
MAP_PRIVATE
写 mmap 区域
-> copy-on-write
-> 变成 anonymous page
-> 不写回原文件
DAX 是一个特例,它绕过传统 page cache。DAX 对 memory-like block device 直接访问存储,去掉额外拷贝。
5. 文件系统、块设备、Page Cache 的关系
普通 ext4 / xfs 文件读取路径:
read("/var/lib/containerd/.../snapshots/12/fs/usr/bin/app")
|
v
VFS
|
v
ext4/xfs inode
|
v
page cache lookup
|
+-- hit -> return
|
+-- miss
|
v
filesystem maps:
file offset 8192
-> extent
-> logical block
-> disk sector
|
v
submit bio/request
|
v
block layer
|
v
device driver / NVMe / SSD
block layer 位于 filesystem 和具体块设备驱动之间。当 userspace 对 block device 执行 I/O,比如读写文件时,blk-mq 会在 userspace/filesystem 与 block device driver 之间管理 I/O requests。
但不是所有文件系统都依赖块设备:
ext4/xfs/btrfs
通常背后是 block device
tmpfs
背后是内存/swap,不是普通磁盘块设备
procfs/sysfs
大量内容是动态生成的 kernel data structure 视图
fuse
VFS 请求会交给 userspace daemon
overlayfs
自己不直接管理真实磁盘块,而是组合 upper/lower 文件系统
nydus/erofs/fuse/fscache
可以把远端 blob/chunk 按需变成文件内容
因此 page cache 的位置要看具体文件系统:
ext4 regular file
page cache keyed by ext4 inode->i_mapping
tmpfs file
page cache-like/shmem pages,本身就是内存对象
fuse cached mode
kernel 可用 page cache 缓存 FUSE 文件内容
fuse direct-io mode
绕过 page cache
FUSE 区分 direct-io 与 cached / write-through / writeback-cache 模式:direct-io 会绕过 page cache;cached mode 中 reads 可以由 page cache 满足,并且 kernel 可以 read-ahead。
6. OverlayFS 如何接入 VFS
OverlayFS 本身是一个 Linux 文件系统类型。mount 时它注册为一个 VFS filesystem instance:
mount -t overlay overlay \
-o lowerdir=/lower1:/lower2,upperdir=/upper,workdir=/work \
/merged
VFS 视角:
file_system_type("overlay")
|
+-- mount()
|
v
overlay super_block
|
v
root overlay dentry at /merged
OverlayFS 会组合 upper filesystem 和 lower filesystem;同名对象同时存在时 upper 可见,lower 被隐藏;如果两边都是目录,则形成 merged directory。
6.1 OverlayFS lookup 过程
假设:
lowerdir:
/etc/os-release
/usr/bin/app
upperdir:
/etc/hosts
容器 merged root:
/
├── etc
│ ├── os-release from lower
│ └── hosts from upper
└── usr
└── bin
└── app from lower
OverlayFS lookup 伪代码:
ovl_lookup(parent, name):
upper = lookup_upper(parent, name)
lower = lookup_lower_layers(parent, name)
if upper is whiteout:
return negative
if upper exists and lower exists:
if both are directories:
return merged_dir_dentry(upper, lower)
else:
return upper_dentry
if upper exists:
return upper_dentry
if lower exists:
return lower_dentry
return negative
6.2 读取 lower 文件
container reads /usr/bin/app
|
v
VFS sees overlay dentry
|
v
overlayfs knows this file is lower-only
|
v
open/read real lower file
|
v
lower filesystem page cache
可以把 OverlayFS 理解成:
VFS 上层看到的是 overlay inode/dentry
真正数据通常在 upper/lower real inode
实际内核细节会随功能选项变化,例如 xino、index、metacopy、NFS export 等;观察时不要简单假设 overlay 视图里的 inode number 一定等于 lower inode number。
6.3 写 lower 文件:copy-up
当容器修改 lower-only 文件:
write("/etc/os-release")
|
v
overlayfs detects lower-only object
|
v
copy_up:
lower /etc/os-release
-> upperdir /etc/os-release
|
v
write upper file
|
v
future reads see upper version
删除 lower 文件时,OverlayFS 不能真的删 lowerdir,因为 lower layer 是共享、只读的 image layer。所以它在 upperdir 记录 whiteout:
rm /bin/foo
|
v
create upperdir /bin/.wh.foo or trusted.overlay.whiteout
|
v
merged view hides lower /bin/foo
OverlayFS 使用 whiteout 和 opaque directory 在不修改 lower filesystem 的情况下表达删除;whiteout 会让 lower 中同名对象被忽略。
7. containerd / runc 创建出来的 rootfs 在 VFS 视角是什么
containerd 的 snapshotter 负责管理容器文件系统快照。snapshotters manage snapshots of container filesystems。containerd 默认核心 snapshotter 包括 overlayfs,还有 native、btrfs、zfs、erofs 等;非核心插件包括 nydus、stargz 等。
典型 containerd overlayfs snapshotter 路径:
/var/lib/containerd/
└── io.containerd.snapshotter.v1.overlayfs/
└── snapshots/
├── 10/
│ └── fs/ # lower layer unpack result
├── 11/
│ └── fs/ # another lower layer
└── 42/
├── fs/ # active upperdir
└── work/ # overlayfs workdir
运行容器时,containerd-shim / runc 周边通常会准备一个 OCI bundle:
/run/containerd/io.containerd.runtime.v2.task/k8s.io/<container-id>/
├── config.json
├── rootfs/ # overlay mount target
├── init.pid
└── log.json
OCI runtime spec 中,root.path 指定容器 root filesystem 的路径;POSIX 平台上它可以是绝对路径,也可以是相对 bundle 的路径,惯例是 rootfs,并且该目录必须存在。
OCI bundle 由 config.json 和 root filesystem 组成;root filesystem 是 config.json 中 root.path 引用的目录。
7.1 runc 做了什么
简化流程:
containerd pull/unpack
|
v
snapshotter prepare active snapshot
|
v
returns mount spec:
type=overlay
options=lowerdir=...,upperdir=...,workdir=...
|
v
containerd-shim prepares OCI bundle/rootfs
|
v
runc creates namespaces
|
v
mount overlay rootfs
|
v
mount /proc, /sys, /dev, /dev/pts, /dev/shm, bind mounts...
|
v
pivot_root/chroot into rootfs
|
v
execve(container init)
OCI Linux spec 使用 namespaces、cgroups、capabilities、LSM、filesystem jails 等 kernel features;其中 mount namespace 让容器拥有隔离的 mount table。
7.2 VFS 视角下的容器 /
容器进程的 / 是:
current->fs->root = struct path {
mnt = overlay vfsmount in this mount namespace,
dentry = overlay root dentry
}
不是:
一个新的内核
一个新的 VFS
一个只属于容器的 page cache
普通 runc 容器共享宿主机内核。隔离来自:
mount namespace
pid namespace
net namespace
uts namespace
ipc namespace
user namespace
cgroup
LSM/seccomp/capabilities
所以容器内:
cat /etc/os-release
在宿主机 VFS 看来就是:
某个 host task
在某个 mount namespace 中
从它的 fs_struct.root 开始
lookup "etc" -> "os-release"
读 overlayfs 视图中的文件
8. Nydus / FUSE / remote snapshotter 为什么可以 lazy loading
传统 OCI image 路径通常是:
pull all layer blobs
|
v
decompress
|
v
unpack each layer into snapshotter lowerdir
|
v
mount overlay
|
v
start container
Nydus 的关键变化是:metadata 和 data 分离,文件数据按 chunk 存储,运行时可以只先拿 metadata,让文件树先可见,真正读文件内容时再按需拉取 chunk。
Nydus snapshotter 的 lazy pulling 意味着容器可以在镜像只部分可用时运行,必要 chunks 会 on-demand 获取。
Nydus RAFS 设计中,metadata 存在 bootstrap,data 存在 blobfile;Nydus 把 container image 拆成 metadata 和 data,metadata 包含启动所需的文件树信息,data 按 chunk 存储。
8.1 FUSE 版本的 lazy loading
container read /usr/lib/libfoo.so
|
v
VFS
|
v
overlayfs merged view
|
v
lowerdir is fuse/nydus filesystem
|
v
FUSE kernel client
|
v
nydusd userspace daemon
|
+-- has chunk in blobcache?
| yes -> return data
|
+-- no
|
v
fetch chunk from registry/P2P/object storage
|
v
verify/decompress
|
v
return data to kernel
|
v
fill page cache
|
v
copy_to_user()
核心点:
路径 lookup/stat/readdir 只需要 metadata
read/mmap page fault 才需要 file data
因此只要 Nydus 能先提供足够 metadata,VFS 就可以让容器先启动。第一次读冷文件时会慢,因为要拉 chunk;之后可能命中:
kernel page cache
nydus blobcache
backend/P2P cache
8.2 FUSE page cache 与 Nydus blobcache 是两层缓存
常见情况可以理解成:
容器文件内容 page cache
key: fuse/nydus file address_space + offset
value: 解压/组装后的文件字节
nydus blobcache
key: blob/chunk digest
value: 从远端取回的压缩或未压缩 chunk
宿主机文件系统 page cache
如果 blobcache 存在 ext4/xfs 文件里,它本身也可能被 host page cache 缓存
所以 Nydus 路径可能有多层缓存:
application buffer
^
|
kernel page cache for FUSE file
^
|
nydusd decoded chunk
^
|
nydus blobcache file
^
|
host FS page cache / disk / remote registry / P2P
8.3 Nydus + OverlayFS
容器一般仍需要 writable rootfs,因此常见组合是:
overlayfs merged root
|
+-- upperdir: writable host directory
|
+-- lowerdir: read-only nydus filesystem
读 lower 文件:
container read
-> overlayfs
-> nydus lower
-> fetch chunk on demand
写 lower 文件:
container write
-> overlayfs copy_up
-> upperdir normal host FS
-> future reads from upperdir, no longer read lower nydus file
8.4 Lazy loading 的失败模式
传统 fully unpack 的 OCI image:
容器启动成功
-> 大多数 image data 已经在本地
Nydus lazy pulling:
容器启动成功
-> 只能说明 metadata/必要数据够了
-> 未来读冷文件时可能还要访问远端
所以网络、registry、P2P backend、blobcache 命中率、prefetch 策略都会影响运行时读延迟和可用性。prefetch 是 lazy fetch 方案中缓解运行后 fetch 失败影响的重要机制。
9. gVisor / runsc 的文件系统路径和普通 runc 有什么不同
普通 runc:
application syscall
|
v
host Linux kernel syscall entry
|
v
host Linux VFS
|
v
overlayfs / fuse / ext4 / xfs / page cache
gVisor / runsc:
application syscall
|
v
gVisor Sentry intercepts syscall
|
v
Sentry's Go-based kernel/VFS implementation
|
+-- gofer/LISAFS path
|
+-- directfs path
|
v
host Linux VFS, but called by Sentry/gofer, not directly by app
gVisor 的 Sentry 需要在 Go 中重新实现 Linux;它包含 syscall interface、memory management、filesystems、network stack、process management、namespaces 等,并且不会把 sandboxed workload 的系统调用原样 passthrough 给 host。
9.1 Gofer 模式
传统 gVisor filesystem 访问:
container app
|
| read("/etc/os-release")
v
Sentry
|
| LISAFS RPC
v
Gofer process
|
| openat/read on host
v
host VFS
|
v
overlayfs / nydus / ext4 / page cache
gVisor 通过一个叫 Gofer 的 file proxy 访问 filesystem;gofer 是独立进程,并通过 LISAFS 和对应 sentry 通信。
这意味着你在宿主机上观察时:
strace 容器应用本身
通常不是普通 runc 那种路径
strace gofer/sentry
才能看到实际 host openat/read/fstatat 等 syscall
9.2 Directfs 模式
gVisor 后来引入 directfs。directfs 让 Sentry 安全地直接访问 container filesystem,避免到 gofer 的昂贵 round trip。
Directfs 大致是:
Gofer
|
+-- 设置安全的 mount namespace / bind mounts
+-- 把 mount point 的 fd 通过 SCM_RIGHTS 给 Sentry
Sentry
|
+-- 使用 openat/fstatat/mkdirat 等 fd-relative syscall
+-- 访问 host VFS
图:
container app syscall
|
v
Sentry VFS
|
| openat(dirfd_from_gofer, "etc/os-release", O_NOFOLLOW...)
v
host Linux VFS
|
v
overlayfs / fuse / ext4 / page cache
这仍然不同于 runc,因为:
runc:
app syscall 直接进入 host kernel VFS
gVisor directfs:
app syscall 先由 Sentry 实现语义
Sentry 再选择性调用 host filesystem syscalls
9.3 gVisor 自己的 VFS 对象不等于 Linux VFS 对象
gVisor 的 VFS2 中,Dentry 类似 Linux struct dentry,但它不把 Dentry 和 inode 强绑定,因为 gVisor 主要和通过 filesystem API 访问的文件系统交互,很多 API 只支持 path/fd 而不支持 inode。
所以在 gVisor 下要区分两套对象:
guest-visible VFS objects
in Sentry, Go objects
host Linux VFS objects
in host kernel, accessed by Sentry/gofer
9.4 gVisor rootfs overlay 的特殊性
gVisor 对 rootfs 还有 sandbox-internal overlay 优化。Docker / Kubernetes 的 rootfs 通常由 overlayfs 组成,lower 是 image layer,upper 是 container layer;gVisor 为减少 gofer RPC 和 host syscall 开销,可以把 writable upper 放到 sandbox 内部 tmpfs / filestore 之类结构中。
所以普通 runc 下你可能看到:
upperdir=/var/lib/containerd/.../snapshots/<active>/fs
但 gVisor 某些配置下,容器写入 rootfs 的路径不一定像普通 runc 一样直接表现为 host upperdir 中一个普通文件树。观察时要看 runsc 配置和是否启用 rootfs overlay / directfs。
10. 用命令观察这些对象
下面假设你有一个容器主进程宿主机 PID:
PID=12345 # 换成测试容器 init 进程所在的宿主机 PID
Docker 可用:
PID=$(docker inspect -f '{{.State.Pid}}' <container>)
containerd / Kubernetes 场景可用 crictl inspect、ctr task ls、nerdctl inspect 找 PID。
下面的命令面向自己创建的测试容器。进入命名空间前,确认 PID 属于该容器。执行观察命令时需要有相应工具可用。
10.1 看容器的 namespace
sudo lsns -p "$PID" -o NS,TYPE,NPROCS,PID,COMMAND,PATH
lsns 会列出当前可访问的 namespaces;它的 namespace identifier 是 inode number。
也可以直接看:
readlink /proc/$PID/ns/mnt
readlink /proc/$PID/ns/pid
readlink /proc/$PID/ns/net
readlink /proc/self/ns/mnt
典型输出:
/proc/12345/ns/mnt -> mnt:[4026532801]
/proc/self/ns/mnt -> mnt:[4026531841]
不同 inode number 说明在不同 mount namespace。
10.2 看容器根目录
sudo ls -l /proc/$PID/root
sudo readlink /proc/$PID/root
sudo ls /proc/$PID/root/etc
/proc/$PID/root 是从宿主机进入该进程 root 的入口。你可以验证:
sudo cat /proc/$PID/root/etc/os-release
这等价于“从该进程的 root 看 /etc/os-release”,但读操作仍由宿主机进程发起,权限和 LSM 规则可能有差异。
10.3 看 mountinfo
sudo cat /proc/$PID/mountinfo
/proc/<pid>/mountinfo 包含该进程 mount namespace 中的 mounts 信息,包括 mount ID、parent ID、major:minor、mount root、mount point、mount options、filesystem type、source、super options 等。
过滤 overlay / fuse / erofs / proc / tmpfs:
sudo grep -E ' - (overlay|fuse|fuse\..*|erofs|proc|tmpfs) ' /proc/$PID/mountinfo
典型 overlay 行:
402 399 0:87 / / rw,relatime - overlay overlay rw,lowerdir=/var/lib/containerd/io.containerd.snapshotter.v1.overlayfs/snapshots/11/fs:/var/lib/containerd/io.containerd.snapshotter.v1.overlayfs/snapshots/10/fs,upperdir=/var/lib/containerd/io.containerd.snapshotter.v1.overlayfs/snapshots/42/fs,workdir=/var/lib/containerd/io.containerd.snapshotter.v1.overlayfs/snapshots/42/work
解释:
402 mount ID
399 parent mount ID
0:87 st_dev major:minor
/ root within filesystem
/ mount point inside this process root
rw,... per-mount options
- separator
overlay filesystem type
overlay source
rw,lowerdir=...,upperdir=...,workdir=... super options
把 mountinfo 变成树:
sudo nsenter -t "$PID" -m -- findmnt -R /
查看某个路径落在哪个 mount 上:
sudo nsenter -t "$PID" -m -- findmnt -T /etc/os-release -o TARGET,SOURCE,FSTYPE,OPTIONS
sudo nsenter -t "$PID" -m -- findmnt -T /proc -o TARGET,SOURCE,FSTYPE,OPTIONS
sudo nsenter -t "$PID" -m -- findmnt -T /dev/shm -o TARGET,SOURCE,FSTYPE,OPTIONS
10.4 看 fd -> file -> mount
先在容器中制造一个长期持有 fd 的进程。例如:
docker exec -d <container> sh -c 'exec 3</etc/os-release; sleep 100000'
找到这个 sleep 或 shell 的宿主机 PID 后:
HPID=12346 # 换成被观察进程的宿主机 PID
sudo ls -l /proc/$HPID/fd
/proc/<pid>/fd/ 每个条目对应进程打开的一个 fd,并且是指向实际文件的 symbolic link。
示例:
0 -> /dev/null
1 -> pipe:[1234567]
2 -> pipe:[1234568]
3 -> /etc/os-release
看 fdinfo:
sudo cat /proc/$HPID/fdinfo/3
可能看到:
pos: 0
flags: 0100000
mnt_id: 402
ino: 123456
把 mnt_id 映射回 mountinfo:
MNT=$(sudo awk '/^mnt_id:/ {print $2}' /proc/$HPID/fdinfo/3)
sudo awk -v id="$MNT" '$1 == id {print}' /proc/$HPID/mountinfo
这条链很有价值:
/proc/$pid/fd/3
-> 这个进程 fd table 的 fd 3
-> struct file
-> fdinfo shows mnt_id
-> mountinfo mount ID
-> filesystem type / mount options / lowerdir / upperdir
10.5 用 stat 看 inode / dev / filesystem
容器视角:
sudo nsenter -t "$PID" -m -- \
stat -Lc 'path=%n type=%F dev=%D ino=%i size=%s mode=%A mount=%m' /etc/os-release
看 filesystem 级别:
sudo nsenter -t "$PID" -m -- \
stat -f -c 'path=/ fs_type=%T block_size=%S total_blocks=%b free_blocks=%f' /
对比 host lowerdir:
sudo find /var/lib/containerd/io.containerd.snapshotter.v1.overlayfs/snapshots \
-path '*/fs/etc/os-release' \
-exec stat -Lc 'host_path=%n dev=%D ino=%i size=%s' {} \;
注意 OverlayFS 场景下:
container stat /etc/os-release
看到的是 overlay view 的 st_dev/st_ino
host stat lowerdir/.../etc/os-release
看到的是 lower filesystem 的真实 st_dev/st_ino
二者可能不同。
因此用 stat 观察 OverlayFS 时,不要把 container view 的 inode number 简单等同于 lowerdir inode number。
10.6 用 strace 看 syscall 路径
直接在容器 mount namespace 中跑:
sudo nsenter -t "$PID" -m -u -i -n -p -- \
strace -f -yy \
-e trace=openat,openat2,newfstatat,statx,read,pread64,mmap,close \
cat /etc/os-release >/dev/null
你会看到类似:
openat(AT_FDCWD, "/etc/os-release", O_RDONLY) = 3</etc/os-release>
newfstatat(3</etc/os-release>, "", {...}, AT_EMPTY_PATH) = 0
read(3</etc/os-release>, "NAME=\"Alpine Linux\"\nID=alpine\n...", 131072) = 123
close(3</etc/os-release>) = 0
观察动态链接器和 mmap:
sudo nsenter -t "$PID" -m -u -i -n -p -- \
strace -f -yy \
-e trace=openat,newfstatat,mmap,mprotect,read,close,execve \
/bin/sh -c 'true'
你会看到 loader 打开 shared libraries,并用 mmap 映射它们:
openat(AT_FDCWD, "/lib/ld-musl-x86_64.so.1", O_RDONLY|O_CLOEXEC) = 3
mmap(NULL, ..., PROT_READ|PROT_EXEC, MAP_PRIVATE, 3, 0) = ...
这说明:
程序启动不只是读你的业务文件。
动态链接器、共享库、locale、配置文件都在走 VFS + page cache。
10.7 观察 OverlayFS copy-up
先找 upperdir:
UPPER=$(sudo awk '
/ - overlay / {
n=split($0, parts, "upperdir=");
if (n > 1) {
split(parts[2], a, ",");
print a[1];
exit;
}
}' /proc/$PID/mountinfo)
echo "$UPPER"
在容器内创建新文件:
sudo nsenter -t "$PID" -m -u -i -n -p -- \
sh -c 'echo hello > /tmp/vfs-demo-new-file'
宿主机看 upperdir:
sudo ls -l "$UPPER/tmp/vfs-demo-new-file"
sudo stat "$UPPER/tmp/vfs-demo-new-file"
修改 lower 已存在文件,触发 copy-up:
sudo nsenter -t "$PID" -m -u -i -n -p -- \
sh -c 'echo "# changed" >> /etc/os-release'
再看 upperdir:
sudo find "$UPPER" -path '*/etc/os-release' -ls
删除 lower 文件,观察 whiteout:
sudo nsenter -t "$PID" -m -u -i -n -p -- \
sh -c 'rm -f /tmp/some-lower-file'
sudo find "$UPPER" -name '.wh.*' -ls
在很多发行版和内核配置下,whiteout 可能表现为 character device 0/0,也可能用 trusted.overlay.whiteout xattr 形式表示。
10.8 观察 Page Cache
strace 能告诉你发生了 read(),但不能告诉你这次 read() 是 page cache hit 还是真的访问了块设备或远端后端。
实验环境中可以粗略演示:
# 仅在专用测试虚拟机中操作,drop_caches 会影响整台机器
sync
echo 3 | sudo tee /proc/sys/vm/drop_caches
sudo nsenter -t "$PID" -m -- \
sh -c 'time cat /usr/bin/some-large-binary >/dev/null'
sudo nsenter -t "$PID" -m -- \
sh -c 'time cat /usr/bin/some-large-binary >/dev/null'
通常第二次更快,因为命中 page cache。但这只是间接观察。更精确的工具通常是:
fincore <file> # util-linux,有些系统自带
vmtouch <file> # 额外工具
mincore(2) # 自己写小程序
perf/bpftrace # 观察 filemap/block tracepoints
10.9 观察 Nydus / FUSE / remote snapshotter
找 mount:
sudo grep -Ei 'nydus|fuse|erofs|overlay' /proc/$PID/mountinfo
sudo nsenter -t "$PID" -m -- findmnt -R / -o TARGET,SOURCE,FSTYPE,OPTIONS
找 nydusd:
ps -ef | grep -E 'nydusd|containerd-nydus'
读一个冷文件:
sudo nsenter -t "$PID" -m -- \
strace -f -yy -e trace=openat,read,pread64,mmap,close \
cat /usr/lib/some-cold-file >/dev/null
同时观察 nydusd 的 host syscall:
NYDUS_PID=$(pgrep -n nydusd)
sudo strace -ff -p "$NYDUS_PID" \
-e trace=openat,read,pread64,pwrite64,recvfrom,sendto,connect \
-s 128
你要建立的链路是:
container read file
|
v
overlayfs lower
|
v
fuse/erofs/nydus mount
|
v
nydusd or fscache backend
|
v
blobcache / registry / P2P backend
10.10 观察 gVisor / runsc
先找 runsc / sentry / gofer:
ps -ef | grep -E 'runsc|sentry|gofer'
普通 runc 下你 strace 容器进程,能看到应用自己的 syscall:
sudo strace -p <app-host-pid> -e trace=openat,read,newfstatat
gVisor 下,你更可能需要观察 Sentry / Gofer:
sudo strace -ff -p <sentry-pid> \
-e trace=openat,openat2,newfstatat,read,pread64,mmap,close
sudo strace -ff -p <gofer-pid> \
-e trace=openat,openat2,newfstatat,read,pread64,mmap,close
差异总结:
runc:
app syscall == host syscall
app fd == host kernel struct file
app mmap == host kernel VM + page cache
gVisor:
app syscall == Sentry 处理的 guest syscall
host syscall 由 Sentry/Gofer 代表 app 发起
app-visible fd/file/dentry 是 Sentry 内部对象
host VFS 只看到 Sentry/Gofer 的访问
11. 把完整链路串起来
11.1 runc + OverlayFS 读文件
container app:
fd = open("/etc/os-release", O_RDONLY)
路径解析:
current->fs->root
= { overlay vfsmount, overlay root dentry }
lookup "etc"
-> overlay dentry for /etc
-> may represent merged upper/lower directory
lookup "os-release"
-> overlay dentry
-> real lower dentry, if not copied up
打开:
alloc struct file
file->f_path = { overlay mnt, overlay dentry("/etc/os-release") }
file->f_op = overlayfs file ops or wrapped real file ops
fd_install(fd, file)
读:
read(fd)
|
v
fdtable[fd] -> struct file
|
v
overlayfs read path
|
v
real lower file
|
v
lower inode->i_mapping page cache
|
+-- hit -> copy_to_user
|
+-- miss -> lower filesystem read_folio/readahead
|
v
ext4/xfs maps blocks
|
v
block layer
|
v
disk
11.2 runc + OverlayFS 写 lower 文件
write(fd)
|
v
overlayfs sees lower-only file
|
v
copy_up lower -> upperdir
|
v
switch data source to upper
|
v
write upper inode page cache
|
v
dirty pages
|
v
writeback -> host fs -> block device
11.3 runc + Nydus lower 读冷文件
read("/usr/lib/libfoo.so")
|
v
overlayfs
|
v
lower nydus filesystem
|
v
FUSE/EROFS
|
v
metadata already local: lookup succeeds
|
v
data chunk missing: fetch on demand
|
v
verify/decompress
|
v
fill kernel page cache
|
v
return to app
11.4 gVisor + Nydus / OverlayFS
app read("/usr/lib/libfoo.so")
|
v
Sentry syscall handler
|
v
Sentry VFS
|
+-- gofer RPC path
| |
| v
| gofer host open/read
|
+-- directfs path
|
v
Sentry host openat/read using safe dirfds
|
v
host Linux VFS
|
v
overlayfs / nydus / fuse / erofs / page cache
所以你的最终心智模型可以压缩成一句话:
容器进程读一个文件,本质是:
fd 找到 struct file;
struct file 找到 {mount, dentry};
dentry 找到 inode;
inode 找到 address_space/page cache;
cache miss 时由具体 filesystem 把 file offset 解析到底层数据来源;
这个底层来源可能是 ext4/xfs 块设备、OverlayFS upper/lower、Nydus FUSE/EROFS 远端 chunk,或者 gVisor 的 Sentry/Gofer 间接访问路径。
12. 建议反复练习的一条观测链
最值得反复练习的一条观测链是:
# 1. 找容器进程 PID
PID=$(docker inspect -f '{{.State.Pid}}' <container>)
# 2. 看 mount namespace
readlink /proc/$PID/ns/mnt
# 3. 看 rootfs mount
sudo grep ' - overlay ' /proc/$PID/mountinfo
# 4. 在容器中打开一个文件并保持 fd
docker exec -d <container> sh -c 'exec 3</etc/os-release; sleep 100000'
# 5. 找持有 fd 的进程,查看 fd
sudo ls -l /proc/$HPID/fd
sudo cat /proc/$HPID/fdinfo/3
# 6. fdinfo mnt_id -> mountinfo
MNT=$(sudo awk '/^mnt_id:/ {print $2}' /proc/$HPID/fdinfo/3)
sudo awk -v id="$MNT" '$1 == id {print}' /proc/$HPID/mountinfo
# 7. stat 看 dev/inode
sudo nsenter -t "$PID" -m -- stat -Lc 'dev=%D ino=%i type=%F path=%n' /etc/os-release
# 8. strace 看 open/read/mmap
sudo nsenter -t "$PID" -m -u -i -n -p -- \
strace -f -yy -e trace=openat,newfstatat,read,mmap,close \
cat /etc/os-release >/dev/null
这条链跑熟之后,VFS、OverlayFS、Nydus lazy loading、gVisor 文件系统路径就不再是抽象名词,而是可以从 /proc、mountinfo、fdinfo、stat、strace 里一层层对上的真实对象。
Sources
- Linux Kernel Documentation: Virtual Filesystem
v6.18 - Linux Kernel Documentation: Filesystem API Summary / address_space
v5.19 - Linux Kernel Documentation: iomap operations / Buffered I/O
v6.14 - Linux Kernel Documentation: OverlayFS
v6.15 - Linux Kernel Documentation: FUSE I/O modes
v6.9 - Linux Kernel Documentation: DAX
- Linux Kernel Documentation: blk-mq
- man7.org: open(2)
- man7.org: mmap(2)
- man7.org: proc_pid_fd(5)
- man7.org: proc_pid_mountinfo(5)
- man7.org: lsns(8)
- man7.org: findmnt(8)
- man7.org: stat(1)
- containerd snapshotters README
2.2 - containerd documentation
1.7 - OCI Runtime Spec: config.md
v1.3.0 - OCI Runtime Spec: bundle.md
v1.3.0 - OCI Runtime Spec: config-linux.md
v1.3.0 - containerd/nydus-snapshotter
- Dragonfly Nydus design
- gVisor architecture guide
- gVisor filesystem guide
- gVisor directfs blog
- gVisor VFS package documentation
- Google Open Source Blog: gVisor root filesystem overlay