您现在可以暂停沙箱并且在后续需要时恢复该沙箱,恢复后,沙箱的文件系统和内存状态,包括正在运行的进程、已加载的变量、数据等都将被恢复。在沙箱暂停期间,我们不会对沙箱的运行时间计费。
请注意:
  • 暂停沙箱所需的时间和沙箱的 RAM(内存)大小有关,每 1 GB RAM 需要约 4 秒;
  • 恢复沙箱需要约 1 秒;
  • 沙箱最多可以暂停 30 天。30 天后,数据将被删除,您将无法恢复沙箱。尝试恢复已删除或不存在的沙箱将导致 NotFoundError 错误(JavaScript SDK)或 NotFoundException 异常(Python SDK)。

暂停沙箱

当您暂停沙箱时,沙箱的文件系统和内存状态都将被保存。包括沙箱文件系统中的所有文件以及所有正在运行的进程、已加载的变量、数据等。
import { Sandbox } from 'ppio-sandbox/code-interpreter'
// or import { Sandbox } from 'ppio-sandbox'
// or import { Sandbox } from 'ppio-sandbox/desktop'

const sandbox = await Sandbox.create()
console.log('Sandbox created', sandbox.sandboxId)

// 暂停沙箱
// 建议您将沙箱 ID 保存到数据库中,以便稍后恢复沙箱。
const result = await sandbox.betaPause()
console.log('Sandbox paused', sandbox.sandboxId, result)

await sandbox.kill()

恢复沙箱

当您恢复沙箱时,沙箱在暂停前文件系统中的所有文件、所有正在运行的进程、已加载的变量、数据等将被恢复。
import { Sandbox } from 'ppio-sandbox/code-interpreter'
// or import { Sandbox } from 'ppio-sandbox'
// or import { Sandbox } from 'ppio-sandbox/desktop'

const sandbox = await Sandbox.create()
console.log('Sandbox created', sandbox.sandboxId)

// 暂停沙箱
// 建议您将沙箱 ID 保存到数据库中,以便稍后恢复沙箱。
const result = await sandbox.betaPause()
console.log('Sandbox paused', sandbox.sandboxId, result)

// 恢复沙箱
const resumedSandbox = await sandbox.connect()
console.log('Sandbox resumed', resumedSandbox.sandboxId)

await sandbox.kill()

恢复时指定超时时间

当您恢复沙箱时,沙箱的 timeout 会重置为默认的 5 分钟。您可以参考如下方法来自定义 timeout 值。
import { Sandbox } from 'ppio-sandbox/code-interpreter'
// or import { Sandbox } from 'ppio-sandbox'
// or import { Sandbox } from 'ppio-sandbox/desktop'

const sandbox = await Sandbox.create()

const connectedSandbox = await Sandbox.connect(sandbox.sandboxId, { timeoutMs: 60 * 1000 }) // 60 秒
console.log('Sandbox connected', connectedSandbox.sandboxId)

await sandbox.kill()

列出暂停的沙箱

您可以参考如下方式列出所有被暂停的沙箱。详情请参考 沙箱列表
import { Sandbox, SandboxInfo } from 'ppio-sandbox/code-interpreter'
// or import { Sandbox, SandboxInfo } from 'ppio-sandbox'
// or import { Sandbox, SandboxInfo } from 'ppio-sandbox/desktop'

const sandbox = await Sandbox.create()

// 过滤出所有被暂停的沙箱
const paginator = Sandbox.list({ query: { state: ['paused'] } })

// 分页获取所有被暂停的沙箱
const sandboxes: SandboxInfo[] = []
while (paginator.hasNext) {
  const items = await paginator.nextItems()
  sandboxes.push(...items)
}

console.log('all paused sandboxes', sandboxes)

await sandbox.kill()

删除暂停的沙箱

您可以通过在沙箱实例上调用 kill 方法来删除暂停的沙箱。
import { Sandbox } from 'ppio-sandbox/code-interpreter'
// or import { Sandbox } from 'ppio-sandbox'
// or import { Sandbox } from 'ppio-sandbox/desktop'

const sandbox = await Sandbox.create()
console.log('Sandbox created', sandbox.sandboxId)

// 暂停沙箱
await sandbox.betaPause()

// 删除被暂停的沙箱
await sandbox.kill()

// 或者通过指定沙箱 ID 来删除被暂停的沙箱
// await Sandbox.kill(sandboxId)

网络连接

当您在沙箱内运行了服务并且暂停沙箱后,该服务将无法再从外部访问,所有客户端都将断开连接。在您恢复沙箱后,该服务可被再次访问,但您需要重新连接客户端。