Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
96 changes: 92 additions & 4 deletions deploy/selfhost/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,7 @@ including `selfhost-hosted-git-v1` when present in that checkout, participate in
(`scripts/selfhost/upgrade-migrations.ts:installedMigrations`, `assertMigrationProgression`).

The command requires a clean tracked checkout and an installation-specific Compose project with
creation receipts. It checks out the target, runs `deploy --init`, rebuilds changed local images,
creation receipts (an older `sam-selfhost` install first needs `--adopt-legacy`, below). It checks out the target, runs `deploy --init`, rebuilds changed local images,
restarts Compose when its inputs changed, deploys and checks health. Failure automatically restores
the encrypted snapshot and previous code/dependencies before starting the previous version.
The recovery checks the original installation, bucket, state and Compose ownership before removing
Expand Down Expand Up @@ -287,9 +287,97 @@ and Compose operation uses that installation's environment and overlays. Set
`SAM_SELFHOST_STATE_DIR` to an absolute path when running Compose manually.

Older installs using the shared `sam-selfhost` project may set `COMPOSE_PROJECT_NAME=sam-selfhost`
explicitly for backup. Upgrades and destructive teardown refuse that shared identity. Move to a
separate, installation-specific Compose project through an operator-controlled migration first;
these commands do not adopt or automatically migrate the old project.
explicitly for backup. Upgrades and destructive teardown refuse that shared identity. Move such an
install to its installation-specific project with legacy adoption (below) first.

### Upgrade an install created before the shared project was retired

Installs created before `pnpm selfhost:upgrade` gained snapshots run under the fixed Compose
project `sam-selfhost` and have no compose creation receipt, so a plain upgrade refuses them. Their
own checkout also still holds the old upgrade tool. Check out the new SAM ref, then let its tool
adopt the install and upgrade it in one command. `--from` is the full 40-character commit the
stack runs now, and `--to` must resolve to the checked-out ref:

```sh
git fetch origin && git checkout --detach <target-ref> && pnpm install --frozen-lockfile
pnpm selfhost:upgrade --adopt-legacy --from <deployed-full-sha> --to <target-ref> \
--encryption-key-file "$HOME/.config/sam/backup.key"
```

`--adoption-backup-to` chooses the adoption snapshot's path (default
`backups/pre-adoption-<timestamp>` next to the state directory). `--backup-to` applies to the
upgrade that follows. `--from` and `--adoption-backup-to` require `--adopt-legacy`, which cannot
be combined with `--rollback-from` or `--rebuild`. The checkout must be clean for tracked files.
The shell must not set `COMPOSE_PROJECT_NAME`, and the box `.env` must leave it unset or set it to
`sam-selfhost`. An install that already has its compose creation receipt is refused: use the plain
upgrade.

The running stack is not touched by the checkout. Adoption changes no SAM code and deploys
nothing (`scripts/selfhost/legacy-adoption.ts:runLegacyAdoption`):

1. It checks out `--from` again, so the compose files and bind mounts match the running stack.
2. It proves ownership (`legacy-adoption-inventory.ts:proveLegacyOwnership`):
- every container of the `sam-selfhost` project carries this checkout's compose directory,
compose files and `.env`; a missing label refuses;
- bind mounts stay inside this checkout or its state directory;
- each project volume is used only by those containers;
- each container's config hash equals `--from`'s compose configuration;
- there is exactly one running celld;
- the canonical project is empty.

Another checkout on the same host using `sam-selfhost`, or a wrong `--from`, refuses before
any change.

3. It takes the encrypted backup from the live legacy stack.
4. It stops the legacy stack, journaling the intent first. It copies each volume into
`<canonical>_<volume>` with a digest-pinned Alpine image, the egress fence's own base, which it
pulls before changing anything if the box does not have it. The helper runs with no network,
all capabilities dropped except the file-ownership ones a faithful copy needs, and a label
carrying a random adoption id. Each copy is verified by a digest of every path's type, owner and
mode and every file's content.
5. It writes `COMPOSE_PROJECT_NAME=<canonical>` into `.env`, keeping every other byte, then starts
the same version under that project and checks health. After health it writes the installation
and compose-project creation receipts and removes the stopped legacy containers.
6. It runs the normal upgrade from `--from` to the target, with its own fresh snapshot, automatic
rollback and printed rollback command.

Each step is journaled (phases `proving`, `backed-up`, `stopped`, `switched`, `adopted`) in
`legacy-adoption.json` in the state directory, beside `legacy-adoption.env`, a private copy of the
original `.env`. Both are removed when the run succeeds or rolls back completely. If the process is
killed, check out the target ref again and rerun the identical command:

- it resumes at the recorded step;
- it removes any helper container the killed run left (only those with its adoption id);
- it recopies an unfinished volume from scratch;
- a backup interrupted mid-way is kept and a new one is taken, after restarting the legacy celld
it may have left stopped;
- a stop that completed before its phase was journaled resumes from the stopped stack;
- a rollback that was interrupted is finished as a rollback, never resumed forward;
- an upgrade that already completed is not run again.

The upgrade marks the adoption journal while its own completed marker is still durable, so a
re-checkout of the target cannot make a finished upgrade look unstarted.

A refusal or failure before the legacy stack stopped returns the checkout to the target and
discards the journal. A later failure, or an unhealthy new project, rolls back to `sam-selfhost`:

- it journals the rollback first, so a killed rollback is finished on the next run;
- if the new stack ran, it first copies each of its volumes back over the legacy one,
digest-verified: the celld cache, Caddy's certificates and, with `local-store`, the bundled
bucket itself, so nothing the new stack wrote is lost;
- it removes the canonical containers and the volumes it created;
- it restores `.env` byte for byte and restarts the legacy stack.

Before the new stack starts, the legacy volumes are only read. Adoption never restores the bucket
from its snapshot: the same deployed version kept writing it. After such a rollback the checkout stays at `--from`, which matches the
running stack. If the rollback itself fails, the journal, the `.env` copy and the legacy volumes
are kept. Inspect the stack (`docker compose -p sam-selfhost ps`) before rerunning, and do not
delete those files to get past the error.

If the upgrade step fails, its automatic rollback restores `--from` under the adopted project; the
adoption stands and its journal remains. Check out the target and rerun the same command to retry
the upgrade. After a successful run the legacy volumes remain until you remove them with the
`docker volume rm` command it prints.

## Teardown

Expand Down
233 changes: 233 additions & 0 deletions scripts/selfhost/legacy-adoption-inventory.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,233 @@
/**
* Ownership proof for a pre-L24 install that still runs under the shared `sam-selfhost` Compose
* project (legacy-adoption.ts). Every container and volume of that project must provably belong
* to this checkout, .env and state directory; anything ambiguous refuses before a change.
*/
import { realpathSync } from 'node:fs';
import { dirname, relative, resolve } from 'node:path';

import { type BoxContext, check } from './backup-lib';

/** The fixed project name every pre-L24 docker-compose.yml declared (`name: sam-selfhost`). */
export const LEGACY_COMPOSE_PROJECT = 'sam-selfhost';

const PROJECT_LABEL = 'com.docker.compose.project';
const SERVICE_LABEL = 'com.docker.compose.service';
const VOLUME_LABEL = 'com.docker.compose.volume';
const HASH_LABEL = 'com.docker.compose.config-hash';
const CONTAINER_ID = /^[a-f0-9]{64}$/;
const VOLUME_SUFFIX = /^[a-z0-9][a-z0-9_.-]*$/;

export interface LegacyContainer {
id: string;
service: string;
running: boolean;
}
export interface LegacyVolume {
/** The compose volume key (`celld-data`); the Docker name is `<project>_<suffix>`. */
suffix: string;
name: string;
}
export interface LegacyInventory {
containers: LegacyContainer[];
volumes: LegacyVolume[];
}

interface Inspected {
Id?: unknown;
State?: { Running?: unknown };
Config?: { Labels?: Record<string, unknown> | null };
Mounts?: { Type?: unknown; Name?: unknown; Source?: unknown }[] | null;
}

const refuse = (why: string): never => {
throw new Error(`Legacy adoption refused: ${why}`);
};

function lines(text: string): string[] {
return text
.split('\n')
.map((line) => line.trim())
.filter(Boolean);
}

function json(text: string, what: string): unknown {
try {
return JSON.parse(text);
} catch {
return refuse(`cannot parse ${what}`);
}
}

function real(path: string): string {
try {
return realpathSync(path);
} catch {
return resolve(path);
}
}

function inside(root: string, path: string): boolean {
const rel = relative(root, path);
return rel === '' || (rel !== '..' && !rel.startsWith('../') && !rel.startsWith('/'));
}

/** Container IDs carrying `label`, all states. */
export function containersLabelled(ctx: Pick<BoxContext, 'run'>, label: string): string[] {
const ids = lines(
check(
ctx.run('docker', ['ps', '--all', '--quiet', '--no-trunc', '--filter', `label=${label}`]),
'list compose containers'
).stdout
);
if (ids.some((id) => !CONTAINER_ID.test(id))) refuse('unexpected container identifier');
return ids;
}

/** Volume names carrying `label`. */
export function volumesLabelled(ctx: Pick<BoxContext, 'run'>, label: string): string[] {
return lines(
check(
ctx.run('docker', ['volume', 'ls', '--quiet', '--filter', `label=${label}`]),
'list compose volumes'
).stdout
);
}

/** `service hash` pairs for the active services of `--from`'s compose configuration. */
function configHashes(output: string): Map<string, string> {
const hashes = new Map<string, string>();
for (const line of lines(output)) {
const [service, hash, extra] = line.split(/\s+/);
if (!service || !hash || extra !== undefined || !/^[a-f0-9]{64}$/.test(hash))
refuse('cannot read the compose configuration hashes');
hashes.set(service as string, hash as string);
}
return hashes;
}

export interface ProveOptions {
legacyProject: string;
/** Root of this checkout: bind mounts may come only from here or from the state directory. */
checkoutRoot: string;
/** `docker compose ... config --hash '*'` for the legacy project at `--from`. */
configHashOutput: string;
/** Before the stop: the legacy stack must be live, with exactly one running celld. */
requireRunningCelld: boolean;
}

/**
* Proves the legacy project is this checkout's install: container labels name this compose
* project directory, these compose files and this .env; bind mounts stay inside the checkout or
* the state directory; the config hashes equal `--from`'s configuration; and each project volume
* is used only by those containers. Returns the inventory adoption will move.
*/
export function proveLegacyOwnership(

Check failure on line 125 in scripts/selfhost/legacy-adoption-inventory.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Refactor this function to reduce its Cognitive Complexity from 58 to the 15 allowed.

See more on https://sonarcloud.io/project/issues?id=raphaeltm_simple-agent-manager&issues=AaH3nn9NUgvRZIAyv8-B&open=AaH3nn9NUgvRZIAyv8-B&pullRequest=2932
ctx: Pick<BoxContext, 'run' | 'envFile' | 'stateDir' | 'composeFiles'>,
opts: ProveOptions
): LegacyInventory {
const projectLabel = `${PROJECT_LABEL}=${opts.legacyProject}`;
const ids = containersLabelled(ctx, projectLabel);
if (ids.length === 0) refuse(`no containers belong to compose project ${opts.legacyProject}`);
const inspected = json(
check(ctx.run('docker', ['inspect', ...ids]), 'inspect legacy containers').stdout,
'container inspection'
);
if (!Array.isArray(inspected) || inspected.length !== ids.length)
refuse('container inspection does not match the project inventory');

const workingDir = real(dirname(ctx.composeFiles[0] ?? ''));
const configFiles = ctx.composeFiles.map(real).join(',');
const envFile = real(ctx.envFile);
const stateDir = real(ctx.stateDir);
const checkoutRoot = real(opts.checkoutRoot);
const hashes = configHashes(opts.configHashOutput);
const mountedBy = new Map<string, Set<string>>();
const containers: LegacyContainer[] = [];

for (const item of inspected as Inspected[]) {
const id = typeof item.Id === 'string' ? item.Id : '';
if (!ids.includes(id)) refuse('container inspection returned an unlisted container');
const labels = item.Config?.Labels ?? {};
const label = (name: string) => (typeof labels[name] === 'string' ? labels[name] : '');
if (label(PROJECT_LABEL) !== opts.legacyProject) refuse(`container ${id} changed project`);
if (
!label('com.docker.compose.project.working_dir') ||
!label('com.docker.compose.project.config_files') ||
!label('com.docker.compose.project.environment_file')
)
refuse(
`container ${id.slice(0, 12)} of project ${opts.legacyProject} belongs to another checkout, compose file set or .env (labels missing)`
);
const files = label('com.docker.compose.project.config_files')
.split(',')
.filter(Boolean)
.map(real)
.join(',');
if (
real(label('com.docker.compose.project.working_dir')) !== workingDir ||
files !== configFiles ||
real(label('com.docker.compose.project.environment_file')) !== envFile
)
refuse(
`container ${id.slice(0, 12)} of project ${opts.legacyProject} belongs to another checkout, compose file set or .env`
);
const service = label(SERVICE_LABEL);
const expectedHash = hashes.get(service);
if (!expectedHash)
refuse(`service ${service || '(none)'} is not in the --from compose configuration`);
if (label(HASH_LABEL) !== expectedHash)
refuse(
`service ${service} does not match the --from compose configuration; pass the deployed commit`
);
for (const mount of item.Mounts ?? []) {
if (mount.Type === 'bind') {
const source = typeof mount.Source === 'string' ? real(mount.Source) : '';
if (!inside(checkoutRoot, source) && !inside(stateDir, source))
refuse(`service ${service} mounts a path outside this checkout and state directory`);
} else if (mount.Type === 'volume') {
const name = typeof mount.Name === 'string' ? mount.Name : '';
if (!name.startsWith(`${opts.legacyProject}_`))
refuse(`service ${service} mounts a volume of another project`);
mountedBy.set(name, (mountedBy.get(name) ?? new Set()).add(id));
} else if (mount.Type !== 'tmpfs') {
refuse(`service ${service} has an unsupported mount type`);
}
}
containers.push({ id, service, running: item.State?.Running === true });
}
const runningCelld = containers.filter((c) => c.service === 'celld' && c.running);
if (opts.requireRunningCelld && runningCelld.length !== 1)
refuse('the legacy project must have exactly one running celld');
if (containers.filter((c) => c.service === 'celld').length !== 1)
refuse('the legacy project must have exactly one celld container');

const volumes: LegacyVolume[] = [];
for (const name of volumesLabelled(ctx, projectLabel)) {
const detail = json(
check(ctx.run('docker', ['volume', 'inspect', name]), 'inspect legacy volume').stdout,
'volume inspection'
);
const labels = (Array.isArray(detail) ? detail[0] : null)?.Labels ?? {};
const suffix = typeof labels[VOLUME_LABEL] === 'string' ? labels[VOLUME_LABEL] : '';
if (
labels[PROJECT_LABEL] !== opts.legacyProject ||
!VOLUME_SUFFIX.test(suffix) ||
name !== `${opts.legacyProject}_${suffix}`
)
refuse(`volume ${name} has inconsistent compose labels`);
if (!mountedBy.has(name)) refuse(`volume ${name} is not used by any proven container`);
// Any container that mounts the volume, of any project, must be one of the proven ones.
const users = lines(
check(
ctx.run('docker', ['ps', '--all', '--quiet', '--no-trunc', '--filter', `volume=${name}`]),
'list volume users'
).stdout
);
if (users.some((id) => !ids.includes(id))) refuse(`volume ${name} is also used elsewhere`);
volumes.push({ suffix, name });
}
for (const name of mountedBy.keys())
if (!volumes.some((v) => v.name === name)) refuse(`volume ${name} has no compose labels`);
return { containers, volumes };
}
Loading
Loading