沙箱生命周期
创建、连接、列举沙箱,暂停与恢复,设置超时与保活,以及超时回收策略。
一个沙箱从创建到回收会经历若干状态:running(运行中)、paused(已暂停)、closed(已关闭)。本页介绍如何管理整个生命周期。
创建沙箱
第一个参数是模板(默认 'default')。创建选项包括超时、注入环境变量、自定义元数据、生命周期策略等。
import { Sandbox } from 'tensor-box';
const sandbox = await Sandbox.create('default', {
domain: 'https://app.tos.run', // 也可由 TENSOR_BOX_DOMAIN 提供
timeoutMs: 60_000, // 无活动多久后触发回收
envs: { API_TOKEN: 'xxx' }, // 注入到沙箱的环境变量
metadata: { userId: '123' }, // 自定义元数据(可用于后续过滤)
lifecycle: { onTimeout: 'pause', autoResume: true },
});from tensor_box import Sandbox, LifecycleConfig
sandbox = Sandbox.create(
"default",
domain="https://app.tos.run", # 也可由 TENSOR_BOX_DOMAIN 提供
timeout_ms=60_000, # 无活动多久后触发回收
envs={"API_TOKEN": "xxx"}, # 注入到沙箱的环境变量
metadata={"userId": "123"}, # 自定义元数据(可用于后续过滤)
lifecycle=LifecycleConfig(on_timeout="pause", auto_resume=True),
)autoResume := true
sandbox, err := tensorbox.Create(ctx, "default", &tensorbox.CreateOptions{
Options: tensorbox.Options{Domain: "https://app.tos.run"}, // 也可由 TENSOR_BOX_DOMAIN 提供
Timeout: 60 * time.Second, // 无活动多久后触发回收
Envs: map[string]string{"API_TOKEN": "xxx"}, // 注入到沙箱的环境变量
Metadata: map[string]string{"userId": "123"}, // 自定义元数据
Lifecycle: &tensorbox.LifecycleConfig{
OnTimeout: "pause",
AutoResume: &autoResume,
},
})tensor-box sandbox create default \
--domain https://app.tos.run \
--timeout-ms 60000 \
--env API_TOKEN=xxx \
--metadata userId=123 \
--json每个沙箱拥有独立的资源配额,默认 2 vCPU / 2048 MiB 内存 / 40 GiB 磁盘。如需更大的规格,可通过自定义模板指定 cpuCount / memoryMB / diskGB。
连接到已有沙箱
用沙箱 ID 重新连接一个已存在的沙箱。如果沙箱处于暂停状态,会自动恢复:
const sandbox = await Sandbox.connect('sbx_abc123', {
domain: 'https://app.tos.run',
});
// 不杀掉沙箱地断开 SDK 连接(之后可再 connect 回来)
await sandbox.disconnect(); // 沙箱继续运行sandbox = Sandbox.connect("sbx_abc123", domain="https://app.tos.run")
# 不杀掉沙箱地断开 SDK 连接(之后可再 connect 回来)
sandbox.disconnect() # 沙箱继续运行sandbox, err := tensorbox.Connect(ctx, "sbx_abc123", &tensorbox.ConnectOptions{
Options: tensorbox.Options{Domain: "https://app.tos.run"},
})
// 不杀掉沙箱地断开 SDK 连接
sandbox.Disconnect() // 沙箱继续运行# connect 子命令展示沙箱信息(暂停的会自动恢复,别名 info)
tensor-box sandbox connect sbx_abc123列举沙箱
// 所有运行中的沙箱
const all = await Sandbox.list({ domain });
// 按状态过滤
const paused = await Sandbox.list({ domain, query: { state: ['paused'] } });
// 按元数据过滤
const mine = await Sandbox.list({ domain, query: { metadata: { userId: '123' } } });# 所有运行中的沙箱
all_sbx = Sandbox.list()
# 按状态 / 元数据过滤
paused = Sandbox.list(state=["paused"])
mine = Sandbox.list(metadata={"userId": "123"})// 按状态 / 元数据过滤
infos, _ := tensorbox.List(ctx, &tensorbox.ListOptions{
State: []string{"running", "paused"},
Metadata: map[string]string{"userId": "123"},
})tensor-box sandbox list --state running --state paused --metadata userId=123返回 SandboxInfo[],每项包含 sandboxId、templateId、state、startedAt、endAt、cpuCount、memoryMB、metadata 等。
暂停与恢复
暂停会把沙箱的内存与磁盘状态快照化,之后可在任意节点恢复,秒级回到原状态。
// 暂停(状态变为 paused,停止计费 vCPU)
await sandbox.pause();
// 恢复(可选地重设超时)
await sandbox.resume(120_000);sandbox.pause()
sandbox.resume(120_000) # 可选地重设超时(毫秒)sandbox.Pause(ctx)
sandbox.Resume(ctx, 120*time.Second) // 可选地重设超时暂停 / 恢复用于让会话"挂起"以释放计算资源、稍后无缝继续。底层依赖快照机制,详见快照与模板。
超时与回收
每个沙箱都有一个无活动超时。超时后如何处理由创建时的生命周期策略决定:
onTimeout: 'kill'— 超时直接销毁沙箱,状态变为closed。onTimeout: 'pause'— 超时暂停沙箱(保留状态),配合autoResume: true,下次访问会自动唤醒。
主动调整生命周期
// 重设无活动超时(毫秒)
await sandbox.setTimeout(120_000);
// 延长存活时间(保活)
await sandbox.keepAlive(300_000);
// 查询是否仍在运行
const running = await sandbox.isRunning();sandbox.set_timeout(120_000) # 重设无活动超时(毫秒)
sandbox.keep_alive(300_000) # 延长存活时间(保活)
running = sandbox.is_running()sandbox.SetTimeout(ctx, 120*time.Second) // 重设无活动超时
sandbox.KeepAlive(ctx, 300*time.Second) // 延长存活时间(保活)
running := sandbox.IsRunning(ctx)销毁沙箱
await sandbox.kill(); // 销毁,状态变为 closedsandbox.kill() # 销毁,状态变为 closedsandbox.Kill(ctx) // 销毁,状态变为 closedtensor-box sandbox kill "$sbx" # 也可一次传多个 ID用完务必销毁,避免沙箱占用配额。如果只是想稍后继续,用 pause() 而非 kill()——暂停会保留内存与磁盘状态。
查询信息、指标与日志
const info = await sandbox.getInfo(); // SandboxInfo
const metrics = await sandbox.getMetrics(); // SandboxMetrics[](CPU / 内存 / 磁盘)
const logs = await sandbox.getLogs(); // SandboxLogEntry[]info = sandbox.get_info() # SandboxInfo
metrics = sandbox.get_metrics() # [SandboxMetrics]
logs = sandbox.get_logs() # [SandboxLogEntry]info, _ := sandbox.GetInfo(ctx) // Info
metrics, _ := sandbox.GetMetrics(ctx) // []Metric
logs, _ := sandbox.GetLogs(ctx) // []LogEntrytensor-box sandbox connect "$sbx" # 信息
tensor-box sandbox metrics "$sbx" # CPU / 内存 / 磁盘
tensor-box sandbox logs "$sbx" # 日志SandboxMetrics 包含 timestamp、cpuCount、cpuUsedPct、memUsed、memTotal、diskUsed、diskTotal。控制台「监控」标签页正是基于这些指标绘制实时折线图。
方法一览
| 方法(TS / Python / Go) | 说明 |
|---|---|
Sandbox.create / Sandbox.create / Create | 创建沙箱 |
Sandbox.connect / Sandbox.connect / Connect | 连接到已有沙箱(暂停的自动恢复) |
Sandbox.list / Sandbox.list / List | 列举沙箱,可按 state / metadata 过滤 |
pause·resume / pause·resume / Pause·Resume | 暂停 / 恢复 |
kill / kill / Kill | 销毁 |
disconnect / disconnect / Disconnect | 断开 SDK 但保持沙箱运行 |
setTimeout·keepAlive / set_timeout·keep_alive / SetTimeout·KeepAlive | 重设超时 / 保活 |
isRunning / is_running / IsRunning | 是否运行中 |
getInfo·getMetrics·getLogs / get_info·get_metrics·get_logs / GetInfo·GetMetrics·GetLogs | 信息 / 指标 / 日志 |
以上实例方法大多也有对应的静态版本(如 TS Sandbox.kill(id, opts)、Python 同名静态调用、Go 后缀 ByID 的包级函数 KillByID / GetInfoByID / SetTimeoutByID 等),便于在不持有实例时按 ID 操作。