Skip to content

Host 挂载 源码级讲解

源码路径:CubeSandbox/examples/host-mount/

概述

Host Mount 是 CubeSandbox 对 E2B API 的扩展能力:在创建沙箱时,把宿主机(Cubelet 节点)上的目录直接挂载到 VM 内部。

为什么需要它? 大数据集、模型权重、代码仓库不适合打包进镜像,也不适合每次都上传。Host Mount 提供零拷贝的本地挂载。

架构图

源码解析:create_with_mount.py

python
with Sandbox.create(
    template=template_id,
    metadata={
        "host-mount": json.dumps([
            {
                "hostPath":  "/tmp/rw",   # 宿主机路径
                "mountPath": "/mnt/rw",   # VM 内路径
                "readOnly":  False,       # 读写
            },
            {
                "hostPath":  "/tmp/ro",
                "mountPath": "/mnt/ro",
                "readOnly":  True,        # 只读
            },
        ])
    },
) as sandbox:
    result = sandbox.commands.run("ls /mnt/rw /mnt/ro")

metadata 扩展机制

Cubelet 侧挂载实现(概念)

python
# Cubelet 内部逻辑(概念伪代码)
mounts = json.loads(sandbox.metadata["host-mount"])
for mount in mounts:
    # 1. 校验 hostPath 存在
    assert os.path.exists(mount["hostPath"])

    # 2. 配置 Hypervisor 挂载
    #    通过 virtio-fs 或 9pfs 将宿主机目录暴露给 VM
    vm.add_virtio_fs_export(
        host_path=mount["hostPath"],
        guest_path=mount["mountPath"],
        readonly=mount["readOnly"],
    )

挂载类型与安全边界

挂载类型安全性适用场景
只读 (readOnly: true)高:VM 无法修改宿主机文件模型权重、配置文件、数据集
读写 (readOnly: false)低:VM 可写宿主机目录代码 workspace、输出目录

重要约束

约束说明
hostPath 必须存在在 Cubelet 节点上创建前必须存在
hostPath 是宿主机路径不是脚本运行机器的路径
不支持远程挂载只能挂载 Cubelet 本地文件系统
生命周期绑定沙箱销毁后挂载消失(但宿主机文件保留)

推荐阅读

  1. create_with_mount.py — metadata 构造与 SDK 调用
  2. env_utils.py — 环境变量加载
  3. README.md — mount descriptor schema

源码参考:create_with_mount.py