更新时间:2026-11-19
分享

存储管理

AgentSphere沙箱实例支持通过挂载OBS或SFS Turbo来实现持久化存储,在沙箱生命周期结束后业务数据可保留并支持跨沙箱复用访问。

前提条件

沙箱中挂载OBS对象存储

Python SDK代码示例

#!/usr/bin/env python3
"""(e2b==2.42.0, e2b-code-interpreter==2.9.1)

用法:
    python allinone_sandbox_obs_mount.py

"""
import json
import sys
from e2b_code_interpreter import Sandbox
# ===========================================================================
# 配置区:按你的环境填写
# ===========================================================================
# --- e2b / AgentSphere 连接配置
E2B_BASE_URL = ""          # e2b API 网关地址(AgentSphere),不使用 SDK 默认地址则填写
E2B_API_KEY = ""           # API Key
E2B_SANDBOX_URL = ""       # 沙箱服务地址(可选)
TEMPLATE_ID = ""           # 模板 ID(必填)

# --- OBS 挂载配置 ---
OBS_BUCKET = ""        # OBS 桶名(必填;留空则该测试被跳过)
OBS_BUCKET_PATH = ""   # 桶内子路径(可选)
OBS_MOUNT_POINT = ""   # 容器内挂载点
OBS_READ_ONLY = False  # 是否只读
# ===========================================================================


# ---------------------------------------------------------------------------
# 存储挂载 metadata 构造
# ---------------------------------------------------------------------------
def _obs_mount(bucket_path: str, mount_dir: str, read_only: bool | None = None) -> dict:
    return {
        "bucket": OBS_BUCKET,
        "bucketPath": bucket_path,
        "mountDir": mount_dir,
        "readOnly": OBS_READ_ONLY if read_only is None else read_only,
    }
def _mount_metadata(obs_mounts: list[dict] | None = None) -> dict:
    metadata = {}
    if obs_mounts:
        metadata["agentsandbox.storage.obs"] = json.dumps(
            {"obsMounts": obs_mounts}, separators=(",", ":")
        )
    return metadata

def create_sandbox(metadata: dict | None = None, timeout: int = 60) -> Sandbox:
    if not TEMPLATE_ID:
        raise RuntimeError("template not set: TEMPLATE_ID")
    opts = {}
    if E2B_API_KEY:
        opts["api_key"] = E2B_API_KEY
    if E2B_BASE_URL:
        opts["api_url"] = E2B_BASE_URL
    if E2B_SANDBOX_URL:
        opts["sandbox_url"] = E2B_SANDBOX_URL
    if timeout > 0:
        opts["timeout"] = timeout
    if metadata:
        opts["metadata"] = metadata
    return Sandbox.create(template=TEMPLATE_ID, **opts)

def test_mount_obs_volume():
    if not OBS_BUCKET:
        print("\n=== Test: Mount OBS Volume [SKIPPED — no OBS_BUCKET configured] ===")
        return

    print("\n=== Test: Mount OBS Volume ===")
    metadata = _mount_metadata(
        obs_mounts=[_obs_mount(OBS_BUCKET_PATH, OBS_MOUNT_POINT)]
    )
    sb = create_sandbox(metadata=metadata)
    print(f"  [INFO] mount metadata: {metadata}")
    print(f"  [INFO] sandbox_id: {sb.sandbox_id}")
    try:
        # 只读校验
        if OBS_READ_ONLY:
            print("  [INFO] readOnly=true, skip write/read verification")
            return

        # 写读校验
        sandbox.files.write(f"{OBS_MOUNT_POINT}/test.txt", "hello from e2b obs mount test")
        content = sandbox.files.read(f"{OBS_MOUNT_POINT}/test.txt")
        print(content)  # 输出: hello from e2b obs mount test

    finally:
        sb.kill()
        print("  [INFO] sandbox killed")


if __name__ == "__main__":
    try:
        test_mount_obs_volume()
    except AssertionError as e:
        print(f"\n[FAIL] {e}")
        sys.exit(1)
    print("\n=== All tests passed ===")

相关文档