Python OpenSandbox SDK
Python OpenSandbox SDK의 이용 방법을 정리한다. API Reference의 나열보다는 Sandbox를 실제 서비스에서 이용할 때 반복되는 패턴을 중심으로 정리한다. 예제는 SDK의 기본 표면인 Async API를 기준으로 한다. 분석 기준 Version은 v1.2.1이다.
1. Lifecycle 및 연결 관리
SDK는 단독으로 동작하지 않으며, 모든 요청을 OpenSandbox Server의 REST API로 전달하는 Client로 동작한다. 따라서 SDK를 이용하려면 먼저 ConnectionConfig를 통해서 OpenSandbox Server의 주소와 API Key를 설정해야 한다. domain과 api_key를 생략하면 각각 OPEN_SANDBOX_DOMAIN과 OPEN_SANDBOX_API_KEY 환경변수를 읽기 때문에, API Key를 Code에 하드코딩하지 않고 주입할 수 있다.
Single-Tenant 구성에서는 Server 전체가 하나의 API Key를 공유하기 때문에 모든 호출자가 동일한 공간에 Sandbox를 생성한다. 반면 Multi-Tenant 구성에서는 Tenant마다 별도의 API Key가 발급되며, 이용하는 Key에 따라서 Sandbox가 생성되는 Namespace와 소유자가 분리되기 때문에 하나의 Server를 다수의 팀이나 서비스가 격리된 채 공유할 수 있다.
import asyncio
from datetime import timedelta
from opensandbox import Sandbox
from opensandbox.config import ConnectionConfig
config = ConnectionConfig(
domain="opensandbox.example.com", # OpenSandbox Server address
api_key="tenant-a-api-key", # Per-tenant API key
)
async def main():
sandbox = await Sandbox.create(
"python:3.11",
connection_config=config,
timeout=timedelta(minutes=30), # Default 10-minute TTL when omitted; None = no expiration
env={"APP_ENV": "dev"}, # Environment variables for the sandbox
resource={"cpu": "1", "memory": "512Mi"}, # CPU/memory limits for the sandbox
)
try:
execution = await sandbox.commands.run("python -V")
print(execution.logs.stdout[0].text) # e.g. Python 3.11.x
finally:
await sandbox.destroy() # kill() + close()
asyncio.run(main())[Code 1]은 Sandbox를 생성하고 Shell 명령을 실행한 후 종료하는 기본 Lifecycle을 나타내고 있다. 모든 Sandbox는 생성 시점에 수명(timeout)을 가지며, 생략하면 기본 10분 TTL이 적용되고 None을 명시하면 만료되지 않는다. 수명 외에도 env로 환경변수를, resource로 CPU/Memory 상한을 생성 시점에 지정할 수 있다. 종료 방식은 원격 Sandbox까지 함께 종료하는 destroy()와 Client 측 Session만 정리하는 close() 두 가지가 있으며, 구분해서 이용해야 한다. 여기서 Session은 Sandbox 객체가 Cluster에서 동작하는 원격 Sandbox와 별개로, Server 및 Sandbox와 통신하기 위해서 Client Process 안에 유지하는 HTTP Connection Pool을 의미한다.
destroy(): 원격 Sandbox를 종료(kill())한 후 Client 측 Session까지 함께 정리한다. Sandbox를 생성하고 사용한 후 바로 폐기하는 Workflow에 적합하다.close(): Client 측 Session만 닫을 뿐 원격 Sandbox에는 종료 요청이 전달되지 않는다. 따라서 Sandbox는 TTL이 만료될 때까지 Cluster에서 계속 동작하며 Resource를 점유한다.
# Create a sandbox and store its ID externally (e.g. DB) —
# reattachment usually happens later or in another process
sandbox = await Sandbox.create("python:3.11", connection_config=config)
sandbox_id = sandbox.id
# Close only the client-side session — the remote sandbox keeps running
await sandbox.close()
# Reattach to the running sandbox by sandboxId (not resume)
sandbox = await Sandbox.connect(sandbox_id, connection_config=config)
# Extend lifetime: resets expiration to (now + duration)
await sandbox.renew(timedelta(minutes=30))
info = await sandbox.get_info()
print(info.status.state, info.expires_at) # e.g. RUNNING 2026-11-29 12:30:00+00:00[Code 2]는 Client 측 Session만 닫은 후 동작 중인 Sandbox에 다시 접속하여 수명을 연장하는 과정을 나타내고 있다. close() 이후에도 원격 Sandbox는 계속 동작하기 때문에, sandboxId만 보관하고 있으면 동일 Process는 물론 분리된 다른 Process에서도 Sandbox.connect()로 다시 접속할 수 있다. Sandbox.connect()는 Resume이 아니라 실행 중인 Sandbox에 Attach하는 동작이며, renew()는 만료 시각을 현재 시각 기준으로 재설정한다.
from opensandbox.models.sandboxes import SandboxLifecycle, RenewalPolicy
sandbox = await Sandbox.create(
"python:3.11",
connection_config=config,
timeout=timedelta(hours=1),
lifecycle=SandboxLifecycle(
# Each observed access extends the expiration by 1 hour (now + 3600s)
renewal_policy=RenewalPolicy(extend_seconds=3600),
),
)[Code 3]은 Renew-on-Access를 선언하는 과정을 나타내고 있다. 매 요청마다 명시적으로 renew()를 호출하는 대신 생성 시점에 Renewal Policy를 선언하면, Gateway/Proxy가 관측한 접근마다 만료 시각이 자동으로 연장된다. Platform 운영자가 OpenSandbox Server 설정(config.toml)에 [renew_intent]를 활성화해둔 경우에만 동작한다.
2. Pool 이용
Sandbox 생성은 Pod Scheduling과 Image Pull 때문에 수 초가 소요된다. Pool은 Sandbox를 미리 준비해두어 이 생성 지연을 요청 경로에서 제거하며, SDK가 Client Level에서 자체 구현한 SDK Pool과 OpenSandbox Controller가 Pre-Warmed Pod를 유지하는 BatchSandbox Pool 두 가지 방식으로 이용할 수 있다.
2.1. SDK Pool 이용
from opensandbox.pool import (
AsyncSandboxPool,
InMemoryAsyncPoolStateStore,
PoolCreationSpec,
)
# Runs once per warmed-up sandbox before it enters the idle pool
async def prepare(sandbox):
await sandbox.commands.run("pip install requests pandas")
pool = AsyncSandboxPool(
pool_name="agent-pool",
max_idle=5, # Number of pre-created idle sandboxes
state_store=InMemoryAsyncPoolStateStore(), # Swap for the Redis store to share across clients
connection_config=config,
creation_spec=PoolCreationSpec(image="python:3.11"),
warmup_sandbox_preparer=prepare,
)
await pool.start() # Warm up idle sandboxes in the background
# Take a pre-created sandbox — no cold start on the request path
sandbox = await pool.acquire(sandbox_timeout=timedelta(minutes=30))[Code 4]는 SDK Pool로 미리 생성해둔 Sandbox를 꺼내 쓰는 과정을 나타내고 있다. SDK Pool은 max_idle 개수만큼 Sandbox를 미리 생성해두고 acquire() 시 즉시 반환한다. acquire()로 꺼낸 Sandbox의 소유권은 호출자에게 넘어오기 때문에, 이후에는 destroy(), close()를 포함하여 일반 Sandbox와 동일하게 이용하면 된다.
꺼내 쓴 만큼은 SDK가 내부적으로 수행하는 Background Reconcile 과정이 자동으로 보충하여 idle 수를 max_idle 수준으로 유지하며, TTL이 임박한 idle Sandbox도 회수 후 새것으로 교체된다. Idle Sandbox가 없으면 기본 정책에 따라서 즉석 생성으로 폴백한다. Warmup 단계에는 warmup_sandbox_preparer Hook으로 Package 설치 같은 준비 작업을 미리 수행해둘 수 있다.
state_store는 Pool의 상태를 보관하는 저장소이다. idle Sandbox 목록(sandboxId와 만료 시각), idle 수량 Counter, 그리고 보충 담당자를 선출하는 Primary Lock이 여기에 저장되며, 모든 상태는 pool_name을 Key로 구분된다. 기본 제공되는 InMemoryAsyncPoolStateStore는 상태를 Process 메모리에 두기 때문에 단일 Process 전용이며, Process가 재시작되면 idle 목록을 잃어버린다. 이때 기존 idle Sandbox가 즉시 제거되는 것은 아니고, 재사용되지 못한 채 각자의 수명(idle_timeout, 기본 24시간)이 만료될 때까지 Server에 남아 Resource를 점유한다.
반면 Redis 기반 AsyncRedisPoolStateStore는 상태를 Process 밖에 보존한다. 동일한 Redis를 바라보는 Process들은 동일한 pool_name을 지정하는 것만으로 같은 Pool 상태를 공유하기 때문에, 재시작한 Process가 idle 목록을 그대로 이어받고 다수의 Client가 하나의 Pool을 나눠 쓸 수 있다. 이 경우에도 Primary Lock을 잡은 하나의 Client만 Warmup과 보충을 수행하기 때문에 중복 생성은 발생하지 않는다.
SDK Pool은 OpenSandbox가 제공하는 기능이 아니라 SDK Level에서 일반 생성/접속 API 위에 자체 구현된 기능이다. 따라서 Server와 Controller는 Pool의 존재를 알지 못하며, Pool의 관리 주체는 Client 자신이다.
2.2. BatchSandbox Pool 이용
# Allocate a pre-warmed pod from the controller-managed pool instead of creating a new pod.
# Sandbox specs (image, entrypoint, resource) are decided by the pool's pod template
sandbox = await Sandbox.create(
connection_config=config,
extensions={"poolRef": "prewarmed-python"},
)[Code 5]는 Controller가 관리하는 Pool에서 Sandbox를 할당받는 과정을 나타내고 있다. Platform 운영자가 Pre-Warmed Pod의 Template과 용량을 선언한 Pool Custom Resource를 미리 생성해두면, 생성 요청의 extensions.poolRef로 Pool 이름을 지정하는 것만으로 Controller가 새 Pod를 만드는 대신 Pool의 Pre-Warmed Pod를 할당한다. Pod가 이미 떠 있기 때문에 image, entrypoint, resource 같은 Sandbox 스펙은 Pool의 Template이 결정하며 요청에서는 생략한다. Pool의 용량이 가득 차면 할당이 가능해질 때까지 대기한다.
SDK Pool과 비교하면 Warm 유지와 보충의 주체가 Client에서 Controller로 옮겨간 구조이다. Client는 state_store 같은 부가 인프라 없이 생성 요청만으로 이용할 수 있고 다수의 Client가 자연스럽게 하나의 Pool을 공유하는 반면, Sandbox 스펙을 요청마다 바꿀 수 없고 Pool의 생성과 용량 관리는 Platform 운영자의 몫이 된다. 또한 Pool 할당은 batchsandbox Workload Provider 경로 전용이기 때문에, agent-sandbox Provider 구성에서는 이용할 수 없다.
3. 명령 실행과 File 송수신
from opensandbox.models.filesystem import WriteEntry
# Upload files
await sandbox.files.write_files([
WriteEntry(path="/workspace/main.py", data="print('hello')", mode=644),
])
# Run shell
execution = await sandbox.commands.run("cd /workspace && python main.py")
# Download a file
content = await sandbox.files.read_file("/workspace/result.json")[Code 6]은 File을 업로드하고 Shell로 실행한 후 결과 File을 다운로드하는 과정을 나타내고 있다. 명령 실행과 File 송수신은 Sandbox Pod에 Init으로 주입된 execd가 처리하며, SDK에서는 Sandbox 객체의 commands(Shell)와 files 하위 객체를 통해서 이용한다.
from opensandbox.models.execd import RunCommandOpts, ExecutionHandlers
async def on_stdout(msg):
print(msg.text, end="")
# Stream stdout of a long-running command in real time
execution = await sandbox.commands.run(
"python train.py",
opts=RunCommandOpts(
working_directory="/workspace",
timeout=timedelta(minutes=30), # Per-command timeout, independent of the sandbox TTL
envs={"EPOCHS": "10"}, # Environment variables for this command only
),
handlers=ExecutionHandlers(on_stdout=on_stdout),
)
# Fire-and-forget: detach the command and return immediately with an execution handle.
# The command keeps running inside the sandbox (until the sandbox TTL expires),
# even if the client closes its session
background = await sandbox.commands.run(
"python warmup.py",
opts=RunCommandOpts(background=True),
)
# Later: fetch the detached command's output incrementally by cursor
logs = await sandbox.commands.get_background_command_logs(background.id)
print(logs.content, logs.cursor) # e.g. warming up... 42[Code 7]은 장시간 실행되는 명령의 출력을 실시간으로 수신하는 과정과, 명령을 Background로 분리하여 즉시 반환받는 과정을 나타내고 있다. handlers에 등록한 Async Callback으로 stdout/stderr를 Streaming으로 수신할 수 있기 때문에, AI Agent의 작업 로그를 사용자에게 실시간으로 중계하는 용도에 적합하다. opts로는 작업 디렉토리와 명령 단위 환경변수 외에 명령 단위 timeout을 지정할 수 있으며, 이 timeout은 Sandbox의 수명(TTL)과는 독립적으로 해당 명령에만 적용된다.
background=True로 실행하면 호출은 명령의 종료를 기다리지 않고 Execution Handle만 받은 채 즉시 반환되며, 명령은 Sandbox 안에서 계속 실행된다. 출력은 반환 시점에 수집되지 않는 대신, Handle의 id로 commands.get_background_command_logs()를 호출하여 사후에 Cursor 기반으로 조회할 수 있다. 명령이 Sandbox 안에서 실행되는 것이기 때문에 Client가 close()로 Session을 닫아도 명령은 계속 실행되지만, Sandbox가 TTL로 만료되면 함께 종료된다.
4. Volume 이용
OpenSandbox는 Kubernetes PVC(PersistentVolumeClaim)를 기반으로 하는 Volume 기능을 제공한다. Sandbox의 수명을 넘어서 상태를 보존하는 Persistent PVC와, Sandbox 종료와 함께 정리되는 실행 단위 임시 공간인 Ephemeral PVC 두 가지 Mode로 이용할 수 있다.
4.1. Persistent PVC 이용
from opensandbox.models.sandboxes import Volume, PVC
def workspace_volume(user_id: str) -> Volume:
return Volume(
pvc=PVC(
claimName=f"ws-{user_id}", # Fixed name derived from the session
createIfNotExists=True, # Server provisions the PVC on first use
deleteOnSandboxTermination=False, # PVC survives the sandbox
storage="20Gi",
),
mountPath="/workspace",
)
# First session: the server provisions the PVC on first use
sandbox = await Sandbox.create(
"python:3.11",
connection_config=config,
volumes=[workspace_volume(user_id)],
)
# Going idle: terminate only the sandbox — the PVC remains
await sandbox.destroy()
# Next session: recreate with the same claimName — prior state is restored at /workspace
sandbox = await Sandbox.create(
"python:3.11",
connection_config=config,
volumes=[workspace_volume(user_id)],
)[Code 8]은 Session 식별자 기반의 고정된 claimName으로 PVC를 선언하고, 유휴 진입시 Sandbox만 종료한 후 다음 Session에서 재생성하는 과정을 나타내고 있다. AI Agent Session처럼 유휴 구간이 긴 Workload에서 Sandbox를 Session 내내 유지하면 유휴 시간만큼 Compute 비용이 낭비된다. Persistent PVC를 이용하면 상태는 PVC에 남겨둔 채 유휴 시점에 Sandbox를 종료하여 Compute를 반납하고, 다시 필요할 때 Sandbox를 재생성하여 상태를 복원할 수 있다.
최초 Session에서 Server가 PVC를 자동으로 생성하며, 이후 Session에서 동일한 claimName으로 Sandbox를 다시 생성하면 새 Sandbox가 기존 PVC를 Mount하기 때문에 이전 상태가 /workspace에 그대로 복원된다. 즉 별도의 재개 API 없이 종료와 재생성만으로 Compute 반납과 상태 복원이 이루어진다.
Volume을 이용할 경우 유의할 점은 두 가지이다. 첫째, Mount 경로 밖의 상태는 보존되지 않는다. pip install로 System 경로에 설치한 Package는 재생성시 사라지기 때문에, venv와 작업물을 PVC 경로(/workspace) 아래에 두도록 Sandbox 내부 작업을 설계해야 한다. 둘째, sandboxId는 재생성시 변경된다. Session과 Sandbox의 매핑은 호출 측(Platform Backend)이 user_id ↔ claimName 기준으로 관리해야 한다. sandboxId를 유지한 채 보존이 필요하면 Snapshot 기반 Pause/Resume이 필요하며, 이는 Container Image Registry 구성을 전제로 한다.
4.2. Ephemeral PVC 이용
Volume(
pvc=PVC(
claimName=f"scratch-{run_id}", # Unique per run (duplicate → 409)
createIfNotExists=True,
deleteOnSandboxTermination=True, # Server deletes it on sandbox termination
storage="5Gi",
),
mountPath="/tmp/scratch",
)[Code 9]는 일회성 Scratch 공간을 Ephemeral PVC로 선언하는 과정을 나타내고 있다. Sandbox의 기본 쓰기 공간은 Container Layer이기 때문에 용량이 보장되지 않으며, 대용량 데이터를 쓰면 Node의 Disk를 압박하여 Eviction의 원인이 된다. 따라서 대용량 Dataset 가공이나 Build처럼 보존할 필요는 없지만 큰 중간 산출물이 생기는 작업에서는, Ephemeral PVC를 선언하여 실행 단위로 크기가 보장된 독립 Volume을 할당받는 것이 안전하다. 여기서 Ephemeral은 저장 매체가 아니라 PVC의 수명을 의미한다. Kubernetes의 Node-Local Ephemeral Storage(emptyDir)를 이용하는 것이 아니라, Sandbox 종료와 함께 삭제되는 일반 PVC이다.
Sandbox가 종료되면 Server가 Ephemeral PVC까지 정리하기 때문에 별도의 뒷정리도 필요 없다. Ephemeral PVC는 생성한 Sandbox가 배타적으로 소유하기 때문에 claimName을 실행 단위로 고유하게 생성해야 하며, 다른 Sandbox가 동일한 이름을 Mount하려고 하면 409 CONFLICT로 거부된다.
5. Endpoint 접근
import time
# Start an HTTP server listening on port 8000 inside the sandbox (background)
await sandbox.commands.run(
"python -m http.server 8000",
opts=RunCommandOpts(background=True),
)
# Resolve the externally reachable endpoint for port 8000
endpoint = await sandbox.get_endpoint(8000)
# e.g. gw.opensandbox.example.com {'OpenSandbox-Ingress-To': '<sandbox-id>-8000'}
print(endpoint.endpoint, endpoint.headers)
# Signed endpoint with a route token expiring at the given Unix time
signed = await sandbox.get_signed_endpoint(8000, expires=int(time.time()) + 600)
# e.g. gw.opensandbox.example.com
# {'OpenSandbox-Ingress-To': '<sandbox-id>-8000-<expires>-<signature>',
# 'OpenSandbox-Secure-Access': '<per-sandbox-access-token>'}
print(signed.endpoint, signed.headers)[Code 10]은 Sandbox 내부에 HTTP Server를 띄우고 외부에서 접근 가능한 Endpoint를 얻는 과정을 나타내고 있다. Jupyter나 Preview Server처럼 Sandbox 안에서 HTTP Server를 서빙하는 경우, get_endpoint()로 해당 Port의 접근 주소를 얻는다. 반환된 주소는 Server의 Ingress 구성에 따라서 Sandbox에 직접 연결되는 주소이거나 Ingress Gateway를 경유하는 주소이며, headers에는 해당 Endpoint 접근에 필요한 Header가 담긴다. 대표적으로 Ingress Gateway가 요청을 전달할 대상 Sandbox와 Port를 찾기 위한 Route 정보인 OpenSandbox-Ingress-To Header가 담기며, 요청마다 함께 전달해야 한다. 불필요한 구성에서는 비어 있다.
Server에 Secure Access가 활성화된 경우에는 get_signed_endpoint()로 지정한 시각까지만 유효한 서명된 Endpoint를 얻을 수 있으며, 결과물을 외부에 임시로 공유하는 URL 용도에 적합하다. 또한 이 경우 headers에는 Sandbox별로 발급되는 접근 Token인 OpenSandbox-Secure-Access Header가 추가되며, Gateway는 Token이 없거나 일치하지 않는 요청을 거부한다.
6. Egress 제한
from opensandbox.models.sandboxes import NetworkPolicy, NetworkRule
sandbox = await Sandbox.create(
"python:3.11",
connection_config=config,
network_policy=NetworkPolicy(
default_action="deny",
egress=[
# Allow only package installation paths
NetworkRule(action="allow", target="pypi.org"),
NetworkRule(action="allow", target="*.pythonhosted.org"),
# Internal DB by IP/CIDR + port (requires dns+nft mode)
NetworkRule(action="allow", target="10.0.20.0/24", ports=[5432]),
],
),
)[Code 11]은 Package 설치 경로와 내부 DB만 허용하는 Allowlist 선언을 나타내고 있다. Prompt Injection으로 생성된 유출 Code처럼 Sandbox에서 실행되는 Code는 신뢰할 수 없기 때문에, Sandbox 생성시 모든 Egress를 기본적으로 거부(Default-Deny)하고 필요한 목적지만 Allowlist로 허용하는 것을 기본 패턴으로 선언한다.
Rule은 target 값에 따라서 Domain 기반(FQDN, Wildcard Domain)과 IP 기반(IP, CIDR)으로 나뉜다. Domain Rule은 Egress Sidecar의 DNS Proxy가 Domain을 조회하는 시점에 허용 여부를 판단한다. 이 시점에는 어느 Port로 접속할지가 아직 정해지지 않았기 때문에 Domain Rule에는 ports를 함께 쓸 수 없으며, 조합하면 Validation Error로 거부된다. 반면 IP/CIDR Rule은 nftables가 실제 Packet을 보고 판단하기 때문에 ports로 TCP 목적지 Port까지 제한할 수 있다.
단, IP/CIDR Rule이 실제로 동작하려면 Server에 nftables를 함께 켜는 [egress] mode = "dns+nft" 설정이 필요하다. 기본값인 [egress] mode = "dns" 설정에서는 DNS Proxy만 동작하기 때문에, IP/CIDR Rule이 에러 없이 받아들여지지만 실제로는 적용되지 않는다. 세 번째 Mode인 [egress] mode = "forward"는 성격이 다르다. Sandbox별 Rule을 평가하지 않고, 모든 Sandbox의 모든 TCP 연결을 지정된 Upstream Proxy로 터널링한다. 어디로 나갈 수 있는지도 Upstream Proxy가 결정하기 때문에, 목적지 제어를 공용 Proxy 한 곳에서 일괄 관리하는 환경에 맞는 Mode이다.
Upstream Proxy는 [egress].upstream_proxy로 설정한다. forward Mode에서는 모든 연결이 향하는 목적지이기 때문에 필수이고, dns+nft Mode에서는 선택 사항이다. 후자에서 설정하면 Sidecar의 검사를 통과한 요청이 바로 외부로 나가는 대신 Upstream Proxy를 한 번 더 경유한다.
# Inspect the currently applied policy
policy = await sandbox.get_egress_policy()
# Add rules while the sandbox is running
await sandbox.patch_egress_rules([
NetworkRule(action="allow", target="api.github.com"),
])
# Remove rules by target
await sandbox.delete_egress_rules(["api.github.com"])[Code 12]는 실행 중인 Sandbox의 Egress Rule을 조회하고 변경하는 과정을 나타내고 있다. Egress Policy는 생성 시점에만 선언할 수 있는 것이 아니라, patch_egress_rules()로 Rule을 추가하고 delete_egress_rules()로 target 기준 제거할 수 있다. 최소 Allowlist로 시작한 후 사용자가 승인한 목적지를 점진적으로 열어주는 대화형 승인 패턴에 적합하다.
7. Pause/Resume
# Asynchronous request — does not become Paused immediately
await sandbox.pause()
while True:
info = await sandbox.get_info()
if info.status.state == "PAUSED":
break
await asyncio.sleep(2)
# Resume the paused sandbox (classmethod) — returns a new instance with the same sandboxId
sandbox = await Sandbox.resume(sandbox.id, connection_config=config)[Code 13]은 Pause를 요청하고 상태 전환을 확인한 후 Resume하는 과정을 나타내고 있다. Pause는 Sandbox를 유휴 상태로 전환하여 Compute Resource를 반납하는 동작이며, Resume은 Pause된 Sandbox를 동일한 sandboxId로 재개하는 동작이다. pause()는 비동기 요청이기 때문에 즉시 Paused 상태가 되지 않으며, get_info()를 통해서 상태 전환을 확인해야 한다.
SDK의 pause() / resume()은 동일한 API로 제공되지만, 실제 동작과 가용성은 Server가 Sandbox를 어떤 방식으로 실행하도록 구성되어 있는지에 따라서 달라진다. Sandbox의 실행 방식은 Workload Provider 종류(batchsandbox, agent-sandbox), Container Runtime 종류(runc, gVisor), Fast Sandbox 이용 여부 같은 Server 구성이 결정하며, Client는 API 호출만으로 이 차이를 구분할 수 없다. 따라서 pause()를 이용하는 Client Code는 Server 구성에 따른 의미 차이를 알고 있어야 한다. Server 구성별 동작 차이는 다음과 같다.
| Workload Provider | Container Runtime | Pause/Resume 동작 | 비고 |
|---|---|---|---|
| batchsandbox | runc | Rootfs가 Registry에 Commit된 후 Pod 제거 | Controller에 Snapshot Registry 미설정시 실패 |
| batchsandbox | gVisor | HTTP 409로 거부 | gVisor 격리와 Snapshot은 양립 불가 |
| agent-sandbox | runc | Pod만 제거, PVC 데이터만 보존 | Registry 불필요 |
| Fast Sandbox | Firecracker MicroVM | Memory까지 보존 | IdlePolicy 선언시 호출 없이 자동 Pause/Wake (전용 기능) |
# Persist a snapshot while the sandbox keeps running
snapshot = await sandbox.create_snapshot(name="before-upgrade", mode="full")
# Later: create a new sandbox restored from the snapshot
restored = await Sandbox.create(
snapshot_id=snapshot.id,
connection_config=config,
)[Code 14]는 실행 중인 Sandbox의 Snapshot을 명시적으로 생성하고, 그 Snapshot으로부터 새 Sandbox를 복원하는 과정을 나타내고 있다. Pause가 “보존 후 정지"라면 create_snapshot()은 Sandbox를 멈추지 않은 채 보존점만 남기는 동작이고, 복원은 Sandbox.create(snapshot_id=...)로 새 Sandbox를 만드는 방식이라 하나의 보존점에서 여러 Sandbox를 분기하는 복제 패턴에도 쓸 수 있다. mode는 Memory와 Process 상태까지 담는 full과 쓰기 Filesystem만 담는 rootfsOnly 중 선택하며, Snapshot 저장을 위한 Registry 구성 등 가용성 전제는 Pause와 동일하다.
8. Credential Vault
from opensandbox.models.sandboxes import (
CredentialProxyConfig, Credential, InlineCredentialSource,
CredentialBinding, CredentialMatch, CredentialAuth,
)
sandbox = await Sandbox.create(
"python:3.11",
connection_config=config,
network_policy=NetworkPolicy(
default_action="deny", # deny every other destination
egress=[NetworkRule(action="allow", target="api.github.com")], # allow only the binding's host
),
credential_proxy=CredentialProxyConfig(enabled=True), # Transparent MITM injection
)
# Write the real token to the sidecar vault — the sandbox never sees it
await sandbox.credential_vault.create(
credentials=[Credential(
name="github-token",
source=InlineCredentialSource(type="inline", value="ghp_realtoken..."), # source.type
)],
bindings=[CredentialBinding(
name="github-api",
match=CredentialMatch(hosts=["api.github.com"]),
auth=CredentialAuth(type="bearer", credential="github-token"), # auth.type
)],
)[Code 15]는 진짜 Credential을 Sandbox에 넣지 않고 외부 API 인증을 처리하는 Credential Vault 설정 과정을 나타내고 있다. 진짜 Secret은 Egress Sidecar의 Vault에만 기록되고 Sandbox 내부는 가짜 또는 빈 값으로 동작하며, 허용된 HTTPS 요청이 Binding의 match(Host, Method, Path)에 일치하면 Sidecar가 Transparent MITM(Man-in-the-Middle) 방식으로 나가는 요청에 인증 Header를 주입한다. Prompt Injection으로 생성된 Code가 환경변수나 Filesystem을 뒤져도 유출할 Secret 자체가 Sandbox 안에 없다.
Credential의 source.type은 Secret 값을 어디서 가져올지 결정한다. [Code 15]의 inline은 요청에 담은 값을 그대로 Vault에 저장하는 방식이고, exchange는 값 대신 외부 Endpoint를 지정해서 Sidecar가 요청 시점마다 Secret을 동적으로 받아오는 방식이다. 어느 방식이든 Vault 조회 API는 Secret 값이 제거된 Metadata만 반환한다.
Binding의 auth.type은 source.type과는 별개의 필드로, 일치한 요청에 Credential을 어떤 형태로 주입할지 결정한다.
bearer:Authorization: Bearer <값>Header를 주입한다.basic:Authorization: Basic <값>Header를 주입한다. Credential 값은 base64로 인코딩된username:password여야 한다.apiKey: 지정한 이름의 Header에 Credential 값을 주입한다.customHeaders: 여러 Header를 각각의 Credential로 주입한다.passthrough: Header를 주입하지 않는다. Header가 아니라 Path, Query String, Body의 Placeholder에 Credential이 필요한 API에서 치환 기능과 함께 이용한다.
Credential Vault를 이용하려면 세 가지 전제 조건이 필요하다. 먼저 Server 설정이 [egress] mode = "dns+nft"여야 한다. DNS 전용 Mode는 IP 직접 접속으로 우회할 수 있어서, Credential Vault는 nftables까지 켜진 Mode에서만 활성화된다. 다음으로 [Code 15]의 network_policy처럼 Binding 대상 Host만 허용하고 나머지는 기본 거부로 막아야 한다. 주입은 Egress Policy를 통과한 요청에만 일어나고, 나머지를 막아야 Credential이 실린 요청이 다른 곳으로 나가지 않는다. 마지막으로 생성 요청에서 credential_proxy를 활성화해야 한다. Header 주입이 Sidecar의 Transparent MITM 위에서 동작하기 때문이다.
9. Monitoring
# Current resource usage (CPU, memory, I/O)
metrics = await sandbox.get_metrics()
# Diagnostic logs and events by scope
logs = await sandbox.get_diagnostic_logs(scope="all") # container, all
events = await sandbox.get_diagnostic_events(scope="runtime") # runtime, all
# Attach operational metadata — set a key to None to remove it
info = await sandbox.patch_metadata({"team": "sre", "ticket": None})[Code 16]은 실행 중인 Sandbox의 상태를 조회하고 운영 Metadata를 관리하는 과정을 나타내고 있다. get_metrics()는 CPU, Memory, I/O 사용량을 반환한다. get_diagnostic_logs()와 get_diagnostic_events()는 진단용 Log와 Event를 반환하며, 어느 영역의 기록을 볼지 scope 인자로 선택한다. scope에 지정할 수 있는 값은 Runtime(Docker, Kubernetes)이 정의하며, 지원하지 않는 값은 400 에러로 거부된다. 현재 지원하는 값은 다음과 같다.
- Log의
container: Sandbox Container가 stdout/stderr로 남긴 출력을 반환한다. - Event의
runtime: Container 시작, 종료, Pause 같은 Runtime의 상태 변화 Event를 반환한다. - 공통
all: Runtime이 제공할 수 있는 모든 기록을 반환한다. 현재 Backend는 Log에는 Container 출력만, Event에는 Runtime Event만 기여한다.
patch_metadata()는 운영 Label을 Sandbox에 붙이는 용도이며 값에 None을 주면 해당 Key가 제거된다. Sandbox 목록과 필터 조회는 SandboxManager를 통해서 제공된다.
10. Sync API
from opensandbox import SandboxSync
from opensandbox.config import ConnectionConfigSync
config = ConnectionConfigSync(
domain="opensandbox.example.com",
api_key="tenant-a-api-key",
)
sandbox = SandboxSync.create("python:3.11", connection_config=config)
try:
execution = sandbox.commands.run("python -V")
print(execution.logs.stdout[0].text) # e.g. Python 3.11.x
finally:
sandbox.destroy()sandbox = SandboxSync.create(
"python:3.11",
connection_config=config,
volumes=[workspace_volume(user_id)], # Same volume declaration as [Code 8]
)
try:
sandbox.files.write_files([
WriteEntry(path="/workspace/note.md", data="session state", mode=644),
])
finally:
sandbox.destroy() # The PVC remains for the next session
# Reattaching to an existing sandbox works the same
sandbox = SandboxSync.connect(sandbox_id, connection_config=config)[Code 17]은 [Code 1]과 동일한 기본 Lifecycle을, [Code 18]은 Volume 기반 상태 보존을 Sync API로 이용하는 과정을 나타내고 있다. Script, Jupyter Notebook, 또는 Async Runtime이 없는 환경에서는 Sync API를 이용한다. Async API와 Method 구성이 동일하며, Sandbox 대신 SandboxSync를, ConnectionConfig 대신 ConnectionConfigSync를 이용하고 await/async 키워드만 제거하면 된다. Volume 선언은 [Code 8]과 동일하게 재사용할 수 있다.
11. 참조
- OpenSandbox Python SDK: https://github.com/opensandbox-group/OpenSandbox/blob/main/docs/sdks/python.md
- OpenSandbox PVC Volume Mount Example: https://github.com/opensandbox-group/OpenSandbox/blob/main/docs/examples/kubernetes-pvc-volume-mount.md
- OpenSandbox Pause/Resume Guide: https://github.com/opensandbox-group/OpenSandbox/blob/main/docs/guides/pause-resume.md