Skip to content

SwarmCracker API Reference

The public HTTP API (v1) and the internal gRPC protocol between swarmd-firecracker and swarmcracker CLI / swarmctl.


SwarmCracker has two machine surfaces:

Surface Audience Contract
HTTP API v1 operators, CI, external readers api/openapi.yaml — see Public HTTP API (v1)
gRPC control protocol the CLI and swarmctl against a cluster member internal; versioned with x-swarmcracker-version (this page, below)

The gRPC section is the internal protocol: it is not a supported integration point and its messages may change with SwarmKit. The HTTP API is the public, documented contract.

The daemons also listen on ports that are not part of the v1 contract and are not documented here: :4243 (/v1/ingress, /v1/ingress/report), the SwarmKit remote API on :4242, the node broker on :4245, and each node’s health/metrics server on :8080. They are cluster-internal or loopback-only and may change in any minor release — do not build on them. See Internal (Private) Endpoints for the purpose, the authentication and the exact wording of that promise.

SwarmCracker uses SwarmKit’s gRPC API via the github.com/moby/swarmkit/v2/api package, extended with a custom API versioning protocol (pkg/apiversion).

┌──────────────────┐ Unix Socket ┌────────────────────────┐
│ swarmcracker │ ───── gRPC (TLS) ────── │ swarmd-firecracker │
│ swarmctl │ /var/run/swarmkit/ │ (manager/worker) │
│ │ swarm.sock │ │
└────────┬─────────┘ └───────────┬────────────┘
│ │
│ X-SwarmCracker-Version: 1 │
│ (gRPC metadata interceptor) │
└─────────────────────────────────────────────────┘

Parameter Value
Socket path /var/run/swarmkit/swarm.sock
State directory /var/lib/swarmkit
Transport Unix socket + TLS
Certificates Auto-generated by SwarmKit CA
import (
"github.com/moby/swarmkit/v2/api"
"github.com/restuhaqza/swarmcracker/pkg/apiversion"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
)
// Load TLS certificates from state dir
tlsConfig := loadTLSConfig("/var/lib/swarmkit")
conn, err := grpc.Dial(
"unix:///var/run/swarmkit/swarm.sock",
grpc.WithTransportCredentials(credentials.NewTLS(tlsConfig)),
apiversion.WithVersion(), // Injects X-SwarmCracker-Version metadata
)
client := api.NewControlClient(conn)

SwarmCracker extends SwarmKit with a gRPC unary client interceptor that injects metadata into every outgoing RPC.

Header Value Description
x-swarmcracker-version "1" Current API version
import (
"github.com/restuhaqza/swarmcracker/pkg/apiversion"
"google.golang.org/grpc"
)
conn, err := grpc.Dial(addr,
grpc.WithTransportCredentials(creds),
apiversion.WithVersion(), // Injects X-SwarmCracker-Version metadata
)

The package is client-only. It exports Current, WithVersion() (a grpc.DialOption) and VersionClientInterceptor(). Servers that need to enforce a minimum version read the x-swarmcracker-version metadata directly from the incoming context.

Version Release Changes
1 v0.8.0+ Initial schema — all v0.x releases share this version
(empty) pre-v0.8.0 Pre-versioning clients — treated as compatible

SwarmCracker leverages the following SwarmKit gRPC services via api.ControlClient:

RPC Request Response Description
ListClusters ListClustersRequest ListClustersResponse List all clusters (used for token generation)
GetCluster GetClusterRequest GetClusterResponse Get cluster details
RPC Request Response Description
ListNodes ListNodesRequest ListNodesResponse List all nodes with status
GetNode GetNodeRequest GetNodeResponse Get node details
UpdateNode UpdateNodeRequest UpdateNodeResponse Update node labels/spec
RPC Request Response Description
CreateService CreateServiceRequest CreateServiceResponse Deploy a new service
UpdateService UpdateServiceRequest UpdateServiceResponse Update existing service
RemoveService RemoveServiceRequest RemoveServiceResponse Remove a service
ListServices ListServicesRequest ListServicesResponse List all services
GetService GetServiceRequest GetServiceResponse Get service details
InspectService — — (via swarmctl)
RPC Request Response Description
ListTasks ListTasksRequest ListTasksResponse List tasks with optional filters
GetTask GetTaskRequest GetTaskResponse Get individual task details
RPC Request Response Description
CreateSecret CreateSecretRequest CreateSecretResponse Store a secret
GetSecret GetSecretRequest GetSecretResponse Retrieve a secret
ListSecrets ListSecretsRequest ListSecretsResponse List all secrets
RemoveSecret RemoveSecretRequest RemoveSecretResponse Delete a secret
CreateConfig CreateConfigRequest CreateConfigResponse Store config data
GetConfig GetConfigRequest GetConfigResponse Retrieve config data
ListConfigs ListConfigsRequest ListConfigsResponse List all configs
RemoveConfig RemoveConfigRequest RemoveConfigResponse Delete a config
RPC Request Response Description
CreateNetwork CreateNetworkRequest CreateNetworkResponse Create overlay network
ListNetworks ListNetworksRequest ListNetworksResponse List all networks
GetNetwork GetNetworkRequest GetNetworkResponse Get network details
RemoveNetwork RemoveNetworkRequest RemoveNetworkResponse Delete a network

The SwarmKit TaskSpec runtime is used to encode Firecracker-specific configuration:

// SwarmKit container spec is converted to SwarmCracker types:
type Container struct {
Image string
Command []string
Args []string
Env []string
Mounts []Mount
}
type Mount struct {
Target string
Source string
ReadOnly bool
}
type NetworkAttachment struct {
Network Network
Addresses []string
}
type SecretRef struct {
ID string // Secret ID from manager
Name string // Secret name
Target string // Mount path in VM
Data []byte // Fetched by agent from manager
}
type ConfigRef struct {
ID string
Name string
Target string
Data []byte
}

The daemon exposes a local HTTP health endpoint for monitoring:

Attribute Value
Bind address 127.0.0.1:8080
Endpoint GET /healthz

The handler returns HTTP 200 when every check passes and HTTP 503 otherwise.

This server is a private loopback endpoint, not part of the v1 contract; it is documented in Internal (Private) Endpoints together with what it exposes and why the bind address is the only boundary.

{
"healthy": true,
"checks": {
"kvm": { "status": "ok", "message": "KVM is accessible" },
"bridge": { "status": "ok", "message": "bridge swarm-br0 exists" },
"firecracker": { "status": "ok", "message": "firecracker found at /usr/local/bin/firecracker" }
}
}

Each check’s status is "ok" or "error"; message carries the human-readable detail. There are no timestamp or consul fields.

The same server exposes the live healthcheck state of every task the node hosts, which service ps / task ls fan out to:

Attribute Value
Endpoint GET /v1/tasks/health
Method GET only (others get HTTP 405)
{
"tasks": [
{
"task_id": "5f3a1b2c9d0e",
"state": "failing",
"failing_streak": 2,
"command": "/bin/sh -c curl -fsS http://localhost:8080/healthz",
"output": "curl: (7) Failed to connect to localhost port 8080",
"updated_at": "2026-10-16T15:04:07Z"
}
]
}

state is one of starting, healthy, failing or unhealthy (see Container Healthchecks). Tasks that declare no healthcheck are absent. The response is deterministic (sorted by task_id).

Trust model. Health only — no authentication; the payload is the healthcheck state plus the probe’s last bounded output, which can carry whatever the check printed. The bind address (--health-addr, default 127.0.0.1:8080) is the boundary; binding it on the cluster network exposes the same information as /healthz and /metrics.


Each Firecracker microVM exposes a local HTTP API on its socket:

Attribute Value
Path <socket-dir>/<task-id>.sock (default socket dir /var/run/firecracker)
Endpoint GET /machine-config
Endpoint GET / (info)
Protocol HTTP via Unix socket

Used by swarmctl for VM introspection and the executor for lifecycle management.


Component Path
API versioning pkg/apiversion/
gRPC client helpers cmd/swarmcracker/token_helper.go
gRPC service handlers cmd/swarmd-firecracker/main.go
SwarmKit types github.com/moby/swarmkit/v2/api
Executor bridge pkg/swarmkit/executor.go (SwarmKit → Firecracker translation)
CNI network allocator pkg/cni/allocator.go
Network discovery pkg/discovery/consul.go

The manager serves versioned resource documents — schemaVersion, kind, items, next for lists and schemaVersion, kind plus the resource fields for single documents — on two listeners:

Listener Address Authentication
TLS/TCP 127.0.0.1:4244 by default (--api-listen) Authorization: Bearer <token> on every route, including /v1/version
Unix socket <state-dir>/api.sock (default /var/lib/swarmkit/api.sock) none — the socket’s file mode is the credential

The read surface is phase 1 and writes are phase 2: services (create, patch, delete, rollback), configs, secrets, networks and nodes (create, patch, delete), plus the live-migration write below. They require the resource’s :write scope. The task-scoped operations — exec, the interactive console, log streaming, file transfer, snapshots and live ?health enrichment — are shipped too: the manager relays them to the node that runs the task through an internal mTLS broker, so the caller never picks a host. A manager with no broker wired answers those routes 501 not_implemented with details.capability.

api/openapi.yaml in the repository is the normative contract for every route, schema, header and error code; this section is the operator’s guide to it.

Runnable Client programs for Python (sdk/python) and Node (sdk/node) are in SDK examples; Go callers use pkg/client.

Only the manager that initialized the cluster serves the API in phase 1: the daemon starts both listeners when its configuration carries no join address (JoinAddr == ""). A worker, and a manager that joined an existing cluster, starts neither. Serving the API on joined managers is a follow-up. --api-disabled turns both listeners off on the initializing manager, and --api-listen "" keeps the Unix socket while disabling the TCP listener.

Reads are GET; services, configs, secrets, networks and nodes also accept the phase-2 writes below, and POST /v1/migrations is the move write.

Method Route Returns
GET /v1/version VersionInfo (API versions, server version, capabilities)
GET /v1/services ServiceList
POST /v1/services ServiceDocument (create; requires services:write)
GET /v1/services/{id} ServiceDocument
PATCH /v1/services/{id} ServiceDocument (merge patch; requires services:write)
DELETE /v1/services/{id} 204 (requires services:write)
POST /v1/services/{id}/rollback ServiceDocument (requires services:write)
GET /v1/services/{id}/tasks TaskList
GET /v1/tasks TaskList (?health=true enriches each task)
GET /v1/tasks/{id} TaskDocument (?health=true enriches the task)
POST /v1/tasks/{id}/exec NDJSON ExecFrame stream (non-interactive; requires tasks:exec)
POST /v1/tasks/{id}/attach full-duplex raw console stream (tasks:exec)
GET /v1/tasks/{id}/logs NDJSON LogFrame stream (tail, since, follow; requires tasks:logs)
GET /v1/tasks/{id}/files raw file bytes (requires tasks:files)
PUT /v1/tasks/{id}/files 204 (raw upload, mode; requires tasks:files)
POST /v1/tasks/{id}/snapshots SnapshotDocument (experimental; requires tasks:snapshots)
GET /v1/tasks/{id}/snapshots SnapshotList (experimental)
POST /v1/tasks/{id}/snapshots/{sid}/restore SnapshotDocument (experimental)
DELETE /v1/tasks/{id}/snapshots/{sid} 204 (experimental)
DELETE /v1/tasks/{id}/restored 204 (experimental; stops the VM a restore started)
GET /v1/snapshots?task={id} SnapshotList (flat address; task required)
POST /v1/snapshots/{sid}/restore?task={id} SnapshotDocument (flat address)
DELETE /v1/snapshots/{sid}?task={id} 204 (flat address)
POST /v1/migrations Migration (moves a running task’s VM to another node; requires migrations:write, admin only)
GET /v1/events SSE or NDJSON Event stream (requires events:read)
GET /v1/nodes NodeList
GET /v1/nodes/{id} NodeDocument
PATCH /v1/nodes/{id} NodeDocument (availability + labels; requires nodes:write, admin only)
GET /v1/networks NetworkList
POST /v1/networks NetworkDocument (create; requires networks:write)
GET /v1/networks/{id} NetworkDocument
DELETE /v1/networks/{id} 204 (requires networks:write)
GET /v1/configs ConfigList
POST /v1/configs ConfigDocument (create; requires configs:write)
GET /v1/configs/{id} ConfigDocument
PATCH /v1/configs/{id} ConfigDocument (labels only; requires configs:write)
DELETE /v1/configs/{id} 204 (requires configs:write)
GET /v1/secrets SecretList (metadata only — never a payload)
POST /v1/secrets SecretDocument (create; requires secrets:write)
GET /v1/secrets/{id} SecretDocument (metadata only)
PATCH /v1/secrets/{id} SecretDocument (labels only; requires secrets:write)
DELETE /v1/secrets/{id} 204 (requires secrets:write)
GET /v1/audit AuditList (requires audit:read, which only admin holds)

The {id} path parameter accepts an exact id, an exact name (for a node, the hostname), or a unique id prefix of at least four characters. A prefix — or a name shared by two objects, which only node hostnames can be — that matches more than one object is 400 ambiguous with details.candidates; a shorter non-exact value is 400 invalid.

GET /v1/version reports capabilities: ["read", "write", "events"] on a manager without a node broker. A manager with a wired broker also advertises exec, logs, files, health and attach, and every advertised operation has a route. When the operator passes --snapshots-enable, a manager whose snapshot transport is wired also advertises snapshots (experimental; see the snapshots guide). The advertisement and the route gate use the same condition, so snapshots appears exactly when the snapshot routes stop answering 501. A manager with a wired broker and a migration spool also advertises migrations, and POST /v1/migrations answers 501 exactly when it is absent. A client that feature-detects the surface sees exactly what the server serves; the phase-2 write routes above are covered by write.

Every list accepts limit and cursor; GET /v1/services/<id>/tasks accepts only those two. Services, nodes, networks, configs and secrets also accept label and filter by it. GET /v1/tasks accepts label too, but only for compatibility with the SDKs, which document forwarding a selector on every list — the task list is not filtered by it and the value is not parsed, so it changes neither items nor the cursor binding. Every route declares the query parameters it implements (the operation in api/openapi.yaml is the per-route list), and a name outside that route’s set is 400 invalid with details.parameter — a typo fails loudly instead of silently changing the request. A cursor is bound to the route and to the filter values that produced the page (the label selectors on the routes that filter, the task reference on the flat snapshot routes), so reusing it on a different query is 400 invalid with details.reason: "cursor_mismatch"; limit may change between pages.

Every response carries X-SwarmCracker-Api-Version: 1 and X-Request-Id. A read answers If-None-Match with 304. A list ETag is the hash of the response body; a single-resource ETag is the quoted SwarmKit revision ("17"), which is exactly the value a later PATCH expects in If-Match. Responses use the application/vnd.swarmcracker.v1+json media type.

GET /v1/configs/{id} includes the payload in data only when the caller holds configs:read-values. A plain configs:read token receives the metadata document with the field absent, and the list route never leaks a payload. The same rule applies to a write response: a token that may write a value but not read values back does not get it echoed. The payload is a UTF-8 string; binary configs are refused on create with details.reason: "binary_not_supported", and a config stored out of band with a non-UTF-8 payload reads with data absent — the API does not transcode or repair bytes it cannot represent.

Every write requires services:write (an operator or admin token). A reader gets 403 forbidden with details.requiredScope: "services:write".

Terminal window
# Create: the body is a ServiceWrite, not a Service.
curl --cacert <state-dir>/api/tls.crt \
-H "Authorization: Bearer $(cat operator.token)" \
-H "Content-Type: application/vnd.swarmcracker.v1+json" \
-d '{"name":"web","spec":{"mode":"replicated","replicas":2,
"task":{"image":"nginx:1.27-alpine","ports":[{"target":80,"published":8080}]}}}' \
https://mgr:4244/v1/services

The create response is 201 Created with a ServiceDocument and ETag: "<revision>". A name conflict is 409 conflict. If-None-Match: * marks the request create-only; it does not turn the call into an upsert, and any other value of that header is invalid. The body is capped at 8 MiB (413), the Content-Type must be application/vnd.swarmcracker.v1+json (415), and unknown body fields are 400 invalid with details.fields.

Merge patch. PATCH /v1/services/{id} takes Content-Type: application/merge-patch+json and the body is an RFC 7386 merge patch over the writable subtree. There is deliberately no PUT: a curated DTO cannot safely replace a whole SwarmKit spec, because it does not model every field.

  • null resets an optional scalar to its default; null on a map key deletes that key; [] clears an array; a non-empty array replaces the array. healthcheck.test: [] clears the whole healthcheck (SwarmKit would read an empty test list as “inherit”); healthcheck: null is equivalent.
  • Only the fields present in the patch are written. SwarmKit fields the API does not model — mount volume options, privileges, endpoint resolver mode, placement preferences, log drivers — survive untouched.
  • id, name, revision, createdAt, updatedAt, status and spec.mode are immutable. Sending one is 400 invalid with details.fields, as is an unknown field at any depth.
  • spec.task.registryAuth is the write-only pull credential. Absent on a patch preserves the current credential, null (or "") clears it, and a non-empty string replaces it. It never appears in a response, because the read types have no such field.
  • mounts[].type: "bind" references a host path and requires the admin role (contract §5.3). An operator token is refused with 403 forbidden and details.requiredRole: "admin". The check only runs when the patch names mounts, so editing an unrelated field on a service that already has a bind mount is allowed.
Terminal window
# Scale to 3, keeping every field the patch does not name.
curl --cacert <state-dir>/api/tls.crt -X PATCH \
-H "Authorization: Bearer $(cat operator.token)" \
-H "Content-Type: application/merge-patch+json" \
-H 'If-Match: "17"' \
-d '{"spec":{"replicas":3}}' \
https://mgr:4244/v1/services/web

Preconditions. PATCH and rollback require If-Match; DELETE accepts it optionally.

Situation Answer
If-Match missing on PATCH or rollback 428 conflict, details.required: "If-Match"
If-Match does not match the current revision 412 conflict with details.expectedRevision and details.currentRevision
Weak validator (W/"17") 412 conflict — a weak tag is never the strong revision
If-Match: * Matches any revision, but the service must exist
Missing service with If-Match 412 (preconditions are evaluated before ignoreMissing)
Missing service without If-Match 404, or 204 with ?ignoreMissing=true

Use the ETag of the last read as If-Match; do not invent a revision. A PATCH that omits both Content-Type and If-Match answers 415 first: the server does not evaluate preconditions on a body it cannot parse.

Delete. DELETE /v1/services/{id} answers 204 with no body. The check and the removal are not atomic: SwarmKit’s RemoveServiceRequest carries no version, so an update can land in between. The delete wins. Callers that need strict ordering patch first and then delete.

Rollback. POST /v1/services/{id}/rollback takes no body (a non-empty body is 400) and requires If-Match. It restores the service’s previous spec and answers 200 with the new ServiceDocument and revision.

Every write that reaches the backend appends an audit record (service.create, service.update, service.delete, service.rollback) with the actor, the resource that was written and result: ok or error. A request rejected before the backend (415, 413, a body that cannot be decoded, a missing If-Match) is not audited, and an audit append failure does not fail a mutation that has already committed.

These routes follow the same transport rules as service writes: the create body is application/vnd.swarmcracker.v1+json, a patch body is application/merge-patch+json, both are capped at 8 MiB, and unknown fields are 400 invalid. Preconditions behave exactly as above: a PATCH requires If-Match (428 when missing, 412 when stale or weak), DELETE accepts it optionally, and preconditions are evaluated before ?ignoreMissing=true.

Route Scope Writable fields
POST /v1/configs configs:write name, labels, data
PATCH /v1/configs/{ref} configs:write labels only
DELETE /v1/configs/{ref} configs:write —
POST /v1/secrets secrets:write name, labels, data or driver
PATCH /v1/secrets/{ref} secrets:write labels only
DELETE /v1/secrets/{ref} secrets:write —
POST /v1/networks networks:write name, driver, ipam, labels, attachable
DELETE /v1/networks/{ref} networks:write —
PATCH /v1/nodes/{ref} nodes:write (admin) availability, labels

A reader token on any of these routes is 403 forbidden with details.requiredScope; it is never 405 or 415.

Configs. data is the payload as UTF-8 text. A payload that is not valid UTF-8 is 400 invalid with details.reason: "binary_not_supported". PATCH accepts labels only: data, name, id, revision, createdAt, updatedAt, schemaVersion and kind are immutable and rejected with 400 invalid. The payload is visible only to a token holding configs:read-values (an operator or admin by default), on reads and on the response to a write.

Secrets. A create carries exactly one of data (standard base64, padding optional) or driver ({name, options}). Sending both or neither is 400 invalid, as is data that is not valid base64. PATCH accepts labels only: data, driver, name, id, revision, the timestamps, schemaVersion and kind are immutable. No secret response ever contains the payload — there is no data field on any read document, for any scope. Rotation is create-new and repoint the service, then delete the old secret.

Networks. driver defaults to overlay. ipam is {subnet, gateway}; the subnet must be a network address in CIDR form (10.0.1.0/24, not 10.0.1.7/24), the gateway must be an IP address inside it, and neither the network address nor the IPv4 broadcast address is a usable gateway. A violation is 400 invalid with the field named. There is no network update: driver, IPAM and labels are fixed at create, and PATCH or PUT on /v1/networks/{id} answers 405 invalid with details.reason: "method_not_allowed" and Allow: GET, DELETE.

Nodes. Only availability (active, pause or drain) and labels are writable. role, membership and every read-envelope field are immutable and rejected with 400 invalid. Node writes require nodes:write, which only the admin role holds, and If-Match is mandatory because SwarmKit’s UpdateNode replaces the whole node spec.

Terminal window
# Create a config. An operator (configs:read-values) sees the value in the response.
curl --cacert <state-dir>/api/tls.crt \
-H "Authorization: Bearer $(cat operator.token)" \
-H "Content-Type: application/vnd.swarmcracker.v1+json" \
-d '{"name":"app-config","data":"listen 8080","labels":{"team":"payments"}}' \
https://mgr:4244/v1/configs
# Drain a node (admin only).
curl --cacert <state-dir>/api/tls.crt -X PATCH \
-H "Authorization: Bearer $(cat admin.token)" \
-H "Content-Type: application/merge-patch+json" \
-H 'If-Match: "9"' \
-d '{"availability":"drain"}' \
https://mgr:4244/v1/nodes/node-2

Every write that reaches the backend appends an audit record: config.create, config.update, config.delete, secret.create, secret.update, secret.delete, network.create, network.delete and node.update. A request rejected before the backend (415, 413, undecodable body, missing If-Match) is not audited, and an audit append failure does not fail a committed mutation. A dry run is not a mutation and is never audited; an idempotent replay does not append a second record; a wait timeout audits the committed mutation once.

GET /v1/events streams the manager’s change feed. SSE is the default; send Accept: application/x-ndjson for one JSON object per line. The stream starts with a ready frame and then emits one event per change:

{"schemaVersion":1,"kind":"Event","cursor":"18422","at":"2026-10-19T10:04:12Z",
"type":"service.updated","resource":{"kind":"Service","id":"svc-1","name":"web"},
"revision":"18"}
  • types is a comma-separated subset of service,task,node,network,config,secret.
  • since (or Last-Event-ID) is the cursor to resume from. A cursor older than the retained watch log is 410 cursor_expired with details.action: "relist".
  • label=k / label=k=v filters events by resource labels.
  • include=object embeds the mapped resource. Config data is included only for a configs:read-values identity; secret data is never included.
  • SSE events carry id: <cursor> and event: <resource>.<created|updated|removed>; the server sends a : ping comment every 15 seconds. Delivery is at-least-once across reconnects; every event in a batch shares one cursor, so dedupe by resource + revision, not by cursor alone.
  • The stream requires events:read. The actor and changed-path fields are gateway-observed/optional in this phase; they are omitted when unavailable.

These five capabilities are relayed by the manager to the node that runs the task. They require a wired node broker (--broker-listen, default 0.0.0.0:4245 on swarmd-firecracker); when it is absent the routes answer 501 not_implemented with details.capability (exec, attach, logs, files or health) and /v1/version does not advertise them. The relay uses the cluster’s mutual TLS identity, never the caller’s bearer token.

  • Exec — POST /v1/tasks/{id}/exec takes an ExecRequest and streams NDJSON ExecFrame objects. A successful stream ends with exactly one exit frame; a non-zero guest status is still a successful API call. tty: true (and therefore stdin: true) is 501 not_implemented with details.reason: "tty_not_supported"; local vm exec -it is unaffected. The task must be running (404 otherwise). Audited as task.exec. For an interactive session use attach below: exec over the API does not carry a TTY in v1, and a browser or a plain HTTP client cannot drive a terminal either.
  • Attach — POST /v1/tasks/{id}/attach is the interactive console (R18): one HTTP/1.1 request, full duplex. The chunked request body is your stdin and the chunked response body is the guest console, both flushed as bytes arrive, so a prompt can reach you before you have finished typing. The response is raw application/octet-stream, not NDJSON and not the v1 envelope. Close the request body to send the guest an EOF; the session ends when the console closes or you disconnect. There is no WebSocket and no second connection, and the route takes no query parameter (?tty= is 400 invalid). The transport is HTTP/1.1 full duplex only: the server calls http.NewResponseController(w).EnableFullDuplex() before it reads the body, so the route requires an HTTP/1.1 connection and does not work over HTTP/2. Browsers and h2-only clients (curl --http2, a fetch/XHR client) are not supported clients for it; the swarmcracker CLI (vm attach -H) is. That is the CLI mapping: swarmcracker -H … vm attach <task> uses this route, while swarmcracker vm attach <task> without -H dials the node’s console Unix socket under --socket-dir and never contacts the manager. Ctrl-P Ctrl-Q detaches in both modes: the remote session closes the request body and cancels the request, which leaves the VM running. It requires tasks:exec and the same task selectors as exec, and the task must be running with its console socket present: otherwise 404 not_found with details.reason: "console_unavailable"; a console that exists but cannot be dialed is 503 unavailable with the same reason and retryable: true. Audited as task.attach.
  • Logs — GET /v1/tasks/{id}/logs streams the Firecracker console as NDJSON LogFrame objects. tail defaults to 200 (max 10000), since is RFC3339 and follow keeps the stream open. A non-following stream always ends with eof. Logs remain readable after the task exits, so this is the route for a failed task. Not audited, and task selectors do not gate reads.
  • Files — GET and PUT /v1/tasks/{id}/files use raw application/octet-stream. The path must be absolute and may not contain a .. segment; a directory is 400 invalid with details.reason: "directory_not_supported", a missing file is 404. PUT accepts a mode and a body up to 1 GiB. The task must be running. Audited as task.files; the path and contents are never recorded.
  • Health — add ?health=true to GET /v1/tasks or GET /v1/tasks/{id}. The list keeps its normal shape and answers 207 with one partial entry per node whose health could not be read; each partial[].error is a complete Error with requestId, retryable and details.nodeId, while the readable tasks keep their documents. A single-task read has no partial array, so an unreachable node is 503 unavailable with details.nodeId. A task that published no healthcheck omits health.

Snapshots are disabled by default and enabled per node with --snapshots-enable (plus the node broker they are relayed through). While they are off, every snapshot route answers 501 not_implemented with details.capability: "snapshots", before the task is resolved and before anything is audited.

  • Routes. The task-scoped forms (/v1/tasks/{id}/snapshots…) are the primary address. The flat forms (/v1/snapshots…) are a convenience and require ?task={id}: a snapshot lives on one node, and the flat path alone does not name a task to resolve that node through.
  • Create snapshots a running task’s VM on its node and may pause it briefly. It also copies the task disk, so the manager’s default deadline is 5 minutes (--snapshot-timeout); a create that exceeds it is 504 with code timeout. The copy is part of the snapshot: its path lives only in the node’s metadata.json (recorded as disk_path) and never crosses the wire, while sizeBytes counts the memory image, the state file and the disk copy. A task that is not running is 404 with details.reason: "task_not_running".
  • Restore is refused for a task that is still running: 409 conflict with details.reason: "restore_task_running". The live VM owns its rootfs and a restored second VM on the same file would corrupt both. Restoring the snapshot of an exited task is the supported case; restore writes the snapshot’s disk copy to the recorded rootfsPath first, replacing whatever is there (a stopped restored VM leaves its disk behind, and its writes do not belong to this snapshot’s memory image). A snapshot whose copy is missing and whose task disk is gone too is 409 conflict with details.reason: "snapshot_incomplete".
  • A malformed snapshot id is a client error. {sid} must be one safe path segment shaped like snap-…; anything else is 400 invalid with details.reason: "invalid_snapshot_id", on the task-scoped and the flat forms alike.
  • Restore can outlive SwarmKit. It starts a Firecracker process outside SwarmKit’s task tracker, so the restored VM is not scheduler-managed. DELETE /v1/tasks/{id}/restored stops it on the node that started it: SIGTERM, up to ten seconds of grace, SIGKILL, then the restored socket is removed. A node that tracks no restored VM for the task — never restored there, already stopped, or restored by an earlier daemon lifetime — answers 404 not_found with details.reason: "no_restored_vm". The route takes no body or query and is audited as task.restored.stop.

See the snapshots guide for the CLI workflow, the file layout and the known limitations; api/openapi.yaml has the normative schema and every error code.

POST /v1/migrations moves one running task’s microVM to another node. It is the only migration route: there is no list, no status document and no cancel, because the call is synchronous and its answer is the whole story of one move. The work is a SwarmKit replacement carrying a snapshot artifact — the source exports the task, the manager relays the artifact through its spool, the target records what its next task restores, the service is pinned to the target and updated, and the replacement loads the artifact there. The caller waits for the whole sequence: three minutes for the move plus up to one minute of cleanup the manager performs before answering.

The route requires migrations:write, which only the admin role holds; a token that lacks it is 403 forbidden with details.requiredScope. Scopes are fixed at mint time, so an admin token minted before migrations:write existed keeps its old list and must be reminted. Only the swarm’s raft leader runs a migration: any other manager answers 503 unavailable with details.reason: "not_leader" and details.leader naming the node to retry against, because two managers running the same move would prepare the same service twice and unpin each other’s placement. A manager that cannot tell who the leader is runs the move rather than refusing.

The body is a MigrationRequest:

{ "taskId": "5f3a1b2c9d4e5f60718293a4b5c6d7e8", "targetNode": "worker-2" }

Both fields are required and unknown fields are rejected. taskId is an exact task ID: the manager reads the task by that ID and resolves nothing, so a shortened ID is 404 not_found. targetNode is a reference the manager does resolve — an exact node ID, an exact hostname, or a unique ID prefix of at least four characters. The source is not a field: it is the node the task already runs on.

The answer is 201 whatever the outcome, because the request did run a migration. The document is a Migration:

Field Meaning
id The artifact the source exported (mig-…). A migration has no identity beyond the artifact that carries the VM.
taskId, serviceId The task that was replaced and the service it belonged to.
sourceNode, targetNode Where the VM ran and where it moved.
phases One entry per step (validate, export, relay, prepare, replace, verify, cleanup) with startedAt, finishedAt, result (ok, error, pending) and, for a non-ok result, a message naming the stable code and reason.
downtimeMs Measured by the manager from the instant the old task was observed gone (or the service update’s return, if it was never observed gone) to the first instant a replacement reported running on the target, at a one-second poll. 0 means no running replacement was seen, not zero downtime.
outcome moved or pending.

pending is not a failure: the service was replaced but no replacement had reported running before the two-minute verify deadline. The target keeps the directive naming the artifact and the staged bytes, and the replaced service’s retry restores from them until the directive expires after ten minutes; a retry after that boots a fresh VM. A failure that left nothing behind is a typed error document whose details.phase names the failing step.

Typed failures:

Status Code / reason When
400 invalid A blank taskId or targetNode (details.fields), a task that is not running, a service that is not replicated (details.reason: "service_mode") or has a replica count other than one ("replicas"), a target equal to the source, a target that is not ready and active ("node_not_schedulable"), or a target string shorter than four characters that is neither an exact node ID nor a hostname.
400 ambiguous targetNode is a node ID prefix that matches more than one node; details.candidates lists each match’s id and name.
403 forbidden The token does not hold migrations:write (details.requiredScope).
404 not_found The task ID names no task (a prefix is not resolved), or the target reference matches nothing.
409 conflict A migration of the same service is already in flight (details.reason: "migration_in_flight").
501 not_implemented This manager has no migration transport (details.capability: "migrations").
503 unavailable Another node is the leader (details.reason: "not_leader", details.leader), or the replacement failed outright after the service update ("replacement_failed").
504 timeout A node call, or the whole move, exceeded its deadline; details.phase names the step.

A failure inside the move carries details.phase naming the step; an error the API layer raises before the move starts (a blank field, an unsupported media type) does not. Every attempt that reaches the move is audited as task.migrate today — one record naming the task, never an artifact or a path, with result: "ok" for a 201 and result: "error" for a typed failure; a request rejected before the move is not audited, and a replay does not append a second record. Idempotency-Key applies here as it does on the other POST routes: the first answer is stored, and a retry with the same key and body returns it with Idempotency-Replayed: true instead of moving the task twice. The CLI workflow, the consistency window and the operator’s reading of a pending report are in the migration guide.

Three opt-in modifiers sit on top of the writes. Without them the phase-2 behaviour is unchanged.

Idempotency-Key (POST only: service, config, secret and network create, plus rollback and live migration). The key is trimmed and scoped to the token, the method and the path, so two callers never collide. A retry with the same key and the same body returns the original status, headers and body plus Idempotency-Replayed: true; the first response never carries that header, and the replay carries the retrying request’s X-Request-Id (a replayed error document is re-rendered with that same current requestId). The same key with a different body is 409 conflict with details.reason: "idempotency_key_reuse"; the same key while the first request is still running is 409 conflict with details.reason: "in_progress", retryable: true and details.retryAfterMs: 250. A key longer than 255 bytes, or one containing control characters, is 400 invalid with details.fields.

State is manager-local and in memory, with a 24 h TTL. It is not replicated and does not survive a restart, so a retry across a leader change can still create twice — that is the v1 single-manager decision, not a bug. A 5xx is never stored, so a failed create can be retried with the same key; a dry run is never stored because nothing was written. A malformed dryRun/wait/timeoutMs modifier, a 428 missing If-Match, a 412 stale precondition, and a 5xx do not spend the key: the corrected request runs normally.

Terminal window
curl --cacert <state-dir>/api/tls.crt \
-H "Authorization: Bearer $(cat operator.token)" \
-H "Content-Type: application/vnd.swarmcracker.v1+json" \
-H "Idempotency-Key: 8f14e45f-ea1b-4c1f-9b1a-2f4b7f0d3a11" \
-d '{"name":"web","spec":{"task":{"image":"nginx:1.27-alpine"}}}' \
https://mgr:4244/v1/services

wait=converged and timeoutMs (service create, patch and rollback only). The response is held until status.converged is true or the budget expires (default 60000 ms, maximum 600000). A timeout is not an error: the mutation committed, so the normal 200/201 is returned with status.converged: false and warnings: [{"code": "wait_timeout", "message": "service did not converge within 150ms"}]. A manager read failure while waiting is warnings: [{"code": "wait_error", ...}] with the last good document. Wait requests are exempt from the normal 30 s request timeout and are bounded only by timeoutMs. wait on any other write route is 400 invalid, as is wait together with dryRun.

Terminal window
curl --cacert <state-dir>/api/tls.crt -X PATCH \
-H "Authorization: Bearer $(cat operator.token)" \
-H "Content-Type: application/merge-patch+json" \
-H 'If-Match: "17"' \
-d '{"spec":{"replicas":3}}' \
"https://mgr:4244/v1/services/web?wait=converged&timeoutMs=120000"

dryRun=true (create and patch). Validation, reference resolution and the preconditions run exactly as on the real call; nothing is persisted. The response has the normal status (201 create, 200 patch) with dryRun: true. A create preview has an empty id, revision and timestamps and checks that the name is free; a patch preview is the merged document carrying the current metadata. If-Match still applies (stale is 412) and If-None-Match: * against an existing name is still 409. A dry run writes no audit record. It is not supported on delete (400 invalid) or rollback (501 not_implemented with details.capability: "dryRun"): a delete has no document to preview, and the previous spec is not what a rollback would write.

Terminal window
curl --cacert <state-dir>/api/tls.crt \
-H "Authorization: Bearer $(cat operator.token)" \
-H "Content-Type: application/vnd.swarmcracker.v1+json" \
-d '{"name":"web","spec":{"task":{"image":"nginx:1.27-alpine"}}}' \
"https://mgr:4244/v1/services?dryRun=true"
Flag Default Description
--api-listen 127.0.0.1:4244 TLS listen address; empty disables the TCP listener
--api-socket <state-dir>/api.sock trusted Unix socket
--api-cert-dir <state-dir>/api directory holding tls.crt and tls.key
--api-token-file <state-dir>/api/tokens.json bearer token store
--api-audit-file <state-dir>/api/audit.jsonl append-only audit log
--api-audit-retention 720h how long audit records are kept
--api-disabled false do not start the API on this manager

An audit path that cannot be opened fails API startup rather than deferring the error to the first write.

Every node also serves the internal broker that backs exec, attach, logs, files and health:

Flag Default Description
--broker-listen 0.0.0.0:4245 mTLS listen address for the node broker; empty disables it
--snapshots-enable false enable the experimental snapshot capability on this node
--snapshot-dir /var/lib/firecracker/snapshots pkg/snapshot root (<id>/metadata.json is the source of truth)
--snapshot-timeout 5m deadline for one snapshot request relayed to a node; create copies the whole task disk

The manager always dials the fixed broker port 4245 and ignores any port in a node’s advertised address — the address is reduced to its host and 4245 is joined back on. A manager and its nodes must therefore agree on 4245; advertising node:9999 at registration does not move the broker. A node without a broker still serves the read API, but the manager’s relay to it fails: exec, attach, logs and files answer 503 unavailable, a single-task health read answers 503 unavailable, and a health-enriched task list answers 207 partial with that node in partial.

These flags belong to swarmd-firecracker. Defaults follow --state-dir, so moving the state directory moves the socket, certificate and token store with it.

TCP always verifies TLS, and there is deliberately no unverified mode. On first start the manager generates a self-signed certificate for its hostname, 127.0.0.1, ::1 and the host part of --api-listen, and writes it to <api-cert-dir>/tls.crt / tls.key.

Because the bootstrap certificate is self-signed, a remote client must trust it explicitly with --ca <api-cert-dir>/tls.crt. The client uses no system trust store and treats a missing --ca as a usage error rather than skipping verification. If the certificate does not name the address you dial, pass --tls-server-name. Signing the API certificate with the cluster CA is a follow-up, not part of phase 1 — rotate the bootstrap certificate by replacing the files in --api-cert-dir and restarting the daemon.

The Unix socket is trusted: it performs no token check, because the socket’s file mode (0600, owned by the daemon user) is the credential. Reach it with ssh or a local swarmcracker invocation, not through a TCP proxy.

Terminal window
# On the manager: print a new secret once, then hand it to the client.
swarmcracker api token create --name ci --role reader
# Inspect or revoke the store (local file; never contacts a manager).
swarmcracker api token list
swarmcracker api token revoke <token-id>

--role is reader, runner, operator or admin; each expands to a scope set (below). The secret is printed once at creation and only its SHA-256 hash is written to tokens.json, so it cannot be recovered later. The CLI’s --token-file names that store; without it the CLI uses <SWARM_STATE_DIR or /var/lib/swarmkit>/api/tokens.json. The daemon re-reads the file when it changes, so a token minted or revoked while the daemon runs takes effect without a restart.

Scopes are enforced server-side, deny by default: a route a token’s scopes do not cover answers 403 forbidden with details.requiredScope. Roles expand to scopes at mint time, and --scope can only narrow a role, never add to it.

Role Scopes Use
reader services:read, tasks:read, tasks:logs, nodes:read, networks:read, configs:read, secrets:read, events:read, cluster:read dashboards, monitoring, read-only CI
runner reader + tasks:exec, tasks:files, tasks:snapshots CI that builds or tests inside VMs
operator runner + services:write, networks:write, configs:write, configs:read-values, secrets:write deploys
admin everything, including nodes:write, migrations:write, tokens:admin, audit:read cluster administration

Every route names the scope it needs: /v1/version is cluster:read, /v1/services/{id}/tasks is tasks:read, /v1/audit is audit:read, and the other resource routes use their own *:read scope. The trusted Unix socket is a local administrator (type: "local", role admin) because its file mode is the credential.

A token may also carry task selectors, which restrict which tasks it can exec, transfer files to or snapshot. Selectors do not narrow the read routes: a runner still lists every task its tasks:read scope covers.

Terminal window
swarmcracker api token create --name build --role runner \
--service-id svc-0123456789abcdef \
--selector-label team=payments \
--scope tasks:read --scope tasks:exec \
--expires-at 2026-12-01T00:00:00Z

The three dimensions (--service-id, --task-id, --selector-label) are ANDed, and every label must match. A runner token must carry at least one selector: minting one without is refused, and an existing one without a selector fails closed with 403 forbidden and details.reason: "selector_required". operator and admin may omit selectors, which means all tasks. --expires-at takes an RFC3339 timestamp; an expired token answers 401 unauthenticated.

api token list shows SCOPES (all when the token still holds its whole role) and EXPIRES (- when it never expires), and never prints a hash or a secret.

Every mutation that reaches the backend is appended to a JSONL log on the manager (0600, one record per line, fsynced per append). A request rejected before the backend (415, 413, an undecodable body, a missing If-Match) is not recorded. Records are kept 30 days by default (--api-audit-retention). A crash-truncated or malformed line is skipped on load instead of making the log unreadable, and only the offending line is skipped — the records behind it are still read. A record larger than 1 MiB is refused rather than written, so one oversized entry cannot break the log.

Appending is best effort after the mutation has committed: a failed append (for example ENOSPC) is not surfaced to the caller and does not roll the write back, because failing the response would invite a retry that duplicates a create. That means a full or read-only audit file stops recording without an error in the API response; watch the manager’s log and the file itself.

The service writes above record service.create, service.update, service.delete and service.rollback; the config, secret, network and node writes record config.create, config.update, config.delete, secret.create, secret.update, secret.delete, network.create, network.delete and node.update; the relayed task operations record task.exec, task.attach, task.files, task.snapshot and task.restored.stop; and a migration attempt records task.migrate. A failed write records result: "error" with the reference or attempted name; a successful delete records the document as it was before removal.

Terminal window
# Needs an admin token: audit:read is admin-only. There is no CLI subcommand for
# the log yet, so read it with curl.
curl --cacert <state-dir>/api/tls.crt \
-H "Authorization: Bearer $(cat admin.token)" \
-H "Accept: application/vnd.swarmcracker.v1+json" \
"https://mgr:4244/v1/audit?limit=50"

GET /v1/audit?limit=&cursor= returns an AuditList ordered by at, then requestId, ascending. Each record names the actor (type: "token" with the token ID and name, or type: "local" for the Unix socket), the action, the resource, result (ok or error) and sourceIp — the TCP peer, never a forwarded header, and absent for a Unix-socket request. A write that used If-Match: * records precondition: "any"; an exact revision records precondition: "revision", so an unconditional update is visible in the log. Secret and config values are never recorded. A manager without an audit log answers 501 not_implemented with details.capability: "audit".

Remote reads are narrower than the read commands suggest. -o json works for service ls|inspect|ps, task ls, node ls, config ls, secret ls and network ls; -o name works only on the list commands (service ls, service ps, task ls, node ls, config ls, secret ls, network ls). service inspect is JSON-only and rejects -o name, and the non-service inspects — task, node, config, secret, network — have no contract path at all: they call the legacy client and are a usage error under --host. Only service ls has a remote table, so service ls, service ls -o table, -o json and -o name all work against --host.

Every other default table output is a usage error when --host is set (--host selects a remote manager: this command only supports the local control socket; use a read command with -o json or -o name), and any command outside the remote reads above is refused the same way. It never silently falls back to the local cluster. Without --host the same commands read the local socket, so a cluster member needs no flags.

Three mutations are remote-capable too: vm exec streams from the task’s node, vm attach carries the interactive console over POST /v1/tasks/{id}/attach (the same relay, tasks:exec), and vm snapshot stop-restored sends the DELETE to the node that holds the restored VM (-H is the only way to reach it from another machine). Without -H, vm attach keeps using the node-local console socket under --socket-dir.

Terminal window
swarmcracker -H https://mgr:4244 --ca <state-dir>/api/tls.crt \
--token-file reader.token service ls
swarmcracker -H https://mgr:4244 --ca <state-dir>/api/tls.crt \
--token-file reader.token service ls -o json
swarmcracker -H https://mgr:4244 --ca <state-dir>/api/tls.crt \
--token-file runner.token vm attach web-1 # Ctrl-P Ctrl-Q detaches

reader.token holds the raw secret (surrounding whitespace is trimmed). -o json prints a v1 document, but for lists it is not a byte-for-byte passthrough: the CLI follows every next cursor and rebuilds one document from the merged pages, so next is always null and any warnings/partial from the individual responses are dropped. Single-resource reads (service inspect) emit the one document they fetched. -o name prints identifiers one per line. JSON output is available on every remote read listed above.

A failed request answers with the ErrorDocument envelope — schemaVersion, kind: Error and error {code, message, requestId, retryable, details} — and the same requestId appears in the X-Request-Id response header. Codes are stable; messages are not. details is typed context, and four shapes are worth matching on: details.parameter names an unknown query parameter (400 invalid), details.cursor carries the value of a cursor this server did not issue (malformed or truncated, 400 invalid, with no reason), details.reason: "cursor_mismatch" means a well-formed cursor came from a different route or filter (400 invalid, and the value is not echoed back), and details.reason: "invalid_snapshot_id" means the snapshot id is not one safe path segment (400 invalid). The authoritative list of wire codes is the Error schema in api/openapi.yaml. The CLI maps its stable codes to process exit statuses in pkg/output (usage/invalid/unsupported_version → 2, not_found/ambiguous → 3, conflict → 4, unauthenticated/forbidden → 5, rate_limited/unavailable/timeout/unreachable → 6, partial → 7, anything else → 1). Exit 7 is the task ls --health partial result: the page printed, but at least one node could not be read.

Every authenticated token gets its own request bucket: 10 requests/second with a burst of 20 by default. The manager answers 429 Too Many Requests, code: "rate_limited", retryable: true, details.retryAfterMs, and a Retry-After header in seconds. Other tokens are unaffected. The daemon exposes --api-rate-limit and --api-rate-burst for operators who need a different budget. An event stream counts as one request, not one per event.