# Operations runbook

Each section is a short procedure. Take a backup before any step that changes the database:

```sh
shipyard backup -out /backups/shipyard-$(date +%F-%H%M).db
```

## Rotate a secret

Shipyard reads every secret from an environment variable named in the configuration (`*_env` settings) or, for the GitHub App key, from a file. Values are read at start, so a rotation is: set the new value, restart, revoke the old one.

| Secret | Setting | After the restart |
|---|---|---|
| Operator API token | `runtime.api_token_env` | Enter the new token in the console; revoke the old value wherever it was stored. |
| Model provider keys | `providers.*.api_key_env` or `api_key_file` | Revoke the old key at the provider. |
| GitHub App private key | `github_app.private_key_file` | Run `shipyard github check`, then delete the old key in the App settings. |
| GitHub webhook secret | `github_app.webhook_secret_env` | Change the secret in the App settings at the same time; deliveries signed with the old one get `401 invalid_signature` and can be redelivered from GitHub. |
| Alertmanager token | `alerts.token_env` | Update `http_config` in `alertmanager.yml`. |
| Prometheus query token | `prometheus.token_env` | — |
| Relay token | `remote.relay_token_env` | Update the Lighthouse relay with the same value. |

Infrastructure principals need no restart: issue a new token with `shipyard principal token -id ID -ttl 24h`, switch the client, and let the old token expire. If a token leaked, `shipyard principal revoke -id ID` revokes the identity and all its tokens at once; add it again with `principal add` and `grant`.

## Renew ship certificates

A ship's client certificate is valid for one year; the fleet CA for ten. A running ship renews its own certificate when less than 30 days are left. It checks at start and every 12 hours, sends a request for a fresh key and reconnects with the new certificate. The old certificate keeps working until the new one is first used, so a renewal cut short by a restart or a network drop never locks the ship out. A revoked ship cannot renew. Renewal needs a Shipyard of this version or newer; with an older one the ship logs *ship certificate renewal failed* and keeps working until the certificate expires.

A ship that was offline past its expiry stops with *ship certificate expired … join again with a new token*. Then:

1. Issue a join token: `shipyard ship token -name NAME` or Docks → **Add ship**.
2. On the ship, join into a new state directory (`join` leaves an existing identity alone): `ship join -server HOST:8443 -token SYP1.… -state /var/lib/ship-new`, then run the ship with that `-state`.
3. Revoke the old ship entry in Docks once the new one is online, and delete the old state directory.

Keep a backup of the database: it holds the fleet CA, and ships cannot reconnect to a Shipyard that lost it.

## Rate limits

**Model providers.** A `429` or `529` answer does not fail a run: it moves to **Waiting** with the time it resumes, and a notice in the console names the limited models. Nothing to do unless it repeats; then lower the run rate or move the role to another model in `models`. Cancel waiting runs you no longer need.

**GitHub.** When the App is rate-limited (`429`, or `403` with no remaining quota, or `Retry-After`), reconciliation logs `github reconciliation rate limited` with the reset time and postpones the next pass until then. Webhooks keep arriving and are applied meanwhile; the GitHub view marks repositories **Stale** if the pause outlasts two reconciliation intervals. If it happens on every pass, raise `github_app.reconcile_every`.

## Recover the queue after a crash

On start, every worker returns runs whose lease expired (30 s without a heartbeat):

- interrupted **diagnostics** are queued again after 2 s, then 4 s, and fail as *dead-lettered* once out of attempts;
- other interrupted runs fail with *worker lease expired; execution may have been interrupted*, because repeating them could repeat side effects. Retry them from the console after checking what they did.

Every recovery is in the run history as *Recovered after interruption*. Webhook deliveries are stored before GitHub gets an answer and applied in order after a restart, so none are lost; a redelivery is recognised and ignored.

If the database itself is damaged, stop Shipyard, restore the newest backup at `storage.path`, start it, and run `shipyard journal verify -expect <saved head>`. If you prune the journal, keep the archive directory with the backups and verify with `shipyard journal verify -archive DIR -expect <saved head>`.

## Restart a service

`serviceRestart` restarts one systemd service on a ship after a second person approves it in Bosun. Shipyard, the ship and the host each keep their own list; all three must allow the service.

1. On the host, allow the ship user to restart exactly these units in `/etc/polkit-1/rules.d/50-shipyard-ship.rules`:

   ```js
   polkit.addRule(function (action, subject) {
       var units = ["nginx.service", "app@blue.service"];
       if (action.id == "org.freedesktop.systemd1.manage-units" &&
           subject.user == "ship" &&
           action.lookup("verb") == "restart" &&
           units.indexOf(action.lookup("unit")) >= 0) {
           return polkit.Result.YES;
       }
   });
   ```

   The ship keeps `NoNewPrivileges=true`; no sudoers entry is needed. A unit missing here fails with `restart_denied` and nothing changes; when the ship starts it checks the rule with `pkcheck` and records a `ship.restart_mismatch` event naming the units polkit would refuse (no `pkcheck`, no systemd or no answer within five seconds: no event).
2. Set the same names without `.service` on the ship, `SHIP_SERVICE_RESTART=nginx,app@blue`, and restart it. The host page lists them under the capabilities.
3. Set `infra.mutations.enabled: true` in Shipyard and restart it.
4. Give requesters `tasks.create` on the host, and approvers `tasks.approve` and a paired Bosun phone.

A request waits in *queued* until another person approves it in Bosun; the approval is used once. A restart whose end is not known (deadline, lost connection, cancel while running, or a restart that ran but whose service state could not be read, reason `state_unreadable`) ends *unknown* and is never repeated: check the service, then ask again.

To switch it off, any one step is enough: `infra.mutations.enabled: false`, unset `SHIP_SERVICE_RESTART` and restart the ship, or remove the polkit rule. Before rolling back to a release without `serviceRestart`, switch it off and wait five minutes, the longest task deadline.

## Roll back an upgrade

Database migrations run forward on start and are not reversible; an older binary refuses a database written by a newer one (*unsupported storage schema version*). To roll back:

1. Stop Shipyard.
2. Restore the backup taken before the upgrade at `storage.path`.
3. Start the previous binary or image.

Runs and deliveries recorded after the backup are lost, so take the backup immediately before upgrading. Ships keep working across a rollback as long as the restored database is the one they joined.

## Update ships

A ship replaces its own binary only when both sides opt in: `fleet.ship_update` on Shipyard and `SHIP_UPDATE=on` on the ship. Every release is signed with Ed25519, and the ship checks the signature with the keys built into its installed binary before it runs anything. A release signed with any other key is refused, on import and on the ship.

**1. Sign a release** on the signing machine, never on Shipyard:

```sh
shipyard ship release keygen -out release.key   # only for a new key: its public half must be built into the binaries first
make build-all
shipyard ship release sign -key release.key -dir bin -version 1.4.2 -floor 1.3.0
```

`-floor` is the lowest version any ship may run after this release; ships remember the highest floor they have seen.

**2. Import** on the Shipyard host and check it:

```sh
shipyard ship release add -dir DIR
shipyard ship release list
```

**3. Start with a canary.** Label one or two ships `ring=canary`, then in the configuration file:

```yaml
fleet:
  ship_update:
    enabled: true
    version: 1.4.2
    labels: [ring=canary]
```

Restart Shipyard. Watch the version in Docks and the `ship.update_*` events in the ship's history (Docks → History, with `infra.enabled`). When the canaries run well, remove `labels` and restart.

**4. Turn it on on a ship:** add `SHIP_UPDATE=on` to `/etc/ship/ship.env` and `sudo systemctl restart ship`. The ship refuses to start when its binary or the binary's directory is writable by the `ship` user, or when it runs in a container, Kubernetes or Homebrew. It downloads an offered release while idle, verifies it, waits for its run, task and SSH sessions to end, and exits; systemd starts the new version. More in [Ships](/ships/#self-update).

**5. A ship rolled back.** A version that fails three starts in a row (exits before its first lease) is replaced by the previous one, then by the installed binary. Read why on the ship and in its history:

```sh
sudo -u ship ship update status -state /var/lib/ship
```

The first lines are the `SHIP_UPDATE` setting and the install kind the ship detected. That ship never takes the rolled-back version again. Fix the cause and publish a new version.

**6. Stop a rollout:** set `enabled: false` and restart Shipyard. Ships keep the version they run.

**7. Go back.** Set `version` to an older imported release with `allow_downgrade: true`. Ships never go below the floor or to a version at or below their installed binary. Below that, reinstall `/usr/local/bin/ship` by hand and delete `/var/lib/ship/update`.

**8. Rotate or revoke the key.** Release N, signed with key A, carries keys A and B in its binaries; release N+1 is signed with B. A ship whose installed binary does not know B refuses N+1 and stays on what it runs; reinstall it by hand. If a key leaks: remove it in the next release, raise `-floor` above every release it signed, and reinstall the installed binaries.

**9. Containers, Kubernetes and Homebrew** do not update themselves: update the image or the package.

`deploy/freebsd/ship` (rc.d, restarted by `daemon`) and `deploy/launchd/ship.plist` (`KeepAlive`) restart the ship like systemd does; they have not been tried on real FreeBSD or macOS hosts yet.
