# Run a fleet of hosts (https://kumoba.dev/guide/fleet)

One kumobad runs as many sandboxes as one machine can hold. When you need more, or your application runs where there is no `/dev/kvm`, run kumobad on several machines and put `kumobad fleet` in front of them. The fleet serves kumobad's own HTTP API, so the CLI and the SDKs work against it once you change their URL. It picks a host for each new sandbox, tries the next one when a host is full, and forwards every later call and preview to the host that runs the sandbox.

```
your app ──(kumobad API)──> kumobad fleet ──TLS, client certificate, token──> each host's API (7788)
browser ──(previews)──────> kumobad fleet ──TLS, preview token only─────────> each host's previews (7789)
```

The fleet keeps no table of sandboxes. Each sandbox id names its host, so several fleet processes can serve the same hosts without talking to each other. The only state is the hosts file.

## Get each host ready [#get-each-host-ready]

On each machine, `kumobad host init` sets kumobad up to serve the fleet: it makes the host's TLS certificate and a CA for client certificates, turns on the network listeners, and prints a pairing code; [Set up a host for a fleet](/guide/remote-daemon#set-up-a-host-for-a-fleet) has the details. You can also set up TLS yourself, as [Run sandboxes on another machine](/guide/remote-daemon) shows, and add the host with its URL and token below. Optionally give each host labels for placement:

```sh
KUMOBAD_HOST_LABELS=zone=a,gpu=none kumobad
```

A kumobad on the fleet's own machine can be a host over its Unix socket, so one machine can be a fleet of one.

Hosts must run the fleet's kumoba version or the one before it (for example 0.10.x and 0.9.x under a 0.10 fleet), and a release that has `GET /v1/info`. The fleet refuses other hosts and says which versions it takes.

## Add the hosts [#add-the-hosts]

On the fleet machine, add each host with the pairing code it printed:

```sh
kumobad fleet add kfp1.eyJ1cmwiOiJodHRwczovLz... --label rack=r1
```

The fleet dials the URL in the code, accepts only the certificate whose SHA-256 fingerprint the code carries, and sends the code's one-time token with a certificate signing request. The host signs a client certificate for the fleet and returns it with its bearer token; the fleet keeps them, the client key it made and the pinned fingerprint, and uses mutual TLS from then on. A code works once and for about an hour; `kumobad host pair-code` on the host prints a new one. When the fleet reaches the host at another address than the code names, such as through NAT, add `--url https://...:7788` (and `--preview-url`); with a code the URL must be `https://`, since the fingerprint is checked only over TLS. `--name` sets the name in the client certificate (default `kumobad-fleet`). The output says when the client certificate expires (one year after pairing); before then, or to rotate the fleet's credentials, pair again with a new code:

```sh
kumobad fleet repair HOST_ID kfp1.eyJ1cmwiOiJodHRwczovLz...
```

`repair` replaces the fleet's certificate, key and token for that host and keeps its labels. It refuses a code that pairs a different host. Its URL comes from `--url` or else the new code; its preview URL from `--preview-url`, else the new code, else the one saved for the host.

A code given as an argument can be read by any local user from `ps` while the command runs, and it stays in shell history. Scripts and tools that drive the fleet should pass it with `--code-file FILE` instead, or `--code-file -` to read it from stdin; both commands take it, with the same other options:

```sh
printf '%s\n' "$CODE" | kumobad fleet add --code-file - --label rack=r1
kumobad fleet repair HOST_ID --code-file /run/secrets/pair-code
```

A byte order mark and surrounding whitespace and line breaks are ignored. A file that does not hold a pairing code, or is larger than 64 KiB, is refused before anything is spent or written, and `--code-file` together with a code argument is refused.

The fleet checks what it can before it uses a code: the URL and preview URL, and whether the code's fingerprint belongs to a host already in the fleet (then `add` points you to `repair`, and the code stays unused). A check that needs the host's answer, such as its version or the `hostId` it reports, can only fail after pairing; the error then names the client certificate the host issued (its CN and serial), which stays valid until it expires or `kumobad host init --force` on the host replaces its client CA.

To add a host whose credentials you copied yourself, give its API URL and token instead. Trust its certificate with its CA (`--ca`) or by its SHA-256 fingerprint (`--fingerprint`), and present a client certificate with `--cert` and `--key` when it asks for one:

```sh
kumobad fleet add --url https://host-a.example.com:7788 \
  --preview-url https://host-a.example.com:7789 \
  --token-file host-a.token --ca host-ca.pem \
  --cert fleet.pem --key fleet.key --label rack=r1
kumobad fleet add --url unix:///home/me/.kumoba/kumobad.sock \
  --token-file ~/.kumoba/token
```

Either way, `fleet add` asks the host for its `/v1/info` first, checks its version, and saves it under the `hostId` it reports. It refuses a host whose id is already in the fleet. That happens when one machine's state directory was copied to another (a cloned VM or machine image): delete `host-id` in the copy's `KUMOBAD_STATE_DIR` and restart it. Labels given to `--label` are merged with the host's own labels; the fleet's win when both set a key.

The hosts file is `~/.kumoba/fleet/hosts.json` (`KUMOBA_FLEET_HOSTS`). Tokens, client keys and certificates in it are encrypted with ChaCha20-Poly1305 under the key in `~/.kumoba/fleet/key` (`KUMOBA_FLEET_KEY_FILE`, created on first use, mode 0600). Keep that key out of backups of the hosts file, or set `KUMOBA_FLEET_KEY_FILE` to a file on another volume or from your secret store: the hosts file alone reveals no credentials. Each host's credentials are also bound to its entry: changing its `url`, `previewUrl` or labels by hand makes them unreadable, so an edit of the file can't send a host's token elsewhere (use `kumobad fleet repair` to move a host). Without the key the saved hosts can't be used: the fleet refuses to start with a hosts file and no key instead of making a new one, and you restore the key or add the hosts again. It logs `fleet_key_readable` when others can read the key.

## Start the fleet [#start-the-fleet]

```sh
kumobad fleet
```

With nothing set it listens on `~/.kumoba/fleet.sock`, on `127.0.0.1:7798` for the API and `127.0.0.1:7799` for previews, so it runs beside a local kumobad. The settings follow kumobad's with `KUMOBA_FLEET_` in place of `KUMOBAD_`: `KUMOBA_FLEET_SOCKET`, `KUMOBA_FLEET_LISTEN`, `KUMOBA_FLEET_PREVIEW_LISTEN`, `KUMOBA_FLEET_PREVIEW_URL` and `KUMOBA_FLEET_TLS_CERT`, `KUMOBA_FLEET_TLS_KEY`, `KUMOBA_FLEET_TLS_CLIENT_CA`; an address other than loopback needs TLS. The fleet's own token is `~/.kumoba/fleet/token` (`KUMOBA_FLEET_TOKEN_FILE`), apart from any host's. `SIGHUP` re-reads it and the TLS files.

Point clients at it:

```sh
export KUMOBA_URL=unix://$HOME/.kumoba/fleet.sock
export KUMOBA_TOKEN_FILE=~/.kumoba/fleet/token
kumoba create --image default --start
```

`kumobad fleet add` and `remove` change the hosts file, and a running fleet picks the change up at its next health check, with no restart.

## How the fleet places sandboxes [#how-the-fleet-places-sandboxes]

A create with `"start": true` and `POST /v1/run` go to a host that:

- answered its last health checks, is not draining and runs a version the fleet takes;
- serves the image;
- carries every label in the request's `placement`, such as `"placement": {"zone": "a"}`.

Among those it takes the one with the most free running slots, trying hosts that report free disk above their `KUMOBAD_MIN_FREE_DISK_MIB` before those that do not, so a host that would have to prune is tried last. When that host answers 429 because it filled up meanwhile, or 507 `disk_full` because its disk is short, the fleet tries the next one at once; when every host it tried was short of disk it answers 507 `disk_full` at once, even with `waitMs`, and names those hosts in `diskFullHosts` (503 `host_unavailable` when some hosts did not answer). See [Free disk on a host](#free-disk-on-a-host). When all are full it answers 429 `capacity` with `Retry-After: 5`, or, with `waitMs`, keeps trying every 250 ms until then (with a single matching host it hands `waitMs` to that host, which serves waiting requests in order). A create without `start` goes to the host with the most free slots. For a macOS image the fleet skips hosts whose macOS slots are all taken and ranks the rest by their free macOS slots, from the image's `kind` in `/v1/info`. A host on the previous kumoba version reports no `kind`; the fleet ranks it by its running slots and lets its own 429 move the request on. Hosts with `KUMOBAD_ADMIT_BY_MEMORY=1` report a memory budget, and for a Linux image the fleet uses it: it skips hosts whose whole budget is smaller than the sandbox's `memoryMib` (4096 when the create names none), and ranks the rest by the smaller of their free slots and how many such sandboxes their free memory holds, so a host whose memory is taken is not tried first. A host whose budget is full answers 429 and one too small for the sandbox answers 422 `exceeds_host_memory`; either way the fleet moves on. When no host's budget can ever hold the sandbox, the fleet answers 422 `exceeds_host_memory` at once, even with `waitMs`.

## Health, drain and versions [#health-drain-and-versions]

The fleet checks every host on `/healthz`, `/v1/capacity` and `/v1/info` every 2 s (`KUMOBA_FLEET_POLL_MS`). After 3 failed checks in a row (`KUMOBA_FLEET_UNHEALTHY_AFTER`) a host gets no new sandboxes, and calls on its sandboxes answer 503 `host_unavailable` until it answers again. A call to a host that stopped answering between checks answers the same right away. The fleet logs `fleet_host` each time a host changes state.

To take a host out of service, for an upgrade or to retire it:

```sh
kumobad fleet drain HOST_ID        # add --strict to refuse starts of stopped sandboxes too
kumobad fleet undrain HOST_ID
```

This drains the host itself, so it refuses new sandboxes from every client, not only from this fleet; running sandboxes carry on. For a rolling upgrade, drain a host, wait until its running count reaches 0 in `kumobad fleet list`, upgrade and restart it (with `KUMOBAD_DRAIN_ON_START=1` if you want to check it first), then undrain it.

`kumobad fleet list` prints each host's state (`active`, `draining`, `unhealthy` or `refused`), version, labels, images, capacity and last error as JSON; `GET /v1/fleet/hosts` on a running fleet returns the same. `kumobad fleet check` prints one line per host and exits 1 when one is not usable:

```
d371e8385e751d26 https://host-a.example.com:7788: active tls version=0.10.0 guest=3 hypervisor=yes images=default running=1/4
345f7ed97ec0b278 https://host-b.example.com:7788: FAIL unhealthy (host 345f7ed97ec0b278 is unavailable: connecting timed out)
```

## Move sandboxes between hosts [#move-sandboxes-between-hosts]

A stopped sandbox lives on the host that created it. To move one, or to empty a host you drain:

```sh
kumobad fleet move HOST_A.SANDBOX_ID HOST_B   # or leave HOST_B out for the active host with the most free disk
kumobad fleet drain HOST_A --move-stopped     # drain, then move every stopped sandbox off it
```

Both export the sandbox from its host, import it on another active host of the same architecture and guest protocol, and only then delete the original, printing a line `{"from": "...", "to": "..."}` per sandbox with its new id. Without a named host the fleet picks among the hosts with room for the disk, and a drain spreads its moves across the hosts with room, sending each to the one that has taken the fewest bytes so far; a host that refuses the import (short of disk, draining, or the disk is larger than its images) passes it to the next.

- A moved sandbox takes its whole disk on the new host, even where it shared most of it with its image on the old one, so a host taking many moves needs that much free space.
- The original is deleted only if it is still stopped as it was when it was exported. If it was started in between, it stays, the copy is removed, and the line has an `error`; move it again.
- A sandbox that fails stays where it was, with an `error` in its line, and `drain --move-stopped` exits 1. If the reply to an import is lost, the copy may already exist on the new host while the original stays too; running the same command again finds that copy by its `movedFrom` key and finishes the move instead of copying again.
- Secrets stay behind: set them again on the new host. Running sandboxes are not moved: stop them, or let them stop, and run the command again. A host that is down can't export, so move sandboxes off a host while it still answers.

Through the fleet API, `GET /v1/sandboxes/{id}/export` reaches the sandbox's host and `POST /v1/sandboxes/import?host=HOST_ID` sends an archive to that host, or to the active host with the most free disk without `host`.

A host whose `/v1/info` reports a different `hostId` than the one it was added with is `refused`, and calls on its ids answer `host_unavailable`, because the machine at that address is no longer the one the fleet knew. Remove and add it again.

## Free disk on a host [#free-disk-on-a-host]

A create that every matching host refuses for disk answers 507 `disk_full` with `diskFullHosts`, the ids of those hosts. Prune their old stopped sandboxes through the fleet, then create again. A host with `KUMOBAD_PRUNE_STOPPED_ON_DISK_PRESSURE_MS` set does this itself: it deletes its own old stopped sandboxes until the create fits, so it answers 507 only when those could not make room (see [Configuration](/configuration#daemon-kumobad)). With `KUMOBA_URL` pointing at the fleet:

```sh
kumoba prune-stopped --older-than-ms 86400000 --host HOST_ID --dry-run   # list what would go
kumoba prune-stopped --older-than-ms 86400000 --host HOST_ID             # delete it
kumoba prune-stopped --older-than-ms 86400000                            # every host
```

The fleet runs each host's own prune, so a host keeps the safety it has alone: it leaves running, booting and busy sandboxes and creates that have not answered yet, deletes only sandboxes stopped for at least `--older-than-ms`, and with `--dry-run` deletes nothing. The reply lists what went, with fleet ids, the bytes freed per host under `hosts`, and under `failedHosts` every host that did not prune and why. A host with `"mayHavePruned": true` got the request but its answer was lost, or took longer than 30 s when pruning every host, so some of its sandboxes may be gone; its `deleted` events in `GET /v1/events` show which, and pruning it alone with `--host` waits for its whole answer. The fleet answers 200 when any host pruned and 503 `host_unavailable` when none did. Running it again is safe. `kumoba.pruneStopped({ olderThanMs, host })` is the TypeScript form.

## Metrics [#metrics]

`GET /metrics` on the fleet, with the fleet's token, serves every active or draining host's own metrics with a `host` label, plus each host's state, drain and running slots. One Prometheus job on the fleet is enough to graph capacity, boot times and refusals across hosts:

```yaml
scrape_configs:
  - job_name: kumobad-fleet
    authorization:
      credentials_file: /etc/prometheus/kumobad-fleet.token
    static_configs:
      - targets: ["127.0.0.1:7798"]
```

`kumobad_fleet_host_metrics_up` is 0 for a host the fleet could not read or whose answer was not valid Prometheus text, and `kumobad_fleet_host_state` tells a host that is down from one that answered badly. See [Metrics](/http-api#metrics) for every series.

## What differs from one kumobad [#what-differs-from-one-kumobad]

The fleet answers kumobad's API with these differences; the [HTTP API](/http-api#fleet) lists them in full.

- Sandbox ids are `<hostId>.<sandboxId>`.
- Preview paths are `/v1/preview/<hostId>/<token>/...`, and `expose` and `desktop` links point at the fleet's preview listener, which forwards them to the host, WebSockets included.
- `GET /v1/capacity` sums the hosts and lists them under `hosts`; `GET /v1/sandboxes`, `GET /v1/events` and `GET /v1/access-log` merge all hosts and name those that did not answer in `unavailableHosts`. The event feed and the access log come host by host, each in its host's recorded order, with one cursor that holds every host's position.
- `POST /v1/sandboxes/prune-stopped` takes `host` to prune one host; without it every host prunes, and the reply names the hosts that did not in `failedHosts`.
- `GET /v1/info`, `POST /v1/drain` and `DELETE /v1/drain` answer 400: read hosts with `GET /v1/fleet/hosts` and drain them with `kumobad fleet drain`.