Documentation
¶
Index ¶
- Constants
- Variables
- func CheckImageUserNonRoot(image, user string) error
- func CheckTeamQuota(team string, limits TeamQuotaRequest, usage TeamQuotaUsage, add TeamQuotaUsage) error
- func CloneLabels(labels map[string]string) map[string]string
- func CreateHasEgress(req *CreateSandboxRequest) bool
- func CustomDomainTXTValue(txtValuePrefix, ownerToken, host string) string
- func DecodeNodeAffinity(encoded string) (string, bool)
- func DefaultDurabilityForRuntime(runtime string) string
- func DiskGBEnforced(engine, runtime string) bool
- func EncodeNodeAffinity(nodeID string) (string, bool)
- func FormatLabels(labels map[string]string) string
- func IsGeneratedSandboxID(ref string) bool
- func JSBundleRefForNode(localRef, nodeID string) string
- func LabelsSatisfy(have, want map[string]string) bool
- func ModuleRefForCreate(req CreateSandboxRequest) string
- func NormalizeCreateDurability(value, runtime string) (string, error)
- func NormalizeCustomDomain(host, baseDomain string) (string, error)
- func NormalizeFailoverPolicy(policy string) (string, error)
- func NormalizeImageDistributionMode(mode string) (string, error)
- func NormalizeWarmPoolOnImageChange(v string) string
- func ParseJSBundleNodeRef(ref string) (nodeID, localRef string, ok bool)
- func ParseNodeLabels(raw, zone string) (map[string]string, error)
- func PlacementUnsatisfiableError(want map[string]string) error
- func QuotaSize(cpu float64, memoryMB int) (float64, int)
- func ResolveContainerEngine(value string) (string, error)
- func ResolveContainerEngineOrDocker(value string) string
- func ResolveOCIRuntime(value string) (string, error)
- func RuntimeMediatesEgress(runtime string) bool
- func RuntimeUsesEgressGateway(runtime string) bool
- func SandboxEngine(sandbox *Sandbox) string
- func TeamOfOwnerRef(ownerRef string) string
- func ValidClusterNodeID(nodeID string) bool
- func ValidDurability(value string) (string, error)
- func ValidExposedPortProtocol(value string) (string, error)
- func ValidExposedPortVisibility(value string) (string, error)
- func ValidRuntime(value string) (string, error)
- func ValidTemplateID(templateID string) bool
- func ValidateCustomDomainList(hosts []string, baseDomain string) ([]string, error)
- func ValidateCustomDomainTargetPort(port int) error
- func ValidateLabelKey(key string) error
- func ValidateLabelValue(key, value string) error
- func ValidateLabels(labels map[string]string) error
- func ValidateRuntimeRequest(req CreateSandboxRequest, effectiveRuntime string, privileged bool, ...) error
- func ValidateSandboxID(id string) error
- func ValidateSandboxName(name string) error
- func ValidateWarmPoolImage(image string) error
- type APIToken
- type APITokenList
- type AddCustomDomainRequest
- type CreateAPITokenRequest
- type CreateJSBundleRequest
- type CreatePolicyError
- type CreateSandboxRequest
- type CreateSandboxResponse
- type CreateSandboxSnapshotRequest
- type CreateSandboxTokenRequest
- type CreateSessionRequest
- type CreateTemplateRequest
- type CreateWasmModuleRequest
- type CreatedAPIToken
- type CustomDomain
- type CustomDomainDNSRecords
- type CustomDomainStatus
- type DNSRecord
- type EgressInject
- type EgressProfile
- type EgressProfileList
- type EgressProfileRef
- type EgressProfileRequest
- type EgressRule
- type ErrorResponse
- type ExecRequest
- type ExecResult
- type ExposePortRequest
- type ExposePortResponse
- type ExposedPort
- type Failover
- type GPURequest
- type GPUVendor
- type HealthStatus
- type IdempotencyKeyReusedError
- type IdempotentRequestRecord
- type IdentityKeyRotation
- type IdentityRequest
- type IdentityRole
- type IdentityRoleList
- type IdentityRoleRequest
- type ImageDistributionMetadata
- type IngressTarget
- type JSBundle
- type Lifecycle
- type MountSpec
- type MountSpecFile
- type MountSpecRedacted
- type MountType
- type NetworkLearned
- type NetworkLearnedEntry
- type NetworkPolicy
- type NetworkPolicyCheckRequest
- type NetworkPolicyCheckResponse
- type NetworkPolicyRequest
- type NetworkUsage
- type PendingVolumeDeletion
- type PlacementRule
- type PlatformVolumeMount
- type PushWasmModuleOptions
- type PushWasmModuleResponse
- type RegistryAuth
- type ResizeSandboxRequest
- type RevokeSandboxTokensResponse
- type Sandbox
- type SandboxCompatState
- type SandboxIdentity
- type SandboxRuntimeState
- type SandboxSnapshot
- type SandboxStatus
- type SandboxToken
- type Session
- type SessionList
- type SessionResizeRequest
- type SessionSignalRequest
- type SessionStatus
- type SnapshotAlias
- type TeamQuota
- type TeamQuotaRequest
- type TeamQuotaUsage
- type Template
- type TemplateStatus
- type UpdateLifecycleRequest
- type UpdateNetworkLimitsRequest
- type Volume
- type VolumeAttachment
- type WarmPool
- type WarmPoolList
- type WarmPoolRequest
- type WarmPoolServerStatus
- type WarmPoolStatus
- type WasmModule
- type WasmModuleStatus
- type WhoAmI
- type WhoAmIPrincipal
Constants ¶
const ( // MaxCustomDomainsPerSandbox bounds the host matcher fan-out per route. // 25 keeps the Caddy host-list small and matches the value documented in // plans/custom-domains.md. MaxCustomDomainsPerSandbox = 25 // MaxCustomDomainsPerCreateRequest bounds how many hostnames a single // CreateSandbox call can attach. Lower than the per-sandbox cap so an // accidental array doesn't burn the ACME budget all at once. MaxCustomDomainsPerCreateRequest = 5 )
Custom-domain caps. Exported so internal/config can read SB_ env overrides against these defaults and the service layer can reference the canonical numbers from one place.
const ( IngressTargetSourceHostname = "hostname" IngressTargetSourceIPs = "ips" IngressTargetSourceMixed = "mixed" IngressTargetSourceUnknown = "unknown" )
IngressTarget Source values. Constants exported so cluster and service layers can build targets without stringly-typed errors.
const ( DNSRecordTypeCNAME = "CNAME" DNSRecordTypeA = "A" DNSRecordTypeAAAA = "AAAA" DNSRecordTypeANAME = "ANAME" DNSRecordTypeALIAS = "ALIAS" )
DNS record types we emit. CNAME / A / AAAA are the routing records on-demand ACME + HTTP-01 require; TXT (composed inline) proves ownership. ANAME / ALIAS are apex-flattening alternatives to CNAME: a bare CNAME is illegal at a zone root (RFC 1034 §3.6.2), so providers expose flattening under different record types (Cloudflare: CNAME, dnsmadeeasy/EasyDNS: ANAME, Route 53/DNSimple: ALIAS). For an apex on a hostname ingress we emit all three as mutually-exclusive candidates — the caller adds the one their provider supports.
const ( ContainerEngineDocker = "docker" ContainerEngineContainerd = "containerd" )
Host-level container engine identifiers. Distinct from Sandbox.Runtime (OCI runtime type: docker/gvisor/firecracker/wasm). Engine selects which daemon on the host realizes OCI sandboxes (dockerd vs native containerd).
const ( MaxCredentialKeys = 32 MaxCredentialBytes = 4096 )
MaxCredentialKeys / MaxCredentialBytes bound credential payload size so a malicious request can't blow up daemon memory.
const ( // PlacementZoneLabel is the reserved label key SB_NODE_ZONE and a // rule's zone field both set. A zone is a label so one matcher serves // both; the separate field exists because "run this in zone X" is the // common ask and should not need a map. PlacementZoneLabel = "zone" // MaxNodeLabels caps the labels a node may declare and a rule may // require (zone included). Labels ride every capacity heartbeat and a // rule rides every replicated spec, so both stay small and bounded. MaxNodeLabels = 16 // MaxLabelLength caps one label key and one label value (owner decision // P1.1: 63 characters each, the Kubernetes name length). MaxLabelLength = 63 )
Placement rules (plans/placement-rules.md). A node declares labels at boot (SB_NODE_ZONE, SB_NODE_LABELS); a create may require some of them. The rules here are shared by the daemon's config loader and the create path so a label a node can declare is exactly a label a create can ask for.
const ( // StatusReasonUserStop: a stop call (API, SDK, CLI, a facade, or the // operator's fleet suspend). StatusReasonUserStop = "user_stop" // StatusReasonIdle: stopIfIdleFor, or the server's SB_IDLE_TIMEOUT_MIN. StatusReasonIdle = "idle" // StatusReasonMaxAge: stopAtAge. StatusReasonMaxAge = "max_age" // StatusReasonOutOfMemory: the sandbox's init was killed for using too // much memory. ExitCode is set. StatusReasonOutOfMemory = "out_of_memory" // StatusReasonDiskLimit: the disk watchdog stopped it for writing more // than its disk size. StatusReasonDiskLimit = "disk_limit" // StatusReasonCrashed: the sandbox went down on its own with a non-zero // exit code that nobody asked for. ExitCode is set. StatusReasonCrashed = "crashed" // StatusReasonReconcile: sandboxd found the sandbox stopped when it // checked, without having seen it stop (it was down, or missed the // event), so it cannot say more. StatusReasonReconcile = "reconcile" )
Status reasons say why a sandbox is in its current status (Sandbox.StatusReason). The set is small and fixed on purpose: SDKs switch on it and the lifecycle metrics use it as a label, so a new value is an API change, not a log detail. last_error keeps the free-form detail.
Reasons a sandbox is stopped:
const ( // StatusReasonProgramExited: the sandbox's main program ended. On a // stopped sandbox, its init exited with code 0 on its own; on a started // one, the program run under toolboxd ended and the sandbox is still up // (lifecycle.destroyAfterExitFor). ExitCode is set. StatusReasonProgramExited = "program_exited" // StatusReasonFailover: the sandbox was recreated on another node after // its owner node failed; its in-memory state did not survive. StatusReasonFailover = "failover" // StatusReasonRestarted: lifecycle.restartOnFailure started the sandbox // again after a crash or an out-of-memory kill. ExitCode is the exit // code of that crash. StatusReasonRestarted = "restarted" )
Reasons that also describe a started sandbox:
const ( RuntimeDocker = "docker" // Docker's standard runc-backed runtime. RuntimeGvisor = "gvisor" // gVisor (runsc). User-space kernel for untrusted workloads. RuntimeKata = "kata" // Reserved: Kata Containers. Not yet implemented; rejected at create time. // RuntimeFirecracker selects the native Firecracker microVM runtime // (no Docker in the path). Plumbed through ValidRuntime so the API // accepts the identifier ahead of the implementation; CreateSandbox // rejects with ErrRuntimeNotImplemented until the per-host operator // opts in via SB_ENABLE_FIRECRACKER=true AND the driver has actually // landed. See plans/snapshot-clone-fast-boot.md. // // Distinct from RuntimeKata, which stays reserved for Kata Containers // (a different shape — Kata-with-Firecracker abstracts the snapshot // API away and is not what this constant refers to). RuntimeFirecracker = "firecracker" // RuntimeWasm selects the WASM/WASI runtime (plans/wasm-runtime.md). // ValidRuntime accepts the identifier ahead of the implementation; create // rejects with ErrRuntimeNotImplemented until SB_ENABLE_WASM lands. RuntimeWasm = "wasm" // RuntimeIsolate selects the V8-isolate (Workers-model) runtime // (plans/isolate-runtime.md). The name is deliberately engine-neutral — // "isolate" describes the model (isolates + fetch handler + capability // grants), not the workerd engine behind it. ValidRuntime accepts the // identifier ahead of the implementation; create rejects with // ErrRuntimeNotImplemented until the operator flips SB_ENABLE_ISOLATE // AND the driver has landed (same gate shape as firecracker/wasm). RuntimeIsolate = "isolate" )
User-facing runtime identifiers. These are the values the API, SDK, and stored sandbox row carry — chosen to match what an operator searching for "Docker" or "gVisor isolation" would type. The pkg/docker layer translates each one to the underlying OCI runtime binary name (runc / runsc / ...) when shaping the daemon request.
The empty string is reserved for legacy rows that pre-date the runtime field — those resolve to the host default at start time.
const ( DurabilityEphemeral = "ephemeral" DurabilityPassivatable = "passivatable" DurabilityDurable = "durable" )
Durability class for sandbox restart/survival semantics (plans/wasm-runtime.md §4.2).
const ( DefaultCPU float64 = 1 DefaultMemoryMB int = 1024 DefaultDiskGB int = 10 )
DefaultCPU, DefaultMemoryMB, DefaultDiskGB are the values normalizeCreateRequest substitutes when the caller leaves them at zero. Exported so any code path that has to reason about an un-normalized CreateSandboxRequest (placement scoring on the way IN, failover-recreate target selection on the way OUT) uses the same numbers — drift here causes placement to score against ghost capacity that doesn't match the eventual admission reservation.
const ( ImageDistributionExternalRegistry = "external_registry" ImageDistributionAOCR = "aocr" ImageDistributionLocalOnly = "local_only" // ImageDistributionAOCRImported is the post-auto-import distribution mode: // the bytes have been re-mounted under the cluster's own AOCR namespace // (`cluster/<id>/_imported/...`) and subsequent pulls use the cluster PAT, // not the user's upstream credentials. The user-visible Image field is // preserved; only the RegistryRef and mode flip. See F21 of the // cluster-mirror-and-snapshot-distribution plan for the full rationale — // the short version is that this is what makes `failover.policy: recreate` // survive upstream credential rotation. ImageDistributionAOCRImported = "aocr_imported" )
const ( SnapshotPushStateActive = "active" SnapshotPushStatePending = "pending" SnapshotPushStatePushing = "pushing" SnapshotPushStateError = "error" )
SnapshotPushState tracks the lifecycle of the optional background push of a local snapshot to the AOCR registry. The two terminal states a polling SDK cares about are "active" (snapshot is ready everywhere it can be) and "error" (push failed; the snapshot is still usable on the originating node and the reconciler will retry). "pending" / "pushing" are transient.
When SB_SNAPSHOT_PUSH_ENABLED is false, or when the snapshot's image already lives in a remote registry, new rows are written with state "active" directly — making the response shape identical to today's behavior.
const ( FailoverPolicyNone = "none" FailoverPolicyRecreate = "recreate" )
const ( NetworkEgressModeEnforce = "enforce" NetworkEgressModeLearn = "learn" )
Egress modes (NetworkEgressMode).
const ( ExposedPortVisibilityPublic = "public" ExposedPortVisibilityToken = "token" )
Exposed port visibilities (A2). Public is the default and the meaning of every row from before visibility existed.
const ( ExposedPortProtocolHTTP = "http" ExposedPortProtocolTCP = "tcp" ExposedPortProtocolTLS = "tls" )
Exposed port protocols. http is the original behavior (Caddy HTTP reverse proxy); tcp and tls are the caddy-l4 paths added with the L4 work.
const ( // Retrying after Retry-After is the recovery. ErrorCodeKeyStoreUnavailable = "key_store_unavailable" // ErrorCodeKeyStoreThrottled: the key store, or this node's cap on calls // to it, is saturated. Retrying after Retry-After is the recovery. ErrorCodeKeyStoreThrottled = "key_store_throttled" // ErrorCodeKeyStoreDenied: the key store refused this node's credentials // or policy. An operator has to fix the grant. ErrorCodeKeyStoreDenied = "key_store_denied" // ErrorCodeKeyRevoked: the key was disabled or deleted in the key store, // so secrets stay sealed until the key owner restores it. ErrorCodeKeyRevoked = "key_revoked" // ErrorCodeKeyVersionRetired: the secret was wrapped under a key version // the key store no longer allows. ErrorCodeKeyVersionRetired = "key_version_retired" )
Key-store error codes, each returned with 503 when the key store that wraps sandbox secrets (SB_SECRET_PROVIDER) answers with one of its five error classes (plans/customer-key-custody.md, eng review Section 2). The response message is fixed text, never the key store's own response.
const ( FacadeDaytona = "daytona" FacadeE2B = "e2b" FacadeRunloop = "runloop" )
Facade names used by sandbox_compat_state, snapshot_aliases, and request_idempotency. The string is the only thing persisted, so renaming a facade later would require a one-shot UPDATE.
const ( RequestStatePending = "pending" RequestStateReady = "ready" )
Idempotent-request states for request_idempotency.state. Pending means a write is in flight and holds the row's lock; Ready means the write completed and retries within ReplayUntil should replay TargetID instead of running again.
const ( TemplatePushStateActive = "active" TemplatePushStatePending = "pending" TemplatePushStatePushing = "pushing" TemplatePushStateError = "error" )
TemplatePushState tracks the lifecycle of the optional background push of a Firecracker template's artifacts (rootfs.ext4 + snapshot.memory + snapshot.state + manifest.json) to the AOCR registry under `cluster/<id>/templates/<tid>:latest`. Mirrors SnapshotPushState* — operators see one push-state vocabulary across snapshots and templates.
"active" is the terminal value (push succeeded OR push is disabled / not applicable on this node). New rows on a daemon with push disabled stay "active" forever; the reconciler only picks "pending" and "error".
const ( // MaxWarmPools bounds the entries a deployment may hold. Each entry's // status rides every warm-pool server's capacity heartbeat (about 60 // bytes), so the bound is what keeps that payload small at fleet scale. MaxWarmPools = 32 // MaxWarmPoolDepth bounds one entry's depth. The capacity gate still // decides how many slots a server can actually park; this only stops a // typo from asking every server for thousands. MaxWarmPoolDepth = 128 )
const ( WarmPoolReplaceNow = "replace_now" WarmPoolReplaceAsUsed = "replace_as_used" )
What a pool does when the image its tag names changes on a server (W3): replace every warm slot holding the old image at once, or keep handing the old slots out and replace each one as it is used. Empty means WarmPoolReplaceNow.
const CreatePolicyRuleRequireNonRoot = "require_non_root"
CreatePolicyRuleRequireNonRoot names the rule CheckImageUserNonRoot enforces.
ErrorCodeArtifactNodeUnavailable is returned (503) when an operation needs a node-bound artifact — a js-bundle or a node-built image — and the one worker holding it is not available. Such artifacts are single-copy; the recovery is to re-create the artifact (re-upload the bundle, rebuild the image), which yields a new node-bound ref.
const ErrorCodeCreateInProgress = "create_in_progress"
ErrorCodeCreateInProgress is returned (503, with Retry-After) for a create that waited past its bound for another create of the same sandbox ID (the same Idempotency-Key) running on the node. Nothing was created; the same request retried later gets that create's sandbox.
const ErrorCodeCreatePolicyDenied = "create_policy_denied"
ErrorCodeCreatePolicyDenied is returned (403) for a create or resize the operator's create policy refuses. The message names the rule.
const ErrorCodeCreatePolicyInvalid = "create_policy_invalid"
ErrorCodeCreatePolicyInvalid is returned (503) for every create and resize while the create policy file is set but did not load at boot: the limits are unknown, so the server fails closed until the file is fixed.
const ErrorCodeEgressApplyFailedHeld = "apply_failed_held"
ErrorCodeEgressApplyFailedHeld is returned (503) when a policy update is stored but could not be made live; a container sandbox is held without egress until a retry (the PUT is idempotent) or the reconcile pass applies it.
const ErrorCodeEgressFloorNotReady = "egress_floor_not_ready"
ErrorCodeEgressFloorNotReady is returned (503, with Retry-After) for a container or Firecracker create while this node's egress deny floor, which keeps sandboxes off the cloud metadata endpoints and the operator's deny_cidrs, is not installed for that runtime; the node retries it every few seconds.
ErrorCodeEgressGatewayUnavailable is returned (503, with Retry-After) when a sandbox with hostname egress rules can't be filtered right now: the node's egress gateway is down, or in a cluster no node has a ready one (plans/egress-domain-filtering.md G7, CEO D20). Retrying is the recovery.
const ErrorCodeEgressOperatorConfigInvalid = "egress_operator_config_invalid"
ErrorCodeEgressOperatorConfigInvalid is returned (503) for every create while the egress operator file is present but invalid at boot: the deployment's default egress policy is unknown, so creates fail closed (plans/egress-domain-filtering.md §5.10).
const ErrorCodeEgressProfileCapExceeded = "egress_profile_cap_exceeded"
ErrorCodeEgressProfileCapExceeded is a profile PUT that would push a referencing sandbox past the 1024-hostname union cap.
const ErrorCodeEgressProfileInUse = "egress_profile_in_use"
ErrorCodeEgressProfileInUse is a profile DELETE while sandboxes reference it.
const ErrorCodeEgressSpecCommitFailed = "spec_commit_failed"
ErrorCodeEgressSpecCommitFailed is returned (503) when a policy update could not be committed to the cluster's replicated spec; nothing changed.
const ErrorCodeIPv6FenceNotReady = "ipv6_fence_not_ready"
ErrorCodeIPv6FenceNotReady is returned (503, with Retry-After) for a container or Firecracker create while this node's IPv6 fence, which keeps IPv6 off the sandbox bridges and TAPs, is not installed for that runtime; the node retries it every few seconds.
const ErrorCodeIdempotencyKeyReused = "idempotency_key_reused"
ErrorCodeIdempotencyKeyReused is returned (422) for a create whose Idempotency-Key was already used with a different request. Retrying the same request cannot succeed: send the original request, or a new key.
ErrorCodeMountToolUnavailable is returned (501) for a create or start whose external-storage or platform-volume mount needs a mount tool (mount-s3, sshfs, rclone, mount) that is not installed on this node, as on a local install. Retrying won't help, so it is not a 503 (every SDK retries those); the operator installs the tool (the server installer does), or the caller creates the sandbox without the mount.
const ErrorCodeNetworkPolicyUnenforced = "network_policy_unenforced"
ErrorCodeNetworkPolicyUnenforced is returned (501) for a create, start, policy update or byte-cap update that needs the host firewall on a node where it is off (SB_ENABLE_NETWORK_RULES=false, or not a Linux host): the docker, containerd and Firecracker runtimes enforce block-all, address lists, hostname rules and byte caps with it. Retrying won't help; the operator turns the firewall on, or the caller drops the policy or picks a runtime that filters egress itself (wasm, isolate).
const ErrorCodeNodeGuardNotReady = "node_guard_not_ready"
ErrorCodeNodeGuardNotReady is returned (503, with Retry-After) for a container or Firecracker create while this node's guard that keeps sandboxes off the node's own services is not installed for that runtime; the node retries it every few seconds.
const ErrorCodeOverloaded = "overloaded"
ErrorCodeOverloaded is returned (503, with Retry-After) when the node shed the request: it already runs as many requests of that kind (cluster-wide sandbox lists) as it is configured to. Retrying after Retry-After is the recovery; nothing is wrong with the request.
const ErrorCodePlacementUnsatisfiable = "placement_unsatisfiable"
ErrorCodePlacementUnsatisfiable is the API code of a create whose placement rule no node satisfies (HTTP 409).
const ErrorCodeRateLimited = "rate_limited"
ErrorCodeRateLimited is returned (429, with Retry-After) when the caller's own tenant already runs its share of the node's requests of that kind (cluster-wide sandbox lists): the node has room, but not for one more from this tenant. Other tenants are unaffected. Retrying after Retry-After is the recovery; slowing down is the cure.
const ErrorCodeTeamQuotaExceeded = "team_quota_exceeded"
ErrorCodeTeamQuotaExceeded is the API code of a create, resize or start a team quota refuses (HTTP 429).
const MaxLifecycleDuration = 30 * 24 * time.Hour
MaxLifecycleDuration caps each Lifecycle field. 30 days is generous for any reasonable workload while still rejecting typos like "87600h" that would otherwise sit in the DB pretending to be useful.
const MaxMountsPerSandbox = 8
MaxMountsPerSandbox caps fan-out so a malicious request can't make sandboxd build an arbitrarily large container spec. Platform volumes count against the same cap as external mounts (a single shared budget).
const SandboxNameOwnerPrefix = "owner:"
SandboxNameOwnerPrefix marks an owner-qualified sandbox name key in the cluster's replicated name index ("owner:<base64url(owner_ref)>/<name>"). Names are unique per owner, and the cluster keeps one global index, so a tenant's name is stored under a key that carries its owner. The prefix is reserved: a caller-supplied name that starts with it could collide with another tenant's key, so new creates reject it.
const TeamOwnerPrefix = "team:"
TeamOwnerPrefix is the owner-ref prefix of a team (controlplane keeps the authoritative copy; models cannot import it).
Variables ¶
var ( // ErrCustomDomainInvalid is the validation error returned by // NormalizeCustomDomain. Wrapped with context (the offending hostname / // reason) so the API surfaces something actionable. ErrCustomDomainInvalid = errors.New("invalid custom domain") // ErrCustomDomainPerRequestCap is returned by ValidateCustomDomainList // when the caller passes too many hostnames in a single create request. ErrCustomDomainPerRequestCap = fmt.Errorf("at most %d custom_domains per create request", MaxCustomDomainsPerCreateRequest) // ErrCustomDomainNotSupported is returned when a deployment cannot accept // custom domains at all: the feature flag is off, or the daemon is running // in IP mode (no SB_DOMAIN). Surfaced as HTTP 412 Precondition Failed so // clients can distinguish "this cluster does not do custom domains" from // "your input is malformed" (which is 400). ErrCustomDomainNotSupported = errors.New("custom domains are not enabled on this deployment") // ErrCustomDomainProtocolConflict is the IRON RULE violation: a sandbox // with custom domains attached must not also expose protocol=tcp/tls // ports, because the L4 listener has no way to honor a host-based match // — the SNI would route to the wrong sandbox. Surfaced as 409 Conflict. ErrCustomDomainProtocolConflict = errors.New("custom domains cannot coexist with tcp/tls exposed ports on the same sandbox") // ErrCustomDomainPerSandboxCap is returned by AddCustomDomain when the // sandbox already holds MaxCustomDomainsPerSandbox rows. Surfaced as 409. ErrCustomDomainPerSandboxCap = fmt.Errorf("at most %d custom domains per sandbox", MaxCustomDomainsPerSandbox) // ErrCustomDomainVerificationFailed is returned when the DNS TXT record check fails. ErrCustomDomainVerificationFailed = errors.New("custom domain TXT record verification failed") // ErrCustomDomainInvalidTargetPort is returned when AddCustomDomainRequest // carries a target_port outside [0, 65535]. Zero is the toolbox-default // sentinel; anything else must be a real TCP port number. Surfaced as 400. ErrCustomDomainInvalidTargetPort = errors.New("invalid custom domain target_port") // ErrCustomDomainPortMismatch is returned when an idempotent re-add of // an already-attached hostname carries a different target_port than the // existing row. We do not silently change the dial target — that would // redirect live traffic without the caller knowing. Surfaced as 409 so // the caller can detach + re-add deliberately. ErrCustomDomainPortMismatch = errors.New("custom domain target_port mismatch on re-add") )
var ( // ErrPlatformVolumesDisabled is returned when a request references platform // volumes but the operator has not enabled them. Facades map this to 412 // Precondition Failed. ErrPlatformVolumesDisabled = errors.New("platform volumes are not enabled on this deployment") // ErrPlatformVolumesUnsupportedRuntime is returned when platform volumes are // requested on a runtime that cannot bind-mount host paths. Firecracker // (ext4 block-device rootfs) and wasm (host-mediated, no container FS) both // silently drop binds, so they are rejected up front. ErrPlatformVolumesUnsupportedRuntime = errors.New("platform volumes are not supported on the firecracker or wasm runtime") // ErrPlatformVolumeQuota is returned when a tenant would exceed its // configured volume-count cap. ErrPlatformVolumeQuota = errors.New("tenant platform-volume quota reached") // ErrPlatformVolumeInUse is returned when a delete is attempted while one or // more live sandboxes still have the volume attached. Facades map this to // 409 Conflict. ErrPlatformVolumeInUse = errors.New("volume is still attached to one or more sandboxes") // ErrPlatformVolumeConflict is returned when a create names an existing // platform volume with a different delete_with_sandbox than the volume was // made with, or names one volume twice with different values. Mapped to // 409 Conflict. ErrPlatformVolumeConflict = errors.New("platform volume already exists with a different delete_with_sandbox") // ErrMountOperatorOnly is returned when an owner-scoped (non-operator) // caller supplies raw mounts. Raw mounts execute host-side as the daemon // user and are trusted only under the "PAT == operator" assumption // (pr-review.md §5); a validated user token is not an operator. Tenants use // owner-namespaced platform volumes instead. Mapped to 403 Forbidden. ErrMountOperatorOnly = errors.New("raw mounts are operator-only; use platform_volumes for tenant storage") )
var ( // ErrInvalidPlacement is a malformed placement rule or node label. It // maps to HTTP 400 (the default branch of the API's error classifier). ErrInvalidPlacement = errors.New("invalid placement") // ErrPlacementUnsatisfiable is a create whose rule no node satisfies. It // is a refusal, never a fallback: a rule that is quietly ignored is worse // than no rule for regulated work (owner decision P1.4). ErrPlacementUnsatisfiable = errors.New("placement_unsatisfiable") )
var ( // ErrTeamQuotaExceeded is a request that would take a team past one of // its quota limits. The message names the team, the limit and the usage. ErrTeamQuotaExceeded = errors.New("team_quota_exceeded") // ErrTeamQuotaNotFound is a GET or a usage read for a team with no quota. ErrTeamQuotaNotFound = errors.New("team quota not found") // ErrInvalidTeamQuota is a malformed quota body (HTTP 400). ErrInvalidTeamQuota = errors.New("invalid team quota") )
ErrBuildKitUnavailable is returned by image-build endpoints when the host engine is containerd but buildkitd is not wired yet (Phase 3). Clear error, never a hang — see plans/containerd-engine.md §7.4.
var ErrContainerEngineNotRegistered = errors.New("container engine driver not registered on this node")
ErrContainerEngineNotRegistered is returned when a sandbox row points at an engine driver that was not wired at daemon boot (e.g. containerd row on a docker-only node).
var ErrCreatePolicyDenied = errors.New("refused by this server's create policy")
ErrCreatePolicyDenied matches every refusal by the operator's create policy (SB_CREATE_POLICY_FILE). The API answers 403 with the code ErrorCodeCreatePolicyDenied: retrying the same request cannot succeed.
var ErrIdempotencyKeyReused = errors.New("idempotency key was already used with a different request")
ErrIdempotencyKeyReused is returned when a create's Idempotency-Key was already used with a different request. It is answered 422 (ErrorCodeIdempotencyKeyReused) with no sandbox data.
var ErrInvalidSandboxName = errors.New("invalid sandbox name")
ErrInvalidSandboxName is returned when a create carries a name that the name rules reserve. It maps to HTTP 400 through the default branch of apihttp.WriteStoreAwareError.
var ErrRuntimeNotImplemented = errors.New("runtime not yet implemented on this build")
ErrRuntimeNotImplemented is returned when a runtime is recognized as a valid identifier but the implementation has not been wired up yet. Today only "kata" hits this path. Surfaced through the API as a 4xx so operators get an actionable error instead of a generic 500.
var ErrSandboxExists = errors.New("sandbox already exists")
ErrSandboxExists is returned when a sandbox row with the same primary key already exists. Distinct from name conflicts (store.ErrSandboxNameConflict).
var ErrSnapshotCorrupt = errors.New("snapshot integrity verification failed")
ErrSnapshotCorrupt is returned when a runtime snapshot fails checksum verification at load time — the on-disk artifact does not match the checksum stamped at capture. Firecracker templates and WASM boundary checkpoints both surface this; the service layer intercepts with errors.Is to mark the backing artifact unhealthy and kick rebuild.
var ErrSnapshotFenced = errors.New("snapshot clone generation fenced")
ErrSnapshotFenced is returned when a snapshot's clone_generation is older than the store row's current token (§4.8 zombie-write guard).
var ErrSnapshotSourceNotReady = errors.New("sandbox cannot be snapshotted in its current state")
ErrSnapshotSourceNotReady is a snapshot request for a sandbox its runtime cannot snapshot in the state it is in: a Firecracker sandbox must be stopped, by an agent that flushed its disk first. The wrapping message says what to do. HTTP 409.
var ErrTemplateNotRebuildable = errors.New("template not eligible for rebuild")
ErrTemplateNotRebuildable is returned by RequestTemplateRebuild when the row is in a state where re-running the snapshot phase is unsafe or unsupported:
- pending / building_rootfs / snapshotting: the initial build is in flight; the goroutine owns the row's state machine and a concurrent rebuild would race the goroutine's status writes.
- ready_no_snapshot: the snapshot phase failed during initial build and the row has no usable snapshot artifact to re-derive from. A full from-scratch rebuild requires source-image access (deferred — see internal/service/template_health.go comments).
- failed: terminal state from a failed initial build; operator must delete + recreate.
apihttp.WriteStoreAwareError maps this to 412 Precondition Failed so the operator's tooling can distinguish "row not in a rebuildable state" from "row missing" (404) and "invalid request" (400).
var ErrWarmPoolInvalid = errors.New("invalid warm pool")
ErrWarmPoolInvalid is a warm-pool PUT the server refuses as malformed (400).
var StatusReasons = []string{ StatusReasonUserStop, StatusReasonIdle, StatusReasonMaxAge, StatusReasonOutOfMemory, StatusReasonDiskLimit, StatusReasonCrashed, StatusReasonProgramExited, StatusReasonReconcile, StatusReasonFailover, StatusReasonRestarted, }
StatusReasons lists every status reason, in documentation order. Tests and the metrics use it so a reason cannot be added in one place only.
Functions ¶
func CheckImageUserNonRoot ¶ added in v0.6.12
CheckImageUserNonRoot holds an image's configured user (the USER line, as the image config reports it) to the require_non_root rule. Like Kubernetes' runAsNonRoot, only a numeric user id other than 0 passes: a name could map to uid 0 in the image's /etc/passwd, and reading that file would mean unpacking the image on the create path. An empty user is root, the runtime default.
func CheckTeamQuota ¶ added in v0.6.12
func CheckTeamQuota(team string, limits TeamQuotaRequest, usage TeamQuotaUsage, add TeamQuotaUsage) error
CheckTeamQuota reports whether usage plus add stays inside limits. The refusal names the team, the limit it would break and the usage, so a caller knows which knob to turn. A zero limit is no limit.
func CloneLabels ¶ added in v0.6.12
CloneLabels returns an independent copy, nil for an empty set.
func CreateHasEgress ¶ added in v0.6.6
func CreateHasEgress(req *CreateSandboxRequest) bool
CreateHasEgress reports whether a create sets any egress field. Cluster placement sends such a mediated-runtime create only to peers that enforce them (capacity Snapshot.MediatedEgress).
func CustomDomainTXTValue ¶ added in v0.6.8
CustomDomainTXTValue is the expected verification TXT value for a hostname. An empty ownerToken yields the legacy, owner-agnostic `<prefix><host>` value (operator deployments and backward compatibility). A non-empty ownerToken — an opaque, stable hash of the owning tenant — binds the proof to that tenant as `<prefix><ownerToken>=<host>`, so one tenant cannot pass verification for a hostname using another tenant's still-published record.
func DecodeNodeAffinity ¶ added in v0.6.1
DecodeNodeAffinity reverses EncodeNodeAffinity and reapplies the node-ID grammar so caller-supplied references cannot introduce protocol delimiters.
func DefaultDurabilityForRuntime ¶ added in v0.5.3
DefaultDurabilityForRuntime returns the API default when the caller omits durability on create. WASM and isolate default to ephemeral; container/VM runtimes default to passivatable (they survive restarts natively).
func DiskGBEnforced ¶ added in v0.5.6
DiskGBEnforced reports whether the host engine actually applies CreateSandbox DiskGB as a storage quota. dockerd may (xfs+pquota StorageOpt); containerd overlayfs and gVisor do not today — callers should warn, not fail.
func EncodeNodeAffinity ¶ added in v0.6.1
EncodeNodeAffinity returns the URL/tag-safe encoding shared by node-bound artifacts. Invalid node IDs are rejected at this boundary as well as config.
func FormatLabels ¶ added in v0.6.12
FormatLabels renders a label set as "k=v, k2=v2" in key order, for error messages and logs that must name the rule.
func IsGeneratedSandboxID ¶ added in v0.6.5
IsGeneratedSandboxID reports whether ref has the shape of a daemon-generated sandbox ID. Agent clients use it to decide between an ID lookup and a name lookup with one request.
func JSBundleRefForNode ¶ added in v0.6.1
JSBundleRefForNode binds a node-local isolate bundle reference to its owner worker. The node ID is base32-encoded so the reference remains safe in JSON, URLs, and CLI arguments without accepting delimiter injection.
func LabelsSatisfy ¶ added in v0.6.12
LabelsSatisfy reports whether a node with labels have may run a sandbox that requires want: every wanted key present with exactly the wanted value. An empty want is satisfied by any node, labelled or not.
func ModuleRefForCreate ¶ added in v0.5.3
func ModuleRefForCreate(req CreateSandboxRequest) string
ModuleRefForCreate returns the WASM module reference from a create request.
func NormalizeCreateDurability ¶ added in v0.5.3
NormalizeCreateDurability validates req.Durability, applies the runtime default when empty, and rejects classes the chosen runtime cannot honor yet.
func NormalizeCustomDomain ¶ added in v0.3.1
NormalizeCustomDomain lowercases, strips a trailing dot, and validates the shape of host. baseDomain is the operator's SB_DOMAIN — empty means the daemon is in IP mode, in which case the caller is expected to reject the request at the 412 layer before reaching validation. We still validate the hostname shape so callers cannot rely on the IP-mode short-circuit.
Returns the canonical (lowercased, dotted-trimmed) hostname on success.
Rejection rules (each maps to a test in types_test.go):
- empty or whitespace-only
- any label > 63 chars
- total length > 253 chars
- non-RFC1035 label charset (letters, digits, hyphen; no leading/trailing hyphen on a label)
- fewer than two labels (single-label is not a public hostname)
- IP literal (v4 or v6)
- "localhost" or anything ending in ".local"
- anything under baseDomain — wildcard already covers it; allowing a custom-domain row would let one tenant steal another sandbox's URL
func NormalizeFailoverPolicy ¶ added in v0.2.2
func NormalizeImageDistributionMode ¶ added in v0.2.1
func NormalizeWarmPoolOnImageChange ¶ added in v0.6.12
NormalizeWarmPoolOnImageChange spells out the default.
func ParseJSBundleNodeRef ¶ added in v0.6.1
ParseJSBundleNodeRef returns the required worker and the worker-local ref. Cluster upload responses use this encoding so later create placement remains O(1) and never probes or replicates a bundle across the fleet.
func ParseNodeLabels ¶ added in v0.6.12
ParseNodeLabels parses SB_NODE_LABELS ("k=v,k=v") and folds zone (from SB_NODE_ZONE) in under PlacementZoneLabel. A key given twice, a zone given both ways with different values, or a malformed entry is an error, so a typo fails the boot instead of making a node silently unmatchable.
func PlacementUnsatisfiableError ¶ added in v0.6.12
PlacementUnsatisfiableError is the refusal for a rule no node satisfies. The message names the rule, never the nodes, so it reads the same from any node that refuses.
func QuotaSize ¶ added in v0.6.12
QuotaSize is the CPU and memory one sandbox counts for: what it asked for, with the server defaults when it asked for nothing. The FSM and the single-node ledger both use it, so a team's usage reads the same in either.
func ResolveContainerEngine ¶ added in v0.5.6
ResolveContainerEngine normalizes SB_CONTAINER_ENGINE. Empty or unknown values default to docker so pre-migration hosts behave identically.
func ResolveContainerEngineOrDocker ¶ added in v0.5.6
ResolveContainerEngineOrDocker is ResolveContainerEngine that never errors — unknown/empty → docker (boot-path safe).
func ResolveOCIRuntime ¶
ResolveOCIRuntime maps a user-facing runtime identifier to the OCI runtime binary name to set on Docker's HostConfig.Runtime. Returns the binary name and true on success, or ErrRuntimeNotImplemented if the identifier is valid but the build does not implement it yet (today: kata).
The empty string is treated as "no override" — the caller leaves HostConfig.Runtime unset and Docker uses its compiled-in default. The "docker" identifier maps to "" for the same reason: avoiding an explicit "runc" entry means the daemon is happy even when /etc/docker/daemon.json has no runtimes.runc map entry, which is the common case.
func RuntimeMediatesEgress ¶ added in v0.6.6
RuntimeMediatesEgress reports whether a runtime filters egress in its own host-side mediator (WASM's worker, isolate's egress proxy) rather than the node's egress gateway.
func RuntimeUsesEgressGateway ¶ added in v0.6.6
RuntimeUsesEgressGateway reports whether hostname egress rules on this runtime are enforced by the node's egress gateway. WASM and isolate filter in their own host-side mediators; Firecracker guests reach the gateway through their TAPs (plans/egress-domain-filtering.md Phase 4). Cluster placement uses it to route gateway-mode creates only to nodes with a ready gateway.
func SandboxEngine ¶ added in v0.5.6
SandboxEngine returns the engine that owns this sandbox's container lifecycle. Legacy rows with an empty engine column resolve to docker.
func TeamOfOwnerRef ¶ added in v0.6.12
TeamOfOwnerRef returns the team an owner ref names, or "" for an owner that is not a team (operator, managed account).
func ValidClusterNodeID ¶ added in v0.6.1
ValidClusterNodeID is the single delimiter-safe grammar for identities that cross certificates, headers, gossip, and node-bound artifact references.
func ValidDurability ¶ added in v0.5.3
ValidDurability normalizes and validates a durability class. Empty input passes through so the caller can apply a runtime-specific default.
func ValidExposedPortProtocol ¶ added in v0.1.4
ValidExposedPortProtocol normalizes "" to http (the historical default) and rejects unknown values. Any caller that surfaces user input must run it through this before persistence.
func ValidExposedPortVisibility ¶ added in v0.6.12
ValidExposedPortVisibility checks a requested visibility. "" stays "" (the caller asked for no change); anything else must be public or token.
func ValidRuntime ¶
ValidRuntime normalizes and validates a user-facing runtime identifier. Empty input passes through unchanged so the caller can substitute the host default; any other value must be one of the recognized names. The intent here is "fail fast at the API boundary" — by the time a request reaches the runtime layer, we should already know the value is one we can act on.
func ValidTemplateID ¶ added in v0.6.1
ValidTemplateID keeps operator-supplied IDs safe as SQL keys, filesystem path components, URL segments, and registry repository components. Requiring an alphanumeric first byte excludes dot-segment traversal.
func ValidateCustomDomainList ¶ added in v0.3.1
ValidateCustomDomainList normalizes every entry in hosts against baseDomain and enforces the per-create-request cap and intra-list uniqueness. Returns the canonical slice or the first error. Empty input returns nil, nil — the caller treats "no custom domains" the same as omitting the field.
func ValidateCustomDomainTargetPort ¶ added in v0.4.1
ValidateCustomDomainTargetPort returns nil for 0 (the toolbox sentinel) and any 1..65535. Anything else is ErrCustomDomainInvalidTargetPort. Kept alongside the other custom-domain validators so the API + service layers reference one canonical bound.
func ValidateLabelKey ¶ added in v0.6.12
ValidateLabelKey checks a label key against the Kubernetes syntax: an optional DNS-subdomain prefix and '/', then a name. The whole key is at most MaxLabelLength characters.
func ValidateLabelValue ¶ added in v0.6.12
ValidateLabelValue checks a label value against the Kubernetes syntax. An empty value is allowed, as in Kubernetes.
func ValidateLabels ¶ added in v0.6.12
ValidateLabels checks a whole label set: every key and value, and the MaxNodeLabels cap.
func ValidateRuntimeRequest ¶ added in v0.5.6
func ValidateRuntimeRequest(req CreateSandboxRequest, effectiveRuntime string, privileged bool, logf func(string, ...any)) error
ValidateRuntimeRequest enforces runtime policy shared by dockerd and containerd drivers. Privileged mode, GPU vendor, and disk quota warnings must not fork per engine.
func ValidateSandboxID ¶ added in v0.6.3
ValidateSandboxID rejects any ID that is empty, over 128 bytes, or carries a character outside [A-Za-z0-9_-]. It is the single guard every path that uses a sandbox ID as a host path component relies on (the mount manager, per- sandbox state dirs). A sandbox ID can originate from a caller-influenced source — the X-Cluster-Create-ID forward header — so it must be validated at the create entry and at the point of use, never trusted because "IDs are generated".
func ValidateSandboxName ¶ added in v0.6.5
ValidateSandboxName applies the intake rules for a new sandbox name. Empty is allowed (an unnamed sandbox). The rules are intake-only: a stored spec replayed on failover keeps whatever name it already had, including legacy names created before these rules existed.
func ValidateWarmPoolImage ¶ added in v0.6.12
ValidateWarmPoolImage checks an entry's image reference. The pool matches creates by the exact string they send, so it is checked for shape only: no scheme, no whitespace or control characters, and a sane length.
Types ¶
type APIToken ¶ added in v0.6.8
type APIToken struct {
// ID is the public id (tok_…): the audit caller id, and what
// DELETE /v1/tokens/{id} takes.
ID string `json:"id"`
Name string `json:"name"`
Role string `json:"role"`
Team string `json:"team"`
CreatedBy string `json:"created_by"`
CreatedAt time.Time `json:"created_at"`
ExpiresAt time.Time `json:"expires_at"`
// Expired tokens no longer authenticate. They stay listed until the
// expiry sweep removes them 30 days after they expire.
Expired bool `json:"expired"`
}
APIToken is one token as GET /v1/tokens lists it. It never carries the secret or its hash.
type APITokenList ¶ added in v0.6.8
type APITokenList struct {
Tokens []APIToken `json:"tokens"`
}
APITokenList is the body of GET /v1/tokens.
type AddCustomDomainRequest ¶ added in v0.3.1
type AddCustomDomainRequest struct {
Hostname string `json:"hostname"`
TargetPort int `json:"target_port,omitempty"`
}
AddCustomDomainRequest is the body for POST /v1/sandboxes/{id}/custom-domains. Omitting target_port (or sending 0) routes the hostname to the toolbox agent, preserving pre-v2 behavior.
type CreateAPITokenRequest ¶ added in v0.6.8
type CreateAPITokenRequest struct {
// Name is 1 to 64 characters of A-Z, a-z, 0-9, '.', '_' and '-',
// unique among the team's tokens.
Name string `json:"name"`
// Role is viewer, runner, auditor or admin.
Role string `json:"role"`
// Team is a team name (1 to 63 of a-z, 0-9, '-') or "*" for every
// team. auditor and admin require "*".
Team string `json:"team"`
// ExpiresIn is the lifetime: "90d", "720h" or any Go duration. It is
// required and capped by SB_TOKEN_MAX_TTL.
ExpiresIn string `json:"expires_in"`
}
CreateAPITokenRequest is the body of POST /v1/tokens.
type CreateJSBundleRequest ¶ added in v0.5.6
type CreateJSBundleRequest struct {
Name string `json:"name,omitempty"`
MainModule string `json:"main_module,omitempty"`
Source string `json:"source,omitempty"`
Modules map[string]string `json:"modules,omitempty"`
CompatibilityDate string `json:"compatibility_date,omitempty"`
}
CreateJSBundleRequest is the body for POST /v1/js-bundles — the "no image, no registry" upload path for the isolate runtime (plans/isolate-runtime.md §8). The bundle is the JS/TS a workerd isolate runs. A one-file bundle sets Source (+ optional MainModule name); a multi-module bundle sets Modules directly. Name is an optional human alias the caller can reference on create instead of the digest; it is scoped to the caller's identity. The API is EXPERIMENTAL until the §10.1 demand checkpoint passes.
type CreatePolicyError ¶ added in v0.6.12
CreatePolicyError is one refusal, naming the policy rule that refused it so the caller (and the operator reading the log) knows which line of the file to look at. It lives here, not in the policy package, because the runtime drivers raise the require_non_root refusal after they read the image.
func (*CreatePolicyError) Error ¶ added in v0.6.12
func (e *CreatePolicyError) Error() string
func (*CreatePolicyError) Is ¶ added in v0.6.12
func (e *CreatePolicyError) Is(target error) bool
Is makes every CreatePolicyError match ErrCreatePolicyDenied.
type CreateSandboxRequest ¶
type CreateSandboxRequest struct {
Image string `json:"image"`
// ImageDistributionMode classifies whether Image can be pulled on any
// worker (external_registry/aocr) or is pinned to the local node
// (local_only). Empty is resolved by the service from snapshot metadata
// or by the default image distribution provider.
ImageDistributionMode string `json:"image_distribution_mode,omitempty"`
ImageDigest string `json:"image_digest,omitempty"`
ImageRegistryRef string `json:"image_registry_ref,omitempty"`
ImageVerifiedAt *time.Time `json:"image_verified_at,omitempty"`
// CPU is the number of CPU cores to allocate. Fractional values are
// supported (e.g. 0.5 = half a core, 1.5 = one and a half cores).
// Translates to Docker's CpuQuota at 100ms periods.
CPU float64 `json:"cpu"`
MemoryMB int `json:"memory_mb"`
DiskGB int `json:"disk_gb"`
Env map[string]string `json:"env"`
OSUser string `json:"os_user"`
NetworkBlockAll bool `json:"network_block_all"`
Registry *RegistryAuth `json:"registry,omitempty"`
ContainerCommand []string `json:"container_command,omitempty"`
// VerifyRegistryAccess forces the runtime to authorize the image against
// its registry even when it is already cached on the node, instead of
// trusting the local image. The service sets it for owner-scoped (validated
// user-token) callers so one tenant cannot start another tenant's private
// image just because it is already in the shared local cache. Internal-only
// (json:"-"): never on the wire, re-derived on the owner node after a
// cluster forward from the re-authenticated caller.
VerifyRegistryAccess bool `json:"-"`
// RequireNonRootUser tells a container runtime to refuse an image whose
// configured user is root, after it has the image config and before the
// container exists (the operator create policy's require_non_root rule,
// CheckImageUserNonRoot). Internal-only (json:"-"): the node that runs the
// sandbox sets it from its own policy file.
RequireNonRootUser bool `json:"-"`
Mounts []MountSpec `json:"mounts,omitempty"`
// PlatformVolumes references named, operator-backed persistent volumes by
// name only — the user never supplies storage coordinates or credentials.
// The service translates each entry into a synthesized, tenant-scoped
// MountSpec against the operator's shared backend (see
// plans/e2b-volume-mounts.md). All facades (E2B volumeMounts, Daytona
// volumes) and the native SDKs populate this single neutral field so the
// translation lives in one version-agnostic place.
PlatformVolumes []PlatformVolumeMount `json:"platform_volumes,omitempty"`
Lifecycle *Lifecycle `json:"lifecycle,omitempty"`
Failover *Failover `json:"failover,omitempty"`
// Name is an optional human-readable identifier. When set, it must be
// unique among the owner's sandboxes (a user token's account, or the
// operator namespace for PAT callers) — the store enforces this with a
// per-owner partial unique index, and cluster mode with an
// owner-qualified Raft name key. Two tenants may use the same name.
// Empty means no name; the sandbox can only be referenced by ID. The
// Daytona facade requires names; the native /v1 API and other facades
// may set or omit it.
//
// Duplicate names within one owner are rejected with HTTP 409 Conflict.
// Names starting with "owner:" or shaped like a generated sandbox ID
// (sb- plus 16 hex) are reserved and rejected with HTTP 400 (see
// ValidateSandboxName).
Name string `json:"name,omitempty"`
// Tags is an optional free-form key/value map associated with the
// sandbox. Used by facades that expose label-style metadata (Daytona
// labels, E2B metadata).
Tags map[string]string `json:"tags,omitempty"`
// CompatState carries each facade's per-sandbox compatibility state
// (sandbox_compat_state) on the FSM-replicated spec so a failover recreate
// can restore it — the rows are node-local and would otherwise be lost with
// the dead owner (B11). It is replication-internal: the create path strips
// any client-supplied value (normalizeCreateRequest), and only the service's
// own UpsertCompatState write-through populates it. Keyed by facade name →
// that facade's state JSON.
CompatState map[string]string `json:"compatState,omitempty"`
// Runtime selects the container runtime for this sandbox. Empty falls back
// to the host default (SB_CONTAINER_RUNTIME). Allowed values: "docker"
// (standard runc-backed Docker runtime, default), "gvisor" (runsc-backed
// userspace kernel — use for untrusted workloads), or "kata" (reserved,
// not yet implemented).
Runtime string `json:"runtime,omitempty"`
// GPUs attaches GPU resources to the sandbox. Nil means no GPU. GPU access
// is not supported with the gVisor runtime — the API returns an error if
// both GPUs and runtime="gvisor" are set.
GPUs *GPURequest `json:"gpus,omitempty"`
// Placement limits which nodes may run the sandbox: a zone and/or exact
// node labels (plans/placement-rules.md). It rides the replicated spec,
// so failover and recreate keep it. No node matching gives 409
// placement_unsatisfiable, never a quiet fallback.
Placement *PlacementRule `json:"placement,omitempty"`
// NetworkBytesInLimit caps lifetime ingress bytes for the sandbox. Zero
// means unlimited. When the cumulative counter crosses the limit, the
// reconcile loop installs an ingress DROP rule. The "we already paid for
// the bytes you see in the meter" caveat applies — host-side ingress is
// counted after the NIC has accepted the packet.
NetworkBytesInLimit int64 `json:"network_bytes_in_limit,omitempty"`
// NetworkBytesOutLimit caps lifetime egress bytes. Zero means unlimited.
// Crossing the limit installs an egress DROP rule via the same primitive
// NetworkBlockAll uses.
NetworkBytesOutLimit int64 `json:"network_bytes_out_limit,omitempty"`
// NetworkAllowOut is an egress allowlist: CIDRs, hostnames, *.suffix
// wildcards and host:port entries (plans/egress-domain-filtering.md §5.1).
// Alone it allows only these destinations. With NetworkDenyOut the
// precedence is allow-wins: an allow match passes, then a deny match
// drops, then the default is accept; a deny of 0.0.0.0/0 makes it an
// allowlist. Hostnames need the egress gateway on container runtimes.
NetworkAllowOut []string `json:"network_allow_out,omitempty"`
// NetworkDenyOut is an egress blocklist of CIDRs (never hostnames): alone,
// the sandbox may reach anything except these. A deny of 0.0.0.0/0 with
// no allow list is block-all and is stored as NetworkBlockAll.
NetworkDenyOut []string `json:"network_deny_out,omitempty"`
// EgressProfiles names egress profiles whose entries join
// NetworkAllowOut; the union is capped at 1024 hostnames. A profile
// update re-applies to every sandbox that references it
// (plans/egress-domain-filtering.md D21).
EgressProfiles []string `json:"egress_profiles,omitempty"`
// NetworkEgressMode is "enforce" (the default) or "learn". Learn mode
// allows all outbound traffic and records what the sandbox reaches, for
// GET /network/learned to turn into an allow list. It is open egress by
// design: trusted runs only. It needs empty lists, no profiles and no
// block-all (plans/egress-domain-filtering.md CEO D2).
NetworkEgressMode string `json:"network_egress_mode,omitempty"`
// NetworkEgressRules are method and path rules that refine hosts the
// allow list admits (plans/egress-domain-filtering.md §5.9, P3-1). An
// inspect rule makes the egress gateway terminate TLS on 443 with the
// node's CA, which the sandbox is given to trust; it has to be set at
// create.
NetworkEgressRules []EgressRule `json:"network_egress_rules,omitempty"`
// EgressWithheldEnv lists env keys the sandbox gets placeholders for
// instead of values (P3-2). sandboxd keeps it in the replicated spec, so
// a key an inject rule withheld at create stays withheld after the rule
// is removed: a recreate on another node must not hand the sandbox a
// credential it never had. A create may set it to withhold keys itself.
EgressWithheldEnv []string `json:"egress_withheld_env,omitempty"`
// AllowPublicTraffic controls whether the sandbox is public from boot. On
// create, omitted (nil) and false both mean private — no <id>.<domain>
// ingress route and empty public_url. Pass true to be public from boot.
// A later expose_port is itself the opt-in: it flips a private sandbox
// public whether this was omitted or false (enableSandboxPublicTraffic).
// The sandbox stays reachable via the platform's own paths (toolbox
// exec/file proxy, SSH gateway), which do not route through the public
// ingress.
AllowPublicTraffic *bool `json:"allow_public_traffic,omitempty"`
// MaskRequestHost, when non-empty, rewrites the upstream Host header on
// ingress to exposed HTTP ports to this value. Dev servers and frameworks
// that validate the Host header (Vite allowedHosts, webpack-dev-server,
// Django ALLOWED_HOSTS, Rails host authorization) reject requests whose
// Host is the per-sandbox public hostname; masking it to a value the app
// accepts (e.g. "localhost") unblocks them. Empty = pass through whatever
// the route would otherwise send (today's behavior). HTTP-only; TCP/TLS
// exposures ignore it (no Host header in raw passthrough).
MaskRequestHost string `json:"mask_request_host,omitempty"`
// CustomDomains attaches operator-provided public hostnames to the
// sandbox at create time. Each hostname must resolve (via DNS) to the
// cluster's ingress host before HTTPS can serve traffic — see
// plans/custom-domains.md. Bare strings on the wire; the response shape
// (Sandbox.CustomDomains) carries per-hostname status. Capped by
// MaxCustomDomainsPerCreateRequest.
CustomDomains []string `json:"custom_domains,omitempty"`
// CreateRequestDigests are keyed digests ("hmac:<key id>:<hex>", one per
// server key, the current key's first) of the request an Idempotency-Key
// create was made with, as the client sent it. Server-internal: the API
// edge sets it from the decoded request and replaces any client value; it
// rides a cluster forward and the replicated spec, so the node that runs
// the sandbox, and a failover recreate, can tell a retry of the same
// request from a reuse of the key for a different one.
CreateRequestDigests []string `json:"create_request_digests,omitempty"`
// TemplateID, when set alongside Runtime="firecracker", skips the
// per-create OCI→ext4 build and reuses a previously prepared
// rootfs.ext4 from a Firecracker template (POST /v1/templates). The
// template must be in status="ready" or Create rejects with a
// not-ready error. Ignored on the Docker path — templates are a
// Firecracker-only concept (see plans/snapshot-clone-fast-boot.md
// Phase 2). Pre-snapshot phase: the rootfs is the only artifact a
// template provides; Phase 3 layers snapshot.memory/state on top.
TemplateID string `json:"template_id,omitempty"`
// OverlaySizeGB, when > 0 and Runtime="firecracker", attaches a
// per-sandbox writable virtio-blk device (drive_id="overlay") of
// this size at /dev/vdb. On the snapshot-load fast-boot path the
// device must exist in the template snapshot's virtio-blk state —
// templates built before Phase 3 PR-B (has_overlay=false) reject
// this field with an error pointing at POST /v1/templates for a
// rebuild. The host allocates a sparse file; the guest is
// responsible for mkfs and mount (or set SB_FIRECRACKER_OVERLAY_MKFS
// on the daemon to have the host mkfs.ext4 the file at create time).
// Ignored on the Docker path. Capped at 1024 GiB by request
// validation; the daemon's admission control may reject smaller.
OverlaySizeGB int `json:"overlay_size_gb,omitempty"`
// Durability selects the sandbox survival class across restarts (§4.2 in
// plans/wasm-runtime.md). Empty defaults per runtime: passivatable for
// docker/firecracker/gvisor; ephemeral for wasm. "durable" is WASM-only
// and not yet implemented on any runtime.
Durability string `json:"durability,omitempty"`
// ModuleRef selects the WASM module for runtime=wasm. When set, Image may
// be omitted; when empty, Image is treated as the module reference.
// runtime=isolate reuses this field for the JS/TS bundle reference
// (plans/isolate-runtime.md §9) — no separate bundle_ref field until the
// demand checkpoint validates the tier.
ModuleRef string `json:"module_ref,omitempty"`
// TenantID is the isolate-group key for runtime=isolate: sandboxes with
// the same tenant share one workerd process; the OS-process boundary
// between tenants is the REQUIRED cross-tenant isolation boundary
// (plans/isolate-runtime.md §2.1). SECURITY: this value is
// server-authorized, never a free-form client value — a caller who could
// choose an arbitrary group key could force co-residency inside another
// tenant's process. The service layer rejects values the authenticated
// identity is not authorized to use; when empty, the group key falls back
// to the authenticated API identity. Ignored by other runtimes today.
TenantID string `json:"tenant_id,omitempty"`
// Identity gives the sandbox a short-lived cloud identity token
// (plans/sandbox-cloud-identity.md). It rides the replicated spec, so a
// failover recreate keeps it; it holds no secret.
Identity *IdentityRequest `json:"identity,omitempty"`
}
func (*CreateSandboxRequest) ApplyImageDistribution ¶ added in v0.2.1
func (r *CreateSandboxRequest) ApplyImageDistribution(meta ImageDistributionMetadata)
func (CreateSandboxRequest) ImageDistribution ¶ added in v0.2.1
func (r CreateSandboxRequest) ImageDistribution() ImageDistributionMetadata
func (CreateSandboxRequest) ShouldRecreateOnFailover ¶ added in v0.2.2
func (r CreateSandboxRequest) ShouldRecreateOnFailover() bool
type CreateSandboxResponse ¶
type CreateSandboxResponse struct {
Sandbox
SSHPrivateKey string `json:"ssh_private_key,omitempty"`
Replayed bool `json:"-"`
}
CreateSandboxResponse is what the API returns from POST /v1/sandboxes. SSHPrivateKey is generated server-side per sandbox and returned exactly once — it is never persisted and never returned again. The corresponding public key is stored on the sandbox record and is the only key authorized to SSH into that sandbox.
Replayed is server-side only: the create found a sandbox an earlier create of the same ID made and answered with it. A caller that rolls a failed create back must not roll back a replay — the sandbox is the earlier create's, not this request's.
type CreateSandboxSnapshotRequest ¶ added in v0.1.7
type CreateSandboxSnapshotRequest struct {
Name string `json:"name"`
// AllowPause says whether the snapshot may pause a running sandbox.
// Omitted or true: a running sandbox is paused for the copy (Docker
// pauses the container while it commits it; Firecracker holds the
// guest's disk writes while it copies the disk) and keeps running
// afterwards. False: a sandbox that is not stopped is refused with
// ErrSnapshotSourceNotReady (409) instead, for workloads that must never
// stall. A stopped sandbox needs no pause either way.
AllowPause *bool `json:"allow_pause,omitempty"`
}
CreateSandboxSnapshotRequest creates a reusable local image snapshot from an existing sandbox container. Name is the image reference callers can later pass back into CreateSandboxRequest.Image.
type CreateSandboxTokenRequest ¶ added in v0.6.12
type CreateSandboxTokenRequest struct {
// ExpiresIn is the token's lifetime: a Go duration ("15m", "2h") or a
// whole number of days ("1d"). Required, and capped by
// SB_SANDBOX_TOKEN_MAX_TTL.
ExpiresIn string `json:"expires_in"`
// Port, when set, makes a token for that port's public URL (a port
// exposed with visibility "token"). Left out, the token is for the
// sandbox's toolbox (exec, files, sessions). One token is never both.
Port int `json:"port,omitempty"`
// PathPrefix limits the request path: the toolbox path (for example
// "/files") or the public URL path (for example "/app"). It must be an
// absolute, clean path; "/files" covers "/files" and "/files/x", not
// "/files-x".
PathPrefix string `json:"path_prefix,omitempty"`
// Methods are the only HTTP methods allowed (GET, HEAD, POST, PUT,
// PATCH, DELETE, OPTIONS).
Methods []string `json:"methods,omitempty"`
}
CreateSandboxTokenRequest is the body of POST /v1/sandboxes/{id}/tokens. Every field but ExpiresIn narrows the token; leaving one out leaves that part of the request unrestricted.
type CreateSessionRequest ¶
type CreateSessionRequest struct {
// Name is the human-friendly session label. Two callers asking for the
// same Name see the same session (idempotent attach). Default "default".
Name string `json:"name,omitempty"`
Argv []string `json:"argv,omitempty"`
Command string `json:"command,omitempty"`
WorkDir string `json:"workdir,omitempty"`
Env map[string]string `json:"env,omitempty"`
PTY bool `json:"pty,omitempty"`
Cols int `json:"cols,omitempty"`
Rows int `json:"rows,omitempty"`
}
CreateSessionRequest is the body of POST /sessions on toolboxd (and the shape the sandboxd proxy forwards). Either Argv or Command may be supplied; Command is run via `sh -c` for convenience.
type CreateTemplateRequest ¶ added in v0.4.1
type CreateTemplateRequest struct {
ID string `json:"id,omitempty"`
Image string `json:"image"`
MinSizeMiB int `json:"min_size_mib,omitempty"`
}
CreateTemplateRequest is the body for POST /v1/templates. ID is optional — empty means "service generates one"; supplying an explicit ID lets a deploy pipeline assert idempotency across retries (the store rejects a duplicate ID with ErrTemplateIDConflict → API 409). Image is the skopeo-style ref ("docker://python:3.11", "oci-archive:/path.tar", etc.) passed through verbatim to pkg/oci.Builder. MinSizeMiB is an optional floor for the ext4 image — useful when the unpacked rootfs is small but the operator expects guests to write substantially more.
type CreateWasmModuleRequest ¶ added in v0.5.3
type CreateWasmModuleRequest struct {
ID string `json:"id,omitempty"`
ModuleRef string `json:"module_ref"`
Entrypoint string `json:"entrypoint,omitempty"`
}
CreateWasmModuleRequest is the body for POST /v1/wasm-modules. ID is optional — empty means the service uses the module digest as the catalogue id. ModuleRef is resolved synchronously on this host.
type CreatedAPIToken ¶ added in v0.6.8
CreatedAPIToken is the 201 body of POST /v1/tokens: the stored token plus its plaintext, which the server shows this once and never stores.
type CustomDomain ¶ added in v0.3.1
type CustomDomain struct {
Hostname string `json:"hostname"`
Status CustomDomainStatus `json:"status"`
// TargetPort is the in-container TCP port traffic for this hostname
// reverse-proxies to. Zero means "use the toolbox port" (the legacy
// behavior before per-domain target ports existed). Non-zero values
// dial straight to the user's app — e.g. an HTTP server on 3333.
// Set once at attach time; changing it requires detach + re-add so
// in-flight traffic can't silently redirect.
TargetPort int `json:"target_port,omitempty"`
LastError string `json:"last_error,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
CustomDomain is the per-domain row returned in Sandbox.CustomDomains.
type CustomDomainDNSRecords ¶ added in v0.3.1
type CustomDomainDNSRecords struct {
Records []DNSRecord `json:"records"`
Target IngressTarget `json:"target"`
}
CustomDomainDNSRecords is the response body for GET /v1/sandboxes/{id}/custom-domains/dns. Records is the flat ready-to-paste list (one row per custom domain × per ingress address); Target is the raw aggregation the records were composed from, included so callers can render their own UI without re-fetching.
type CustomDomainStatus ¶ added in v0.3.1
type CustomDomainStatus string
CustomDomainStatus is the per-domain lifecycle state surfaced through the API + SDK so callers can render "DNS not pointed yet" vs "issuing cert" vs "ready" without polling Caddy. Driven entirely server-side; clients read.
const ( // CustomDomainPendingDNS — row exists, Caddy has not yet asked for the // hostname. This is the state after AddCustomDomain returns and before // the first inbound HTTPS connection. CustomDomainPendingDNS CustomDomainStatus = "pending_dns" // CustomDomainIssuing — first ask hit, ACME flow started. Cleared on the // next ask that sees the cert in storage. CustomDomainIssuing CustomDomainStatus = "issuing" // CustomDomainReady — cert in shared storage, serving connections. CustomDomainReady CustomDomainStatus = "ready" // CustomDomainFailed — Caddy gave up on ACME for this host (LastError // carries the surfaced reason). No automatic retry beyond Caddy's own // backoff; the next ask will flip it back to issuing. CustomDomainFailed CustomDomainStatus = "failed" )
type DNSRecord ¶ added in v0.3.1
type DNSRecord struct {
Hostname string `json:"hostname"`
Type string `json:"type"`
Name string `json:"name"`
Value string `json:"value"`
Notes string `json:"notes,omitempty"`
}
DNSRecord is one DNS row a user must add at their provider to make a custom domain reach the cluster. Hostname is the full custom hostname (api.acme.com); Name is the leftmost label (or "@" for apex) the way DNS UIs accept it; Value is the right-hand side (target hostname or IP).
Notes carries provider-specific gotchas the SDK pre-renders so callers don't have to embed the documentation themselves. Currently only used to surface the Cloudflare "DNS only, gray cloud" warning — without it the proxy terminates TLS and on-demand ACME never fires.
func ComposeDNSRecords ¶ added in v0.3.1
func ComposeDNSRecords(hostnames []string, target IngressTarget, txtNamePrefix, txtValuePrefix string) []DNSRecord
ComposeDNSRecords expands every hostname against an IngressTarget into the set of DNS records the user must create at their provider. Shape rules:
- Subdomains with target.Hostname available → one CNAME (smallest, survives IP changes, works at every provider).
- Apex hostnames with target.IPs available → one A (and AAAA for IPv6) per IP. Apex prefers IPs over CNAME because CNAME-at-apex requires provider-specific flattening (Cloudflare, Route 53 alias, DNSimple ALIAS, etc.) and many providers reject it.
- Apex hostnames with only target.Hostname (no IPs) → three mutually- exclusive flattening candidates (CNAME, ANAME, ALIAS), all at "@" with the same value. A bare CNAME is illegal at a zone root, and providers name their flattening record differently, so we emit all three and the note tells the caller to add the one their provider supports.
- Subdomains with only target.IPs → one A/AAAA per IP.
- target empty / Source=unknown → returns nil. Callers render an operator-must-configure-ingress error rather than fake records.
One strategy per hostname is required: a CNAME owner name cannot coexist with A/AAAA records at the same name (RFC 1034 §3.6.2). DNS providers reject the second row, so emitting both as "ready-to-paste" would just trip the user up.
The TXT verification record proves zone control, not sandbox binding: value is `<txtValuePrefix><hostname>`, so the same record stays valid across sandbox recreates and can be provisioned BEFORE a sandbox exists. Cross-sandbox hijack is still blocked by the cluster-wide uniqueness gate on hostname insert. `txtNamePrefix` and `txtValuePrefix` allow customizing the verification TXT records.
func ComposeDNSRecordsForOwner ¶ added in v0.6.8
func ComposeDNSRecordsForOwner(hostnames []string, target IngressTarget, txtNamePrefix, txtValuePrefix, ownerToken string) []DNSRecord
ComposeDNSRecordsForOwner is ComposeDNSRecords with a tenant owner token folded into the TXT verification value (see CustomDomainTXTValue).
type EgressInject ¶ added in v0.6.6
type EgressInject struct {
// Header is replaced, never added to or substituted inside bodies.
Header string `json:"header"`
// SecretRef is "env:<KEY>": a key in the sandbox's env, withheld from
// the sandbox (it gets "aerolvm-placeholder:<KEY>") and handed to the
// egress gateway instead. Rotating it means recreating the sandbox.
SecretRef string `json:"secret_ref"`
}
EgressInject is a rule's credential injection (plans/egress-domain- filtering.md §5.9, P3-2).
type EgressProfile ¶ added in v0.6.6
type EgressProfile struct {
Name string `json:"name"`
AllowOut []string `json:"allow_out"`
Description string `json:"description,omitempty"`
Generation int64 `json:"generation"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
EgressProfile is a named allowlist sandboxes reference by name (plans/egress-domain-filtering.md D21). Profiles are owner-scoped like sandbox names; Generation goes up by one on every change.
type EgressProfileList ¶ added in v0.6.6
type EgressProfileList struct {
Profiles []EgressProfile `json:"profiles"`
NextCursor string `json:"next_cursor,omitempty"`
}
EgressProfileList is one page of GET /v1/egress-profiles.
type EgressProfileRef ¶ added in v0.6.6
EgressProfileRef is a profile and the generation of it a sandbox has live.
type EgressProfileRequest ¶ added in v0.6.6
type EgressProfileRequest struct {
AllowOut []string `json:"allow_out"`
Description string `json:"description,omitempty"`
}
EgressProfileRequest is the body of PUT /v1/egress-profiles/{name}, a full replace: the same body twice is a no-op.
type EgressRule ¶ added in v0.6.6
type EgressRule struct {
// Host is an exact name or "*." wildcard the allow list already admits.
Host string `json:"host"`
// Ports is [80] by default, or [443] with Inspect; only 80 and 443.
Ports []uint16 `json:"ports,omitempty"`
// Methods are exact, upper case; empty allows any.
Methods []string `json:"methods,omitempty"`
// Paths are globs: "*" within a segment, "**" as a whole segment for
// any number of them; empty allows any.
Paths []string `json:"paths,omitempty"`
// Inspect terminates TLS on 443 with the node's CA so requests can be
// checked, and makes the gateway require Host to equal the SNI.
Inspect bool `json:"inspect,omitempty"`
// Inject replaces a header on the requests this rule allows with a
// secret from the sandbox's own env, which the sandbox itself only
// sees as a placeholder (P3-2). Needs Inspect.
Inject *EgressInject `json:"inject,omitempty"`
// Binaries limits the rule to connections opened by these executables
// (absolute paths inside the sandbox; an interpreter's script counts),
// on runc sandboxes only (P3-3). A rule with only binaries decides
// whole connections, on any port the allow list opens.
Binaries []string `json:"binaries,omitempty"`
}
EgressRule is one method and path rule (plans/egress-domain-filtering.md §5.9, P3-1). Rules for one host are alternatives: a request to a ruled host passes when some rule admits its method and path, and is refused with 403 otherwise. A host no rule names keeps its allow-list decision.
type ErrorResponse ¶
type ErrorResponse struct {
Error string `json:"error"`
// Code is an optional stable identifier for errors a client is expected
// to act on programmatically (retry, re-upload, ...). Absent for errors
// that are only ever shown to a person.
Code string `json:"code,omitempty"`
// Reason is the standard refusal reason on a 401 for an avm_ token or a
// JWT (expired, not_yet_valid, wrong_audience, ...; plans/
// identity-and-access.md D17), mirrored in the RFC 6750 WWW-Authenticate
// error_description. On a 403 for a verified OIDC token that matched no
// role binding it is no_binding or group_overage (design review DR8).
// Absent on every other error, including the operator token's 401, so
// those bodies are byte for byte unchanged.
Reason string `json:"reason,omitempty"`
// RequiredPermission and Role are set only on a 403 for an avm_ token or
// an OIDC caller (plans/identity-and-access.md §5.3, D9): the permission
// the route needs and the role the caller holds; Error carries the hint.
// Absent for the operator token and managed callers, so their 403 bodies
// are byte for byte unchanged.
RequiredPermission string `json:"required_permission,omitempty"`
Role string `json:"role,omitempty"`
// Issuer, Name and Groups are set only on the "no binding" 403 (Reason
// no_binding or group_overage): the identity-file name of the issuer
// the caller signed in through, the caller's display name, and the
// groups the caller's token carried (none on group_overage). All three
// are the caller's own claims, so the dashboard and the CLI can show
// what an admin needs to add a binding (D9, DR8).
Issuer string `json:"issuer,omitempty"`
Name string `json:"name,omitempty"`
Groups []string `json:"groups,omitempty"`
}
type ExecRequest ¶
type ExecRequest struct {
Command string `json:"command"`
// Argv runs a program with these arguments instead of Command, with no
// shell parsing in between: spaces, quotes, $ and ; reach the program
// as written. It finds programs the same way Command does, including
// what the login profile adds to PATH. Set Command or Argv, not both.
// An agent older than Argv answers "command is required"; the SDKs
// check /version (exec.argv) first.
Argv []string `json:"argv,omitempty"`
WorkDir string `json:"workdir,omitempty"`
Env map[string]string `json:"env,omitempty"`
TimeoutSeconds int `json:"timeout_seconds,omitempty"`
// MaxStdoutBytes and MaxStderrBytes keep only the first N bytes of each
// stream; toolboxd reads and drops the rest, so the command never blocks
// on a full pipe. 0 means the caller sets no cap: sandboxd may fill in
// the operator's default (SB_EXEC_OUTPUT_DEFAULT_BYTES), and toolboxd
// still applies its own hard ceiling. An agent older than these fields
// ignores them, so the SDKs check /version (exec.max_output_bytes) and
// refuse rather than send them to it.
MaxStdoutBytes int64 `json:"max_stdout_bytes,omitempty"`
MaxStderrBytes int64 `json:"max_stderr_bytes,omitempty"`
}
type ExecResult ¶
type ExecResult struct {
Stdout string `json:"stdout"`
Stderr string `json:"stderr"`
ExitCode int `json:"exit_code"`
DurationMS int64 `json:"duration_ms"`
// TimedOut is true when the command ran past its timeout and toolboxd
// killed its whole process group. A sandbox agent older than this field
// never sets it.
TimedOut bool `json:"timed_out,omitempty"`
// StdoutTruncated and StderrTruncated report that the stream printed more
// than its cap and only the first bytes are in Stdout or Stderr. One flag
// per stream, because the caps are set per stream: a caller whose stdout
// is complete can trust it even when noisy stderr was cut, and a single
// flag would make it compare lengths, which fails when the output is
// exactly the cap. Output a background job prints after the reply is
// dropped (B2) and never sets them.
StdoutTruncated bool `json:"stdout_truncated,omitempty"`
StderrTruncated bool `json:"stderr_truncated,omitempty"`
// Signal names the signal that ended the process toolboxd started, such
// as "SIGKILL" (a timeout) or "SIGSEGV"; empty when it exited on its
// own. ExitCode stays -1 then, as before this field; the shell
// convention for the same end is 128 + the signal's number (137 for
// SIGKILL). A command run by a shell that outlives it reports the
// shell's 128+n exit code and no signal. Response-only: an older agent
// leaves it out.
Signal string `json:"signal,omitempty"`
}
type ExposePortRequest ¶ added in v0.1.4
type ExposePortRequest struct {
Protocol string `json:"protocol,omitempty"`
// Visibility is "public" (anyone with the URL) or "token" (the URL needs
// a sandbox token for this port, A2). Omitted, a new exposure is public
// and a re-expose keeps the visibility it has: only an explicit value
// changes it, so an older client's retry can never open a gated port.
Visibility string `json:"visibility,omitempty"`
}
ExposePortRequest is the optional JSON body for POST /v1/sandboxes/{id}/ports/{port}. Empty body or empty Protocol falls back to "http" — the historical default — so old SDK callers keep working unchanged.
type ExposePortResponse ¶ added in v0.1.6
type ExposePortResponse struct {
Protocol string `json:"protocol"`
PublicURL string `json:"public_url"`
Host string `json:"host,omitempty"`
HostPort int `json:"host_port,omitempty"`
// Visibility is set only for a token-gated port ("token"); a public
// port leaves it out, so the body is what it was before A2.
Visibility string `json:"visibility,omitempty"`
}
ExposePortResponse is the JSON body returned by POST /v1/sandboxes/{id}/ports/{port}. Protocol is the canonical value the daemon picked ("http", "tcp", or "tls"), PublicURL is the dialable URL for the exposure, and Host/HostPort are populated only on the raw-TCP path so SDKs can hand them to native protocol clients without parsing tcp://host:port out of PublicURL.
type ExposedPort ¶
type ExposedPort struct {
SandboxID string `json:"sandbox_id"`
Port int `json:"port"`
// Protocol is one of "http" (default — Caddy HTTP reverse proxy), "tcp"
// (caddy-l4 listener bound to HostPort, raw TCP forward to the container),
// or "tls" (caddy-l4 SNI route on the shared TLS listener). Pre-migration
// rows carry "http" via the column default.
Protocol string `json:"protocol"`
// HostPort is the parent-host TCP listener allocated for protocol="tcp"
// from the configured pool (default [22000, 23000]). Zero for http/tls
// modes, which don't reserve a per-exposure host port.
HostPort int `json:"host_port,omitempty"`
PublicURL string `json:"public_url"`
CreatedAt time.Time `json:"created_at"`
// Visibility is "token" for a port whose public URL needs a sandbox
// token; empty (public) otherwise. Stored as "public" for every row
// written before A2 (the column default).
Visibility string `json:"visibility,omitempty"`
}
func (ExposedPort) TokenGated ¶ added in v0.6.12
func (p ExposedPort) TokenGated() bool
TokenGated reports whether the exposure's public URL needs a sandbox token.
type Failover ¶ added in v0.2.2
type Failover struct {
Policy string `json:"policy,omitempty"`
}
Failover controls what the cluster should do if the sandbox's owner node is declared dead. Empty or omitted means "none": orphan the placement and return 410 Gone. "recreate" opts the sandbox into best-effort recreation from its replicated create spec on another worker.
func (Failover) NormalizedPolicy ¶ added in v0.2.2
func (Failover) ShouldRecreate ¶ added in v0.2.2
type GPURequest ¶ added in v0.1.3
type GPURequest struct {
// Vendor is required. Allowed values: "nvidia", "amd", "apple".
Vendor GPUVendor `json:"vendor"`
// Count is the number of GPUs to allocate. Use -1 to request all GPUs on
// the host. Zero is treated as 1 (default). Ignored for AMD (all AMD GPUs
// on the host are exposed via /dev/kfd and /dev/dri).
Count int `json:"count,omitempty"`
// DeviceIDs pins the sandbox to specific GPU device indices or UUIDs.
// For NVIDIA: GPU indices ("0", "1") or UUIDs ("GPU-abc123...").
// For AMD and Apple: ignored.
DeviceIDs []string `json:"device_ids,omitempty"`
}
GPURequest describes the GPU resources to attach to a sandbox. The parent CreateSandboxRequest.GPUs field is a pointer, so omitting it entirely means no GPU — this struct only appears when the caller explicitly opts in.
func (*GPURequest) Validate ¶ added in v0.1.3
func (g *GPURequest) Validate() error
Validate checks GPURequest fields for consistency.
type GPUVendor ¶ added in v0.1.3
type GPUVendor string
GPUVendor identifies the GPU hardware vendor for sandbox GPU allocation.
const ( // GPUVendorNVIDIA selects NVIDIA GPUs via nvidia-container-runtime. // Requires nvidia-container-toolkit installed on the host. GPUVendorNVIDIA GPUVendor = "nvidia" // GPUVendorAMD selects AMD GPUs via ROCm device bind-mounts (/dev/kfd, // /dev/dri). Requires ROCm drivers on the host. GPUVendorAMD GPUVendor = "amd" // GPUVendorApple selects Apple Silicon GPU via Docker Desktop's // experimental Metal support. Only functional on macOS with Docker Desktop; // Linux hosts will receive a Docker daemon error at container creation. GPUVendorApple GPUVendor = "apple" )
type HealthStatus ¶
type HealthStatus struct {
Status string `json:"status"`
Sandboxes int `json:"sandboxes"`
Docker string `json:"docker"`
Caddy string `json:"caddy"`
Firecracker string `json:"firecracker,omitempty"`
Wasm string `json:"wasm,omitempty"`
Isolate string `json:"isolate,omitempty"`
SSHGateway string `json:"ssh_gateway"`
ClusterTopology string `json:"cluster_topology,omitempty"`
ClusterNodes int `json:"cluster_nodes,omitempty"`
// KeyCustody is "revoked" while the customer's key store has revoked
// the server key and the node has stopped processing their data;
// otherwise empty (plans/customer-key-custody.md §10).
KeyCustody string `json:"key_custody,omitempty"`
Version string `json:"version"`
}
type IdempotencyKeyReusedError ¶ added in v0.6.9
type IdempotencyKeyReusedError struct {
Key string
}
IdempotencyKeyReusedError is ErrIdempotencyKeyReused naming the key.
func (*IdempotencyKeyReusedError) Error ¶ added in v0.6.9
func (e *IdempotencyKeyReusedError) Error() string
func (*IdempotencyKeyReusedError) Is ¶ added in v0.6.9
func (e *IdempotencyKeyReusedError) Is(target error) bool
Is makes errors.Is(err, ErrIdempotencyKeyReused) hold.
type IdempotentRequestRecord ¶ added in v0.1.7
type IdempotentRequestRecord struct {
Scope string
Fingerprint string
TargetID string
State string
LockedUntil time.Time
ReplayUntil time.Time
CreatedAt time.Time
UpdatedAt time.Time
}
IdempotentRequestRecord is the row shape for request_idempotency. Scope is a facade-defined namespace string (e.g. "e2b.create") so the same fingerprint hash can be reused across facades without collision. The generic store helpers stay facade-agnostic — only the scope string says which caller owns the row.
type IdentityKeyRotation ¶ added in v0.6.12
type IdentityKeyRotation struct {
ActiveKeyID string `json:"active_key_id"`
PublishedKeyID []string `json:"published_key_ids"`
}
IdentityKeyRotation is the body of POST /v1/identity/keys/rotate: the key id that now signs and the ones the JWKS still lists. Never key material.
type IdentityRequest ¶ added in v0.6.12
type IdentityRequest struct {
RoleTag string `json:"role_tag"`
// Audience is the token's aud; empty means sts.amazonaws.com.
Audience string `json:"audience,omitempty"`
// AWSRoleARN, when set, also gives the sandbox AWS_ROLE_ARN and
// AWS_WEB_IDENTITY_TOKEN_FILE, which every AWS SDK reads.
AWSRoleARN string `json:"aws_role_arn,omitempty"`
// AzureClientID and AzureTenantID, set together, give the sandbox the
// AZURE_* variables the Azure SDKs read for workload identity.
AzureClientID string `json:"azure_client_id,omitempty"`
AzureTenantID string `json:"azure_tenant_id,omitempty"`
}
IdentityRequest is the create option `identity` (D1.6). RoleTag must be on the owner's allow list (/v1/identity/roles) and the caller must hold its minimum role. The token's subject is built from the caller's own team and RoleTag, never from anything else in the request.
type IdentityRole ¶ added in v0.6.12
type IdentityRole struct {
Tag string `json:"tag"`
MinRole string `json:"min_role"`
Team string `json:"team,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
IdentityRole is one role tag on an owner's allow list. MinRole is the least caller role (runner or admin) that may create a sandbox with it.
type IdentityRoleList ¶ added in v0.6.12
type IdentityRoleList struct {
Roles []IdentityRole `json:"roles"`
// NextCursor, when set, is the cursor for the next page.
NextCursor string `json:"next_cursor,omitempty"`
}
IdentityRoleList is the body of GET /v1/identity/roles.
type IdentityRoleRequest ¶ added in v0.6.12
type IdentityRoleRequest struct {
MinRole string `json:"min_role"`
}
IdentityRoleRequest is the body of PUT /v1/identity/roles/{tag}.
type ImageDistributionMetadata ¶ added in v0.2.1
type ImageDistributionMetadata struct {
Mode string `json:"mode,omitempty"`
Digest string `json:"digest,omitempty"`
RegistryRef string `json:"registry_ref,omitempty"`
VerifiedAt *time.Time `json:"verified_at,omitempty"`
}
ImageDistributionMetadata describes whether an image can be materialized on an arbitrary worker. It is deliberately metadata only: registries, AOCR, and cache services remain pluggable deployment choices outside the core daemon.
func (ImageDistributionMetadata) IsZero ¶ added in v0.2.1
func (m ImageDistributionMetadata) IsZero() bool
type IngressTarget ¶ added in v0.3.1
type IngressTarget struct {
Hostname string `json:"hostname,omitempty"`
IPs []string `json:"ips,omitempty"`
Source string `json:"source"`
}
IngressTarget is the cluster-published address(es) that DNS for a custom domain must point at. The shape depends on how the operator deployed AerolVM:
- Source="hostname" — the cluster advertises a stable hostname (e.g. ingress.example.com that itself resolves to a load balancer). DNS for custom domains is a CNAME to this hostname.
- Source="ips" — the cluster advertises one or more raw IPs. DNS for custom domains is one A (and AAAA for IPv6) record per IP.
- Source="mixed" — some ingress nodes gossip a hostname, others gossip raw IPs. Callers should prefer the hostname (smaller record set, survives IP changes) but render both so apex domains without CNAME-flattening can still be configured.
- Source="unknown" — no ingress node has gossiped a public address yet. This is the boot-time / mis-configured case; callers should treat the target as unusable rather than guessing.
The struct mirrors what GET /v1/ingress/dns returns. SDK helpers wrap it in language-idiomatic types but the JSON shape is shared.
type JSBundle ¶ added in v0.5.6
type JSBundle struct {
Digest string `json:"digest"`
ModuleRef string `json:"module_ref"`
Name string `json:"name,omitempty"`
MainModule string `json:"main_module"`
SizeBytes int64 `json:"size_bytes"`
}
JSBundle is the catalogue view of a stored bundle (POST/GET /v1/js-bundles). ModuleRef is the "sha256:<digest>" form a create request passes as module_ref; Name, when set, is the alias that also resolves on create.
type Lifecycle ¶
type Lifecycle struct {
StopIfIdleFor time.Duration `json:"stop_if_idle_for,omitempty"`
DestroyIfIdleFor time.Duration `json:"destroy_if_idle_for,omitempty"`
StopAtAge time.Duration `json:"stop_at_age,omitempty"`
DestroyAtAge time.Duration `json:"destroy_at_age,omitempty"`
// Serverless opts the sandbox into HTTP-wake behavior: stops driven by
// lifecycle (idle timer / age) or involuntary exits arm the sandbox to
// be transparently restarted on the next inbound HTTP request. Manual
// StopSandbox calls clear the arming so the sandbox stays down.
// Requires StopIfIdleFor to be set explicitly; there is no implicit
// default — see Validate.
Serverless bool `json:"serverless,omitempty"`
// RestartOnFailure starts the sandbox again after it crashes or its init
// is OOM-killed, with a backoff from 5 s to 5 min that resets after 10
// minutes of running fine (plans/agent-sandbox-feature-parity.md L1).
// Off by default. Docker and containerd (gVisor included) only: their
// die events are the failure signal; the service refuses it for other
// runtimes. Not a timer, so it does not count for IsZero: a sandbox
// with only this flag still gets the server's default timers.
RestartOnFailure bool `json:"restart_on_failure,omitempty"`
// DestroyAfterExitFor destroys the sandbox this long after its main
// program (the container command toolboxd runs) ends (L5, owner row
// P2). The lifecycle sweep reads the program's state from toolboxd's
// /health and stores the exit, so a daemon restart keeps the timer.
// Zero is off. WASM and isolate sandboxes have no main program and
// refuse it.
DestroyAfterExitFor time.Duration `json:"destroy_after_exit_for,omitempty"`
// DestroyAt is an input-only clock time (RFC 3339) to destroy the
// sandbox at (L6). ResolveDestroyAt turns it into DestroyAtAge measured
// from the sandbox's creation, so only the age is stored, replicated and
// returned; Validate refuses one left unconverted.
DestroyAt *time.Time `json:"destroy_at,omitempty"`
}
Lifecycle declares automatic stop/destroy timers for a sandbox. Each field is a duration; zero means "disabled" for that axis. Idle triggers measure time since LastActiveAt (i.e. since the last toolbox/exec/SSH activity). Age triggers measure time since CreatedAt — they are absolute deadlines that do not reset on Stop+Start, so a "destroy at 24h" sandbox stays destroyable even if the user restarts it minutes before the deadline.
Multiple fields can be set; whichever timer fires first wins. Destroy supersedes Stop for the same trigger axis. The lifecycle sweep runs every minute, so deadlines are honored to roughly that resolution.
func (Lifecycle) IsZero ¶
IsZero reports whether every timer is disabled and the sandbox is not serverless: a sandbox with no lifecycle of its own, which the server-wide defaults apply to. RestartOnFailure is not a timer and does not count.
func (*Lifecycle) ResolveDestroyAt ¶ added in v0.6.12
ResolveDestroyAt turns DestroyAt into DestroyAtAge, the age the sandbox created at createdAt has at that time, and clears DestroyAt. now is the current time: a DestroyAt that is not after it is refused, as is one set together with DestroyAtAge (which would win is unclear) and one more than MaxLifecycleDuration after createdAt. A nil DestroyAt is a no-op.
func (Lifecycle) Validate ¶
Validate enforces the invariants we rely on at sweep time:
- no negative durations (zero means disabled, negative is meaningless),
- each field <= MaxLifecycleDuration,
- if both stop and destroy of the same trigger are set, destroy must not fire before stop. Without this we could surprise a user who set "stop at 2h, destroy at 1h" by skipping the stop entirely.
func (Lifecycle) ValidateWithBypassFloor ¶ added in v0.2.4
ValidateWithBypassFloor runs Validate then additionally enforces the activity-floor constraint that HTTP-wake direct-route bypass imposes on serverless sandboxes: the netstats poller is the per-sandbox activity signal in the bypass shape, and the idle sweep needs at least one full netstats tick + one reconcile pass to observe "no traffic" without false-stopping a busy sandbox. The floor is 2 × pollInterval + reconcileInterval; sub-floor StopIfIdleFor values would let the sweep fire between netstats ticks and stop a sandbox that was actively serving the whole time.
Callers in the wake-aware (non-bypass) shape must use Validate() directly — the floor does not apply when every request still bumps LastActiveAt through sandboxd's ingress proxy. See plans/warm-direct-route-bypass.md D4.
type MountSpec ¶
type MountSpec struct {
Type MountType `json:"type"`
Target string `json:"target"`
Source string `json:"source"`
Options map[string]string `json:"options,omitempty"`
Credentials map[string]string `json:"credentials,omitempty"`
ReadOnly bool `json:"read_only,omitempty"`
}
MountSpec describes a single external-storage mount the user wants to be available inside their sandbox. Credentials are encrypted at rest in the daemon's database, materialized only on the host as the FUSE process needs them, and never returned by any read API.
func (*MountSpec) Redact ¶
func (m *MountSpec) Redact() MountSpecRedacted
Redact strips credentials, returning the user-safe view.
func (*MountSpec) Validate ¶
Validate checks the spec against the daemon's mount policy. toolboxMountPath is the path the toolbox binary is bind-mounted to inside the container; we refuse to let the user shadow it.
func (*MountSpec) ValidateSecretsPlacement ¶ added in v0.6.1
ValidateSecretsPlacement refuses credential-shaped names in the fields that are stored and replicated unsealed. See mountCredentialNameMarkers.
type MountSpecFile ¶
type MountSpecFile struct {
Mounts []MountSpec `json:"mounts"`
}
MountSpecFile is the JSON envelope used to (de)serialize the encrypted blob of a sandbox's mount specs in the daemon's database. Kept as a struct rather than a bare slice so future fields (version, key id) can be added without a migration.
type MountSpecRedacted ¶
type MountSpecRedacted struct {
Type MountType `json:"type"`
Target string `json:"target"`
Source string `json:"source"`
Options map[string]string `json:"options,omitempty"`
ReadOnly bool `json:"read_only,omitempty"`
HasCredentials bool `json:"has_credentials"`
}
MountSpecRedacted is the read-only view returned by the API. It mirrors MountSpec but strips credentials.
func RedactMounts ¶
func RedactMounts(mounts []MountSpec) []MountSpecRedacted
RedactMounts returns the read-only API view for a slice of mounts.
type MountType ¶
type MountType string
MountType identifies the storage backend the user wants mounted inside their container. The daemon runs the mount tool on the host (in a per-sandbox directory) and bind-mounts that directory into the container, so credentials never enter the container and the user's image needs no mount tooling.
type NetworkLearned ¶ added in v0.6.6
type NetworkLearned struct {
Mode string `json:"mode"`
Truncated bool `json:"truncated"`
Entries []NetworkLearnedEntry `json:"entries"`
CIDRs []string `json:"cidrs"`
SuggestedAllowOut []string `json:"suggested_allow_out"`
SuggestedProfile *EgressProfileRequest `json:"suggested_profile"`
}
NetworkLearned is GET /v1/sandboxes/{id}/network/learned: what a sandbox reached while in learn mode, and the allow list that would have allowed it. Exactly one of SuggestedAllowOut and SuggestedProfile holds the list: the inline list when it fits 64 hostnames, a profile body otherwise. Truncated means recording stopped at the cap.
type NetworkLearnedEntry ¶ added in v0.6.6
type NetworkLearnedEntry struct {
Host string `json:"host"`
Ports []uint16 `json:"ports"`
FirstSeen time.Time `json:"first_seen"`
LastSeen time.Time `json:"last_seen"`
Hits uint64 `json:"hits"`
}
NetworkLearnedEntry is one destination a learn-mode sandbox reached.
type NetworkPolicy ¶ added in v0.6.6
type NetworkPolicy struct {
NetworkBlockAll bool `json:"network_block_all"`
NetworkAllowOut []string `json:"network_allow_out"`
NetworkDenyOut []string `json:"network_deny_out"`
EgressProfiles []string `json:"egress_profiles"`
// NetworkEgressMode is "enforce" or "learn".
NetworkEgressMode string `json:"network_egress_mode"`
NetworkEgressRules []EgressRule `json:"network_egress_rules,omitempty"`
// EffectiveHostnameCount counts the hostname entries in force: inline
// plus every referenced profile's (at most 1024).
EffectiveHostnameCount int `json:"effective_hostname_count"`
EgressStatus string `json:"egress_status,omitempty"`
}
NetworkPolicy is the effective egress policy a PUT leaves in force. A 2xx means it is stored, replicated in a cluster, and live on a running sandbox. EgressStatus is set for a container sandbox in gateway mode, as on GET; "unenforced" there means the node's host firewall is off and the policy was accepted only under SB_ALLOW_UNENFORCED_NETWORK_POLICY.
type NetworkPolicyCheckRequest ¶ added in v0.6.6
type NetworkPolicyCheckRequest struct {
NetworkBlockAll bool `json:"network_block_all,omitempty"`
NetworkAllowOut []string `json:"network_allow_out,omitempty"`
NetworkDenyOut []string `json:"network_deny_out,omitempty"`
Destination string `json:"destination"`
}
NetworkPolicyCheckRequest is POST /v1/network/policy/check: would a sandbox created with these egress fields reach Destination? Destination is "host", "host:port", "IP" or "IP:port"; a bare host is checked as the web ports. No sandbox is involved (plans/egress-domain-filtering.md P2-9, CEO D5).
type NetworkPolicyCheckResponse ¶ added in v0.6.6
type NetworkPolicyCheckResponse struct {
Allowed bool `json:"allowed"`
MatchedRule string `json:"matched_rule"`
DefaultVerdict string `json:"default_verdict"`
OutsideCeiling string `json:"outside_ceiling,omitempty"`
}
NetworkPolicyCheckResponse answers a policy check. MatchedRule is the entry that decided, "" when the default verdict did. The check does not resolve DNS, so deny CIDRs that a hostname's address would hit at connect time are not evaluated. OutsideCeiling names the first allow entry outside this deployment's operator ceiling (a create with it would get 400).
type NetworkPolicyRequest ¶ added in v0.6.6
type NetworkPolicyRequest struct {
NetworkBlockAll bool `json:"network_block_all"`
NetworkAllowOut []string `json:"network_allow_out"`
NetworkDenyOut []string `json:"network_deny_out"`
EgressProfiles []string `json:"egress_profiles"`
// NetworkEgressMode is "enforce" (empty means the same) or "learn".
NetworkEgressMode string `json:"network_egress_mode,omitempty"`
// NetworkEgressRules replaces the method and path rules. Adding an
// inspect rule needs a sandbox created with one (409 otherwise).
NetworkEgressRules []EgressRule `json:"network_egress_rules,omitempty"`
}
UpdateNetworkLimitsRequest is the body for PATCH /v1/sandboxes/{id}/network/limits. NetworkPolicyRequest is PUT /v1/sandboxes/{id}/network/policy (plans/egress-domain-filtering.md §5.8): a full replace of the sandbox's egress policy, with the same fields and rules as create. Sending the same body twice is a no-op.
type NetworkUsage ¶ added in v0.1.7
type NetworkUsage struct {
SandboxID string `json:"sandbox_id"`
BytesIn int64 `json:"bytes_in"`
BytesOut int64 `json:"bytes_out"`
BytesInLimit int64 `json:"bytes_in_limit"`
BytesOutLimit int64 `json:"bytes_out_limit"`
QuotaExceeded bool `json:"quota_exceeded"`
QuotaExceededAt *time.Time `json:"quota_exceeded_at,omitempty"`
// LastSampledAt is omitted until the netstats poller has produced at
// least one sample. Pointer + omitempty so we don't serialize the zero
// time as "0001-01-01T00:00:00Z" before the first tick.
LastSampledAt *time.Time `json:"last_sampled_at,omitempty"`
}
NetworkUsage is the response shape for GET /v1/sandboxes/{id}/network/usage. BytesInLimit / BytesOutLimit zero means unlimited.
type PendingVolumeDeletion ¶ added in v0.5.4
type PendingVolumeDeletion struct {
VolumeID string `json:"volume_id"`
Tenant string `json:"tenant"`
Name string `json:"name"`
Backend string `json:"backend"`
Source string `json:"source"`
CreatedAt time.Time `json:"created_at"`
}
PendingVolumeDeletion is a durable cleanup ledger row. Daytona delete removes the user-visible metadata row only after this record exists, so a backend cleanup failure never leaves remote data without coordinates to reconcile.
type PlacementRule ¶ added in v0.6.12
type PlacementRule struct {
Zone string `json:"zone,omitempty"`
Labels map[string]string `json:"labels,omitempty"`
}
PlacementRule says where a sandbox may run. Every given key must match a node's label exactly (AND); there are no operators in this version (owner decision P1.3). Zone is shorthand for the label "zone".
func NormalizePlacementRule ¶ added in v0.6.12
func NormalizePlacementRule(r *PlacementRule) (*PlacementRule, error)
NormalizePlacementRule validates a create's rule and returns its canonical form: the zone in Zone (moved there from labels["zone"] if given that way) and every other label in Labels. An empty rule normalizes to nil, so a create that sends "placement": {} places exactly like one that sends nothing and carries no rule in its replicated spec.
func (*PlacementRule) RequiredLabels ¶ added in v0.6.12
func (r *PlacementRule) RequiredLabels() map[string]string
RequiredLabels is the label set a node must carry to run the sandbox: the rule's labels plus its zone under PlacementZoneLabel. nil for no rule.
type PlatformVolumeMount ¶ added in v0.5.4
type PlatformVolumeMount struct {
Name string `json:"name"`
Path string `json:"path"`
ReadOnly bool `json:"read_only,omitempty"`
// DeleteWithSandbox makes a volume created by this reference go away,
// files and record, once the last sandbox attached to it is destroyed
// (plans/agent-sandbox-feature-parity.md V1). It is a property of the
// volume, fixed when the volume is made: a reference to an existing volume
// must name the same value or the create is refused
// (ErrPlatformVolumeConflict), so nobody deletes a volume they meant to
// keep, or keeps one they meant to delete.
DeleteWithSandbox bool `json:"delete_with_sandbox,omitempty"`
}
PlatformVolumeMount is a request to attach a named, operator-backed persistent volume at Path inside the sandbox. Name is sanitized and scoped to the caller's tenant by the service; the user supplies nothing else (no bucket, no credentials). See plans/e2b-volume-mounts.md.
type PushWasmModuleOptions ¶ added in v0.5.3
type PushWasmModuleOptions struct {
Name string
Tag string
Module []byte
RegistryUsername string
RegistryToken string
}
PushWasmModuleOptions is the SDK-side input for a BYO module upload. The wire form is the raw .wasm body plus name/tag query params and the caller's registry credentials as headers; this struct is the Go SDK's ergonomic shape.
type PushWasmModuleResponse ¶ added in v0.5.3
type PushWasmModuleResponse struct {
ModuleRef string `json:"module_ref"`
Digest string `json:"digest"`
SizeBytes int64 `json:"size_bytes"`
}
PushWasmModuleResponse is returned by POST /v1/wasm-modules/push after the daemon validates a BYO .wasm upload and forwards it to the registry. The daemon stores nothing; the caller references ModuleRef (an oci:// ref) on a subsequent create.
type RegistryAuth ¶
type ResizeSandboxRequest ¶
type RevokeSandboxTokensResponse ¶ added in v0.6.12
type RevokeSandboxTokensResponse struct {
SandboxID string `json:"sandbox_id"`
TokensNotBefore time.Time `json:"tokens_not_before"`
}
RevokeSandboxTokensResponse is the 200 body of POST /v1/sandboxes/{id}/tokens/revoke. Every token for the sandbox issued before TokensNotBefore is refused from now on; a token issued after the call works.
type Sandbox ¶
type Sandbox struct {
ID string `json:"id"`
Image string `json:"image"`
Status SandboxStatus `json:"status"`
PublicURL string `json:"public_url"`
ContainerID string `json:"container_id,omitempty"`
ContainerIP string `json:"container_ip,omitempty"`
CPU float64 `json:"cpu"`
MemoryMB int `json:"memory_mb"`
DiskGB int `json:"disk_gb"`
OSUser string `json:"os_user"`
Env map[string]string `json:"env,omitempty"`
NetworkBlockAll bool `json:"network_block_all"`
ToolboxEnabled bool `json:"toolbox_enabled"`
ToolboxToken string `json:"-"`
// CreateRequestDigest is the keyed digest of the request an
// Idempotency-Key create was made with (CreateSandboxRequest's current
// one). Stored in sandbox_create_digests, never on the wire.
CreateRequestDigest string `json:"-"`
// AuditIncarnationID scopes retained audit evidence to this exact sandbox
// lifecycle. It is persisted in sandbox_audit_acl, not on the sandbox row,
// and never crosses the public API or Raft recovery payload.
AuditIncarnationID string `json:"-"`
// ToolboxTokenSealed is the at-rest representation used by the store when
// toolbox-token sealing is enabled. It never crosses API or Raft payloads.
ToolboxTokenSealed []byte `json:"-"`
SSHPublicKey string `json:"ssh_public_key,omitempty"`
ExposedPorts []ExposedPort `json:"exposed_ports,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
LastActiveAt time.Time `json:"last_active_at"`
LastError string `json:"last_error,omitempty"`
// StatusReason says why the sandbox is in its current status, one of the
// StatusReason* values. Empty when a call simply created or started it.
// The store writes it only with a status change (or through a targeted
// update), so a whole-row write from an older read cannot undo it.
StatusReason string `json:"status_reason,omitempty"`
// ExitCode is the exit code behind out_of_memory, crashed,
// program_exited and restarted; nil for every other reason.
ExitCode *int `json:"exit_code,omitempty"`
// RestartFailures, RestartAt and LastRestartedAt are the restart-on-
// failure backoff state (L1): consecutive failures, when the pending
// restart is due (nil when none is pending), and when the last restart
// ran. Stored so a daemon restart keeps the backoff; never on the wire.
RestartFailures int `json:"-"`
RestartAt *time.Time `json:"-"`
LastRestartedAt *time.Time `json:"-"`
// ProgramExitedAt is when the main program ended, as the lifecycle
// sweep recorded it from toolboxd (L5); nil while it runs, and cleared
// when the sandbox starts again. destroy_after_exit_for counts from it.
ProgramExitedAt *time.Time `json:"-"`
// TokensNotBefore is the unix second before which a sandbox token for
// this sandbox is refused (pkg/sandboxtoken): set by a revoke and when
// a row is created, 0 when neither ever happened. It lives only in the
// owner node's row, never on the wire or in Raft.
TokensNotBefore int64 `json:"-"`
// RunGeneration says which run of the sandbox this row was read in: the
// store adds one each time the sandbox starts. A main-program exit is
// stored only for the run it was read from. Never on the wire.
RunGeneration int64 `json:"-"`
// RollbackPending marks a sandbox whose create the client was told
// failed but whose rollback could not finish (a cluster create whose
// rollback destroy needed a Raft leader that was not there). The
// ownership replay never publishes such a row and reconcile keeps
// destroying it. Set once, by the rollback; never on the wire or in Raft.
RollbackPending bool `json:"-"`
ContainerCommand []string `json:"container_command,omitempty"`
Lifecycle Lifecycle `json:"lifecycle"`
Failover *Failover `json:"failover,omitempty"`
// FailoverReady is set on Get/List when failover.policy=recreate: true iff
// the secret holder count meets HA (owner + ≥1 backup) or the recipient
// set is single-node (len≤1). Omitted for non-recreate sandboxes.
FailoverReady *bool `json:"failover_ready,omitempty"`
// Name is the optional identifier set at create time, unique per owner
// (see CreateSandboxRequest.Name). Empty when the sandbox was created
// without one (the common path on /v1 today).
Name string `json:"name,omitempty"`
// Tags is the optional key/value bag set at create time. Facades use it
// for label-style metadata (Daytona labels, E2B metadata) but the field
// is facade-agnostic — anything that wants attribute-tagged sandboxes
// can write here.
Tags map[string]string `json:"tags,omitempty"`
// Runtime is the container runtime this sandbox uses (one of "docker",
// "gvisor", or "kata"). Pre-migration rows carry "" and resolve to the
// host default at start time; new sandboxes always store the resolved
// value so the choice cannot drift across host restarts.
Runtime string `json:"runtime"`
// Engine is the host-level container engine that owns this sandbox's
// lifecycle (dockerd or native containerd). Pre-migration rows carry ""
// and resolve to docker so flipping SB_CONTAINER_ENGINE does not strand
// existing sandboxes on the wrong driver.
Engine string `json:"engine,omitempty"`
// GPUs is the GPU configuration this sandbox was created with. Nil means
// no GPU was requested.
GPUs *GPURequest `json:"gpus,omitempty"`
// RegistryAuthSealed is the AES-GCM-encrypted JSON of the original
// RegistryAuth supplied at create time, or nil/empty when the sandbox
// pulled from a public registry. Persisted so cluster failover can hand
// the credentials back to the new owner's docker pull. Never serialized
// over the API — it is internal store ↔ service plumbing.
RegistryAuthSealed []byte `json:"-"`
// RegistryAuth is the transient, UNSEALED registry credential. It is never
// persisted (no column) nor serialized (json:"-"); the service unseals
// RegistryAuthSealed into it in-memory right before a WASM start/rehydrate
// so a failover peer can re-pull a private oci:// module under the tenant's
// identity (codex C4). Nil on the create/public path.
RegistryAuth *RegistryAuth `json:"-"`
// NetworkBytesIn / NetworkBytesOut are cumulative byte counters
// maintained by the netstats poller. They survive container restarts —
// a new veth resets in-memory baseline math but the persisted total is
// preserved.
NetworkBytesIn int64 `json:"network_bytes_in"`
NetworkBytesOut int64 `json:"network_bytes_out"`
// NetworkBytesInLimit / NetworkBytesOutLimit are the caps the sandbox was
// created or patched with. Zero = unlimited.
NetworkBytesInLimit int64 `json:"network_bytes_in_limit"`
NetworkBytesOutLimit int64 `json:"network_bytes_out_limit"`
// NetworkAllowOut / NetworkDenyOut are the egress policy the sandbox was
// created with, persisted so the start and reconcile paths can reinstall
// the rules after a restart (parity with NetworkBlockAll). Both may be set:
// allow-wins precedence (plans/egress-domain-filtering.md D4).
NetworkAllowOut []string `json:"network_allow_out,omitempty"`
NetworkDenyOut []string `json:"network_deny_out,omitempty"`
// EgressProfiles are the profiles this sandbox references, and
// EgressProfilesApplied the generation of each that is live, so a caller
// can see when a profile update has reached it. On the stored row
// NetworkAllowOut is the effective list (inline entries plus every
// profile's), which is what enforcement reads; API responses show the
// inline list instead.
EgressProfiles []string `json:"egress_profiles,omitempty"`
EgressProfilesApplied []EgressProfileRef `json:"egress_profiles_applied,omitempty"`
// NetworkEgressMode is "learn" for a sandbox recording its egress, and
// empty (enforce) otherwise.
NetworkEgressMode string `json:"network_egress_mode,omitempty"`
// NetworkEgressRules are the sandbox's method and path rules (P3-1).
NetworkEgressRules []EgressRule `json:"network_egress_rules,omitempty"`
// EgressStatus is the hostname-egress state on GET for a sandbox whose
// policy needs the egress gateway: "active", "held" (attach failed or the
// stored policy is invalid; no egress until it attaches) or
// "unavailable" (the gateway is down or lost its table). "unenforced" is
// any egress policy on a runtime whose host firewall is off on this node
// (SB_ENABLE_NETWORK_RULES=false): nothing filters the sandbox's traffic.
// Empty for every other sandbox, and on list responses
// (plans/egress-domain-filtering.md D16). Response-only: never stored.
EgressStatus string `json:"egress_status,omitempty"`
// AllowPublicTraffic is whether the sandbox currently has a public route:
// only true is public. It starts as the create-time flag and the first
// ExposePort sets it to true (enableSandboxPublicTraffic), so nil and
// false behave the same. Persisted so the state survives restarts.
AllowPublicTraffic *bool `json:"allow_public_traffic,omitempty"`
// MaskRequestHost mirrors the create-time flag: the value the ingress layer
// rewrites the upstream Host header to for exposed HTTP ports. Persisted so
// the direct Caddy route (baked at install time) and the serverless wake
// proxy (read per request) agree on the same value after a restart.
MaskRequestHost string `json:"mask_request_host,omitempty"`
// NetworkQuotaExceeded reflects whether either lifetime byte counter has
// crossed its limit. The reconcile loop installs DROP rules when this is
// true; clearing requires raising the limit (or zeroing it for unlimited).
NetworkQuotaExceeded bool `json:"network_quota_exceeded"`
// NetworkQuotaExceededAt is the wall-clock time the limit was first
// observed crossed. Nil while under quota.
NetworkQuotaExceededAt *time.Time `json:"network_quota_exceeded_at,omitempty"`
// AutoImportPending is set by the post-pull auto-import path when the
// AOCR ImportAPI call failed. A background reconciler walks rows with
// this flag and re-tries the import; once the import succeeds the flag
// is cleared and the create spec's ImageDistributionMode flips to
// `aocr_imported`. The flag is local-node bookkeeping — it is not
// replicated via Raft, since each owner gets one opportunistic shot
// at the import per pull.
AutoImportPending bool `json:"-"`
// WakeArmed indicates the sandbox is currently in the stopped state
// because of a lifecycle-driven idle timeout or an involuntary exit
// while Lifecycle.Serverless was true. Wake-aware control-plane proxies
// transparently start the sandbox on the next inbound request when this
// is set. Cleared on manual StopSandbox and after a successful wake.
// Internal-only bookkeeping; never exposed over the wire.
WakeArmed bool `json:"-"`
// CustomDomains carries the per-hostname rows for any operator-attached
// public hostnames. Status is server-managed (pending_dns → issuing →
// ready / failed). Nil when the sandbox has no custom domains.
CustomDomains []CustomDomain `json:"custom_domains,omitempty"`
// TemplateID records the Firecracker template this sandbox was created
// from, when one was supplied. Empty for Docker sandboxes and for
// Firecracker sandboxes built from an ad-hoc Image. The Phase 2 template
// GC reads this column via IsTemplateReferenced to decide whether a
// template is still in use; the firecracker driver also reads it on
// recreate so failover stays on the same rootfs.
TemplateID string `json:"template_id,omitempty"`
// OverlaySizeGB is the size of the per-sandbox writable overlay
// drive (virtio-blk at /dev/vdb), echoed back from the create
// request so callers can confirm what was provisioned. Zero means
// no overlay was attached. Persisted because the runtime cleanup
// path needs to know whether overlay.ext4 was allocated in the
// per-sandbox runDir.
OverlaySizeGB int `json:"overlay_size_gb,omitempty"`
// OwnerRef is the account key this sandbox is attributed to, resolved by
// the optional fleet control plane from a user token at create time.
// Empty means operator/PAT-created (the only possibility on the
// open-source build). Owner scoping uses it to fence user tokens to their
// own sandboxes; the PAT bypasses scoping. Never exposed over the wire —
// it is internal attribution, not caller-facing.
OwnerRef string `json:"-"`
// FleetSuspended marks a sandbox that was stopped by a fleet standing
// directive (suspend), as opposed to a user/operator stop. Recovery
// restarts exactly the sandboxes carrying this marker, then clears it.
// Internal-only bookkeeping.
FleetSuspended bool `json:"-"`
// Durability is the survival class this sandbox was created with. Empty
// on pre-migration rows resolves to passivatable at read time.
Durability string `json:"durability,omitempty"`
// ModuleRef is the WASM module reference when runtime=wasm.
ModuleRef string `json:"module_ref,omitempty"`
// ModuleDigest is the sha256 hex digest of the resolved .wasm bytes.
ModuleDigest string `json:"module_digest,omitempty"`
// CheckpointPath points at a local §4.8.1 mem.snap directory when status
// is passivated. Internal-only; not exposed over the wire.
CheckpointPath string `json:"-"`
// CloneGeneration is the §4.8 fencing token for checkpoint/clone writes.
CloneGeneration string `json:"-"`
// WasmRegistryRef is the AOCR ref for the last pushed durable checkpoint.
WasmRegistryRef string `json:"-"`
// WasmRegistryDigest is the manifest digest from the last AOCR push.
WasmRegistryDigest string `json:"-"`
// TenantID is the isolate-group key this sandbox was created under
// (runtime=isolate only; empty for other runtimes and when the group key
// fell back to the authenticated identity). Persisted so restart
// reconcile and cluster failover rebuild the same per-tenant group
// process the security posture is stated in terms of
// (plans/isolate-runtime.md §2.1).
TenantID string `json:"tenant_id,omitempty"`
// Identity is the sandbox's cloud identity, when it was created with
// one (plans/sandbox-cloud-identity.md). It never carries the token.
Identity *SandboxIdentity `json:"identity,omitempty"`
}
type SandboxCompatState ¶ added in v0.1.7
type SandboxCompatState struct {
SandboxID string
Facade string
StateJSON string
CreatedAt time.Time
UpdatedAt time.Time
}
SandboxCompatState carries facade-private state that has no native meaning on its own — opaque wire-shape sugar like Daytona's `target` or E2B's `template_id`. The store treats StateJSON as a byte string; facades own the schema inside it.
type SandboxIdentity ¶ added in v0.6.12
type SandboxIdentity struct {
RoleTag string `json:"role_tag"`
Audience string `json:"audience"`
Subject string `json:"subject"`
AWSRoleARN string `json:"aws_role_arn,omitempty"`
AzureClientID string `json:"azure_client_id,omitempty"`
AzureTenantID string `json:"azure_tenant_id,omitempty"`
// TokenFile is where the token is inside the sandbox.
TokenFile string `json:"token_file"`
// TokenExpiresAt is when the token now in the sandbox expires; absent
// until the first one arrives.
TokenExpiresAt *time.Time `json:"token_expires_at,omitempty"`
// LastError is why the last token push failed; empty after a success.
LastError string `json:"last_error,omitempty"`
}
SandboxIdentity is a sandbox's identity as GET shows it.
type SandboxRuntimeState ¶
type SandboxRuntimeState struct {
SandboxID string
ContainerID string
ContainerIP string
Status SandboxStatus
// WASM-only: resolved module metadata returned by the wasm driver on create.
ModuleRef string
ModuleDigest string
// ModulePath / ModuleSizeBytes are the resolved local artifact location and
// size. The service persists them onto the catalogue row so the row is
// resolvable by catalogue id instead of a misleading empty-path "ready" row
// (codex P1). Empty when resolution did not yield a local path.
ModulePath string
ModuleSizeBytes int64
// AdoptedParkID is non-empty when Create adopted a warm-pool slot; the
// service uses it to release the park capacity reservation (§4).
AdoptedParkID string
// StartedAt is when the run a start began, on the clock the engine's
// exit events are stamped with: Docker's State.StartedAt, or the
// containerd driver's host clock just before it makes the new task. The
// service tells an exit event of an earlier run by it (run_starts.go),
// so it must be no later than anything the new run can report, and no
// earlier than the exit of the run before. Zero when the runtime does
// not say (Firecracker, WASM and isolate send no exit events).
StartedAt time.Time
}
SandboxRuntimeState is the runtime view of a sandbox returned by the container runtime layer (Docker today, gVisor/native runsc tomorrow). It carries only what the service needs to reconcile and route — anything else belongs on models.Sandbox or stays in the runtime implementation.
type SandboxSnapshot ¶ added in v0.1.7
type SandboxSnapshot struct {
Name string `json:"name"`
Image string `json:"image"`
ImageID string `json:"image_id,omitempty"`
SourceSandboxID string `json:"source_sandbox_id"`
CreatedAt time.Time `json:"created_at"`
// Image distribution metadata is the snapshot-level placement contract.
// Local-only snapshots may be started only on the node whose Docker image
// store contains Image; external_registry/aocr snapshots may be placed on
// any worker that can pull RegistryRef/Image.
ImageDistributionMode string `json:"image_distribution_mode,omitempty"`
ImageDigest string `json:"image_digest,omitempty"`
ImageRegistryRef string `json:"image_registry_ref,omitempty"`
ImageVerifiedAt *time.Time `json:"image_verified_at,omitempty"`
// Entrypoint is the optional command override the caller wants the
// runtime to use when starting a sandbox from this snapshot.
Entrypoint []string `json:"entrypoint,omitempty"`
// RegionID echoes the region the caller requested when creating the
// snapshot. The facade persists this verbatim for read-back; region
// routing itself is not yet wired through the daemon.
RegionID string `json:"region_id,omitempty"`
// CPU / MemoryMB / DiskGB / GPU mirror the resource hints the caller
// supplied on create — surfaced back to clients that poll the snapshot
// after creation.
CPU float64 `json:"cpu,omitempty"`
MemoryMB int `json:"memory_mb,omitempty"`
DiskGB int `json:"disk_gb,omitempty"`
GPU float64 `json:"gpu,omitempty"`
// PushState reflects the AOCR-push lifecycle for this snapshot. See the
// SnapshotPushState* constants above. When push is disabled (or the image
// already lives in a remote registry) this is "active" from the moment
// the row is inserted, matching pre-feature behavior. Otherwise it
// transitions pending → pushing → active|error, and the cluster placement
// path treats the snapshot as locally-pinned until it hits "active".
PushState string `json:"push_state,omitempty"`
// PushError is populated only when PushState is "error" — the last error
// the reconciler saw, surfaced to the Daytona facade's errorReason field.
PushError string `json:"push_error,omitempty"`
// OwnerRef is the account the snapshot belongs to, with the same meaning
// and scoping rule as Sandbox.OwnerRef. It lives on the snapshot because
// a snapshot outlives the sandbox it was taken from: once the source is
// destroyed there is nothing else left to check ownership against. Never
// exposed over the wire.
OwnerRef string `json:"-"`
}
SandboxSnapshot is the persisted metadata for a committed sandbox image. Image is the reusable image reference; ImageID is the content-addressed Docker image ID returned by the runtime after the commit succeeds.
Two creation paths populate this row:
- Snapshot-of-a-running-sandbox (legacy) — SourceSandboxID is set, resource fields stay zero, the image is committed by the runtime.
- Snapshot-from-image (Daytona facade) — SourceSandboxID is empty, resource fields and Entrypoint reflect the caller's create payload, and Image is either the caller-supplied imageName or a freshly built tag from a buildInfo Dockerfile.
func (*SandboxSnapshot) ApplyImageDistribution ¶ added in v0.2.1
func (s *SandboxSnapshot) ApplyImageDistribution(meta ImageDistributionMetadata)
func (SandboxSnapshot) ImageDistribution ¶ added in v0.2.1
func (s SandboxSnapshot) ImageDistribution() ImageDistributionMetadata
type SandboxStatus ¶
type SandboxStatus string
const ( SandboxStatusCreating SandboxStatus = "creating" SandboxStatusStarted SandboxStatus = "started" SandboxStatusStopped SandboxStatus = "stopped" SandboxStatusDestroyed SandboxStatus = "destroyed" SandboxStatusError SandboxStatus = "error" // SandboxStatusPassivated marks a WASM sandbox checkpointed to disk, // awaiting rehydrate after daemon restart (plans/wasm-runtime.md §4.3). SandboxStatusPassivated SandboxStatus = "passivated" // SandboxStatusAwaitingRuntime marks a passivated/durable WASM row found // when EnableWasm=false — reconcile holds the row until WASM is re-enabled. SandboxStatusAwaitingRuntime SandboxStatus = "awaiting_runtime" // SandboxStatusPassivateFailed marks a WASM sandbox whose drain checkpoint // timed out or failed; durability is preserved for operator inspection. SandboxStatusPassivateFailed SandboxStatus = "passivate_failed" )
Sandbox lifecycle states.
SandboxStatusDestroyed marks a sandbox whose container is gone — either because the user called DELETE /sandboxes/{id}, or because the container died out-of-band and the event monitor noticed. The status exists as a transient marker only: the API-driven destroy path deletes the row in the same call, and the reconcile loop deletes any row whose container has gone missing on its next pass. Destroyed rows are not retained — keeping them around would also keep their host_port reservations in exposed_ports, slowly exhausting the L4 TCP allocator pool over the daemon's lifetime.
type SandboxToken ¶ added in v0.6.12
type SandboxToken struct {
Token string `json:"token"`
// TokenID is the token's public id (stk_…): what audit records and
// logs name instead of the token.
TokenID string `json:"token_id"`
SandboxID string `json:"sandbox_id"`
Port int `json:"port,omitempty"`
PathPrefix string `json:"path_prefix,omitempty"`
Methods []string `json:"methods,omitempty"`
ExpiresAt time.Time `json:"expires_at"`
}
SandboxToken is the 201 body of POST /v1/sandboxes/{id}/tokens. Token is shown in this answer only: the server stores nothing, so a lost token cannot be looked up again (issue another).
type Session ¶
type Session struct {
ID string `json:"id"`
Name string `json:"name"`
Argv []string `json:"argv"`
WorkDir string `json:"workdir,omitempty"`
PTY bool `json:"pty"`
Status SessionStatus `json:"status"`
ExitCode int `json:"exit_code"`
ExitSignal string `json:"exit_signal,omitempty"`
CreatedAt time.Time `json:"created_at"`
StartedAt time.Time `json:"started_at"`
ExitedAt time.Time `json:"exited_at,omitempty"`
Recording bool `json:"recording"`
Bytes int64 `json:"bytes"` // total stdout+stderr bytes produced
Attached int `json:"attached"` // current number of attached clients
}
Session is the metadata view of a session — never includes its output.
type SessionList ¶
type SessionList struct {
Sessions []Session `json:"sessions"`
}
SessionList is the GET /sessions response shape.
type SessionResizeRequest ¶
SessionResizeRequest is the POST /sessions/{id}/resize body.
type SessionSignalRequest ¶
type SessionSignalRequest struct {
Signal string `json:"signal"`
}
SessionSignalRequest is the POST /sessions/{id}/signal body. Signal is one of INT, TERM, KILL, HUP, QUIT (or the SIG*-prefixed forms).
type SessionStatus ¶
type SessionStatus string
SessionStatus is the lifecycle stage of a long-running command session inside a sandbox container.
const ( SessionStatusRunning SessionStatus = "running" SessionStatusExited SessionStatus = "exited" SessionStatusKilled SessionStatus = "killed" SessionStatusFailed SessionStatus = "failed" // could not start )
type SnapshotAlias ¶ added in v0.1.7
type SnapshotAlias struct {
Alias string
SnapshotName string
// OwnerRef is the tenant that owns the snapshot this alias points at.
// Snapshot names are unique per owner, so the alias carries the owner to
// name a single snapshot and to cascade-delete with the right one.
OwnerRef string
Facade string
ExtraNames []string
// StateJSON is facade-private state for the snapshot, opaque to the
// store (the snapshot counterpart of SandboxCompatState.StateJSON).
StateJSON string
CreatedAt time.Time
UpdatedAt time.Time
}
SnapshotAlias maps a facade-shaped alternate identifier (e.g. E2B's base64-encoded `snapshot_*` token) onto a native sandbox_snapshots.name. ExtraNames carries additional facade-visible names that point at the same native snapshot.
type TeamQuota ¶ added in v0.6.12
type TeamQuota struct {
Team string `json:"team"`
MaxSandboxes int `json:"max_sandboxes,omitempty"`
MaxCPU float64 `json:"max_cpu,omitempty"`
MaxMemoryMB int `json:"max_memory_mb,omitempty"`
Generation int64 `json:"generation"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Usage *TeamQuotaUsage `json:"usage,omitempty"`
}
TeamQuota is one team's quota, and its usage when read back.
func (TeamQuota) Limits ¶ added in v0.6.12
func (q TeamQuota) Limits() TeamQuotaRequest
Limits returns the request form of the quota's limits.
type TeamQuotaRequest ¶ added in v0.6.12
type TeamQuotaRequest struct {
MaxSandboxes int `json:"max_sandboxes,omitempty"`
MaxCPU float64 `json:"max_cpu,omitempty"`
MaxMemoryMB int `json:"max_memory_mb,omitempty"`
}
TeamQuotaRequest is the PUT /v1/teams/{team}/quota body. A zero (or omitted) limit means "no limit on that axis".
func (TeamQuotaRequest) Validate ¶ added in v0.6.12
func (r TeamQuotaRequest) Validate() error
Validate refuses negative limits and a quota with no limit at all, which would be a quota that limits nothing (DELETE removes a quota).
type TeamQuotaUsage ¶ added in v0.6.12
type TeamQuotaUsage struct {
Sandboxes int `json:"sandboxes"`
CPU float64 `json:"cpu"`
MemoryMB int `json:"memory_mb"`
}
TeamQuotaUsage is what a team holds now: every sandbox that is not deleted, running or stopped, at the CPU and memory it asked for.
type Template ¶ added in v0.4.1
type Template struct {
ID string `json:"id"`
Image string `json:"image"`
Status TemplateStatus `json:"status"`
RootfsPath string `json:"-"`
RootfsSizeBytes int64 `json:"rootfs_size_bytes,omitempty"`
MinSizeMiB int `json:"min_size_mib,omitempty"`
LastError string `json:"last_error,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
ReadyAt *time.Time `json:"ready_at,omitempty"`
SnapshotMemoryPath string `json:"-"`
SnapshotStatePath string `json:"-"`
SnapshotSizeBytes int64 `json:"snapshot_size_bytes,omitempty"`
SnapshotChecksum string `json:"-"`
SnapshotVsockCID uint32 `json:"-"`
SnapshotError string `json:"snapshot_error,omitempty"`
HasSnapshot bool `json:"has_snapshot"`
// HasOverlay is the API-facing "this template was built with a
// per-sandbox overlay drive placeholder baked into its snapshot
// state" flag. PR-A templates have it false; the snapshot-load path
// rejects an OverlaySizeGB request against a HasOverlay=false
// template because Firecracker cannot add a virtio-blk device
// post-load — only PATCH an existing one's backing path. Operators
// rebuild the template via POST /v1/templates to upgrade.
HasOverlay bool `json:"has_overlay"`
// PushState reflects the AOCR-push lifecycle for this template's
// artifacts (Phase 6 PR 6-B.1). See the TemplatePushState* constants.
// When push is disabled (or this is a warm-upgrade row) the value is
// "active" from the moment the row is inserted, matching pre-feature
// behaviour. Otherwise it transitions pending → pushing → active|error
// driven by TemplateArtifactPushReconciler.
PushState string `json:"push_state,omitempty"`
// PushError is populated only when PushState is "error" — the last
// error the reconciler saw, surfaced to operator-facing API responses.
PushError string `json:"push_error,omitempty"`
// RegistryRef is the canonical destination ref the push pipeline
// wrote (`<host>/cluster/<id>/templates/<tid>:latest`). Populated
// after a successful push; empty until then. Read by consumer-side
// code in PR 6-B.2 to know where peers can pull the template from.
RegistryRef string `json:"registry_ref,omitempty"`
// PushDigest is the manifest digest (`sha256:...`) the registry
// assigned to the pushed tag, as reported by the Docker push stream's
// `aux` payload. Empty when the daemon did not surface one — older
// daemons or registries that don't return a manifest digest leave
// this blank.
PushDigest string `json:"push_digest,omitempty"`
}
Template is the persisted record for a Firecracker rootfs template. See plans/snapshot-clone-fast-boot.md Phase 2: an image is converted once into a rootfs.ext4 and many sandboxes can boot from it without re-running the skopeo+umoci+mkfs pipeline.
RootfsPath is the absolute on-disk location of the prepared rootfs.ext4 (`<FirecrackerTemplatesDir>/<id>/rootfs.ext4`). It is json:"-" — the path is a server-internal detail that should not leak to API callers; clients reference templates by ID.
Snapshot* fields are populated by the Phase 3 second build phase. HasSnapshot is the API-facing "this template fast-boots" flag — the path/checksum/CID fields stay json:"-" because they are pure server detail. SnapshotError carries the reason a template ended up ready_no_snapshot (rootfs is usable, snapshot phase failed) so the operator does not have to grep daemon logs.
type TemplateStatus ¶ added in v0.4.1
type TemplateStatus string
TemplateStatus tracks a Firecracker template through its async build. pending is the wire-visible state immediately after POST /v1/templates (matches Phase 2 — clients that simply poll for ready keep working). building_rootfs and snapshotting are intermediate states the Phase 3 two-phase build goroutine walks through. ready means rootfs+snapshot are both on disk; ready_no_snapshot means rootfs is fine but the snapshot phase failed (CID alloc, snapshotter error) — sandboxes can still cold-boot from this template, just without fast-boot. failed means even the rootfs phase did not complete; LastError carries the reason for the operator to inspect. unhealthy is the Phase 6 PR-A terminal state for "snapshot was ready and worked at least once, then a load-time checksum mismatch proved the on-disk artifact is corrupt" — distinct from ready_no_snapshot (which is build-time degradation) so operators can alert on the runtime regression specifically. Cold- boot still works against unhealthy because the rootfs is unaffected; the service layer kicks an async rebuild that transitions back to ready once the snapshot phase succeeds.
const ( TemplateStatusPending TemplateStatus = "pending" TemplateStatusBuildingRootfs TemplateStatus = "building_rootfs" TemplateStatusSnapshotting TemplateStatus = "snapshotting" TemplateStatusReady TemplateStatus = "ready" TemplateStatusReadyNoSnapshot TemplateStatus = "ready_no_snapshot" TemplateStatusFailed TemplateStatus = "failed" TemplateStatusUnhealthy TemplateStatus = "unhealthy" )
type UpdateLifecycleRequest ¶
type UpdateLifecycleRequest struct {
Lifecycle
}
UpdateLifecycleRequest is the body for PUT /v1/sandboxes/{id}/lifecycle. Full-replacement semantics: send all four fields. To clear a field, set it to zero. To preserve a field, send its current value (read it via GET first if the caller doesn't already have it).
type UpdateNetworkLimitsRequest ¶ added in v0.1.7
type UpdateNetworkLimitsRequest struct {
NetworkBytesInLimit *int64 `json:"network_bytes_in_limit,omitempty"`
NetworkBytesOutLimit *int64 `json:"network_bytes_out_limit,omitempty"`
}
Each field is a pointer so the handler can distinguish "leave alone" (nil) from "set to unlimited" (pointer to zero). Negative values are rejected at the service layer.
type Volume ¶ added in v0.5.4
type Volume struct {
ID string `json:"id"`
Tenant string `json:"tenant"`
Name string `json:"name"`
Backend string `json:"backend"`
// Source is the backend coordinate (S3 bucket/prefix or NFS host:/path)
// frozen at creation time. Delete and reconciliation read this stored value
// rather than recomputing it from mutable operator config, so a volume keeps
// mounting and reclaiming the exact location it was created against even if
// the operator later changes the configured bucket/prefix/export. Empty for
// rows created before this column existed; callers fall back to recompute.
Source string `json:"source"`
CreatedAt time.Time `json:"created_at"`
// DeleteWithSandbox: delete this volume once its last attachment goes
// (PlatformVolumeMount.DeleteWithSandbox). It rides the cluster FSM's
// volume rows as JSON, so a node that predates it reads false and keeps
// the volume: the safe direction.
DeleteWithSandbox bool `json:"delete_with_sandbox,omitempty"`
}
Volume is a first-class, operator-backed persistent volume object. E2B references volumes by name only (no object), but the Daytona facade exposes full CRUD, so a volume needs a durable row: a stable id, the owning tenant, the user-facing name, and which backend it lives on. The backing storage (S3 prefix / NFS dir) is derived deterministically from (tenant, name) — the row is metadata, not the data itself.
type VolumeAttachment ¶ added in v0.5.4
type VolumeAttachment struct {
Tenant string `json:"tenant"`
VolumeID string `json:"volume_id"`
SandboxID string `json:"sandbox_id"`
IncarnationID string `json:"incarnation_id"`
Target string `json:"target"`
Source string `json:"source"`
CreatedAt time.Time `json:"created_at"`
CreatedVolume bool `json:"-"`
}
VolumeAttachment is the indexed store-side reference from a sandbox to a platform volume. It deliberately duplicates the deterministic source so delete and reconciliation paths never need to decrypt sandbox_mounts or rebuild the source from mutable operator config just to answer "is this attached?".
type WarmPool ¶ added in v0.6.12
type WarmPool struct {
Image string `json:"image"`
Depth int `json:"depth"`
// MinDepth and MaxDepth make the depth follow demand (W2): each server
// sets its own target from a moving average of the creates it served
// from the image, kept between them. MaxDepth 0 means a fixed Depth.
MinDepth int `json:"min_depth,omitempty"`
MaxDepth int `json:"max_depth,omitempty"`
// OnImageChange is WarmPoolReplaceNow or WarmPoolReplaceAsUsed.
OnImageChange string `json:"on_image_change,omitempty"`
Generation int64 `json:"generation"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Status *WarmPoolStatus `json:"status,omitempty"`
}
WarmPool is one image's warm-pool entry. Generation goes up by one on every change, so the same PUT twice leaves it alone. Status is filled on reads; a PUT answers without it.
func (WarmPool) FollowsDemand ¶ added in v0.6.12
FollowsDemand reports an entry whose depth follows demand between MinDepth and MaxDepth rather than staying at Depth.
type WarmPoolList ¶ added in v0.6.12
type WarmPoolList struct {
Pools []WarmPool `json:"pools"`
}
WarmPoolList is GET /v1/warm-pools: every entry, by image.
type WarmPoolRequest ¶ added in v0.6.12
type WarmPoolRequest struct {
Depth int `json:"depth"`
MinDepth int `json:"min_depth,omitempty"`
MaxDepth int `json:"max_depth,omitempty"`
OnImageChange string `json:"on_image_change,omitempty"`
}
WarmPoolRequest is the body of PUT /v1/warm-pools/{image}, a full replace: the same body twice is a no-op.
func (WarmPoolRequest) Validate ¶ added in v0.6.12
func (r WarmPoolRequest) Validate() error
Validate checks a PUT body. An entry is either a fixed depth, or a min_depth/max_depth range to follow demand; asking for both is refused rather than guessed at.
type WarmPoolServerStatus ¶ added in v0.6.12
type WarmPoolServerStatus struct {
NodeID string `json:"node_id"`
Ready int `json:"ready"`
Target int `json:"target"`
Outdated int `json:"outdated,omitempty"`
Stale bool `json:"stale,omitempty"`
}
WarmPoolServerStatus is one server's pool for an image. Stale marks a server whose last capacity report is too old to trust; its numbers are the last ones it sent.
type WarmPoolStatus ¶ added in v0.6.12
type WarmPoolStatus struct {
Ready int `json:"ready"`
Target int `json:"target"`
// Outdated is how many ready slots hold an image older than the one the
// tag names now (a replace_as_used rollout in progress).
Outdated int `json:"outdated,omitempty"`
Servers []WarmPoolServerStatus `json:"servers"`
}
WarmPoolStatus is how full an entry's pools are: the total over every server that runs a warm pool, and each server on its own.
type WasmModule ¶ added in v0.5.3
type WasmModule struct {
ID string `json:"id"`
ModuleRef string `json:"module_ref"`
Status WasmModuleStatus `json:"status"`
ModulePath string `json:"-"`
ModuleSizeBytes int64 `json:"module_size_bytes,omitempty"`
Digest string `json:"digest,omitempty"`
Entrypoint string `json:"entrypoint,omitempty"`
HasWarm bool `json:"has_warm"`
LastError string `json:"last_error,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
ReadyAt *time.Time `json:"ready_at,omitempty"`
}
WasmModule is one row in the wasm_modules catalogue (plans/wasm-runtime.md).
type WasmModuleStatus ¶ added in v0.5.3
type WasmModuleStatus string
WasmModuleStatus is the catalogue lifecycle for POST /v1/wasm-modules rows.
const ( WasmModuleStatusReady WasmModuleStatus = "ready" WasmModuleStatusFailed WasmModuleStatus = "failed" )
type WhoAmI ¶ added in v0.6.8
type WhoAmI struct {
Principal WhoAmIPrincipal `json:"principal"`
// Role is viewer, runner, auditor or admin.
Role string `json:"role"`
// Team is "*" for a caller that acts on every team, the team name for a
// team-bound credential, and absent for a managed account.
Team string `json:"team,omitempty"`
// ExpiresAt is when the presented credential stops working; absent for
// one that does not expire (the operator token).
ExpiresAt *time.Time `json:"expires_at,omitempty"`
}
WhoAmI is the body of GET /v1/whoami: the caller's own resolved identity (plans/identity-and-access.md §5.2). It only ever describes the caller.
type WhoAmIPrincipal ¶ added in v0.6.8
type WhoAmIPrincipal struct {
Kind string `json:"kind"`
ID string `json:"id"`
Name string `json:"name,omitempty"`
}
WhoAmIPrincipal names who the caller is. ID is stable ("operator", "node:n3", "controlplane:<subject>", later "tok_…" or "oidc:<issuer>:<sub>"); Name is for display only.