Skip to content

代码沙箱快速入门 源码级讲解

源码路径:CubeSandbox/examples/code-sandbox-quickstart/

概述

这是 CubeSandbox 最基础、最核心的案例:创建沙箱 → 运行代码 → 销毁。看起来简单,但它串联了完整的控制面和数据面链路,是理解整个系统的起点。

全局架构

源码解析:create.py — 创建沙箱

python
with Sandbox.create(template=template_id) as sandbox:
    info = sandbox.get_info()
    print("sandbox info %s" % info)

Sandbox.create() 内部调用链

关键数据流:控制面 vs 数据面

说明链路
控制面生命周期管理(创建/销毁)SDK → CubeAPI → CubeMaster → Cubelet
数据面代码执行与数据交互SDK → CubeProxy → envd

源码解析:exec_code.py — 运行代码

python
with Sandbox.create(template=template_id) as sandbox:
    print(sandbox.run_code(python_code, on_stdout=lambda data: print(data)))

run_code() 执行流程

envd:沙箱里的"执行引擎"

envd 是运行在 VM 内部的 gRPC 服务,由 cube-agent 拉起。它负责:

能力说明
run_code在 Python 环境中执行代码
commands.run执行任意 Shell 命令
files.read/write读写沙箱内文件
/healthreadiness probe

源码解析:cmd.py — Shell 命令执行

python
sandbox.commands.run("ls -la")

run_code 的区别:

方法执行环境适用场景
run_code()Python 环境数据分析、科学计算
commands.run()Shell 环境系统命令、脚本执行

with 语句的隐含生命周期

python
with Sandbox.create(template=template_id) as sandbox:
    # 沙箱运行中
    pass
# 离开 with 块 → 自动调用 sandbox.kill()

阅读建议

  1. 先读 create.py — 理解控制面完整链路
  2. 再读 exec_code.py — 理解数据面代码执行
  3. 最后读 cmd.py — 理解 Shell 命令与文件操作

源码参考:create.py | exec_code.py | cmd.py