From 113d7398dd17aef81d7349690048655fa75d16e6 Mon Sep 17 00:00:00 2001 From: Austin Burdine Date: Mon, 2 Nov 2026 15:04:11 -0500 Subject: [PATCH 01/15] =?UTF-8?q?=E2=9C=A8=20Added=20a=20shared=20Caddy=20?= =?UTF-8?q?for=20several=20production=20sites=20on=20one=20server=20(S13)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ref https://linear.app/ghost/issue/PLA-484 Ghost-CLI ran several sites behind one nginx; with Docker only one Caddy can hold 80 and 443, so it is shared and everything else, MySQL included, stays per site. Backup, restore, update and import are unchanged for a site behind it. `install --infra` sets the shared Caddy up as a Compose project of its own, the `infra` profile of the same compose.yml, on a network the manager creates and labels with its directory, so no project's `down` removes it. On a server that has it, a production install selects the `shared-caddy` profile instead of `production`: no Caddy of its own, Ghost and its optional services on the shared network under their unique aliases, and its routes in the shared Caddy's caddy/sites/.caddy. The manager cannot see that directory, so it writes, validates and reloads through the running Caddy container, as the directory's owner. A domain Caddy already serves, or a project with routes there, is refused before anything is written. Every site now has an `ingress` network that Caddy shares only with what it routes to; for a site with its own Caddy it is the site's. compose.yml no longer `:?`-guards Ghost's and MySQL's variables, since Compose interpolates services a profile leaves out and the shared Caddy's directory has none; `config validate` requires them instead. Converting an existing single site to sit behind it is PLA-504. A site installed `--no-caddy` is behind the operator's own proxy, so it never joins the shared Caddy, and `--infra` refuses `--no-caddy`. The shared Caddy's directory has metadata of an `infra` mode with no Ghost, so self-update there replaces untouched stack files, re-pins the launcher and recreates Caddy. It takes no backup: the directory holds no data, only certificates in a volume `up` keeps. A failure puts the files back and starts the previous Caddy again. The sites' routes are left out of its snapshot, since the update never writes them. - compose.yml, .env.example: shared-caddy and infra profiles, the ingress network, guards moved to validation. - manager/src/shared.ts: finding the shared Caddy, and its routes. - manager/src/docker/client.ts: networks and exec. - manager/src/commands/install.ts: --infra, and joining behind it. - manager/src/commands/remove.ts: takes a site down, and its routes out. - manager/src/commands/self-update.ts: the infra path. - manager/src/meta.ts: site and infra metadata, each schema chosen by `mode`. - manager/src/verify.ts, commands/site.ts: check through the shared Caddy, and list showing it and the sites behind it. - manager/src/config.ts, site.ts, payload.ts: the layouts, their stack files and their validation. - manager/src/restore.ts, backup.ts, undo.ts: routes a backup does not hold, and a failed install's routes removed. - manager/test, tests/e2e/shared-caddy.sh, test.yml: unit, integration and end-to-end coverage of PLA-484's acceptance. - docs: the shared Caddy's setup, trust model, restarts, updates and capacity; S13 removed from the roadmap. --- .env.example | 9 +- .github/workflows/test.yml | 1 + README.md | 3 +- compose.yml | 61 +- docs/architecture.md | 19 +- docs/caddy.md | 111 +++- docs/configuration.md | 20 +- docs/ghost-cli-replacement.md | 45 +- docs/install.md | 46 +- docs/reference.md | 51 +- manager/src/backup.ts | 15 +- manager/src/cli.ts | 2 + manager/src/commands/common.ts | 13 +- manager/src/commands/config.ts | 12 +- manager/src/commands/install.ts | 286 +++++++- manager/src/commands/remove.ts | 96 +++ manager/src/commands/self-update.ts | 241 ++++++- manager/src/commands/site.ts | 39 +- manager/src/config.ts | 73 ++- manager/src/docker/client.ts | 145 +++++ manager/src/legacy.ts | 1 + manager/src/meta.ts | 107 ++- manager/src/payload.ts | 6 +- manager/src/restore.ts | 49 +- manager/src/shared.ts | 274 ++++++++ manager/src/site.ts | 48 +- manager/src/undo.ts | 47 +- manager/src/verify.ts | 126 +++- manager/test/config.test.ts | 2 +- manager/test/integration/shared.test.ts | 178 +++++ manager/test/integration/site.ts | 3 + manager/test/shared.test.ts | 825 ++++++++++++++++++++++++ tests/e2e/shared-caddy.sh | 250 +++++++ 33 files changed, 3006 insertions(+), 198 deletions(-) create mode 100644 manager/src/commands/remove.ts create mode 100644 manager/src/shared.ts create mode 100644 manager/test/integration/shared.test.ts create mode 100644 manager/test/shared.test.ts create mode 100755 tests/e2e/shared-caddy.sh diff --git a/.env.example b/.env.example index 275f0ca5..97070831 100644 --- a/.env.example +++ b/.env.example @@ -12,7 +12,8 @@ # interpolated by accident. # --- Site mode ------------------------------------------------------------- -# Exactly one site mode must be selected: `local` or `production`. +# Exactly one site mode must be selected: `local` or `production`, or `shared-caddy` +# for a production site behind the shared Caddy (docs/caddy.md#the-shared-caddy). # Optional per-site profiles are added to the same list: `analytics`, # `activitypub`, `supervisor`, and for a local site `mailpit`. Profiles are additive; adding # an optional profile never changes the site mode. @@ -73,6 +74,12 @@ GHOST_PORT="2368" HTTP_PORT="80" HTTPS_PORT="443" +# Behind the shared Caddy, and in its own directory: its network, which the +# manager created and no Compose project owns. Unset, a site with its own +# Caddy gets a network of its own. +# INGRESS_NETWORK="ghost-ingress" +# INGRESS_EXTERNAL="true" + # --- Lifecycle ------------------------------------------------------------ # Applied to long-running services only. One-shot jobs keep `restart: "no"`. # production: unless-stopped diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 954ceaeb..cc968c0b 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -123,6 +123,7 @@ jobs: - { name: Ghost nightly channel, script: ghost-nightly } - { name: Migration from the released main layout, script: migrate-main } - { name: Backup and restore, script: backup } + - { name: Shared Caddy, script: shared-caddy } - { name: Import, script: import, node: "22" } steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 diff --git a/README.md b/README.md index 0a6333be..e3f4465c 100644 --- a/README.md +++ b/README.md @@ -61,7 +61,8 @@ Linux. There is no native Windows launcher. ## Site modes `install --local` selects Ghost and MySQL on loopback. A production install -adds Caddy with automatic HTTPS. [Configuration](docs/configuration.md#site-modes-and-profiles) +adds Caddy with automatic HTTPS; several production sites on one server share +one Caddy, set up with `install --infra` ([caddy.md](docs/caddy.md#the-shared-caddy)). [Configuration](docs/configuration.md#site-modes-and-profiles) defines the modes and optional profiles; [installation](docs/install.md#optional-services) explains how to enable them. diff --git a/compose.yml b/compose.yml index 3938f188..c77048bc 100644 --- a/compose.yml +++ b/compose.yml @@ -11,10 +11,18 @@ # credentials (MySQL root) that Ghost must not receive. # # Site modes are selected through COMPOSE_PROFILES and are additive: -# local ghost + db, Ghost published on 127.0.0.1:${GHOST_PORT} -# production ghost + db + caddy (HTTPS ingress) -# no-caddy ghost + db, a production site behind the operator's own proxy -# (nginx, Apache) on 127.0.0.1:${GHOST_PORT} +# local ghost + db, Ghost published on 127.0.0.1:${GHOST_PORT} +# production ghost + db + caddy (HTTPS ingress) +# no-caddy ghost + db, a production site behind the operator's own proxy +# (nginx, Apache) on 127.0.0.1:${GHOST_PORT} +# shared-caddy ghost + db, a production site behind the shared Caddy +# and `infra` is the shared Caddy's own directory: caddy alone, for the +# sites' routes (docs/caddy.md#the-shared-caddy). +# +# Variables a site needs and the shared Caddy does not are not `:?`-guarded, +# because Compose interpolates services its profiles leave out too: +# `./ghost-docker config validate` requires them for a site. +# # Optional, per-site profiles: analytics, activitypub, and for local sites # mailpit, and `supervisor`, which runs Ghost updates asked for in Ghost Admin # (docs/upgrade-supervisor.md). @@ -35,7 +43,7 @@ services: # Do not alter this without updating the Tinybird Sync container as well image: ${GHOST_IMAGE_REF:-${GHOST_IMAGE:-ghost}:${GHOST_VERSION:-6-next-alpine}} restart: ${RESTART_POLICY:-unless-stopped} - profiles: [local, production, no-caddy] + profiles: [local, production, no-caddy, shared-caddy] labels: <<: *site-labels org.ghost.docker.lifecycle: long-running @@ -51,7 +59,7 @@ services: # Container-owned keys. These override anything set in ghost.env. environment: NODE_ENV: ${NODE_ENV:-production} - url: ${URL:?URL is required (for example https://example.com or http://localhost:2368)} + url: ${URL:-} admin__url: ${ADMIN_URL:-} server__host: 0.0.0.0 server__port: "2368" @@ -60,9 +68,9 @@ services: database__connection__host: ${DATABASE_HOST:-db} database__connection__port: ${DATABASE_PORT:-3306} database__connection__user: ${DATABASE_USER:-ghost} - database__connection__password: ${DATABASE_PASSWORD:?DATABASE_PASSWORD is required} + database__connection__password: ${DATABASE_PASSWORD:-} database__connection__database: ${DATABASE_NAME:-ghost} - tinybird__tracker__endpoint: ${URL}/.ghost/analytics/api/v1/page_hit + tinybird__tracker__endpoint: ${URL:-}/.ghost/analytics/api/v1/page_hit tinybird__tracker__datasource: analytics_events tinybird__adminToken: ${TINYBIRD_ADMIN_TOKEN:-} tinybird__workspaceId: ${TINYBIRD_WORKSPACE_ID:-} @@ -110,11 +118,14 @@ services: # Unique alias. Generated proxy routes and helper clients address Ghost # through this name, never through the bare `ghost` service name. - ghost-${COMPOSE_PROJECT_NAME:-ghost} + ingress: + aliases: + - ghost-${COMPOSE_PROJECT_NAME:-ghost} db: image: mysql:8.0.44@sha256:f37951fc3753a6a22d6c7bf6978c5e5fefcf6f31814d98c582524f98eae52b21 restart: ${RESTART_POLICY:-unless-stopped} - profiles: [local, production, no-caddy] + profiles: [local, production, no-caddy, shared-caddy] labels: <<: *site-labels org.ghost.docker.lifecycle: long-running @@ -122,9 +133,9 @@ services: expose: - "3306" environment: - MYSQL_ROOT_PASSWORD: ${DATABASE_ROOT_PASSWORD:?DATABASE_ROOT_PASSWORD is required} + MYSQL_ROOT_PASSWORD: ${DATABASE_ROOT_PASSWORD:-} MYSQL_USER: ${DATABASE_USER:-ghost} - MYSQL_PASSWORD: ${DATABASE_PASSWORD:?DATABASE_PASSWORD is required} + MYSQL_PASSWORD: ${DATABASE_PASSWORD:-} MYSQL_DATABASE: ${DATABASE_NAME:-ghost} MYSQL_MULTIPLE_DATABASES: ${DATABASE_EXTRA_DATABASES:-activitypub} volumes: @@ -186,10 +197,12 @@ services: networks: - ghost_network + # A production site's own Caddy, or with `infra`, the shared Caddy, which + # serves the members' routes from caddy/sites/. caddy: image: caddy:2.10.2-alpine@sha256:953131cfea8e12bfe1c631a36308e9660e4389f0c3dfb3be957044d3ac92d446 restart: ${RESTART_POLICY:-unless-stopped} - profiles: [production] + profiles: [production, infra] labels: <<: *site-labels org.ghost.docker.lifecycle: long-running @@ -214,8 +227,11 @@ services: depends_on: ghost: condition: service_started + # The shared Caddy has no Ghost of its own. + required: false + # Only what Caddy routes to is on this network: never MySQL. networks: - - ghost_network + - ingress traffic-analytics: image: ghost/traffic-analytics:1.0.450@sha256:33c0ff8a369040e1455b790cf1711c2ea7f3174bcd26230dc9f7fc77b401816c @@ -241,6 +257,9 @@ services: ghost_network: aliases: - traffic-analytics-${COMPOSE_PROJECT_NAME:-ghost} + ingress: + aliases: + - traffic-analytics-${COMPOSE_PROJECT_NAME:-ghost} activitypub: image: ghcr.io/tryghost/activitypub:1.2.16@sha256:b440548b8a87eaf70c9440d4b157beee4898b85ba4294509926517a85e7573c7 @@ -260,10 +279,10 @@ services: MYSQL_HOST: ${DATABASE_HOST:-db} MYSQL_PORT: ${DATABASE_PORT:-3306} MYSQL_USER: ${DATABASE_USER:-ghost} - MYSQL_PASSWORD: ${DATABASE_PASSWORD:?DATABASE_PASSWORD is required} + MYSQL_PASSWORD: ${DATABASE_PASSWORD:-} MYSQL_DATABASE: ${ACTIVITYPUB_DATABASE_NAME:-activitypub} LOCAL_STORAGE_PATH: /opt/activitypub/content/images/activitypub - LOCAL_STORAGE_HOSTING_URL: ${URL}/content/images/activitypub + LOCAL_STORAGE_HOSTING_URL: ${URL:-}/content/images/activitypub depends_on: db: condition: service_healthy @@ -273,6 +292,9 @@ services: ghost_network: aliases: - activitypub-${COMPOSE_PROJECT_NAME:-ghost} + ingress: + aliases: + - activitypub-${COMPOSE_PROJECT_NAME:-ghost} # Local sites only: catches the mail Ghost sends (staff invites, password # resets, member sign-in links) and shows it in a web inbox. Newsletters go @@ -324,7 +346,7 @@ services: org.ghost.docker.lifecycle: one-shot logging: *default-logging environment: - MYSQL_DB: mysql://${DATABASE_USER:-ghost}:${DATABASE_PASSWORD:?DATABASE_PASSWORD is required}@tcp(${DATABASE_HOST:-db}:${DATABASE_PORT:-3306})/${ACTIVITYPUB_DATABASE_NAME:-activitypub} + MYSQL_DB: mysql://${DATABASE_USER:-ghost}:${DATABASE_PASSWORD:-}@tcp(${DATABASE_HOST:-db}:${DATABASE_PORT:-3306})/${ACTIVITYPUB_DATABASE_NAME:-activitypub} depends_on: db: condition: service_healthy @@ -413,3 +435,10 @@ volumes: networks: ghost_network: + # What Caddy reaches the site's services on. A site with its own Caddy gets + # one of its own. Behind the shared Caddy, and in its directory, it is the + # shared Caddy's network, which the manager creates and no project owns + # (`.env` names it). + ingress: + name: ${INGRESS_NETWORK:-${COMPOSE_PROJECT_NAME:-ghost}_ingress} + external: ${INGRESS_EXTERNAL:-false} diff --git a/docs/architecture.md b/docs/architecture.md index 71e2ac75..656b508d 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -93,7 +93,9 @@ The strict schema in [`src/meta.ts`](../manager/src/meta.ts) defines `.ghost-docker.json`. It records installation provenance, resolved Ghost identity and managed-file checksums. It is private, gitignored, atomically written and machine-owned. Missing metadata is distinct from invalid metadata; commands -requiring it refuse either with an actionable diagnostic. +requiring it refuse either with an actionable diagnostic. The shared Caddy's +directory has metadata of its own `mode`, `infra`, with no site URL and no +Ghost; `requireMetadata` refuses it, so only `self-update` and `info` read it. `source` distinguishes files installed from the image from files used in a checkout. `stack.image` is the manager pin. `payload` stores the checksum of each @@ -123,6 +125,21 @@ sites installed before, keeping any file in them that was edited. Caddy routes a `templates/site.caddy`, then belong to the operator. [caddy.md](caddy.md) owns route edits and reload instructions. +`src/shared.ts` is the shared Caddy: one Caddy project per daemon (`install +--infra`, the `infra` profile, and metadata of the `infra` mode with no +Ghost, so that `self-update` can keep its stack files and launcher current +without a backup, as it holds no data), on a network the manager creates +and labels with its directory, so no Compose project's `down` removes it. A +production install finds it by that network and selects the `shared-caddy` profile: Caddy's +own payload is left out, and its routes are a file in the shared Caddy's +`caddy/sites/`. The manager cannot see that directory, so it reads and writes +it through the running Caddy container (Engine API exec), as the directory's +owner; Caddy validates the whole configuration before it is reloaded, and +routes it refuses are removed. Duplicate domains (from Caddy's loaded +configuration) and projects (a routes file of that name) are refused before +any write. `remove` and a failed install's undo take a site's routes out +again. A backup does not hold them: they are the shared Caddy's. + `src/bundle/manifest.ts` defines the migration bundle schema and depends only on zod so the exporter can share it. Import policy stays outside that schema. `src/bundle/stage.ts` stages and validates input, `src/import.ts` sequences the diff --git a/docs/caddy.md b/docs/caddy.md index dd755ce8..582af4f8 100644 --- a/docs/caddy.md +++ b/docs/caddy.md @@ -2,7 +2,9 @@ `./ghost-docker install --domain` writes this site's routes into `caddy/sites/site.caddy`, once. From then on the file is yours, as the nginx -file Ghost-CLI generated was: the manager never rewrites it. +file Ghost-CLI generated was: the manager never rewrites it. On a server with +[the shared Caddy](#the-shared-caddy), the routes go into the shared Caddy's +directory instead, in a file named for the site. ## Layout @@ -32,8 +34,8 @@ A site moved from `main` keeps its own Caddyfile as `caddy/sites/site.caddy` main's snippets, which take no arguments, from `caddy/sites/legacy-snippets/`, and proxies to bare service names (`ghost:2368`), which resolve on the site's own network. Both keep working. Moving to this layout's snippets and aliases, -as `install` writes them, is optional, and is needed before the site joins a -shared Caddy. +as `install` writes them, is optional, and is needed before the site could +join a shared Caddy. ## Changing routes @@ -92,3 +94,106 @@ ActivityPub routes are always present. With the `activitypub` profile they point at this site's own service; otherwise at the hosted service, `https://ap.ghost.org`. ActivityPub, its migration job, database grants, storage and serving URL all belong to the site. + +## The shared Caddy + +Only one program can hold ports 80 and 443, so several production sites on +one server share one Caddy, as Ghost-CLI's sites shared one nginx. Everything +else stays each site's own: Ghost, MySQL, ActivityPub, analytics, backups, +updates and restores work exactly as they do for a site on its own. A local +site never uses the shared Caddy, and a server without one runs each +production site with its own Caddy, as before. + +Set it up once, in a directory of its own, before the sites: + +```bash +mkdir ~/caddy && cd ~/caddy +curl -fsSL https://docker.ghost.org/install.sh | bash -s -- install --infra +``` + +Then install each site as usual, each in its own directory. On a server with +the shared Caddy, `install --domain` joins it: the site has no Caddy of its +own, and its routes are written to the shared Caddy's +`caddy/sites/.caddy`, which Caddy validates and loads before the +site starts. A site installed `--no-caddy` does not join it. `` is the site's `COMPOSE_PROJECT_NAME`. A domain the +shared Caddy already serves, or a project that already has routes there, is +refused before anything is written. An existing site cannot be moved behind +the shared Caddy yet; it keeps its own Caddy, which needs 80 and 443, so set +the shared Caddy up on a server before its first production site. + +| Path, in the shared Caddy's directory | Owner | +| --- | --- | +| `caddy/sites/.caddy` | one per site behind it: written by that site's `install`, then yours | +| `caddy/custom/*.caddy`, `caddy/global/*.caddy` | yours, as for a single site | + +Edit a site's routes as described above, then reload the shared Caddy, in +its directory: + +```bash +docker compose exec caddy caddy reload --config /etc/caddy/Caddyfile +``` + +A configuration Caddy does not load is not applied: every site keeps being +served as before, and Caddy says why. `./ghost-docker check` in a site's +directory reports the shared Caddy's health, the site's routes file, and +HTTPS through it. `./ghost-docker list` shows the shared Caddy as `infra`, +and each site behind it as `shared-caddy`. + +`./ghost-docker remove`, in a site's directory, removes its routes file, +reloads the shared Caddy, and takes the site's containers down; no other site +is touched. The site's directory, data and backups stay until you delete them. +A backup does not hold a site's routes, which are the shared Caddy's files: +restoring a site behind it needs them in place, and says so when they are not. + +### How it is connected + +The shared Caddy is its own Compose project (`ghost-infra` unless `--name` +says otherwise), with the `infra` profile. `install --infra` creates the +network `ghost-ingress`, which belongs to no Compose project, so taking the +shared Caddy down never takes it away from the sites. Each site behind it +selects the `shared-caddy` profile, and its Ghost, ActivityPub and analytics join +`ghost-ingress` under their unique aliases (`ghost-:2368` and so +on), which is why routes always use them. MySQL and every one-shot job stay on +the site's own network. + +Ghost is still published on the site's loopback port, so a site behind the +shared Caddy can be reached without it, for example from your own proxy. + +### What it trusts + +The shared network is not isolation between sites. Every container on it can +reach every other site's Ghost, ActivityPub and analytics, and a site's bare +service names (`ghost`, `activitypub`) answer for every site on it, which is +why nothing routes by them. MySQL is never on it. Run sites behind one Caddy +only when you would trust them on one server anyway, as with Ghost-CLI. + +The shared Caddy's directory holds every site's routes, and its `caddy_data` +volume their certificates. Its `caddy/` is writable by whoever installed it, and the manager writes a site's +routes as the owner of `caddy/sites/`. + +### Restarting and updating it + +Restarting the shared Caddy (`docker compose restart`, or `down` then +`up -d`, in its directory) interrupts every site behind it for those seconds, +and brings each back with its routes; certificates are kept in its +`caddy_data` volume. A site's own operations (`update`, `self-update`, +`backup`, `restore`, `docker compose down`) never restart it. + +Its Caddy image is pinned in its `compose.yml`, by the release it runs. +`./ghost-docker self-update`, in its directory, moves it to a newer release as +for a site: untouched stack files are replaced, edited ones kept beside the +release's `.new`, and the launcher re-pinned; then Caddy is recreated, which +restarts it as above, and must pass its health check. There is no backup, +because it holds no data. A failed update puts its files back and starts the +previous Caddy again. It never updates the sites behind it, and their own +`self-update` never touches it. + +### Capacity + +Caddy itself costs little per site: a few routes, and a certificate it renews +in the background. What limits a server is each site's own Ghost and MySQL, +and ActivityPub and analytics where selected, which cost what they would on a +server of their own ([configuration.md](configuration.md#site-modes-and-profiles) +lists the optional services' costs). Size the server for the sum of them. +Let's Encrypt limits how many certificates one account obtains per hour; +installing many sites at once can reach it, and Caddy retries later. diff --git a/docs/configuration.md b/docs/configuration.md index a50631b5..b66207b3 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -107,16 +107,22 @@ value in either file may be a credential. ## Site modes and profiles Site mode is selected through `COMPOSE_PROFILES`, and exactly one of `local`, -`production` or `no-caddy` must be present: +`production`, `no-caddy` or `shared-caddy` must be present: | Profile | Services | Ingress | `SITE_MODE` | | --- | --- | --- | --- | | `local` | `ghost`, `db` | Ghost on `127.0.0.1:${GHOST_PORT}` | `local` | | `production` | `ghost`, `db`, `caddy` | Caddy on `${HTTP_PORT}` / `${HTTPS_PORT}` | `production` | | `no-caddy` | `ghost`, `db` | [Your own proxy](#your-own-proxy), to Ghost on `127.0.0.1:${GHOST_PORT}` | `production` | +| `shared-caddy` | `ghost`, `db` | [The shared Caddy](caddy.md#the-shared-caddy), on its network `${INGRESS_NETWORK}` | `production` | -A `no-caddy` site is a production site in every other way: backup, restore, -update, `self-update` and the upgrade supervisor treat it as one. +A `no-caddy` or `shared-caddy` site is a production site in every other way: +backup, restore, update, `self-update` and the upgrade supervisor treat it as +one, and production's rules below apply to it. The shared Caddy's own +directory selects `infra`, and nothing else: Caddy alone, with no site. Its +`.env` needs no Ghost or database settings, so compose.yml guards none of +them with `:?` (Compose interpolates the services a profile leaves out too); +`config validate` requires them for a site instead. Optional per-site profiles are added to the same list and are purely additive. Adding one never changes the site mode: @@ -269,7 +275,13 @@ Each service has a unique alias suffixed with the project name: - `mailpit-${COMPOSE_PROJECT_NAME}:1025` (SMTP) Generated proxy routes and helper clients use these, never the bare service -name. `COMPOSE_PROJECT_NAME` is the site's stable identity and is kept +name. Ghost, ActivityPub and analytics are also on the `ingress` network, under +the same aliases, which is all Caddy reaches: never MySQL. A site with its own +Caddy has an `ingress` network of its own. Behind the shared Caddy it is the +shared Caddy's, `ghost-ingress`, which `.env` names (`INGRESS_NETWORK`, with +`INGRESS_EXTERNAL=true`, since the manager created it and no Compose project +owns it); there every site's bare service names answer for every site, so +only the unique aliases identify one. `COMPOSE_PROJECT_NAME` is the site's stable identity and is kept independent of the directory name. `install` chooses it once: the domain's in production, and locally the directory's name and a random pair (`ghost-local-blog-secondary-roadrunner`) that no project on the daemon has, diff --git a/docs/ghost-cli-replacement.md b/docs/ghost-cli-replacement.md index 4090a36f..13d52cb9 100644 --- a/docs/ghost-cli-replacement.md +++ b/docs/ghost-cli-replacement.md @@ -12,7 +12,6 @@ Linear](https://linear.app/ghost/issue/PLA-412). | Outcome | Remaining work | Dependencies | | --- | --- | --- | | Tagged single-site production | S12 qualification | Existing image self-update, local and production import, backup and restore | -| Several sites behind shared Caddy | S13 | Existing backup/restore and released-main migration | | Later extensions | S11 file secrets, S14 service references, S15 nightly transitions, S16 Redis | See each step | Qualify production on Linux with rootful Docker Engine. Local qualification also covers @@ -42,12 +41,12 @@ environment-based installs, older imports, restart, and restore still work. Repo: ghost-docker, with cross-repo fixtures. Deps: existing install, local and production import, backup/restore, self-update, released-main migration, and the upgrade supervisor with -Ghost Admin's updates; qualify S13 and S11 when they have shipped. +Ghost Admin's updates, and the shared Caddy; qualify S11 when it has shipped. Gates the first stable tag and merging `next-docker` into `main`. Include the launcher on Linux, macOS and WSL2. Consolidate CI and qualify the actual minimum supported tools and image versions. Run fresh local/production install, optional-service variants, CLI migration, legacy stack update, Ghost upgrade/recovery, supervisor/Admin, and restore -scenarios. On a site with analytics, `update` must rerun Tinybird sync from the new +scenarios, and several sites behind the shared Caddy. On a site with analytics, `update` must rerun Tinybird sync from the new image and the deploy must succeed; it needs a Tinybird login, so it is run by hand. Before merging, pin the migration tests' `GD_RELEASED_MAIN` (default `origin/main`, in `manager/test/site.ts`, `tests/e2e/migrate-main.sh` and the manager CI job) to `main`'s last commit, and rerun them. Include Linux runtime tests and macOS-compatible shell/configuration checks. @@ -59,37 +58,11 @@ README/help include quick starts, prerequisites, version/compatibility policy, backup/restore, migration losses and cutover, custom proxy configuration, diagnostics, and uninstall. Document deletion of bind-mounted data separately from `down -v`, with explicit recovery consequences. Explain command equivalences without claiming full CLI -parity for unsupported features. Describe shared infra according to whether S13 has -shipped. - -### S13 — Optional shared Caddy - -Repo: ghost-docker. Depends on backup/restore for new member sites; converting an -existing site into a member (PLA-504) starts from a site on this layout, which the -released-main migration provides. Several sites on one server, as -Ghost-CLI ran several sites behind one nginx. 80 and 443 can belong to one Caddy only, -so that Caddy is shared; everything else stays per site, MySQL included, so backup, -restore, upgrade and import are unchanged. - -- `install --infra` sets up the shared Caddy once: a Compose project of its own, - with an external network each member site's Ghost (and optional services) also - joins. Infra-only configuration must resolve without a Ghost `URL`; review - required-variable guards and the profile validation when adding this mode. `install --domain` on a server that has it adds the site as a member - instead of starting a Caddy of its own. -- Each member's routes are a file in the shared Caddy's `sites/` directory, - written once by its install and then the operator's, as for a single-site install. Upstreams are - the member's unique aliases, described in [configuration.md](configuration.md#service-names-on-the-network). -- `list` shows the members; removing a site removes its routes file. -- Ghost publishes on loopback as before, so a member can still be reached - without Caddy. - -Acceptance: a shared Caddy with two members on different Ghost versions, each with its -own optional services; upgrading, restoring or removing one leaves the other untouched; -a duplicate domain is refused; a Caddy restart brings both back. +parity for unsupported features. ### S14 — Service images as full references -Repo: ghost-docker. Deps: S12; independent of S13. Give every service a full, +Repo: ghost-docker. Deps: S12. Give every service a full, registry-qualified reference behind an `.env` variable, pinned by the release with its digest. `config set` selects a mirror or another registry. There is no registry selector or separate registry state: the reference is the choice. @@ -142,7 +115,7 @@ supervisor's status. Repo: ghost-docker, verifying behavior against supported Ghost versions. Deps: S12 and existing configuration, installer, backup, upgrade, and secret interfaces; independent -of S13-S15. Follow the requirements below. Add `install --with redis` and the `redis` +of S14 and S15. Follow the requirements below. Add `install --with redis` and the `redis` profile for existing sites, with the service, version-aware Ghost cache wiring, private network, healthchecks, credentials, resource policy, diagnostics, and enable/disable steps. Keep Redis per-site even when shared infra exists. Default installs are @@ -157,8 +130,8 @@ Acceptance: `--with redis` installs, local and production, use Redis; default in start no Redis and behave as before; enabling and disabling it on an existing site keeps operator overrides. Verify real cache reads/writes and invalidation, resource limits, restart/outage/reconnect, upgrade/restore behavior, secret handling, and supported Ghost -version coverage. If S13 has shipped, verify two sites do not share cache data or expose -Redis through the shared ingress network. Specify cache rebuilding/persistence behavior +version coverage. Verify two sites behind the shared Caddy do not share cache data or +expose Redis through its network, `ghost-ingress`. Specify cache rebuilding/persistence behavior explicitly. Do not wire speculative traffic-analytics/ActivityPub consumers until their released interfaces exist and their cache-versus-durable-state requirements are established. @@ -193,5 +166,5 @@ support. Before wiring any such consumer, verify its released configuration cont distinguish disposable cache from durable queues/counters/salts/other state. Durable state needs appropriate persistence, eviction, isolation, backup/restore, and upgrade policy; separate instances when policies differ. Key prefixes or Redis logical DBs alone -do not isolate memory/eviction/durability policies. Redis remains per-site if a shared -Caddy (S13) is in use. +do not isolate memory/eviction/durability policies. Redis remains per-site behind the +shared Caddy. diff --git a/docs/install.md b/docs/install.md index 4385dfc0..a0809ce0 100644 --- a/docs/install.md +++ b/docs/install.md @@ -22,7 +22,8 @@ and curl for the install command above. Production is supported on Linux with ro see [Windows](#windows). **One directory is one site.** The site directory is the current directory, or -`--dir PATH`. +`--dir PATH`. Several production sites on one server share one Caddy; see +[Several sites on one server](#several-sites-on-one-server). ## Releases @@ -56,6 +57,7 @@ ghost-docker install [--local | --domain example.com [--admin-domain admin.examp [--channel stable|beta | --release vX.Y.Z] [--no-prompt] [--no-start] ghost-docker install --import BUNDLE [--name NAME] [--port 2368] [--with mailpit] [--no-prompt] [--no-start] ghost-docker install --import BUNDLE [--domain DOMAIN] [--admin-domain DOMAIN] [--email EMAIL | --no-caddy] [--no-start] +ghost-docker install --infra [--name NAME] [--channel stable|beta | --release vX.Y.Z] [--no-start] ``` | Option | Meaning | @@ -75,6 +77,7 @@ ghost-docker install --import BUNDLE [--domain DOMAIN] [--admin-domain DOMAIN] [ | `--no-prompt` | Never ask: every input must be an option. | | `--no-start` | Write the configuration and routes; start nothing. | | `--import BUNDLE` | Import a Ghost-CLI site; see [Importing a Ghost-CLI site](#importing-a-ghost-cli-site). | +| `--infra` | Set up the shared Caddy in this directory, for several production sites; see [Several sites on one server](#several-sites-on-one-server). | `install` refuses a directory that already holds a site or data, checks the host first (as `./ghost-docker doctor` does), generates fresh database @@ -302,6 +305,32 @@ docker compose up -d Remove the copy when you are done: `docker compose down`, then delete the directory, with `sudo` because MySQL owns `data/mysql`. For the real move, export again with the source stopped, to a new path. +## Several sites on one server + +As Ghost-CLI ran several sites behind one nginx, several production sites run +behind one shared Caddy: it alone holds 80 and 443. Each site keeps its own +directory, Ghost, MySQL and optional services, and is backed up, updated and +restored on its own. Set the shared Caddy up first, in a directory of its own: + +```bash +mkdir ~/caddy && cd ~/caddy +curl -fsSL https://docker.ghost.org/install.sh | bash -s -- install --infra + +mkdir ~/blog && cd ~/blog +curl -fsSL https://docker.ghost.org/install.sh | bash -s -- install --domain blog.example.com +mkdir ~/shop && cd ~/shop +curl -fsSL https://docker.ghost.org/install.sh | bash -s -- install --domain shop.example.com +``` + +On a server with the shared Caddy, every production install joins it, except +one with `--no-caddy`, and its routes are written to the shared Caddy's +`caddy/sites/`. A domain it already +serves is refused. `./ghost-docker remove`, in a site's directory, removes its +routes and takes it down, leaving the other sites alone. A site installed with +a Caddy of its own cannot be moved behind the shared Caddy yet. The trust +model, restarts, updates and capacity are in +[caddy.md](caddy.md#the-shared-caddy). + ## Ports, and your existing proxy **Installation never stops or reconfigures anything already running.** @@ -309,9 +338,10 @@ directory, with `sudo` because MySQL owns `data/mysql`. For the real move, expor - A port `install` chooses skips ports other containers publish, and on macOS ports other programs hold too. A busy port you ask for with `--port` is an error. -- A production site needs 80 and 443 for Caddy. If anything holds them, - installation fails, names the port, and leaves the directory as it was. A - site installed `--no-caddy` does not use them. +- A production site needs 80 and 443 for Caddy, unless the server has the + shared Caddy. If anything holds them, installation fails, names the port, + and leaves the directory as it was. A site installed `--no-caddy` does not + use them. **On Linux, use Docker Engine 28 or later.** Ghost (and Mailpit) are published on `127.0.0.1` only, but older engines let other machines on the local network @@ -350,6 +380,7 @@ How ports are detected on each platform: [Ports](reference.md#ports). ./ghost-docker self-update # ghost-docker itself; see below ./ghost-docker backup # the databases, content and configuration, into backups/ ./ghost-docker restore backups/ +./ghost-docker remove # take the site down; its directory and data stay ``` `check` exits non-zero when anything is wrong. A new production site whose DNS @@ -359,7 +390,8 @@ is verified](reference.md#how-a-site-is-verified). The routes are a file you edit, `caddy/sites/site.caddy`, followed by `docker compose exec caddy caddy reload --config /etc/caddy/Caddyfile`; see -[caddy.md](caddy.md). +[caddy.md](caddy.md). Behind the shared Caddy, they are in its directory +instead, and it is reloaded there. ## update @@ -407,7 +439,9 @@ ghost-docker self-update [--check] [--no-backup] [--channel stable|beta | --to v Updates ghost-docker itself (the stack's files and the manager image) to the newest release on the site's channel. **It never changes Ghost**; use [`update`](#update) for that. If a release needs a newer Ghost than the site -runs, it stops first and says so. +runs, it stops first and says so. In the shared Caddy's directory it updates +the shared Caddy, which restarts it for every site behind it; see +[caddy.md](caddy.md#restarting-and-updating-it). | Option | Meaning | | --- | --- | diff --git a/docs/reference.md b/docs/reference.md index b7c613c5..ff3c8afd 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -16,8 +16,8 @@ happens underneath them. path), and disk and memory, which warn rather than refuse. 3. **Ports Docker knows about.** The default port skips any that a container publishes. An explicit `--port`, or 80 and 443 for a production site with - Caddy, that - a container publishes is an error naming the container. Nothing is + a Caddy of its own, that a container publishes is an error naming the + container. Nothing is stopped. Ports held by anything else are found when the services start; see [Ports](#ports). 4. **The exact Ghost image.** The requested tag is pulled, and the pulled @@ -41,6 +41,15 @@ happens underneath them. the site's domains, its network aliases and every snippet argument. It is yours from then on; see [caddy.md](caddy.md). With `--no-caddy`, nothing: the routing is your proxy's ([configuration.md](configuration.md#your-own-proxy)). + On a server with [the shared Caddy](caddy.md#the-shared-caddy), the site + selects the `shared-caddy` profile instead of `production` and has no Caddy + of its own: the routes are written to the shared Caddy's + `caddy/sites/.caddy`, through its running container, as the owner + of that directory, then Caddy validates its whole configuration and + reloads. Before anything is written, a shared Caddy that is not running, a + project that already has routes there, and a domain it already serves are + refused; routes Caddy does not accept are removed again. A `--no-caddy` + site never joins the shared Caddy. 8. **Metadata**: `.ghost-docker.json`, described in [architecture.md](architecture.md#installation-metadata). 9. **Start and verify**, unless `--no-start`: `docker compose up --wait`, so @@ -50,12 +59,41 @@ happens underneath them. running container is not readiness. **A failed installation removes what it created** — containers, network, -volumes, the data directories, `.env`, `ghost.env`, the metadata and the -written stack files — so the same command can simply be run again in the same +volumes, the data directories, `.env`, `ghost.env`, the metadata, the +written stack files and the site's routes in the shared Caddy — so the same command can simply be run again in the same directory. That covers a port conflict, a failed pull, a service that never becomes healthy, and a site that starts but cannot be reached. Before removing anything it prints the services' last log lines. +### install --infra + +Sets up [the shared Caddy](caddy.md#the-shared-caddy) in an empty directory: +`compose.yml`, `caddy/` and the launcher, an `.env` selecting the `infra` +profile, and the network `ghost-ingress`, labelled with the directory and +project, which no Compose project owns. It takes no site options, and writes +no `ghost.env` or data directories: there is no Ghost. Its metadata records +the `infra` mode, no Ghost, and the stack files, for `self-update`. It refuses a +daemon that already has the network, and 80 and 443 held by a container. +Caddy must start and pass its health check; a failure removes everything, +the network included. Site commands (`check`, `backup`, `update`, `restore`, +`remove`, ...) refuse its directory; `config`, `info` and `self-update` work +there. Its `self-update` takes no backup and pauses no writers: it writes the +release's files, recreates Caddy and waits for its health check, and on a +failure puts the files back and starts the previous Caddy (see +[caddy.md](caddy.md#restarting-and-updating-it)). + +## remove + +`./ghost-docker remove [--yes]` takes the site in this directory down and +leaves everything else on the server as it was. Behind the shared Caddy, it +first removes the site's `caddy/sites/.caddy` there and reloads the +shared Caddy, which must be running. Then `docker compose down` removes the +site's containers and networks; its volumes, directory, data and backups +stay, and `docker compose up -d` starts it again (behind the shared Caddy, +once its routes are back). It asks first, at a terminal; without one it needs +`--yes`. It holds the site's lock, so it is refused while a backup, restore or +update runs. + ## How a site is verified Each service is judged by its own health check, which `up --wait` already @@ -71,6 +109,7 @@ Each answer is reported for what it is: | https | An HTTPS request to Caddy's container for Ghost's `/ghost/api/admin/site/`, with the domain as its server name and Host, as a browser asks. **serving** means this site's Ghost answered through Caddy: Ghost reports its site's URL, and that must be the site's `URL` (by either name, the canonical one, not the admin domain). It names the certificate's issuer and expiry; a certificate from a CA browsers do not trust (staging, or Caddy's internal CA) is a `warning`. **pending** means Caddy has no certificate for the name yet, so Ghost could not be asked through it: Caddy obtains one once the domain's DNS reaches this host, `./ghost-docker check` reports the change, and `docker compose logs caddy` shows each attempt. Caddy answering with something other than Ghost (a broken route, a 502), another site's Ghost (a route to the wrong upstream), or an out-of-date certificate, is an `ERROR`. | `ok`, `warning`, `note` or `ERROR` | | admin https | With an admin domain of its own: the same, for that name. Ghost reached by the admin domain still reports the site's `URL`, which is what is checked. On the site's domain, Ghost answering the Admin API path with a redirect to the admin domain counts as Ghost answering; the admin domain's own answer then names the site. | `ok`, `warning`, `note` or `ERROR` | | ingress | With `--no-caddy` (the `no-caddy` profile), in place of **caddy** and **https**: the site is served by your own proxy, which the manager cannot reach from its container, so it is not checked. The note names the URL and the loopback port the proxy must pass it to with `X-Forwarded-Proto: https`. | `note` | +| shared caddy, routes | Behind [the shared Caddy](caddy.md#the-shared-caddy), in place of **caddy**: the shared Caddy's health check, from its container, and that its `caddy/sites/.caddy` exists. A server without the shared Caddy's network is an `ERROR`. **https** then asks the shared Caddy, on its network. | `ok` or `ERROR` | | mailpit | With `--with mailpit`: its health check. The check names `mailpit-${COMPOSE_PROJECT_NAME}:1025`, where Ghost sends mail. | `ok` or `ERROR` | | published ports | The ports Docker says it published. A container cannot reach the host's own loopback interface, so they are not checked from there (the **https** request goes to Caddy's container, not to the host's ports): opening the URL is that check. | `note` | @@ -98,8 +137,8 @@ offered; for a private name, put `tls internal` in a `caddy/custom/` file. records its port, and a new site may be given the same one. - A port you *asked for* does not: `--port` on a busy port is an error, because a site at an address nothing else expects is worse than a refusal. -- A production site needs 80 and 443 for Caddy; one installed `--no-caddy` - does not. If a container holds them, installation +- A production site needs 80 and 443 for Caddy; one installed `--no-caddy`, + or behind the shared Caddy, does not. If a container holds them, installation stops before writing anything and names it. If another program holds them, Docker refuses to start Caddy; the error names the port, says nothing that was running was stopped, and the directory is as it was. diff --git a/manager/src/backup.ts b/manager/src/backup.ts index 844840a5..1b176234 100644 --- a/manager/src/backup.ts +++ b/manager/src/backup.ts @@ -44,7 +44,14 @@ import { runningImages, type ResolvedSite, } from './resolved.ts'; -import { BACKUPS_DIR, DATA_DIRS, hasProfile, splitProfiles, type SiteFacts } from './site.ts'; +import { + BACKUPS_DIR, + DATA_DIRS, + hasProfile, + SHARED_CADDY_PROFILE, + splitProfiles, + type SiteFacts, +} from './site.ts'; import { managerVersion } from './versions.ts'; /** mysqldump's last line, which a dump cut short never has. */ @@ -174,7 +181,11 @@ export function siteOverrides(resolved: ResolvedSite): string[] { function notIncluded(site: SiteFacts): string[] { const profiles = site.settings.get('COMPOSE_PROFILES') ?? ''; const lines: string[] = []; - if (site.layout === 'production') { + if (site.layout === SHARED_CADDY_PROFILE) { + lines.push( + "its routes, in the shared Caddy's caddy/sites/, which are the shared Caddy's files, with its certificates", + ); + } else if (site.layout === 'production') { lines.push( "Caddy's certificates and state, which Caddy obtains again when the site starts", ); diff --git a/manager/src/cli.ts b/manager/src/cli.ts index fd010a10..44cab024 100644 --- a/manager/src/cli.ts +++ b/manager/src/cli.ts @@ -9,6 +9,7 @@ import { backupCommand, restoreCommand } from './commands/backup.ts'; import { getCommand, setCommand, validateCommand } from './commands/config.ts'; import { doctorCommand } from './commands/doctor.ts'; import { installCommand } from './commands/install.ts'; +import { removeCommand } from './commands/remove.ts'; import { checkCommand, infoCommand, listCommand } from './commands/site.ts'; import { selfUpdateCommand } from './commands/self-update.ts'; import { supervisorRunCommand } from './commands/supervisor.ts'; @@ -31,6 +32,7 @@ const COMMANDS: Record = { 'supervisor run': supervisorRunCommand, backup: backupCommand, restore: restoreCommand, + remove: removeCommand, version: versionCommand, doctor: doctorCommand, help: defineCommand({ diff --git a/manager/src/commands/common.ts b/manager/src/commands/common.ts index c96378cf..14eaff24 100644 --- a/manager/src/commands/common.ts +++ b/manager/src/commands/common.ts @@ -12,6 +12,7 @@ import { readMetadata, type Metadata } from '../meta.ts'; import { channelOf, CHANNELS, isRelease, type Channel } from '../release.ts'; import { ENV_FILE, + isInfra, META_FILE, readSettings, siteFacts, @@ -42,9 +43,10 @@ export function siteContext(io: Io): Context { /** * The launcher's context, and the site in its directory. A site whose .env * names another directory is refused, unless `moved` allows it: `config get` - * and `config set` are how a moved site's PROJECT_DIR is put right. + * and `config set` are how a moved site's PROJECT_DIR is put right. The + * shared Caddy's directory is refused unless `infra` allows it: it has no site. */ -export function installedSite(io: Io, { moved = false } = {}): InstalledSite { +export function installedSite(io: Io, { moved = false, infra = false } = {}): InstalledSite { const context = siteContext(io); const dir = context.siteDir; const settings = readSettings(dir); @@ -54,6 +56,13 @@ export function installedSite(io: Io, { moved = false } = {}): InstalledSite { ' Run ./ghost-docker install, or ./ghost-docker --dir PATH ... for a site elsewhere.', ); } + if (!infra && isInfra(settings)) { + throw new CliError( + `${dir} holds the shared Caddy, not a site, so there is nothing here for this command.\n` + + ' ./ghost-docker list shows it and the sites behind it; docker compose ps and logs, in\n' + + ' this directory, show Caddy itself (docs/caddy.md#the-shared-caddy).', + ); + } const site = siteFacts(dir, settings); const declared = settings.get('PROJECT_DIR'); if (!moved && declared && declared !== dir) { diff --git a/manager/src/commands/config.ts b/manager/src/commands/config.ts index 4b1d598e..5cef2a4d 100644 --- a/manager/src/commands/config.ts +++ b/manager/src/commands/config.ts @@ -13,7 +13,7 @@ import { atomicWrite, PRIVATE, readIfExists } from '../fs.ts'; import type { Io } from '../io.ts'; import { acquireLock } from '../lock.ts'; import { printChecks } from '../report.ts'; -import { CONFIG_FILES, ENV_FILE, GHOST_ENV_FILE, type ConfigFile } from '../site.ts'; +import { CONFIG_FILES, ENV_FILE, GHOST_ENV_FILE, isInfra, type ConfigFile } from '../site.ts'; import { installedSite } from './common.ts'; const isConfigFile = (value: string | undefined): value is ConfigFile => @@ -60,7 +60,7 @@ export const getCommand = defineCommand({ brief: 'Print one decoded value.', positionals: ['file', 'key'], run: async (_values, args, io) => { - const { site } = installedSite(io, { moved: true }); + const { site } = installedSite(io, { moved: true, infra: true }); const { file, rest } = await target(io, site.dir, args, 1); const key = rest[0]!; checkKey(key); @@ -81,7 +81,7 @@ export const setCommand = defineCommand({ 'A value that starts with a dash goes after --. Holds the site lock while it writes.', positionals: ['file', 'key', 'value'], run: async (_values, args, io) => { - const { site } = installedSite(io, { moved: true }); + const { site } = installedSite(io, { moved: true, infra: true }); const { file, rest } = await target(io, site.dir, args, 2); const [key, value] = rest as [string, string]; checkKey(key); @@ -118,14 +118,16 @@ export const setCommand = defineCommand({ }); export async function validateSite(io: Io): Promise { - const { site } = installedSite(io); + const { site } = installedSite(io, { infra: true }); const findings = await io.busy('Validating the configuration', () => validate(io, site.dir)); printChecks(io, findingChecks(findings), 10); if (findings.some((finding) => finding.level === 'error')) { return EXIT.failure; } io.stdout( - `.env and ghost.env are valid for ${site.mode === null ? 'this' : `a ${site.mode}`} site\n`, + isInfra(site.settings) + ? '.env is valid for the shared Caddy\n' + : `.env and ghost.env are valid for ${site.mode === null ? 'this' : `a ${site.mode}`} site\n`, ); return EXIT.ok; } diff --git a/manager/src/commands/install.ts b/manager/src/commands/install.ts index d0a15acd..88aff7b1 100644 --- a/manager/src/commands/install.ts +++ b/manager/src/commands/install.ts @@ -1,5 +1,7 @@ // `install`: a local or production site, configured, started and verified. -// A production site has Caddy, or with --no-caddy, the operator's own proxy. +// A production site has Caddy, or with --no-caddy, the operator's own proxy; +// with --infra, the shared Caddy (shared.ts), and on a server that has one, a +// production site behind it. // `run` takes the parts in order, each a function of its own: refusals that // need nothing; with --import, the bundle (import.ts); preflight, ports, the // exact Ghost image and a free project name, still changing nothing; then @@ -9,8 +11,9 @@ import { randomBytes } from 'node:crypto'; import { existsSync, readdirSync } from 'node:fs'; import { join } from 'node:path'; -import { ACME_EMAIL, isHostname, SITE_FILE, writeRoutes } from '../caddy.ts'; -import { ALL_PROFILES, compose, upAndWait } from '../compose.ts'; +import { ACME_EMAIL, isHostname, renderRoutes, SITE_FILE, writeRoutes } from '../caddy.ts'; +import { ALL_PROFILES, compose, composePs, upAndWait } from '../compose.ts'; +import { createNetwork, MANAGED_LABEL } from '../docker/client.ts'; import { z } from 'zod'; import { defineCommand, flag, refused } from '../command.ts'; import { findingErrors, validate } from '../config.ts'; @@ -28,7 +31,7 @@ import { } from '../ghost.ts'; import { clearUnfinishedImport, Importing, importConflict } from '../import.ts'; import type { Io, Prompter } from '../io.ts'; -import { installationMetadata, writeMetadata } from '../meta.ts'; +import { infraMetadata, installationMetadata, writeMetadata } from '../meta.ts'; import { isCheckout, makeDirectories, @@ -45,13 +48,29 @@ import { ENV_FILE, generatedSettings, GHOST_ENV_FILE, + ingressSettings, + INFRA_PROFILE, MAILPIT_DATA_DIR, + SHARED_CADDY_PROFILE, META_FILE, profileConflict, NO_CADDY_PROFILE, type Layout, type SiteMode, } from '../site.ts'; +import { + addRoutes, + describeShared, + findSharedCaddy, + INFRA_DIR_LABEL, + INFRA_PROJECT, + INFRA_PROJECT_LABEL, + INGRESS_NETWORK, + refuseTaken, + routesPath, + runningCaddy, + type SharedCaddy, +} from '../shared.ts'; import { takenPorts } from '../ports.ts'; import { knownProjects, PROJECT_NAME, projectName, refuseForeignProject } from '../project.ts'; import { Created } from '../undo.ts'; @@ -206,6 +225,9 @@ const options = z release: releaseOption( 'Install this release, vX.Y.Z or vX.Y.Z-beta.N. The launcher resolves it.', ), + infra: flag( + 'Set up the shared Caddy in this directory, for several production sites on this server; each later production install joins it, unless --no-caddy. See docs/caddy.md.', + ), noPrompt: flag('Never ask: every input must be an option.'), noStart: flag('Write the configuration and routes; start nothing.'), }) @@ -232,7 +254,8 @@ const options = z (flags.ghostImage !== undefined && flags.import !== undefined ? '--ghost-image cannot be combined with --import: an import runs on the published Ghost release' : null) ?? - (flags.import === undefined ? null : importConflict(flags)); + (flags.import === undefined ? null : importConflict(flags)) ?? + (flags.infra ? infraConflict(flags) : null); if (conflict !== null) { ctx.addIssue({ code: 'custom', message: conflict }); } @@ -240,6 +263,30 @@ const options = z type Flags = z.output; +/** The options --infra cannot take: it sets up Caddy alone, for sites installed after it. */ +function infraConflict(flags: Flags): string | null { + const given = ( + [ + ['--local', flags.local], + ['--domain', flags.domain !== undefined], + ['--admin-domain', flags.adminDomain !== undefined], + ['--no-caddy', flags.noCaddy], + ['--email', flags.email !== undefined], + ['--port', flags.port !== undefined], + ['--version', flags.version !== undefined], + ['--ghost-image', flags.ghostImage !== undefined], + ['--ghost-channel', flags.ghostChannel !== 'stable'], + ['--with', flags.with.length > 0], + ['--import', flags.import !== undefined], + ] as const + ) + .filter(([, set]) => set) + .map(([option]) => option); + return given.length === 0 + ? null + : `--infra sets up the shared Caddy alone, so it takes no ${given.join(', ')}; install each site afterwards, in its own directory`; +} + // --- What to install --------------------------------------------------------- interface Plan { @@ -372,8 +419,12 @@ interface Site extends Target { /** The manager image the launcher is pinned to; none in a checkout. */ readonly pin: string | null; readonly project: string; + /** Its intent's layout, or behind the shared Caddy, `shared-caddy`. */ + readonly layout: Layout; readonly profiles: string; readonly production: boolean; + /** The shared Caddy this production site is installed behind, if the server has one. */ + readonly shared: SharedCaddy | null; readonly url: string; /** This manager's release, and the channel the site follows. */ readonly release: ManagerRelease; @@ -387,6 +438,9 @@ export const installCommand = defineCommand({ const release = requestedRelease(flags.channel, flags.release, '--release'); const context = siteContext(io); const dir = context.siteDir; + if (flags.infra) { + return installInfra(refuseOccupied(io, context, dir), flags, release); + } await clearUnfinishedImport(io, context, dir, flags.import !== undefined); const target = refuseOccupied(io, context, dir); @@ -464,9 +518,17 @@ async function prepare( if (intent.services.includes('supervisor')) { await refuseUnsupportedDaemon(io, context); } + // A production site with Caddy, on a server with the shared Caddy, is + // installed behind it. + const shared = intent.layout === 'production' ? await findSharedCaddy(io) : null; + if (shared !== null) { + runningCaddy(shared); + ok(io, 'shared caddy', `${describeShared(shared)} will serve this site`); + } + const layout: Layout = shared === null ? intent.layout : SHARED_CADDY_PROFILE; const { port, mailpitPort } = await sitePorts( io, - intent.layout, + layout, flags.port, intent.services.includes('mailpit'), ); @@ -488,11 +550,14 @@ async function prepare( // A production name is the domain's, and --name is the operator's: another // directory may already have either. await refuseForeignProject(io, project, dir); + if (shared !== null) { + await refuseTaken(io, shared, project, [intent.domain, intent.adminDomain].filter(Boolean)); + } const production = intent.mode === 'production'; return { ...target, - files: clone ? [] : payloadFiles(target.stack, intent.layout), + files: clone ? [] : payloadFiles(target.stack, layout), flags, intent, port, @@ -500,8 +565,10 @@ async function prepare( ghost, pin, project, - profiles: [intent.layout, ...intent.services].join(','), + layout, + profiles: [layout, ...intent.services].join(','), production, + shared, url: production ? `https://${intent.domain}` : `http://localhost:${port}`, release, }; @@ -542,7 +609,10 @@ async function sitePorts( : null; const wanted = [ port, - ...(layout === 'production' ? [PRODUCTION_PORTS.http, PRODUCTION_PORTS.https] : []), + // Caddy's, for a site with its own, or the shared Caddy itself. + ...(layout === 'production' || layout === INFRA_PROFILE + ? [PRODUCTION_PORTS.http, PRODUCTION_PORTS.https] + : []), ]; const holders = taken.holders(wanted); if (holders.size > 0) { @@ -606,7 +676,7 @@ async function createSite(site: Site, created: Created, importing: Importing | n makeDataDirectories(site, created, importing !== null); await validateConfiguration(site); await importing?.load(created, site.profiles, site.ghost.version); - writeSiteRoutes(site, created); + await writeSiteRoutes(site, created); writeSiteMetadata(site, created); if (site.flags.noStart) { site.io.stdout('\nNot starting: --no-start was given.\n'); @@ -628,7 +698,7 @@ function writeStack(site: Site, created: Created) { ok( io, 'stack files', - `compose.yml, ${site.intent.layout === 'production' ? 'caddy/, mysql-init/, tinybird/' : 'mysql-init/'} from the manager image`, + `compose.yml, ${site.layout === 'production' ? 'caddy/, mysql-init/, tinybird/' : site.layout === SHARED_CADDY_PROFILE ? 'mysql-init/, tinybird/' : 'mysql-init/'} from the manager image`, ); writeLauncher(dir, io.env, { image: pin!, channel: site.release.channel }, created); created.save(); @@ -648,6 +718,7 @@ function writeEnv(site: Site, created: Created) { port: site.port, mailpitPort: site.mailpitPort, ports: { http: String(PRODUCTION_PORTS.http), https: String(PRODUCTION_PORTS.https) }, + ingress: site.shared?.network ?? null, database: { user: 'ghost', password: secret(), rootPassword: secret() }, }); if (intent.services.includes('supervisor')) { @@ -721,25 +792,43 @@ async function validateConfiguration({ io, dir, intent }: Site) { ok(io, 'configuration', `.env and ghost.env are valid for a ${intent.mode} site`); } -/** A production site's Caddy routes. Written once; from here on the file is the operator's. */ -function writeSiteRoutes({ io, dir, project, intent }: Site, created: Created) { - if (intent.layout !== 'production') { +/** + * A production site's Caddy routes, in its own caddy/sites/, or behind the + * shared Caddy in the shared Caddy's, which then validates and reloads them. + * Written once; from here on the file is the operator's. + */ +async function writeSiteRoutes( + { io, dir, layout, project, intent, shared }: Site, + created: Created, +) { + if (layout !== 'production' && layout !== SHARED_CADDY_PROFILE) { return; } const { domain, adminDomain, email, services } = intent; - created.file(join(dir, SITE_FILE)); - writeRoutes(dir, { + const routes = { project, domain, adminDomain, email, activitypub: services.includes('activitypub'), - }); - ok( - io, - SITE_FILE, - `routes for ${[domain, adminDomain].filter(Boolean).join(' and ')}; yours to edit`, - ); + }; + const names = [domain, adminDomain].filter(Boolean).join(' and '); + if (shared !== null) { + created.routes = true; + created.save(); + await io.busy('Adding the routes to the shared Caddy', () => + addRoutes(io, shared, project, renderRoutes(routes)), + ); + ok( + io, + 'routes', + `${routesPath(shared, project)}: routes for ${names}, loaded by the shared Caddy; yours to edit`, + ); + return; + } + created.file(join(dir, SITE_FILE)); + writeRoutes(dir, routes); + ok(io, SITE_FILE, `routes for ${names}; yours to edit`); } function writeSiteMetadata(site: Site, created: Created) { @@ -767,14 +856,14 @@ function writeSiteMetadata(site: Site, created: Created) { ok(io, META_FILE, 'installation metadata'); } -async function startAndVerify({ io, dir, intent }: Site, created: Created) { +async function startAndVerify({ io, dir, layout }: Site, created: Created) { heading(io, 'Starting the services'); created.project = true; await upAndWait( io, dir, 'Pulling images, starting the services and waiting for them to be healthy', - (intent.layout === 'production' + (layout === 'production' ? ' If a port is already in use, choose another for Ghost with --port; a production\n' + ' site needs 80 and 443 free for Caddy.' : ' If a port is already in use, choose another for Ghost with --port.') + @@ -785,6 +874,150 @@ async function startAndVerify({ io, dir, intent }: Site, created: Created) { await verifySite(io, dir); } +// --- The shared Caddy ------------------------------------------------------------ + +/** + * `install --infra`: the shared Caddy, alone, in its own directory and + * project, on a network of its own that each production site installed after + * it joins. Nothing about a site is written, and there is no Ghost to resolve; + * its metadata records the stack files, for self-update. + */ +async function installInfra(target: Target, flags: Flags, requested: Requested): Promise { + const { io, context, dir, clone } = target; + const release = releaseOf(requested, io.env); + const existing = await findSharedCaddy(io); + if (existing !== null) { + throw new CliError( + `this server already has ${describeShared(existing)}, on the network ${existing.network}.\n` + + ' Install each production site in its own directory; it joins that Caddy. If that directory no\n' + + ` longer holds it, remove the network first: docker network rm ${existing.network}. Nothing has been changed.`, + ); + } + await preflight(io, context); + await sitePorts(io, INFRA_PROFILE, undefined, false); + const pin = clone + ? null + : await io.busy('Resolving the manager image', () => managerPin(io, context)); + const project = flags.name ?? INFRA_PROJECT; + await refuseForeignProject(io, project, dir); + + const created = new Created(io, context, dir); + try { + heading(io, 'Writing the shared Caddy'); + if (!clone) { + const files = payloadFiles(target.stack, INFRA_PROFILE); + writePayload(dir, target.stack, files, created); + ok(io, 'stack files', 'compose.yml and caddy/ from the manager image'); + writeLauncher(dir, io.env, { image: pin!, channel: release.channel }, created); + ok(io, 'ghost-docker', `the launcher, pinned to ${pin!}`); + } + // Where the members' routes go; Caddy mounts caddy/ whole. + makeDirectories(join(dir, 'caddy', 'sites'), created.directories); + const path = join(dir, ENV_FILE); + created.file(path); + atomicWrite( + path, + env.serializeAll( + Object.entries({ + COMPOSE_PROFILES: INFRA_PROFILE, + SITE_MODE: INFRA_PROFILE, + COMPOSE_PROJECT_NAME: project, + PROJECT_DIR: dir, + RESTART_POLICY: 'unless-stopped', + HTTP_PORT: String(PRODUCTION_PORTS.http), + HTTPS_PORT: String(PRODUCTION_PORTS.https), + ...ingressSettings(INGRESS_NETWORK), + }), + '# The shared Caddy: Caddy alone, serving the production sites on this server.\n' + + '# Their routes are in caddy/sites/, one file each; see docs/caddy.md.\n', + ), + PRIVATE, + ); + ok(io, ENV_FILE, 'the shared Caddy\u2019s settings'); + // No project owns it, so taking the shared Caddy down leaves its members attached. + created.network = INGRESS_NETWORK; + await createNetwork(io.docker, INGRESS_NETWORK, { + [MANAGED_LABEL.split('=')[0]!]: 'true', + [INFRA_DIR_LABEL]: dir, + [INFRA_PROJECT_LABEL]: project, + }); + ok(io, 'network', `${INGRESS_NETWORK}, which the services of each site behind it join`); + created.file(join(dir, META_FILE)); + writeMetadata( + dir, + infraMetadata({ + channel: clone ? null : release.channel, + source: clone ? 'checkout' : 'image', + stack: { version: release.version, image: pin }, + project, + dir, + payload: created.checksums, + }), + ); + ok(io, META_FILE, 'installation metadata, which self-update keeps current'); + const findings = await io.busy('Validating the configuration', () => validate(io, dir)); + const errors = findingErrors(findings); + if (errors) { + throw new CliError( + `the generated configuration did not validate; please report this:\n${errors}`, + ); + } + if (flags.noStart) { + io.stdout('\nNot starting: --no-start was given.\n'); + } else { + heading(io, 'Starting the shared Caddy'); + created.project = true; + await upAndWait( + io, + dir, + 'Pulling Caddy, starting it and waiting for it to be healthy', + ' The shared Caddy needs ports 80 and 443 free. Nothing that was already running was stopped.', + ); + const caddy = (await composePs(io, dir))?.find((state) => state.Service === 'caddy'); + if (caddy?.Health !== 'healthy') { + throw new CliError('Caddy started, but it is not healthy'); + } + ok(io, 'caddy', 'healthy: its admin API answers, with its configuration loaded'); + } + } catch (error) { + io.stderr( + `\n${describeError(error)}\n\nThe installation did not complete. Removing what it created\n`, + ); + const leftovers = await io.busy('Removing what the installation created', () => + created.remove(), + ); + io.stderr( + leftovers.length > 0 + ? `Some of it could not be removed:\n${leftovers.map((item) => ` ${item}\n`).join('')}` + : `${dir} is as it was before. Nothing that was already running was stopped.\n`, + ); + throw new CliError( + 'installation failed; fix the error above and run the same command again.', + ); + } + io.stdout( + [ + '', + 'The shared Caddy is installed.', + '', + ` Project ${project} (${INFRA_PROFILE}), in ${dir}`, + ` Network ${INGRESS_NETWORK}`, + '', + flags.noStart + ? 'Nothing is running. Start it with: docker compose up -d' + : 'It serves no site yet. Install each production site in a directory of its own with', + ...(flags.noStart + ? [] + : [ + './ghost-docker install --domain example.com: it joins this Caddy, and its routes', + 'are written to caddy/sites/ here.', + ]), + '', + ].join('\n'), + ); + return EXIT.ok; +} + // --- The outcome ---------------------------------------------------------------- /** @@ -881,6 +1114,11 @@ function printSummary(site: Site, importing: Importing | null) { ` Ghost Admin ${admin}/ghost/`, ` Project ${site.project} (${site.profiles}), in ${site.dir}`, ` Ghost ${ghost.version}, ${ghost.reference}`, + ...(site.shared === null + ? [] + : [ + ` Routes ${routesPath(site.shared, site.project)}, served by the shared Caddy`, + ]), ...(ghostChannelOf(ghost.image) === 'nightly' ? [ ` Channel nightly: a build of Ghost's main branch, for testing, ${production ? 'which this production site should not run' : 'never for production'}`, diff --git a/manager/src/commands/remove.ts b/manager/src/commands/remove.ts new file mode 100644 index 00000000..a8335985 --- /dev/null +++ b/manager/src/commands/remove.ts @@ -0,0 +1,96 @@ +// `remove`: a site taken down, and behind the shared Caddy, its routes taken +// out of it, so every other site behind it is left as it was. The site's +// directory, data and backups stay, for the operator to keep or delete. +import { z } from 'zod'; +import { defineCommand, flag } from '../command.ts'; +import { ALL_PROFILES, composeDown, composeError } from '../compose.ts'; +import { CliError, EXIT, UsageError } from '../errors.ts'; +import type { Io } from '../io.ts'; +import { acquireLock } from '../lock.ts'; +import { refuseForeignProject } from '../project.ts'; +import { ok } from '../report.ts'; +import { + describeShared, + findSharedCaddy, + removeRoutes, + routesPath, + runningCaddy, +} from '../shared.ts'; +import { SHARED_CADDY_PROFILE } from '../site.ts'; +import { installedSite } from './common.ts'; + +export const removeCommand = defineCommand({ + brief: 'Take the site down, and behind the shared Caddy, remove its routes from it. Its directory and data stay. See docs/install.md.', + options: z.object({ + yes: flag('Remove the site without asking first.'), + }), + async run(flags, _positionals, io) { + const { site } = installedSite(io); + const dir = site.dir; + const project = site.settings.get('COMPOSE_PROJECT_NAME') || ''; + await refuseForeignProject(io, project, dir); + const shared = site.layout === SHARED_CADDY_PROFILE ? await findSharedCaddy(io) : null; + if (shared !== null) { + runningCaddy(shared); + } + await confirm(io, dir, project, flags.yes); + + const lock = acquireLock(dir, 'remove'); + try { + if (shared !== null) { + await io.busy('Removing the routes from the shared Caddy', () => + removeRoutes(io, shared, project), + ); + ok( + io, + 'routes', + `${routesPath(shared, project)} removed; ${describeShared(shared)} reloaded without them`, + ); + } + const down = await io.busy("Stopping and removing the site's containers", () => + composeDown(io, dir, { profiles: ALL_PROFILES }), + ); + if (down.exitCode !== 0) { + throw new CliError( + `docker compose down failed: ${composeError(down, 4)}\n` + + ' Run it again in this directory once the cause is fixed.', + ); + } + ok(io, 'services', `the containers and networks of ${project} are removed`); + } finally { + lock.release(); + } + io.stdout( + `\nThe site is removed. ${dir} still holds its configuration, data and backups:\n` + + 'docker compose up -d starts it again' + + (shared === null + ? '' + : `, once its routes are back in ${routesPath(shared, project)}`) + + '.\nTo delete it for good, remove the directory (with sudo: MySQL owns data/mysql).\n', + ); + return EXIT.ok; + }, +}); + +/** Taking a site down is never a surprise: it is asked, or --yes says so. */ +async function confirm(io: Io, dir: string, project: string, yes: boolean) { + if (yes) { + return; + } + if (io.prompt === null) { + throw new UsageError( + `remove takes down the site in ${dir} (${project}).\n` + + ' Run it again with --yes to go ahead. Nothing has been changed.', + ); + } + const answer = await io.prompt.choose( + `Take down ${project} and remove its containers? Its directory and data stay.`, + [ + { name: 'No, change nothing', value: 'no' }, + { name: 'Yes, remove the site', value: 'yes' }, + ], + ); + if (answer !== 'yes') { + throw new CliError('the removal was cancelled. Nothing has been changed.'); + } +} diff --git a/manager/src/commands/self-update.ts b/manager/src/commands/self-update.ts index a7717a4d..3852640e 100644 --- a/manager/src/commands/self-update.ts +++ b/manager/src/commands/self-update.ts @@ -12,11 +12,13 @@ import { } from 'node:fs'; import { dirname, join, relative } from 'node:path'; import { refuseDrift } from '../backup.ts'; -import { compose, composeError } from '../compose.ts'; +import { compose, composeError, composePs, upAndWait } from '../compose.ts'; import { z } from 'zod'; import { defineCommand, flag } from '../command.ts'; import { requireValid } from '../config.ts'; -import { CliError, EXIT, UsageError } from '../errors.ts'; +import type { Context } from '../context.ts'; +import { CliError, describeError, EXIT, UsageError } from '../errors.ts'; +import { acquireLock } from '../lock.ts'; import { atomicWrite } from '../fs.ts'; import type { Io } from '../io.ts'; import { isReleasedMainLayout, migrateReleasedMain } from '../legacy.ts'; @@ -26,6 +28,7 @@ import { requireMetadata, siteFiles, writeMetadata, + type AnyMetadata, type Metadata, } from '../meta.ts'; import { @@ -37,12 +40,21 @@ import { sha256, stackDir, } from '../payload.ts'; -import { describeServices } from '../recovery.ts'; +import { describeServices, Snapshot } from '../recovery.ts'; import { compareReleases, isRelease } from '../release.ts'; import { resolveSite } from '../resolved.ts'; import { heading, note, ok } from '../report.ts'; import * as env from '../env.ts'; -import { COMPOSE_FILE, ENV_FILE, META_FILE, type Layout, type SiteFacts } from '../site.ts'; +import { + COMPOSE_FILE, + ENV_FILE, + INFRA_PROFILE, + isInfra, + META_FILE, + UPDATE_DIR, + type Layout, + type SiteFacts, +} from '../site.ts'; import { reportNeedsOperator, reportRestored, @@ -60,6 +72,7 @@ import { releaseOption, requestedRelease, type ManagerRelease, + type Requested, } from './common.ts'; /** How long pulling a release's images may take. */ @@ -125,7 +138,7 @@ const checksumOf = (path: string): string | null => existsSync(path) ? sha256(readFileSync(path)) : null; /** - * What the update does to each managed file of a site of this mode. A file is + * What the update does to each managed file of a site of this layout. A file is * untouched when its checksum is the one recorded when the manager wrote it. */ function planPayload( @@ -182,7 +195,7 @@ function removeEmptyParents(dir: string, directory: string): void { * snapshot holds. The site's own files, as a backup and a restore know them, * and what this release adds. */ -function touched(metadata: Metadata, payload: Payload): string[] { +function touched(metadata: AnyMetadata, payload: Payload): string[] { const paths: string[] = siteFiles(metadata); for (const { file, action } of payload.changes) { paths.push(file); @@ -295,8 +308,11 @@ export const selfUpdateCommand = defineCommand({ options, async run(flags, _positionals, io) { const requested = requestedRelease(flags.channel, flags.to, '--to'); - const { context, site } = installedSite(io); + const { context, site } = installedSite(io, { infra: true }); const dir = site.dir; + if (isInfra(site.settings)) { + return updateInfra(io, context, site, requested, flags.check); + } // An installation of the released main layout has no metadata: this is // how it moves onto this one (legacy.ts). if (readMetadata(dir).state === 'absent' && isReleasedMainLayout(site.settings)) { @@ -308,26 +324,7 @@ export const selfUpdateCommand = defineCommand({ return migrateReleasedMain(io, context, site, requested, flags.check); } const metadata = requireMetadata(dir, 'update cannot tell which files are its own'); - if (metadata.source === 'checkout') { - throw new CliError( - 'this site is a checkout of the repository, and self-update updates only a site installed\n' + - ' from the manager image. Update a checkout with git and Compose, in the site directory:\n' + - ' ./ghost-docker backup\n' + - ' git fetch --tags && git checkout \n' + - ' ./ghost-docker config validate\n' + - ' docker compose pull --ignore-buildable\n' + - ' docker compose up -d --wait\n' + - ' ./ghost-docker check\n' + - ' If the site does not come back, check out the commit it ran and restore the backup.\n' + - ' Nothing has been changed.', - ); - } - if (context.source === 'checkout') { - throw new CliError( - 'this site was installed from the manager image, and this manager was built from a checkout.\n' + - ' Run the site’s own ./ghost-docker self-update. Nothing has been changed.', - ); - } + refuseCheckouts(metadata.source, context.source); const release = releaseOf(requested, io.env); const from: Stack = { version: metadata.stack.version, image: metadata.stack.image }; @@ -374,6 +371,175 @@ export const selfUpdateCommand = defineCommand({ }, }); +/** A checkout is updated with git; a site from the image only by its own launcher's manager. */ +function refuseCheckouts(source: AnyMetadata['source'], running: Context['source']): void { + if (source === 'checkout') { + throw new CliError( + 'this site is a checkout of the repository, and self-update updates only a site installed\n' + + ' from the manager image. Update a checkout with git and Compose, in the site directory:\n' + + ' ./ghost-docker backup\n' + + ' git fetch --tags && git checkout \n' + + ' ./ghost-docker config validate\n' + + ' docker compose pull --ignore-buildable\n' + + ' docker compose up -d --wait\n' + + ' ./ghost-docker check\n' + + ' If the site does not come back, check out the commit it ran and restore the backup.\n' + + ' Nothing has been changed.', + ); + } + if (running === 'checkout') { + throw new CliError( + 'this site was installed from the manager image, and this manager was built from a checkout.\n' + + ' Run the site’s own ./ghost-docker self-update. Nothing has been changed.', + ); + } +} + +// --- The shared Caddy ------------------------------------------------------------- + +/** + * The shared Caddy's directory (shared.ts): its stack files and launcher, then + * Caddy recreated on the release's image. It holds no data, only Caddy's + * certificates in a volume `up` keeps, so there is no backup, and a failure + * puts the files back and starts the previous Caddy again: nothing it ran on + * the new files can have changed anything the old ones depend on. Every site + * behind it is unreachable while Caddy restarts, and updates on its own. + */ +async function updateInfra( + io: Io, + context: Context, + site: SiteFacts, + requested: Requested, + check: boolean, +): Promise { + const dir = site.dir; + const read = readMetadata(dir); + if (read.state !== 'present' || read.metadata.mode !== INFRA_PROFILE) { + throw new CliError( + read.state === 'invalid' + ? `${read.reason}. Nothing has been changed.` + : `${dir} holds the shared Caddy, but has no ${META_FILE} recording its files, so self-update\n` + + ' cannot tell them from yours. Nothing has been changed.', + ); + } + const metadata = read.metadata; + refuseCheckouts(metadata.source, context.source); + + const release = releaseOf(requested, io.env); + const from: Stack = { version: metadata.stack.version, image: metadata.stack.image }; + const image = await io.busy('Resolving the manager image', () => managerPin(io, context)); + const to: Stack = { version: release.version, image }; + const decided = compare(from, to); + if (typeof decided === 'object') { + throw new CliError(`${decided.unordered}. Nothing has been changed.`); + } + const stack = stackDir(io.env); + const payload = planPayload(dir, stack, INFRA_PROFILE, metadata.payload); + if (check) { + io.stdout( + `The shared Caddy runs ${describeStack(from)}. This release is ${describeStack(to)}.\n`, + ); + if (decided === 'newer') { + io.stdout('An update is available. Caddy restarts with it.\n'); + describeChanges(io, payload, to); + } else { + io.stdout( + decided === 'current' + ? 'It is up to date.\n' + : 'That is older, and update would refuse it.\n', + ); + } + return EXIT.ok; + } + if (decided === 'current') { + io.stdout(`The shared Caddy already runs ${describeStack(to)}. Nothing to update.\n`); + return EXIT.ok; + } + if (decided === 'downgrade') { + throw new CliError( + `the shared Caddy runs ${describeStack(from)}, which is newer than ${describeStack(to)}. An update\n` + + ' never moves to an older release. Nothing has been changed.', + ); + } + refuseUnfinished(dir, 'self-update'); + + const lock = acquireLock(dir, `update to ${describeStack(to)}`); + try { + io.stdout( + `Updating the shared Caddy from ${describeStack(from)} to ${describeStack(to)}\n`, + ); + heading(io, 'Keeping the current files'); + // Not the sites' routes: the update never writes them, and a site + // installed meanwhile adds its own, which putting files back would lose. + const snapshot = new Snapshot( + dir, + touched(metadata, payload).filter((path) => path !== join('caddy', 'sites')), + ); + snapshot.take(); + ok(io, UPDATE_DIR, 'the configuration, the metadata and the files this update writes'); + let started = false; + try { + heading(io, 'Writing the stack'); + writePayloadChanges(io, dir, stack, payload); + await requireValid(io, dir, 'this release'); + const pull = await io.busy( + 'Pulling the images this release names', + () => compose(io, { dir, timeout: PULL_MS })`pull --quiet --ignore-buildable`, + ); + if (pull.exitCode !== 0) { + throw new CliError(`the images could not be pulled: ${composeError(pull)}`); + } + heading(io, 'Restarting the shared Caddy'); + started = true; + await caddyUp( + io, + dir, + 'Recreating Caddy on this release and waiting for it to be healthy', + ); + recordStack(io, dir, metadata, from, to, release, payload); + } catch (error) { + io.stderr( + `\n${describeError(error)}\n\nThe update to ${describeStack(to)} did not complete. Putting ${describeStack(from)}'s files back\n`, + ); + snapshot.restore(); + if (started) { + try { + await caddyUp(io, dir, `Starting ${describeStack(from)}'s Caddy again`); + } catch (again) { + throw new CliError( + `the files are ${describeStack(from)}'s again, but Caddy did not start on them: ${describeError(again)}\n` + + ' Every site behind it is unreachable until it does: docker compose up -d, and\n' + + ` docker compose logs caddy, in ${dir}. The files as they were are in ${UPDATE_DIR}/files;\n` + + ` remove ${UPDATE_DIR} once Caddy runs.`, + ); + } + } + snapshot.remove(); + throw new CliError( + `the update failed; the shared Caddy is back on ${describeStack(from)}${started ? ', and running' : ', and was never stopped'}.`, + ); + } + snapshot.remove(); + } finally { + lock.release(); + } + io.stdout( + `\nUpdated the shared Caddy from ${describeStack(from)} to ${describeStack(to)}.\n` + + 'Each site behind it keeps its own release; update each with its own ./ghost-docker self-update.\n', + ); + return EXIT.ok; +} + +/** `up --wait`, and Caddy healthy by its own check. */ +async function caddyUp(io: Io, dir: string, spinner: string): Promise { + await upAndWait(io, dir, spinner); + const caddy = (await composePs(io, dir))?.find((state) => state.Service === 'caddy'); + if (caddy?.Health !== 'healthy') { + throw new CliError('Caddy started, but it is not healthy'); + } + ok(io, 'caddy', 'healthy: its admin API answers, with its configuration loaded'); +} + /** --check: what an update would do, changing nothing. */ function report({ io, from, to, payload, metadata }: Update, direction: Direction): number { io.stdout(`This site runs ${describeStack(from)}. This release is ${describeStack(to)}.\n`); @@ -392,6 +558,12 @@ function report({ io, from, to, payload, metadata }: Update, direction: Directio return EXIT.ok; } io.stdout(`An update is available. Ghost stays at ${metadata.ghost.version}.\n`); + describeChanges(io, payload, to); + return EXIT.ok; +} + +/** What --check says an update does to each file. */ +function describeChanges(io: Io, payload: Payload, to: Stack): void { const lines: Record = { add: 'added', replace: 'replaced', @@ -407,7 +579,6 @@ function report({ io, from, to, payload, metadata }: Update, direction: Directio } } io.stdout(` ${LAUNCHER}: pinned to ${to.image}\n`); - return EXIT.ok; } async function apply(update: Update, backup: boolean): Promise { @@ -482,7 +653,19 @@ async function apply(update: Update, backup: boolean): Promise { /** The launcher pinned to this image, then the metadata. */ function record({ io, site, metadata, from, to, release, payload }: Update): void { - const dir = site.dir; + recordStack(io, site.dir, metadata, from, to, release, payload); +} + +/** What `record` writes for any metadata: the launcher pinned, then the stack recorded. */ +function recordStack( + io: Io, + dir: string, + metadata: AnyMetadata, + from: Stack, + to: Stack, + release: ManagerRelease, + payload: Payload, +): void { const checksums = { ...payload.checksums }; const launcher = join(dir, LAUNCHER); const present = checksumOf(launcher); diff --git a/manager/src/commands/site.ts b/manager/src/commands/site.ts index 746f8499..2f3a7b60 100644 --- a/manager/src/commands/site.ts +++ b/manager/src/commands/site.ts @@ -14,7 +14,14 @@ import { describeMetadata, readMetadata } from '../meta.ts'; import { foreignProject, PROJECT_LABEL } from '../project.ts'; import { failed, printChecks, type Check } from '../report.ts'; import { imageDrift, observeSite, resolveSite, type ResolvedSite } from '../resolved.ts'; -import { hasProfile, readSettings, RESTORE_DIR } from '../site.ts'; +import { INGRESS_NETWORK } from '../shared.ts'; +import { + hasProfile, + INFRA_PROFILE, + SHARED_CADDY_PROFILE, + readSettings, + RESTORE_DIR, +} from '../site.ts'; import { verifyIngress } from '../verify.ts'; import { installedSite } from './common.ts'; import { collect } from './doctor.ts'; @@ -310,12 +317,22 @@ export const listCommand = defineCommand({ io.stderr('error: docker compose ls failed\n'); return EXIT.failure; } - const modes = new Map( - containers.map((container) => [ - container.labels[PROJECT_LABEL] ?? '', - container.labels['org.ghost.docker.mode'] ?? '', - ]), - ); + // The shared Caddy's mode is infra; a production site any of whose + // containers is on its network is behind it. + const modes = new Map(); + for (const container of containers) { + const project = container.labels[PROJECT_LABEL] ?? ''; + const mode = container.labels['org.ghost.docker.mode'] ?? ''; + modes.set( + project, + mode === INFRA_PROFILE + ? INFRA_PROFILE + : modes.get(project) === SHARED_CADDY_PROFILE || + (mode === 'production' && container.networks.includes(INGRESS_NETWORK)) + ? SHARED_CADDY_PROFILE + : mode, + ); + } const sites = projects .filter((project) => modes.has(project.name)) .sort((a, b) => a.name.localeCompare(b.name)); @@ -323,11 +340,17 @@ export const listCommand = defineCommand({ io.stdout('No ghost-docker site has containers on this host.\n'); } else { const row = (...cells: string[]) => - `${cells[0]!.padEnd(28)} ${cells[1]!.padEnd(11)} ${cells[2]!.padEnd(20)} ${cells[3]}\n`; + `${cells[0]!.padEnd(28)} ${cells[1]!.padEnd(12)} ${cells[2]!.padEnd(20)} ${cells[3]}\n`; io.stdout(row('SITE', 'MODE', 'STATUS', 'DIRECTORY')); for (const site of sites) { io.stdout(row(site.name, modes.get(site.name)!, site.status, site.dir)); } + if ([...modes.values()].includes(SHARED_CADDY_PROFILE)) { + io.stdout( + `\n${SHARED_CADDY_PROFILE} is a production site behind the shared Caddy (${INFRA_PROFILE}), which serves\n` + + "its routes from a file named for it in the shared Caddy's caddy/sites/.\n", + ); + } } io.stdout( '\nOnly sites whose containers exist are listed, stopped ones included. There is no\n' + diff --git a/manager/src/config.ts b/manager/src/config.ts index 81e2bfa4..a9e5691c 100644 --- a/manager/src/config.ts +++ b/manager/src/config.ts @@ -15,9 +15,12 @@ import { ENV_EXAMPLE_FILE, ENV_FILE, GHOST_ENV_FILE, + hasProfile, hostOf, + INFRA_PROFILE, layoutOf, MODE_PROFILE_NAMES, + SHARED_CADDY_PROFILE, OPTIONAL_PROFILES, profileConflict, siteMode, @@ -33,14 +36,12 @@ export interface Finding { /** Keys required in `.env` that nothing else would catch, by mode. */ export const REQUIRED_KEYS = { - common: [ - 'COMPOSE_PROFILES', - 'COMPOSE_PROJECT_NAME', - 'SITE_MODE', - 'PROJECT_DIR', - 'GHOST_VERSION', - ], + common: ['COMPOSE_PROFILES', 'COMPOSE_PROJECT_NAME', 'SITE_MODE', 'PROJECT_DIR'], + /** compose.yml does not `:?`-guard these: the shared Caddy's directory has none. */ + site: ['GHOST_VERSION', 'DATABASE_PASSWORD', 'DATABASE_ROOT_PASSWORD'], production: ['URL'], + /** Behind the shared Caddy, and in its own directory. */ + shared: ['INGRESS_NETWORK'], } as const; /** Modes that hold credentials and are still private. */ @@ -97,6 +98,13 @@ export async function validateEnv(io: Io, dir: string): Promise { ), ]; } + if (layoutOf(profiles) === INFRA_PROFILE) { + return [ + ...validateInfra(file, values), + ...interpolated(file, text), + ...privacy(file, path), + ]; + } const mode = siteMode(profiles); if (mode === null) { findings.push( @@ -131,9 +139,12 @@ export async function validateEnv(io: Io, dir: string): Promise { ); } + const behindSharedCaddy = hasProfile(profiles, SHARED_CADDY_PROFILE); const required = [ ...REQUIRED_KEYS.common, + ...REQUIRED_KEYS.site, ...(mode === 'production' ? REQUIRED_KEYS.production : []), + ...(behindSharedCaddy ? REQUIRED_KEYS.shared : []), ]; for (const key of required) { if (values[key] === undefined) { @@ -159,6 +170,10 @@ export async function validateEnv(io: Io, dir: string): Promise { } } + if (behindSharedCaddy) { + findings.push(...externalIngress(file, values)); + } + // The extra databases are created once, on first initialisation. A custom // ActivityPub database name that is not in that list never exists. const activitypubDatabase = values.ACTIVITYPUB_DATABASE_NAME; @@ -217,6 +232,50 @@ export async function validateEnv(io: Io, dir: string): Promise { return findings; } +/** + * The shared Caddy's directory: Caddy alone, so `infra` and nothing else, + * on the network the manager created for it. + */ +function validateInfra(file: string, values: Record): Finding[] { + const findings: Finding[] = []; + const profiles = splitProfiles(values.COMPOSE_PROFILES ?? ''); + if (profiles.length !== 1) { + findings.push( + error( + file, + `COMPOSE_PROFILES=${values.COMPOSE_PROFILES} selects the shared Caddy (${INFRA_PROFILE}), which runs Caddy alone: remove ${profiles.filter((profile) => profile !== INFRA_PROFILE).join(', ')}`, + ), + ); + } + if (values.SITE_MODE && values.SITE_MODE !== INFRA_PROFILE) { + findings.push( + error( + file, + `SITE_MODE=${values.SITE_MODE} does not match COMPOSE_PROFILES (${INFRA_PROFILE})`, + ), + ); + } + for (const key of [...REQUIRED_KEYS.common, ...REQUIRED_KEYS.shared]) { + if (values[key] === undefined) { + findings.push(error(file, `${key} is required for the shared Caddy`)); + } else if (values[key] === '') { + findings.push(error(file, `${key} is empty`)); + } + } + return [...findings, ...externalIngress(file, values)]; +} + +/** The shared Caddy's network is the manager's, so Compose must not create or remove it. */ +const externalIngress = (file: string, values: Record): Finding[] => + values.INGRESS_EXTERNAL === 'true' + ? [] + : [ + error( + file, + `INGRESS_EXTERNAL must be true: ${values.INGRESS_NETWORK || 'the network'} is the shared Caddy's, which no Compose project creates or removes`, + ), + ]; + /** * `ghost.env` holds Ghost application settings only. Two mistakes matter, and * both are detected rather than listed: diff --git a/manager/src/docker/client.ts b/manager/src/docker/client.ts index 0d5c1076..9ea969b5 100644 --- a/manager/src/docker/client.ts +++ b/manager/src/docker/client.ts @@ -8,6 +8,7 @@ import { DaemonTimeout, DaemonUnreachable, type DockerRequest, + type DockerResponse, type DockerTransport, } from './transport.ts'; @@ -217,6 +218,12 @@ const containerSummary = z.object({ Image: z.string().default(''), ImageID: z.string().default(''), Labels: z.record(z.string(), z.string()).nullable().default({}), + NetworkSettings: z + .looseObject({ + Networks: z.record(z.string(), z.unknown()).nullable().default({}), + }) + .nullable() + .default({ Networks: {} }), Ports: z .array( z.object({ @@ -244,6 +251,8 @@ export interface ContainerFacts { readonly labels: Readonly>; /** Host ports the container publishes. */ readonly publishedPorts: readonly number[]; + /** The names of the networks it is attached to. */ + readonly networks: readonly string[]; } /** `docker ps`, or with `all` `docker ps -a`, optionally filtered by label. */ @@ -275,6 +284,7 @@ export async function listContainers( ), ), ], + networks: Object.keys(container.NetworkSettings?.Networks ?? {}), })); } @@ -446,6 +456,74 @@ export async function disconnectNetwork( } } +const networkInspect = z.object({ + Id: z.string(), + Name: z.string(), + Labels: z.record(z.string(), z.string()).nullable().default({}), +}); + +export interface NetworkFacts { + readonly id: string; + readonly name: string; + readonly labels: Readonly>; +} + +/** `docker network inspect`, or null when the daemon has no network by that name. */ +export async function inspectNetwork( + docker: DockerTransport, + name: string, +): Promise { + try { + const network = await call( + docker, + { method: 'GET', path: `/networks/${encodeURIComponent(name)}` }, + networkInspect, + ); + // The daemon also matches an ID or its prefix; only the name counts. + return network.Name === name + ? { id: network.Id, name: network.Name, labels: network.Labels ?? {} } + : null; + } catch (error) { + if (error instanceof DaemonError && error.status === 404) { + return null; + } + throw error; + } +} + +/** `docker network create --label ...`: a bridge network. Returns its ID. */ +export async function createNetwork( + docker: DockerTransport, + name: string, + labels: Readonly>, +): Promise { + const network = await call( + docker, + { + method: 'POST', + path: '/networks/create', + body: { Name: name, Driver: 'bridge', Labels: labels, CheckDuplicate: true }, + }, + created, + ); + return network.Id; +} + +/** `docker network rm`. A network that is already gone is not an error. */ +export async function removeNetwork(docker: DockerTransport, name: string): Promise { + try { + await call( + docker, + { method: 'DELETE', path: `/networks/${encodeURIComponent(name)}` }, + z.unknown(), + ); + } catch (error) { + if (!(error instanceof DaemonError && error.status === 404)) { + throw error; + } + } +} + // --- One-shot containers ---------------------------------------------------- export interface Bind { @@ -564,6 +642,73 @@ export async function runOnce(docker: DockerTransport, spec: RunSpec): Promise { + let id: string; + try { + id = ( + await call( + docker, + { + method: 'POST', + path: `/containers/${encodeURIComponent(container)}/exec`, + body: { + Cmd: [...cmd], + AttachStdout: true, + AttachStderr: true, + Tty: false, + ...(user ? { User: user } : {}), + }, + }, + created, + ) + ).Id; + } catch (error) { + if (error instanceof DaemonError) { + return { status: null, stdout: '', stderr: error.message, timedOut: false }; + } + throw error; + } + let output: DockerResponse; + try { + output = await docker({ + method: 'POST', + path: `/exec/${id}/start`, + body: { Detach: false, Tty: false }, + timeoutMs, + }); + } catch (error) { + if (error instanceof DaemonTimeout) { + return { status: null, stdout: '', stderr: '', timedOut: true }; + } + throw error; + } + if (output.status >= 400) { + return { status: null, stdout: '', stderr: output.body.toString('utf8'), timedOut: false }; + } + const { stdout, stderr } = demultiplex(output.body); + const state = await call(docker, { method: 'GET', path: `/exec/${id}/json` }, execInspect); + return { status: state.Running ? null : state.ExitCode, stdout, stderr, timedOut: false }; +} + /** * The log stream of a container without a TTY: frames of an 8-byte header * (stream type, three zero bytes, big-endian payload length) and a payload. diff --git a/manager/src/legacy.ts b/manager/src/legacy.ts index b6ca6779..8b137d2b 100644 --- a/manager/src/legacy.ts +++ b/manager/src/legacy.ts @@ -316,6 +316,7 @@ async function prepare( port, mailpitPort: null, ports: { http: old.HTTP_PORT || '80', https: old.HTTPS_PORT || '443' }, + ingress: null, database: { user: old.DATABASE_USER || 'ghost', password: old.DATABASE_PASSWORD!, diff --git a/manager/src/meta.ts b/manager/src/meta.ts index 05fa4106..64979fdf 100644 --- a/manager/src/meta.ts +++ b/manager/src/meta.ts @@ -3,7 +3,7 @@ import { join } from 'node:path'; import { z } from 'zod'; import { atomicWrite, PRIVATE, readIfExists } from './fs.ts'; -import { META_FILE, OPERATOR_FILES, SITE_MODES } from './site.ts'; +import { INFRA_PROFILE, META_FILE, OPERATOR_FILES, SITE_MODES } from './site.ts'; import { CliError } from './errors.ts'; export const SCHEMA_VERSION = 1; @@ -11,12 +11,12 @@ export const SCHEMA_VERSION = 1; /** A field nobody supplied is null, so "not known" and "empty" stay distinct. */ const nullable = z.string().min(1).nullable(); -export const metadataSchema = z.strictObject({ +/** What a site's and the shared Caddy's metadata have alike. */ +const common = { schemaVersion: z.literal(SCHEMA_VERSION), installedAt: z.iso.datetime(), /** When `self-update` last completed; null until it has. */ updatedAt: z.iso.datetime().nullable(), - mode: z.enum(SITE_MODES), channel: z.enum(['stable', 'beta', 'edge']).nullable(), // `image`: the payload was written from the manager image. `checkout`: the // site is a clone of the repository and its files are used in place. @@ -32,6 +32,18 @@ export const metadataSchema = z.strictObject({ */ previous: z.strictObject({ version: nullable, image: nullable }).nullable(), }), + profiles: z.array(z.string().min(1)), + /** + * SHA-256 of every file the manager wrote from the image's payload, by + * path relative to the site. An update replaces an untouched file and + * never silently replaces an edited one (docs/architecture.md#releases-and-compatibility). Empty in clone mode. + */ + payload: z.record(z.string(), z.string().regex(/^[0-9a-f]{64}$/)), +}; + +export const metadataSchema = z.strictObject({ + ...common, + mode: z.enum(SITE_MODES), site: z.strictObject({ project: z.string().min(1), dir: z.string().startsWith('/'), @@ -45,16 +57,33 @@ export const metadataSchema = z.strictObject({ version: z.string().min(1), digest: z.string().regex(/^sha256:[0-9a-f]{64}$/), }), - profiles: z.array(z.string().min(1)), - /** - * SHA-256 of every file the manager wrote from the image's payload, by - * path relative to the site. An update replaces an untouched file and - * never silently replaces an edited one (docs/architecture.md#releases-and-compatibility). Empty in clone mode. - */ - payload: z.record(z.string(), z.string().regex(/^[0-9a-f]{64}$/)), }); +/** + * The shared Caddy's directory (shared.ts): the stack files and launcher + * `self-update` keeps current, and no site or Ghost. + */ +export const infraMetadataSchema = z.strictObject({ + ...common, + mode: z.literal(INFRA_PROFILE), + site: z.strictObject({ + project: z.string().min(1), + dir: z.string().startsWith('/'), + }), + ghost: z.null(), +}); + +/** A site's metadata: what every command about a site works from. */ export type Metadata = z.infer; +export type InfraMetadata = z.infer; +/** Whatever `.ghost-docker.json` holds. */ +export type AnyMetadata = Metadata | InfraMetadata; + +/** The schema a document's `mode` selects, so a mismatch names its fields. */ +const schemaOf = (document: unknown) => + (document as { mode?: unknown } | null)?.mode === INFRA_PROFILE + ? infraMetadataSchema + : metadataSchema; /** A moment as metadata, locks and backups record it: ISO 8601 to the second. */ export const isoSeconds = (date = new Date()): string => @@ -66,6 +95,11 @@ export const isoSeconds = (date = new Date()): string => */ export function requireMetadata(dir: string, why: string): Metadata { const read = readMetadata(dir); + if (read.state === 'present' && read.metadata.mode === INFRA_PROFILE) { + throw new CliError( + `${dir} holds the shared Caddy, not a site, and ${why}. Nothing has been changed.`, + ); + } if (read.state === 'absent') { throw new CliError( `${dir} has no ${META_FILE}, so it was not installed by ./ghost-docker install, and ${why}.\n` + @@ -75,7 +109,7 @@ export function requireMetadata(dir: string, why: string): Metadata { if (read.state === 'invalid') { throw new CliError(`${read.reason}. Nothing has been changed.`); } - return read.metadata; + return read.metadata as Metadata; } /** @@ -86,7 +120,7 @@ export function requireMetadata(dir: string, why: string): Metadata { * images this one did. */ export const siteFiles = ( - metadata: Metadata | null, + metadata: Pick | null, overrides: readonly string[] = [], ): string[] => [ ...new Set([ @@ -98,7 +132,7 @@ export const siteFiles = ( export type MetadataRead = | { state: 'absent' } - | { state: 'present'; metadata: Metadata } + | { state: 'present'; metadata: AnyMetadata } | { state: 'invalid'; reason: string }; export const metaPath = (dir: string): string => join(dir, META_FILE); @@ -128,7 +162,7 @@ export function readMetadata(dir: string): MetadataRead { : ''), }; } - const parsed = metadataSchema.safeParse(document); + const parsed = schemaOf(document).safeParse(document); if (!parsed.success) { const where = parsed.error.issues.map((issue) => issue.path.join('.') || '(root)'); return { @@ -167,13 +201,42 @@ export function installationMetadata( }; } +/** The shared Caddy's metadata as `install --infra` first writes it. */ +export function infraMetadata(input: { + readonly channel: InfraMetadata['channel']; + readonly source: InfraMetadata['source']; + readonly stack: { readonly version: string | null; readonly image: string | null }; + readonly project: string; + readonly dir: string; + readonly payload: Record; +}): InfraMetadata { + return { + schemaVersion: SCHEMA_VERSION, + installedAt: isoSeconds(), + updatedAt: null, + mode: INFRA_PROFILE, + channel: input.channel, + source: input.source, + stack: { + version: input.stack.version, + ref: input.source === 'checkout' ? null : input.stack.version, + image: input.stack.image, + previous: null, + }, + site: { project: input.project, dir: input.dir }, + ghost: null, + profiles: [INFRA_PROFILE], + payload: input.payload, + }; +} + /** * Validated before it is written, so a bad document never replaces a good * one. Two writes of the same document are the same bytes: the parse orders * the objects' keys as the schema does, and `payload`, a record, is sorted. */ -export function writeMetadata(dir: string, metadata: Metadata): void { - const valid = metadataSchema.parse(metadata); +export function writeMetadata(dir: string, metadata: AnyMetadata): void { + const valid = schemaOf(metadata).parse(metadata); valid.payload = Object.fromEntries( Object.entries(valid.payload).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)), ); @@ -203,10 +266,14 @@ export function describeMetadata(read: MetadataRead): string[] { ...(m.stack.previous ? [`previous ${unknown(m.stack.previous.version)}`] : []), `project ${m.site.project}`, `directory ${m.site.dir}`, - `url ${m.site.url}`, - ...(m.site.adminDomain ? [`admin domain ${m.site.adminDomain}`] : []), - `ghost ${m.ghost.version} (${m.ghost.image}:${m.ghost.tag})`, - `ghost image ${m.ghost.image}@${m.ghost.digest}`, + ...(m.mode === INFRA_PROFILE + ? ['the shared Caddy: no site, and no Ghost'] + : [ + `url ${m.site.url}`, + ...(m.site.adminDomain ? [`admin domain ${m.site.adminDomain}`] : []), + `ghost ${m.ghost.version} (${m.ghost.image}:${m.ghost.tag})`, + `ghost image ${m.ghost.image}@${m.ghost.digest}`, + ]), `profiles ${m.profiles.join(',')}`, ]; } diff --git a/manager/src/payload.ts b/manager/src/payload.ts index d6af9a1f..111499d6 100644 --- a/manager/src/payload.ts +++ b/manager/src/payload.ts @@ -32,12 +32,16 @@ export const isCheckout = (context: Context, dir: string): boolean => /** * The top-level payload entries a directory of each layout does without: a * site with no Caddy has no routes, and cannot select analytics, whose - * Tinybird jobs are built from tinybird/. + * Tinybird jobs are built from tinybird/; a site behind the shared Caddy has + * its routes in the shared Caddy's directory; and that directory runs Caddy + * alone. */ const UNUSED: Record = { local: ['caddy', 'tinybird'], production: [], 'no-caddy': ['caddy', 'tinybird'], + 'shared-caddy': ['caddy'], + infra: ['mysql-init', 'tinybird', 'ghost.env.example'], }; /** diff --git a/manager/src/restore.ts b/manager/src/restore.ts index a61e9458..266e80c3 100644 --- a/manager/src/restore.ts +++ b/manager/src/restore.ts @@ -40,12 +40,23 @@ import { COMPOSE_OVERRIDE_FILE, DATA_DIRS, ENV_FILE, + hasProfile, + INFRA_PROFILE, MAILPIT_DATA_DIR, + SHARED_CADDY_PROFILE, META_FILE, readSettings, RESTORE_DIR, siteFacts, } from './site.ts'; +import { + describeShared, + findSharedCaddy, + routeFiles, + routesFile, + routesPath, + runningCaddy, +} from './shared.ts'; import { verifySite } from './verify.ts'; /** `over`: the backup's own site, replaced. `fresh`: a new, empty directory. */ @@ -71,6 +82,7 @@ export async function restoreSite({ io, context, root, yes }: RestoreInput): Pro ); const target = classify(context, dir, manifest); + await refuseWithoutRoutes(io, root, manifest); if (target === 'fresh') { await refuseTaken(io, root, manifest); } else { @@ -383,6 +395,36 @@ async function refuseOtherConfiguration( ok(io, 'configuration', "the backup's resolves the images it records"); } +/** + * A site that was behind the shared Caddy is restored behind it: its network + * must exist, and its routes, which are the shared Caddy's files rather than + * the site's and so not in the backup, must be there to verify it. + */ +async function refuseWithoutRoutes(io: Io, root: string, manifest: BackupManifest): Promise { + const settings = env.toRecord(readIfExists(join(root, SITE_FILES_DIR, ENV_FILE)) ?? ''); + if (!hasProfile(settings.COMPOSE_PROFILES ?? '', SHARED_CADDY_PROFILE)) { + return; + } + const shared = await findSharedCaddy(io); + if (shared === null) { + throw new CliError( + `this backup is of a site behind the shared Caddy, and this server has none.\n` + + ' Set one up first with ./ghost-docker install --infra, in a directory of its own, and put\n' + + ` the site's routes in its caddy/sites/${routesFile(manifest.site.project)}. Nothing has been changed.`, + ); + } + const project = manifest.site.project; + if (!(await routeFiles(io, runningCaddy(shared))).includes(routesFile(project))) { + throw new CliError( + `this backup is of a site behind the shared Caddy, which has no routes for it:\n` + + ` ${routesPath(shared, project)} does not exist. Routes are the shared Caddy's files, not the\n` + + " site's, so a backup does not hold them: put them back (or write them as docs/caddy.md\n" + + ' describes), then run the restore again. Nothing has been changed.', + ); + } + ok(io, 'routes', `${routesPath(shared, project)}, in ${describeShared(shared)}`); +} + /** * A site restored into a new directory keeps its project name and its ports, * so nothing running on this daemon may already use them; a stopped site @@ -619,7 +661,12 @@ function writeSiteFiles( } const metadata = readMetadata(dir); const pin = restoredPin(manifest); - if (metadata.state === 'present' && (metadata.metadata.site.dir !== dir || pin !== null)) { + // A backup is always of a site, never of the shared Caddy. + if ( + metadata.state === 'present' && + metadata.metadata.mode !== INFRA_PROFILE && + (metadata.metadata.site.dir !== dir || pin !== null) + ) { const recorded = metadata.metadata.ghost; writeMetadata(dir, { ...metadata.metadata, diff --git a/manager/src/shared.ts b/manager/src/shared.ts new file mode 100644 index 00000000..e25a887c --- /dev/null +++ b/manager/src/shared.ts @@ -0,0 +1,274 @@ +// The shared Caddy: one Caddy for several production sites on a server, as +// Ghost-CLI ran several sites behind one nginx. Only one process can hold 80 +// and 443, so Caddy is shared; everything else, MySQL included, stays per +// site. It is a Compose project of its own (`install --infra`), on a network +// the manager creates and no project owns, which each site's Ghost and +// optional services join under their unique aliases. The network's labels say +// where the shared Caddy's directory is. +// +// Each site's routes are a file in that directory's caddy/sites/, named for +// the site's project. The manager cannot see that directory, only its own +// site's, so it reads and writes it through the running Caddy container, which +// mounts it: what is written is exactly what Caddy reads. See docs/caddy.md. +import { CliError } from './errors.ts'; +import { + execInContainer, + inspectNetwork, + listContainers, + type ContainerFacts, +} from './docker/client.ts'; +import type { RunResult } from './docker/client.ts'; +import type { Io } from './io.ts'; +import { PROJECT_LABEL, WORKING_DIR_LABEL } from './project.ts'; + +/** The shared Caddy's network. One per daemon, as 80 and 443 are. */ +export const INGRESS_NETWORK = 'ghost-ingress'; +/** The network's labels: the shared Caddy's directory and project. */ +export const INFRA_DIR_LABEL = 'org.ghost.docker.infra.dir'; +export const INFRA_PROJECT_LABEL = 'org.ghost.docker.infra.project'; +/** The label Compose gives each container its service's name. */ +export const SERVICE_LABEL = 'com.docker.compose.service'; +/** The default project name of the shared Caddy. */ +export const INFRA_PROJECT = 'ghost-infra'; + +/** Where the shared Caddy container mounts the members' routes. */ +const SITES = '/etc/caddy/sites'; +const CADDYFILE = '/etc/caddy/Caddyfile'; + +export interface SharedCaddy { + readonly network: string; + /** The shared Caddy's directory on the host. */ + readonly dir: string; + readonly project: string; + /** Its Caddy container, running or not; null when it has none. */ + readonly container: ContainerFacts | null; +} + +/** The shared Caddy on this daemon, or null when there is none. */ +export async function findSharedCaddy(io: Io): Promise { + const network = await inspectNetwork(io.docker, INGRESS_NETWORK); + if (network === null) { + return null; + } + const project = network.labels[INFRA_PROJECT_LABEL] ?? ''; + const [container] = + project === '' + ? [] + : await listContainers(io.docker, { + all: true, + labels: [`${PROJECT_LABEL}=${project}`, `${SERVICE_LABEL}=caddy`], + }); + return { + network: network.name, + dir: container?.labels[WORKING_DIR_LABEL] ?? network.labels[INFRA_DIR_LABEL] ?? '', + project, + container: container ?? null, + }; +} + +/** How to name the shared Caddy to a person. */ +export const describeShared = (shared: SharedCaddy): string => + `the shared Caddy${shared.dir ? ` in ${shared.dir}` : ''}`; + +/** + * The shared Caddy's container, which must be running for its routes to be + * read or changed; otherwise a CliError saying how to start it. + */ +export function runningCaddy(shared: SharedCaddy): ContainerFacts { + const { container } = shared; + if (container === null || container.state !== 'running') { + throw new CliError( + `${describeShared(shared)} is not running, so its routes cannot be read or changed.\n` + + ` Start it in its directory: cd ${shared.dir || ''} && docker compose up -d\n` + + ' Nothing has been changed.', + ); + } + return container; +} + +/** A site's routes file, in the shared Caddy's caddy/sites/. */ +export const routesFile = (project: string): string => `${project}.caddy`; + +/** The routes file, as a person finds it on the host. */ +export const routesPath = (shared: SharedCaddy, project: string): string => + `${shared.dir || ''}/caddy/sites/${routesFile(project)}`; + +const inCaddy = ( + io: Io, + caddy: ContainerFacts, + cmd: readonly string[], + user?: string, +): Promise => execInContainer(io.docker, caddy.id, { cmd, user }); + +/** What a command in the Caddy container said when it failed, for an error. */ +const said = (result: RunResult): string => + (result.stderr.trim() || result.stdout.trim() || 'no output') + .split('\n') + .slice(-8) + .map((line) => ` ${line}`) + .join('\n'); + +/** Every host name the shared Caddy's loaded configuration matches, lowercase. */ +export async function servedHosts(io: Io, caddy: ContainerFacts): Promise> { + // Its admin API listens inside the container only, as the health check uses it. + const result = await inCaddy(io, caddy, [ + 'wget', + '-q', + '-O', + '-', + 'http://127.0.0.1:2019/config/', + ]); + if (result.status !== 0) { + throw new CliError( + `the shared Caddy's configuration could not be read from its admin API:\n${said(result)}`, + ); + } + const hosts = new Set(); + const walk = (value: unknown): void => { + if (Array.isArray(value)) { + value.forEach(walk); + } else if (value !== null && typeof value === 'object') { + for (const [key, inner] of Object.entries(value)) { + if (key === 'host' && Array.isArray(inner)) { + for (const host of inner) { + if (typeof host === 'string') { + hosts.add(host.toLowerCase()); + } + } + } else { + walk(inner); + } + } + } + }; + walk(result.stdout.trim() === '' ? null : JSON.parse(result.stdout)); + return hosts; +} + +/** The files in the shared Caddy's caddy/sites/. */ +export async function routeFiles(io: Io, caddy: ContainerFacts): Promise { + const result = await inCaddy(io, caddy, ['ls', '-1A', SITES]); + if (result.status !== 0) { + throw new CliError(`the shared Caddy's ${SITES} could not be listed:\n${said(result)}`); + } + return result.stdout.split('\n').filter((line) => line !== ''); +} + +/** + * Refuses a site whose project already has routes in the shared Caddy, or + * whose domains it already serves, for whichever site: before anything is + * written. Caddy would also refuse a second block for one address, but only + * once the file was there. + */ +export async function refuseTaken( + io: Io, + shared: SharedCaddy, + project: string, + domains: readonly string[], +): Promise { + const caddy = runningCaddy(shared); + if ((await routeFiles(io, caddy)).includes(routesFile(project))) { + throw new CliError( + `${routesPath(shared, project)} already exists: the project ${project} already has routes in\n` + + ' the shared Caddy. Choose another name with --name, or remove that site first\n' + + ' (./ghost-docker remove, in its directory). Nothing has been changed.', + ); + } + const served = await servedHosts(io, caddy); + const taken = domains + .map((domain) => domain.toLowerCase()) + .filter((domain) => served.has(domain)); + if (taken.length > 0) { + throw new CliError( + `the shared Caddy already serves ${taken.join(' and ')}, for another site or in its own\n` + + ` configuration (${shared.dir || 'its directory'}/caddy). Two sites cannot share a domain.\n` + + ' Nothing has been changed.', + ); + } +} + +/** + * Writes a site's routes into the shared Caddy, owned by whoever owns its + * caddy/sites/, has Caddy validate its whole configuration with them, and + * reloads it. Routes Caddy refuses are removed again, and Caddy keeps serving + * what it served. + */ +export async function addRoutes( + io: Io, + shared: SharedCaddy, + project: string, + routes: string, +): Promise { + const caddy = runningCaddy(shared); + const owner = await inCaddy(io, caddy, ['stat', '-c', '%u:%g', SITES]); + if (owner.status !== 0) { + throw new CliError(`the shared Caddy's ${SITES} could not be read:\n${said(owner)}`); + } + const file = `${SITES}/${routesFile(project)}`; + // Written beside it under a name the Caddyfile's *.caddy does not import, + // then renamed, so Caddy never reads half a file. + const written = await inCaddy( + io, + caddy, + [ + 'sh', + '-c', + 'umask 022 && [ ! -e "$2" ] && printf "%s" "$1" > "$2.new" && mv "$2.new" "$2"', + 'sh', + routes, + file, + ], + owner.stdout.trim(), + ); + if (written.status !== 0) { + throw new CliError( + `the routes could not be written to the shared Caddy:\n${said(written)}`, + ); + } + const valid = await inCaddy(io, caddy, ['caddy', 'validate', '--config', CADDYFILE]); + if (valid.status !== 0) { + const removed = await inCaddy(io, caddy, ['rm', '-f', file], owner.stdout.trim()); + if (removed.status !== 0) { + throw new CliError( + `the shared Caddy does not accept its configuration with these routes, and they could not\n` + + ` be removed again: remove ${routesPath(shared, project)} by hand. Until then Caddy keeps\n` + + ` serving, but will not start again. Caddy said:\n${said(valid)}`, + ); + } + throw new CliError( + `the shared Caddy does not accept its configuration with these routes, so they were removed\n` + + ` again; Caddy still serves what it served. Caddy said:\n${said(valid)}`, + ); + } + await reloadCaddy(io, shared); +} + +/** + * Removes a site's routes from the shared Caddy and reloads it. Routes + * that are already gone are not an error. + */ +export async function removeRoutes(io: Io, shared: SharedCaddy, project: string): Promise { + const caddy = runningCaddy(shared); + const removed = await inCaddy(io, caddy, ['rm', '-f', `${SITES}/${routesFile(project)}`]); + if (removed.status !== 0) { + throw new CliError( + `${routesPath(shared, project)} could not be removed:\n${said(removed)}`, + ); + } + await reloadCaddy(io, shared); +} + +/** + * `caddy reload`: the configuration loads whole, or Caddy says why and keeps + * serving the one it had. + */ +export async function reloadCaddy(io: Io, shared: SharedCaddy): Promise { + const caddy = runningCaddy(shared); + const reloaded = await inCaddy(io, caddy, ['caddy', 'reload', '--config', CADDYFILE]); + if (reloaded.status !== 0) { + throw new CliError( + `the shared Caddy did not load its configuration, and keeps serving the one it had.\n` + + ` Caddy said:\n${said(reloaded)}`, + ); + } +} diff --git a/manager/src/site.ts b/manager/src/site.ts index fb3a6be5..ec0c6bc3 100644 --- a/manager/src/site.ts +++ b/manager/src/site.ts @@ -56,26 +56,44 @@ export type SiteMode = (typeof SITE_MODES)[number]; * host: Ghost and MySQL, no Caddy. Its mode is production. */ export const NO_CADDY_PROFILE = 'no-caddy'; +/** + * A production site behind the shared Caddy (shared.ts): Ghost and MySQL of + * its own, its routes in the shared Caddy's directory. Its mode is production. + */ +export const SHARED_CADDY_PROFILE = 'shared-caddy'; +/** The shared Caddy's own directory: Caddy alone, and no site. */ +export const INFRA_PROFILE = 'infra'; /** The profiles that select a site's mode, and the mode each selects. */ const MODE_PROFILES: Readonly> = { local: 'local', production: 'production', [NO_CADDY_PROFILE]: 'production', + [SHARED_CADDY_PROFILE]: 'production', }; export const MODE_PROFILE_NAMES = Object.keys(MODE_PROFILES); /** - * What a directory's files are for: a site of either mode, or a production - * site behind the operator's own proxy. The stack files each one needs differ - * (payload.ts), and only a production layout has Caddy. + * What a directory's files are for: a site of either mode, a production site + * behind the operator's own proxy or behind the shared Caddy, or the shared + * Caddy itself. The stack files each one needs differ (payload.ts), and only a + * production layout has a Caddy of its own. */ -export type Layout = SiteMode | typeof NO_CADDY_PROFILE; +export type Layout = + | SiteMode + | typeof NO_CADDY_PROFILE + | typeof SHARED_CADDY_PROFILE + | typeof INFRA_PROFILE; /** The layout COMPOSE_PROFILES selects; a production one unless it says otherwise. */ export function layoutOf(profiles: string): Layout { const selected = splitProfiles(profiles); - for (const layout of [NO_CADDY_PROFILE, 'local'] as const) { + for (const layout of [ + INFRA_PROFILE, + NO_CADDY_PROFILE, + SHARED_CADDY_PROFILE, + 'local', + ] as const) { if (selected.includes(layout)) { return layout; } @@ -83,6 +101,10 @@ export function layoutOf(profiles: string): Layout { return 'production'; } +/** Does this `.env` belong to the shared Caddy's directory rather than a site? */ +export const isInfra = (settings: SiteSettings): boolean => + hasProfile(settings.get('COMPOSE_PROFILES') ?? '', INFRA_PROFILE); + /** Additive, per-site. `supervisor` runs the upgrade supervisor (docs/upgrade-supervisor.md). */ export const OPTIONAL_PROFILES = ['analytics', 'activitypub', 'mailpit', 'supervisor'] as const; @@ -176,8 +198,10 @@ export function generatedSettings(input: { >; readonly port: number; readonly mailpitPort: number | null; - /** Caddy's, written for a production site with Caddy. */ + /** Caddy's, written for a production site with a Caddy of its own. */ readonly ports: { readonly http: string; readonly https: string }; + /** The shared Caddy's network, for a site behind it; null for one with its own. */ + readonly ingress: string | null; readonly database: { readonly user: string; readonly password: string; @@ -204,6 +228,7 @@ export function generatedSettings(input: { ...(input.mailpitPort === null ? {} : { MAILPIT_PORT: String(input.mailpitPort) }), RESTART_POLICY: production ? 'unless-stopped' : 'no', ...(caddy ? { HTTP_PORT: input.ports.http, HTTPS_PORT: input.ports.https } : {}), + ...(input.ingress === null ? {} : ingressSettings(input.ingress)), DATABASE_HOST: 'db', DATABASE_PORT: '3306', DATABASE_NAME: 'ghost', @@ -213,6 +238,12 @@ export function generatedSettings(input: { }); } +/** What puts a directory's services on the shared Caddy's network, which it does not create. */ +export const ingressSettings = (network: string): Record => ({ + INGRESS_NETWORK: network, + INGRESS_EXTERNAL: 'true', +}); + /** The hostname a URL names, or '' when it is not a URL. */ export const hostOf = (url: string): string => { try { @@ -226,7 +257,10 @@ export const hostOf = (url: string): string => { export interface SiteFacts { readonly dir: string; readonly mode: SiteMode | null; - /** Whether Caddy serves it ('production'), or the operator's own proxy ('no-caddy'). */ + /** + * Whether its own Caddy serves it ('production'), the shared Caddy + * ('shared-caddy'), or the operator's own proxy ('no-caddy'). + */ readonly layout: Layout; /** The hosts of URL and ADMIN_URL: what Caddy should serve, in production. */ readonly domain: string; diff --git a/manager/src/undo.ts b/manager/src/undo.ts index 0e2d8a56..bb714348 100644 --- a/manager/src/undo.ts +++ b/manager/src/undo.ts @@ -13,13 +13,16 @@ import { removeAsRoot } from './asroot.ts'; import { atomicWrite, PRIVATE, readIfExists } from './fs.ts'; import type { Io } from './io.ts'; import type { Written } from './payload.ts'; -import { DATA_DIRS, ENV_FILE, GHOST_ENV_FILE, META_FILE } from './site.ts'; +import { removeNetwork } from './docker/client.ts'; +import { findSharedCaddy, removeRoutes, routesFile, routesPath } from './shared.ts'; +import { DATA_DIRS, ENV_FILE, GHOST_ENV_FILE, META_FILE, readSettings } from './site.ts'; const journalSchema = z.object({ files: z.array(z.string().startsWith('/')), directories: z.array(z.string().startsWith('/')), data: z.array(z.string().startsWith('/')), project: z.boolean(), + routes: z.boolean().default(false), }); export class Created implements Written { @@ -30,6 +33,10 @@ export class Created implements Written { readonly data: string[] = []; /** Compose has created something for this project: a network, containers, volumes. */ project = false; + /** The site's routes are in the shared Caddy, named for its project (shared.ts). */ + routes = false; + /** The shared Caddy's network, created by `install --infra`. */ + network: string | null = null; /** The import marker, when this is an import. */ journal: string | null = null; @@ -59,6 +66,8 @@ export class Created implements Written { directories: [], data: DATA_DIRS.map((data) => join(dir, data)), project: true, + // Named for this site's project, which no other site's can have. + routes: true, }; } // Only ever inside this site directory, whatever the file says. @@ -67,6 +76,7 @@ export class Created implements Written { created.directories.push(...recorded.directories.filter(inside)); created.data.push(...recorded.data.filter(inside)); created.project = recorded.project && existsSync(join(dir, ENV_FILE)); + created.routes = recorded.routes; return created; } @@ -80,16 +90,19 @@ export class Created implements Written { if (this.journal === null) { return; } - const { files, directories, data, project } = this; + const { files, directories, data, project, routes } = this; atomicWrite( this.journal, - `${JSON.stringify({ files, directories, data, project }, null, 2)}\n`, + `${JSON.stringify({ files, directories, data, project, routes }, null, 2)}\n`, PRIVATE, ); } async remove(): Promise { const leftovers: string[] = []; + if (this.routes) { + leftovers.push(...(await this.removeRoutes())); + } if (this.project) { // Every profile, so whatever was started is found; the .env it // interpolates is still in place. @@ -103,6 +116,11 @@ export class Created implements Written { ); } } + if (this.network !== null) { + await removeNetwork(this.io.docker, this.network).catch((error: unknown) => + leftovers.push(`the network ${this.network} (${(error as Error).message})`), + ); + } if (this.data.length > 0) { leftovers.push(...(await this.removeData())); } @@ -128,6 +146,29 @@ export class Created implements Written { return leftovers; } + /** The site's routes in the shared Caddy, which is reloaded without them. */ + private async removeRoutes(): Promise { + const project = readSettings(this.dir)?.get('COMPOSE_PROJECT_NAME') ?? ''; + if (project === '') { + return []; + } + let shared = null; + try { + shared = await findSharedCaddy(this.io); + if (shared === null) { + return []; + } + await removeRoutes(this.io, shared, project); + return []; + } catch (error) { + const path = + shared === null + ? `${routesFile(project)} in the shared Caddy` + : routesPath(shared, project); + return [`${path} (${(error as Error).message.split('\n')[0]})`]; + } + } + /** MySQL's data directory belongs to MySQL's user once it has run (asroot.ts). */ private async removeData(): Promise { const left = await removeAsRoot( diff --git a/manager/src/verify.ts b/manager/src/verify.ts index d28faa0b..874da605 100644 --- a/manager/src/verify.ts +++ b/manager/src/verify.ts @@ -9,7 +9,22 @@ import type { Io } from './io.ts'; import { NetworkUnavailable, type SiteNetwork } from './network.ts'; import { CliError } from './errors.ts'; import { failed, heading, printChecks, type Check } from './report.ts'; -import { hasProfile, NO_CADDY_PROFILE, readSettings, siteFacts, type SiteFacts } from './site.ts'; +import { + describeShared, + findSharedCaddy, + INGRESS_NETWORK, + routeFiles, + routesFile, + routesPath, +} from './shared.ts'; +import { + hasProfile, + NO_CADDY_PROFILE, + SHARED_CADDY_PROFILE, + readSettings, + siteFacts, + type SiteFacts, +} from './site.ts'; const describeState = (state: ServiceState | undefined): string => state ? [state.State, state.Health].filter(Boolean).join(', ') : 'no container'; @@ -192,7 +207,8 @@ export async function verifyIngress( site: SiteFacts, known?: readonly ServiceState[] | null, ): Promise { - const production = site.layout === 'production'; + // Served by a Caddy: its own, or the shared one. + const production = site.layout === 'production' || site.layout === SHARED_CADDY_PROFILE; const withMailpit = hasProfile(site.settings.get('COMPOSE_PROFILES') ?? '', 'mailpit'); // `check` has the service states already. const services = known ?? (await composePs(io, site.dir)); @@ -200,14 +216,21 @@ export async function verifyIngress( const checks: Check[] = [ healthy('ghost', state('ghost'), 'its Admin API answers inside the container'), ]; + // Behind the shared Caddy, Caddy is, in another project. + const shared = + site.layout === SHARED_CADDY_PROFILE ? await sharedCaddyOf(io, site, checks) : null; + const caddy = shared === null ? state('caddy') : shared.state; if (production) { checks.push( healthy( - 'caddy', - state('caddy'), + shared === null ? 'caddy' : 'shared caddy', + caddy, 'its admin API answers, with its configuration loaded', ), ); + if (shared?.routes) { + checks.push(shared.routes); + } // The domain, and the admin domain when it has one of its own. const adminElsewhere = site.adminDomain !== '' && site.adminDomain !== site.domain ? site.adminDomain : null; @@ -230,15 +253,19 @@ export async function verifyIngress( } else { try { checks.push( - ...(await io.siteNetwork(services ?? [], ['caddy'], async (network) => { - const answers: Check[] = []; - for (const [label, name, elsewhere] of names) { - answers.push( - await https(io, network, label, name, expected, elsewhere), - ); - } - return answers; - })), + ...(await io.siteNetwork( + caddy === undefined ? [] : [caddy], + ['caddy'], + async (network) => { + const answers: Check[] = []; + for (const [label, name, elsewhere] of names) { + answers.push( + await https(io, network, label, name, expected, elsewhere), + ); + } + return answers; + }, + )), ); } catch (failure) { if (!(failure instanceof NetworkUnavailable)) { @@ -271,13 +298,84 @@ export async function verifyIngress( label: 'published ports', detail: `Docker publishes Ghost on ${publishedPorts(services, 'ghost')}` + - (production ? ` and Caddy on ${publishedPorts(services, 'caddy')}` : '') + + (production + ? ` and ${shared === null ? 'Caddy' : 'the shared Caddy'} on ${publishedPorts(shared === null ? services : [shared.state].filter((each) => each !== undefined), 'caddy')}` + : '') + (withMailpit ? `, and Mailpit's inbox on ${publishedPorts(services, 'mailpit')}` : '') + '; a container cannot reach the host, so open the URL to see them from there', }); return checks; } +/** The health Docker reports in a container's status: `Up 2 minutes (healthy)`. */ +const healthOf = (status: string): string => + /\(healthy\)/.test(status) + ? 'healthy' + : /\(unhealthy\)/.test(status) + ? 'unhealthy' + : /\(health: starting\)/.test(status) + ? 'starting' + : ''; + +/** + * The shared Caddy a site is behind: its container as `ps` would report it, + * and whether this site's routes are in its directory. A server with no + * shared Caddy is reported in `checks`. + */ +async function sharedCaddyOf( + io: Io, + site: SiteFacts, + checks: Check[], +): Promise<{ state: ServiceState | undefined; routes: Check | null } | null> { + const shared = await findSharedCaddy(io); + if (shared === null) { + checks.push( + error( + 'shared caddy', + `this site is behind the shared Caddy (${SHARED_CADDY_PROFILE} in COMPOSE_PROFILES), and this server has none: its network ${INGRESS_NETWORK} does not exist`, + ), + ); + return { state: undefined, routes: null }; + } + const { container } = shared; + const state: ServiceState | undefined = + container === null + ? undefined + : { + ID: container.id, + Service: 'caddy', + State: container.state, + Health: healthOf(container.status), + ExitCode: 0, + Publishers: container.publishedPorts.map((port) => ({ + URL: '', + TargetPort: 0, + PublishedPort: port, + Protocol: 'tcp', + })), + }; + if (container?.state !== 'running') { + return { state, routes: null }; + } + const project = site.settings.get('COMPOSE_PROJECT_NAME') || ''; + const path = routesPath(shared, project); + const present = (await routeFiles(io, container).catch(() => null))?.includes( + routesFile(project), + ); + return { + state, + routes: + present === undefined + ? error('routes', `the shared Caddy's caddy/sites/ could not be listed`) + : present + ? ok('routes', `${path}, in ${describeShared(shared)}`) + : error( + 'routes', + `${path} does not exist, so the shared Caddy has no routes of this site's`, + ), + }; +} + /** A site just started, verified and reported; a failure is a CliError. */ export async function verifySite(io: Io, dir: string): Promise { heading(io, 'Verifying the site'); diff --git a/manager/test/config.test.ts b/manager/test/config.test.ts index fb61bf2d..1a41e2c5 100644 --- a/manager/test/config.test.ts +++ b/manager/test/config.test.ts @@ -75,7 +75,7 @@ describe('.env', () => { makeSite(h, { ...PRODUCTION, COMPOSE_PROFILES: 'no-caddy,production' }); assert.match( (await validate()).errors, - /exactly one site mode \(local, production, no-caddy\)/, + /exactly one site mode \(local, production, no-caddy, shared-caddy\)/, ); makeSite(h, { ...PRODUCTION, URL: 'http://example.com', COMPOSE_PROFILES: 'no-caddy' }); assert.match((await validate()).errors, /URL must be https:\/\//); diff --git a/manager/test/integration/shared.test.ts b/manager/test/integration/shared.test.ts new file mode 100644 index 00000000..4465e2cc --- /dev/null +++ b/manager/test/integration/shared.test.ts @@ -0,0 +1,178 @@ +// The shared Caddy, against the real daemon and a real Caddy: a site's +// routes written, validated and loaded through the running container, its +// Ghost reached by its unique alias on the shared network, a taken domain or +// project refused, routes Caddy refuses taken out again, and removal. +// +// The shared Caddy here is the stack's own compose.yml with the `infra` +// profile, on a network of this run's rather than the real one. The site's +// Ghost is a stand-in that answers as a Ghost of its URL would: the real one +// is tests/e2e/shared-caddy.sh's. +import assert from 'node:assert/strict'; +import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { after, before, test } from 'node:test'; +import { renderRoutes } from '../../src/caddy.ts'; +import { listContainers } from '../../src/docker/client.ts'; +import { CliError } from '../../src/errors.ts'; +import { PROJECT_LABEL } from '../../src/project.ts'; +import { + addRoutes, + refuseTaken, + removeRoutes, + routeFiles, + servedHosts, + SERVICE_LABEL, + type SharedCaddy, +} from '../../src/shared.ts'; +import { makeSite, named, realIo, type TestSite } from './site.ts'; + +const io = realIo(); +const INGRESS = named('ingress'); +const CADDY_IMAGE = /image: (caddy:\S+)/.exec( + readFileSync(join(import.meta.dirname, '..', '..', '..', 'compose.yml'), 'utf8'), +)![1]!; + +const ingress: [string, string][] = [ + ['INGRESS_NETWORK', INGRESS], + ['INGRESS_EXTERNAL', 'true'], +]; + +let infra: TestSite; +let delta: TestSite; +let shared: SharedCaddy; + +/** Delta's Ghost: Caddy answering every request as Ghost's site endpoint does. */ +const STAND_IN = `services: + ghost: + image: ${CADDY_IMAGE} + command: ["caddy", "respond", "--listen", ":2368", "--body", '{"site":{"url":"https://delta.test/"}}'] + healthcheck: + test: [CMD, wget, -q, -O, /dev/null, "http://127.0.0.1:2368/"] + interval: 1s + start_period: 0s + ports: !reset [] +`; + +const routes = (project: string, domain: string) => + renderRoutes({ project, domain, adminDomain: '', email: '', activitypub: false }); + +before( + async () => { + const created = await io.docker({ + method: 'POST', + path: '/networks/create', + body: { Name: INGRESS }, + }); + assert.equal(created.status, 201, created.body.toString()); + infra = makeSite(io, 'shared-caddy', { profiles: 'infra', env: ingress }); + // Certificates from Caddy's own CA at once, rather than ACME's. + mkdirSync(join(infra.dir, 'caddy', 'global'), { recursive: true }); + writeFileSync(join(infra.dir, 'caddy', 'global', 'test.caddy'), 'local_certs\n'); + delta = makeSite(io, 'behind-delta', { + profiles: 'shared-caddy', + url: 'https://delta.test', + env: ingress, + override: STAND_IN, + }); + await Promise.all([infra.up('caddy'), delta.up('ghost')]); + const [container] = await listContainers(io.docker, { + labels: [`${PROJECT_LABEL}=${infra.project}`, `${SERVICE_LABEL}=caddy`], + }); + shared = { + network: INGRESS, + dir: infra.dir, + project: infra.project, + container: container!, + }; + }, + { timeout: 1_200_000 }, +); + +after(async () => { + for (const site of [delta, infra]) { + await site?.down(); + } + await io.docker({ method: 'DELETE', path: `/networks/${INGRESS}` }).catch(() => undefined); +}); + +const sitesFile = (name: string) => join(infra.dir, 'caddy', 'sites', name); + +test("a site's routes are written as the directory's owner, validated and loaded", async () => { + await addRoutes(io, shared, delta.project, routes(delta.project, 'delta.test')); + const file = sitesFile(`${delta.project}.caddy`); + assert.ok(existsSync(file)); + const owner = statSync(join(infra.dir, 'caddy', 'sites')); + assert.equal(statSync(file).uid, owner.uid); + assert.ok(!existsSync(`${file}.new`)); + assert.ok((await servedHosts(io, shared.container!)).has('delta.test')); +}); + +test("the site's Ghost answers through the shared Caddy, by its alias on the shared network", async () => { + const answer = await io.siteNetwork( + [ + { + ID: shared.container!.id, + Service: 'caddy', + State: 'running', + Health: 'healthy', + ExitCode: 0, + Publishers: [], + }, + ], + ['caddy'], + async (network) => { + assert.equal(network.name, INGRESS); + // Caddy issues its internal certificate in the background. + for (let attempt = 0; ; attempt += 1) { + try { + return await io.clients.https({ + host: network.address('caddy')!.host, + port: 443, + servername: 'delta.test', + path: '/ghost/api/admin/site/', + }); + } catch (error) { + if (attempt === 30) { + throw error; + } + await new Promise((resolve) => setTimeout(resolve, 1000)); + } + } + }, + ); + assert.equal(answer.status, 200); + assert.match(answer.body, /"url":"https:\/\/delta\.test\/"/); +}); + +test('a taken project or domain is refused before anything is written', async () => { + const before = await routeFiles(io, shared.container!); + await assert.rejects( + refuseTaken(io, shared, delta.project, ['other.test']), + (error: unknown) => error instanceof CliError && /already has routes/.test(error.message), + ); + await assert.rejects( + refuseTaken(io, shared, named('echo'), ['other.test', 'DELTA.test']), + (error: unknown) => + error instanceof CliError && /already serves delta\.test/.test(error.message), + ); + await refuseTaken(io, shared, named('echo'), ['echo.test']); + assert.deepEqual(await routeFiles(io, shared.container!), before); +}); + +test('routes Caddy refuses are taken out again, and Caddy keeps serving', async () => { + const project = named('broken'); + await assert.rejects( + addRoutes(io, shared, project, 'broken.test {\n\treverse_proxy {\n'), + (error: unknown) => error instanceof CliError && /does not accept/.test(error.message), + ); + assert.ok(!existsSync(sitesFile(`${project}.caddy`))); + assert.ok((await servedHosts(io, shared.container!)).has('delta.test')); +}); + +test('removing a site removes its routes, and Caddy reloads without them', async () => { + await removeRoutes(io, shared, delta.project); + assert.ok(!existsSync(sitesFile(`${delta.project}.caddy`))); + assert.ok(!(await servedHosts(io, shared.container!)).has('delta.test')); + // Already gone is not an error. + await removeRoutes(io, shared, delta.project); +}); diff --git a/manager/test/integration/site.ts b/manager/test/integration/site.ts index a312256c..4e34702c 100644 --- a/manager/test/integration/site.ts +++ b/manager/test/integration/site.ts @@ -68,6 +68,8 @@ export interface SiteOptions { readonly override?: string; /** caddy/sites/site.caddy. */ readonly caddy?: string; + /** More `.env` settings. */ + readonly env?: readonly [string, string][]; } export function makeSite(io: Io, name: string, options: SiteOptions): TestSite { @@ -88,6 +90,7 @@ export function makeSite(io: Io, name: string, options: SiteOptions): TestSite { ['URL', options.url ?? 'http://localhost:2368'], ['DATABASE_PASSWORD', secret()], ['DATABASE_ROOT_PASSWORD', secret()], + ...(options.env ?? []), ]), { mode: 0o600 }, ); diff --git a/manager/test/shared.test.ts b/manager/test/shared.test.ts new file mode 100644 index 00000000..52464299 --- /dev/null +++ b/manager/test/shared.test.ts @@ -0,0 +1,825 @@ +// The shared Caddy, against a scripted daemon and Compose: `install --infra`, +// a production install joining it, the refusals before anything is written, +// and `list`, `check`, `remove` and `config validate` knowing about it. What +// the real Caddy does with the routes is test/integration/shared.test.ts, and +// several sites on one server tests/e2e/shared-caddy.sh. +import assert from 'node:assert/strict'; +import { existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { afterEach, beforeEach, describe, test } from 'node:test'; +import * as env from '../src/env.ts'; +import type { DockerRequest, DockerResponse } from '../src/docker/transport.ts'; +import { frame } from '../src/docker/client.ts'; +import { payloadFiles } from '../src/payload.ts'; +import { layoutOf, readSettings, siteFacts, siteMode } from '../src/site.ts'; +import { verifyIngress } from '../src/verify.ts'; +import { failed, harness, json, ok, type Harness } from './helpers.ts'; +import { imageApi, imageStack, rootContainer } from './site.ts'; + +const INFRA_DIR = '/srv/caddy'; + +/** A shared Caddy as the daemon would show it: its network, its container, and the files it mounts. */ +interface FakeShared { + /** Files in its caddy/sites/, by name. */ + sites: Map; + /** Host names its loaded configuration matches. */ + hosts: Set; + running: boolean; + /** What `caddy validate` says: null accepts. */ + refuse: string | null; + /** Each command run in its container, with the user it ran as. */ + execs: { cmd: string[]; user: string }[]; + /** The labels the network was created with, when the manager created it. */ + created: Record | null; + exists: boolean; +} + +function fakeShared(): FakeShared { + return { + sites: new Map(), + hosts: new Set(), + running: true, + refuse: null, + execs: [], + created: null, + exists: true, + }; +} + +const CADDY = { + Id: 'shared-caddy', + Names: ['/ghost-infra-caddy-1'], + State: 'running', + Status: 'Up 2 minutes (healthy)', + Labels: { + 'org.ghost.docker.managed': 'true', + 'org.ghost.docker.mode': 'infra', + 'com.docker.compose.project': 'ghost-infra', + 'com.docker.compose.project.working_dir': INFRA_DIR, + 'com.docker.compose.service': 'caddy', + }, + Ports: [ + { PrivatePort: 80, PublicPort: 80, Type: 'tcp' }, + { PrivatePort: 443, PublicPort: 443, Type: 'tcp' }, + ], + NetworkSettings: { Networks: { 'ghost-ingress': {} } }, +}; + +/** The daemon's answers about the shared Caddy: its network, and commands run in its container. */ +function sharedApi(shared: FakeShared) { + let pending: { cmd: string[]; user: string } | null = null; + let status = 0; + return (request: DockerRequest): DockerResponse | undefined => { + const { method, path } = request; + if (path === '/networks/ghost-ingress' && method === 'GET') { + return shared.exists + ? json(200, { + Id: 'ingress-id', + Name: 'ghost-ingress', + Labels: shared.created ?? { + 'org.ghost.docker.infra.dir': INFRA_DIR, + 'org.ghost.docker.infra.project': 'ghost-infra', + }, + }) + : json(404, { message: 'network ghost-ingress not found' }); + } + if (path === '/networks/create' && method === 'POST') { + const body = request.body as { Name: string; Labels: Record }; + assert.equal(body.Name, 'ghost-ingress'); + shared.created = body.Labels; + shared.exists = true; + return json(201, { Id: 'ingress-id' }); + } + if (path === '/networks/ghost-ingress' && method === 'DELETE') { + shared.exists = false; + shared.created = null; + return { status: 204, body: Buffer.alloc(0) }; + } + if (path === '/containers/shared-caddy/exec' && method === 'POST') { + const body = request.body as { Cmd: string[]; User?: string }; + pending = { cmd: body.Cmd, user: body.User ?? '' }; + shared.execs.push(pending); + return json(201, { Id: 'exec-1' }); + } + if (path === '/exec/exec-1/start') { + const { stdout, code } = run(shared, pending!); + status = code; + return { status: 200, body: frame(code === 0 ? 1 : 2, stdout) }; + } + if (path === '/exec/exec-1/json') { + return json(200, { Running: false, ExitCode: status }); + } + return undefined; + }; +} + +/** A command in the shared Caddy's container, done to the fake's files. */ +function run(shared: FakeShared, { cmd }: { cmd: string[] }): { stdout: string; code: number } { + const name = (path: string) => path.replace('/etc/caddy/sites/', ''); + switch (cmd[0]) { + case 'wget': { + const routes = [...shared.hosts].map((host) => ({ match: [{ host: [host] }] })); + return { + stdout: JSON.stringify({ apps: { http: { servers: { srv0: { routes } } } } }), + code: 0, + }; + } + case 'ls': + return { + stdout: [...shared.sites.keys()].map((file) => `${file}\n`).join(''), + code: 0, + }; + case 'stat': + return { stdout: '1000:1000\n', code: 0 }; + case 'sh': { + // sh -c SCRIPT sh ROUTES FILE + shared.sites.set(name(cmd[5]!), cmd[4]!); + return { stdout: '', code: 0 }; + } + case 'rm': + shared.sites.delete(name(cmd.at(-1)!)); + return { stdout: '', code: 0 }; + case 'caddy': + if (cmd[1] === 'validate' && shared.refuse !== null) { + return { stdout: shared.refuse, code: 1 }; + } + if (cmd[1] === 'reload') { + // What the files now serve. + shared.hosts = new Set( + [...shared.sites.values()].flatMap( + (routes) => + /^([^\s#{][^{]*)\{/m + .exec(routes)?.[1]! + .split(',') + .map((host) => host.trim()) ?? [], + ), + ); + } + return { stdout: '', code: 0 }; + default: + return { stdout: `unexpected: ${cmd.join(' ')}`, code: 127 }; + } +} + +let h: Harness; +let shared: FakeShared; +let compose: string[][]; +let ps: () => string; +beforeEach(() => { + h = harness(); + imageStack(h); + shared = fakeShared(); + compose = []; + ps = () => ''; + const images = imageApi(); + const caddy = sharedApi(shared); + h.daemon.api = (request) => images(request) ?? caddy(request); + h.daemon.run = rootContainer; + h.daemon.containers = [CADDY]; + h.daemon.composeRun = (args) => { + compose.push(args); + switch (args[0]) { + case 'config': + return ok(JSON.stringify({ services: { ghost: { environment: {} } } })); + case 'ps': + return ok(ps()); + default: + return ok(''); + } + }; +}); +afterEach(() => h.cleanup()); + +const settings = () => env.toRecord(readFileSync(join(h.dir, '.env'), 'utf8')); +const files = () => + readdirSync(h.dir) + .filter((name) => name !== '.ghost-docker-probe') + .sort(); + +describe('install --infra', () => { + beforeEach(() => { + shared.exists = false; + h.daemon.containers = []; + }); + + test('sets up Caddy alone, on a network no project owns, labelled with where it is', async () => { + ps = () => + JSON.stringify({ ID: 'c', Service: 'caddy', State: 'running', Health: 'healthy' }); + const result = await h.run('install', '--infra'); + assert.equal(result.code, 0, result.stderr); + assert.deepEqual(shared.created, { + 'org.ghost.docker.managed': 'true', + 'org.ghost.docker.infra.dir': h.dir, + 'org.ghost.docker.infra.project': 'ghost-infra', + }); + assert.deepEqual( + { + profiles: settings().COMPOSE_PROFILES, + mode: settings().SITE_MODE, + project: settings().COMPOSE_PROJECT_NAME, + network: settings().INGRESS_NETWORK, + external: settings().INGRESS_EXTERNAL, + http: settings().HTTP_PORT, + url: settings().URL, + }, + { + profiles: 'infra', + mode: 'infra', + project: 'ghost-infra', + network: 'ghost-ingress', + external: 'true', + http: '80', + url: undefined, + }, + ); + // Caddy's files, and nothing of a site's: no Ghost or MySQL. + assert.deepEqual(files(), [ + '.env', + '.env.example', + '.ghost-docker.json', + 'caddy', + 'compose.ipv6.yml', + 'compose.yml', + 'ghost-docker', + ]); + const metadata = JSON.parse(readFileSync(join(h.dir, '.ghost-docker.json'), 'utf8')); + assert.equal(metadata.mode, 'infra'); + assert.equal(metadata.ghost, null); + assert.deepEqual(metadata.site, { project: 'ghost-infra', dir: h.dir }); + assert.ok(metadata.payload['caddy/Caddyfile'] && metadata.payload['ghost-docker']); + assert.ok(!Object.keys(metadata.payload).some((file) => file.startsWith('mysql-init/'))); + assert.ok(existsSync(join(h.dir, 'caddy', 'sites'))); + assert.ok(compose.some((args) => args[0] === 'up')); + assert.match(result.stdout, /The shared Caddy is installed/); + }); + + test('a server has one: a second is refused before anything is written', async () => { + shared.exists = true; + const result = await h.run('install', '--infra'); + assert.equal(result.code, 1); + assert.match(result.stderr, /already has the shared Caddy in \/srv\/caddy/); + assert.deepEqual(files(), []); + }); + + test('80 and 443 must be free', async () => { + h.daemon.containers = [{ ...CADDY, Id: 'p', Names: ['/operators-proxy'], Labels: {} }]; + const result = await h.run('install', '--infra'); + assert.equal(result.code, 1); + assert.match( + result.stderr, + /port 80 is already in use by the Docker container operators-proxy/, + ); + assert.equal(shared.created, null); + }); + + test('it takes no site options', async () => { + const result = await h.run( + 'install', + '--infra', + '--domain', + 'example.com', + '--with', + 'activitypub', + ); + assert.equal(result.code, 2); + assert.match( + result.stderr, + /--infra sets up the shared Caddy alone, so it takes no --domain, --with/, + ); + }); + + test('it is Caddy, so it takes no --no-caddy', async () => { + const result = await h.run('install', '--infra', '--no-caddy'); + assert.equal(result.code, 2); + assert.match(result.stderr, /so it takes no --no-caddy/); + }); + + test('a failed start removes the network with everything else', async () => { + h.daemon.composeRun = (args) => + args[0] === 'up' ? failed(1, 'Bind for 0.0.0.0:80 failed') : ok(''); + const result = await h.run('install', '--infra'); + assert.equal(result.code, 1); + assert.equal(shared.exists, false); + assert.deepEqual(files(), []); + }); +}); + +describe('self-update of the shared Caddy', () => { + const FIRST = `sha256:${'2'.repeat(64)}`; + const SECOND = `sha256:${'3'.repeat(64)}`; + let manager: string; + let up: () => ReturnType; + const release = (version: string) => + writeFileSync(h.env.GD_VERSION_FILE!, JSON.stringify({ version, commit: 'c'.repeat(40) })); + const metadata = () => JSON.parse(readFileSync(join(h.dir, '.ghost-docker.json'), 'utf8')); + + beforeEach(async () => { + shared.exists = false; + h.daemon.containers = []; + const stack = h.env.GD_STACK_DIR!; + h.env.GD_VERSION_FILE = `${stack}-version.json`; + manager = FIRST; + const images = imageApi({ manager: () => manager }); + const caddy = sharedApi(shared); + h.daemon.api = (request) => images(request) ?? caddy(request); + up = () => ok(''); + ps = () => + JSON.stringify({ ID: 'c', Service: 'caddy', State: 'running', Health: 'healthy' }); + h.daemon.composeRun = (args) => { + compose.push(args); + switch (args[0]) { + case 'config': + return ok(JSON.stringify({ services: { caddy: {} } })); + case 'ps': + return ok(ps()); + case 'up': + return up(); + default: + return ok(''); + } + }; + release('v0.1.0-beta.1'); + h.env.GD_CHANNEL = 'beta'; + const installed = await h.run('install', '--infra'); + assert.equal(installed.code, 0, installed.stderr); + compose.length = 0; + // The next release: a new image, with a changed snippet. + release('v0.1.0-beta.2'); + manager = SECOND; + writeFileSync(join(stack, 'caddy', 'snippets', 'Logging'), '# changed in beta.2\n'); + }); + + test('moves its files and launcher to the release, and recreates Caddy, with no backup', async () => { + const result = await h.run('self-update'); + assert.equal(result.code, 0, result.stderr); + assert.equal( + readFileSync(join(h.dir, 'caddy', 'snippets', 'Logging'), 'utf8'), + '# changed in beta.2\n', + ); + assert.match( + readFileSync(join(h.dir, 'ghost-docker'), 'utf8'), + new RegExp(`GD_PINNED_IMAGE="${SECOND}"`), + ); + const after = metadata(); + assert.equal(after.mode, 'infra'); + assert.deepEqual(after.stack.previous, { version: 'v0.1.0-beta.1', image: FIRST }); + assert.equal(after.stack.version, 'v0.1.0-beta.2'); + assert.deepEqual( + compose.map((args) => args[0]), + ['config', 'pull', 'up', 'ps'], + ); + assert.ok(!existsSync(join(h.dir, 'backups'))); + assert.ok(!existsSync(join(h.dir, '.ghost-docker-update'))); + assert.ok(!existsSync(join(h.dir, '.ghost-docker.lock'))); + assert.match( + result.stdout, + /Updated the shared Caddy from v0\.1\.0-beta\.1 to v0\.1\.0-beta\.2/, + ); + }); + + test('--check says what it would change, and changes nothing', async () => { + const before = readFileSync(join(h.dir, 'caddy', 'snippets', 'Logging'), 'utf8'); + const result = await h.run('self-update', '--check'); + assert.equal(result.code, 0, result.stderr); + assert.match(result.stdout, /An update is available\. Caddy restarts with it\./); + assert.match(result.stdout, /caddy\/snippets\/Logging: replaced/); + assert.equal(readFileSync(join(h.dir, 'caddy', 'snippets', 'Logging'), 'utf8'), before); + assert.deepEqual(compose, []); + }); + + test("an edited file is kept, with the release's beside it", async () => { + writeFileSync(join(h.dir, 'caddy', 'snippets', 'Logging'), '# mine\n'); + const result = await h.run('self-update'); + assert.equal(result.code, 0, result.stderr); + assert.equal(readFileSync(join(h.dir, 'caddy', 'snippets', 'Logging'), 'utf8'), '# mine\n'); + assert.equal( + readFileSync(join(h.dir, 'caddy', 'snippets', 'Logging.new'), 'utf8'), + '# changed in beta.2\n', + ); + }); + + test('a Caddy that does not become healthy is put back on the files it ran', async () => { + const before = readFileSync(join(h.dir, 'caddy', 'snippets', 'Logging'), 'utf8'); + let ups = 0; + up = () => (ups++ === 0 ? failed(1, 'container caddy is unhealthy') : ok('')); + const result = await h.run('self-update'); + assert.equal(result.code, 1); + assert.match(result.stderr, /is back on v0\.1\.0-beta\.1, and running/); + assert.equal(readFileSync(join(h.dir, 'caddy', 'snippets', 'Logging'), 'utf8'), before); + assert.match( + readFileSync(join(h.dir, 'ghost-docker'), 'utf8'), + new RegExp(`GD_PINNED_IMAGE="${FIRST}"`), + ); + assert.equal(metadata().stack.version, 'v0.1.0-beta.1'); + assert.equal(compose.filter((args) => args[0] === 'up').length, 2); + assert.ok(!existsSync(join(h.dir, '.ghost-docker-update'))); + assert.ok(!existsSync(join(h.dir, '.ghost-docker.lock'))); + }); + + test('a Caddy that will not start again either is left for the operator, with the files kept', async () => { + up = () => failed(1, 'Bind for 0.0.0.0:443 failed'); + const result = await h.run('self-update'); + assert.equal(result.code, 1); + assert.match(result.stderr, /Caddy did not start on them[\s\S]*unreachable until it does/); + assert.ok(existsSync(join(h.dir, '.ghost-docker-update', 'files'))); + }); + + test('site commands still refuse it', async () => { + for (const command of ['backup', 'update', 'check']) { + const result = await h.run(command); + assert.equal(result.code, 1, command); + assert.match(result.stderr, /holds the shared Caddy, not a site/, command); + } + }); +}); + +describe('a production install on a server with the shared Caddy', () => { + test('joins it: no Caddy of its own, its routes in the shared Caddy, loaded', async () => { + const result = await h.run( + 'install', + '--domain', + 'example.com', + '--with', + 'activitypub', + '--no-start', + ); + assert.equal(result.code, 0, result.stderr); + const values = settings(); + assert.equal(values.COMPOSE_PROFILES, 'shared-caddy,activitypub'); + assert.equal(values.SITE_MODE, 'production'); + assert.equal(values.INGRESS_NETWORK, 'ghost-ingress'); + assert.equal(values.INGRESS_EXTERNAL, 'true'); + assert.equal(values.HTTP_PORT, undefined); + assert.ok(!existsSync(join(h.dir, 'caddy')), 'a site behind it has no caddy/ of its own'); + const routes = shared.sites.get('ghost-example-com.caddy')!; + assert.match(routes, /^example\.com \{$/m); + assert.match(routes, /reverse_proxy ghost-ghost-example-com:2368/); + assert.match(routes, /ActivityPub activitypub-ghost-example-com:8080/); + // Written as whoever owns caddy/sites/, then validated, then loaded. + const commands = shared.execs.map( + ({ cmd, user }) => `${cmd[0]} ${cmd[1]}${user ? ` as ${user}` : ''}`, + ); + assert.deepEqual(commands.slice(-4), [ + 'stat -c', + 'sh -c as 1000:1000', + 'caddy validate', + 'caddy reload', + ]); + assert.ok(shared.hosts.has('example.com')); + const metadata = JSON.parse(readFileSync(join(h.dir, '.ghost-docker.json'), 'utf8')); + assert.equal(metadata.mode, 'production'); + assert.ok(!Object.keys(metadata.payload).some((file) => file.startsWith('caddy/'))); + assert.match( + result.stdout, + /Routes +\/srv\/caddy\/caddy\/sites\/ghost-example-com\.caddy, served by the shared Caddy/, + ); + }); + + test('80 and 443 are the shared Caddy’s, and not asked for', async () => { + const result = await h.run('install', '--domain', 'example.com', '--no-start'); + assert.equal(result.code, 0, result.stderr); + }); + + test('a domain it already serves is refused before anything is written', async () => { + shared.hosts.add('www.example.com'); + const result = await h.run( + 'install', + '--domain', + 'blog.example.com', + '--admin-domain', + 'www.example.com', + '--no-start', + ); + assert.equal(result.code, 1); + assert.match(result.stderr, /already serves www\.example\.com/); + assert.deepEqual(files(), []); + assert.equal(shared.sites.size, 0); + }); + + test('a project that already has routes is refused before anything is written', async () => { + shared.sites.set('ghost-example-com.caddy', 'routes of another directory'); + const result = await h.run('install', '--domain', 'example.com', '--no-start'); + assert.equal(result.code, 1); + assert.match( + result.stderr, + /ghost-example-com\.caddy already exists: the project ghost-example-com already has routes/, + ); + assert.match(result.stderr, /--name/); + assert.deepEqual(files(), []); + assert.equal(shared.sites.get('ghost-example-com.caddy'), 'routes of another directory'); + }); + + test('a stopped shared Caddy is refused, saying how to start it', async () => { + h.daemon.containers = [{ ...CADDY, State: 'exited' }]; + const result = await h.run('install', '--domain', 'example.com', '--no-start'); + assert.equal(result.code, 1); + assert.match( + result.stderr, + /the shared Caddy in \/srv\/caddy is not running[\s\S]*cd \/srv\/caddy && docker compose up -d/, + ); + assert.deepEqual(files(), []); + }); + + test('routes Caddy refuses are removed with everything else the installation created', async () => { + shared.refuse = 'Error: adapting config using caddyfile: ambiguous site definition'; + const result = await h.run('install', '--domain', 'example.com', '--no-start'); + assert.equal(result.code, 1); + assert.match( + result.stderr, + /does not accept its configuration[\s\S]*ambiguous site definition/, + ); + assert.equal(shared.sites.size, 0); + assert.deepEqual(files(), []); + }); + + test('a local site never joins it', async () => { + const result = await h.run('install', '--local', '--no-start'); + assert.equal(result.code, 0, result.stderr); + assert.equal(settings().COMPOSE_PROFILES, 'local'); + assert.equal(settings().INGRESS_NETWORK, undefined); + assert.deepEqual(shared.execs, []); + }); + + test('a site behind your own proxy never joins it', async () => { + const result = await h.run( + 'install', + '--domain', + 'example.com', + '--no-caddy', + '--no-start', + ); + assert.equal(result.code, 0, result.stderr); + assert.equal(settings().COMPOSE_PROFILES, 'no-caddy'); + assert.equal(settings().INGRESS_NETWORK, undefined); + assert.deepEqual(shared.execs, []); + assert.equal(shared.sites.size, 0); + }); +}); + +describe('a server without one', () => { + test('a production site gets a Caddy and a network of its own, as before', async () => { + shared.exists = false; + h.daemon.containers = []; + const result = await h.run('install', '--domain', 'example.com', '--no-start'); + assert.equal(result.code, 0, result.stderr); + assert.equal(settings().COMPOSE_PROFILES, 'production'); + assert.equal(settings().INGRESS_NETWORK, undefined); + assert.ok(existsSync(join(h.dir, 'caddy', 'sites', 'site.caddy'))); + }); +}); + +/** A .env behind the shared Caddy, as install writes it. */ +const sharedCaddyEnv = (project = 'ghost-example-com') => + writeFileSync( + join(h.dir, '.env'), + env.serializeAll([ + ['COMPOSE_PROFILES', 'shared-caddy'], + ['SITE_MODE', 'production'], + ['COMPOSE_PROJECT_NAME', project], + ['PROJECT_DIR', h.dir], + ['URL', 'https://example.com'], + ['GHOST_VERSION', '6-next-alpine'], + ['DATABASE_PASSWORD', 'a'], + ['DATABASE_ROOT_PASSWORD', 'b'], + ['INGRESS_NETWORK', 'ghost-ingress'], + ['INGRESS_EXTERNAL', 'true'], + ]), + { mode: 0o600 }, + ); + +describe('remove', () => { + test("a site's routes are removed and the shared Caddy reloaded, then the site is taken down", async () => { + sharedCaddyEnv(); + shared.sites.set('ghost-example-com.caddy', 'example.com {\n}\n'); + shared.sites.set('ghost-other-com.caddy', 'other.com {\n}\n'); + const result = await h.run('remove', '--yes'); + assert.equal(result.code, 0, result.stderr); + assert.deepEqual([...shared.sites.keys()], ['ghost-other-com.caddy']); + assert.deepEqual(shared.execs.map(({ cmd }) => cmd[0]).slice(-2), ['rm', 'caddy']); + assert.ok(compose.some((args) => args[0] === 'down' && !args.includes('--volumes'))); + assert.ok(existsSync(join(h.dir, '.env')), 'the directory and its data stay'); + assert.match(result.stdout, /still holds its configuration, data and backups/); + }); + + test('it is asked, or --yes says so', async () => { + sharedCaddyEnv(); + shared.sites.set('ghost-example-com.caddy', 'x'); + const result = await h.run('remove'); + assert.equal(result.code, 2); + assert.match(result.stderr, /Run it again with --yes/); + assert.equal(shared.sites.size, 1); + assert.ok(!compose.some((args) => args[0] === 'down')); + }); + + test('the shared Caddy itself is not a site', async () => { + writeFileSync( + join(h.dir, '.env'), + env.serializeAll([ + ['COMPOSE_PROFILES', 'infra'], + ['SITE_MODE', 'infra'], + ]), + ); + const result = await h.run('remove', '--yes'); + assert.equal(result.code, 1); + assert.match(result.stderr, /holds the shared Caddy, not a site/); + }); +}); + +describe('verification', () => { + const answer = { + status: 200, + body: JSON.stringify({ site: { url: 'https://example.com/' } }), + location: null, + certificate: { + issuer: "Let's Encrypt", + covers: true, + validTo: '2027-01-07T12:00:00.000Z', + expired: false, + untrusted: null, + }, + }; + + test("a site behind it is asked for through the shared Caddy, whose routes file is this site's", async () => { + sharedCaddyEnv(); + shared.sites.set('ghost-example-com.caddy', 'example.com {\n}\n'); + ps = () => + JSON.stringify({ ID: 'g', Service: 'ghost', State: 'running', Health: 'healthy' }); + h.daemon.https = ({ host, servername }) => { + assert.equal(host, 'caddy-ghost-example-com'); + assert.equal(servername, 'example.com'); + return answer; + }; + const checks = await verifyIngress(h.io(), siteFacts(h.dir, readSettings(h.dir)!)); + const by = Object.fromEntries(checks.map((check) => [check.label, check])); + assert.equal(by['shared caddy']?.status, 'ok'); + assert.equal(by.routes?.status, 'ok'); + assert.match(by.routes!.detail, /\/srv\/caddy\/caddy\/sites\/ghost-example-com\.caddy/); + assert.equal(by.https?.status, 'ok', by.https?.detail ?? ''); + assert.match( + by['published ports']!.detail, + /the shared Caddy on 0\.0\.0\.0:80, 0\.0\.0\.0:443/, + ); + }); + + test('routes that are gone, or a shared Caddy that is gone, are errors', async () => { + sharedCaddyEnv(); + ps = () => + JSON.stringify({ ID: 'g', Service: 'ghost', State: 'running', Health: 'healthy' }); + h.daemon.https = () => answer; + let checks = await verifyIngress(h.io(), siteFacts(h.dir, readSettings(h.dir)!)); + assert.match( + checks.find((check) => check.label === 'routes')!.detail, + /ghost-example-com\.caddy does not exist/, + ); + shared.exists = false; + checks = await verifyIngress(h.io(), siteFacts(h.dir, readSettings(h.dir)!)); + const missing = checks.find((check) => check.label === 'shared caddy')!; + assert.equal(missing.status, 'error'); + assert.match(missing.detail, /this server has none/); + }); +}); + +describe('list', () => { + test('shows the shared Caddy and the sites behind it', async () => { + h.daemon.containers = [ + CADDY, + { + Id: 'm', + Names: ['/ghost-example-com-ghost-1'], + Labels: { + 'org.ghost.docker.managed': 'true', + 'org.ghost.docker.mode': 'production', + 'com.docker.compose.project': 'ghost-example-com', + }, + Ports: [], + NetworkSettings: { + Networks: { 'ghost-example-com_ghost_network': {}, 'ghost-ingress': {} }, + }, + }, + { + Id: 's', + Names: ['/ghost-solo-com-ghost-1'], + Labels: { + 'org.ghost.docker.managed': 'true', + 'org.ghost.docker.mode': 'production', + 'com.docker.compose.project': 'ghost-solo-com', + }, + Ports: [], + NetworkSettings: { Networks: { 'ghost-solo-com_ingress': {} } }, + }, + ]; + h.daemon.composeRun = (args) => + args[0] === 'ls' + ? ok( + JSON.stringify( + ['ghost-infra', 'ghost-example-com', 'ghost-solo-com'].map((name) => ({ + Name: name, + Status: 'running(1)', + ConfigFiles: `/srv/${name}/compose.yml`, + })), + ), + ) + : undefined; + const result = await h.run('list'); + assert.equal(result.code, 0, result.stderr); + assert.match(result.stdout, /^ghost-example-com +shared-caddy /m); + assert.match(result.stdout, /^ghost-infra +infra /m); + assert.match(result.stdout, /^ghost-solo-com +production /m); + assert.match(result.stdout, /shared-caddy is a production site behind the shared Caddy/); + }); +}); + +describe('config validate', () => { + test("the shared Caddy's .env needs no Ghost, but its network", async () => { + writeFileSync( + join(h.dir, '.env'), + env.serializeAll([ + ['COMPOSE_PROFILES', 'infra'], + ['SITE_MODE', 'infra'], + ['COMPOSE_PROJECT_NAME', 'ghost-infra'], + ['PROJECT_DIR', h.dir], + ['INGRESS_NETWORK', 'ghost-ingress'], + ['INGRESS_EXTERNAL', 'true'], + ]), + { mode: 0o600 }, + ); + const valid = await h.run('config', 'validate'); + assert.equal(valid.code, 0, valid.stdout + valid.stderr); + assert.match(valid.stdout, /valid for the shared Caddy/); + + writeFileSync( + join(h.dir, '.env'), + env.serializeAll([ + ['COMPOSE_PROFILES', 'infra,activitypub'], + ['SITE_MODE', 'infra'], + ['COMPOSE_PROJECT_NAME', 'ghost-infra'], + ['PROJECT_DIR', h.dir], + ]), + { mode: 0o600 }, + ); + const invalid = await h.run('config', 'validate'); + assert.equal(invalid.code, 1); + assert.match(invalid.stdout + invalid.stderr, /runs Caddy alone: remove activitypub/); + assert.match( + invalid.stdout + invalid.stderr, + /INGRESS_NETWORK is required for the shared Caddy/, + ); + assert.match(invalid.stdout + invalid.stderr, /INGRESS_EXTERNAL must be true/); + }); + + test('a site behind it is a production site, and must be on the shared network', async () => { + sharedCaddyEnv(); + const valid = await h.run('config', 'validate'); + assert.equal(valid.code, 0, valid.stdout + valid.stderr); + assert.match(valid.stdout, /valid for a production site/); + + const values = settings(); + delete values.INGRESS_EXTERNAL; + writeFileSync(join(h.dir, '.env'), env.serializeAll(Object.entries(values)), { + mode: 0o600, + }); + const invalid = await h.run('config', 'validate'); + assert.equal(invalid.code, 1); + assert.match(invalid.stdout + invalid.stderr, /INGRESS_EXTERNAL must be true/); + }); + + test('a site needs its database passwords, which compose.yml no longer guards', async () => { + sharedCaddyEnv(); + const values = settings(); + delete values.DATABASE_ROOT_PASSWORD; + writeFileSync(join(h.dir, '.env'), env.serializeAll(Object.entries(values)), { + mode: 0o600, + }); + const result = await h.run('config', 'validate'); + assert.equal(result.code, 1); + assert.match(result.stdout + result.stderr, /DATABASE_ROOT_PASSWORD is required/); + }); +}); + +describe('the pieces', () => { + test('shared-caddy selects production; infra selects no site mode', () => { + assert.equal(siteMode('shared-caddy,activitypub'), 'production'); + assert.equal(siteMode('shared-caddy,production'), null); + assert.equal(siteMode('infra'), null); + assert.equal(layoutOf('shared-caddy,analytics'), 'shared-caddy'); + assert.equal(layoutOf('infra'), 'infra'); + assert.equal(layoutOf('production'), 'production'); + assert.equal(layoutOf('local,mailpit'), 'local'); + }); + + test("each layout's stack files", () => { + const stack = h.env.GD_STACK_DIR!; + const tops = (layout: Parameters[1]) => [ + ...new Set(payloadFiles(stack, layout).map((file) => file.split('/')[0])), + ]; + assert.deepEqual(tops('infra'), [ + '.env.example', + 'caddy', + 'compose.ipv6.yml', + 'compose.yml', + ]); + assert.ok(!tops('shared-caddy').includes('caddy')); + assert.ok(tops('shared-caddy').includes('tinybird')); + assert.ok(tops('production').includes('caddy')); + }); +}); diff --git a/tests/e2e/shared-caddy.sh b/tests/e2e/shared-caddy.sh new file mode 100755 index 00000000..58a22111 --- /dev/null +++ b/tests/e2e/shared-caddy.sh @@ -0,0 +1,250 @@ +#!/usr/bin/env bash +# Several production sites behind one shared Caddy, against real containers. +# +# tests/e2e/shared-caddy.sh +# +# Builds the manager image from this checkout, sets up the shared Caddy with +# `install --infra`, and installs two production sites behind it: one on +# Ghost 6.61.0 with ActivityPub, one on the newest Ghost 6, each with its own +# MySQL. Caddy serves them with its own test CA under names curl resolves to +# this host. A third site asking for a domain the shared Caddy already serves +# is refused before anything is written. Then each operation on one site is +# checked to leave the other as it was, the same containers serving the same +# routes: updating the first site's Ghost, backing it up and restoring it over +# itself, restarting and recreating the shared Caddy (both sites come back), +# and removing the second site, whose routes go with it. The shared Caddy's +# own directory answers self-update; moving it between releases is unit-tested. +# +# It pulls images, starts containers and binds ports 80 and 443 (it fails +# when something else holds them, or is skipped with GD_E2E_ALLOW_SKIP=1). It +# needs jq and curl. Exits non-zero at the first check that fails, naming it. +set -euo pipefail + +ROOT=$(CDPATH='' cd -- "$(dirname -- "$0")/../.." && pwd -P) +IMAGE=ghost-docker:e2e-shared-caddy +FROM=6.61.0 +DOMAIN_A=alpha-e2e.test +DOMAIN_B=bravo-e2e.test + +# What this host cannot run fails the run, unless GD_E2E_ALLOW_SKIP=1. +# shellcheck source=/dev/null +source "$ROOT/tests/e2e/lib.sh" +require_docker +port_free() { ! (exec 3<>"/dev/tcp/127.0.0.1/$1") 2>/dev/null; } +if ! port_free 80 || ! port_free 443; then + skip "something on this host already holds 80 or 443" + passed "Nothing ran: the shared Caddy is on 80 and 443." + exit 0 +fi +if docker network inspect ghost-ingress >/dev/null 2>&1; then + skip "this daemon already has a shared Caddy (the network ghost-ingress)" + passed "Nothing ran: a daemon has one shared Caddy." + exit 0 +fi +for tool in jq curl; do + command -v "$tool" >/dev/null || { + printf 'shared-caddy.sh needs %s\n' "$tool" >&2 + exit 1 + } +done + +work_dir shared-caddy +SITES=() +SITE="" + +# The members first, then the shared Caddy and its network, then every +# directory, removed as root: MySQL's data belongs to MySQL's user. +teardown() { + local site + for site in ${SITES[@]+"${SITES[@]}"}; do + [[ -f $site/.env ]] && docker compose --project-directory "$site" -f "$site/compose.yml" \ + down --volumes --remove-orphans --timeout 5 >/dev/null 2>&1 + done + [[ -f ${CADDY:-}/.env ]] && docker compose --project-directory "$CADDY" -f "$CADDY/compose.yml" \ + down --volumes --remove-orphans --timeout 5 >/dev/null 2>&1 + docker network rm ghost-ingress >/dev/null 2>&1 + docker run --rm --user 0 --entrypoint rm -v "$WORK:/work" "$IMAGE" -rf /work/sites >/dev/null 2>&1 +} + +on_fail() { + [[ -z ${CADDY:-} ]] || docker compose --project-directory "$CADDY" -f "$CADDY/compose.yml" \ + logs --no-color --tail 40 caddy >&2 2>&1 || true +} + +# gd SITE ARGS... -- a site's own launcher, on the image built here. +gd() { GD_IMAGE=$IMAGE "$1/ghost-docker" --dir "$@"; } + +# through DOMAIN -- what Ghost's site endpoint answers for DOMAIN, through the +# shared Caddy on this host's port 443, trusting its test CA as told to. +through() { + curl --disable --silent --insecure --noproxy '*' --max-time 20 --resolve "$1:443:127.0.0.1" \ + "https://$1/ghost/api/admin/site/" | jq -r '.site.url' 2>/dev/null || true +} + +# serves DOMAIN -- Ghost for DOMAIN answers through the shared Caddy, waiting +# for Caddy's certificate and for Ghost to boot. +serves() { + local tries=0 + until [[ $(through "$1") == "https://$1/" ]]; do + tries=$((tries + 1)) + ((tries < 90)) || fail "Ghost for $1 does not answer through the shared Caddy" "$(through "$1")" + sleep 2 + done +} + +# containers SITE -- each of the site's containers, with when it started. +containers() { + compose_in "$1" ps --all -q | sort | xargs docker inspect --format '{{.Id}} {{.State.StartedAt}}' +} + +# routes -- the shared Caddy's routes files, with their checksums. +routes() { (cd "$CADDY/caddy/sites" && find . -type f | sort | xargs shasum -a 256); } + +# untouched SITE BEFORE -- SITE's containers are the ones there were, as they were. +untouched() { + [[ $(containers "$1") == "$2" ]] || fail "$(basename "$1")'s containers changed" "$(containers "$1")" +} + +printf 'Docker: %s on %s\n' "$(docker info --format '{{.OperatingSystem}}')" "$(uname -s)" + +step "Build the manager image, and set up the shared Caddy" +run docker build --quiet --file "$ROOT/manager/Dockerfile" --tag "$IMAGE" "$ROOT" +expect_status 0 +mkdir -p "$WORK/launcher-only" "$WORK/sites/caddy/caddy/global" +cp "$ROOT/ghost-docker" "$WORK/launcher-only/ghost-docker" +CADDY=$WORK/sites/caddy +# Caddy's own CA for the names, at once: a test fixture standing in for the +# CA a real domain gets. +printf 'local_certs\n' >"$CADDY/caddy/global/test-ca.caddy" +run env GD_IMAGE=$IMAGE "$WORK/launcher-only/ghost-docker" --dir "$CADDY" install --infra +expect_status 0 +expect_output 'The shared Caddy is installed' +[[ $(setting "$CADDY" COMPOSE_PROFILES) == infra ]] || fail "the shared Caddy's profiles are not infra" +[[ ! -e $CADDY/ghost.env && ! -e $CADDY/mysql-init && ! -e $CADDY/data ]] || fail "the shared Caddy has a site's files" +[[ $(docker network inspect ghost-ingress --format '{{index .Labels "org.ghost.docker.infra.dir"}}') == "$CADDY" ]] || + fail "the network does not say where the shared Caddy is" +[[ $(compose_in "$CADDY" ps --format '{{.Service}} {{.Health}}') == 'caddy healthy' ]] || + fail "Caddy is not the only service, or not healthy" "$(compose_in "$CADDY" ps)" +run env GD_IMAGE=$IMAGE "$WORK/launcher-only/ghost-docker" --dir "$WORK/sites/second" install --infra +expect_status 1 +expect_output "already has the shared Caddy in $CADDY" +[[ $(jq -r '.mode + " " + (.ghost | tostring)' "$CADDY/.ghost-docker.json") == 'infra null' ]] || + fail "the shared Caddy's metadata is not infra's" "$(cat "$CADDY/.ghost-docker.json")" +# Moving between releases is self-update.sh's; here, that it is the shared Caddy's command too. +run gd "$CADDY" self-update --check +expect_status 0 +expect_output '^The shared Caddy runs ' +expect_output '^It is up to date' +run gd "$CADDY" backup +expect_status 1 +expect_output 'holds the shared Caddy, not a site' +ok "$CADDY, on ghost-ingress; self-update knows it, site commands refuse it, a second is refused" + +step "Two sites behind it, on different Ghost versions, each with its own MySQL" +new_site alpha +A=$SITE +run env GD_IMAGE=$IMAGE "$WORK/launcher-only/ghost-docker" --dir "$A" install --domain "$DOMAIN_A" \ + --version "$FROM" --with activitypub --no-prompt +expect_status 0 +expect_output 'served by the shared Caddy' +new_site bravo +B=$SITE +run env GD_IMAGE=$IMAGE "$WORK/launcher-only/ghost-docker" --dir "$B" install --domain "$DOMAIN_B" --no-prompt +expect_status 0 +for site in "$A" "$B"; do + [[ $(setting "$site" COMPOSE_PROFILES) == shared-caddy* ]] || fail "$site is not behind the shared Caddy" + [[ ! -e $site/caddy ]] || fail "$site has a Caddy of its own" + [[ -z $(compose_in "$site" ps -q caddy) ]] || fail "$site runs a Caddy" + [[ -n $(compose_in "$site" ps -q db) ]] || fail "$site has no MySQL of its own" +done +[[ -f $CADDY/caddy/sites/ghost-alpha-e2e-test.caddy && -f $CADDY/caddy/sites/ghost-bravo-e2e-test.caddy ]] || + fail "the routes are not in the shared Caddy" "$(ls "$CADDY/caddy/sites")" +[[ -n $(compose_in "$A" ps -q activitypub) ]] || fail "alpha's ActivityPub is not running" +version_a=$(compose_in "$A" exec -T ghost printenv GHOST_VERSION) +version_b=$(compose_in "$B" exec -T ghost printenv GHOST_VERSION) +[[ $version_a == "$FROM" && $version_b != "$FROM" ]] || fail "the sites run $version_a and $version_b" +serves "$DOMAIN_A" +serves "$DOMAIN_B" +for site in "$A" "$B"; do + run gd "$site" check + expect_status 0 + expect_output 'shared caddy +healthy' + expect_output 'routes +.*\.caddy, in the shared Caddy' +done +run gd "$A" list +expect_status 0 +expect_output '^ghost-infra +infra ' +expect_output '^ghost-alpha-e2e-test +shared-caddy ' +expect_output '^ghost-bravo-e2e-test +shared-caddy ' +ok "alpha on Ghost $version_a with ActivityPub, bravo on Ghost $version_b; both served, check passes" + +step "A domain the shared Caddy serves is refused before anything is written" +new_site charlie +run env GD_IMAGE=$IMAGE "$WORK/launcher-only/ghost-docker" --dir "$SITE" install --domain "www.$DOMAIN_B" \ + --admin-domain "$DOMAIN_A" --no-prompt +expect_status 1 +expect_output "already serves $DOMAIN_A" +[[ -z $(find "$SITE" -mindepth 1 -not -name .ghost-docker-probe) ]] || + fail "the refused install wrote into its directory" "$(ls -A "$SITE")" +ok "refused, and $SITE is empty" + +before_b=$(containers "$B") +routes_before=$(routes) + +step "Updating alpha's Ghost leaves bravo untouched" +run gd "$A" update +expect_status 0 +expect_output "Updated Ghost from $FROM to " +[[ $(compose_in "$A" exec -T ghost printenv GHOST_VERSION) != "$FROM" ]] || fail "alpha still runs $FROM" +serves "$DOMAIN_A" +untouched "$B" "$before_b" +[[ $(routes) == "$routes_before" ]] || fail "the routes changed" "$(routes)" +[[ $(through "$DOMAIN_B") == "https://$DOMAIN_B/" ]] || fail "bravo no longer answers" +ok "alpha updated; bravo's containers and every route as they were" + +step "Backing alpha up and restoring it over itself leaves bravo untouched" +run gd "$A" backup +expect_status 0 +backup=$(find "$A/backups" -mindepth 1 -maxdepth 1 | sort | tail -1) +jq -e '.notIncluded | any(test("shared Caddy"))' "$backup/manifest.json" >/dev/null || + fail "the backup does not say it leaves the routes out" "$(cat "$backup/manifest.json")" +run gd "$A" restore --yes "$backup" +expect_status 0 +serves "$DOMAIN_A" +untouched "$B" "$before_b" +[[ $(routes) == "$routes_before" ]] || fail "the routes changed" "$(routes)" +ok "restored $(basename "$backup"); bravo's containers and every route as they were" + +step "Restarting, and recreating, the shared Caddy brings both back" +before_a=$(containers "$A") +compose_in "$CADDY" restart caddy >/dev/null 2>&1 || fail "Caddy did not restart" +serves "$DOMAIN_A" +serves "$DOMAIN_B" +out=$(compose_in "$CADDY" down 2>&1) || fail "the shared Caddy did not come down" "$out" +docker network inspect ghost-ingress >/dev/null 2>&1 || fail "taking the shared Caddy down removed its network" +compose_in "$CADDY" up --detach --wait >/dev/null 2>&1 || fail "the shared Caddy did not start again" +serves "$DOMAIN_A" +serves "$DOMAIN_B" +untouched "$A" "$before_a" +untouched "$B" "$before_b" +ok "both answer after a restart and after down and up; neither site's containers changed" + +step "Removing bravo removes its routes, and leaves alpha untouched" +run gd "$B" remove +expect_status 2 +expect_output 'Run it again with --yes' +run gd "$B" remove --yes +expect_status 0 +[[ ! -e $CADDY/caddy/sites/ghost-bravo-e2e-test.caddy ]] || fail "bravo's routes are still there" +[[ -f $CADDY/caddy/sites/ghost-alpha-e2e-test.caddy ]] || fail "alpha's routes went too" +[[ -z $(compose_in "$B" ps --all -q) ]] || fail "bravo's containers are still there" +[[ -f $B/.env ]] || fail "bravo's directory was not kept" +[[ $(through "$DOMAIN_B") != "https://$DOMAIN_B/" ]] || fail "bravo still answers" +serves "$DOMAIN_A" +untouched "$A" "$before_a" +run gd "$A" list +expect_output '^ghost-alpha-e2e-test +shared-caddy ' +refute_output 'ghost-bravo-e2e-test' +ok "bravo removed with its routes; alpha's containers as they were, and served" + +passed 'All shared Caddy checks passed.' From 90c70730ee21fe8ed5871081ccf13e00450fa2b0 Mon Sep 17 00:00:00 2001 From: Austin Burdine Date: Mon, 2 Nov 2026 15:09:56 -0500 Subject: [PATCH 02/15] Undid only what a shared-Caddy install created, and refused a stray ingress network (S13) ref https://linear.app/ghost/issue/PLA-484 Review of #427 found ways a failed or concurrent install could remove what another installation owned, and a configuration the manager would accept but the shared Caddy could not route. - manager/src/commands/install.ts: the ingress network is recorded for undo only once this install created it, and a site's routes only once this install wrote them, so a network or routes file another installation made meanwhile is refused and left alone. - manager/src/shared.ts: addRoutes reports when the file is its own. - manager/src/commands/remove.ts: a site behind a shared Caddy that is gone is refused, since its routes could not be removed; a failed `docker compose down` says the routes are already gone. - manager/src/config.ts: INGRESS_NETWORK must be ghost-ingress, the network the shared Caddy is found by. - tests/e2e/shared-caddy.sh: the second `install --infra` runs in a directory that exists, so it reaches the refusal it checks. - manager/test/shared.test.ts: each of these. --- manager/src/commands/install.ts | 11 ++++-- manager/src/commands/remove.ts | 15 ++++++++ manager/src/config.ts | 21 +++++++++-- manager/src/shared.ts | 13 ++++--- manager/test/shared.test.ts | 65 ++++++++++++++++++++++++++++++++- tests/e2e/shared-caddy.sh | 1 + 6 files changed, 111 insertions(+), 15 deletions(-) diff --git a/manager/src/commands/install.ts b/manager/src/commands/install.ts index 88aff7b1..28f4f212 100644 --- a/manager/src/commands/install.ts +++ b/manager/src/commands/install.ts @@ -814,10 +814,12 @@ async function writeSiteRoutes( }; const names = [domain, adminDomain].filter(Boolean).join(' and '); if (shared !== null) { - created.routes = true; - created.save(); + // Claimed once written: a file another installation wrote is refused, never removed. await io.busy('Adding the routes to the shared Caddy', () => - addRoutes(io, shared, project, renderRoutes(routes)), + addRoutes(io, shared, project, renderRoutes(routes), () => { + created.routes = true; + created.save(); + }), ); ok( io, @@ -935,12 +937,13 @@ async function installInfra(target: Target, flags: Flags, requested: Requested): ); ok(io, ENV_FILE, 'the shared Caddy\u2019s settings'); // No project owns it, so taking the shared Caddy down leaves its members attached. - created.network = INGRESS_NETWORK; await createNetwork(io.docker, INGRESS_NETWORK, { [MANAGED_LABEL.split('=')[0]!]: 'true', [INFRA_DIR_LABEL]: dir, [INFRA_PROJECT_LABEL]: project, }); + // Only now: one another installation created meanwhile is not this one's to remove. + created.network = INGRESS_NETWORK; ok(io, 'network', `${INGRESS_NETWORK}, which the services of each site behind it join`); created.file(join(dir, META_FILE)); writeMetadata( diff --git a/manager/src/commands/remove.ts b/manager/src/commands/remove.ts index a8335985..e5e67b0d 100644 --- a/manager/src/commands/remove.ts +++ b/manager/src/commands/remove.ts @@ -12,6 +12,7 @@ import { ok } from '../report.ts'; import { describeShared, findSharedCaddy, + INGRESS_NETWORK, removeRoutes, routesPath, runningCaddy, @@ -30,6 +31,16 @@ export const removeCommand = defineCommand({ const project = site.settings.get('COMPOSE_PROJECT_NAME') || ''; await refuseForeignProject(io, project, dir); const shared = site.layout === SHARED_CADDY_PROFILE ? await findSharedCaddy(io) : null; + if (site.layout === SHARED_CADDY_PROFILE && shared === null) { + // Its routes may still be in the shared Caddy's directory, which only + // the running shared Caddy lets the manager change. + throw new CliError( + `this site is behind the shared Caddy, and this server has none (no ${INGRESS_NETWORK} network),\n` + + ' so its routes cannot be removed. Start the shared Caddy and run this again, or take the\n' + + ' site down alone with docker compose down and remove its routes file by hand.\n' + + ' Nothing has been changed.', + ); + } if (shared !== null) { runningCaddy(shared); } @@ -53,6 +64,10 @@ export const removeCommand = defineCommand({ if (down.exitCode !== 0) { throw new CliError( `docker compose down failed: ${composeError(down, 4)}\n` + + (shared === null + ? '' + : ` Its routes are already gone from ${describeShared(shared)}, so the site is not\n` + + ' served until this finishes.\n') + ' Run it again in this directory once the cause is fixed.', ); } diff --git a/manager/src/config.ts b/manager/src/config.ts index a9e5691c..9a97593b 100644 --- a/manager/src/config.ts +++ b/manager/src/config.ts @@ -10,6 +10,7 @@ import { CliError } from './errors.ts'; import { modeOf, readIfExists } from './fs.ts'; import type { Io } from './io.ts'; import { ok, type Check } from './report.ts'; +import { INGRESS_NETWORK } from './shared.ts'; import { COMPOSE_OVERRIDE_FILE, ENV_EXAMPLE_FILE, @@ -265,16 +266,28 @@ function validateInfra(file: string, values: Record): Finding[] return [...findings, ...externalIngress(file, values)]; } -/** The shared Caddy's network is the manager's, so Compose must not create or remove it. */ -const externalIngress = (file: string, values: Record): Finding[] => - values.INGRESS_EXTERNAL === 'true' +/** + * The shared Caddy's network is the manager's, so Compose must not create or + * remove it; and it is the one the manager finds the shared Caddy by. + */ +const externalIngress = (file: string, values: Record): Finding[] => [ + ...(values.INGRESS_NETWORK && values.INGRESS_NETWORK !== INGRESS_NETWORK + ? [ + error( + file, + `INGRESS_NETWORK must be ${INGRESS_NETWORK}, the shared Caddy's network: got ${values.INGRESS_NETWORK}`, + ), + ] + : []), + ...(values.INGRESS_EXTERNAL === 'true' ? [] : [ error( file, `INGRESS_EXTERNAL must be true: ${values.INGRESS_NETWORK || 'the network'} is the shared Caddy's, which no Compose project creates or removes`, ), - ]; + ]), +]; /** * `ghost.env` holds Ghost application settings only. Two mistakes matter, and diff --git a/manager/src/shared.ts b/manager/src/shared.ts index e25a887c..ba4f5ae0 100644 --- a/manager/src/shared.ts +++ b/manager/src/shared.ts @@ -191,13 +191,15 @@ export async function refuseTaken( * Writes a site's routes into the shared Caddy, owned by whoever owns its * caddy/sites/, has Caddy validate its whole configuration with them, and * reloads it. Routes Caddy refuses are removed again, and Caddy keeps serving - * what it served. + * what it served. `written` is called once the file is this call's: an + * existing one is never overwritten, so a caller only undoes its own. */ export async function addRoutes( io: Io, shared: SharedCaddy, project: string, routes: string, + written: () => void = () => undefined, ): Promise { const caddy = runningCaddy(shared); const owner = await inCaddy(io, caddy, ['stat', '-c', '%u:%g', SITES]); @@ -207,7 +209,7 @@ export async function addRoutes( const file = `${SITES}/${routesFile(project)}`; // Written beside it under a name the Caddyfile's *.caddy does not import, // then renamed, so Caddy never reads half a file. - const written = await inCaddy( + const write = await inCaddy( io, caddy, [ @@ -220,11 +222,10 @@ export async function addRoutes( ], owner.stdout.trim(), ); - if (written.status !== 0) { - throw new CliError( - `the routes could not be written to the shared Caddy:\n${said(written)}`, - ); + if (write.status !== 0) { + throw new CliError(`the routes could not be written to the shared Caddy:\n${said(write)}`); } + written(); const valid = await inCaddy(io, caddy, ['caddy', 'validate', '--config', CADDYFILE]); if (valid.status !== 0) { const removed = await inCaddy(io, caddy, ['rm', '-f', file], owner.stdout.trim()); diff --git a/manager/test/shared.test.ts b/manager/test/shared.test.ts index 52464299..486b7dd1 100644 --- a/manager/test/shared.test.ts +++ b/manager/test/shared.test.ts @@ -32,6 +32,8 @@ interface FakeShared { /** The labels the network was created with, when the manager created it. */ created: Record | null; exists: boolean; + /** Another installation, creating the network or a routes file first. */ + raced: { network?: boolean; routes?: string }; } function fakeShared(): FakeShared { @@ -43,6 +45,7 @@ function fakeShared(): FakeShared { execs: [], created: null, exists: true, + raced: {}, }; } @@ -86,6 +89,10 @@ function sharedApi(shared: FakeShared) { if (path === '/networks/create' && method === 'POST') { const body = request.body as { Name: string; Labels: Record }; assert.equal(body.Name, 'ghost-ingress'); + if (shared.raced.network) { + shared.exists = true; + return json(409, { message: 'network with name ghost-ingress already exists' }); + } shared.created = body.Labels; shared.exists = true; return json(201, { Id: 'ingress-id' }); @@ -132,7 +139,13 @@ function run(shared: FakeShared, { cmd }: { cmd: string[] }): { stdout: string; case 'stat': return { stdout: '1000:1000\n', code: 0 }; case 'sh': { - // sh -c SCRIPT sh ROUTES FILE + // sh -c SCRIPT sh ROUTES FILE, which never overwrites a file. + if (shared.raced.routes !== undefined) { + shared.sites.set(name(cmd[5]!), shared.raced.routes); + } + if (shared.sites.has(name(cmd[5]!))) { + return { stdout: '', code: 1 }; + } shared.sites.set(name(cmd[5]!), cmd[4]!); return { stdout: '', code: 0 }; } @@ -302,6 +315,14 @@ describe('install --infra', () => { assert.equal(shared.exists, false); assert.deepEqual(files(), []); }); + + test('a network another installation created meanwhile is not removed', async () => { + shared.raced.network = true; + const result = await h.run('install', '--infra'); + assert.equal(result.code, 1); + assert.equal(shared.exists, true); + assert.deepEqual(files(), []); + }); }); describe('self-update of the shared Caddy', () => { @@ -509,6 +530,15 @@ describe('a production install on a server with the shared Caddy', () => { assert.equal(shared.sites.get('ghost-example-com.caddy'), 'routes of another directory'); }); + test('routes another installation wrote meanwhile are refused, and left alone', async () => { + shared.raced.routes = 'routes of another directory'; + const result = await h.run('install', '--domain', 'example.com', '--no-start'); + assert.equal(result.code, 1); + assert.match(result.stderr, /could not be written to the shared Caddy/); + assert.equal(shared.sites.get('ghost-example-com.caddy'), 'routes of another directory'); + assert.deepEqual(files(), []); + }); + test('a stopped shared Caddy is refused, saying how to start it', async () => { h.daemon.containers = [{ ...CADDY, State: 'exited' }]; const result = await h.run('install', '--domain', 'example.com', '--no-start'); @@ -601,6 +631,25 @@ describe('remove', () => { assert.match(result.stdout, /still holds its configuration, data and backups/); }); + test('a server whose shared Caddy is gone is refused, as its routes cannot be removed', async () => { + sharedCaddyEnv(); + shared.exists = false; + const result = await h.run('remove', '--yes'); + assert.equal(result.code, 1); + assert.match(result.stderr, /this server has none \(no ghost-ingress network\)/); + assert.ok(!compose.some((args) => args[0] === 'down')); + }); + + test('a failed docker compose down says the routes are already gone', async () => { + sharedCaddyEnv(); + shared.sites.set('ghost-example-com.caddy', 'example.com {\n}\n'); + h.daemon.composeRun = (args) => (args[0] === 'down' ? failed(1, 'daemon gone') : ok('')); + const result = await h.run('remove', '--yes'); + assert.equal(result.code, 1); + assert.match(result.stderr, /Its routes are already gone from the shared Caddy/); + assert.equal(shared.sites.size, 0); + }); + test('it is asked, or --yes says so', async () => { sharedCaddyEnv(); shared.sites.set('ghost-example-com.caddy', 'x'); @@ -781,6 +830,20 @@ describe('config validate', () => { const invalid = await h.run('config', 'validate'); assert.equal(invalid.code, 1); assert.match(invalid.stdout + invalid.stderr, /INGRESS_EXTERNAL must be true/); + + writeFileSync( + join(h.dir, '.env'), + env.serializeAll( + Object.entries({ ...values, INGRESS_EXTERNAL: 'true', INGRESS_NETWORK: 'other' }), + ), + { mode: 0o600 }, + ); + const elsewhere = await h.run('config', 'validate'); + assert.equal(elsewhere.code, 1); + assert.match( + elsewhere.stdout + elsewhere.stderr, + /INGRESS_NETWORK must be ghost-ingress, the shared Caddy's network: got other/, + ); }); test('a site needs its database passwords, which compose.yml no longer guards', async () => { diff --git a/tests/e2e/shared-caddy.sh b/tests/e2e/shared-caddy.sh index 58a22111..4d5f8808 100755 --- a/tests/e2e/shared-caddy.sh +++ b/tests/e2e/shared-caddy.sh @@ -125,6 +125,7 @@ expect_output 'The shared Caddy is installed' fail "the network does not say where the shared Caddy is" [[ $(compose_in "$CADDY" ps --format '{{.Service}} {{.Health}}') == 'caddy healthy' ]] || fail "Caddy is not the only service, or not healthy" "$(compose_in "$CADDY" ps)" +mkdir -p "$WORK/sites/second" run env GD_IMAGE=$IMAGE "$WORK/launcher-only/ghost-docker" --dir "$WORK/sites/second" install --infra expect_status 1 expect_output "already has the shared Caddy in $CADDY" From 93bbf3d1406ec1b2925e530c59f36875895aa96e Mon Sep 17 00:00:00 2001 From: Austin Burdine Date: Mon, 2 Nov 2026 15:29:32 -0500 Subject: [PATCH 03/15] Linked routes into place, and planned the shared Caddy's self-update as a site's (S13) ref https://linear.app/ghost/issue/PLA-484 Review of #427 found two writers of one project's routes could both pass the existence check and the second rename replace the first, and that the shared Caddy's self-update skipped refusals a site's makes. - manager/src/shared.ts: routes are written to a temporary file of the writer's own and hard-linked into place, which fails when the file exists, so one writer's routes are never replaced by another's. addRoutes says when the file stops being the caller's, once routes Caddy refused are removed. - manager/src/commands/install.ts: undo forgets refused routes, so it cannot remove a file another installation wrote after them. - manager/src/commands/self-update.ts: the shared Caddy's update refuses a project another directory owns, takes the lock through lockPlanned so metadata changed while it planned is refused, and when its files cannot be put back says where they are, without starting Caddy on them. - manager/src/commands/common.ts: lockPlanned takes either metadata. - manager/test/shared.test.ts: each of these. --- manager/src/commands/common.ts | 4 +- manager/src/commands/install.ts | 4 +- manager/src/commands/self-update.ts | 17 ++++++-- manager/src/shared.ts | 18 +++++---- manager/test/shared.test.ts | 60 ++++++++++++++++++++++++++++- 5 files changed, 88 insertions(+), 15 deletions(-) diff --git a/manager/src/commands/common.ts b/manager/src/commands/common.ts index 14eaff24..42b19a77 100644 --- a/manager/src/commands/common.ts +++ b/manager/src/commands/common.ts @@ -8,7 +8,7 @@ import { loadContext, type Context } from '../context.ts'; import { CliError } from '../errors.ts'; import type { Io } from '../io.ts'; import { acquireLock, type Lock } from '../lock.ts'; -import { readMetadata, type Metadata } from '../meta.ts'; +import { readMetadata, type AnyMetadata, type Metadata } from '../meta.ts'; import { channelOf, CHANNELS, isRelease, type Channel } from '../release.ts'; import { ENV_FILE, @@ -99,7 +99,7 @@ export function refuseUnfinished(dir: string, again: string): void { export function lockPlanned( dir: string, operation: string, - planned: Metadata, + planned: AnyMetadata, again: string, ): Lock { const lock = acquireLock(dir, operation); diff --git a/manager/src/commands/install.ts b/manager/src/commands/install.ts index 28f4f212..bc6fa179 100644 --- a/manager/src/commands/install.ts +++ b/manager/src/commands/install.ts @@ -816,8 +816,8 @@ async function writeSiteRoutes( if (shared !== null) { // Claimed once written: a file another installation wrote is refused, never removed. await io.busy('Adding the routes to the shared Caddy', () => - addRoutes(io, shared, project, renderRoutes(routes), () => { - created.routes = true; + addRoutes(io, shared, project, renderRoutes(routes), (owned) => { + created.routes = owned; created.save(); }), ); diff --git a/manager/src/commands/self-update.ts b/manager/src/commands/self-update.ts index 3852640e..7c10b3f5 100644 --- a/manager/src/commands/self-update.ts +++ b/manager/src/commands/self-update.ts @@ -18,7 +18,7 @@ import { defineCommand, flag } from '../command.ts'; import { requireValid } from '../config.ts'; import type { Context } from '../context.ts'; import { CliError, describeError, EXIT, UsageError } from '../errors.ts'; -import { acquireLock } from '../lock.ts'; +import { refuseForeignProject } from '../project.ts'; import { atomicWrite } from '../fs.ts'; import type { Io } from '../io.ts'; import { isReleasedMainLayout, migrateReleasedMain } from '../legacy.ts'; @@ -462,8 +462,10 @@ async function updateInfra( ); } refuseUnfinished(dir, 'self-update'); + // A project another directory owns would be recreated as this one's. + await refuseForeignProject(io, site.settings.get('COMPOSE_PROJECT_NAME') || '', dir); - const lock = acquireLock(dir, `update to ${describeStack(to)}`); + const lock = lockPlanned(dir, `update to ${describeStack(to)}`, metadata, 'self-update'); try { io.stdout( `Updating the shared Caddy from ${describeStack(from)} to ${describeStack(to)}\n`, @@ -501,7 +503,16 @@ async function updateInfra( io.stderr( `\n${describeError(error)}\n\nThe update to ${describeStack(to)} did not complete. Putting ${describeStack(from)}'s files back\n`, ); - snapshot.restore(); + try { + snapshot.restore(); + } catch (restoreError) { + throw new CliError( + `the update failed, and ${describeStack(from)}'s files could not be put back: ${describeError(restoreError)}\n` + + ` They are in ${UPDATE_DIR}/files, in ${dir}: copy them back, then docker compose up -d\n` + + ` there, and remove ${UPDATE_DIR} once Caddy runs on them.` + + (started ? ' Caddy may be stopped until then.' : ''), + ); + } if (started) { try { await caddyUp(io, dir, `Starting ${describeStack(from)}'s Caddy again`); diff --git a/manager/src/shared.ts b/manager/src/shared.ts index ba4f5ae0..9f788922 100644 --- a/manager/src/shared.ts +++ b/manager/src/shared.ts @@ -191,15 +191,16 @@ export async function refuseTaken( * Writes a site's routes into the shared Caddy, owned by whoever owns its * caddy/sites/, has Caddy validate its whole configuration with them, and * reloads it. Routes Caddy refuses are removed again, and Caddy keeps serving - * what it served. `written` is called once the file is this call's: an - * existing one is never overwritten, so a caller only undoes its own. + * what it served. `owned` says whether the file is this call's to undo: true + * once written, as an existing one is never replaced, and false again once + * the routes Caddy refused are removed, since another site may then add its own. */ export async function addRoutes( io: Io, shared: SharedCaddy, project: string, routes: string, - written: () => void = () => undefined, + owned: (yes: boolean) => void = () => undefined, ): Promise { const caddy = runningCaddy(shared); const owner = await inCaddy(io, caddy, ['stat', '-c', '%u:%g', SITES]); @@ -207,15 +208,17 @@ export async function addRoutes( throw new CliError(`the shared Caddy's ${SITES} could not be read:\n${said(owner)}`); } const file = `${SITES}/${routesFile(project)}`; - // Written beside it under a name the Caddyfile's *.caddy does not import, - // then renamed, so Caddy never reads half a file. + // Written beside it under a name of this writer's that the Caddyfile's + // *.caddy does not import, then linked into place: a link, unlike a + // rename, fails when the file exists, so another site's is never replaced + // and Caddy never reads half a file. const write = await inCaddy( io, caddy, [ 'sh', '-c', - 'umask 022 && [ ! -e "$2" ] && printf "%s" "$1" > "$2.new" && mv "$2.new" "$2"', + 'umask 022 && t="$2.$$.new" && printf "%s" "$1" > "$t" && ln "$t" "$2"; s=$?; rm -f "$t"; exit $s', 'sh', routes, file, @@ -225,7 +228,7 @@ export async function addRoutes( if (write.status !== 0) { throw new CliError(`the routes could not be written to the shared Caddy:\n${said(write)}`); } - written(); + owned(true); const valid = await inCaddy(io, caddy, ['caddy', 'validate', '--config', CADDYFILE]); if (valid.status !== 0) { const removed = await inCaddy(io, caddy, ['rm', '-f', file], owner.stdout.trim()); @@ -236,6 +239,7 @@ export async function addRoutes( ` serving, but will not start again. Caddy said:\n${said(valid)}`, ); } + owned(false); throw new CliError( `the shared Caddy does not accept its configuration with these routes, so they were removed\n` + ` again; Caddy still serves what it served. Caddy said:\n${said(valid)}`, diff --git a/manager/test/shared.test.ts b/manager/test/shared.test.ts index 486b7dd1..a56f4f97 100644 --- a/manager/test/shared.test.ts +++ b/manager/test/shared.test.ts @@ -4,7 +4,8 @@ // the real Caddy does with the routes is test/integration/shared.test.ts, and // several sites on one server tests/e2e/shared-caddy.sh. import assert from 'node:assert/strict'; -import { existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { execFileSync } from 'node:child_process'; +import { existsSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; import { afterEach, beforeEach, describe, test } from 'node:test'; import * as env from '../src/env.ts'; @@ -445,6 +446,60 @@ describe('self-update of the shared Caddy', () => { assert.ok(existsSync(join(h.dir, '.ghost-docker-update', 'files'))); }); + test('files it cannot put back are left for the operator, with Caddy not started on them', async () => { + up = () => { + // A kept file Node cannot copy back. + const kept = join(h.dir, '.ghost-docker-update', 'files', 'compose.yml'); + rmSync(kept); + execFileSync('mkfifo', [kept]); + return failed(1, 'container caddy is unhealthy'); + }; + const result = await h.run('self-update'); + assert.equal(result.code, 1); + assert.match( + result.stderr, + /files could not be put back[\s\S]*\.ghost-docker-update\/files/, + ); + assert.equal(compose.filter((args) => args[0] === 'up').length, 1); + assert.ok(existsSync(join(h.dir, '.ghost-docker-update'))); + }); + + test('a project another directory owns is refused before anything is pulled', async () => { + h.daemon.containers = [ + { + ...CADDY, + Labels: { + ...CADDY.Labels, + 'com.docker.compose.project.working_dir': '/elsewhere', + }, + }, + ]; + const result = await h.run('self-update'); + assert.equal(result.code, 1); + assert.match(result.stderr, /\/elsewhere/); + assert.deepEqual(compose, []); + assert.equal(metadata().stack.version, 'v0.1.0-beta.1'); + }); + + test('metadata changed while it was planned is refused under the lock', async () => { + const path = join(h.dir, '.ghost-docker.json'); + manager = ''; + const images = imageApi({ + manager: () => { + const changed = metadata(); + changed.stack.version = 'v0.1.0-beta.0'; + writeFileSync(path, JSON.stringify(changed)); + return SECOND; + }, + }); + const caddy = sharedApi(shared); + h.daemon.api = (request) => images(request) ?? caddy(request); + const result = await h.run('self-update'); + assert.equal(result.code, 1); + assert.match(result.stderr, /changed while this update was being prepared/); + assert.deepEqual(compose, []); + }); + test('site commands still refuse it', async () => { for (const command of ['backup', 'update', 'check']) { const result = await h.run(command); @@ -552,6 +607,8 @@ describe('a production install on a server with the shared Caddy', () => { test('routes Caddy refuses are removed with everything else the installation created', async () => { shared.refuse = 'Error: adapting config using caddyfile: ambiguous site definition'; + // Removed once, by addRoutes: the file is then not this install's to undo. + const removals = () => shared.execs.filter(({ cmd }) => cmd[0] === 'rm').length; const result = await h.run('install', '--domain', 'example.com', '--no-start'); assert.equal(result.code, 1); assert.match( @@ -560,6 +617,7 @@ describe('a production install on a server with the shared Caddy', () => { ); assert.equal(shared.sites.size, 0); assert.deepEqual(files(), []); + assert.equal(removals(), 1); }); test('a local site never joins it', async () => { From c53b2a0d97cb8540c9929f070ae9b9427360ca52 Mon Sep 17 00:00:00 2001 From: Austin Burdine Date: Mon, 2 Nov 2026 15:48:18 -0500 Subject: [PATCH 04/15] Marked each site's routes with their write, and reloaded the shared Caddy on update (S13) ref https://linear.app/ghost/issue/PLA-484 Review of #427 found two more gaps. A routes write whose result the daemon never reported, such as a timed-out exec, could have created the file, but undo only removed routes it knew it wrote, so the file was left and the next install of that project refused. And `compose up` recreates the shared Caddy only when its service changes, so a release that changed only the Caddyfile or a snippet was recorded as installed while Caddy kept serving the old configuration. - manager/src/shared.ts: each write's routes start with a marker naming a random token, which the caller is given before the write, and removeRoutes with a token removes the file only while it has that marker. - manager/src/undo.ts: the journal keeps the token, so undo removes only routes this install wrote; a journal of true still removes the file. - manager/src/commands/install.ts: records the token, or nothing once the file is certainly not this install's. - manager/src/commands/self-update.ts: Caddy reloads after `up`, and a configuration it refuses fails the update, which puts the files back and loads them again. - docs/caddy.md: the marker line, and the reload on update. - manager/test/shared.test.ts: each of these. --- docs/caddy.md | 8 +++- manager/src/commands/install.ts | 4 +- manager/src/commands/self-update.ts | 11 ++++++ manager/src/shared.ts | 57 ++++++++++++++++++++++++----- manager/src/undo.ts | 18 +++++++-- manager/test/shared.test.ts | 53 ++++++++++++++++++++++++++- 6 files changed, 132 insertions(+), 19 deletions(-) diff --git a/docs/caddy.md b/docs/caddy.md index 582af4f8..dcf98ea1 100644 --- a/docs/caddy.md +++ b/docs/caddy.md @@ -115,7 +115,9 @@ Then install each site as usual, each in its own directory. On a server with the shared Caddy, `install --domain` joins it: the site has no Caddy of its own, and its routes are written to the shared Caddy's `caddy/sites/.caddy`, which Caddy validates and loads before the -site starts. A site installed `--no-caddy` does not join it. `` is the site's `COMPOSE_PROJECT_NAME`. A domain the +site starts. Its first line, `# ghost-docker install `, names the +write, so a failed install removes the file only while it is still that +write's. A site installed `--no-caddy` does not join it. `` is the site's `COMPOSE_PROJECT_NAME`. A domain the shared Caddy already serves, or a project that already has routes there, is refused before anything is written. An existing site cannot be moved behind the shared Caddy yet; it keeps its own Caddy, which needs 80 and 443, so set @@ -183,7 +185,9 @@ Its Caddy image is pinned in its `compose.yml`, by the release it runs. `./ghost-docker self-update`, in its directory, moves it to a newer release as for a site: untouched stack files are replaced, edited ones kept beside the release's `.new`, and the launcher re-pinned; then Caddy is recreated, which -restarts it as above, and must pass its health check. There is no backup, +restarts it as above, reloads its configuration (so a changed Caddyfile or +snippet is loaded even when the container was not recreated), and must pass +its health check. There is no backup, because it holds no data. A failed update puts its files back and starts the previous Caddy again. It never updates the sites behind it, and their own `self-update` never touches it. diff --git a/manager/src/commands/install.ts b/manager/src/commands/install.ts index bc6fa179..ed56d4ae 100644 --- a/manager/src/commands/install.ts +++ b/manager/src/commands/install.ts @@ -816,8 +816,8 @@ async function writeSiteRoutes( if (shared !== null) { // Claimed once written: a file another installation wrote is refused, never removed. await io.busy('Adding the routes to the shared Caddy', () => - addRoutes(io, shared, project, renderRoutes(routes), (owned) => { - created.routes = owned; + addRoutes(io, shared, project, renderRoutes(routes), (token) => { + created.routes = token ?? false; created.save(); }), ); diff --git a/manager/src/commands/self-update.ts b/manager/src/commands/self-update.ts index 7c10b3f5..3341ad5b 100644 --- a/manager/src/commands/self-update.ts +++ b/manager/src/commands/self-update.ts @@ -544,6 +544,17 @@ async function updateInfra( /** `up --wait`, and Caddy healthy by its own check. */ async function caddyUp(io: Io, dir: string, spinner: string): Promise { await upAndWait(io, dir, spinner); + // `up` recreates Caddy only when its service changed; a Caddyfile or + // snippet it mounts is loaded only by a reload. + const reload = await io.busy( + 'Loading the configuration', + () => compose(io, { dir })`exec -T caddy caddy reload --config /etc/caddy/Caddyfile`, + ); + if (reload.exitCode !== 0) { + throw new CliError( + `Caddy did not load its configuration, and keeps serving the one it had: ${composeError(reload)}`, + ); + } const caddy = (await composePs(io, dir))?.find((state) => state.Service === 'caddy'); if (caddy?.Health !== 'healthy') { throw new CliError('Caddy started, but it is not healthy'); diff --git a/manager/src/shared.ts b/manager/src/shared.ts index 9f788922..710caf53 100644 --- a/manager/src/shared.ts +++ b/manager/src/shared.ts @@ -10,6 +10,7 @@ // the site's project. The manager cannot see that directory, only its own // site's, so it reads and writes it through the running Caddy container, which // mounts it: what is written is exactly what Caddy reads. See docs/caddy.md. +import { randomUUID } from 'node:crypto'; import { CliError } from './errors.ts'; import { execInContainer, @@ -187,20 +188,30 @@ export async function refuseTaken( } } +/** + * The first line of routes an installation wrote: which write they are, so + * undoing it removes them only while they are still that write's. + */ +export const routesMarker = (token: string): string => `# ghost-docker install ${token}`; + /** * Writes a site's routes into the shared Caddy, owned by whoever owns its * caddy/sites/, has Caddy validate its whole configuration with them, and * reloads it. Routes Caddy refuses are removed again, and Caddy keeps serving - * what it served. `owned` says whether the file is this call's to undo: true - * once written, as an existing one is never replaced, and false again once - * the routes Caddy refused are removed, since another site may then add its own. + * what it served. + * + * `owned` is told the token of the write before it is made, since a write + * whose result is unknown may have happened, and null once the file is + * certainly not this write's: an existing one is never replaced, and routes + * Caddy refused are removed. Undo then removes the file only if it is still + * marked with that token (removeRoutes). */ export async function addRoutes( io: Io, shared: SharedCaddy, project: string, routes: string, - owned: (yes: boolean) => void = () => undefined, + owned: (token: string | null) => void = () => undefined, ): Promise { const caddy = runningCaddy(shared); const owner = await inCaddy(io, caddy, ['stat', '-c', '%u:%g', SITES]); @@ -208,6 +219,8 @@ export async function addRoutes( throw new CliError(`the shared Caddy's ${SITES} could not be read:\n${said(owner)}`); } const file = `${SITES}/${routesFile(project)}`; + const token = randomUUID(); + owned(token); // Written beside it under a name of this writer's that the Caddyfile's // *.caddy does not import, then linked into place: a link, unlike a // rename, fails when the file exists, so another site's is never replaced @@ -220,15 +233,18 @@ export async function addRoutes( '-c', 'umask 022 && t="$2.$$.new" && printf "%s" "$1" > "$t" && ln "$t" "$2"; s=$?; rm -f "$t"; exit $s', 'sh', - routes, + `${routesMarker(token)}\n${routes}`, file, ], owner.stdout.trim(), ); if (write.status !== 0) { + // A status means it did not happen; none, that it may have. + if (write.status !== null) { + owned(null); + } throw new CliError(`the routes could not be written to the shared Caddy:\n${said(write)}`); } - owned(true); const valid = await inCaddy(io, caddy, ['caddy', 'validate', '--config', CADDYFILE]); if (valid.status !== 0) { const removed = await inCaddy(io, caddy, ['rm', '-f', file], owner.stdout.trim()); @@ -239,7 +255,7 @@ export async function addRoutes( ` serving, but will not start again. Caddy said:\n${said(valid)}`, ); } - owned(false); + owned(null); throw new CliError( `the shared Caddy does not accept its configuration with these routes, so they were removed\n` + ` again; Caddy still serves what it served. Caddy said:\n${said(valid)}`, @@ -250,11 +266,32 @@ export async function addRoutes( /** * Removes a site's routes from the shared Caddy and reloads it. Routes - * that are already gone are not an error. + * that are already gone are not an error. With a token, only routes that + * write made (routesMarker) are removed: undoing an install never takes + * another's. */ -export async function removeRoutes(io: Io, shared: SharedCaddy, project: string): Promise { +export async function removeRoutes( + io: Io, + shared: SharedCaddy, + project: string, + token?: string, +): Promise { const caddy = runningCaddy(shared); - const removed = await inCaddy(io, caddy, ['rm', '-f', `${SITES}/${routesFile(project)}`]); + const file = `${SITES}/${routesFile(project)}`; + const removed = await inCaddy( + io, + caddy, + token === undefined + ? ['rm', '-f', file] + : [ + 'sh', + '-c', + 'if head -n 1 "$2" 2>/dev/null | grep -qxF "$1"; then rm -f "$2"; fi', + 'sh', + routesMarker(token), + file, + ], + ); if (removed.status !== 0) { throw new CliError( `${routesPath(shared, project)} could not be removed:\n${said(removed)}`, diff --git a/manager/src/undo.ts b/manager/src/undo.ts index bb714348..052a5249 100644 --- a/manager/src/undo.ts +++ b/manager/src/undo.ts @@ -22,7 +22,8 @@ const journalSchema = z.object({ directories: z.array(z.string().startsWith('/')), data: z.array(z.string().startsWith('/')), project: z.boolean(), - routes: z.boolean().default(false), + // A write's token (shared.ts routesMarker), or true for whatever is there. + routes: z.union([z.string(), z.boolean()]).default(false), }); export class Created implements Written { @@ -33,8 +34,12 @@ export class Created implements Written { readonly data: string[] = []; /** Compose has created something for this project: a network, containers, volumes. */ project = false; - /** The site's routes are in the shared Caddy, named for its project (shared.ts). */ - routes = false; + /** + * The site's routes in the shared Caddy, named for its project + * (shared.ts): the token of the write that may have made them, or true + * for whatever file is there. + */ + routes: string | boolean = false; /** The shared Caddy's network, created by `install --infra`. */ network: string | null = null; /** The import marker, when this is an import. */ @@ -158,7 +163,12 @@ export class Created implements Written { if (shared === null) { return []; } - await removeRoutes(this.io, shared, project); + await removeRoutes( + this.io, + shared, + project, + typeof this.routes === 'string' ? this.routes : undefined, + ); return []; } catch (error) { const path = diff --git a/manager/test/shared.test.ts b/manager/test/shared.test.ts index a56f4f97..d135d2fc 100644 --- a/manager/test/shared.test.ts +++ b/manager/test/shared.test.ts @@ -35,6 +35,8 @@ interface FakeShared { exists: boolean; /** Another installation, creating the network or a routes file first. */ raced: { network?: boolean; routes?: string }; + /** A routes write that runs, but whose result the daemon never reports. */ + lost: boolean; } function fakeShared(): FakeShared { @@ -47,6 +49,7 @@ function fakeShared(): FakeShared { created: null, exists: true, raced: {}, + lost: false, }; } @@ -112,6 +115,9 @@ function sharedApi(shared: FakeShared) { if (path === '/exec/exec-1/start') { const { stdout, code } = run(shared, pending!); status = code; + if (shared.lost && pending!.cmd[0] === 'sh' && !pending!.cmd[2]!.includes('grep')) { + return { status: 500, body: Buffer.from('connection reset') }; + } return { status: 200, body: frame(code === 0 ? 1 : 2, stdout) }; } if (path === '/exec/exec-1/json') { @@ -140,6 +146,13 @@ function run(shared: FakeShared, { cmd }: { cmd: string[] }): { stdout: string; case 'stat': return { stdout: '1000:1000\n', code: 0 }; case 'sh': { + // sh -c SCRIPT sh MARKER FILE: removes the file if it is that write's. + if (cmd[2]!.includes('grep')) { + if (shared.sites.get(name(cmd[5]!))?.split('\n')[0] === cmd[4]) { + shared.sites.delete(name(cmd[5]!)); + } + return { stdout: '', code: 0 }; + } // sh -c SCRIPT sh ROUTES FILE, which never overwrites a file. if (shared.raced.routes !== undefined) { shared.sites.set(name(cmd[5]!), shared.raced.routes); @@ -388,7 +401,7 @@ describe('self-update of the shared Caddy', () => { assert.equal(after.stack.version, 'v0.1.0-beta.2'); assert.deepEqual( compose.map((args) => args[0]), - ['config', 'pull', 'up', 'ps'], + ['config', 'pull', 'up', 'exec', 'ps'], ); assert.ok(!existsSync(join(h.dir, 'backups'))); assert.ok(!existsSync(join(h.dir, '.ghost-docker-update'))); @@ -438,6 +451,27 @@ describe('self-update of the shared Caddy', () => { assert.ok(!existsSync(join(h.dir, '.ghost-docker.lock'))); }); + test('a configuration Caddy will not reload is put back, and the old one loaded again', async () => { + const before = readFileSync(join(h.dir, 'caddy', 'snippets', 'Logging'), 'utf8'); + let reloads = 0; + h.daemon.composeRun = (args) => { + compose.push(args); + if (args[0] === 'exec') { + return reloads++ === 0 ? failed(1, 'adapting config: unknown directive') : ok(''); + } + if (args[0] === 'config') { + return ok(JSON.stringify({ services: { caddy: {} } })); + } + return args[0] === 'ps' ? ok(ps()) : ok(''); + }; + const result = await h.run('self-update'); + assert.equal(result.code, 1); + assert.match(result.stderr, /did not load its configuration[\s\S]*unknown directive/); + assert.match(result.stderr, /is back on v0\.1\.0-beta\.1, and running/); + assert.equal(readFileSync(join(h.dir, 'caddy', 'snippets', 'Logging'), 'utf8'), before); + assert.equal(reloads, 2); + }); + test('a Caddy that will not start again either is left for the operator, with the files kept', async () => { up = () => failed(1, 'Bind for 0.0.0.0:443 failed'); const result = await h.run('self-update'); @@ -594,6 +628,23 @@ describe('a production install on a server with the shared Caddy', () => { assert.deepEqual(files(), []); }); + test('routes written with no result reported are still undone, by their marker', async () => { + shared.lost = true; + const result = await h.run('install', '--domain', 'example.com', '--no-start'); + assert.equal(result.code, 1); + assert.match(result.stderr, /could not be written to the shared Caddy/); + assert.equal(shared.sites.size, 0); + assert.deepEqual(files(), []); + }); + + test("another's routes are left alone when a write's result is unknown", async () => { + shared.lost = true; + shared.raced.routes = 'routes of another directory'; + const result = await h.run('install', '--domain', 'example.com', '--no-start'); + assert.equal(result.code, 1); + assert.equal(shared.sites.get('ghost-example-com.caddy'), 'routes of another directory'); + }); + test('a stopped shared Caddy is refused, saying how to start it', async () => { h.daemon.containers = [{ ...CADDY, State: 'exited' }]; const result = await h.run('install', '--domain', 'example.com', '--no-start'); From 38b50eec32e5da9b55a1004aa2a4e72b7c92ed28 Mon Sep 17 00:00:00 2001 From: Austin Burdine Date: Mon, 2 Nov 2026 16:28:27 -0500 Subject: [PATCH 05/15] Serialized the shared Caddy's reloads with the sites' route changes (S13) ref https://linear.app/ghost/issue/PLA-484 `caddy reload` reads the configuration, routes included, then loads it. A shared-Caddy self-update reloading while a site was installed could read before the site's routes were written and load after the site's own reload, dropping them from the running Caddy after install had reported success. The managers involved see none of each other's directories, so the lock is taken inside the container: every reload runs under flock on /etc/caddy/sites, which busybox flock can lock as a directory, so no lock file is left in the operator's directory. - manager/src/shared.ts: RELOAD, the serialized reload, for route changes. - manager/src/commands/self-update.ts: the shared Caddy's reload uses it. - docs/caddy.md: reloads take turns. - manager/test/shared.test.ts: both reloads go through the lock. --- docs/caddy.md | 4 +++- manager/src/commands/self-update.ts | 4 +++- manager/src/shared.ts | 15 +++++++++++++-- manager/test/shared.test.ts | 23 +++++++++++++++++++++-- 4 files changed, 40 insertions(+), 6 deletions(-) diff --git a/docs/caddy.md b/docs/caddy.md index dcf98ea1..0056d0c6 100644 --- a/docs/caddy.md +++ b/docs/caddy.md @@ -187,7 +187,9 @@ for a site: untouched stack files are replaced, edited ones kept beside the release's `.new`, and the launcher re-pinned; then Caddy is recreated, which restarts it as above, reloads its configuration (so a changed Caddyfile or snippet is loaded even when the container was not recreated), and must pass -its health check. There is no backup, +its health check. Its reloads and those of each site's `install` and `remove` +take turns, through a lock on `caddy/sites/` inside the container, so none +loads a configuration read before another site's routes were written. There is no backup, because it holds no data. A failed update puts its files back and starts the previous Caddy again. It never updates the sites behind it, and their own `self-update` never touches it. diff --git a/manager/src/commands/self-update.ts b/manager/src/commands/self-update.ts index 3341ad5b..7b538fd3 100644 --- a/manager/src/commands/self-update.ts +++ b/manager/src/commands/self-update.ts @@ -19,6 +19,7 @@ import { requireValid } from '../config.ts'; import type { Context } from '../context.ts'; import { CliError, describeError, EXIT, UsageError } from '../errors.ts'; import { refuseForeignProject } from '../project.ts'; +import { RELOAD } from '../shared.ts'; import { atomicWrite } from '../fs.ts'; import type { Io } from '../io.ts'; import { isReleasedMainLayout, migrateReleasedMain } from '../legacy.ts'; @@ -548,7 +549,8 @@ async function caddyUp(io: Io, dir: string, spinner: string): Promise { // snippet it mounts is loaded only by a reload. const reload = await io.busy( 'Loading the configuration', - () => compose(io, { dir })`exec -T caddy caddy reload --config /etc/caddy/Caddyfile`, + // One at a time with the sites' route changes (shared.ts RELOAD). + () => compose(io, { dir })`exec -T caddy ${[...RELOAD]}`, ); if (reload.exitCode !== 0) { throw new CliError( diff --git a/manager/src/shared.ts b/manager/src/shared.ts index 710caf53..5a2801ef 100644 --- a/manager/src/shared.ts +++ b/manager/src/shared.ts @@ -32,10 +32,21 @@ export const SERVICE_LABEL = 'com.docker.compose.service'; /** The default project name of the shared Caddy. */ export const INFRA_PROJECT = 'ghost-infra'; -/** Where the shared Caddy container mounts the members' routes. */ +/** Where the shared Caddy container mounts the sites' routes. */ const SITES = '/etc/caddy/sites'; const CADDYFILE = '/etc/caddy/Caddyfile'; +/** + * `caddy reload` in the shared Caddy's container, one at a time. A reload + * reads the configuration, routes included, then loads it: a reload that read + * before another site's routes were written, and loaded after that site's own + * reload, would drop them from the running Caddy. Each site's manager and the + * shared Caddy's self-update see none of each other's directories, so the + * lock is taken in the container, on the sites' directory itself (busybox + * flock locks a directory), which leaves no file behind. + */ +export const RELOAD = ['flock', SITES, 'caddy', 'reload', '--config', CADDYFILE] as const; + export interface SharedCaddy { readonly network: string; /** The shared Caddy's directory on the host. */ @@ -306,7 +317,7 @@ export async function removeRoutes( */ export async function reloadCaddy(io: Io, shared: SharedCaddy): Promise { const caddy = runningCaddy(shared); - const reloaded = await inCaddy(io, caddy, ['caddy', 'reload', '--config', CADDYFILE]); + const reloaded = await inCaddy(io, caddy, RELOAD); if (reloaded.status !== 0) { throw new CliError( `the shared Caddy did not load its configuration, and keeps serving the one it had.\n` + diff --git a/manager/test/shared.test.ts b/manager/test/shared.test.ts index d135d2fc..568e4527 100644 --- a/manager/test/shared.test.ts +++ b/manager/test/shared.test.ts @@ -131,6 +131,10 @@ function sharedApi(shared: FakeShared) { function run(shared: FakeShared, { cmd }: { cmd: string[] }): { stdout: string; code: number } { const name = (path: string) => path.replace('/etc/caddy/sites/', ''); switch (cmd[0]) { + case 'flock': + // Reloads are serialized on the sites' directory. + assert.equal(cmd[1], '/etc/caddy/sites'); + return run(shared, { cmd: cmd.slice(2) }); case 'wget': { const routes = [...shared.hosts].map((host) => ({ match: [{ host: [host] }] })); return { @@ -403,6 +407,21 @@ describe('self-update of the shared Caddy', () => { compose.map((args) => args[0]), ['config', 'pull', 'up', 'exec', 'ps'], ); + // Serialized with the sites' route changes. + assert.deepEqual( + compose.find((args) => args[0] === 'exec'), + [ + 'exec', + '-T', + 'caddy', + 'flock', + '/etc/caddy/sites', + 'caddy', + 'reload', + '--config', + '/etc/caddy/Caddyfile', + ], + ); assert.ok(!existsSync(join(h.dir, 'backups'))); assert.ok(!existsSync(join(h.dir, '.ghost-docker-update'))); assert.ok(!existsSync(join(h.dir, '.ghost-docker.lock'))); @@ -573,7 +592,7 @@ describe('a production install on a server with the shared Caddy', () => { 'stat -c', 'sh -c as 1000:1000', 'caddy validate', - 'caddy reload', + 'flock /etc/caddy/sites', ]); assert.ok(shared.hosts.has('example.com')); const metadata = JSON.parse(readFileSync(join(h.dir, '.ghost-docker.json'), 'utf8')); @@ -734,7 +753,7 @@ describe('remove', () => { const result = await h.run('remove', '--yes'); assert.equal(result.code, 0, result.stderr); assert.deepEqual([...shared.sites.keys()], ['ghost-other-com.caddy']); - assert.deepEqual(shared.execs.map(({ cmd }) => cmd[0]).slice(-2), ['rm', 'caddy']); + assert.deepEqual(shared.execs.map(({ cmd }) => cmd[0]).slice(-2), ['rm', 'flock']); assert.ok(compose.some((args) => args[0] === 'down' && !args.includes('--volumes'))); assert.ok(existsSync(join(h.dir, '.env')), 'the directory and its data stay'); assert.match(result.stdout, /still holds its configuration, data and backups/); From 6b501e0cd5d9cc524920bc86da947904575aa64e Mon Sep 17 00:00:00 2001 From: Austin Burdine Date: Wed, 4 Nov 2026 10:55:24 -0500 Subject: [PATCH 06/15] Fixed the shared Caddy's update rollback, and required URL for local sites (S13) A site's install or remove reloads the shared Caddy from its directory's files at any moment, so files an update wrote could be loaded while its images were still pulling; a failure then put the files back but left Caddy serving the new configuration. The release's images are now pulled from its compose.yml before any file is written, and a failure after the write reloads the files put back even when Caddy was never recreated. compose.yml no longer guards URL, and validation required it only for production, so a local site without one resolved Ghost's url to empty. --- manager/src/commands/self-update.ts | 66 +++++++++++++++++++---------- manager/src/config.ts | 4 +- manager/test/config.test.ts | 5 ++- 3 files changed, 48 insertions(+), 27 deletions(-) diff --git a/manager/src/commands/self-update.ts b/manager/src/commands/self-update.ts index 7b538fd3..398775da 100644 --- a/manager/src/commands/self-update.ts +++ b/manager/src/commands/self-update.ts @@ -471,6 +471,25 @@ async function updateInfra( io.stdout( `Updating the shared Caddy from ${describeStack(from)} to ${describeStack(to)}\n`, ); + // Before any file is written: a site's install or remove reloads the + // shared Caddy from this directory's files at any moment, so a written + // file is live from then on, and a failure after it needs a reload. + heading(io, 'Pulling the release’s images'); + const pull = await io.busy( + 'Pulling the images this release names', + () => + compose(io, { + dir, + composeFile: join(stack, COMPOSE_FILE), + timeout: PULL_MS, + })`pull --quiet --ignore-buildable`, + ); + if (pull.exitCode !== 0) { + throw new CliError( + `the images could not be pulled: ${composeError(pull)}. Nothing has been changed.`, + ); + } + ok(io, 'images', 'pulled, while Caddy kept running'); heading(io, 'Keeping the current files'); // Not the sites' routes: the update never writes them, and a site // installed meanwhile adds its own, which putting files back would lose. @@ -485,13 +504,6 @@ async function updateInfra( heading(io, 'Writing the stack'); writePayloadChanges(io, dir, stack, payload); await requireValid(io, dir, 'this release'); - const pull = await io.busy( - 'Pulling the images this release names', - () => compose(io, { dir, timeout: PULL_MS })`pull --quiet --ignore-buildable`, - ); - if (pull.exitCode !== 0) { - throw new CliError(`the images could not be pulled: ${composeError(pull)}`); - } heading(io, 'Restarting the shared Caddy'); started = true; await caddyUp( @@ -514,21 +526,26 @@ async function updateInfra( (started ? ' Caddy may be stopped until then.' : ''), ); } - if (started) { - try { + try { + if (started) { await caddyUp(io, dir, `Starting ${describeStack(from)}'s Caddy again`); - } catch (again) { - throw new CliError( - `the files are ${describeStack(from)}'s again, but Caddy did not start on them: ${describeError(again)}\n` + - ' Every site behind it is unreachable until it does: docker compose up -d, and\n' + - ` docker compose logs caddy, in ${dir}. The files as they were are in ${UPDATE_DIR}/files;\n` + - ` remove ${UPDATE_DIR} once Caddy runs.`, - ); + } else { + // Never restarted, but a site's reload may have loaded the + // written files: load the ones put back. + await reloadCaddy(io, dir); } + } catch (again) { + throw new CliError( + `the files are ${describeStack(from)}'s again, but Caddy did not ${started ? 'start on' : 'load'} them: ${describeError(again)}\n` + + ' Sites behind it may be unreachable, or served by the release that failed, until it\n' + + ` does: docker compose up -d, then docker compose exec caddy ${RELOAD.join(' ')},\n` + + ` and docker compose logs caddy, in ${dir}. The files as they were are in ${UPDATE_DIR}/files;\n` + + ` remove ${UPDATE_DIR} once Caddy runs on them.`, + ); } snapshot.remove(); throw new CliError( - `the update failed; the shared Caddy is back on ${describeStack(from)}${started ? ', and running' : ', and was never stopped'}.`, + `the update failed; the shared Caddy is back on ${describeStack(from)}${started ? ', and running' : ', with its configuration loaded again'}.`, ); } snapshot.remove(); @@ -547,6 +564,16 @@ async function caddyUp(io: Io, dir: string, spinner: string): Promise { await upAndWait(io, dir, spinner); // `up` recreates Caddy only when its service changed; a Caddyfile or // snippet it mounts is loaded only by a reload. + await reloadCaddy(io, dir); + const caddy = (await composePs(io, dir))?.find((state) => state.Service === 'caddy'); + if (caddy?.Health !== 'healthy') { + throw new CliError('Caddy started, but it is not healthy'); + } + ok(io, 'caddy', 'healthy: its admin API answers, with its configuration loaded'); +} + +/** The running Caddy's configuration loaded from the directory's files. */ +async function reloadCaddy(io: Io, dir: string): Promise { const reload = await io.busy( 'Loading the configuration', // One at a time with the sites' route changes (shared.ts RELOAD). @@ -557,11 +584,6 @@ async function caddyUp(io: Io, dir: string, spinner: string): Promise { `Caddy did not load its configuration, and keeps serving the one it had: ${composeError(reload)}`, ); } - const caddy = (await composePs(io, dir))?.find((state) => state.Service === 'caddy'); - if (caddy?.Health !== 'healthy') { - throw new CliError('Caddy started, but it is not healthy'); - } - ok(io, 'caddy', 'healthy: its admin API answers, with its configuration loaded'); } /** --check: what an update would do, changing nothing. */ diff --git a/manager/src/config.ts b/manager/src/config.ts index 9a97593b..d2df7432 100644 --- a/manager/src/config.ts +++ b/manager/src/config.ts @@ -39,8 +39,7 @@ export interface Finding { export const REQUIRED_KEYS = { common: ['COMPOSE_PROFILES', 'COMPOSE_PROJECT_NAME', 'SITE_MODE', 'PROJECT_DIR'], /** compose.yml does not `:?`-guard these: the shared Caddy's directory has none. */ - site: ['GHOST_VERSION', 'DATABASE_PASSWORD', 'DATABASE_ROOT_PASSWORD'], - production: ['URL'], + site: ['GHOST_VERSION', 'URL', 'DATABASE_PASSWORD', 'DATABASE_ROOT_PASSWORD'], /** Behind the shared Caddy, and in its own directory. */ shared: ['INGRESS_NETWORK'], } as const; @@ -144,7 +143,6 @@ export async function validateEnv(io: Io, dir: string): Promise { const required = [ ...REQUIRED_KEYS.common, ...REQUIRED_KEYS.site, - ...(mode === 'production' ? REQUIRED_KEYS.production : []), ...(behindSharedCaddy ? REQUIRED_KEYS.shared : []), ]; for (const key of required) { diff --git a/manager/test/config.test.ts b/manager/test/config.test.ts index 1a41e2c5..21d0cdf0 100644 --- a/manager/test/config.test.ts +++ b/manager/test/config.test.ts @@ -143,10 +143,11 @@ describe('.env', () => { assert.match(result.errors, /warning .*mode is 0644; it holds credentials/); }); - test('Compose guards URL itself, so validation does not list it twice', async () => { + test('a local site needs URL too: compose.yml no longer guards it', async () => { makeSite(h, { ...LOCAL, URL: undefined }); const result = await validate(); - assert.doesNotMatch(result.errors, /\.env +URL is required/); + assert.equal(result.code, 1); + assert.match(result.errors, /URL is required for mode local/); }); }); From f3eaa60f3d18cdd598cf0c9fa7684fd5861800cd Mon Sep 17 00:00:00 2001 From: Austin Burdine Date: Wed, 4 Nov 2026 10:55:25 -0500 Subject: [PATCH 07/15] Kept a site's shared-Caddy routes in its backup, and restored them (S13) PLA-484 leaves backup and restore unchanged for a site behind the shared Caddy, but its routes are the shared Caddy's files, so a backup left them out and a restore needed them in place: a removed site, or one moved to a new server, could not be brought back from its backup alone. A backup now reads the routes through the shared Caddy and keeps them as routes.caddy, without the install's marker line; when they cannot be read it warns and says so in notIncluded. A restore keeps routes the shared Caddy already has for the project, and otherwise writes the backup's, refusing domains it already serves. The shared Caddy's own directory still has no backup: it holds no data, and install --infra sets it up again. --- docs/architecture.md | 3 +- docs/caddy.md | 16 ++- docs/reference.md | 13 +- manager/src/backup.ts | 49 ++++++- manager/src/backup/manifest.ts | 9 ++ manager/src/restore.ts | 75 ++++++++-- manager/src/shared.ts | 25 ++++ manager/test/backup.test.ts | 96 +++++++++++++ manager/test/shared-caddy.ts | 187 ++++++++++++++++++++++++ manager/test/shared.test.ts | 253 ++++++++++----------------------- tests/e2e/shared-caddy.sh | 22 ++- 11 files changed, 538 insertions(+), 210 deletions(-) create mode 100644 manager/test/shared-caddy.ts diff --git a/docs/architecture.md b/docs/architecture.md index 656b508d..8b3db562 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -138,7 +138,8 @@ owner; Caddy validates the whole configuration before it is reloaded, and routes it refuses are removed. Duplicate domains (from Caddy's loaded configuration) and projects (a routes file of that name) are refused before any write. `remove` and a failed install's undo take a site's routes out -again. A backup does not hold them: they are the shared Caddy's. +again. A site's backup holds a copy (`routes.caddy`), which a restore writes +back when the shared Caddy has none for the project. `src/bundle/manifest.ts` defines the migration bundle schema and depends only on zod so the exporter can share it. Import policy stays outside that schema. diff --git a/docs/caddy.md b/docs/caddy.md index 0056d0c6..304ce261 100644 --- a/docs/caddy.md +++ b/docs/caddy.md @@ -144,8 +144,13 @@ and each site behind it as `shared-caddy`. `./ghost-docker remove`, in a site's directory, removes its routes file, reloads the shared Caddy, and takes the site's containers down; no other site is touched. The site's directory, data and backups stay until you delete them. -A backup does not hold a site's routes, which are the shared Caddy's files: -restoring a site behind it needs them in place, and says so when they are not. +A site's backup holds its routes, read from the shared Caddy. Restoring it +keeps the routes the shared Caddy has for the project, since they may have +been edited since, and otherwise writes the backup's back: a site removed, or +moved to a new server with a shared Caddy of its own, comes back with them. +The shared Caddy's own directory has no backup; it holds no data, and +`install --infra` sets it up again, with your edits to its Caddyfile and +snippets yours to keep. ### How it is connected @@ -190,8 +195,11 @@ snippet is loaded even when the container was not recreated), and must pass its health check. Its reloads and those of each site's `install` and `remove` take turns, through a lock on `caddy/sites/` inside the container, so none loads a configuration read before another site's routes were written. There is no backup, -because it holds no data. A failed update puts its files back and starts the -previous Caddy again. It never updates the sites behind it, and their own +because it holds no data. The release's images are pulled before any file is +written, so one that cannot be pulled changes nothing. Once files are written, +a site's reload can load them, so a failed update puts its files back and +reloads them into Caddy, or starts the previous Caddy again when it had been +recreated. It never updates the sites behind it, and their own `self-update` never touches it. ### Capacity diff --git a/docs/reference.md b/docs/reference.md index ff3c8afd..e31c51aa 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -402,6 +402,7 @@ self-update. Compose files you used with `-f` by hand, such as | `database/ghost.sql` | A `mysqldump` of Ghost's database, taken as the site's own database user in one consistent snapshot. | | `database/activitypub.sql` | ActivityPub's database, when the `activitypub` profile is on. | | `content.tar.gz` | The content directory, `data/ghost`: images, media, files, themes, settings. | +| `routes.caddy` | Behind the shared Caddy: the site's routes, its `caddy/sites/.caddy` there, without the marker line its install wrote. When the shared Caddy cannot be read, the backup warns and holds none. | | `site/` | `.env`, `ghost.env`, `.ghost-docker.json`, `compose.override.yml` and the overrides `COMPOSE_FILE` names, `caddy/sites/`, `caddy/custom/`, `caddy/global/` and, for a site installed from the image, the stack's files and the launcher the site ran. | A backup is **checked** before it counts as one: every dump is loaded into a @@ -413,8 +414,9 @@ is an error, not a backup:** `backup` exits `1` and leaves nothing in `backups/`. What a backup cannot hold is named in its manifest and in the summary: -Caddy's certificates, which Caddy obtains again when the site starts; the -Tinybird workspace and analytics data outside the site; Mailpit's inbox. +Caddy's certificates, which Caddy obtains again when the site starts (behind +the shared Caddy, its own configuration and certificates); the Tinybird +workspace and analytics data outside the site; Mailpit's inbox. ### What a backup captures @@ -485,7 +487,10 @@ In order: project and busy ports are refused, named, and never stopped. The backup's configuration (for a clone, with the clone's `compose.yml`) is resolved outside the site, and must name exactly the images the backup - records and mount the data where restore loads it. Nothing has changed. + records and mount the data where restore loads it. Behind the shared + Caddy, it must be running; routes it already has for the project are kept, + and otherwise the backup must hold them, for domains it does not already + serve. Nothing has changed. 2. **The lock**, then every image the backup records is pulled before anything stops, and each service that was running must get, by its image ID or a registry digest, the very image it ran. A reference that names another @@ -505,6 +510,8 @@ In order: 5. **The databases.** MySQL starts on an empty data directory, which creates the site's databases and user from the restored `.env`; each dump is loaded as the site's user, and every table's rows must match the manifest. + Behind the shared Caddy, the backup's routes, when it has none for the + project, are written into it, validated and loaded, as an install's are. 6. **Start and verify.** `up --wait`, then the site is verified through its ingress as `check` does. `.ghost-docker-restore/` is removed. diff --git a/manager/src/backup.ts b/manager/src/backup.ts index 1b176234..b973b4e9 100644 --- a/manager/src/backup.ts +++ b/manager/src/backup.ts @@ -23,12 +23,14 @@ import { DATABASE_NAME, MANIFEST_FILE, readBackupManifest, + ROUTES_FILE, SITE_FILES_DIR, type BackupManifest, } from './backup/manifest.ts'; import { compose, composeError, composeOverrides, composePs, composeUp } from './compose.ts'; import { runOnce } from './docker/client.ts'; -import { CliError } from './errors.ts'; +import { CliError, describeError } from './errors.ts'; +import { describeShared, findSharedCaddy, readRoutes, routesPath } from './shared.ts'; import { WriterPause } from './writers.ts'; import { atomicWrite, copyPresent, filesUnder, PRIVATE } from './fs.ts'; import { DATABASE_MS, tableCount, withSiteDatabase } from './import/database.ts'; @@ -177,13 +179,47 @@ export function siteOverrides(resolved: ResolvedSite): string[] { }); } +/** + * Behind the shared Caddy, the site's routes, copied into the backup so a + * restore can write them back. They are the shared Caddy's files, read + * through its container; one that cannot be read leaves the backup without + * them, with a warning, rather than failing it. + */ +async function captureRoutes(io: Io, project: string, partial: string): Promise { + try { + const shared = await findSharedCaddy(io); + if (shared === null) { + warn(io, 'routes', 'this server has no shared Caddy, so the backup holds no routes'); + return false; + } + const routes = await readRoutes(io, shared, project); + if (routes === null) { + warn( + io, + 'routes', + `${routesPath(shared, project)} does not exist, so the backup holds no routes`, + ); + return false; + } + atomicWrite(join(partial, ROUTES_FILE), routes, PRIVATE); + ok(io, 'routes', `${routesPath(shared, project)}, from ${describeShared(shared)}`); + return true; + } catch (failure) { + warn(io, 'routes', `${describeError(failure)}\n The backup holds no routes.`); + return false; + } +} + /** What the site has that a backup cannot hold, for the manifest and the summary. */ -function notIncluded(site: SiteFacts): string[] { +function notIncluded(site: SiteFacts, routes: boolean): string[] { const profiles = site.settings.get('COMPOSE_PROFILES') ?? ''; const lines: string[] = []; if (site.layout === SHARED_CADDY_PROFILE) { + if (!routes) { + lines.push("its routes, which could not be read from the shared Caddy's caddy/sites/"); + } lines.push( - "its routes, in the shared Caddy's caddy/sites/, which are the shared Caddy's files, with its certificates", + "the shared Caddy's own configuration and its certificates, which are not the site's", ); } else if (site.layout === 'production') { lines.push( @@ -477,6 +513,10 @@ export async function takeBackup({ `${copied} files and directories: configuration, metadata, Caddy${overrides.length > 0 ? `, ${overrides.join(', ')}` : ''}`, ); + const routes = + site.layout === SHARED_CADDY_PROFILE && + (await captureRoutes(io, metadata.site.project, partial)); + // Captured: the site runs again before the slower checks, unless the // caller keeps it paused. await resume(); @@ -562,8 +602,9 @@ export async function takeBackup({ running: ran, databases: manifestDatabases, content: { file: CONTENT_ARCHIVE, entries }, + ...(routes ? { routes: ROUTES_FILE } : {}), files, - notIncluded: notIncluded(site), + notIncluded: notIncluded(site, routes), }; atomicWrite( join(partial, MANIFEST_FILE), diff --git a/manager/src/backup/manifest.ts b/manager/src/backup/manifest.ts index a04ba748..f6799de2 100644 --- a/manager/src/backup/manifest.ts +++ b/manager/src/backup/manifest.ts @@ -6,6 +6,9 @@ import { readIfExists } from '../fs.ts'; export const BACKUP_FORMAT = 'ghost-docker-backup'; export const BACKUP_VERSION = 1; + +/** Behind the shared Caddy, the site's routes, in the backup (manifest `routes`). */ +export const ROUTES_FILE = 'routes.caddy'; export const MANIFEST_FILE = 'manifest.json'; /** The content directory, as a gzipped tarball of its contents. */ export const CONTENT_ARCHIVE = 'content.tar.gz'; @@ -85,6 +88,12 @@ export const backupManifestSchema = z.strictObject({ file: inside, entries: z.number().int().nonnegative(), }), + /** + * Behind the shared Caddy: the site's routes, as its caddy/sites/.caddy + * held them, without the marker line its install wrote. A restore writes + * them back when the shared Caddy has none for the project. + */ + routes: inside.optional(), /** SHA-256 of every file in the backup but this one, by path. */ files: z.record(inside, z.string().regex(/^[0-9a-f]{64}$/)), /** What the site has that this backup does not, for a person to read. */ diff --git a/manager/src/restore.ts b/manager/src/restore.ts index 266e80c3..728c74e6 100644 --- a/manager/src/restore.ts +++ b/manager/src/restore.ts @@ -1,7 +1,15 @@ // Restore validates the inputs it will write before replacing the site. // After writing begins, failure needs the operator; recovery instructions must // name only copies that exist. See docs/architecture.md#restore. -import { cpSync, existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync } from 'node:fs'; +import { + cpSync, + existsSync, + mkdirSync, + mkdtempSync, + readdirSync, + readFileSync, + rmSync, +} from 'node:fs'; import { tmpdir } from 'node:os'; import { basename, dirname, join } from 'node:path'; import { backupSiteFiles, readBackup, refuseMovedData } from './backup.ts'; @@ -50,12 +58,15 @@ import { siteFacts, } from './site.ts'; import { + addRoutes, describeShared, findSharedCaddy, + refuseTaken as refuseServed, routeFiles, routesFile, routesPath, runningCaddy, + type SharedCaddy, } from './shared.ts'; import { verifySite } from './verify.ts'; @@ -82,7 +93,7 @@ export async function restoreSite({ io, context, root, yes }: RestoreInput): Pro ); const target = classify(context, dir, manifest); - await refuseWithoutRoutes(io, root, manifest); + const routes = await refuseWithoutRoutes(io, root, manifest); if (target === 'fresh') { await refuseTaken(io, root, manifest); } else { @@ -134,6 +145,16 @@ export async function restoreSite({ io, context, root, yes }: RestoreInput): Pro writeSiteFiles(io, root, dir, manifest, pin === null ? null : pulled.get(pin)!); await checkImages(io, dir, manifest); await loadBackupData(io, root, dir, manifest); + if (routes !== null) { + await io.busy('Writing the routes into the shared Caddy', () => + addRoutes(io, routes.shared, manifest.site.project, routes.text), + ); + ok( + io, + 'routes', + `${routesPath(routes.shared, manifest.site.project)}, from the backup; the shared Caddy reloaded`, + ); + } heading(io, 'Starting the services'); await upAndWait(io, dir, 'Starting the services and waiting for them to be healthy'); @@ -396,33 +417,57 @@ async function refuseOtherConfiguration( } /** - * A site that was behind the shared Caddy is restored behind it: its network - * must exist, and its routes, which are the shared Caddy's files rather than - * the site's and so not in the backup, must be there to verify it. + * A site that was behind the shared Caddy is restored behind it: the shared + * Caddy must run, and serve the site's routes. Routes it already has are + * kept, as the operator may have edited them since; otherwise the backup's + * are written back (returned here, written once the site's data is), when + * no other site serves their domains. A backup without routes needs them in + * place first. */ -async function refuseWithoutRoutes(io: Io, root: string, manifest: BackupManifest): Promise { +async function refuseWithoutRoutes( + io: Io, + root: string, + manifest: BackupManifest, +): Promise<{ shared: SharedCaddy; text: string } | null> { const settings = env.toRecord(readIfExists(join(root, SITE_FILES_DIR, ENV_FILE)) ?? ''); if (!hasProfile(settings.COMPOSE_PROFILES ?? '', SHARED_CADDY_PROFILE)) { - return; + return null; } + const project = manifest.site.project; const shared = await findSharedCaddy(io); if (shared === null) { throw new CliError( `this backup is of a site behind the shared Caddy, and this server has none.\n` + - ' Set one up first with ./ghost-docker install --infra, in a directory of its own, and put\n' + - ` the site's routes in its caddy/sites/${routesFile(manifest.site.project)}. Nothing has been changed.`, + ' Set one up first with ./ghost-docker install --infra, in a directory of its own' + + (manifest.routes === undefined + ? `, and put\n the site's routes in its caddy/sites/${routesFile(project)}` + : '; the restore\n writes the routes the backup holds') + + '. Nothing has been changed.', ); } - const project = manifest.site.project; - if (!(await routeFiles(io, runningCaddy(shared))).includes(routesFile(project))) { + if ((await routeFiles(io, runningCaddy(shared))).includes(routesFile(project))) { + ok( + io, + 'routes', + `${routesPath(shared, project)}, kept as it is, in ${describeShared(shared)}`, + ); + return null; + } + if (manifest.routes === undefined) { throw new CliError( `this backup is of a site behind the shared Caddy, which has no routes for it:\n` + - ` ${routesPath(shared, project)} does not exist. Routes are the shared Caddy's files, not the\n` + - " site's, so a backup does not hold them: put them back (or write them as docs/caddy.md\n" + - ' describes), then run the restore again. Nothing has been changed.', + ` ${routesPath(shared, project)} does not exist, and the backup holds none. Put them back\n` + + ' (or write them as docs/caddy.md describes), then run the restore again. Nothing has\n' + + ' been changed.', ); } - ok(io, 'routes', `${routesPath(shared, project)}, in ${describeShared(shared)}`); + const domains = [settings.URL, settings.ADMIN_URL] + .filter((url): url is string => Boolean(url)) + .map((url) => URL.parse(url)?.hostname) + .filter((host): host is string => Boolean(host)); + await refuseServed(io, shared, project, domains); + ok(io, 'routes', `the backup's, written to ${routesPath(shared, project)} once the data is`); + return { shared, text: readFileSync(join(root, manifest.routes), 'utf8') }; } /** diff --git a/manager/src/shared.ts b/manager/src/shared.ts index 5a2801ef..48148c96 100644 --- a/manager/src/shared.ts +++ b/manager/src/shared.ts @@ -166,6 +166,31 @@ export async function routeFiles(io: Io, caddy: ContainerFacts): Promise line !== ''); } +/** The marker line an install writes first in its routes (routesMarker). */ +const MARKER_LINE = /^# ghost-docker install [0-9a-f-]+\n/; + +/** + * A site's routes as the shared Caddy holds them, without the marker line + * of the install that wrote them, or null when it has none: what a backup + * keeps, and what a restore writes back with addRoutes. + */ +export async function readRoutes( + io: Io, + shared: SharedCaddy, + project: string, +): Promise { + const caddy = runningCaddy(shared); + if (!(await routeFiles(io, caddy)).includes(routesFile(project))) { + return null; + } + const read = await inCaddy(io, caddy, ['cat', `${SITES}/${routesFile(project)}`]); + if (read.status !== 0) { + throw new CliError(`${routesPath(shared, project)} could not be read: +${said(read)}`); + } + return read.stdout.replace(MARKER_LINE, ''); +} + /** * Refuses a site whose project already has routes in the shared Caddy, or * whose domains it already serves, for whichever site: before anything is diff --git a/manager/test/backup.test.ts b/manager/test/backup.test.ts index 540ff6b8..c8bac42e 100644 --- a/manager/test/backup.test.ts +++ b/manager/test/backup.test.ts @@ -34,6 +34,7 @@ import { type Harness, type ProgramResult, } from './helpers.ts'; +import { CADDY, fakeShared, sharedApi, type FakeShared } from './shared-caddy.ts'; import { imageApi, imageStack, INDEX, REFERENCE, resolvedProject, rootContainer } from './site.ts'; const MANAGER = `sha256:${'2'.repeat(64)}`; @@ -566,6 +567,101 @@ describe('backup records what the site runs', () => { }); }); +describe('a site behind the shared Caddy', () => { + const ROUTES = 'example.com {\n\treverse_proxy ghost-example-com-ghost:2368\n}\n'; + let shared: FakeShared; + let project: string; + const routesFile = () => `${project}.caddy`; + + beforeEach(() => { + project = env.toRecord(readSite('.env')).COMPOSE_PROJECT_NAME!; + // The site as an install behind the shared Caddy leaves it. + const profiles = env.toRecord(readSite('.env')).COMPOSE_PROFILES!; + setEnv('COMPOSE_PROFILES', profiles.replace('production', 'shared-caddy')); + setEnv('INGRESS_NETWORK', 'ghost-ingress'); + setEnv('INGRESS_EXTERNAL', 'true'); + shared = fakeShared(); + shared.sites.set(routesFile(), `# ghost-docker install ${'a'.repeat(8)}-0000\n${ROUTES}`); + const site = h.daemon.api; + const caddy = sharedApi(shared); + h.daemon.api = (request) => caddy(request) ?? site!(request); + h.daemon.containers = [CADDY]; + }); + + test('its backup holds its routes, without their marker line', async () => { + const root = await backUp(); + const manifest = JSON.parse(readFileSync(join(root, 'manifest.json'), 'utf8')); + assert.equal(manifest.routes, 'routes.caddy'); + assert.equal(readFileSync(join(root, 'routes.caddy'), 'utf8'), ROUTES); + assert.ok(manifest.files['routes.caddy']); + assert.ok(!manifest.notIncluded.some((line: string) => /its routes/.test(line))); + }); + + test('routes the shared Caddy does not have leave the backup without them, and say so', async () => { + shared.sites.clear(); + const result = await h.run('backup'); + assert.equal(result.code, 0, result.stderr); + assert.match( + result.stdout + result.stderr, + /does not exist, so the backup holds no routes/, + ); + const manifest = JSON.parse( + readFileSync(join(h.dir, 'backups', backups()[0]!, 'manifest.json'), 'utf8'), + ); + assert.equal(manifest.routes, undefined); + assert.ok(manifest.notIncluded.some((line: string) => /its routes/.test(line))); + }); + + test("a restore writes the backup's routes back when the shared Caddy has none", async () => { + const root = await backUp(); + // The site was removed, its routes with it. + shared.sites.clear(); + const result = await h.run('restore', '--yes', root); + assert.equal(result.code, 0, result.stderr); + assert.match(result.stdout, /the backup's, written to/); + const written = shared.sites.get(routesFile()); + assert.ok(written !== undefined, result.stderr); + assert.match(written, /^# ghost-docker install [0-9a-f-]+\n/); + assert.equal(written.replace(/^.*\n/, ''), ROUTES); + assert.ok(shared.execs.some(({ cmd }) => cmd.includes('reload'))); + }); + + test('a restore keeps the routes the shared Caddy has', async () => { + const root = await backUp(); + const edited = `# ghost-docker install ${'b'.repeat(8)}\nexample.com {\n\trespond 503\n}\n`; + shared.sites.set(routesFile(), edited); + const result = await h.run('restore', '--yes', root); + assert.equal(result.code, 0, result.stderr); + assert.match(result.stdout, /kept as it is/); + assert.equal(shared.sites.get(routesFile()), edited); + }); + + test('a backup without routes is refused while the shared Caddy has none', async () => { + shared.sites.clear(); + const result = await h.run('backup'); + assert.equal(result.code, 0, result.stderr); + const root = join(h.dir, 'backups', backups()[0]!); + const restored = await h.run('restore', '--yes', root); + assert.equal(restored.code, 1); + assert.match( + restored.stderr, + /has no routes for it[\s\S]*the backup holds none[\s\S]*Nothing has/, + ); + }); + + test("routes whose domain another site's routes serve are refused before anything changes", async () => { + const root = await backUp(); + shared.sites.clear(); + shared.hosts = new Set(['example.com']); + const env = readSite('.env'); + const restored = await h.run('restore', '--yes', root); + assert.equal(restored.code, 1); + assert.match(restored.stderr, /already serves example\.com/); + assert.equal(readSite('.env'), env); + assert.equal(shared.sites.size, 0); + }); +}); + describe('restore over the site', () => { test('puts the backup back, pinned, and removes the site it replaced once verified', async () => { const root = await backUp(); diff --git a/manager/test/shared-caddy.ts b/manager/test/shared-caddy.ts new file mode 100644 index 00000000..03046c58 --- /dev/null +++ b/manager/test/shared-caddy.ts @@ -0,0 +1,187 @@ +// A shared Caddy as the daemon shows it, for tests of the sites behind it: +// its network, its container, and the files in its caddy/sites/. +import assert from 'node:assert/strict'; +import type { DockerRequest, DockerResponse } from '../src/docker/transport.ts'; +import { frame } from '../src/docker/client.ts'; +import { json } from './helpers.ts'; + +export const INFRA_DIR = '/srv/caddy'; + +/** A shared Caddy as the daemon would show it: its network, its container, and the files it mounts. */ +export interface FakeShared { + /** Files in its caddy/sites/, by name. */ + sites: Map; + /** Host names its loaded configuration matches. */ + hosts: Set; + running: boolean; + /** What `caddy validate` says: null accepts. */ + refuse: string | null; + /** Each command run in its container, with the user it ran as. */ + execs: { cmd: string[]; user: string }[]; + /** The labels the network was created with, when the manager created it. */ + created: Record | null; + exists: boolean; + /** Another installation, creating the network or a routes file first. */ + raced: { network?: boolean; routes?: string }; + /** A routes write that runs, but whose result the daemon never reports. */ + lost: boolean; +} + +export function fakeShared(): FakeShared { + return { + sites: new Map(), + hosts: new Set(), + running: true, + refuse: null, + execs: [], + created: null, + exists: true, + raced: {}, + lost: false, + }; +} + +export const CADDY = { + Id: 'shared-caddy', + Names: ['/ghost-infra-caddy-1'], + State: 'running', + Status: 'Up 2 minutes (healthy)', + Labels: { + 'org.ghost.docker.managed': 'true', + 'org.ghost.docker.mode': 'infra', + 'com.docker.compose.project': 'ghost-infra', + 'com.docker.compose.project.working_dir': INFRA_DIR, + 'com.docker.compose.service': 'caddy', + }, + Ports: [ + { PrivatePort: 80, PublicPort: 80, Type: 'tcp' }, + { PrivatePort: 443, PublicPort: 443, Type: 'tcp' }, + ], + NetworkSettings: { Networks: { 'ghost-ingress': {} } }, +}; + +/** The daemon's answers about the shared Caddy: its network, and commands run in its container. */ +export function sharedApi(shared: FakeShared) { + let pending: { cmd: string[]; user: string } | null = null; + let status = 0; + return (request: DockerRequest): DockerResponse | undefined => { + const { method, path } = request; + if (path === '/networks/ghost-ingress' && method === 'GET') { + return shared.exists + ? json(200, { + Id: 'ingress-id', + Name: 'ghost-ingress', + Labels: shared.created ?? { + 'org.ghost.docker.infra.dir': INFRA_DIR, + 'org.ghost.docker.infra.project': 'ghost-infra', + }, + }) + : json(404, { message: 'network ghost-ingress not found' }); + } + if (path === '/networks/create' && method === 'POST') { + const body = request.body as { Name: string; Labels: Record }; + assert.equal(body.Name, 'ghost-ingress'); + if (shared.raced.network) { + shared.exists = true; + return json(409, { message: 'network with name ghost-ingress already exists' }); + } + shared.created = body.Labels; + shared.exists = true; + return json(201, { Id: 'ingress-id' }); + } + if (path === '/networks/ghost-ingress' && method === 'DELETE') { + shared.exists = false; + shared.created = null; + return { status: 204, body: Buffer.alloc(0) }; + } + if (path === '/containers/shared-caddy/exec' && method === 'POST') { + const body = request.body as { Cmd: string[]; User?: string }; + pending = { cmd: body.Cmd, user: body.User ?? '' }; + shared.execs.push(pending); + return json(201, { Id: 'exec-1' }); + } + if (path === '/exec/exec-1/start') { + const { stdout, code } = run(shared, pending!); + status = code; + if (shared.lost && pending!.cmd[0] === 'sh' && !pending!.cmd[2]!.includes('grep')) { + return { status: 500, body: Buffer.from('connection reset') }; + } + return { status: 200, body: frame(code === 0 ? 1 : 2, stdout) }; + } + if (path === '/exec/exec-1/json') { + return json(200, { Running: false, ExitCode: status }); + } + return undefined; + }; +} + +/** A command in the shared Caddy's container, done to the fake's files. */ +function run(shared: FakeShared, { cmd }: { cmd: string[] }): { stdout: string; code: number } { + const name = (path: string) => path.replace('/etc/caddy/sites/', ''); + switch (cmd[0]) { + case 'flock': + // Reloads are serialized on the sites' directory. + assert.equal(cmd[1], '/etc/caddy/sites'); + return run(shared, { cmd: cmd.slice(2) }); + case 'wget': { + const routes = [...shared.hosts].map((host) => ({ match: [{ host: [host] }] })); + return { + stdout: JSON.stringify({ apps: { http: { servers: { srv0: { routes } } } } }), + code: 0, + }; + } + case 'ls': + return { + stdout: [...shared.sites.keys()].map((file) => `${file}\n`).join(''), + code: 0, + }; + case 'cat': { + const routes = shared.sites.get(name(cmd[1]!)); + return routes === undefined + ? { stdout: `cat: ${cmd[1]}: No such file`, code: 1 } + : { stdout: routes, code: 0 }; + } + case 'stat': + return { stdout: '1000:1000\n', code: 0 }; + case 'sh': { + // sh -c SCRIPT sh MARKER FILE: removes the file if it is that write's. + if (cmd[2]!.includes('grep')) { + if (shared.sites.get(name(cmd[5]!))?.split('\n')[0] === cmd[4]) { + shared.sites.delete(name(cmd[5]!)); + } + return { stdout: '', code: 0 }; + } + // sh -c SCRIPT sh ROUTES FILE, which never overwrites a file. + if (shared.raced.routes !== undefined) { + shared.sites.set(name(cmd[5]!), shared.raced.routes); + } + if (shared.sites.has(name(cmd[5]!))) { + return { stdout: '', code: 1 }; + } + shared.sites.set(name(cmd[5]!), cmd[4]!); + return { stdout: '', code: 0 }; + } + case 'rm': + shared.sites.delete(name(cmd.at(-1)!)); + return { stdout: '', code: 0 }; + case 'caddy': + if (cmd[1] === 'validate' && shared.refuse !== null) { + return { stdout: shared.refuse, code: 1 }; + } + if (cmd[1] === 'reload') { + // What the files now serve. + shared.hosts = new Set( + [...shared.sites.values()].flatMap( + (routes) => + /^([^\s#{][^{]*)\{/m + .exec(routes)?.[1]! + .split(',') + .map((host) => host.trim()) ?? [], + ), + ); + } + return { stdout: '', code: 0 }; + default: + return { stdout: `unexpected: ${cmd.join(' ')}`, code: 127 }; + } +} diff --git a/manager/test/shared.test.ts b/manager/test/shared.test.ts index 568e4527..4e6b7817 100644 --- a/manager/test/shared.test.ts +++ b/manager/test/shared.test.ts @@ -9,189 +9,13 @@ import { existsSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'no import { join } from 'node:path'; import { afterEach, beforeEach, describe, test } from 'node:test'; import * as env from '../src/env.ts'; -import type { DockerRequest, DockerResponse } from '../src/docker/transport.ts'; -import { frame } from '../src/docker/client.ts'; import { payloadFiles } from '../src/payload.ts'; import { layoutOf, readSettings, siteFacts, siteMode } from '../src/site.ts'; import { verifyIngress } from '../src/verify.ts'; -import { failed, harness, json, ok, type Harness } from './helpers.ts'; +import { failed, harness, ok, type Harness } from './helpers.ts'; +import { CADDY, fakeShared, sharedApi, type FakeShared } from './shared-caddy.ts'; import { imageApi, imageStack, rootContainer } from './site.ts'; -const INFRA_DIR = '/srv/caddy'; - -/** A shared Caddy as the daemon would show it: its network, its container, and the files it mounts. */ -interface FakeShared { - /** Files in its caddy/sites/, by name. */ - sites: Map; - /** Host names its loaded configuration matches. */ - hosts: Set; - running: boolean; - /** What `caddy validate` says: null accepts. */ - refuse: string | null; - /** Each command run in its container, with the user it ran as. */ - execs: { cmd: string[]; user: string }[]; - /** The labels the network was created with, when the manager created it. */ - created: Record | null; - exists: boolean; - /** Another installation, creating the network or a routes file first. */ - raced: { network?: boolean; routes?: string }; - /** A routes write that runs, but whose result the daemon never reports. */ - lost: boolean; -} - -function fakeShared(): FakeShared { - return { - sites: new Map(), - hosts: new Set(), - running: true, - refuse: null, - execs: [], - created: null, - exists: true, - raced: {}, - lost: false, - }; -} - -const CADDY = { - Id: 'shared-caddy', - Names: ['/ghost-infra-caddy-1'], - State: 'running', - Status: 'Up 2 minutes (healthy)', - Labels: { - 'org.ghost.docker.managed': 'true', - 'org.ghost.docker.mode': 'infra', - 'com.docker.compose.project': 'ghost-infra', - 'com.docker.compose.project.working_dir': INFRA_DIR, - 'com.docker.compose.service': 'caddy', - }, - Ports: [ - { PrivatePort: 80, PublicPort: 80, Type: 'tcp' }, - { PrivatePort: 443, PublicPort: 443, Type: 'tcp' }, - ], - NetworkSettings: { Networks: { 'ghost-ingress': {} } }, -}; - -/** The daemon's answers about the shared Caddy: its network, and commands run in its container. */ -function sharedApi(shared: FakeShared) { - let pending: { cmd: string[]; user: string } | null = null; - let status = 0; - return (request: DockerRequest): DockerResponse | undefined => { - const { method, path } = request; - if (path === '/networks/ghost-ingress' && method === 'GET') { - return shared.exists - ? json(200, { - Id: 'ingress-id', - Name: 'ghost-ingress', - Labels: shared.created ?? { - 'org.ghost.docker.infra.dir': INFRA_DIR, - 'org.ghost.docker.infra.project': 'ghost-infra', - }, - }) - : json(404, { message: 'network ghost-ingress not found' }); - } - if (path === '/networks/create' && method === 'POST') { - const body = request.body as { Name: string; Labels: Record }; - assert.equal(body.Name, 'ghost-ingress'); - if (shared.raced.network) { - shared.exists = true; - return json(409, { message: 'network with name ghost-ingress already exists' }); - } - shared.created = body.Labels; - shared.exists = true; - return json(201, { Id: 'ingress-id' }); - } - if (path === '/networks/ghost-ingress' && method === 'DELETE') { - shared.exists = false; - shared.created = null; - return { status: 204, body: Buffer.alloc(0) }; - } - if (path === '/containers/shared-caddy/exec' && method === 'POST') { - const body = request.body as { Cmd: string[]; User?: string }; - pending = { cmd: body.Cmd, user: body.User ?? '' }; - shared.execs.push(pending); - return json(201, { Id: 'exec-1' }); - } - if (path === '/exec/exec-1/start') { - const { stdout, code } = run(shared, pending!); - status = code; - if (shared.lost && pending!.cmd[0] === 'sh' && !pending!.cmd[2]!.includes('grep')) { - return { status: 500, body: Buffer.from('connection reset') }; - } - return { status: 200, body: frame(code === 0 ? 1 : 2, stdout) }; - } - if (path === '/exec/exec-1/json') { - return json(200, { Running: false, ExitCode: status }); - } - return undefined; - }; -} - -/** A command in the shared Caddy's container, done to the fake's files. */ -function run(shared: FakeShared, { cmd }: { cmd: string[] }): { stdout: string; code: number } { - const name = (path: string) => path.replace('/etc/caddy/sites/', ''); - switch (cmd[0]) { - case 'flock': - // Reloads are serialized on the sites' directory. - assert.equal(cmd[1], '/etc/caddy/sites'); - return run(shared, { cmd: cmd.slice(2) }); - case 'wget': { - const routes = [...shared.hosts].map((host) => ({ match: [{ host: [host] }] })); - return { - stdout: JSON.stringify({ apps: { http: { servers: { srv0: { routes } } } } }), - code: 0, - }; - } - case 'ls': - return { - stdout: [...shared.sites.keys()].map((file) => `${file}\n`).join(''), - code: 0, - }; - case 'stat': - return { stdout: '1000:1000\n', code: 0 }; - case 'sh': { - // sh -c SCRIPT sh MARKER FILE: removes the file if it is that write's. - if (cmd[2]!.includes('grep')) { - if (shared.sites.get(name(cmd[5]!))?.split('\n')[0] === cmd[4]) { - shared.sites.delete(name(cmd[5]!)); - } - return { stdout: '', code: 0 }; - } - // sh -c SCRIPT sh ROUTES FILE, which never overwrites a file. - if (shared.raced.routes !== undefined) { - shared.sites.set(name(cmd[5]!), shared.raced.routes); - } - if (shared.sites.has(name(cmd[5]!))) { - return { stdout: '', code: 1 }; - } - shared.sites.set(name(cmd[5]!), cmd[4]!); - return { stdout: '', code: 0 }; - } - case 'rm': - shared.sites.delete(name(cmd.at(-1)!)); - return { stdout: '', code: 0 }; - case 'caddy': - if (cmd[1] === 'validate' && shared.refuse !== null) { - return { stdout: shared.refuse, code: 1 }; - } - if (cmd[1] === 'reload') { - // What the files now serve. - shared.hosts = new Set( - [...shared.sites.values()].flatMap( - (routes) => - /^([^\s#{][^{]*)\{/m - .exec(routes)?.[1]! - .split(',') - .map((host) => host.trim()) ?? [], - ), - ); - } - return { stdout: '', code: 0 }; - default: - return { stdout: `unexpected: ${cmd.join(' ')}`, code: 127 }; - } -} - let h: Harness; let shared: FakeShared; let compose: string[][]; @@ -405,7 +229,7 @@ describe('self-update of the shared Caddy', () => { assert.equal(after.stack.version, 'v0.1.0-beta.2'); assert.deepEqual( compose.map((args) => args[0]), - ['config', 'pull', 'up', 'exec', 'ps'], + ['pull', 'config', 'up', 'exec', 'ps'], ); // Serialized with the sites' route changes. assert.deepEqual( @@ -491,11 +315,80 @@ describe('self-update of the shared Caddy', () => { assert.equal(reloads, 2); }); + test('images it cannot pull refuse the update before any file is written', async () => { + const before = readFileSync(join(h.dir, 'caddy', 'snippets', 'Logging'), 'utf8'); + h.daemon.composeRun = (args) => { + compose.push(args); + return args[0] === 'pull' ? failed(1, 'manifest unknown') : ok(''); + }; + const result = await h.run('self-update'); + assert.equal(result.code, 1); + assert.match(result.stderr, /could not be pulled[\s\S]*Nothing has been changed/); + assert.equal(readFileSync(join(h.dir, 'caddy', 'snippets', 'Logging'), 'utf8'), before); + assert.deepEqual( + compose.map((args) => args[0]), + ['pull'], + ); + assert.equal(metadata().stack.version, 'v0.1.0-beta.1'); + }); + + test("a failure before Caddy restarts reloads the old files, which a site's reload may have replaced", async () => { + const before = readFileSync(join(h.dir, 'caddy', 'snippets', 'Logging'), 'utf8'); + let live = before; + h.daemon.composeRun = (args) => { + compose.push(args); + switch (args[0]) { + case 'config': + // A site installs meanwhile, and its reload loads the + // release's files; then the release does not validate. + live = readFileSync(join(h.dir, 'caddy', 'snippets', 'Logging'), 'utf8'); + return failed(1, 'services.caddy: invalid'); + case 'exec': + live = readFileSync(join(h.dir, 'caddy', 'snippets', 'Logging'), 'utf8'); + return ok(''); + case 'ps': + return ok(ps()); + default: + return ok(''); + } + }; + const result = await h.run('self-update'); + assert.equal(result.code, 1); + assert.match( + result.stderr, + /back on v0\.1\.0-beta\.1, with its configuration loaded again/, + ); + assert.equal(live, before); + assert.equal(compose.filter((args) => args[0] === 'up').length, 0); + assert.deepEqual(compose.at(-1)!.slice(0, 5), [ + 'exec', + '-T', + 'caddy', + 'flock', + '/etc/caddy/sites', + ]); + assert.ok(!existsSync(join(h.dir, '.ghost-docker-update'))); + }); + + test('a Caddy that will not reload the old files is left for the operator', async () => { + h.daemon.composeRun = (args) => { + compose.push(args); + if (args[0] === 'config') { + return failed(1, 'services.caddy: invalid'); + } + return args[0] === 'exec' ? failed(1, 'container caddy is not running') : ok(''); + }; + const result = await h.run('self-update'); + assert.equal(result.code, 1); + assert.match(result.stderr, /Caddy did not load them[\s\S]*not running/); + assert.ok(existsSync(join(h.dir, '.ghost-docker-update', 'files'))); + }); + test('a Caddy that will not start again either is left for the operator, with the files kept', async () => { up = () => failed(1, 'Bind for 0.0.0.0:443 failed'); const result = await h.run('self-update'); assert.equal(result.code, 1); - assert.match(result.stderr, /Caddy did not start on them[\s\S]*unreachable until it does/); + assert.match(result.stderr, /Caddy did not start on them[\s\S]*may be unreachable/); assert.ok(existsSync(join(h.dir, '.ghost-docker-update', 'files'))); }); diff --git a/tests/e2e/shared-caddy.sh b/tests/e2e/shared-caddy.sh index 4d5f8808..e7f09059 100755 --- a/tests/e2e/shared-caddy.sh +++ b/tests/e2e/shared-caddy.sh @@ -12,7 +12,8 @@ # checked to leave the other as it was, the same containers serving the same # routes: updating the first site's Ghost, backing it up and restoring it over # itself, restarting and recreating the shared Caddy (both sites come back), -# and removing the second site, whose routes go with it. The shared Caddy's +# and removing the second site, whose routes go with it, then restoring it +# from its backup, which holds them. The shared Caddy's # own directory answers self-update; moving it between releases is unit-tested. # # It pulls images, starts containers and binds ports 80 and 443 (it fails @@ -207,8 +208,10 @@ step "Backing alpha up and restoring it over itself leaves bravo untouched" run gd "$A" backup expect_status 0 backup=$(find "$A/backups" -mindepth 1 -maxdepth 1 | sort | tail -1) -jq -e '.notIncluded | any(test("shared Caddy"))' "$backup/manifest.json" >/dev/null || - fail "the backup does not say it leaves the routes out" "$(cat "$backup/manifest.json")" +jq -e '.routes == "routes.caddy"' "$backup/manifest.json" >/dev/null || + fail "the backup does not hold alpha's routes" "$(cat "$backup/manifest.json")" +[[ $(tail -n +2 "$CADDY/caddy/sites/ghost-alpha-e2e-test.caddy") == "$(cat "$backup/routes.caddy")" ]] || + fail "the backup's routes are not alpha's, without their marker line" "$(cat "$backup/routes.caddy")" run gd "$A" restore --yes "$backup" expect_status 0 serves "$DOMAIN_A" @@ -231,6 +234,9 @@ untouched "$B" "$before_b" ok "both answer after a restart and after down and up; neither site's containers changed" step "Removing bravo removes its routes, and leaves alpha untouched" +run gd "$B" backup +expect_status 0 +backup_b=$(find "$B/backups" -mindepth 1 -maxdepth 1 | sort | tail -1) run gd "$B" remove expect_status 2 expect_output 'Run it again with --yes' @@ -248,4 +254,14 @@ expect_output '^ghost-alpha-e2e-test +shared-caddy ' refute_output 'ghost-bravo-e2e-test' ok "bravo removed with its routes; alpha's containers as they were, and served" +step "Restoring bravo's backup writes its routes back" +run gd "$B" restore --yes "$backup_b" +expect_status 0 +expect_output "the backup's, written to" +[[ -f $CADDY/caddy/sites/ghost-bravo-e2e-test.caddy ]] || fail "bravo's routes were not written back" +serves "$DOMAIN_B" +serves "$DOMAIN_A" +untouched "$A" "$before_a" +ok "bravo restored behind the shared Caddy, with the routes its backup held; alpha untouched" + passed 'All shared Caddy checks passed.' From 0db74efe9ae63566c0fd201289fd8e140083e828 Mon Sep 17 00:00:00 2001 From: Austin Burdine Date: Wed, 4 Nov 2026 11:01:23 -0500 Subject: [PATCH 08/15] Required a checksum for the routes a backup holds (S13) A restore writes a backup's routes into the shared Caddy, but reading the backup required checksums only for the dumps and the content archive, so routes.caddy left out of manifest.files was installed unchecked while the restore reported every file matching its checksum. --- manager/src/backup.ts | 6 +++++- manager/test/backup.test.ts | 23 +++++++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/manager/src/backup.ts b/manager/src/backup.ts index b973b4e9..addd253c 100644 --- a/manager/src/backup.ts +++ b/manager/src/backup.ts @@ -642,7 +642,11 @@ export async function readBackup(io: Io, root: string): Promise throw new CliError(`${read.reason}. Nothing has been changed.`); } const { manifest } = read; - const wanted = [manifest.content.file, ...manifest.databases.map((database) => database.file)]; + const wanted = [ + manifest.content.file, + ...manifest.databases.map((database) => database.file), + ...(manifest.routes === undefined ? [] : [manifest.routes]), + ]; for (const file of wanted) { if (!(file in manifest.files)) { throw new CliError( diff --git a/manager/test/backup.test.ts b/manager/test/backup.test.ts index c8bac42e..5c39b6fd 100644 --- a/manager/test/backup.test.ts +++ b/manager/test/backup.test.ts @@ -649,6 +649,29 @@ describe('a site behind the shared Caddy', () => { ); }); + test('routes with no checksum are refused before anything changes', async () => { + const root = await backUp(); + const manifest = JSON.parse(readFileSync(join(root, 'manifest.json'), 'utf8')); + delete manifest.files['routes.caddy']; + writeFileSync(join(root, 'manifest.json'), JSON.stringify(manifest)); + writeFileSync( + join(root, 'routes.caddy'), + 'example.com {\n\trespond "not the backup\'s"\n}\n', + ); + shared.sites.clear(); + shared.execs.length = 0; + const before = readSite('.env'); + const restored = await h.run('restore', '--yes', root); + assert.equal(restored.code, 1); + assert.match( + restored.stderr, + /lists no checksum for routes\.caddy\. Nothing has been changed/, + ); + assert.equal(readSite('.env'), before); + assert.equal(shared.sites.size, 0); + assert.deepEqual(shared.execs, []); + }); + test("routes whose domain another site's routes serve are refused before anything changes", async () => { const root = await backUp(); shared.sites.clear(); From c97802ec6b7434fc382d6d481a5ffa861c6c23cb Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 6 Dec 2026 17:09:41 +0000 Subject: [PATCH 09/15] Made the shared Caddy static, with each site's own Caddy behind it (S13) ref https://linear.app/ghost/issue/PLA-484 The shared Caddy held every site's routes in its own directory, which a site's manager cannot see. So routes were written through its container, marked for undo, reloaded under a lock, and copied into backups and written back on restore. That was most of the change, and the reason backup and restore had to change at all. Here the shared Caddy names no site. Each site behind it keeps its own Caddy and routes, serving plain HTTP on the shared network under its domains as aliases, and the shared Caddy obtains certificates on demand and passes each request to the alias of the name asked for. Installing, changing or removing a site writes nothing in the shared Caddy's directory and reloads nothing; a site's routes are in its own backup as a single site's are; and sites on different releases can route differently, since each carries its own Caddy files. - infra/: the shared Caddy's own compose.yml and Caddyfile, so the sites' compose.yml keeps its `:?` guards - compose.yml: `caddy-internal`, the site's Caddy without ports, on the shared network under INGRESS_HOST and INGRESS_ADMIN_HOST - manager/src/shared.ts: finding the shared Caddy, and refusing a domain another site's Caddy answers to; nothing written through it - manager/src/commands/install.ts: routes written into the site, for HTTP, with the shared Caddy trusted as a proxy; --email is the shared Caddy's, and --infra takes it - manager/src/config.ts: the ingress names must match URL and ADMIN_URL - manager/src/backup.ts, restore.ts, undo.ts: as on next-docker, bar refusing a restore on a server with no shared Caddy - manager/src/commands/remove.ts: removed; docker compose down is all removing a site takes - manager/src/commands/self-update.ts: the shared Caddy's update has no sites' reloads to take turns with - manager/src/update.ts, verify.ts: a site's Caddy by its service name - manager/src/docker/client.ts: no exec in a container - manager/test/, tests/e2e/shared-caddy.sh: follow, against a real shared Caddy and site Caddy - docs/: the shared Caddy as it now is --- .dockerignore | 2 + .env.example | 10 +- compose.yml | 82 +++-- docs/architecture.md | 28 +- docs/caddy.md | 185 ++++++---- docs/configuration.md | 23 +- docs/install.md | 22 +- docs/reference.md | 75 ++-- infra/caddy/Caddyfile | 49 +++ infra/caddy/custom/README.md | 22 ++ infra/caddy/global/README.md | 15 + infra/compose.yml | 60 ++++ manager/Dockerfile | 2 + manager/src/backup.ts | 62 +--- manager/src/backup/manifest.ts | 9 - manager/src/caddy.ts | 33 +- manager/src/cli.ts | 2 - manager/src/commands/install.ts | 120 +++---- manager/src/commands/remove.ts | 111 ------ manager/src/commands/self-update.ts | 50 ++- manager/src/commands/site.ts | 22 +- manager/src/config.ts | 60 ++-- manager/src/docker/client.ts | 77 ---- manager/src/legacy.ts | 1 - manager/src/payload.ts | 17 +- manager/src/restore.ts | 109 ++---- manager/src/shared.ts | 324 +++-------------- manager/src/site.ts | 27 +- manager/src/undo.ts | 49 +-- manager/src/update.ts | 11 +- manager/src/verify.ts | 94 +++-- manager/templates/site.caddy | 2 +- manager/test/backup.test.ts | 119 ------- manager/test/config.test.ts | 5 +- manager/test/integration/shared.test.ts | 144 ++++---- manager/test/integration/site.ts | 12 +- manager/test/shared-caddy.ts | 174 +++------ manager/test/shared.test.ts | 448 ++++++++---------------- manager/test/site.ts | 2 +- tests/e2e/shared-caddy.sh | 126 +++---- 40 files changed, 1023 insertions(+), 1762 deletions(-) create mode 100644 infra/caddy/Caddyfile create mode 100644 infra/caddy/custom/README.md create mode 100644 infra/caddy/global/README.md create mode 100644 infra/compose.yml delete mode 100644 manager/src/commands/remove.ts diff --git a/.dockerignore b/.dockerignore index a4df6275..051f844e 100644 --- a/.dockerignore +++ b/.dockerignore @@ -18,6 +18,8 @@ backups caddy/sites/*.caddy caddy/custom/*.caddy caddy/global/*.caddy +infra/caddy/custom/*.caddy +infra/caddy/global/*.caddy docs pages scripts diff --git a/.env.example b/.env.example index 97070831..e0655d3a 100644 --- a/.env.example +++ b/.env.example @@ -74,11 +74,11 @@ GHOST_PORT="2368" HTTP_PORT="80" HTTPS_PORT="443" -# Behind the shared Caddy, and in its own directory: its network, which the -# manager created and no Compose project owns. Unset, a site with its own -# Caddy gets a network of its own. -# INGRESS_NETWORK="ghost-ingress" -# INGRESS_EXTERNAL="true" +# Behind the shared Caddy (`shared-caddy`): the hosts of URL and ADMIN_URL, +# which name the site's Caddy on the shared Caddy's network. `install` writes +# them; they must match URL and ADMIN_URL. +# INGRESS_HOST="example.com" +# INGRESS_ADMIN_HOST="admin.example.com" # --- Lifecycle ------------------------------------------------------------ # Applied to long-running services only. One-shot jobs keep `restart: "no"`. diff --git a/compose.yml b/compose.yml index eb84f793..e2b49908 100644 --- a/compose.yml +++ b/compose.yml @@ -11,18 +11,12 @@ # credentials (MySQL root) that Ghost must not receive. # # Site modes are selected through COMPOSE_PROFILES and are additive: -# local ghost + db, Ghost published on 127.0.0.1:${GHOST_PORT} -# production ghost + db + caddy (HTTPS ingress) -# no-caddy ghost + db, a production site behind the operator's own proxy -# (nginx, Apache) on 127.0.0.1:${GHOST_PORT} -# shared-caddy ghost + db, a production site behind the shared Caddy -# and `infra` is the shared Caddy's own directory: caddy alone, for the -# sites' routes (docs/caddy.md#the-shared-caddy). -# -# Variables a site needs and the shared Caddy does not are not `:?`-guarded, -# because Compose interpolates services its profiles leave out too: -# `./ghost-docker config validate` requires them for a site. -# +# local ghost + db, Ghost published on 127.0.0.1:${GHOST_PORT} +# production ghost + db + caddy (HTTPS ingress) +# no-caddy ghost + db, a production site behind the operator's own proxy +# (nginx, Apache) on 127.0.0.1:${GHOST_PORT} +# shared-caddy ghost + db + caddy-internal, a production site behind the +# server's shared Caddy (infra/compose.yml), which holds 80 and 443 # Optional, per-site profiles: analytics, activitypub, and for local sites # mailpit, and `supervisor`, which runs Ghost updates asked for in Ghost Admin # (docs/upgrade-supervisor.md). @@ -59,7 +53,7 @@ services: # Container-owned keys. These override anything set in ghost.env. environment: NODE_ENV: ${NODE_ENV:-production} - url: ${URL:-} + url: ${URL:?URL is required (for example https://example.com or http://localhost:2368)} admin__url: ${ADMIN_URL:-} server__host: 0.0.0.0 server__port: "2368" @@ -68,9 +62,9 @@ services: database__connection__host: ${DATABASE_HOST:-db} database__connection__port: ${DATABASE_PORT:-3306} database__connection__user: ${DATABASE_USER:-ghost} - database__connection__password: ${DATABASE_PASSWORD:-} + database__connection__password: ${DATABASE_PASSWORD:?DATABASE_PASSWORD is required} database__connection__database: ${DATABASE_NAME:-ghost} - tinybird__tracker__endpoint: ${URL:-}/.ghost/analytics/api/v1/page_hit + tinybird__tracker__endpoint: ${URL}/.ghost/analytics/api/v1/page_hit tinybird__tracker__datasource: analytics_events tinybird__adminToken: ${TINYBIRD_ADMIN_TOKEN:-} tinybird__workspaceId: ${TINYBIRD_WORKSPACE_ID:-} @@ -118,9 +112,6 @@ services: # Unique alias. Generated proxy routes and helper clients address Ghost # through this name, never through the bare `ghost` service name. - ghost-${COMPOSE_PROJECT_NAME:-ghost} - ingress: - aliases: - - ghost-${COMPOSE_PROJECT_NAME:-ghost} db: image: mysql:8.0.44@sha256:f37951fc3753a6a22d6c7bf6978c5e5fefcf6f31814d98c582524f98eae52b21 @@ -133,9 +124,9 @@ services: expose: - "3306" environment: - MYSQL_ROOT_PASSWORD: ${DATABASE_ROOT_PASSWORD:-} + MYSQL_ROOT_PASSWORD: ${DATABASE_ROOT_PASSWORD:?DATABASE_ROOT_PASSWORD is required} MYSQL_USER: ${DATABASE_USER:-ghost} - MYSQL_PASSWORD: ${DATABASE_PASSWORD:-} + MYSQL_PASSWORD: ${DATABASE_PASSWORD:?DATABASE_PASSWORD is required} MYSQL_DATABASE: ${DATABASE_NAME:-ghost} MYSQL_MULTIPLE_DATABASES: ${DATABASE_EXTRA_DATABASES:-activitypub} volumes: @@ -197,12 +188,10 @@ services: networks: - ghost_network - # A production site's own Caddy, or with `infra`, the shared Caddy, which - # serves the members' routes from caddy/sites/. - caddy: + caddy: &caddy image: caddy:2.10.2-alpine@sha256:953131cfea8e12bfe1c631a36308e9660e4389f0c3dfb3be957044d3ac92d446 restart: ${RESTART_POLICY:-unless-stopped} - profiles: [production, infra] + profiles: [production] labels: <<: *site-labels org.ghost.docker.lifecycle: long-running @@ -227,11 +216,24 @@ services: depends_on: ghost: condition: service_started - # The shared Caddy has no Ghost of its own. - required: false - # Only what Caddy routes to is on this network: never MySQL. networks: - - ingress + - ghost_network + + # Behind the shared Caddy (docs/caddy.md#the-shared-caddy): the site's own + # Caddy, with the same routes and files, serving plain HTTP and publishing no + # port. The shared Caddy holds 80 and 443 and the certificates, and reaches + # this one on its network by the site's domains, which are its aliases there. + # Nothing else of the site is on that network. + caddy-internal: + <<: *caddy + profiles: [shared-caddy] + ports: [] + networks: + ghost_network: + ingress: + aliases: + - ${INGRESS_HOST:-}.ghost.internal + - ${INGRESS_ADMIN_HOST:-${INGRESS_HOST:-}}.ghost.internal traffic-analytics: image: ghost/traffic-analytics:1.0.450@sha256:33c0ff8a369040e1455b790cf1711c2ea7f3174bcd26230dc9f7fc77b401816c @@ -257,9 +259,6 @@ services: ghost_network: aliases: - traffic-analytics-${COMPOSE_PROJECT_NAME:-ghost} - ingress: - aliases: - - traffic-analytics-${COMPOSE_PROJECT_NAME:-ghost} activitypub: image: ghcr.io/tryghost/activitypub:1.3.0@sha256:59f0a7470df4ee27b609bd97f4189bf3c6c3f3ecf87f434bbe338fafd5f80070 @@ -279,10 +278,10 @@ services: MYSQL_HOST: ${DATABASE_HOST:-db} MYSQL_PORT: ${DATABASE_PORT:-3306} MYSQL_USER: ${DATABASE_USER:-ghost} - MYSQL_PASSWORD: ${DATABASE_PASSWORD:-} + MYSQL_PASSWORD: ${DATABASE_PASSWORD:?DATABASE_PASSWORD is required} MYSQL_DATABASE: ${ACTIVITYPUB_DATABASE_NAME:-activitypub} LOCAL_STORAGE_PATH: /opt/activitypub/content/images/activitypub - LOCAL_STORAGE_HOSTING_URL: ${URL:-}/content/images/activitypub + LOCAL_STORAGE_HOSTING_URL: ${URL}/content/images/activitypub depends_on: db: condition: service_healthy @@ -292,9 +291,6 @@ services: ghost_network: aliases: - activitypub-${COMPOSE_PROJECT_NAME:-ghost} - ingress: - aliases: - - activitypub-${COMPOSE_PROJECT_NAME:-ghost} # Local sites only: catches the mail Ghost sends (staff invites, password # resets, member sign-in links) and shows it in a web inbox. Newsletters go @@ -346,7 +342,7 @@ services: org.ghost.docker.lifecycle: one-shot logging: *default-logging environment: - MYSQL_DB: mysql://${DATABASE_USER:-ghost}:${DATABASE_PASSWORD:-}@tcp(${DATABASE_HOST:-db}:${DATABASE_PORT:-3306})/${ACTIVITYPUB_DATABASE_NAME:-activitypub} + MYSQL_DB: mysql://${DATABASE_USER:-ghost}:${DATABASE_PASSWORD:?DATABASE_PASSWORD is required}@tcp(${DATABASE_HOST:-db}:${DATABASE_PORT:-3306})/${ACTIVITYPUB_DATABASE_NAME:-activitypub} depends_on: db: condition: service_healthy @@ -435,10 +431,10 @@ volumes: networks: ghost_network: - # What Caddy reaches the site's services on. A site with its own Caddy gets - # one of its own. Behind the shared Caddy, and in its directory, it is the - # shared Caddy's network, which the manager creates and no project owns - # (`.env` names it). + # The shared Caddy's network, which `install --infra` creates and no Compose + # project owns. Only a site behind the shared Caddy uses it. ingress: - name: ${INGRESS_NETWORK:-${COMPOSE_PROJECT_NAME:-ghost}_ingress} - external: ${INGRESS_EXTERNAL:-false} + # Always ghost-ingress, which the manager finds the shared Caddy by; the + # integration tests alone name another. + name: ${INGRESS_NETWORK:-ghost-ingress} + external: true diff --git a/docs/architecture.md b/docs/architecture.md index 8b3db562..cf34ff87 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -126,20 +126,20 @@ sites installed before, keeping any file in them that was edited. Caddy routes a route edits and reload instructions. `src/shared.ts` is the shared Caddy: one Caddy project per daemon (`install ---infra`, the `infra` profile, and metadata of the `infra` mode with no -Ghost, so that `self-update` can keep its stack files and launcher current -without a backup, as it holds no data), on a network the manager creates -and labels with its directory, so no Compose project's `down` removes it. A -production install finds it by that network and selects the `shared-caddy` profile: Caddy's -own payload is left out, and its routes are a file in the shared Caddy's -`caddy/sites/`. The manager cannot see that directory, so it reads and writes -it through the running Caddy container (Engine API exec), as the directory's -owner; Caddy validates the whole configuration before it is reloaded, and -routes it refuses are removed. Duplicate domains (from Caddy's loaded -configuration) and projects (a routes file of that name) are refused before -any write. `remove` and a failed install's undo take a site's routes out -again. A site's backup holds a copy (`routes.caddy`), which a restore writes -back when the shared Caddy has none for the project. +--infra`, with its own stack files in the payload's `infra/` and metadata of +the `infra` mode with no Ghost, so that `self-update` can keep them and the +launcher current without a backup, as it holds no data), on a network the +manager creates and labels with its directory, so no Compose project's `down` +removes it. It names no site: it obtains certificates on demand and passes +each request to `.ghost.internal` on that network. A production install +finds it by the network and selects the `shared-caddy` profile, which runs +the site's own Caddy as `caddy-internal`: no published port, plain HTTP, and +the site's domains as its aliases on the shared network. The site's routes +and Caddy files stay in its own directory, so the file inventory, backup, +restore and `self-update` treat them as a single site's, and nothing is ever +written in the shared Caddy's directory for a site. Before any write, an +install refuses a domain another site's Caddy has on the network. A restore +refuses a backup of such a site on a server with no shared Caddy. `src/bundle/manifest.ts` defines the migration bundle schema and depends only on zod so the exporter can share it. Import policy stays outside that schema. diff --git a/docs/caddy.md b/docs/caddy.md index 304ce261..d46db78e 100644 --- a/docs/caddy.md +++ b/docs/caddy.md @@ -99,115 +99,148 @@ storage and serving URL all belong to the site. Only one program can hold ports 80 and 443, so several production sites on one server share one Caddy, as Ghost-CLI's sites shared one nginx. Everything -else stays each site's own: Ghost, MySQL, ActivityPub, analytics, backups, -updates and restores work exactly as they do for a site on its own. A local -site never uses the shared Caddy, and a server without one runs each -production site with its own Caddy, as before. +else stays each site's own: Ghost, MySQL, ActivityPub, analytics, its routes, +backups, updates and restores work exactly as they do for a site on its own. +A local site never uses the shared Caddy, and a server without one runs each +production site with its own Caddy on 80 and 443, as before. Set it up once, in a directory of its own, before the sites: ```bash mkdir ~/caddy && cd ~/caddy -curl -fsSL https://docker.ghost.org/install.sh | bash -s -- install --infra +curl -fsSL https://docker.ghost.org/install.sh | bash -s -- install --infra --email you@example.com ``` Then install each site as usual, each in its own directory. On a server with -the shared Caddy, `install --domain` joins it: the site has no Caddy of its -own, and its routes are written to the shared Caddy's -`caddy/sites/.caddy`, which Caddy validates and loads before the -site starts. Its first line, `# ghost-docker install `, names the -write, so a failed install removes the file only while it is still that -write's. A site installed `--no-caddy` does not join it. `` is the site's `COMPOSE_PROJECT_NAME`. A domain the -shared Caddy already serves, or a project that already has routes there, is -refused before anything is written. An existing site cannot be moved behind -the shared Caddy yet; it keeps its own Caddy, which needs 80 and 443, so set -the shared Caddy up on a server before its first production site. - -| Path, in the shared Caddy's directory | Owner | -| --- | --- | -| `caddy/sites/.caddy` | one per site behind it: written by that site's `install`, then yours | -| `caddy/custom/*.caddy`, `caddy/global/*.caddy` | yours, as for a single site | +the shared Caddy, `install --domain` joins it. A site installed `--no-caddy` +does not. A domain another site behind it already answers to is refused +before anything is written. An existing site cannot be moved behind the +shared Caddy yet; it keeps its own Caddy, which needs 80 and 443, so set the +shared Caddy up on a server before its first production site. + +### How it is connected -Edit a site's routes as described above, then reload the shared Caddy, in -its directory: +The shared Caddy names no site. It holds 80 and 443, obtains every site's +certificate, and passes each request, whole, to that site's own Caddy. + +- The shared Caddy is its own Compose project (`ghost-infra` unless `--name` + says otherwise), with a `compose.yml` and `caddy/Caddyfile` of its own. + `install --infra` creates the network `ghost-ingress`, which belongs to no + Compose project, so taking the shared Caddy down never takes it away from + the sites. +- Each site behind it selects the `shared-caddy` profile. It keeps a Caddy of + its own, the service `caddy-internal`, with the same `caddy/` directory as a + site on its own: its routes are `caddy/sites/site.caddy` in the site's + directory, yours to edit, and in the site's backups. That Caddy publishes + no port and serves plain HTTP (the routes' addresses are `http://`). +- The site's Caddy joins `ghost-ingress` under the site's domains, as + `.ghost.internal` (`INGRESS_HOST` and `INGRESS_ADMIN_HOST` in the + site's `.env`). The shared Caddy passes a request for `example.com` to + `example.com.ghost.internal`. Nothing else of the site is on that network: + not Ghost, not MySQL. +- A name no site has is never passed anywhere: `.ghost.internal` resolves on + that network only, and the request is answered `502`. + +So installing, changing or removing a site writes nothing in the shared +Caddy's directory and never reloads or restarts it. After editing a site's +routes, reload that site's Caddy, in the site's directory: ```bash -docker compose exec caddy caddy reload --config /etc/caddy/Caddyfile +docker compose exec caddy-internal caddy reload --config /etc/caddy/Caddyfile ``` -A configuration Caddy does not load is not applied: every site keeps being -served as before, and Caddy says why. `./ghost-docker check` in a site's -directory reports the shared Caddy's health, the site's routes file, and -HTTPS through it. `./ghost-docker list` shows the shared Caddy as `infra`, -and each site behind it as `shared-caddy`. - -`./ghost-docker remove`, in a site's directory, removes its routes file, -reloads the shared Caddy, and takes the site's containers down; no other site -is touched. The site's directory, data and backups stay until you delete them. -A site's backup holds its routes, read from the shared Caddy. Restoring it -keeps the routes the shared Caddy has for the project, since they may have -been edited since, and otherwise writes the backup's back: a site removed, or -moved to a new server with a shared Caddy of its own, comes back with them. -The shared Caddy's own directory has no backup; it holds no data, and -`install --infra` sets it up again, with your edits to its Caddyfile and -snippets yours to keep. - -### How it is connected +`docker compose down`, in a site's directory, takes that site away; no other +site is touched. `./ghost-docker check` in a site's directory reports the +site's own Caddy, the shared Caddy's health, and HTTPS through both. +`./ghost-docker list` shows the shared Caddy as `infra`, and each site behind +it as `shared-caddy`. -The shared Caddy is its own Compose project (`ghost-infra` unless `--name` -says otherwise), with the `infra` profile. `install --infra` creates the -network `ghost-ingress`, which belongs to no Compose project, so taking the -shared Caddy down never takes it away from the sites. Each site behind it -selects the `shared-caddy` profile, and its Ghost, ActivityPub and analytics join -`ghost-ingress` under their unique aliases (`ghost-:2368` and so -on), which is why routes always use them. MySQL and every one-shot job stay on -the site's own network. +`install` writes `caddy/global/shared-caddy.caddy` into a site behind the +shared Caddy. It tells the site's Caddy to trust the shared one, so Ghost +learns the visitor used HTTPS; without it Ghost redirects to HTTPS for ever. Ghost is still published on the site's loopback port, so a site behind the -shared Caddy can be reached without it, for example from your own proxy. +shared Caddy can be reached without it. + +Because each site carries its own Caddy, snippets and routes, sites on +different releases can route differently; a release that changes a snippet +changes it for the sites updated to it, and no others. + +### Certificates + +The shared Caddy obtains a site's certificate when its domain is first asked +for, not when the site is installed: the first request waits a few seconds +for it. It obtains one only for a name a site's Caddy answers to on +`ghost-ingress`, so a stranger pointing a domain at the server gets none. + +The ACME account is the shared Caddy's, for every site: `install --infra +--email` writes it to `caddy/global/acme.caddy` in its directory, and other +global options (a DNS provider, an internal CA) go beside it. A site's own +`install --email` is refused on a server with the shared Caddy, and its +routes, served over plain HTTP, take no `tls` directive. + +### More hostnames for a site + +A site's Caddy is reached only by the names it has on `ghost-ingress`. To +serve a site under another hostname, add it to the site's routes and give +the site's Caddy the name, in the site's `compose.override.yml`: + +```yaml +services: + caddy-internal: + networks: + ingress: + aliases: + - www.example.com.ghost.internal +``` + +Then `docker compose up -d` in the site's directory. + +Sites of your own that are not Ghost sites go in the shared Caddy's +`caddy/custom/`, as for a single site; a name with a block there is served by +that block and never passed on. ### What it trusts -The shared network is not isolation between sites. Every container on it can -reach every other site's Ghost, ActivityPub and analytics, and a site's bare -service names (`ghost`, `activitypub`) answer for every site on it, which is -why nothing routes by them. MySQL is never on it. Run sites behind one Caddy -only when you would trust them on one server anyway, as with Ghost-CLI. +The shared network is not isolation between sites' Caddies: every container +on it can reach every site's Caddy, and so every site as a visitor would. +Ghost, MySQL, ActivityPub and analytics are never on it. Run sites behind one +Caddy only when you would trust them on one server anyway, as with Ghost-CLI. + +The shared Caddy's `caddy_data` volume holds every site's certificates. -The shared Caddy's directory holds every site's routes, and its `caddy_data` -volume their certificates. Its `caddy/` is writable by whoever installed it, and the manager writes a site's -routes as the owner of `caddy/sites/`. +Two sites cannot share a domain. `install` refuses a domain another site's +Caddy has, running or stopped. A site taken down with `docker compose down` +holds no name until it is up again, so do not install another site on its +domain while you mean to bring it back. ### Restarting and updating it Restarting the shared Caddy (`docker compose restart`, or `down` then `up -d`, in its directory) interrupts every site behind it for those seconds, -and brings each back with its routes; certificates are kept in its -`caddy_data` volume. A site's own operations (`update`, `self-update`, -`backup`, `restore`, `docker compose down`) never restart it. +and brings each back; certificates are kept in its `caddy_data` volume. A +site's own operations (`update`, `self-update`, `backup`, `restore`, +`docker compose down`) never restart it. Its Caddy image is pinned in its `compose.yml`, by the release it runs. `./ghost-docker self-update`, in its directory, moves it to a newer release as for a site: untouched stack files are replaced, edited ones kept beside the release's `.new`, and the launcher re-pinned; then Caddy is recreated, which -restarts it as above, reloads its configuration (so a changed Caddyfile or -snippet is loaded even when the container was not recreated), and must pass -its health check. Its reloads and those of each site's `install` and `remove` -take turns, through a lock on `caddy/sites/` inside the container, so none -loads a configuration read before another site's routes were written. There is no backup, -because it holds no data. The release's images are pulled before any file is -written, so one that cannot be pulled changes nothing. Once files are written, -a site's reload can load them, so a failed update puts its files back and -reloads them into Caddy, or starts the previous Caddy again when it had been -recreated. It never updates the sites behind it, and their own -`self-update` never touches it. +restarts it as above, reloads its configuration (so a changed Caddyfile is +loaded even when the container was not recreated), and must pass its health +check. There is no backup, because it holds no data. The release's images are +pulled before any file is written, so one that cannot be pulled changes +nothing. A failed update puts its files back, and starts the previous Caddy +again when it had been recreated. It never updates the sites behind it, and +their own `self-update` never touches it; each site's own Caddy is updated +with the site. ### Capacity -Caddy itself costs little per site: a few routes, and a certificate it renews -in the background. What limits a server is each site's own Ghost and MySQL, -and ActivityPub and analytics where selected, which cost what they would on a +Each site's own Caddy uses little memory (about 15 MB idle), and the shared +one little more. What limits a server is each site's own Ghost and MySQL, and +ActivityPub and analytics where selected, which cost what they would on a server of their own ([configuration.md](configuration.md#site-modes-and-profiles) lists the optional services' costs). Size the server for the sum of them. Let's Encrypt limits how many certificates one account obtains per hour; -installing many sites at once can reach it, and Caddy retries later. +many new sites first visited at once can reach it, and Caddy retries later. diff --git a/docs/configuration.md b/docs/configuration.md index b66207b3..2c38d110 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -114,15 +114,16 @@ Site mode is selected through `COMPOSE_PROFILES`, and exactly one of `local`, | `local` | `ghost`, `db` | Ghost on `127.0.0.1:${GHOST_PORT}` | `local` | | `production` | `ghost`, `db`, `caddy` | Caddy on `${HTTP_PORT}` / `${HTTPS_PORT}` | `production` | | `no-caddy` | `ghost`, `db` | [Your own proxy](#your-own-proxy), to Ghost on `127.0.0.1:${GHOST_PORT}` | `production` | -| `shared-caddy` | `ghost`, `db` | [The shared Caddy](caddy.md#the-shared-caddy), on its network `${INGRESS_NETWORK}` | `production` | +| `shared-caddy` | `ghost`, `db`, `caddy-internal` | [The shared Caddy](caddy.md#the-shared-caddy), through the site's own Caddy, which publishes no port | `production` | A `no-caddy` or `shared-caddy` site is a production site in every other way: backup, restore, update, `self-update` and the upgrade supervisor treat it as -one, and production's rules below apply to it. The shared Caddy's own -directory selects `infra`, and nothing else: Caddy alone, with no site. Its -`.env` needs no Ghost or database settings, so compose.yml guards none of -them with `:?` (Compose interpolates the services a profile leaves out too); -`config validate` requires them for a site instead. +one, and production's rules below apply to it. Behind the shared Caddy, +`INGRESS_HOST` and `INGRESS_ADMIN_HOST` must be the hosts of `URL` and +`ADMIN_URL`: they name the site's Caddy on the shared Caddy's network, and +`config validate` reports a mismatch. The shared Caddy's own directory has a +`compose.yml` of its own and selects `infra`, and nothing else: Caddy alone, +with no site, and no Ghost or database settings. Optional per-site profiles are added to the same list and are purely additive. Adding one never changes the site mode: @@ -275,13 +276,9 @@ Each service has a unique alias suffixed with the project name: - `mailpit-${COMPOSE_PROJECT_NAME}:1025` (SMTP) Generated proxy routes and helper clients use these, never the bare service -name. Ghost, ActivityPub and analytics are also on the `ingress` network, under -the same aliases, which is all Caddy reaches: never MySQL. A site with its own -Caddy has an `ingress` network of its own. Behind the shared Caddy it is the -shared Caddy's, `ghost-ingress`, which `.env` names (`INGRESS_NETWORK`, with -`INGRESS_EXTERNAL=true`, since the manager created it and no Compose project -owns it); there every site's bare service names answer for every site, so -only the unique aliases identify one. `COMPOSE_PROJECT_NAME` is the site's stable identity and is kept +name. Behind [the shared Caddy](caddy.md#the-shared-caddy), the site's own +Caddy is also on the shared Caddy's network, `ghost-ingress`, as +`.ghost.internal`; nothing else of the site is. `COMPOSE_PROJECT_NAME` is the site's stable identity and is kept independent of the directory name. `install` chooses it once: the domain's in production, and locally the directory's name and a random pair (`ghost-local-blog-secondary-roadrunner`) that no project on the daemon has, diff --git a/docs/install.md b/docs/install.md index bbc3734c..ea5671aa 100644 --- a/docs/install.md +++ b/docs/install.md @@ -57,7 +57,7 @@ ghost-docker install [--local | --domain example.com [--admin-domain admin.examp [--channel stable|beta | --release vX.Y.Z] [--no-prompt] [--no-start] ghost-docker install --import BUNDLE [--name NAME] [--port 2368] [--with mailpit] [--no-prompt] [--no-start] ghost-docker install --import BUNDLE [--domain DOMAIN] [--admin-domain DOMAIN] [--email EMAIL | --no-caddy] [--no-start] -ghost-docker install --infra [--name NAME] [--channel stable|beta | --release vX.Y.Z] [--no-start] +ghost-docker install --infra [--name NAME] [--email you@example.com] [--channel stable|beta | --release vX.Y.Z] [--no-start] ``` | Option | Meaning | @@ -325,12 +325,15 @@ curl -fsSL https://docker.ghost.org/install.sh | bash -s -- install --domain sho ``` On a server with the shared Caddy, every production install joins it, except -one with `--no-caddy`, and its routes are written to the shared Caddy's -`caddy/sites/`. A domain it already -serves is refused. `./ghost-docker remove`, in a site's directory, removes its -routes and takes it down, leaving the other sites alone. A site installed with -a Caddy of its own cannot be moved behind the shared Caddy yet. The trust -model, restarts, updates and capacity are in +one with `--no-caddy`. The site keeps a Caddy and routes of its own, in its +own directory, which publishes no port; the shared Caddy obtains its +certificate when the domain is first asked for, and passes its requests on. +A domain another site behind it already answers to is refused. +`docker compose down`, in a site's directory, takes it down and leaves the +other sites and the shared Caddy alone. `--email` is given to `install +--infra`, once, for every site. A site installed with a Caddy of its own +cannot be moved behind the shared Caddy yet. How it is connected, +certificates, the trust model, restarts, updates and capacity are in [caddy.md](caddy.md#the-shared-caddy). ## Ports, and your existing proxy @@ -382,7 +385,6 @@ How ports are detected on each platform: [Ports](reference.md#ports). ./ghost-docker self-update # ghost-docker itself; see below ./ghost-docker backup # the databases, content and configuration, into backups/ ./ghost-docker restore backups/ -./ghost-docker remove # take the site down; its directory and data stay ``` `check` exits non-zero when anything is wrong. A new production site whose DNS @@ -392,8 +394,8 @@ is verified](reference.md#how-a-site-is-verified). The routes are a file you edit, `caddy/sites/site.caddy`, followed by `docker compose exec caddy caddy reload --config /etc/caddy/Caddyfile`; see -[caddy.md](caddy.md). Behind the shared Caddy, they are in its directory -instead, and it is reloaded there. +[caddy.md](caddy.md). Behind the shared Caddy, the site's Caddy is the +service `caddy-internal`, and is what you reload. ## update diff --git a/docs/reference.md b/docs/reference.md index e31c51aa..51ff231f 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -42,14 +42,15 @@ happens underneath them. yours from then on; see [caddy.md](caddy.md). With `--no-caddy`, nothing: the routing is your proxy's ([configuration.md](configuration.md#your-own-proxy)). On a server with [the shared Caddy](caddy.md#the-shared-caddy), the site - selects the `shared-caddy` profile instead of `production` and has no Caddy - of its own: the routes are written to the shared Caddy's - `caddy/sites/.caddy`, through its running container, as the owner - of that directory, then Caddy validates its whole configuration and - reloads. Before anything is written, a shared Caddy that is not running, a - project that already has routes there, and a domain it already serves are - refused; routes Caddy does not accept are removed again. A `--no-caddy` - site never joins the shared Caddy. + selects the `shared-caddy` profile instead of `production`: its own Caddy + runs as `caddy-internal`, publishing no port, its routes are written for + plain HTTP, and `caddy/global/shared-caddy.caddy` tells it to trust the + shared Caddy's forwarded headers. `.env` records the site's names on the + shared Caddy's network (`INGRESS_HOST`, `INGRESS_ADMIN_HOST`). Before + anything is written, a domain another site's Caddy has on that network is + refused, and so is `--email`, which is the shared Caddy's. Nothing is + written in the shared Caddy's directory. A `--no-caddy` site never joins + the shared Caddy. 8. **Metadata**: `.ghost-docker.json`, described in [architecture.md](architecture.md#installation-metadata). 9. **Start and verify**, unless `--no-start`: `docker compose up --wait`, so @@ -59,8 +60,8 @@ happens underneath them. running container is not readiness. **A failed installation removes what it created** — containers, network, -volumes, the data directories, `.env`, `ghost.env`, the metadata, the -written stack files and the site's routes in the shared Caddy — so the same command can simply be run again in the same +volumes, the data directories, `.env`, `ghost.env`, the metadata and the +written stack files — so the same command can simply be run again in the same directory. That covers a port conflict, a failed pull, a service that never becomes healthy, and a site that starts but cannot be reached. Before removing anything it prints the services' last log lines. @@ -68,32 +69,22 @@ anything it prints the services' last log lines. ### install --infra Sets up [the shared Caddy](caddy.md#the-shared-caddy) in an empty directory: -`compose.yml`, `caddy/` and the launcher, an `.env` selecting the `infra` -profile, and the network `ghost-ingress`, labelled with the directory and -project, which no Compose project owns. It takes no site options, and writes -no `ghost.env` or data directories: there is no Ghost. Its metadata records -the `infra` mode, no Ghost, and the stack files, for `self-update`. It refuses a -daemon that already has the network, and 80 and 443 held by a container. -Caddy must start and pass its health check; a failure removes everything, -the network included. Site commands (`check`, `backup`, `update`, `restore`, -`remove`, ...) refuse its directory; `config`, `info` and `self-update` work -there. Its `self-update` takes no backup and pauses no writers: it writes the -release's files, recreates Caddy and waits for its health check, and on a -failure puts the files back and starts the previous Caddy (see +its own `compose.yml` and `caddy/` (the payload's `infra/`), the launcher, an +`.env` selecting the `infra` profile, and the network `ghost-ingress`, +labelled with the directory and project, which no Compose project owns. +`--email` writes the ACME account to `caddy/global/acme.caddy`. It takes no +other site option, and writes no `ghost.env` or data directories: there is no +Ghost. Its metadata records the `infra` mode, no Ghost, and the stack files, +for `self-update`. It refuses a daemon that already has the network, 80 and +443 held by a container, and a checkout of the repository. Caddy must start +and pass its health check; a failure removes everything, the network +included. Site commands (`check`, `backup`, `update`, `restore`, ...) refuse +its directory; `config`, `info` and `self-update` work there. Its +`self-update` takes no backup and pauses no writers: it writes the release's +files, recreates Caddy and waits for its health check, and on a failure puts +the files back and starts the previous Caddy (see [caddy.md](caddy.md#restarting-and-updating-it)). -## remove - -`./ghost-docker remove [--yes]` takes the site in this directory down and -leaves everything else on the server as it was. Behind the shared Caddy, it -first removes the site's `caddy/sites/.caddy` there and reloads the -shared Caddy, which must be running. Then `docker compose down` removes the -site's containers and networks; its volumes, directory, data and backups -stay, and `docker compose up -d` starts it again (behind the shared Caddy, -once its routes are back). It asks first, at a terminal; without one it needs -`--yes`. It holds the site's lock, so it is refused while a backup, restore or -update runs. - ## How a site is verified Each service is judged by its own health check, which `up --wait` already @@ -109,7 +100,7 @@ Each answer is reported for what it is: | https | An HTTPS request to Caddy's container for Ghost's `/ghost/api/admin/site/`, with the domain as its server name and Host, as a browser asks. **serving** means this site's Ghost answered through Caddy: Ghost reports its site's URL, and that must be the site's `URL` (by either name, the canonical one, not the admin domain). It names the certificate's issuer and expiry; a certificate from a CA browsers do not trust (staging, or Caddy's internal CA) is a `warning`. **pending** means Caddy has no certificate for the name yet, so Ghost could not be asked through it: Caddy obtains one once the domain's DNS reaches this host, `./ghost-docker check` reports the change, and `docker compose logs caddy` shows each attempt. Caddy answering with something other than Ghost (a broken route, a 502), another site's Ghost (a route to the wrong upstream), or an out-of-date certificate, is an `ERROR`. | `ok`, `warning`, `note` or `ERROR` | | admin https | With an admin domain of its own: the same, for that name. Ghost reached by the admin domain still reports the site's `URL`, which is what is checked. On the site's domain, Ghost answering the Admin API path with a redirect to the admin domain counts as Ghost answering; the admin domain's own answer then names the site. | `ok`, `warning`, `note` or `ERROR` | | ingress | With `--no-caddy` (the `no-caddy` profile), in place of **caddy** and **https**: the site is served by your own proxy, which the manager cannot reach from its container, so it is not checked. The note names the URL and the loopback port the proxy must pass it to with `X-Forwarded-Proto: https`. | `note` | -| shared caddy, routes | Behind [the shared Caddy](caddy.md#the-shared-caddy), in place of **caddy**: the shared Caddy's health check, from its container, and that its `caddy/sites/.caddy` exists. A server without the shared Caddy's network is an `ERROR`. **https** then asks the shared Caddy, on its network. | `ok` or `ERROR` | +| shared caddy | Behind [the shared Caddy](caddy.md#the-shared-caddy), beside **caddy**, which is the site's own (`caddy-internal`): the shared Caddy's health check, from its container. A server without the shared Caddy's network is an `ERROR`. **https** then asks the shared Caddy, on its network, and so passes through both. | `ok` or `ERROR` | | mailpit | With `--with mailpit`: its health check. The check names `mailpit-${COMPOSE_PROJECT_NAME}:1025`, where Ghost sends mail. | `ok` or `ERROR` | | published ports | The ports Docker says it published. A container cannot reach the host's own loopback interface, so they are not checked from there (the **https** request goes to Caddy's container, not to the host's ports): opening the URL is that check. | `note` | @@ -402,7 +393,6 @@ self-update. Compose files you used with `-f` by hand, such as | `database/ghost.sql` | A `mysqldump` of Ghost's database, taken as the site's own database user in one consistent snapshot. | | `database/activitypub.sql` | ActivityPub's database, when the `activitypub` profile is on. | | `content.tar.gz` | The content directory, `data/ghost`: images, media, files, themes, settings. | -| `routes.caddy` | Behind the shared Caddy: the site's routes, its `caddy/sites/.caddy` there, without the marker line its install wrote. When the shared Caddy cannot be read, the backup warns and holds none. | | `site/` | `.env`, `ghost.env`, `.ghost-docker.json`, `compose.override.yml` and the overrides `COMPOSE_FILE` names, `caddy/sites/`, `caddy/custom/`, `caddy/global/` and, for a site installed from the image, the stack's files and the launcher the site ran. | A backup is **checked** before it counts as one: every dump is loaded into a @@ -415,8 +405,8 @@ is an error, not a backup:** `backup` exits `1` and leaves nothing in What a backup cannot hold is named in its manifest and in the summary: Caddy's certificates, which Caddy obtains again when the site starts (behind -the shared Caddy, its own configuration and certificates); the Tinybird -workspace and analytics data outside the site; Mailpit's inbox. +the shared Caddy, the shared Caddy and the certificates it holds); the +Tinybird workspace and analytics data outside the site; Mailpit's inbox. ### What a backup captures @@ -487,10 +477,9 @@ In order: project and busy ports are refused, named, and never stopped. The backup's configuration (for a clone, with the clone's `compose.yml`) is resolved outside the site, and must name exactly the images the backup - records and mount the data where restore loads it. Behind the shared - Caddy, it must be running; routes it already has for the project are kept, - and otherwise the backup must hold them, for domains it does not already - serve. Nothing has changed. + records and mount the data where restore loads it. A backup of a site + behind the shared Caddy is refused on a server that has none. Nothing has + changed. 2. **The lock**, then every image the backup records is pulled before anything stops, and each service that was running must get, by its image ID or a registry digest, the very image it ran. A reference that names another @@ -510,8 +499,6 @@ In order: 5. **The databases.** MySQL starts on an empty data directory, which creates the site's databases and user from the restored `.env`; each dump is loaded as the site's user, and every table's rows must match the manifest. - Behind the shared Caddy, the backup's routes, when it has none for the - project, are written into it, validated and loaded, as an install's are. 6. **Start and verify.** `up --wait`, then the site is verified through its ingress as `check` does. `.ghost-docker-restore/` is removed. diff --git a/infra/caddy/Caddyfile b/infra/caddy/Caddyfile new file mode 100644 index 00000000..17a773e5 --- /dev/null +++ b/infra/caddy/Caddyfile @@ -0,0 +1,49 @@ +# The shared Caddy: ports 80 and 443 and the certificates of every production +# site on this server. This file is tracked and should not be edited. +# +# It names no site. A request for example.com goes to whichever container +# answers to example.com.ghost.internal on the network ghost-ingress: that +# site's own Caddy, which holds its routes (caddy/sites/site.caddy in the +# site's directory). Installing, changing or removing a site changes nothing +# here, and needs no reload. +# +# Add global options (the ACME account's email, a DNS provider, ...) as .caddy +# files in caddy/global/, and sites of your own as .caddy files in +# caddy/custom/; a site named there is served by its own block, not passed on. +# After changing any of them: +# +# docker compose exec caddy caddy reload --config /etc/caddy/Caddyfile + +{ + # A certificate is obtained when a name is first asked for, and only for + # a name a site answers to (below). + on_demand_tls { + ask http://127.0.0.1:2020/ + } + + import /etc/caddy/global/*.caddy +} + +# Asked by Caddy itself before it obtains a certificate for ?domain=: allowed +# only when a site's Caddy is on the network under that name. +http://127.0.0.1:2020 { + bind 127.0.0.1 + + reverse_proxy {query.domain}.ghost.internal:80 { + handle_response { + respond 200 + } + } +} + +import /etc/caddy/custom/*.caddy + +# Every other name. `.ghost.internal` resolves on ghost-ingress only, so a +# name no site has is answered 502 and never passed to another host. +https:// { + tls { + on_demand + } + + reverse_proxy {host}.ghost.internal:80 +} diff --git a/infra/caddy/custom/README.md b/infra/caddy/custom/README.md new file mode 100644 index 00000000..4f1c8d81 --- /dev/null +++ b/infra/caddy/custom/README.md @@ -0,0 +1,22 @@ +# Custom Caddy sites + +Files matching `*.caddy` in this directory are imported into the shared +Caddy. Use them for sites on this server that are not Ghost sites behind it, +for example: + +```caddyfile +status.example.com { + reverse_proxy 172.17.0.1:9000 +} +``` + +A name with a block here is served by that block, never passed on to a Ghost +site. A Ghost site's own routes are in its own directory, in +`caddy/sites/site.caddy`. + +Reload Caddy after a change; it refuses a configuration that does not load and +keeps serving the previous one: + +```bash +docker compose exec caddy caddy reload --config /etc/caddy/Caddyfile +``` diff --git a/infra/caddy/global/README.md b/infra/caddy/global/README.md new file mode 100644 index 00000000..0baba6da --- /dev/null +++ b/infra/caddy/global/README.md @@ -0,0 +1,15 @@ +# Caddy global options + +Files matching `*.caddy` in this directory are imported into the shared +Caddy's global options block. They apply to every site behind it, for example: + +```caddyfile +# The ACME account, which receives Let's Encrypt's expiry notices. +email you@example.com +``` + +Reload Caddy after a change: + +```bash +docker compose exec caddy caddy reload --config /etc/caddy/Caddyfile +``` diff --git a/infra/compose.yml b/infra/compose.yml new file mode 100644 index 00000000..4c790ae1 --- /dev/null +++ b/infra/compose.yml @@ -0,0 +1,60 @@ +--- +# yaml-language-server: $schema=https://raw.githubusercontent.com/compose-spec/compose-spec/main/schema/compose-spec.json +# +# Ghost Docker — the shared Caddy: one Caddy holding ports 80 and 443 for +# several production sites on a server (docs/caddy.md#the-shared-caddy). +# +# `./ghost-docker install --infra` writes this file as compose.yml into a +# directory of its own, with caddy/ beside it. It runs Caddy alone. Each site +# behind it is a Compose project of its own, with its own Caddy on the network +# below; nothing here names a site. + +x-logging: &default-logging + driver: ${LOG_DRIVER:-json-file} + options: + max-size: ${LOG_MAX_SIZE:-10m} + max-file: "${LOG_MAX_FILE:-3}" + +services: + caddy: + image: caddy:2.10.2-alpine@sha256:953131cfea8e12bfe1c631a36308e9660e4389f0c3dfb3be957044d3ac92d446 + restart: ${RESTART_POLICY:-unless-stopped} + profiles: [infra] + labels: + org.ghost.docker.managed: "true" + org.ghost.docker.site: ${COMPOSE_PROJECT_NAME:-ghost-infra} + org.ghost.docker.mode: infra + org.ghost.docker.lifecycle: long-running + logging: *default-logging + ports: + - "${HTTP_PORT:-80}:80" + - "${HTTPS_PORT:-443}:443" + volumes: + - ./caddy:/etc/caddy + - caddy_data:/data + - caddy_config:/config + # Caddy is up and has loaded its configuration: its admin API answers. + # 127.0.0.1, not localhost, which busybox resolves to ::1 first. + healthcheck: + test: [CMD, wget, -q, -O, /dev/null, "http://127.0.0.1:2019/config/"] + interval: 30s + timeout: 10s + start_period: 30s + start_interval: 1s + retries: 5 + networks: + - ingress + +volumes: + # Every site's certificates. + caddy_data: + caddy_config: + +networks: + # `install --infra` creates it, and no Compose project owns it, so taking + # the shared Caddy down never takes it away from the sites. + ingress: + # Always ghost-ingress, which the manager finds the shared Caddy by; the + # integration tests alone name another. + name: ${INGRESS_NETWORK:-ghost-ingress} + external: true diff --git a/manager/Dockerfile b/manager/Dockerfile index 79340347..18c117e8 100644 --- a/manager/Dockerfile +++ b/manager/Dockerfile @@ -36,6 +36,7 @@ WORKDIR /opt/ghost-docker COPY compose.yml compose.ipv6.yml .env.example ghost.env.example ./ COPY caddy ./caddy COPY mysql-init ./mysql-init +COPY infra ./infra WORKDIR /opt/ghost-docker/manager COPY manager/src ./src COPY manager/templates ./templates @@ -81,6 +82,7 @@ COPY compose.yml compose.ipv6.yml .env.example ghost.env.example /opt/ghost-dock COPY caddy /opt/ghost-docker/stack/caddy COPY mysql-init /opt/ghost-docker/stack/mysql-init COPY tinybird /opt/ghost-docker/stack/tinybird +COPY infra /opt/ghost-docker/stack/infra # The launcher, which install copies into an image-mode site pinned to this # image's digest. COPY --chmod=0755 ghost-docker /opt/ghost-docker/launcher/ghost-docker diff --git a/manager/src/backup.ts b/manager/src/backup.ts index addd253c..e0648c00 100644 --- a/manager/src/backup.ts +++ b/manager/src/backup.ts @@ -23,14 +23,12 @@ import { DATABASE_NAME, MANIFEST_FILE, readBackupManifest, - ROUTES_FILE, SITE_FILES_DIR, type BackupManifest, } from './backup/manifest.ts'; import { compose, composeError, composeOverrides, composePs, composeUp } from './compose.ts'; import { runOnce } from './docker/client.ts'; -import { CliError, describeError } from './errors.ts'; -import { describeShared, findSharedCaddy, readRoutes, routesPath } from './shared.ts'; +import { CliError } from './errors.ts'; import { WriterPause } from './writers.ts'; import { atomicWrite, copyPresent, filesUnder, PRIVATE } from './fs.ts'; import { DATABASE_MS, tableCount, withSiteDatabase } from './import/database.ts'; @@ -179,53 +177,18 @@ export function siteOverrides(resolved: ResolvedSite): string[] { }); } -/** - * Behind the shared Caddy, the site's routes, copied into the backup so a - * restore can write them back. They are the shared Caddy's files, read - * through its container; one that cannot be read leaves the backup without - * them, with a warning, rather than failing it. - */ -async function captureRoutes(io: Io, project: string, partial: string): Promise { - try { - const shared = await findSharedCaddy(io); - if (shared === null) { - warn(io, 'routes', 'this server has no shared Caddy, so the backup holds no routes'); - return false; - } - const routes = await readRoutes(io, shared, project); - if (routes === null) { - warn( - io, - 'routes', - `${routesPath(shared, project)} does not exist, so the backup holds no routes`, - ); - return false; - } - atomicWrite(join(partial, ROUTES_FILE), routes, PRIVATE); - ok(io, 'routes', `${routesPath(shared, project)}, from ${describeShared(shared)}`); - return true; - } catch (failure) { - warn(io, 'routes', `${describeError(failure)}\n The backup holds no routes.`); - return false; - } -} - /** What the site has that a backup cannot hold, for the manifest and the summary. */ -function notIncluded(site: SiteFacts, routes: boolean): string[] { +function notIncluded(site: SiteFacts): string[] { const profiles = site.settings.get('COMPOSE_PROFILES') ?? ''; const lines: string[] = []; - if (site.layout === SHARED_CADDY_PROFILE) { - if (!routes) { - lines.push("its routes, which could not be read from the shared Caddy's caddy/sites/"); - } - lines.push( - "the shared Caddy's own configuration and its certificates, which are not the site's", - ); - } else if (site.layout === 'production') { + if (site.layout === 'production') { lines.push( "Caddy's certificates and state, which Caddy obtains again when the site starts", ); } + if (site.layout === SHARED_CADDY_PROFILE) { + lines.push('the shared Caddy and the certificates it holds, which are not the site\u2019s'); + } if (hasProfile(profiles, 'analytics')) { lines.push( 'the Tinybird workspace and the analytics data held outside the site, which are not part of it', @@ -513,10 +476,6 @@ export async function takeBackup({ `${copied} files and directories: configuration, metadata, Caddy${overrides.length > 0 ? `, ${overrides.join(', ')}` : ''}`, ); - const routes = - site.layout === SHARED_CADDY_PROFILE && - (await captureRoutes(io, metadata.site.project, partial)); - // Captured: the site runs again before the slower checks, unless the // caller keeps it paused. await resume(); @@ -602,9 +561,8 @@ export async function takeBackup({ running: ran, databases: manifestDatabases, content: { file: CONTENT_ARCHIVE, entries }, - ...(routes ? { routes: ROUTES_FILE } : {}), files, - notIncluded: notIncluded(site, routes), + notIncluded: notIncluded(site), }; atomicWrite( join(partial, MANIFEST_FILE), @@ -642,11 +600,7 @@ export async function readBackup(io: Io, root: string): Promise throw new CliError(`${read.reason}. Nothing has been changed.`); } const { manifest } = read; - const wanted = [ - manifest.content.file, - ...manifest.databases.map((database) => database.file), - ...(manifest.routes === undefined ? [] : [manifest.routes]), - ]; + const wanted = [manifest.content.file, ...manifest.databases.map((database) => database.file)]; for (const file of wanted) { if (!(file in manifest.files)) { throw new CliError( diff --git a/manager/src/backup/manifest.ts b/manager/src/backup/manifest.ts index f6799de2..a04ba748 100644 --- a/manager/src/backup/manifest.ts +++ b/manager/src/backup/manifest.ts @@ -6,9 +6,6 @@ import { readIfExists } from '../fs.ts'; export const BACKUP_FORMAT = 'ghost-docker-backup'; export const BACKUP_VERSION = 1; - -/** Behind the shared Caddy, the site's routes, in the backup (manifest `routes`). */ -export const ROUTES_FILE = 'routes.caddy'; export const MANIFEST_FILE = 'manifest.json'; /** The content directory, as a gzipped tarball of its contents. */ export const CONTENT_ARCHIVE = 'content.tar.gz'; @@ -88,12 +85,6 @@ export const backupManifestSchema = z.strictObject({ file: inside, entries: z.number().int().nonnegative(), }), - /** - * Behind the shared Caddy: the site's routes, as its caddy/sites/.caddy - * held them, without the marker line its install wrote. A restore writes - * them back when the shared Caddy has none for the project. - */ - routes: inside.optional(), /** SHA-256 of every file in the backup but this one, by path. */ files: z.record(inside, z.string().regex(/^[0-9a-f]{64}$/)), /** What the site has that this backup does not, for a person to read. */ diff --git a/manager/src/caddy.ts b/manager/src/caddy.ts index 1b5fecf9..4b8c5d93 100644 --- a/manager/src/caddy.ts +++ b/manager/src/caddy.ts @@ -4,6 +4,7 @@ import { readFileSync } from 'node:fs'; import { join } from 'node:path'; import { atomicWrite } from './fs.ts'; +import { INTERNAL_CADDY } from './site.ts'; export const SITE_FILE = join('caddy', 'sites', 'site.caddy'); const HOSTED_ACTIVITYPUB = 'https://ap.ghost.org'; @@ -23,6 +24,11 @@ export interface RouteOptions { /** The ACME account, rendered as `tls `; empty for none. */ readonly email: string; readonly activitypub: boolean; + /** + * Behind the shared Caddy (shared.ts), which holds the certificates: the + * site's own Caddy serves these routes over plain HTTP. + */ + readonly shared?: boolean; } /** The routes' template, with `{{name}}` placeholders. */ @@ -50,16 +56,39 @@ export function fill(template: string, values: Readonly>) export function renderRoutes(site: RouteOptions): string { return fill(readFileSync(TEMPLATE, 'utf8'), { project: site.project, - addresses: [site.domain, site.adminDomain].filter(Boolean).join(', '), - tls: site.email ? `tls ${site.email}` : '# tls you@example.com', + service: site.shared ? INTERNAL_CADDY : 'caddy', + addresses: [site.domain, site.adminDomain] + .filter(Boolean) + .map((name) => (site.shared ? `http://${name}` : name)) + .join(', '), + tls: site.shared + ? "# Not here: the shared Caddy obtains this site's certificates." + : site.email + ? `tls ${site.email}` + : '# tls you@example.com', activitypub: site.activitypub ? `activitypub-${site.project}:8080` : HOSTED_ACTIVITYPUB, adminDomain: site.adminDomain, }); } +/** + * Behind the shared Caddy, the site's own Caddy is told to trust it, so the + * `X-Forwarded-Proto: https` it sends reaches Ghost, which otherwise redirects + * to HTTPS for ever. Written once by `install`, beside the routes. + */ +export const SHARED_GLOBAL_FILE = join('caddy', 'global', 'shared-caddy.caddy'); +export const SHARED_GLOBAL = + '# Written by ./ghost-docker install for a site behind the shared Caddy, whose\n' + + '# forwarded headers (X-Forwarded-Proto: https, the visitor\u2019s address) this\n' + + '# site\u2019s Caddy passes on to Ghost. Without it Ghost redirects to HTTPS for ever.\n' + + 'servers {\n\ttrusted_proxies static private_ranges\n}\n'; + /** Write the routes into the site. Returns the path written. */ export function writeRoutes(dir: string, site: RouteOptions): string { const path = join(dir, SITE_FILE); atomicWrite(path, renderRoutes(site), 0o644); + if (site.shared) { + atomicWrite(join(dir, SHARED_GLOBAL_FILE), SHARED_GLOBAL, 0o644); + } return path; } diff --git a/manager/src/cli.ts b/manager/src/cli.ts index 44cab024..fd010a10 100644 --- a/manager/src/cli.ts +++ b/manager/src/cli.ts @@ -9,7 +9,6 @@ import { backupCommand, restoreCommand } from './commands/backup.ts'; import { getCommand, setCommand, validateCommand } from './commands/config.ts'; import { doctorCommand } from './commands/doctor.ts'; import { installCommand } from './commands/install.ts'; -import { removeCommand } from './commands/remove.ts'; import { checkCommand, infoCommand, listCommand } from './commands/site.ts'; import { selfUpdateCommand } from './commands/self-update.ts'; import { supervisorRunCommand } from './commands/supervisor.ts'; @@ -32,7 +31,6 @@ const COMMANDS: Record = { 'supervisor run': supervisorRunCommand, backup: backupCommand, restore: restoreCommand, - remove: removeCommand, version: versionCommand, doctor: doctorCommand, help: defineCommand({ diff --git a/manager/src/commands/install.ts b/manager/src/commands/install.ts index f26c61a6..019ffd0d 100644 --- a/manager/src/commands/install.ts +++ b/manager/src/commands/install.ts @@ -1,7 +1,7 @@ // `install`: a local or production site, configured, started and verified. // A production site has Caddy, or with --no-caddy, the operator's own proxy; // with --infra, the shared Caddy (shared.ts), and on a server that has one, a -// production site behind it. +// production site's own Caddy is put behind it. // `run` takes the parts in order, each a function of its own: refusals that // need nothing; with --import, the bundle (import.ts); preflight, ports, the // exact Ghost image and a free project name, still changing nothing; then @@ -11,7 +11,7 @@ import { randomBytes } from 'node:crypto'; import { existsSync, readdirSync } from 'node:fs'; import { join } from 'node:path'; -import { ACME_EMAIL, isHostname, renderRoutes, SITE_FILE, writeRoutes } from '../caddy.ts'; +import { ACME_EMAIL, isHostname, SHARED_GLOBAL_FILE, SITE_FILE, writeRoutes } from '../caddy.ts'; import { ALL_PROFILES, compose, composePs, upAndWait } from '../compose.ts'; import { createNetwork, MANAGED_LABEL } from '../docker/client.ts'; import { z } from 'zod'; @@ -37,6 +37,7 @@ import { makeDirectories, managerPin, payloadConflicts, + infraStackDir, payloadFiles, stackDir, writeLauncher, @@ -48,8 +49,8 @@ import { ENV_FILE, generatedSettings, GHOST_ENV_FILE, - ingressSettings, INFRA_PROFILE, + INTERNAL_CADDY, MAILPIT_DATA_DIR, SHARED_CADDY_PROFILE, META_FILE, @@ -59,7 +60,6 @@ import { type SiteMode, } from '../site.ts'; import { - addRoutes, describeShared, findSharedCaddy, INFRA_DIR_LABEL, @@ -67,8 +67,6 @@ import { INFRA_PROJECT_LABEL, INGRESS_NETWORK, refuseTaken, - routesPath, - runningCaddy, type SharedCaddy, } from '../shared.ts'; import { takenPorts } from '../ports.ts'; @@ -271,7 +269,6 @@ function infraConflict(flags: Flags): string | null { ['--domain', flags.domain !== undefined], ['--admin-domain', flags.adminDomain !== undefined], ['--no-caddy', flags.noCaddy], - ['--email', flags.email !== undefined], ['--port', flags.port !== undefined], ['--version', flags.version !== undefined], ['--ghost-image', flags.ghostImage !== undefined], @@ -522,7 +519,12 @@ async function prepare( // installed behind it. const shared = intent.layout === 'production' ? await findSharedCaddy(io) : null; if (shared !== null) { - runningCaddy(shared); + if (flags.email !== undefined) { + throw new UsageError( + `--email is the ACME account of the Caddy that obtains certificates, which for this site is\n` + + ` ${describeShared(shared)}: set it there (caddy/global/, docs/caddy.md#the-shared-caddy).`, + ); + } ok(io, 'shared caddy', `${describeShared(shared)} will serve this site`); } const layout: Layout = shared === null ? intent.layout : SHARED_CADDY_PROFILE; @@ -676,7 +678,7 @@ async function createSite(site: Site, created: Created, importing: Importing | n makeDataDirectories(site, created, importing !== null); await validateConfiguration(site); await importing?.load(created, site.profiles, site.ghost.version); - await writeSiteRoutes(site, created); + writeSiteRoutes(site, created); writeSiteMetadata(site, created); if (site.flags.noStart) { site.io.stdout('\nNot starting: --no-start was given.\n'); @@ -698,7 +700,7 @@ function writeStack(site: Site, created: Created) { ok( io, 'stack files', - `compose.yml, ${site.layout === 'production' ? 'caddy/, mysql-init/, tinybird/' : site.layout === SHARED_CADDY_PROFILE ? 'mysql-init/, tinybird/' : 'mysql-init/'} from the manager image`, + `compose.yml, ${site.layout === 'production' || site.layout === SHARED_CADDY_PROFILE ? 'caddy/, mysql-init/, tinybird/' : 'mysql-init/'} from the manager image`, ); writeLauncher(dir, io.env, { image: pin!, channel: site.release.channel }, created); created.save(); @@ -718,7 +720,6 @@ function writeEnv(site: Site, created: Created) { port: site.port, mailpitPort: site.mailpitPort, ports: { http: String(PRODUCTION_PORTS.http), https: String(PRODUCTION_PORTS.https) }, - ingress: site.shared?.network ?? null, database: { user: 'ghost', password: secret(), rootPassword: secret() }, }); if (intent.services.includes('supervisor')) { @@ -803,44 +804,33 @@ async function validateConfiguration({ io, dir, intent }: Site) { } /** - * A production site's Caddy routes, in its own caddy/sites/, or behind the - * shared Caddy in the shared Caddy's, which then validates and reloads them. - * Written once; from here on the file is the operator's. + * A production site's Caddy routes. Behind the shared Caddy they are served + * over plain HTTP, and the site's Caddy is told to trust it (caddy.ts). + * Written once; from here on the files are the operator's. */ -async function writeSiteRoutes( - { io, dir, layout, project, intent, shared }: Site, - created: Created, -) { +function writeSiteRoutes({ io, dir, layout, project, intent }: Site, created: Created) { if (layout !== 'production' && layout !== SHARED_CADDY_PROFILE) { return; } const { domain, adminDomain, email, services } = intent; - const routes = { + const shared = layout === SHARED_CADDY_PROFILE; + created.file(join(dir, SITE_FILE)); + if (shared) { + created.file(join(dir, SHARED_GLOBAL_FILE)); + } + writeRoutes(dir, { project, domain, adminDomain, email, activitypub: services.includes('activitypub'), - }; - const names = [domain, adminDomain].filter(Boolean).join(' and '); - if (shared !== null) { - // Claimed once written: a file another installation wrote is refused, never removed. - await io.busy('Adding the routes to the shared Caddy', () => - addRoutes(io, shared, project, renderRoutes(routes), (token) => { - created.routes = token ?? false; - created.save(); - }), - ); - ok( - io, - 'routes', - `${routesPath(shared, project)}: routes for ${names}, loaded by the shared Caddy; yours to edit`, - ); - return; - } - created.file(join(dir, SITE_FILE)); - writeRoutes(dir, routes); - ok(io, SITE_FILE, `routes for ${names}; yours to edit`); + shared, + }); + ok( + io, + SITE_FILE, + `routes for ${[domain, adminDomain].filter(Boolean).join(' and ')}${shared ? ', served to the shared Caddy over HTTP' : ''}; yours to edit`, + ); } function writeSiteMetadata(site: Site, created: Created) { @@ -888,6 +878,9 @@ async function startAndVerify({ io, dir, layout }: Site, created: Created) { // --- The shared Caddy ------------------------------------------------------------ +/** The shared Caddy's ACME account, written when --email names one. */ +const ACME_FILE = join('caddy', 'global', 'acme.caddy'); + /** * `install --infra`: the shared Caddy, alone, in its own directory and * project, on a network of its own that each production site installed after @@ -905,26 +898,36 @@ async function installInfra(target: Target, flags: Flags, requested: Requested): ` longer holds it, remove the network first: docker network rm ${existing.network}. Nothing has been changed.`, ); } + if (clone) { + throw new CliError( + 'the shared Caddy is installed from the manager image, into a directory of its own, and this\n' + + ' directory is a checkout of the repository. Nothing has been changed.', + ); + } + const stack = infraStackDir(io.env); await preflight(io, context); await sitePorts(io, INFRA_PROFILE, undefined, false); - const pin = clone - ? null - : await io.busy('Resolving the manager image', () => managerPin(io, context)); + const pin = await io.busy('Resolving the manager image', () => managerPin(io, context)); const project = flags.name ?? INFRA_PROJECT; await refuseForeignProject(io, project, dir); const created = new Created(io, context, dir); try { heading(io, 'Writing the shared Caddy'); - if (!clone) { - const files = payloadFiles(target.stack, INFRA_PROFILE); - writePayload(dir, target.stack, files, created); - ok(io, 'stack files', 'compose.yml and caddy/ from the manager image'); - writeLauncher(dir, io.env, { image: pin!, channel: release.channel }, created); - ok(io, 'ghost-docker', `the launcher, pinned to ${pin!}`); + writePayload(dir, stack, payloadFiles(stack), created); + ok(io, 'stack files', 'compose.yml and caddy/ from the manager image'); + writeLauncher(dir, io.env, { image: pin, channel: release.channel }, created); + ok(io, 'ghost-docker', `the launcher, pinned to ${pin}`); + if (flags.email !== undefined) { + const account = join(dir, ACME_FILE); + created.file(account); + atomicWrite( + account, + `# The ACME account, which receives Let's Encrypt's expiry notices.\nemail ${flags.email}\n`, + 0o644, + ); + ok(io, ACME_FILE, `the ACME account ${flags.email}; yours to edit`); } - // Where the members' routes go; Caddy mounts caddy/ whole. - makeDirectories(join(dir, 'caddy', 'sites'), created.directories); const path = join(dir, ENV_FILE); created.file(path); atomicWrite( @@ -938,10 +941,9 @@ async function installInfra(target: Target, flags: Flags, requested: Requested): RESTART_POLICY: 'unless-stopped', HTTP_PORT: String(PRODUCTION_PORTS.http), HTTPS_PORT: String(PRODUCTION_PORTS.https), - ...ingressSettings(INGRESS_NETWORK), }), - '# The shared Caddy: Caddy alone, serving the production sites on this server.\n' + - '# Their routes are in caddy/sites/, one file each; see docs/caddy.md.\n', + '# The shared Caddy: Caddy alone, holding ports 80 and 443 for the production sites on\n' + + '# this server. Each site keeps its routes in its own directory; see docs/caddy.md.\n', ), PRIVATE, ); @@ -954,13 +956,13 @@ async function installInfra(target: Target, flags: Flags, requested: Requested): }); // Only now: one another installation created meanwhile is not this one's to remove. created.network = INGRESS_NETWORK; - ok(io, 'network', `${INGRESS_NETWORK}, which the services of each site behind it join`); + ok(io, 'network', `${INGRESS_NETWORK}, which the Caddy of each site behind it joins`); created.file(join(dir, META_FILE)); writeMetadata( dir, infraMetadata({ - channel: clone ? null : release.channel, - source: clone ? 'checkout' : 'image', + channel: release.channel, + source: 'image', stack: { version: release.version, image: pin }, project, dir, @@ -1022,8 +1024,8 @@ async function installInfra(target: Target, flags: Flags, requested: Requested): ...(flags.noStart ? [] : [ - './ghost-docker install --domain example.com: it joins this Caddy, and its routes', - 'are written to caddy/sites/ here.', + './ghost-docker install --domain example.com: its own Caddy joins this one, which', + 'obtains its certificate when the domain is first asked for.', ]), '', ].join('\n'), @@ -1130,7 +1132,7 @@ function printSummary(site: Site, importing: Importing | null) { ...(site.shared === null ? [] : [ - ` Routes ${routesPath(site.shared, site.project)}, served by the shared Caddy`, + ` Ingress ${describeShared(site.shared)}, through this site's ${INTERNAL_CADDY}`, ]), ...(ghostChannelOf(ghost.image) === 'nightly' ? [ diff --git a/manager/src/commands/remove.ts b/manager/src/commands/remove.ts deleted file mode 100644 index e5e67b0d..00000000 --- a/manager/src/commands/remove.ts +++ /dev/null @@ -1,111 +0,0 @@ -// `remove`: a site taken down, and behind the shared Caddy, its routes taken -// out of it, so every other site behind it is left as it was. The site's -// directory, data and backups stay, for the operator to keep or delete. -import { z } from 'zod'; -import { defineCommand, flag } from '../command.ts'; -import { ALL_PROFILES, composeDown, composeError } from '../compose.ts'; -import { CliError, EXIT, UsageError } from '../errors.ts'; -import type { Io } from '../io.ts'; -import { acquireLock } from '../lock.ts'; -import { refuseForeignProject } from '../project.ts'; -import { ok } from '../report.ts'; -import { - describeShared, - findSharedCaddy, - INGRESS_NETWORK, - removeRoutes, - routesPath, - runningCaddy, -} from '../shared.ts'; -import { SHARED_CADDY_PROFILE } from '../site.ts'; -import { installedSite } from './common.ts'; - -export const removeCommand = defineCommand({ - brief: 'Take the site down, and behind the shared Caddy, remove its routes from it. Its directory and data stay. See docs/install.md.', - options: z.object({ - yes: flag('Remove the site without asking first.'), - }), - async run(flags, _positionals, io) { - const { site } = installedSite(io); - const dir = site.dir; - const project = site.settings.get('COMPOSE_PROJECT_NAME') || ''; - await refuseForeignProject(io, project, dir); - const shared = site.layout === SHARED_CADDY_PROFILE ? await findSharedCaddy(io) : null; - if (site.layout === SHARED_CADDY_PROFILE && shared === null) { - // Its routes may still be in the shared Caddy's directory, which only - // the running shared Caddy lets the manager change. - throw new CliError( - `this site is behind the shared Caddy, and this server has none (no ${INGRESS_NETWORK} network),\n` + - ' so its routes cannot be removed. Start the shared Caddy and run this again, or take the\n' + - ' site down alone with docker compose down and remove its routes file by hand.\n' + - ' Nothing has been changed.', - ); - } - if (shared !== null) { - runningCaddy(shared); - } - await confirm(io, dir, project, flags.yes); - - const lock = acquireLock(dir, 'remove'); - try { - if (shared !== null) { - await io.busy('Removing the routes from the shared Caddy', () => - removeRoutes(io, shared, project), - ); - ok( - io, - 'routes', - `${routesPath(shared, project)} removed; ${describeShared(shared)} reloaded without them`, - ); - } - const down = await io.busy("Stopping and removing the site's containers", () => - composeDown(io, dir, { profiles: ALL_PROFILES }), - ); - if (down.exitCode !== 0) { - throw new CliError( - `docker compose down failed: ${composeError(down, 4)}\n` + - (shared === null - ? '' - : ` Its routes are already gone from ${describeShared(shared)}, so the site is not\n` + - ' served until this finishes.\n') + - ' Run it again in this directory once the cause is fixed.', - ); - } - ok(io, 'services', `the containers and networks of ${project} are removed`); - } finally { - lock.release(); - } - io.stdout( - `\nThe site is removed. ${dir} still holds its configuration, data and backups:\n` + - 'docker compose up -d starts it again' + - (shared === null - ? '' - : `, once its routes are back in ${routesPath(shared, project)}`) + - '.\nTo delete it for good, remove the directory (with sudo: MySQL owns data/mysql).\n', - ); - return EXIT.ok; - }, -}); - -/** Taking a site down is never a surprise: it is asked, or --yes says so. */ -async function confirm(io: Io, dir: string, project: string, yes: boolean) { - if (yes) { - return; - } - if (io.prompt === null) { - throw new UsageError( - `remove takes down the site in ${dir} (${project}).\n` + - ' Run it again with --yes to go ahead. Nothing has been changed.', - ); - } - const answer = await io.prompt.choose( - `Take down ${project} and remove its containers? Its directory and data stay.`, - [ - { name: 'No, change nothing', value: 'no' }, - { name: 'Yes, remove the site', value: 'yes' }, - ], - ); - if (answer !== 'yes') { - throw new CliError('the removal was cancelled. Nothing has been changed.'); - } -} diff --git a/manager/src/commands/self-update.ts b/manager/src/commands/self-update.ts index 398775da..7a7cbaf3 100644 --- a/manager/src/commands/self-update.ts +++ b/manager/src/commands/self-update.ts @@ -19,7 +19,6 @@ import { requireValid } from '../config.ts'; import type { Context } from '../context.ts'; import { CliError, describeError, EXIT, UsageError } from '../errors.ts'; import { refuseForeignProject } from '../project.ts'; -import { RELOAD } from '../shared.ts'; import { atomicWrite } from '../fs.ts'; import type { Io } from '../io.ts'; import { isReleasedMainLayout, migrateReleasedMain } from '../legacy.ts'; @@ -37,6 +36,7 @@ import { LAUNCHER, launcherContent, managerPin, + infraStackDir, payloadFiles, sha256, stackDir, @@ -404,7 +404,8 @@ function refuseCheckouts(source: AnyMetadata['source'], running: Context['source * certificates in a volume `up` keeps, so there is no backup, and a failure * puts the files back and starts the previous Caddy again: nothing it ran on * the new files can have changed anything the old ones depend on. Every site - * behind it is unreachable while Caddy restarts, and updates on its own. + * behind it is unreachable while Caddy restarts, and updates on its own; none + * of them writes anything here. */ async function updateInfra( io: Io, @@ -434,7 +435,7 @@ async function updateInfra( if (typeof decided === 'object') { throw new CliError(`${decided.unordered}. Nothing has been changed.`); } - const stack = stackDir(io.env); + const stack = infraStackDir(io.env); const payload = planPayload(dir, stack, INFRA_PROFILE, metadata.payload); if (check) { io.stdout( @@ -471,9 +472,7 @@ async function updateInfra( io.stdout( `Updating the shared Caddy from ${describeStack(from)} to ${describeStack(to)}\n`, ); - // Before any file is written: a site's install or remove reloads the - // shared Caddy from this directory's files at any moment, so a written - // file is live from then on, and a failure after it needs a reload. + // Before any file is written, so one that cannot be pulled changes nothing. heading(io, 'Pulling the release’s images'); const pull = await io.busy( 'Pulling the images this release names', @@ -491,12 +490,7 @@ async function updateInfra( } ok(io, 'images', 'pulled, while Caddy kept running'); heading(io, 'Keeping the current files'); - // Not the sites' routes: the update never writes them, and a site - // installed meanwhile adds its own, which putting files back would lose. - const snapshot = new Snapshot( - dir, - touched(metadata, payload).filter((path) => path !== join('caddy', 'sites')), - ); + const snapshot = new Snapshot(dir, touched(metadata, payload)); snapshot.take(); ok(io, UPDATE_DIR, 'the configuration, the metadata and the files this update writes'); let started = false; @@ -526,26 +520,23 @@ async function updateInfra( (started ? ' Caddy may be stopped until then.' : ''), ); } - try { - if (started) { + // Nothing loads the written files before Caddy is restarted on them. + if (started) { + try { await caddyUp(io, dir, `Starting ${describeStack(from)}'s Caddy again`); - } else { - // Never restarted, but a site's reload may have loaded the - // written files: load the ones put back. - await reloadCaddy(io, dir); + } catch (again) { + throw new CliError( + `the files are ${describeStack(from)}'s again, but Caddy did not start on them: ${describeError(again)}\n` + + ' Sites behind it may be unreachable, or served by the release that failed, until it\n' + + ` does: docker compose up -d, then docker compose exec caddy ${RELOAD},\n` + + ` and docker compose logs caddy, in ${dir}. The files as they were are in ${UPDATE_DIR}/files;\n` + + ` remove ${UPDATE_DIR} once Caddy runs on them.`, + ); } - } catch (again) { - throw new CliError( - `the files are ${describeStack(from)}'s again, but Caddy did not ${started ? 'start on' : 'load'} them: ${describeError(again)}\n` + - ' Sites behind it may be unreachable, or served by the release that failed, until it\n' + - ` does: docker compose up -d, then docker compose exec caddy ${RELOAD.join(' ')},\n` + - ` and docker compose logs caddy, in ${dir}. The files as they were are in ${UPDATE_DIR}/files;\n` + - ` remove ${UPDATE_DIR} once Caddy runs on them.`, - ); } snapshot.remove(); throw new CliError( - `the update failed; the shared Caddy is back on ${describeStack(from)}${started ? ', and running' : ', with its configuration loaded again'}.`, + `the update failed; the shared Caddy is back on ${describeStack(from)}${started ? ', and running' : ', which it never stopped running'}.`, ); } snapshot.remove(); @@ -559,6 +550,8 @@ async function updateInfra( return EXIT.ok; } +const RELOAD = 'caddy reload --config /etc/caddy/Caddyfile'; + /** `up --wait`, and Caddy healthy by its own check. */ async function caddyUp(io: Io, dir: string, spinner: string): Promise { await upAndWait(io, dir, spinner); @@ -576,8 +569,7 @@ async function caddyUp(io: Io, dir: string, spinner: string): Promise { async function reloadCaddy(io: Io, dir: string): Promise { const reload = await io.busy( 'Loading the configuration', - // One at a time with the sites' route changes (shared.ts RELOAD). - () => compose(io, { dir })`exec -T caddy ${[...RELOAD]}`, + () => compose(io, { dir })`exec -T caddy ${RELOAD.split(' ')}`, ); if (reload.exitCode !== 0) { throw new CliError( diff --git a/manager/src/commands/site.ts b/manager/src/commands/site.ts index 2f3a7b60..6ac8feb8 100644 --- a/manager/src/commands/site.ts +++ b/manager/src/commands/site.ts @@ -14,10 +14,11 @@ import { describeMetadata, readMetadata } from '../meta.ts'; import { foreignProject, PROJECT_LABEL } from '../project.ts'; import { failed, printChecks, type Check } from '../report.ts'; import { imageDrift, observeSite, resolveSite, type ResolvedSite } from '../resolved.ts'; -import { INGRESS_NETWORK } from '../shared.ts'; +import { SERVICE_LABEL } from '../shared.ts'; import { hasProfile, INFRA_PROFILE, + INTERNAL_CADDY, SHARED_CADDY_PROFILE, readSettings, RESTORE_DIR, @@ -317,20 +318,17 @@ export const listCommand = defineCommand({ io.stderr('error: docker compose ls failed\n'); return EXIT.failure; } - // The shared Caddy's mode is infra; a production site any of whose - // containers is on its network is behind it. + // The shared Caddy's mode is infra; a production site with a Caddy of + // its own for the shared one to reach is behind it. const modes = new Map(); for (const container of containers) { const project = container.labels[PROJECT_LABEL] ?? ''; - const mode = container.labels['org.ghost.docker.mode'] ?? ''; + const behind = + modes.get(project) === SHARED_CADDY_PROFILE || + container.labels[SERVICE_LABEL] === INTERNAL_CADDY; modes.set( project, - mode === INFRA_PROFILE - ? INFRA_PROFILE - : modes.get(project) === SHARED_CADDY_PROFILE || - (mode === 'production' && container.networks.includes(INGRESS_NETWORK)) - ? SHARED_CADDY_PROFILE - : mode, + behind ? SHARED_CADDY_PROFILE : (container.labels['org.ghost.docker.mode'] ?? ''), ); } const sites = projects @@ -347,8 +345,8 @@ export const listCommand = defineCommand({ } if ([...modes.values()].includes(SHARED_CADDY_PROFILE)) { io.stdout( - `\n${SHARED_CADDY_PROFILE} is a production site behind the shared Caddy (${INFRA_PROFILE}), which serves\n` + - "its routes from a file named for it in the shared Caddy's caddy/sites/.\n", + `\n${SHARED_CADDY_PROFILE} is a production site behind the shared Caddy (${INFRA_PROFILE}), which holds\n` + + 'ports 80 and 443 and passes each request to the site\u2019s own Caddy.\n', ); } } diff --git a/manager/src/config.ts b/manager/src/config.ts index d2df7432..ebc2ff97 100644 --- a/manager/src/config.ts +++ b/manager/src/config.ts @@ -10,7 +10,6 @@ import { CliError } from './errors.ts'; import { modeOf, readIfExists } from './fs.ts'; import type { Io } from './io.ts'; import { ok, type Check } from './report.ts'; -import { INGRESS_NETWORK } from './shared.ts'; import { COMPOSE_OVERRIDE_FILE, ENV_EXAMPLE_FILE, @@ -38,10 +37,11 @@ export interface Finding { /** Keys required in `.env` that nothing else would catch, by mode. */ export const REQUIRED_KEYS = { common: ['COMPOSE_PROFILES', 'COMPOSE_PROJECT_NAME', 'SITE_MODE', 'PROJECT_DIR'], - /** compose.yml does not `:?`-guard these: the shared Caddy's directory has none. */ - site: ['GHOST_VERSION', 'URL', 'DATABASE_PASSWORD', 'DATABASE_ROOT_PASSWORD'], - /** Behind the shared Caddy, and in its own directory. */ - shared: ['INGRESS_NETWORK'], + /** A site's; the shared Caddy's directory has neither. */ + site: ['GHOST_VERSION'], + production: ['URL'], + /** Behind the shared Caddy: its own Caddy's name on the shared Caddy's network. */ + shared: ['INGRESS_HOST'], } as const; /** Modes that hold credentials and are still private. */ @@ -143,6 +143,7 @@ export async function validateEnv(io: Io, dir: string): Promise { const required = [ ...REQUIRED_KEYS.common, ...REQUIRED_KEYS.site, + ...(mode === 'production' ? REQUIRED_KEYS.production : []), ...(behindSharedCaddy ? REQUIRED_KEYS.shared : []), ]; for (const key of required) { @@ -170,7 +171,7 @@ export async function validateEnv(io: Io, dir: string): Promise { } if (behindSharedCaddy) { - findings.push(...externalIngress(file, values)); + findings.push(...ingressNames(file, values)); } // The extra databases are created once, on first initialisation. A custom @@ -232,8 +233,7 @@ export async function validateEnv(io: Io, dir: string): Promise { } /** - * The shared Caddy's directory: Caddy alone, so `infra` and nothing else, - * on the network the manager created for it. + * The shared Caddy's directory: Caddy alone, so `infra` and nothing else. */ function validateInfra(file: string, values: Record): Finding[] { const findings: Finding[] = []; @@ -254,38 +254,38 @@ function validateInfra(file: string, values: Record): Finding[] ), ); } - for (const key of [...REQUIRED_KEYS.common, ...REQUIRED_KEYS.shared]) { + for (const key of REQUIRED_KEYS.common) { if (values[key] === undefined) { findings.push(error(file, `${key} is required for the shared Caddy`)); } else if (values[key] === '') { findings.push(error(file, `${key} is empty`)); } } - return [...findings, ...externalIngress(file, values)]; + return findings; } /** - * The shared Caddy's network is the manager's, so Compose must not create or - * remove it; and it is the one the manager finds the shared Caddy by. + * Behind the shared Caddy, a site is reached by the names its own Caddy has + * on the shared Caddy's network, which compose.yml takes from these: they + * must be the hosts of URL and ADMIN_URL, or the site is not served. */ -const externalIngress = (file: string, values: Record): Finding[] => [ - ...(values.INGRESS_NETWORK && values.INGRESS_NETWORK !== INGRESS_NETWORK - ? [ - error( - file, - `INGRESS_NETWORK must be ${INGRESS_NETWORK}, the shared Caddy's network: got ${values.INGRESS_NETWORK}`, - ), - ] - : []), - ...(values.INGRESS_EXTERNAL === 'true' - ? [] - : [ - error( - file, - `INGRESS_EXTERNAL must be true: ${values.INGRESS_NETWORK || 'the network'} is the shared Caddy's, which no Compose project creates or removes`, - ), - ]), -]; +const ingressNames = (file: string, values: Record): Finding[] => + ( + [ + ['INGRESS_HOST', 'URL'], + ['INGRESS_ADMIN_HOST', 'ADMIN_URL'], + ] as const + ).flatMap(([key, url]) => { + const host = hostOf(values[url] ?? ''); + return (values[key] ?? '') === host || (values[key] === undefined && host === '') + ? [] + : [ + error( + file, + `${key} must be ${host || 'unset'}, the host of ${url}, for the shared Caddy to reach this site: got ${values[key] || 'nothing'}`, + ), + ]; + }); /** * `ghost.env` holds Ghost application settings only. Two mistakes matter, and diff --git a/manager/src/docker/client.ts b/manager/src/docker/client.ts index 9ea969b5..9b40f061 100644 --- a/manager/src/docker/client.ts +++ b/manager/src/docker/client.ts @@ -8,7 +8,6 @@ import { DaemonTimeout, DaemonUnreachable, type DockerRequest, - type DockerResponse, type DockerTransport, } from './transport.ts'; @@ -218,12 +217,6 @@ const containerSummary = z.object({ Image: z.string().default(''), ImageID: z.string().default(''), Labels: z.record(z.string(), z.string()).nullable().default({}), - NetworkSettings: z - .looseObject({ - Networks: z.record(z.string(), z.unknown()).nullable().default({}), - }) - .nullable() - .default({ Networks: {} }), Ports: z .array( z.object({ @@ -251,8 +244,6 @@ export interface ContainerFacts { readonly labels: Readonly>; /** Host ports the container publishes. */ readonly publishedPorts: readonly number[]; - /** The names of the networks it is attached to. */ - readonly networks: readonly string[]; } /** `docker ps`, or with `all` `docker ps -a`, optionally filtered by label. */ @@ -284,7 +275,6 @@ export async function listContainers( ), ), ], - networks: Object.keys(container.NetworkSettings?.Networks ?? {}), })); } @@ -642,73 +632,6 @@ export async function runOnce(docker: DockerTransport, spec: RunSpec): Promise { - let id: string; - try { - id = ( - await call( - docker, - { - method: 'POST', - path: `/containers/${encodeURIComponent(container)}/exec`, - body: { - Cmd: [...cmd], - AttachStdout: true, - AttachStderr: true, - Tty: false, - ...(user ? { User: user } : {}), - }, - }, - created, - ) - ).Id; - } catch (error) { - if (error instanceof DaemonError) { - return { status: null, stdout: '', stderr: error.message, timedOut: false }; - } - throw error; - } - let output: DockerResponse; - try { - output = await docker({ - method: 'POST', - path: `/exec/${id}/start`, - body: { Detach: false, Tty: false }, - timeoutMs, - }); - } catch (error) { - if (error instanceof DaemonTimeout) { - return { status: null, stdout: '', stderr: '', timedOut: true }; - } - throw error; - } - if (output.status >= 400) { - return { status: null, stdout: '', stderr: output.body.toString('utf8'), timedOut: false }; - } - const { stdout, stderr } = demultiplex(output.body); - const state = await call(docker, { method: 'GET', path: `/exec/${id}/json` }, execInspect); - return { status: state.Running ? null : state.ExitCode, stdout, stderr, timedOut: false }; -} - /** * The log stream of a container without a TTY: frames of an 8-byte header * (stream type, three zero bytes, big-endian payload length) and a payload. diff --git a/manager/src/legacy.ts b/manager/src/legacy.ts index 8b137d2b..b6ca6779 100644 --- a/manager/src/legacy.ts +++ b/manager/src/legacy.ts @@ -316,7 +316,6 @@ async function prepare( port, mailpitPort: null, ports: { http: old.HTTP_PORT || '80', https: old.HTTPS_PORT || '443' }, - ingress: null, database: { user: old.DATABASE_USER || 'ghost', password: old.DATABASE_PASSWORD!, diff --git a/manager/src/payload.ts b/manager/src/payload.ts index 111499d6..4e50f98f 100644 --- a/manager/src/payload.ts +++ b/manager/src/payload.ts @@ -16,6 +16,12 @@ import type { Layout } from './site.ts'; export const stackDir = (env: NodeJS.ProcessEnv): string => env.GD_STACK_DIR ?? '/opt/ghost-docker/stack'; +/** + * The shared Caddy's own stack (shared.ts): a compose.yml and caddy/ of its + * own, in the payload's infra/, written into its directory as a site's are. + */ +export const infraStackDir = (env: NodeJS.ProcessEnv): string => join(stackDir(env), INFRA_STACK); +const INFRA_STACK = 'infra'; export const launcherSource = (env: NodeJS.ProcessEnv): string => env.GD_LAUNCHER_SOURCE ?? '/opt/ghost-docker/launcher/ghost-docker'; @@ -32,16 +38,15 @@ export const isCheckout = (context: Context, dir: string): boolean => /** * The top-level payload entries a directory of each layout does without: a * site with no Caddy has no routes, and cannot select analytics, whose - * Tinybird jobs are built from tinybird/; a site behind the shared Caddy has - * its routes in the shared Caddy's directory; and that directory runs Caddy - * alone. + * Tinybird jobs are built from tinybird/. The shared Caddy's directory takes + * the whole of its own stack (infraStackDir), which is no part of a site's. */ const UNUSED: Record = { local: ['caddy', 'tinybird'], production: [], 'no-caddy': ['caddy', 'tinybird'], - 'shared-caddy': ['caddy'], - infra: ['mysql-init', 'tinybird', 'ghost.env.example'], + 'shared-caddy': [], + infra: [], }; /** @@ -49,7 +54,7 @@ const UNUSED: Record = { * order; with a layout, only those a directory of that layout uses. */ export function payloadFiles(stack: string, layout?: Layout): string[] { - const unused = layout === undefined ? [] : UNUSED[layout]; + const unused = [INFRA_STACK, ...(layout === undefined ? [] : UNUSED[layout])]; return filesUnder(stack).filter((file) => !unused.includes(file.split('/')[0]!)); } diff --git a/manager/src/restore.ts b/manager/src/restore.ts index 728c74e6..0965ac14 100644 --- a/manager/src/restore.ts +++ b/manager/src/restore.ts @@ -1,15 +1,7 @@ // Restore validates the inputs it will write before replacing the site. // After writing begins, failure needs the operator; recovery instructions must // name only copies that exist. See docs/architecture.md#restore. -import { - cpSync, - existsSync, - mkdirSync, - mkdtempSync, - readdirSync, - readFileSync, - rmSync, -} from 'node:fs'; +import { cpSync, existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { basename, dirname, join } from 'node:path'; import { backupSiteFiles, readBackup, refuseMovedData } from './backup.ts'; @@ -51,23 +43,13 @@ import { hasProfile, INFRA_PROFILE, MAILPIT_DATA_DIR, - SHARED_CADDY_PROFILE, META_FILE, readSettings, RESTORE_DIR, + SHARED_CADDY_PROFILE, siteFacts, } from './site.ts'; -import { - addRoutes, - describeShared, - findSharedCaddy, - refuseTaken as refuseServed, - routeFiles, - routesFile, - routesPath, - runningCaddy, - type SharedCaddy, -} from './shared.ts'; +import { findSharedCaddy } from './shared.ts'; import { verifySite } from './verify.ts'; /** `over`: the backup's own site, replaced. `fresh`: a new, empty directory. */ @@ -93,7 +75,6 @@ export async function restoreSite({ io, context, root, yes }: RestoreInput): Pro ); const target = classify(context, dir, manifest); - const routes = await refuseWithoutRoutes(io, root, manifest); if (target === 'fresh') { await refuseTaken(io, root, manifest); } else { @@ -104,6 +85,7 @@ export async function restoreSite({ io, context, root, yes }: RestoreInput): Pro await refuseOtherCommit(io, dir, manifest); } await refuseOtherConfiguration(io, root, dir, manifest); + await refuseWithoutSharedCaddy(io, root); if (existsSync(join(dir, RESTORE_DIR))) { throw new CliError( `${join(dir, RESTORE_DIR)} is left from a restore that did not finish, and holds the site as\n` + @@ -145,16 +127,6 @@ export async function restoreSite({ io, context, root, yes }: RestoreInput): Pro writeSiteFiles(io, root, dir, manifest, pin === null ? null : pulled.get(pin)!); await checkImages(io, dir, manifest); await loadBackupData(io, root, dir, manifest); - if (routes !== null) { - await io.busy('Writing the routes into the shared Caddy', () => - addRoutes(io, routes.shared, manifest.site.project, routes.text), - ); - ok( - io, - 'routes', - `${routesPath(routes.shared, manifest.site.project)}, from the backup; the shared Caddy reloaded`, - ); - } heading(io, 'Starting the services'); await upAndWait(io, dir, 'Starting the services and waiting for them to be healthy'); @@ -358,6 +330,25 @@ function restoredEnv(text: string, dir: string, manifest: BackupManifest): strin * Compose resolves, in this directory, the files the restore will write * (restoredFiles) and the `.env` it will write, as they will be written. */ +/** + * A site that was behind the shared Caddy is restored behind one: its own + * Caddy publishes no port and joins the shared Caddy's network, which must + * exist. Its routes are in the backup, with the rest of the site's files. + */ +async function refuseWithoutSharedCaddy(io: Io, root: string): Promise { + const settings = env.toRecord(readIfExists(join(root, SITE_FILES_DIR, ENV_FILE)) ?? ''); + if ( + hasProfile(settings.COMPOSE_PROFILES ?? '', SHARED_CADDY_PROFILE) && + (await findSharedCaddy(io)) === null + ) { + throw new CliError( + 'this backup is of a site behind the shared Caddy, and this server has none.\n' + + ' Set one up first with ./ghost-docker install --infra, in a directory of its own\n' + + ' (docs/caddy.md#the-shared-caddy). Nothing has been changed.', + ); + } +} + async function refuseOtherConfiguration( io: Io, root: string, @@ -416,60 +407,6 @@ async function refuseOtherConfiguration( ok(io, 'configuration', "the backup's resolves the images it records"); } -/** - * A site that was behind the shared Caddy is restored behind it: the shared - * Caddy must run, and serve the site's routes. Routes it already has are - * kept, as the operator may have edited them since; otherwise the backup's - * are written back (returned here, written once the site's data is), when - * no other site serves their domains. A backup without routes needs them in - * place first. - */ -async function refuseWithoutRoutes( - io: Io, - root: string, - manifest: BackupManifest, -): Promise<{ shared: SharedCaddy; text: string } | null> { - const settings = env.toRecord(readIfExists(join(root, SITE_FILES_DIR, ENV_FILE)) ?? ''); - if (!hasProfile(settings.COMPOSE_PROFILES ?? '', SHARED_CADDY_PROFILE)) { - return null; - } - const project = manifest.site.project; - const shared = await findSharedCaddy(io); - if (shared === null) { - throw new CliError( - `this backup is of a site behind the shared Caddy, and this server has none.\n` + - ' Set one up first with ./ghost-docker install --infra, in a directory of its own' + - (manifest.routes === undefined - ? `, and put\n the site's routes in its caddy/sites/${routesFile(project)}` - : '; the restore\n writes the routes the backup holds') + - '. Nothing has been changed.', - ); - } - if ((await routeFiles(io, runningCaddy(shared))).includes(routesFile(project))) { - ok( - io, - 'routes', - `${routesPath(shared, project)}, kept as it is, in ${describeShared(shared)}`, - ); - return null; - } - if (manifest.routes === undefined) { - throw new CliError( - `this backup is of a site behind the shared Caddy, which has no routes for it:\n` + - ` ${routesPath(shared, project)} does not exist, and the backup holds none. Put them back\n` + - ' (or write them as docs/caddy.md describes), then run the restore again. Nothing has\n' + - ' been changed.', - ); - } - const domains = [settings.URL, settings.ADMIN_URL] - .filter((url): url is string => Boolean(url)) - .map((url) => URL.parse(url)?.hostname) - .filter((host): host is string => Boolean(host)); - await refuseServed(io, shared, project, domains); - ok(io, 'routes', `the backup's, written to ${routesPath(shared, project)} once the data is`); - return { shared, text: readFileSync(join(root, manifest.routes), 'utf8') }; -} - /** * A site restored into a new directory keeps its project name and its ports, * so nothing running on this daemon may already use them; a stopped site diff --git a/manager/src/shared.ts b/manager/src/shared.ts index 48148c96..c529bf29 100644 --- a/manager/src/shared.ts +++ b/manager/src/shared.ts @@ -1,29 +1,35 @@ // The shared Caddy: one Caddy for several production sites on a server, as // Ghost-CLI ran several sites behind one nginx. Only one process can hold 80 -// and 443, so Caddy is shared; everything else, MySQL included, stays per -// site. It is a Compose project of its own (`install --infra`), on a network -// the manager creates and no project owns, which each site's Ghost and -// optional services join under their unique aliases. The network's labels say -// where the shared Caddy's directory is. +// and 443, so it holds them, and the certificates; everything else, MySQL +// included, stays per site. It is a Compose project of its own +// (`install --infra`, infra/compose.yml), on a network the manager creates +// and no project owns. The network's labels say where its directory is. // -// Each site's routes are a file in that directory's caddy/sites/, named for -// the site's project. The manager cannot see that directory, only its own -// site's, so it reads and writes it through the running Caddy container, which -// mounts it: what is written is exactly what Caddy reads. See docs/caddy.md. -import { randomUUID } from 'node:crypto'; +// It names no site. Each site behind it keeps a Caddy of its own, with its +// routes in its own directory, serving plain HTTP on that network under the +// site's domains as aliases (`example.com.ghost.internal`), and the shared +// Caddy passes each request to the alias of the name asked for. So adding, +// changing or removing a site writes nothing in the shared Caddy's directory +// and reloads nothing. See docs/caddy.md. import { CliError } from './errors.ts'; import { - execInContainer, + inspectContainer, inspectNetwork, listContainers, type ContainerFacts, } from './docker/client.ts'; -import type { RunResult } from './docker/client.ts'; import type { Io } from './io.ts'; import { PROJECT_LABEL, WORKING_DIR_LABEL } from './project.ts'; +import { INTERNAL_CADDY } from './site.ts'; /** The shared Caddy's network. One per daemon, as 80 and 443 are. */ export const INGRESS_NETWORK = 'ghost-ingress'; +/** + * What follows a site's domain in its Caddy's alias on that network. Nothing + * under `.internal` resolves anywhere else, so the shared Caddy can only ever + * pass a request to a site's Caddy. + */ +export const INGRESS_SUFFIX = '.ghost.internal'; /** The network's labels: the shared Caddy's directory and project. */ export const INFRA_DIR_LABEL = 'org.ghost.docker.infra.dir'; export const INFRA_PROJECT_LABEL = 'org.ghost.docker.infra.project'; @@ -32,21 +38,6 @@ export const SERVICE_LABEL = 'com.docker.compose.service'; /** The default project name of the shared Caddy. */ export const INFRA_PROJECT = 'ghost-infra'; -/** Where the shared Caddy container mounts the sites' routes. */ -const SITES = '/etc/caddy/sites'; -const CADDYFILE = '/etc/caddy/Caddyfile'; - -/** - * `caddy reload` in the shared Caddy's container, one at a time. A reload - * reads the configuration, routes included, then loads it: a reload that read - * before another site's routes were written, and loaded after that site's own - * reload, would drop them from the running Caddy. Each site's manager and the - * shared Caddy's self-update see none of each other's directories, so the - * lock is taken in the container, on the sites' directory itself (busybox - * flock locks a directory), which leaves no file behind. - */ -export const RELOAD = ['flock', SITES, 'caddy', 'reload', '--config', CADDYFILE] as const; - export interface SharedCaddy { readonly network: string; /** The shared Caddy's directory on the host. */ @@ -83,119 +74,10 @@ export const describeShared = (shared: SharedCaddy): string => `the shared Caddy${shared.dir ? ` in ${shared.dir}` : ''}`; /** - * The shared Caddy's container, which must be running for its routes to be - * read or changed; otherwise a CliError saying how to start it. - */ -export function runningCaddy(shared: SharedCaddy): ContainerFacts { - const { container } = shared; - if (container === null || container.state !== 'running') { - throw new CliError( - `${describeShared(shared)} is not running, so its routes cannot be read or changed.\n` + - ` Start it in its directory: cd ${shared.dir || ''} && docker compose up -d\n` + - ' Nothing has been changed.', - ); - } - return container; -} - -/** A site's routes file, in the shared Caddy's caddy/sites/. */ -export const routesFile = (project: string): string => `${project}.caddy`; - -/** The routes file, as a person finds it on the host. */ -export const routesPath = (shared: SharedCaddy, project: string): string => - `${shared.dir || ''}/caddy/sites/${routesFile(project)}`; - -const inCaddy = ( - io: Io, - caddy: ContainerFacts, - cmd: readonly string[], - user?: string, -): Promise => execInContainer(io.docker, caddy.id, { cmd, user }); - -/** What a command in the Caddy container said when it failed, for an error. */ -const said = (result: RunResult): string => - (result.stderr.trim() || result.stdout.trim() || 'no output') - .split('\n') - .slice(-8) - .map((line) => ` ${line}`) - .join('\n'); - -/** Every host name the shared Caddy's loaded configuration matches, lowercase. */ -export async function servedHosts(io: Io, caddy: ContainerFacts): Promise> { - // Its admin API listens inside the container only, as the health check uses it. - const result = await inCaddy(io, caddy, [ - 'wget', - '-q', - '-O', - '-', - 'http://127.0.0.1:2019/config/', - ]); - if (result.status !== 0) { - throw new CliError( - `the shared Caddy's configuration could not be read from its admin API:\n${said(result)}`, - ); - } - const hosts = new Set(); - const walk = (value: unknown): void => { - if (Array.isArray(value)) { - value.forEach(walk); - } else if (value !== null && typeof value === 'object') { - for (const [key, inner] of Object.entries(value)) { - if (key === 'host' && Array.isArray(inner)) { - for (const host of inner) { - if (typeof host === 'string') { - hosts.add(host.toLowerCase()); - } - } - } else { - walk(inner); - } - } - } - }; - walk(result.stdout.trim() === '' ? null : JSON.parse(result.stdout)); - return hosts; -} - -/** The files in the shared Caddy's caddy/sites/. */ -export async function routeFiles(io: Io, caddy: ContainerFacts): Promise { - const result = await inCaddy(io, caddy, ['ls', '-1A', SITES]); - if (result.status !== 0) { - throw new CliError(`the shared Caddy's ${SITES} could not be listed:\n${said(result)}`); - } - return result.stdout.split('\n').filter((line) => line !== ''); -} - -/** The marker line an install writes first in its routes (routesMarker). */ -const MARKER_LINE = /^# ghost-docker install [0-9a-f-]+\n/; - -/** - * A site's routes as the shared Caddy holds them, without the marker line - * of the install that wrote them, or null when it has none: what a backup - * keeps, and what a restore writes back with addRoutes. - */ -export async function readRoutes( - io: Io, - shared: SharedCaddy, - project: string, -): Promise { - const caddy = runningCaddy(shared); - if (!(await routeFiles(io, caddy)).includes(routesFile(project))) { - return null; - } - const read = await inCaddy(io, caddy, ['cat', `${SITES}/${routesFile(project)}`]); - if (read.status !== 0) { - throw new CliError(`${routesPath(shared, project)} could not be read: -${said(read)}`); - } - return read.stdout.replace(MARKER_LINE, ''); -} - -/** - * Refuses a site whose project already has routes in the shared Caddy, or - * whose domains it already serves, for whichever site: before anything is - * written. Caddy would also refuse a second block for one address, but only - * once the file was there. + * Refuses a site whose domains another site behind the shared Caddy already + * answers to, before anything is written. Docker would attach both, and + * answer the name with either. Every site's Caddy counts, running or not; + * one taken down with `docker compose down` holds no name until it is up. */ export async function refuseTaken( io: Io, @@ -203,150 +85,30 @@ export async function refuseTaken( project: string, domains: readonly string[], ): Promise { - const caddy = runningCaddy(shared); - if ((await routeFiles(io, caddy)).includes(routesFile(project))) { - throw new CliError( - `${routesPath(shared, project)} already exists: the project ${project} already has routes in\n` + - ' the shared Caddy. Choose another name with --name, or remove that site first\n' + - ' (./ghost-docker remove, in its directory). Nothing has been changed.', - ); - } - const served = await servedHosts(io, caddy); - const taken = domains - .map((domain) => domain.toLowerCase()) - .filter((domain) => served.has(domain)); - if (taken.length > 0) { - throw new CliError( - `the shared Caddy already serves ${taken.join(' and ')}, for another site or in its own\n` + - ` configuration (${shared.dir || 'its directory'}/caddy). Two sites cannot share a domain.\n` + - ' Nothing has been changed.', - ); - } -} - -/** - * The first line of routes an installation wrote: which write they are, so - * undoing it removes them only while they are still that write's. - */ -export const routesMarker = (token: string): string => `# ghost-docker install ${token}`; - -/** - * Writes a site's routes into the shared Caddy, owned by whoever owns its - * caddy/sites/, has Caddy validate its whole configuration with them, and - * reloads it. Routes Caddy refuses are removed again, and Caddy keeps serving - * what it served. - * - * `owned` is told the token of the write before it is made, since a write - * whose result is unknown may have happened, and null once the file is - * certainly not this write's: an existing one is never replaced, and routes - * Caddy refused are removed. Undo then removes the file only if it is still - * marked with that token (removeRoutes). - */ -export async function addRoutes( - io: Io, - shared: SharedCaddy, - project: string, - routes: string, - owned: (token: string | null) => void = () => undefined, -): Promise { - const caddy = runningCaddy(shared); - const owner = await inCaddy(io, caddy, ['stat', '-c', '%u:%g', SITES]); - if (owner.status !== 0) { - throw new CliError(`the shared Caddy's ${SITES} could not be read:\n${said(owner)}`); - } - const file = `${SITES}/${routesFile(project)}`; - const token = randomUUID(); - owned(token); - // Written beside it under a name of this writer's that the Caddyfile's - // *.caddy does not import, then linked into place: a link, unlike a - // rename, fails when the file exists, so another site's is never replaced - // and Caddy never reads half a file. - const write = await inCaddy( - io, - caddy, - [ - 'sh', - '-c', - 'umask 022 && t="$2.$$.new" && printf "%s" "$1" > "$t" && ln "$t" "$2"; s=$?; rm -f "$t"; exit $s', - 'sh', - `${routesMarker(token)}\n${routes}`, - file, - ], - owner.stdout.trim(), + const wanted = new Map( + domains + .map((domain) => domain.toLowerCase()) + .map((domain) => [`${domain}${INGRESS_SUFFIX}`, domain]), ); - if (write.status !== 0) { - // A status means it did not happen; none, that it may have. - if (write.status !== null) { - owned(null); - } - throw new CliError(`the routes could not be written to the shared Caddy:\n${said(write)}`); - } - const valid = await inCaddy(io, caddy, ['caddy', 'validate', '--config', CADDYFILE]); - if (valid.status !== 0) { - const removed = await inCaddy(io, caddy, ['rm', '-f', file], owner.stdout.trim()); - if (removed.status !== 0) { + const others = ( + await listContainers(io.docker, { + all: true, + labels: [`${SERVICE_LABEL}=${INTERNAL_CADDY}`], + }) + ).filter((container) => container.labels[PROJECT_LABEL] !== project); + for (const container of others) { + const detail = await inspectContainer(io.docker, container.id); + const names = + detail?.endpoints.find((endpoint) => endpoint.network === shared.network)?.names ?? []; + const taken = names + .map((alias) => wanted.get(alias.toLowerCase())) + .filter((domain) => domain !== undefined); + if (taken.length > 0) { + const where = container.labels[WORKING_DIR_LABEL]; throw new CliError( - `the shared Caddy does not accept its configuration with these routes, and they could not\n` + - ` be removed again: remove ${routesPath(shared, project)} by hand. Until then Caddy keeps\n` + - ` serving, but will not start again. Caddy said:\n${said(valid)}`, + `${taken.join(' and ')} ${taken.length > 1 ? 'are' : 'is'} already served behind the shared Caddy, by the site ${container.labels[PROJECT_LABEL] ?? container.name}` + + `${where ? `\n in ${where}` : ''}. Two sites cannot share a domain. Nothing has been changed.`, ); } - owned(null); - throw new CliError( - `the shared Caddy does not accept its configuration with these routes, so they were removed\n` + - ` again; Caddy still serves what it served. Caddy said:\n${said(valid)}`, - ); - } - await reloadCaddy(io, shared); -} - -/** - * Removes a site's routes from the shared Caddy and reloads it. Routes - * that are already gone are not an error. With a token, only routes that - * write made (routesMarker) are removed: undoing an install never takes - * another's. - */ -export async function removeRoutes( - io: Io, - shared: SharedCaddy, - project: string, - token?: string, -): Promise { - const caddy = runningCaddy(shared); - const file = `${SITES}/${routesFile(project)}`; - const removed = await inCaddy( - io, - caddy, - token === undefined - ? ['rm', '-f', file] - : [ - 'sh', - '-c', - 'if head -n 1 "$2" 2>/dev/null | grep -qxF "$1"; then rm -f "$2"; fi', - 'sh', - routesMarker(token), - file, - ], - ); - if (removed.status !== 0) { - throw new CliError( - `${routesPath(shared, project)} could not be removed:\n${said(removed)}`, - ); - } - await reloadCaddy(io, shared); -} - -/** - * `caddy reload`: the configuration loads whole, or Caddy says why and keeps - * serving the one it had. - */ -export async function reloadCaddy(io: Io, shared: SharedCaddy): Promise { - const caddy = runningCaddy(shared); - const reloaded = await inCaddy(io, caddy, RELOAD); - if (reloaded.status !== 0) { - throw new CliError( - `the shared Caddy did not load its configuration, and keeps serving the one it had.\n` + - ` Caddy said:\n${said(reloaded)}`, - ); } } diff --git a/manager/src/site.ts b/manager/src/site.ts index ec0c6bc3..4559cbd9 100644 --- a/manager/src/site.ts +++ b/manager/src/site.ts @@ -57,10 +57,16 @@ export type SiteMode = (typeof SITE_MODES)[number]; */ export const NO_CADDY_PROFILE = 'no-caddy'; /** - * A production site behind the shared Caddy (shared.ts): Ghost and MySQL of - * its own, its routes in the shared Caddy's directory. Its mode is production. + * A production site behind the shared Caddy (shared.ts): everything a + * production site has, its own Caddy included, which publishes no port and + * serves plain HTTP to the shared one. Its mode is production. */ export const SHARED_CADDY_PROFILE = 'shared-caddy'; +/** A site's own Caddy behind the shared one, in compose.yml. */ +export const INTERNAL_CADDY = 'caddy-internal'; +/** The service that is a site's own Caddy, or null for a site without one. */ +export const caddyServiceOf = (layout: Layout): string | null => + layout === 'production' ? 'caddy' : layout === SHARED_CADDY_PROFILE ? INTERNAL_CADDY : null; /** The shared Caddy's own directory: Caddy alone, and no site. */ export const INFRA_PROFILE = 'infra'; @@ -200,8 +206,6 @@ export function generatedSettings(input: { readonly mailpitPort: number | null; /** Caddy's, written for a production site with a Caddy of its own. */ readonly ports: { readonly http: string; readonly https: string }; - /** The shared Caddy's network, for a site behind it; null for one with its own. */ - readonly ingress: string | null; readonly database: { readonly user: string; readonly password: string; @@ -228,7 +232,9 @@ export function generatedSettings(input: { ...(input.mailpitPort === null ? {} : { MAILPIT_PORT: String(input.mailpitPort) }), RESTART_POLICY: production ? 'unless-stopped' : 'no', ...(caddy ? { HTTP_PORT: input.ports.http, HTTPS_PORT: input.ports.https } : {}), - ...(input.ingress === null ? {} : ingressSettings(input.ingress)), + ...(layoutOf(input.profiles.join(',')) === SHARED_CADDY_PROFILE + ? ingressHosts(input.url, input.adminUrl) + : {}), DATABASE_HOST: 'db', DATABASE_PORT: '3306', DATABASE_NAME: 'ghost', @@ -238,10 +244,13 @@ export function generatedSettings(input: { }); } -/** What puts a directory's services on the shared Caddy's network, which it does not create. */ -export const ingressSettings = (network: string): Record => ({ - INGRESS_NETWORK: network, - INGRESS_EXTERNAL: 'true', +/** + * Behind the shared Caddy: the names the site's own Caddy answers to on the + * shared Caddy's network (compose.yml), which are the hosts of its URLs. + */ +export const ingressHosts = (url: string, adminUrl: string): Record => ({ + INGRESS_HOST: hostOf(url), + ...(adminUrl ? { INGRESS_ADMIN_HOST: hostOf(adminUrl) } : {}), }); /** The hostname a URL names, or '' when it is not a URL. */ diff --git a/manager/src/undo.ts b/manager/src/undo.ts index 052a5249..d4c465fa 100644 --- a/manager/src/undo.ts +++ b/manager/src/undo.ts @@ -14,16 +14,13 @@ import { atomicWrite, PRIVATE, readIfExists } from './fs.ts'; import type { Io } from './io.ts'; import type { Written } from './payload.ts'; import { removeNetwork } from './docker/client.ts'; -import { findSharedCaddy, removeRoutes, routesFile, routesPath } from './shared.ts'; -import { DATA_DIRS, ENV_FILE, GHOST_ENV_FILE, META_FILE, readSettings } from './site.ts'; +import { DATA_DIRS, ENV_FILE, GHOST_ENV_FILE, META_FILE } from './site.ts'; const journalSchema = z.object({ files: z.array(z.string().startsWith('/')), directories: z.array(z.string().startsWith('/')), data: z.array(z.string().startsWith('/')), project: z.boolean(), - // A write's token (shared.ts routesMarker), or true for whatever is there. - routes: z.union([z.string(), z.boolean()]).default(false), }); export class Created implements Written { @@ -34,12 +31,6 @@ export class Created implements Written { readonly data: string[] = []; /** Compose has created something for this project: a network, containers, volumes. */ project = false; - /** - * The site's routes in the shared Caddy, named for its project - * (shared.ts): the token of the write that may have made them, or true - * for whatever file is there. - */ - routes: string | boolean = false; /** The shared Caddy's network, created by `install --infra`. */ network: string | null = null; /** The import marker, when this is an import. */ @@ -71,8 +62,6 @@ export class Created implements Written { directories: [], data: DATA_DIRS.map((data) => join(dir, data)), project: true, - // Named for this site's project, which no other site's can have. - routes: true, }; } // Only ever inside this site directory, whatever the file says. @@ -81,7 +70,6 @@ export class Created implements Written { created.directories.push(...recorded.directories.filter(inside)); created.data.push(...recorded.data.filter(inside)); created.project = recorded.project && existsSync(join(dir, ENV_FILE)); - created.routes = recorded.routes; return created; } @@ -95,19 +83,16 @@ export class Created implements Written { if (this.journal === null) { return; } - const { files, directories, data, project, routes } = this; + const { files, directories, data, project } = this; atomicWrite( this.journal, - `${JSON.stringify({ files, directories, data, project, routes }, null, 2)}\n`, + `${JSON.stringify({ files, directories, data, project }, null, 2)}\n`, PRIVATE, ); } async remove(): Promise { const leftovers: string[] = []; - if (this.routes) { - leftovers.push(...(await this.removeRoutes())); - } if (this.project) { // Every profile, so whatever was started is found; the .env it // interpolates is still in place. @@ -151,34 +136,6 @@ export class Created implements Written { return leftovers; } - /** The site's routes in the shared Caddy, which is reloaded without them. */ - private async removeRoutes(): Promise { - const project = readSettings(this.dir)?.get('COMPOSE_PROJECT_NAME') ?? ''; - if (project === '') { - return []; - } - let shared = null; - try { - shared = await findSharedCaddy(this.io); - if (shared === null) { - return []; - } - await removeRoutes( - this.io, - shared, - project, - typeof this.routes === 'string' ? this.routes : undefined, - ); - return []; - } catch (error) { - const path = - shared === null - ? `${routesFile(project)} in the shared Caddy` - : routesPath(shared, project); - return [`${path} (${(error as Error).message.split('\n')[0]})`]; - } - } - /** MySQL's data directory belongs to MySQL's user once it has run (asroot.ts). */ private async removeData(): Promise { const left = await removeAsRoot( diff --git a/manager/src/update.ts b/manager/src/update.ts index be8ed692..de6fa43e 100644 --- a/manager/src/update.ts +++ b/manager/src/update.ts @@ -12,7 +12,7 @@ import type { Io } from './io.ts'; import type { Metadata } from './meta.ts'; import { runningServices, Snapshot, stopServices } from './recovery.ts'; import { heading, ok } from './report.ts'; -import { UPDATE_DIR, type SiteFacts } from './site.ts'; +import { caddyServiceOf, UPDATE_DIR, type SiteFacts } from './site.ts'; import { verifySite } from './verify.ts'; import { WriterPause } from './writers.ts'; @@ -231,8 +231,9 @@ export async function runUpdate(plan: UpdatePlan): Promise { except, ); ok(io, 'services', 'healthy, by their own health checks'); - if (site.layout === 'production') { - await reloadCaddy(io, dir); + const caddy = caddyServiceOf(site.layout); + if (caddy !== null) { + await reloadCaddy(io, dir, caddy); } plan.onStage?.('verifying'); @@ -263,10 +264,10 @@ export async function runUpdate(plan: UpdatePlan): Promise { * `up` recreates Caddy only when its service changed; a Caddyfile or snippet * it mounts is loaded only by a reload. One Caddy refuses is a failed update. */ -async function reloadCaddy(io: Io, dir: string): Promise { +async function reloadCaddy(io: Io, dir: string, service: string): Promise { const reload = await io.busy( 'Loading Caddy’s configuration', - () => compose(io, { dir })`exec -T caddy caddy reload --config /etc/caddy/Caddyfile`, + () => compose(io, { dir })`exec -T ${service} caddy reload --config /etc/caddy/Caddyfile`, ); if (reload.exitCode !== 0) { throw new CliError( diff --git a/manager/src/verify.ts b/manager/src/verify.ts index 874da605..73a21ddd 100644 --- a/manager/src/verify.ts +++ b/manager/src/verify.ts @@ -9,16 +9,10 @@ import type { Io } from './io.ts'; import { NetworkUnavailable, type SiteNetwork } from './network.ts'; import { CliError } from './errors.ts'; import { failed, heading, printChecks, type Check } from './report.ts'; -import { - describeShared, - findSharedCaddy, - INGRESS_NETWORK, - routeFiles, - routesFile, - routesPath, -} from './shared.ts'; +import { findSharedCaddy, INGRESS_NETWORK } from './shared.ts'; import { hasProfile, + caddyServiceOf, NO_CADDY_PROFILE, SHARED_CADDY_PROFILE, readSettings, @@ -216,20 +210,26 @@ export async function verifyIngress( const checks: Check[] = [ healthy('ghost', state('ghost'), 'its Admin API answers inside the container'), ]; - // Behind the shared Caddy, Caddy is, in another project. - const shared = - site.layout === SHARED_CADDY_PROFILE ? await sharedCaddyOf(io, site, checks) : null; + // Behind the shared Caddy, the site's own Caddy serves it, and the shared + // one, in another project, is what the site is asked through. + const shared = site.layout === SHARED_CADDY_PROFILE ? await sharedCaddyOf(io, checks) : null; const caddy = shared === null ? state('caddy') : shared.state; if (production) { checks.push( healthy( - shared === null ? 'caddy' : 'shared caddy', - caddy, + 'caddy', + state(caddyServiceOf(site.layout) ?? 'caddy'), 'its admin API answers, with its configuration loaded', ), ); - if (shared?.routes) { - checks.push(shared.routes); + if (shared !== null && caddy !== undefined) { + checks.push( + healthy( + 'shared caddy', + caddy, + 'its admin API answers, with its configuration loaded', + ), + ); } // The domain, and the admin domain when it has one of its own. const adminElsewhere = @@ -318,15 +318,13 @@ const healthOf = (status: string): string => : ''; /** - * The shared Caddy a site is behind: its container as `ps` would report it, - * and whether this site's routes are in its directory. A server with no - * shared Caddy is reported in `checks`. + * The shared Caddy a site is behind: its container as `ps` would report it. + * A server with no shared Caddy is reported in `checks`. */ async function sharedCaddyOf( io: Io, - site: SiteFacts, checks: Check[], -): Promise<{ state: ServiceState | undefined; routes: Check | null } | null> { +): Promise<{ state: ServiceState | undefined } | null> { const shared = await findSharedCaddy(io); if (shared === null) { checks.push( @@ -335,44 +333,32 @@ async function sharedCaddyOf( `this site is behind the shared Caddy (${SHARED_CADDY_PROFILE} in COMPOSE_PROFILES), and this server has none: its network ${INGRESS_NETWORK} does not exist`, ), ); - return { state: undefined, routes: null }; + return { state: undefined }; } const { container } = shared; - const state: ServiceState | undefined = - container === null - ? undefined - : { - ID: container.id, - Service: 'caddy', - State: container.state, - Health: healthOf(container.status), - ExitCode: 0, - Publishers: container.publishedPorts.map((port) => ({ - URL: '', - TargetPort: 0, - PublishedPort: port, - Protocol: 'tcp', - })), - }; - if (container?.state !== 'running') { - return { state, routes: null }; + if (container === null) { + checks.push( + error( + 'shared caddy', + `it has no container: start it in ${shared.dir || 'its directory'}`, + ), + ); + return { state: undefined }; } - const project = site.settings.get('COMPOSE_PROJECT_NAME') || ''; - const path = routesPath(shared, project); - const present = (await routeFiles(io, container).catch(() => null))?.includes( - routesFile(project), - ); return { - state, - routes: - present === undefined - ? error('routes', `the shared Caddy's caddy/sites/ could not be listed`) - : present - ? ok('routes', `${path}, in ${describeShared(shared)}`) - : error( - 'routes', - `${path} does not exist, so the shared Caddy has no routes of this site's`, - ), + state: { + ID: container.id, + Service: 'caddy', + State: container.state, + Health: healthOf(container.status), + ExitCode: 0, + Publishers: container.publishedPorts.map((port) => ({ + URL: '', + TargetPort: 0, + PublishedPort: port, + Protocol: 'tcp', + })), + }, }; } diff --git a/manager/templates/site.caddy b/manager/templates/site.caddy index d287444f..8b51b7ae 100644 --- a/manager/templates/site.caddy +++ b/manager/templates/site.caddy @@ -1,7 +1,7 @@ # Routes for {{project}}, written by ./ghost-docker install. This file is # yours: edit it, then reload Caddy: # -# docker compose exec caddy caddy reload --config /etc/caddy/Caddyfile +# docker compose exec {{service}} caddy reload --config /etc/caddy/Caddyfile # # docs/caddy.md lists the snippets and the arguments each one takes. diff --git a/manager/test/backup.test.ts b/manager/test/backup.test.ts index 5c39b6fd..540ff6b8 100644 --- a/manager/test/backup.test.ts +++ b/manager/test/backup.test.ts @@ -34,7 +34,6 @@ import { type Harness, type ProgramResult, } from './helpers.ts'; -import { CADDY, fakeShared, sharedApi, type FakeShared } from './shared-caddy.ts'; import { imageApi, imageStack, INDEX, REFERENCE, resolvedProject, rootContainer } from './site.ts'; const MANAGER = `sha256:${'2'.repeat(64)}`; @@ -567,124 +566,6 @@ describe('backup records what the site runs', () => { }); }); -describe('a site behind the shared Caddy', () => { - const ROUTES = 'example.com {\n\treverse_proxy ghost-example-com-ghost:2368\n}\n'; - let shared: FakeShared; - let project: string; - const routesFile = () => `${project}.caddy`; - - beforeEach(() => { - project = env.toRecord(readSite('.env')).COMPOSE_PROJECT_NAME!; - // The site as an install behind the shared Caddy leaves it. - const profiles = env.toRecord(readSite('.env')).COMPOSE_PROFILES!; - setEnv('COMPOSE_PROFILES', profiles.replace('production', 'shared-caddy')); - setEnv('INGRESS_NETWORK', 'ghost-ingress'); - setEnv('INGRESS_EXTERNAL', 'true'); - shared = fakeShared(); - shared.sites.set(routesFile(), `# ghost-docker install ${'a'.repeat(8)}-0000\n${ROUTES}`); - const site = h.daemon.api; - const caddy = sharedApi(shared); - h.daemon.api = (request) => caddy(request) ?? site!(request); - h.daemon.containers = [CADDY]; - }); - - test('its backup holds its routes, without their marker line', async () => { - const root = await backUp(); - const manifest = JSON.parse(readFileSync(join(root, 'manifest.json'), 'utf8')); - assert.equal(manifest.routes, 'routes.caddy'); - assert.equal(readFileSync(join(root, 'routes.caddy'), 'utf8'), ROUTES); - assert.ok(manifest.files['routes.caddy']); - assert.ok(!manifest.notIncluded.some((line: string) => /its routes/.test(line))); - }); - - test('routes the shared Caddy does not have leave the backup without them, and say so', async () => { - shared.sites.clear(); - const result = await h.run('backup'); - assert.equal(result.code, 0, result.stderr); - assert.match( - result.stdout + result.stderr, - /does not exist, so the backup holds no routes/, - ); - const manifest = JSON.parse( - readFileSync(join(h.dir, 'backups', backups()[0]!, 'manifest.json'), 'utf8'), - ); - assert.equal(manifest.routes, undefined); - assert.ok(manifest.notIncluded.some((line: string) => /its routes/.test(line))); - }); - - test("a restore writes the backup's routes back when the shared Caddy has none", async () => { - const root = await backUp(); - // The site was removed, its routes with it. - shared.sites.clear(); - const result = await h.run('restore', '--yes', root); - assert.equal(result.code, 0, result.stderr); - assert.match(result.stdout, /the backup's, written to/); - const written = shared.sites.get(routesFile()); - assert.ok(written !== undefined, result.stderr); - assert.match(written, /^# ghost-docker install [0-9a-f-]+\n/); - assert.equal(written.replace(/^.*\n/, ''), ROUTES); - assert.ok(shared.execs.some(({ cmd }) => cmd.includes('reload'))); - }); - - test('a restore keeps the routes the shared Caddy has', async () => { - const root = await backUp(); - const edited = `# ghost-docker install ${'b'.repeat(8)}\nexample.com {\n\trespond 503\n}\n`; - shared.sites.set(routesFile(), edited); - const result = await h.run('restore', '--yes', root); - assert.equal(result.code, 0, result.stderr); - assert.match(result.stdout, /kept as it is/); - assert.equal(shared.sites.get(routesFile()), edited); - }); - - test('a backup without routes is refused while the shared Caddy has none', async () => { - shared.sites.clear(); - const result = await h.run('backup'); - assert.equal(result.code, 0, result.stderr); - const root = join(h.dir, 'backups', backups()[0]!); - const restored = await h.run('restore', '--yes', root); - assert.equal(restored.code, 1); - assert.match( - restored.stderr, - /has no routes for it[\s\S]*the backup holds none[\s\S]*Nothing has/, - ); - }); - - test('routes with no checksum are refused before anything changes', async () => { - const root = await backUp(); - const manifest = JSON.parse(readFileSync(join(root, 'manifest.json'), 'utf8')); - delete manifest.files['routes.caddy']; - writeFileSync(join(root, 'manifest.json'), JSON.stringify(manifest)); - writeFileSync( - join(root, 'routes.caddy'), - 'example.com {\n\trespond "not the backup\'s"\n}\n', - ); - shared.sites.clear(); - shared.execs.length = 0; - const before = readSite('.env'); - const restored = await h.run('restore', '--yes', root); - assert.equal(restored.code, 1); - assert.match( - restored.stderr, - /lists no checksum for routes\.caddy\. Nothing has been changed/, - ); - assert.equal(readSite('.env'), before); - assert.equal(shared.sites.size, 0); - assert.deepEqual(shared.execs, []); - }); - - test("routes whose domain another site's routes serve are refused before anything changes", async () => { - const root = await backUp(); - shared.sites.clear(); - shared.hosts = new Set(['example.com']); - const env = readSite('.env'); - const restored = await h.run('restore', '--yes', root); - assert.equal(restored.code, 1); - assert.match(restored.stderr, /already serves example\.com/); - assert.equal(readSite('.env'), env); - assert.equal(shared.sites.size, 0); - }); -}); - describe('restore over the site', () => { test('puts the backup back, pinned, and removes the site it replaced once verified', async () => { const root = await backUp(); diff --git a/manager/test/config.test.ts b/manager/test/config.test.ts index 21d0cdf0..1a41e2c5 100644 --- a/manager/test/config.test.ts +++ b/manager/test/config.test.ts @@ -143,11 +143,10 @@ describe('.env', () => { assert.match(result.errors, /warning .*mode is 0644; it holds credentials/); }); - test('a local site needs URL too: compose.yml no longer guards it', async () => { + test('Compose guards URL itself, so validation does not list it twice', async () => { makeSite(h, { ...LOCAL, URL: undefined }); const result = await validate(); - assert.equal(result.code, 1); - assert.match(result.errors, /URL is required for mode local/); + assert.doesNotMatch(result.errors, /\.env +URL is required/); }); }); diff --git a/manager/test/integration/shared.test.ts b/manager/test/integration/shared.test.ts index 4465e2cc..d573bf23 100644 --- a/manager/test/integration/shared.test.ts +++ b/manager/test/integration/shared.test.ts @@ -1,29 +1,22 @@ -// The shared Caddy, against the real daemon and a real Caddy: a site's -// routes written, validated and loaded through the running container, its -// Ghost reached by its unique alias on the shared network, a taken domain or -// project refused, routes Caddy refuses taken out again, and removal. +// The shared Caddy, against the real daemon and a real Caddy: a site's own +// Caddy reached through it by the site's domain, which is its name on the +// shared network; the shared Caddy's forwarded headers passed on to Ghost; a +// certificate only for a name a site has; a taken domain refused; and a site +// taken down, which changes nothing in the shared Caddy. // -// The shared Caddy here is the stack's own compose.yml with the `infra` -// profile, on a network of this run's rather than the real one. The site's -// Ghost is a stand-in that answers as a Ghost of its URL would: the real one -// is tests/e2e/shared-caddy.sh's. +// The shared Caddy here is its own stack (infra/), on a network of this run's +// rather than the real one. The site's Ghost is a stand-in that answers as a +// Ghost of its URL would: the real one is tests/e2e/shared-caddy.sh's. import assert from 'node:assert/strict'; -import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'; +import { readFileSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; import { after, before, test } from 'node:test'; -import { renderRoutes } from '../../src/caddy.ts'; +import { SHARED_GLOBAL, SHARED_GLOBAL_FILE, renderRoutes } from '../../src/caddy.ts'; +import type { HttpsAnswer } from '../../src/clients.ts'; import { listContainers } from '../../src/docker/client.ts'; import { CliError } from '../../src/errors.ts'; import { PROJECT_LABEL } from '../../src/project.ts'; -import { - addRoutes, - refuseTaken, - removeRoutes, - routeFiles, - servedHosts, - SERVICE_LABEL, - type SharedCaddy, -} from '../../src/shared.ts'; +import { refuseTaken, SERVICE_LABEL, type SharedCaddy } from '../../src/shared.ts'; import { makeSite, named, realIo, type TestSite } from './site.ts'; const io = realIo(); @@ -32,20 +25,18 @@ const CADDY_IMAGE = /image: (caddy:\S+)/.exec( readFileSync(join(import.meta.dirname, '..', '..', '..', 'compose.yml'), 'utf8'), )![1]!; -const ingress: [string, string][] = [ - ['INGRESS_NETWORK', INGRESS], - ['INGRESS_EXTERNAL', 'true'], -]; - let infra: TestSite; let delta: TestSite; let shared: SharedCaddy; -/** Delta's Ghost: Caddy answering every request as Ghost's site endpoint does. */ +/** + * Delta's Ghost: Caddy answering every request as Ghost's site endpoint does, + * and saying in Location which protocol it was told the visitor used. + */ const STAND_IN = `services: ghost: image: ${CADDY_IMAGE} - command: ["caddy", "respond", "--listen", ":2368", "--body", '{"site":{"url":"https://delta.test/"}}'] + command: ["caddy", "respond", "--listen", ":2368", "--header", "Location: /{http.request.header.X-Forwarded-Proto}", "--body", '{"site":{"url":"https://delta.test/"}}'] healthcheck: test: [CMD, wget, -q, -O, /dev/null, "http://127.0.0.1:2368/"] interval: 1s @@ -53,9 +44,6 @@ const STAND_IN = `services: ports: !reset [] `; -const routes = (project: string, domain: string) => - renderRoutes({ project, domain, adminDomain: '', email: '', activitypub: false }); - before( async () => { const created = await io.docker({ @@ -64,17 +52,34 @@ before( body: { Name: INGRESS }, }); assert.equal(created.status, 201, created.body.toString()); - infra = makeSite(io, 'shared-caddy', { profiles: 'infra', env: ingress }); + infra = makeSite(io, 'shared-caddy', { + profiles: 'infra', + infra: true, + env: [['INGRESS_NETWORK', INGRESS]], + override: 'services:\n caddy:\n ports: !reset []\n', + }); // Certificates from Caddy's own CA at once, rather than ACME's. - mkdirSync(join(infra.dir, 'caddy', 'global'), { recursive: true }); writeFileSync(join(infra.dir, 'caddy', 'global', 'test.caddy'), 'local_certs\n'); delta = makeSite(io, 'behind-delta', { profiles: 'shared-caddy', url: 'https://delta.test', - env: ingress, + env: [ + ['INGRESS_NETWORK', INGRESS], + ['INGRESS_HOST', 'delta.test'], + ], override: STAND_IN, + // As install writes them for a site behind the shared Caddy. + caddy: renderRoutes({ + project: named('behind-delta'), + domain: 'delta.test', + adminDomain: '', + email: '', + activitypub: false, + shared: true, + }), }); - await Promise.all([infra.up('caddy'), delta.up('ghost')]); + writeFileSync(join(delta.dir, SHARED_GLOBAL_FILE), SHARED_GLOBAL); + await Promise.all([infra.up('caddy'), delta.up('ghost', 'caddy-internal')]); const [container] = await listContainers(io.docker, { labels: [`${PROJECT_LABEL}=${infra.project}`, `${SERVICE_LABEL}=caddy`], }); @@ -95,20 +100,9 @@ after(async () => { await io.docker({ method: 'DELETE', path: `/networks/${INGRESS}` }).catch(() => undefined); }); -const sitesFile = (name: string) => join(infra.dir, 'caddy', 'sites', name); - -test("a site's routes are written as the directory's owner, validated and loaded", async () => { - await addRoutes(io, shared, delta.project, routes(delta.project, 'delta.test')); - const file = sitesFile(`${delta.project}.caddy`); - assert.ok(existsSync(file)); - const owner = statSync(join(infra.dir, 'caddy', 'sites')); - assert.equal(statSync(file).uid, owner.uid); - assert.ok(!existsSync(`${file}.new`)); - assert.ok((await servedHosts(io, shared.container!)).has('delta.test')); -}); - -test("the site's Ghost answers through the shared Caddy, by its alias on the shared network", async () => { - const answer = await io.siteNetwork( +/** `name` asked of the shared Caddy over TLS, from its network. */ +const ask = (name: string, attempts = 30): Promise => + io.siteNetwork( [ { ID: shared.container!.id, @@ -122,17 +116,17 @@ test("the site's Ghost answers through the shared Caddy, by its alias on the sha ['caddy'], async (network) => { assert.equal(network.name, INGRESS); - // Caddy issues its internal certificate in the background. - for (let attempt = 0; ; attempt += 1) { + // Caddy obtains the certificate when the name is first asked for. + for (let attempt = 1; ; attempt += 1) { try { return await io.clients.https({ host: network.address('caddy')!.host, port: 443, - servername: 'delta.test', + servername: name, path: '/ghost/api/admin/site/', }); } catch (error) { - if (attempt === 30) { + if (attempt >= attempts) { throw error; } await new Promise((resolve) => setTimeout(resolve, 1000)); @@ -140,39 +134,39 @@ test("the site's Ghost answers through the shared Caddy, by its alias on the sha } }, ); + +test("the site's Ghost answers through the shared Caddy and its own, told the visitor used HTTPS", async () => { + const answer = await ask('delta.test'); assert.equal(answer.status, 200); assert.match(answer.body, /"url":"https:\/\/delta\.test\/"/); + // The shared Caddy's X-Forwarded-Proto, passed on by the site's Caddy. + assert.equal(answer.location, '/https'); }); -test('a taken project or domain is refused before anything is written', async () => { - const before = await routeFiles(io, shared.container!); - await assert.rejects( - refuseTaken(io, shared, delta.project, ['other.test']), - (error: unknown) => error instanceof CliError && /already has routes/.test(error.message), - ); +test('a name no site has gets no certificate', async () => { + await assert.rejects(ask('nobody.test', 2)); +}); + +test('a domain another site answers to is refused; a free one, or its own, is not', async () => { await assert.rejects( refuseTaken(io, shared, named('echo'), ['other.test', 'DELTA.test']), (error: unknown) => - error instanceof CliError && /already serves delta\.test/.test(error.message), + error instanceof CliError && + /delta\.test is already served behind the shared Caddy/.test(error.message), ); await refuseTaken(io, shared, named('echo'), ['echo.test']); - assert.deepEqual(await routeFiles(io, shared.container!), before); -}); - -test('routes Caddy refuses are taken out again, and Caddy keeps serving', async () => { - const project = named('broken'); - await assert.rejects( - addRoutes(io, shared, project, 'broken.test {\n\treverse_proxy {\n'), - (error: unknown) => error instanceof CliError && /does not accept/.test(error.message), - ); - assert.ok(!existsSync(sitesFile(`${project}.caddy`))); - assert.ok((await servedHosts(io, shared.container!)).has('delta.test')); + await refuseTaken(io, shared, delta.project, ['delta.test']); }); -test('removing a site removes its routes, and Caddy reloads without them', async () => { - await removeRoutes(io, shared, delta.project); - assert.ok(!existsSync(sitesFile(`${delta.project}.caddy`))); - assert.ok(!(await servedHosts(io, shared.container!)).has('delta.test')); - // Already gone is not an error. - await removeRoutes(io, shared, delta.project); +test('a site taken down frees its domain, with nothing done to the shared Caddy', async () => { + assert.ok((await delta.down()).ok); + await refuseTaken(io, shared, named('echo'), ['delta.test']); + // Its certificate is still held; there is no site to pass the request to. + assert.equal((await ask('delta.test', 1)).status, 502); + // The same container, never restarted. + const [container] = await listContainers(io.docker, { + labels: [`${PROJECT_LABEL}=${infra.project}`, `${SERVICE_LABEL}=caddy`], + }); + assert.equal(container!.id, shared.container!.id); + assert.equal(container!.state, 'running'); }); diff --git a/manager/test/integration/site.ts b/manager/test/integration/site.ts index 4e34702c..893275e7 100644 --- a/manager/test/integration/site.ts +++ b/manager/test/integration/site.ts @@ -70,15 +70,21 @@ export interface SiteOptions { readonly caddy?: string; /** More `.env` settings. */ readonly env?: readonly [string, string][]; + /** The shared Caddy's own stack (infra/), rather than a site's. */ + readonly infra?: boolean; } export function makeSite(io: Io, name: string, options: SiteOptions): TestSite { const dir = join(WORK!, name); const project = named(name); mkdirSync(dir, { recursive: true }); - cpSync(join(REPO, 'compose.yml'), join(dir, 'compose.yml')); - for (const directory of ['caddy', 'mysql-init']) { - cpSync(join(REPO, directory), join(dir, directory), { recursive: true }); + if (options.infra) { + cpSync(join(REPO, 'infra'), dir, { recursive: true }); + } else { + cpSync(join(REPO, 'compose.yml'), join(dir, 'compose.yml')); + for (const directory of ['caddy', 'mysql-init']) { + cpSync(join(REPO, directory), join(dir, directory), { recursive: true }); + } } const secret = () => randomBytes(12).toString('hex'); writeFileSync( diff --git a/manager/test/shared-caddy.ts b/manager/test/shared-caddy.ts index 03046c58..e902f10f 100644 --- a/manager/test/shared-caddy.ts +++ b/manager/test/shared-caddy.ts @@ -1,45 +1,21 @@ // A shared Caddy as the daemon shows it, for tests of the sites behind it: -// its network, its container, and the files in its caddy/sites/. +// its network, its container, and the Caddy of a site already behind it. import assert from 'node:assert/strict'; import type { DockerRequest, DockerResponse } from '../src/docker/transport.ts'; -import { frame } from '../src/docker/client.ts'; import { json } from './helpers.ts'; export const INFRA_DIR = '/srv/caddy'; -/** A shared Caddy as the daemon would show it: its network, its container, and the files it mounts. */ +/** The shared Caddy's network as the daemon would show it. */ export interface FakeShared { - /** Files in its caddy/sites/, by name. */ - sites: Map; - /** Host names its loaded configuration matches. */ - hosts: Set; - running: boolean; - /** What `caddy validate` says: null accepts. */ - refuse: string | null; - /** Each command run in its container, with the user it ran as. */ - execs: { cmd: string[]; user: string }[]; + exists: boolean; /** The labels the network was created with, when the manager created it. */ created: Record | null; - exists: boolean; - /** Another installation, creating the network or a routes file first. */ - raced: { network?: boolean; routes?: string }; - /** A routes write that runs, but whose result the daemon never reports. */ - lost: boolean; + /** Another installation creates the network first. */ + raced: boolean; } -export function fakeShared(): FakeShared { - return { - sites: new Map(), - hosts: new Set(), - running: true, - refuse: null, - execs: [], - created: null, - exists: true, - raced: {}, - lost: false, - }; -} +export const fakeShared = (): FakeShared => ({ exists: true, created: null, raced: false }); export const CADDY = { Id: 'shared-caddy', @@ -57,15 +33,53 @@ export const CADDY = { { PrivatePort: 80, PublicPort: 80, Type: 'tcp' }, { PrivatePort: 443, PublicPort: 443, Type: 'tcp' }, ], - NetworkSettings: { Networks: { 'ghost-ingress': {} } }, }; -/** The daemon's answers about the shared Caddy: its network, and commands run in its container. */ -export function sharedApi(shared: FakeShared) { - let pending: { cmd: string[]; user: string } | null = null; - let status = 0; +/** The Caddy of a site behind the shared one, answering to `domains` on its network. */ +export const siteCaddy = (project: string, domains: readonly string[], state = 'running') => ({ + Id: `caddy-of-${project}`, + Names: [`/${project}-caddy-internal-1`], + State: state, + Status: state === 'running' ? 'Up 2 minutes (healthy)' : 'Exited (0) 2 minutes ago', + Labels: { + 'org.ghost.docker.managed': 'true', + 'org.ghost.docker.mode': 'production', + 'com.docker.compose.project': project, + 'com.docker.compose.project.working_dir': `/srv/${project}`, + 'com.docker.compose.service': 'caddy-internal', + }, + Ports: [], + NetworkSettings: { + Networks: { + [`${project}_ghost_network`]: { Aliases: ['caddy-internal'] }, + 'ghost-ingress': { + Aliases: ['caddy-internal', ...domains.map((domain) => `${domain}.ghost.internal`)], + }, + }, + }, +}); + +/** + * The daemon's answers about the shared Caddy's network, and `docker inspect` + * of a site's Caddy on it, which is where its names are. + */ +export function sharedApi(shared: FakeShared, containers: () => readonly unknown[] = () => []) { return (request: DockerRequest): DockerResponse | undefined => { const { method, path } = request; + const inspected = /^\/containers\/(caddy-of-[^/]+)\/json$/.exec(path); + if (inspected && method === 'GET') { + const found = containers().find( + (each) => (each as { Id?: string }).Id === inspected[1], + ) as ReturnType | undefined; + return found === undefined + ? json(404, { message: 'No such container' }) + : json(200, { + Id: found.Id, + Name: found.Names[0], + Config: { Labels: found.Labels }, + NetworkSettings: found.NetworkSettings, + }); + } if (path === '/networks/ghost-ingress' && method === 'GET') { return shared.exists ? json(200, { @@ -81,7 +95,7 @@ export function sharedApi(shared: FakeShared) { if (path === '/networks/create' && method === 'POST') { const body = request.body as { Name: string; Labels: Record }; assert.equal(body.Name, 'ghost-ingress'); - if (shared.raced.network) { + if (shared.raced) { shared.exists = true; return json(409, { message: 'network with name ghost-ingress already exists' }); } @@ -94,94 +108,6 @@ export function sharedApi(shared: FakeShared) { shared.created = null; return { status: 204, body: Buffer.alloc(0) }; } - if (path === '/containers/shared-caddy/exec' && method === 'POST') { - const body = request.body as { Cmd: string[]; User?: string }; - pending = { cmd: body.Cmd, user: body.User ?? '' }; - shared.execs.push(pending); - return json(201, { Id: 'exec-1' }); - } - if (path === '/exec/exec-1/start') { - const { stdout, code } = run(shared, pending!); - status = code; - if (shared.lost && pending!.cmd[0] === 'sh' && !pending!.cmd[2]!.includes('grep')) { - return { status: 500, body: Buffer.from('connection reset') }; - } - return { status: 200, body: frame(code === 0 ? 1 : 2, stdout) }; - } - if (path === '/exec/exec-1/json') { - return json(200, { Running: false, ExitCode: status }); - } return undefined; }; } - -/** A command in the shared Caddy's container, done to the fake's files. */ -function run(shared: FakeShared, { cmd }: { cmd: string[] }): { stdout: string; code: number } { - const name = (path: string) => path.replace('/etc/caddy/sites/', ''); - switch (cmd[0]) { - case 'flock': - // Reloads are serialized on the sites' directory. - assert.equal(cmd[1], '/etc/caddy/sites'); - return run(shared, { cmd: cmd.slice(2) }); - case 'wget': { - const routes = [...shared.hosts].map((host) => ({ match: [{ host: [host] }] })); - return { - stdout: JSON.stringify({ apps: { http: { servers: { srv0: { routes } } } } }), - code: 0, - }; - } - case 'ls': - return { - stdout: [...shared.sites.keys()].map((file) => `${file}\n`).join(''), - code: 0, - }; - case 'cat': { - const routes = shared.sites.get(name(cmd[1]!)); - return routes === undefined - ? { stdout: `cat: ${cmd[1]}: No such file`, code: 1 } - : { stdout: routes, code: 0 }; - } - case 'stat': - return { stdout: '1000:1000\n', code: 0 }; - case 'sh': { - // sh -c SCRIPT sh MARKER FILE: removes the file if it is that write's. - if (cmd[2]!.includes('grep')) { - if (shared.sites.get(name(cmd[5]!))?.split('\n')[0] === cmd[4]) { - shared.sites.delete(name(cmd[5]!)); - } - return { stdout: '', code: 0 }; - } - // sh -c SCRIPT sh ROUTES FILE, which never overwrites a file. - if (shared.raced.routes !== undefined) { - shared.sites.set(name(cmd[5]!), shared.raced.routes); - } - if (shared.sites.has(name(cmd[5]!))) { - return { stdout: '', code: 1 }; - } - shared.sites.set(name(cmd[5]!), cmd[4]!); - return { stdout: '', code: 0 }; - } - case 'rm': - shared.sites.delete(name(cmd.at(-1)!)); - return { stdout: '', code: 0 }; - case 'caddy': - if (cmd[1] === 'validate' && shared.refuse !== null) { - return { stdout: shared.refuse, code: 1 }; - } - if (cmd[1] === 'reload') { - // What the files now serve. - shared.hosts = new Set( - [...shared.sites.values()].flatMap( - (routes) => - /^([^\s#{][^{]*)\{/m - .exec(routes)?.[1]! - .split(',') - .map((host) => host.trim()) ?? [], - ), - ); - } - return { stdout: '', code: 0 }; - default: - return { stdout: `unexpected: ${cmd.join(' ')}`, code: 127 }; - } -} diff --git a/manager/test/shared.test.ts b/manager/test/shared.test.ts index 4e6b7817..17c7f1c9 100644 --- a/manager/test/shared.test.ts +++ b/manager/test/shared.test.ts @@ -1,7 +1,7 @@ // The shared Caddy, against a scripted daemon and Compose: `install --infra`, // a production install joining it, the refusals before anything is written, -// and `list`, `check`, `remove` and `config validate` knowing about it. What -// the real Caddy does with the routes is test/integration/shared.test.ts, and +// and `list`, `check` and `config validate` knowing about it. What the real +// Caddy does with a site behind it is test/integration/shared.test.ts, and // several sites on one server tests/e2e/shared-caddy.sh. import assert from 'node:assert/strict'; import { execFileSync } from 'node:child_process'; @@ -9,11 +9,11 @@ import { existsSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'no import { join } from 'node:path'; import { afterEach, beforeEach, describe, test } from 'node:test'; import * as env from '../src/env.ts'; -import { payloadFiles } from '../src/payload.ts'; +import { infraStackDir, payloadFiles } from '../src/payload.ts'; import { layoutOf, readSettings, siteFacts, siteMode } from '../src/site.ts'; import { verifyIngress } from '../src/verify.ts'; import { failed, harness, ok, type Harness } from './helpers.ts'; -import { CADDY, fakeShared, sharedApi, type FakeShared } from './shared-caddy.ts'; +import { CADDY, fakeShared, sharedApi, siteCaddy, type FakeShared } from './shared-caddy.ts'; import { imageApi, imageStack, rootContainer } from './site.ts'; let h: Harness; @@ -27,7 +27,7 @@ beforeEach(() => { compose = []; ps = () => ''; const images = imageApi(); - const caddy = sharedApi(shared); + const caddy = sharedApi(shared, () => h.daemon.containers ?? []); h.daemon.api = (request) => images(request) ?? caddy(request); h.daemon.run = rootContainer; h.daemon.containers = [CADDY]; @@ -72,8 +72,6 @@ describe('install --infra', () => { profiles: settings().COMPOSE_PROFILES, mode: settings().SITE_MODE, project: settings().COMPOSE_PROJECT_NAME, - network: settings().INGRESS_NETWORK, - external: settings().INGRESS_EXTERNAL, http: settings().HTTP_PORT, url: settings().URL, }, @@ -81,8 +79,6 @@ describe('install --infra', () => { profiles: 'infra', mode: 'infra', project: 'ghost-infra', - network: 'ghost-ingress', - external: 'true', http: '80', url: undefined, }, @@ -90,20 +86,21 @@ describe('install --infra', () => { // Caddy's files, and nothing of a site's: no Ghost or MySQL. assert.deepEqual(files(), [ '.env', - '.env.example', '.ghost-docker.json', 'caddy', - 'compose.ipv6.yml', 'compose.yml', 'ghost-docker', ]); + // Its own compose.yml and Caddyfile, which name no site. + assert.match(readFileSync(join(h.dir, 'compose.yml'), 'utf8'), /profiles: \[infra\]/); + assert.match(readFileSync(join(h.dir, 'caddy', 'Caddyfile'), 'utf8'), /on_demand/); const metadata = JSON.parse(readFileSync(join(h.dir, '.ghost-docker.json'), 'utf8')); assert.equal(metadata.mode, 'infra'); assert.equal(metadata.ghost, null); assert.deepEqual(metadata.site, { project: 'ghost-infra', dir: h.dir }); assert.ok(metadata.payload['caddy/Caddyfile'] && metadata.payload['ghost-docker']); assert.ok(!Object.keys(metadata.payload).some((file) => file.startsWith('mysql-init/'))); - assert.ok(existsSync(join(h.dir, 'caddy', 'sites'))); + assert.ok(!existsSync(join(h.dir, 'caddy', 'sites')), 'it holds no site\u2019s routes'); assert.ok(compose.some((args) => args[0] === 'up')); assert.match(result.stdout, /The shared Caddy is installed/); }); @@ -143,6 +140,15 @@ describe('install --infra', () => { ); }); + test('--email is its ACME account, for every site behind it', async () => { + const result = await h.run('install', '--infra', '--email', 'me@example.com', '--no-start'); + assert.equal(result.code, 0, result.stderr); + assert.match( + readFileSync(join(h.dir, 'caddy', 'global', 'acme.caddy'), 'utf8'), + /^email me@example\.com$/m, + ); + }); + test('it is Caddy, so it takes no --no-caddy', async () => { const result = await h.run('install', '--infra', '--no-caddy'); assert.equal(result.code, 2); @@ -159,7 +165,7 @@ describe('install --infra', () => { }); test('a network another installation created meanwhile is not removed', async () => { - shared.raced.network = true; + shared.raced = true; const result = await h.run('install', '--infra'); assert.equal(result.code, 1); assert.equal(shared.exists, true); @@ -170,6 +176,8 @@ describe('install --infra', () => { describe('self-update of the shared Caddy', () => { const FIRST = `sha256:${'2'.repeat(64)}`; const SECOND = `sha256:${'3'.repeat(64)}`; + /** A file of the shared Caddy's own stack that the next release changes. */ + const FILE = join('caddy', 'custom', 'README.md'); let manager: string; let up: () => ReturnType; const release = (version: string) => @@ -179,11 +187,10 @@ describe('self-update of the shared Caddy', () => { beforeEach(async () => { shared.exists = false; h.daemon.containers = []; - const stack = h.env.GD_STACK_DIR!; - h.env.GD_VERSION_FILE = `${stack}-version.json`; + h.env.GD_VERSION_FILE = `${h.env.GD_STACK_DIR!}-version.json`; manager = FIRST; const images = imageApi({ manager: () => manager }); - const caddy = sharedApi(shared); + const caddy = sharedApi(shared, () => h.daemon.containers ?? []); h.daemon.api = (request) => images(request) ?? caddy(request); up = () => ok(''); ps = () => @@ -209,16 +216,13 @@ describe('self-update of the shared Caddy', () => { // The next release: a new image, with a changed snippet. release('v0.1.0-beta.2'); manager = SECOND; - writeFileSync(join(stack, 'caddy', 'snippets', 'Logging'), '# changed in beta.2\n'); + writeFileSync(join(infraStackDir(h.env), FILE), '# changed in beta.2\n'); }); test('moves its files and launcher to the release, and recreates Caddy, with no backup', async () => { const result = await h.run('self-update'); assert.equal(result.code, 0, result.stderr); - assert.equal( - readFileSync(join(h.dir, 'caddy', 'snippets', 'Logging'), 'utf8'), - '# changed in beta.2\n', - ); + assert.equal(readFileSync(join(h.dir, FILE), 'utf8'), '# changed in beta.2\n'); assert.match( readFileSync(join(h.dir, 'ghost-docker'), 'utf8'), new RegExp(`GD_PINNED_IMAGE="${SECOND}"`), @@ -231,20 +235,9 @@ describe('self-update of the shared Caddy', () => { compose.map((args) => args[0]), ['pull', 'config', 'up', 'exec', 'ps'], ); - // Serialized with the sites' route changes. assert.deepEqual( compose.find((args) => args[0] === 'exec'), - [ - 'exec', - '-T', - 'caddy', - 'flock', - '/etc/caddy/sites', - 'caddy', - 'reload', - '--config', - '/etc/caddy/Caddyfile', - ], + ['exec', '-T', 'caddy', 'caddy', 'reload', '--config', '/etc/caddy/Caddyfile'], ); assert.ok(!existsSync(join(h.dir, 'backups'))); assert.ok(!existsSync(join(h.dir, '.ghost-docker-update'))); @@ -256,34 +249,31 @@ describe('self-update of the shared Caddy', () => { }); test('--check says what it would change, and changes nothing', async () => { - const before = readFileSync(join(h.dir, 'caddy', 'snippets', 'Logging'), 'utf8'); + const before = readFileSync(join(h.dir, FILE), 'utf8'); const result = await h.run('self-update', '--check'); assert.equal(result.code, 0, result.stderr); assert.match(result.stdout, /An update is available\. Caddy restarts with it\./); - assert.match(result.stdout, /caddy\/snippets\/Logging: replaced/); - assert.equal(readFileSync(join(h.dir, 'caddy', 'snippets', 'Logging'), 'utf8'), before); + assert.match(result.stdout, /caddy\/custom\/README\.md: replaced/); + assert.equal(readFileSync(join(h.dir, FILE), 'utf8'), before); assert.deepEqual(compose, []); }); test("an edited file is kept, with the release's beside it", async () => { - writeFileSync(join(h.dir, 'caddy', 'snippets', 'Logging'), '# mine\n'); + writeFileSync(join(h.dir, FILE), '# mine\n'); const result = await h.run('self-update'); assert.equal(result.code, 0, result.stderr); - assert.equal(readFileSync(join(h.dir, 'caddy', 'snippets', 'Logging'), 'utf8'), '# mine\n'); - assert.equal( - readFileSync(join(h.dir, 'caddy', 'snippets', 'Logging.new'), 'utf8'), - '# changed in beta.2\n', - ); + assert.equal(readFileSync(join(h.dir, FILE), 'utf8'), '# mine\n'); + assert.equal(readFileSync(join(h.dir, `${FILE}.new`), 'utf8'), '# changed in beta.2\n'); }); test('a Caddy that does not become healthy is put back on the files it ran', async () => { - const before = readFileSync(join(h.dir, 'caddy', 'snippets', 'Logging'), 'utf8'); + const before = readFileSync(join(h.dir, FILE), 'utf8'); let ups = 0; up = () => (ups++ === 0 ? failed(1, 'container caddy is unhealthy') : ok('')); const result = await h.run('self-update'); assert.equal(result.code, 1); assert.match(result.stderr, /is back on v0\.1\.0-beta\.1, and running/); - assert.equal(readFileSync(join(h.dir, 'caddy', 'snippets', 'Logging'), 'utf8'), before); + assert.equal(readFileSync(join(h.dir, FILE), 'utf8'), before); assert.match( readFileSync(join(h.dir, 'ghost-docker'), 'utf8'), new RegExp(`GD_PINNED_IMAGE="${FIRST}"`), @@ -295,7 +285,7 @@ describe('self-update of the shared Caddy', () => { }); test('a configuration Caddy will not reload is put back, and the old one loaded again', async () => { - const before = readFileSync(join(h.dir, 'caddy', 'snippets', 'Logging'), 'utf8'); + const before = readFileSync(join(h.dir, FILE), 'utf8'); let reloads = 0; h.daemon.composeRun = (args) => { compose.push(args); @@ -311,12 +301,12 @@ describe('self-update of the shared Caddy', () => { assert.equal(result.code, 1); assert.match(result.stderr, /did not load its configuration[\s\S]*unknown directive/); assert.match(result.stderr, /is back on v0\.1\.0-beta\.1, and running/); - assert.equal(readFileSync(join(h.dir, 'caddy', 'snippets', 'Logging'), 'utf8'), before); + assert.equal(readFileSync(join(h.dir, FILE), 'utf8'), before); assert.equal(reloads, 2); }); test('images it cannot pull refuse the update before any file is written', async () => { - const before = readFileSync(join(h.dir, 'caddy', 'snippets', 'Logging'), 'utf8'); + const before = readFileSync(join(h.dir, FILE), 'utf8'); h.daemon.composeRun = (args) => { compose.push(args); return args[0] === 'pull' ? failed(1, 'manifest unknown') : ok(''); @@ -324,7 +314,7 @@ describe('self-update of the shared Caddy', () => { const result = await h.run('self-update'); assert.equal(result.code, 1); assert.match(result.stderr, /could not be pulled[\s\S]*Nothing has been changed/); - assert.equal(readFileSync(join(h.dir, 'caddy', 'snippets', 'Logging'), 'utf8'), before); + assert.equal(readFileSync(join(h.dir, FILE), 'utf8'), before); assert.deepEqual( compose.map((args) => args[0]), ['pull'], @@ -332,58 +322,23 @@ describe('self-update of the shared Caddy', () => { assert.equal(metadata().stack.version, 'v0.1.0-beta.1'); }); - test("a failure before Caddy restarts reloads the old files, which a site's reload may have replaced", async () => { - const before = readFileSync(join(h.dir, 'caddy', 'snippets', 'Logging'), 'utf8'); - let live = before; + test('a release that does not validate is put back, with Caddy never restarted', async () => { + const before = readFileSync(join(h.dir, FILE), 'utf8'); h.daemon.composeRun = (args) => { compose.push(args); - switch (args[0]) { - case 'config': - // A site installs meanwhile, and its reload loads the - // release's files; then the release does not validate. - live = readFileSync(join(h.dir, 'caddy', 'snippets', 'Logging'), 'utf8'); - return failed(1, 'services.caddy: invalid'); - case 'exec': - live = readFileSync(join(h.dir, 'caddy', 'snippets', 'Logging'), 'utf8'); - return ok(''); - case 'ps': - return ok(ps()); - default: - return ok(''); - } + return args[0] === 'config' ? failed(1, 'services.caddy: invalid') : ok(''); }; const result = await h.run('self-update'); assert.equal(result.code, 1); - assert.match( - result.stderr, - /back on v0\.1\.0-beta\.1, with its configuration loaded again/, + assert.match(result.stderr, /back on v0\.1\.0-beta\.1, which it never stopped running/); + assert.equal(readFileSync(join(h.dir, FILE), 'utf8'), before); + assert.deepEqual( + compose.map((args) => args[0]), + ['pull', 'config'], ); - assert.equal(live, before); - assert.equal(compose.filter((args) => args[0] === 'up').length, 0); - assert.deepEqual(compose.at(-1)!.slice(0, 5), [ - 'exec', - '-T', - 'caddy', - 'flock', - '/etc/caddy/sites', - ]); assert.ok(!existsSync(join(h.dir, '.ghost-docker-update'))); }); - test('a Caddy that will not reload the old files is left for the operator', async () => { - h.daemon.composeRun = (args) => { - compose.push(args); - if (args[0] === 'config') { - return failed(1, 'services.caddy: invalid'); - } - return args[0] === 'exec' ? failed(1, 'container caddy is not running') : ok(''); - }; - const result = await h.run('self-update'); - assert.equal(result.code, 1); - assert.match(result.stderr, /Caddy did not load them[\s\S]*not running/); - assert.ok(existsSync(join(h.dir, '.ghost-docker-update', 'files'))); - }); - test('a Caddy that will not start again either is left for the operator, with the files kept', async () => { up = () => failed(1, 'Bind for 0.0.0.0:443 failed'); const result = await h.run('self-update'); @@ -438,7 +393,7 @@ describe('self-update of the shared Caddy', () => { return SECOND; }, }); - const caddy = sharedApi(shared); + const caddy = sharedApi(shared, () => h.daemon.containers ?? []); h.daemon.api = (request) => images(request) ?? caddy(request); const result = await h.run('self-update'); assert.equal(result.code, 1); @@ -456,11 +411,13 @@ describe('self-update of the shared Caddy', () => { }); describe('a production install on a server with the shared Caddy', () => { - test('joins it: no Caddy of its own, its routes in the shared Caddy, loaded', async () => { + test('joins it: its own Caddy behind the shared one, its routes in its own directory', async () => { const result = await h.run( 'install', '--domain', 'example.com', + '--admin-domain', + 'admin.example.com', '--with', 'activitypub', '--no-start', @@ -469,126 +426,88 @@ describe('a production install on a server with the shared Caddy', () => { const values = settings(); assert.equal(values.COMPOSE_PROFILES, 'shared-caddy,activitypub'); assert.equal(values.SITE_MODE, 'production'); - assert.equal(values.INGRESS_NETWORK, 'ghost-ingress'); - assert.equal(values.INGRESS_EXTERNAL, 'true'); + // The names its Caddy answers to on the shared Caddy's network. + assert.equal(values.INGRESS_HOST, 'example.com'); + assert.equal(values.INGRESS_ADMIN_HOST, 'admin.example.com'); + // 80 and 443 are the shared Caddy's. assert.equal(values.HTTP_PORT, undefined); - assert.ok(!existsSync(join(h.dir, 'caddy')), 'a site behind it has no caddy/ of its own'); - const routes = shared.sites.get('ghost-example-com.caddy')!; - assert.match(routes, /^example\.com \{$/m); + const routes = readFileSync(join(h.dir, 'caddy', 'sites', 'site.caddy'), 'utf8'); + // Plain HTTP: the shared Caddy holds the certificates. + assert.match(routes, /^http:\/\/example\.com, http:\/\/admin\.example\.com \{$/m); + assert.doesNotMatch(routes, /^\s*tls /m); assert.match(routes, /reverse_proxy ghost-ghost-example-com:2368/); assert.match(routes, /ActivityPub activitypub-ghost-example-com:8080/); - // Written as whoever owns caddy/sites/, then validated, then loaded. - const commands = shared.execs.map( - ({ cmd, user }) => `${cmd[0]} ${cmd[1]}${user ? ` as ${user}` : ''}`, + assert.match(routes, /docker compose exec caddy-internal caddy reload/); + // Without this Ghost never sees https, and redirects for ever. + assert.match( + readFileSync(join(h.dir, 'caddy', 'global', 'shared-caddy.caddy'), 'utf8'), + /trusted_proxies static private_ranges/, ); - assert.deepEqual(commands.slice(-4), [ - 'stat -c', - 'sh -c as 1000:1000', - 'caddy validate', - 'flock /etc/caddy/sites', - ]); - assert.ok(shared.hosts.has('example.com')); const metadata = JSON.parse(readFileSync(join(h.dir, '.ghost-docker.json'), 'utf8')); assert.equal(metadata.mode, 'production'); - assert.ok(!Object.keys(metadata.payload).some((file) => file.startsWith('caddy/'))); - assert.match( - result.stdout, - /Routes +\/srv\/caddy\/caddy\/sites\/ghost-example-com\.caddy, served by the shared Caddy/, - ); + assert.ok(metadata.payload['caddy/Caddyfile']); + assert.ok(!Object.keys(metadata.payload).some((file) => file.startsWith('infra/'))); + assert.match(result.stdout, /Ingress +the shared Caddy in \/srv\/caddy/); }); - test('80 and 443 are the shared Caddy’s, and not asked for', async () => { + test('a site without an admin domain has one name', async () => { const result = await h.run('install', '--domain', 'example.com', '--no-start'); assert.equal(result.code, 0, result.stderr); + assert.equal(settings().INGRESS_HOST, 'example.com'); + assert.equal(settings().INGRESS_ADMIN_HOST, undefined); }); - test('a domain it already serves is refused before anything is written', async () => { - shared.hosts.add('www.example.com'); + test('a domain another site behind it answers to is refused before anything is written', async () => { + h.daemon.containers = [ + CADDY, + siteCaddy('ghost-other-com', ['other.com', 'www.example.com']), + ]; const result = await h.run( 'install', '--domain', 'blog.example.com', '--admin-domain', - 'www.example.com', + 'WWW.example.com', '--no-start', ); assert.equal(result.code, 1); - assert.match(result.stderr, /already serves www\.example\.com/); - assert.deepEqual(files(), []); - assert.equal(shared.sites.size, 0); - }); - - test('a project that already has routes is refused before anything is written', async () => { - shared.sites.set('ghost-example-com.caddy', 'routes of another directory'); - const result = await h.run('install', '--domain', 'example.com', '--no-start'); - assert.equal(result.code, 1); assert.match( result.stderr, - /ghost-example-com\.caddy already exists: the project ghost-example-com already has routes/, + /www\.example\.com is already served behind the shared Caddy, by the site ghost-other-com\n {2}in \/srv\/ghost-other-com/, ); - assert.match(result.stderr, /--name/); assert.deepEqual(files(), []); - assert.equal(shared.sites.get('ghost-example-com.caddy'), 'routes of another directory'); }); - test('routes another installation wrote meanwhile are refused, and left alone', async () => { - shared.raced.routes = 'routes of another directory'; + test('a stopped site still holds its domains', async () => { + h.daemon.containers = [CADDY, siteCaddy('ghost-other-com', ['example.com'], 'exited')]; const result = await h.run('install', '--domain', 'example.com', '--no-start'); assert.equal(result.code, 1); - assert.match(result.stderr, /could not be written to the shared Caddy/); - assert.equal(shared.sites.get('ghost-example-com.caddy'), 'routes of another directory'); + assert.match(result.stderr, /example\.com is already served behind the shared Caddy/); assert.deepEqual(files(), []); }); - test('routes written with no result reported are still undone, by their marker', async () => { - shared.lost = true; - const result = await h.run('install', '--domain', 'example.com', '--no-start'); - assert.equal(result.code, 1); - assert.match(result.stderr, /could not be written to the shared Caddy/); - assert.equal(shared.sites.size, 0); - assert.deepEqual(files(), []); - }); - - test("another's routes are left alone when a write's result is unknown", async () => { - shared.lost = true; - shared.raced.routes = 'routes of another directory'; - const result = await h.run('install', '--domain', 'example.com', '--no-start'); - assert.equal(result.code, 1); - assert.equal(shared.sites.get('ghost-example-com.caddy'), 'routes of another directory'); - }); - - test('a stopped shared Caddy is refused, saying how to start it', async () => { - h.daemon.containers = [{ ...CADDY, State: 'exited' }]; - const result = await h.run('install', '--domain', 'example.com', '--no-start'); - assert.equal(result.code, 1); - assert.match( - result.stderr, - /the shared Caddy in \/srv\/caddy is not running[\s\S]*cd \/srv\/caddy && docker compose up -d/, + test('--email is the shared Caddy’s to set', async () => { + const result = await h.run( + 'install', + '--domain', + 'example.com', + '--email', + 'me@example.com', + '--no-start', ); - assert.deepEqual(files(), []); - }); - - test('routes Caddy refuses are removed with everything else the installation created', async () => { - shared.refuse = 'Error: adapting config using caddyfile: ambiguous site definition'; - // Removed once, by addRoutes: the file is then not this install's to undo. - const removals = () => shared.execs.filter(({ cmd }) => cmd[0] === 'rm').length; - const result = await h.run('install', '--domain', 'example.com', '--no-start'); - assert.equal(result.code, 1); + assert.equal(result.code, 2); assert.match( result.stderr, - /does not accept its configuration[\s\S]*ambiguous site definition/, + /--email is the ACME account[\s\S]*the shared Caddy in \/srv\/caddy/, ); - assert.equal(shared.sites.size, 0); assert.deepEqual(files(), []); - assert.equal(removals(), 1); }); test('a local site never joins it', async () => { const result = await h.run('install', '--local', '--no-start'); assert.equal(result.code, 0, result.stderr); assert.equal(settings().COMPOSE_PROFILES, 'local'); - assert.equal(settings().INGRESS_NETWORK, undefined); - assert.deepEqual(shared.execs, []); + assert.equal(settings().INGRESS_HOST, undefined); }); test('a site behind your own proxy never joins it', async () => { @@ -601,21 +520,22 @@ describe('a production install on a server with the shared Caddy', () => { ); assert.equal(result.code, 0, result.stderr); assert.equal(settings().COMPOSE_PROFILES, 'no-caddy'); - assert.equal(settings().INGRESS_NETWORK, undefined); - assert.deepEqual(shared.execs, []); - assert.equal(shared.sites.size, 0); + assert.equal(settings().INGRESS_HOST, undefined); }); }); describe('a server without one', () => { - test('a production site gets a Caddy and a network of its own, as before', async () => { + test('a production site gets a Caddy of its own on 80 and 443, as before', async () => { shared.exists = false; h.daemon.containers = []; const result = await h.run('install', '--domain', 'example.com', '--no-start'); assert.equal(result.code, 0, result.stderr); assert.equal(settings().COMPOSE_PROFILES, 'production'); - assert.equal(settings().INGRESS_NETWORK, undefined); - assert.ok(existsSync(join(h.dir, 'caddy', 'sites', 'site.caddy'))); + assert.equal(settings().INGRESS_HOST, undefined); + assert.equal(settings().HTTP_PORT, '80'); + const routes = readFileSync(join(h.dir, 'caddy', 'sites', 'site.caddy'), 'utf8'); + assert.match(routes, /^example\.com \{$/m); + assert.ok(!existsSync(join(h.dir, 'caddy', 'global', 'shared-caddy.caddy'))); }); }); @@ -632,69 +552,11 @@ const sharedCaddyEnv = (project = 'ghost-example-com') => ['GHOST_VERSION', '6-next-alpine'], ['DATABASE_PASSWORD', 'a'], ['DATABASE_ROOT_PASSWORD', 'b'], - ['INGRESS_NETWORK', 'ghost-ingress'], - ['INGRESS_EXTERNAL', 'true'], + ['INGRESS_HOST', 'example.com'], ]), { mode: 0o600 }, ); -describe('remove', () => { - test("a site's routes are removed and the shared Caddy reloaded, then the site is taken down", async () => { - sharedCaddyEnv(); - shared.sites.set('ghost-example-com.caddy', 'example.com {\n}\n'); - shared.sites.set('ghost-other-com.caddy', 'other.com {\n}\n'); - const result = await h.run('remove', '--yes'); - assert.equal(result.code, 0, result.stderr); - assert.deepEqual([...shared.sites.keys()], ['ghost-other-com.caddy']); - assert.deepEqual(shared.execs.map(({ cmd }) => cmd[0]).slice(-2), ['rm', 'flock']); - assert.ok(compose.some((args) => args[0] === 'down' && !args.includes('--volumes'))); - assert.ok(existsSync(join(h.dir, '.env')), 'the directory and its data stay'); - assert.match(result.stdout, /still holds its configuration, data and backups/); - }); - - test('a server whose shared Caddy is gone is refused, as its routes cannot be removed', async () => { - sharedCaddyEnv(); - shared.exists = false; - const result = await h.run('remove', '--yes'); - assert.equal(result.code, 1); - assert.match(result.stderr, /this server has none \(no ghost-ingress network\)/); - assert.ok(!compose.some((args) => args[0] === 'down')); - }); - - test('a failed docker compose down says the routes are already gone', async () => { - sharedCaddyEnv(); - shared.sites.set('ghost-example-com.caddy', 'example.com {\n}\n'); - h.daemon.composeRun = (args) => (args[0] === 'down' ? failed(1, 'daemon gone') : ok('')); - const result = await h.run('remove', '--yes'); - assert.equal(result.code, 1); - assert.match(result.stderr, /Its routes are already gone from the shared Caddy/); - assert.equal(shared.sites.size, 0); - }); - - test('it is asked, or --yes says so', async () => { - sharedCaddyEnv(); - shared.sites.set('ghost-example-com.caddy', 'x'); - const result = await h.run('remove'); - assert.equal(result.code, 2); - assert.match(result.stderr, /Run it again with --yes/); - assert.equal(shared.sites.size, 1); - assert.ok(!compose.some((args) => args[0] === 'down')); - }); - - test('the shared Caddy itself is not a site', async () => { - writeFileSync( - join(h.dir, '.env'), - env.serializeAll([ - ['COMPOSE_PROFILES', 'infra'], - ['SITE_MODE', 'infra'], - ]), - ); - const result = await h.run('remove', '--yes'); - assert.equal(result.code, 1); - assert.match(result.stderr, /holds the shared Caddy, not a site/); - }); -}); - describe('verification', () => { const answer = { status: 200, @@ -708,12 +570,16 @@ describe('verification', () => { untrusted: null, }, }; - - test("a site behind it is asked for through the shared Caddy, whose routes file is this site's", async () => { + const running = (...services: string[]) => + services + .map((Service) => + JSON.stringify({ ID: Service, Service, State: 'running', Health: 'healthy' }), + ) + .join('\n'); + + test('a site behind it is asked for through the shared Caddy, and its own Caddy is checked', async () => { sharedCaddyEnv(); - shared.sites.set('ghost-example-com.caddy', 'example.com {\n}\n'); - ps = () => - JSON.stringify({ ID: 'g', Service: 'ghost', State: 'running', Health: 'healthy' }); + ps = () => running('ghost', 'caddy-internal'); h.daemon.https = ({ host, servername }) => { assert.equal(host, 'caddy-ghost-example-com'); assert.equal(servername, 'example.com'); @@ -721,9 +587,8 @@ describe('verification', () => { }; const checks = await verifyIngress(h.io(), siteFacts(h.dir, readSettings(h.dir)!)); const by = Object.fromEntries(checks.map((check) => [check.label, check])); + assert.equal(by.caddy?.status, 'ok', by.caddy?.detail ?? ''); assert.equal(by['shared caddy']?.status, 'ok'); - assert.equal(by.routes?.status, 'ok'); - assert.match(by.routes!.detail, /\/srv\/caddy\/caddy\/sites\/ghost-example-com\.caddy/); assert.equal(by.https?.status, 'ok', by.https?.detail ?? ''); assert.match( by['published ports']!.detail, @@ -731,16 +596,12 @@ describe('verification', () => { ); }); - test('routes that are gone, or a shared Caddy that is gone, are errors', async () => { + test('its own Caddy stopped, or a shared Caddy that is gone, are errors', async () => { sharedCaddyEnv(); - ps = () => - JSON.stringify({ ID: 'g', Service: 'ghost', State: 'running', Health: 'healthy' }); + ps = () => running('ghost'); h.daemon.https = () => answer; let checks = await verifyIngress(h.io(), siteFacts(h.dir, readSettings(h.dir)!)); - assert.match( - checks.find((check) => check.label === 'routes')!.detail, - /ghost-example-com\.caddy does not exist/, - ); + assert.equal(checks.find((check) => check.label === 'caddy')!.status, 'error'); shared.exists = false; checks = await verifyIngress(h.io(), siteFacts(h.dir, readSettings(h.dir)!)); const missing = checks.find((check) => check.label === 'shared caddy')!; @@ -762,10 +623,8 @@ describe('list', () => { 'com.docker.compose.project': 'ghost-example-com', }, Ports: [], - NetworkSettings: { - Networks: { 'ghost-example-com_ghost_network': {}, 'ghost-ingress': {} }, - }, }, + siteCaddy('ghost-example-com', ['example.com']), { Id: 's', Names: ['/ghost-solo-com-ghost-1'], @@ -775,7 +634,6 @@ describe('list', () => { 'com.docker.compose.project': 'ghost-solo-com', }, Ports: [], - NetworkSettings: { Networks: { 'ghost-solo-com_ingress': {} } }, }, ]; h.daemon.composeRun = (args) => @@ -800,7 +658,7 @@ describe('list', () => { }); describe('config validate', () => { - test("the shared Caddy's .env needs no Ghost, but its network", async () => { + test("the shared Caddy's .env needs no Ghost", async () => { writeFileSync( join(h.dir, '.env'), env.serializeAll([ @@ -808,8 +666,6 @@ describe('config validate', () => { ['SITE_MODE', 'infra'], ['COMPOSE_PROJECT_NAME', 'ghost-infra'], ['PROJECT_DIR', h.dir], - ['INGRESS_NETWORK', 'ghost-ingress'], - ['INGRESS_EXTERNAL', 'true'], ]), { mode: 0o600 }, ); @@ -823,7 +679,6 @@ describe('config validate', () => { ['COMPOSE_PROFILES', 'infra,activitypub'], ['SITE_MODE', 'infra'], ['COMPOSE_PROJECT_NAME', 'ghost-infra'], - ['PROJECT_DIR', h.dir], ]), { mode: 0o600 }, ); @@ -832,51 +687,44 @@ describe('config validate', () => { assert.match(invalid.stdout + invalid.stderr, /runs Caddy alone: remove activitypub/); assert.match( invalid.stdout + invalid.stderr, - /INGRESS_NETWORK is required for the shared Caddy/, + /PROJECT_DIR is required for the shared Caddy/, ); - assert.match(invalid.stdout + invalid.stderr, /INGRESS_EXTERNAL must be true/); }); - test('a site behind it is a production site, and must be on the shared network', async () => { + test('a site behind it is a production site, named on the shared network by its URLs', async () => { sharedCaddyEnv(); const valid = await h.run('config', 'validate'); assert.equal(valid.code, 0, valid.stdout + valid.stderr); assert.match(valid.stdout, /valid for a production site/); const values = settings(); - delete values.INGRESS_EXTERNAL; - writeFileSync(join(h.dir, '.env'), env.serializeAll(Object.entries(values)), { - mode: 0o600, - }); - const invalid = await h.run('config', 'validate'); - assert.equal(invalid.code, 1); - assert.match(invalid.stdout + invalid.stderr, /INGRESS_EXTERNAL must be true/); - - writeFileSync( - join(h.dir, '.env'), - env.serializeAll( - Object.entries({ ...values, INGRESS_EXTERNAL: 'true', INGRESS_NETWORK: 'other' }), - ), - { mode: 0o600 }, + const write = (changed: Record) => + writeFileSync(join(h.dir, '.env'), env.serializeAll(Object.entries(changed)), { + mode: 0o600, + }); + // The URL moved, and the name did not. + write({ ...values, URL: 'https://moved.example.com' }); + const moved = await h.run('config', 'validate'); + assert.equal(moved.code, 1); + assert.match( + moved.stdout + moved.stderr, + /INGRESS_HOST must be moved\.example\.com, the host of URL[\s\S]*got example\.com/, ); - const elsewhere = await h.run('config', 'validate'); - assert.equal(elsewhere.code, 1); + // An admin domain needs its name too. + write({ ...values, ADMIN_URL: 'https://admin.example.com' }); + const admin = await h.run('config', 'validate'); + assert.equal(admin.code, 1); assert.match( - elsewhere.stdout + elsewhere.stderr, - /INGRESS_NETWORK must be ghost-ingress, the shared Caddy's network: got other/, + admin.stdout + admin.stderr, + /INGRESS_ADMIN_HOST must be admin\.example\.com, the host of ADMIN_URL/, ); - }); - - test('a site needs its database passwords, which compose.yml no longer guards', async () => { - sharedCaddyEnv(); - const values = settings(); - delete values.DATABASE_ROOT_PASSWORD; - writeFileSync(join(h.dir, '.env'), env.serializeAll(Object.entries(values)), { - mode: 0o600, + write({ + ...values, + ADMIN_URL: 'https://admin.example.com', + INGRESS_ADMIN_HOST: 'admin.example.com', }); - const result = await h.run('config', 'validate'); - assert.equal(result.code, 1); - assert.match(result.stdout + result.stderr, /DATABASE_ROOT_PASSWORD is required/); + const both = await h.run('config', 'validate'); + assert.equal(both.code, 0, both.stdout + both.stderr); }); }); @@ -896,14 +744,18 @@ describe('the pieces', () => { const tops = (layout: Parameters[1]) => [ ...new Set(payloadFiles(stack, layout).map((file) => file.split('/')[0])), ]; - assert.deepEqual(tops('infra'), [ - '.env.example', - 'caddy', - 'compose.ipv6.yml', - 'compose.yml', - ]); - assert.ok(!tops('shared-caddy').includes('caddy')); - assert.ok(tops('shared-caddy').includes('tinybird')); + // A site's own Caddy stays, behind the shared one; the shared Caddy's + // stack is its own, and no part of a site's. + assert.deepEqual(tops('shared-caddy'), tops('production')); assert.ok(tops('production').includes('caddy')); + assert.ok(!tops('production').includes('infra')); + assert.deepEqual( + [ + ...new Set( + payloadFiles(infraStackDir(h.env), 'infra').map((file) => file.split('/')[0]), + ), + ], + ['caddy', 'compose.yml'], + ); }); }); diff --git a/manager/test/site.ts b/manager/test/site.ts index 7fee4024..da2f4f68 100644 --- a/manager/test/site.ts +++ b/manager/test/site.ts @@ -227,7 +227,7 @@ export function imageStack(h: Harness): string { for (const file of ['compose.yml', 'compose.ipv6.yml', '.env.example', 'ghost.env.example']) { copyFileSync(join(REPO, file), join(stack, file)); } - for (const directory of ['caddy', 'mysql-init', 'tinybird']) { + for (const directory of ['caddy', 'mysql-init', 'tinybird', 'infra']) { cpSync(join(REPO, directory), join(stack, directory), { recursive: true }); } h.env.GD_STACK_DIR = stack; diff --git a/tests/e2e/shared-caddy.sh b/tests/e2e/shared-caddy.sh index e7f09059..3c8c6f4b 100755 --- a/tests/e2e/shared-caddy.sh +++ b/tests/e2e/shared-caddy.sh @@ -6,15 +6,15 @@ # Builds the manager image from this checkout, sets up the shared Caddy with # `install --infra`, and installs two production sites behind it: one on # Ghost 6.61.0 with ActivityPub, one on the newest Ghost 6, each with its own -# MySQL. Caddy serves them with its own test CA under names curl resolves to -# this host. A third site asking for a domain the shared Caddy already serves -# is refused before anything is written. Then each operation on one site is -# checked to leave the other as it was, the same containers serving the same -# routes: updating the first site's Ghost, backing it up and restoring it over -# itself, restarting and recreating the shared Caddy (both sites come back), -# and removing the second site, whose routes go with it, then restoring it -# from its backup, which holds them. The shared Caddy's -# own directory answers self-update; moving it between releases is unit-tested. +# MySQL, and its own Caddy, which publishes no port. The shared Caddy serves +# them with its own test CA under names curl resolves to this host. A third +# site asking for a domain another already answers to is refused before +# anything is written. Then each operation on one site is checked to leave the +# other, and the shared Caddy's container and files, as they were: updating the +# first site's Ghost, backing it up and restoring it over itself, and taking +# the second site down and restoring it from its backup. Restarting and +# recreating the shared Caddy brings both sites back. The shared Caddy's own +# directory answers self-update; moving it between releases is unit-tested. # # It pulls images, starts containers and binds ports 80 and 443 (it fails # when something else holds them, or is skipped with GD_E2E_ALLOW_SKIP=1). It @@ -53,7 +53,7 @@ work_dir shared-caddy SITES=() SITE="" -# The members first, then the shared Caddy and its network, then every +# The sites first, then the shared Caddy and its network, then every # directory, removed as root: MySQL's data belongs to MySQL's user. teardown() { local site @@ -98,8 +98,17 @@ containers() { compose_in "$1" ps --all -q | sort | xargs docker inspect --format '{{.Id}} {{.State.StartedAt}}' } -# routes -- the shared Caddy's routes files, with their checksums. -routes() { (cd "$CADDY/caddy/sites" && find . -type f | sort | xargs shasum -a 256); } +# shared_caddy -- the shared Caddy's container, and every file of its +# directory's caddy/, with their checksums: what no site's operation changes. +shared_caddy() { + containers "$CADDY" + (cd "$CADDY/caddy" && find . -type f | sort | xargs shasum -a 256) +} + +# unchanged BEFORE -- the shared Caddy is the container it was, on the files it had. +unchanged() { + [[ $(shared_caddy) == "$1" ]] || fail "the shared Caddy's container or files changed" "$(shared_caddy)" +} # untouched SITE BEFORE -- SITE's containers are the ones there were, as they were. untouched() { @@ -121,7 +130,8 @@ run env GD_IMAGE=$IMAGE "$WORK/launcher-only/ghost-docker" --dir "$CADDY" instal expect_status 0 expect_output 'The shared Caddy is installed' [[ $(setting "$CADDY" COMPOSE_PROFILES) == infra ]] || fail "the shared Caddy's profiles are not infra" -[[ ! -e $CADDY/ghost.env && ! -e $CADDY/mysql-init && ! -e $CADDY/data ]] || fail "the shared Caddy has a site's files" +[[ ! -e $CADDY/ghost.env && ! -e $CADDY/mysql-init && ! -e $CADDY/data && ! -e $CADDY/caddy/sites ]] || + fail "the shared Caddy has a site's files" [[ $(docker network inspect ghost-ingress --format '{{index .Labels "org.ghost.docker.infra.dir"}}') == "$CADDY" ]] || fail "the network does not say where the shared Caddy is" [[ $(compose_in "$CADDY" ps --format '{{.Service}} {{.Health}}') == 'caddy healthy' ]] || @@ -148,30 +158,36 @@ A=$SITE run env GD_IMAGE=$IMAGE "$WORK/launcher-only/ghost-docker" --dir "$A" install --domain "$DOMAIN_A" \ --version "$FROM" --with activitypub --no-prompt expect_status 0 -expect_output 'served by the shared Caddy' +expect_output 'Ingress +the shared Caddy in' new_site bravo B=$SITE run env GD_IMAGE=$IMAGE "$WORK/launcher-only/ghost-docker" --dir "$B" install --domain "$DOMAIN_B" --no-prompt expect_status 0 for site in "$A" "$B"; do [[ $(setting "$site" COMPOSE_PROFILES) == shared-caddy* ]] || fail "$site is not behind the shared Caddy" - [[ ! -e $site/caddy ]] || fail "$site has a Caddy of its own" - [[ -z $(compose_in "$site" ps -q caddy) ]] || fail "$site runs a Caddy" + # Its own Caddy and routes, over plain HTTP, publishing nothing. + grep -q '^http://' "$site/caddy/sites/site.caddy" || fail "$site's routes are not plain HTTP" "$(cat "$site/caddy/sites/site.caddy")" + [[ -n $(compose_in "$site" ps -q caddy-internal) ]] || fail "$site's own Caddy is not running" + [[ -z $(compose_in "$site" ps -q caddy) ]] || fail "$site runs a Caddy on 80 and 443" + [[ -z $(docker port "$(compose_in "$site" ps -q caddy-internal)") ]] || fail "$site's Caddy publishes a port" [[ -n $(compose_in "$site" ps -q db) ]] || fail "$site has no MySQL of its own" done -[[ -f $CADDY/caddy/sites/ghost-alpha-e2e-test.caddy && -f $CADDY/caddy/sites/ghost-bravo-e2e-test.caddy ]] || - fail "the routes are not in the shared Caddy" "$(ls "$CADDY/caddy/sites")" +[[ -z $(find "$CADDY/caddy" -name '*alpha*' -o -name '*bravo*') ]] || fail "the shared Caddy's directory names a site" [[ -n $(compose_in "$A" ps -q activitypub) ]] || fail "alpha's ActivityPub is not running" version_a=$(compose_in "$A" exec -T ghost printenv GHOST_VERSION) version_b=$(compose_in "$B" exec -T ghost printenv GHOST_VERSION) [[ $version_a == "$FROM" && $version_b != "$FROM" ]] || fail "the sites run $version_a and $version_b" serves "$DOMAIN_A" serves "$DOMAIN_B" +# Ghost is told the visitor used HTTPS, or it would redirect there for ever. +[[ $(curl --disable --silent --insecure --noproxy '*' --max-time 20 --resolve "$DOMAIN_A:443:127.0.0.1" \ + --output /dev/null --write-out '%{http_code}' "https://$DOMAIN_A/") == 200 ]] || + fail "alpha's front page does not answer 200 through both Caddies" for site in "$A" "$B"; do run gd "$site" check expect_status 0 expect_output 'shared caddy +healthy' - expect_output 'routes +.*\.caddy, in the shared Caddy' + expect_output 'ok +caddy +healthy' done run gd "$A" list expect_status 0 @@ -180,88 +196,78 @@ expect_output '^ghost-alpha-e2e-test +shared-caddy ' expect_output '^ghost-bravo-e2e-test +shared-caddy ' ok "alpha on Ghost $version_a with ActivityPub, bravo on Ghost $version_b; both served, check passes" -step "A domain the shared Caddy serves is refused before anything is written" +step "A domain another site answers to is refused before anything is written" new_site charlie run env GD_IMAGE=$IMAGE "$WORK/launcher-only/ghost-docker" --dir "$SITE" install --domain "www.$DOMAIN_B" \ --admin-domain "$DOMAIN_A" --no-prompt expect_status 1 -expect_output "already serves $DOMAIN_A" +expect_output "$DOMAIN_A is already served behind the shared Caddy" [[ -z $(find "$SITE" -mindepth 1 -not -name .ghost-docker-probe) ]] || fail "the refused install wrote into its directory" "$(ls -A "$SITE")" ok "refused, and $SITE is empty" before_b=$(containers "$B") -routes_before=$(routes) +shared_before=$(shared_caddy) -step "Updating alpha's Ghost leaves bravo untouched" +step "Updating alpha's Ghost leaves bravo and the shared Caddy untouched" run gd "$A" update expect_status 0 expect_output "Updated Ghost from $FROM to " [[ $(compose_in "$A" exec -T ghost printenv GHOST_VERSION) != "$FROM" ]] || fail "alpha still runs $FROM" serves "$DOMAIN_A" untouched "$B" "$before_b" -[[ $(routes) == "$routes_before" ]] || fail "the routes changed" "$(routes)" +unchanged "$shared_before" [[ $(through "$DOMAIN_B") == "https://$DOMAIN_B/" ]] || fail "bravo no longer answers" -ok "alpha updated; bravo's containers and every route as they were" +ok "alpha updated; bravo's containers and the shared Caddy as they were" -step "Backing alpha up and restoring it over itself leaves bravo untouched" +step "Backing alpha up and restoring it over itself leaves bravo and the shared Caddy untouched" run gd "$A" backup expect_status 0 backup=$(find "$A/backups" -mindepth 1 -maxdepth 1 | sort | tail -1) -jq -e '.routes == "routes.caddy"' "$backup/manifest.json" >/dev/null || - fail "the backup does not hold alpha's routes" "$(cat "$backup/manifest.json")" -[[ $(tail -n +2 "$CADDY/caddy/sites/ghost-alpha-e2e-test.caddy") == "$(cat "$backup/routes.caddy")" ]] || - fail "the backup's routes are not alpha's, without their marker line" "$(cat "$backup/routes.caddy")" +# Its routes are its own files, so the backup holds them as a single site's. +[[ -f $backup/site/caddy/sites/site.caddy ]] || fail "the backup does not hold alpha's routes" "$(find "$backup" -maxdepth 3)" run gd "$A" restore --yes "$backup" expect_status 0 serves "$DOMAIN_A" untouched "$B" "$before_b" -[[ $(routes) == "$routes_before" ]] || fail "the routes changed" "$(routes)" -ok "restored $(basename "$backup"); bravo's containers and every route as they were" +unchanged "$shared_before" +ok "restored $(basename "$backup"); bravo's containers and the shared Caddy as they were" -step "Restarting, and recreating, the shared Caddy brings both back" +step "Taking bravo down, and restoring it, leaves alpha and the shared Caddy untouched" before_a=$(containers "$A") -compose_in "$CADDY" restart caddy >/dev/null 2>&1 || fail "Caddy did not restart" -serves "$DOMAIN_A" -serves "$DOMAIN_B" -out=$(compose_in "$CADDY" down 2>&1) || fail "the shared Caddy did not come down" "$out" -docker network inspect ghost-ingress >/dev/null 2>&1 || fail "taking the shared Caddy down removed its network" -compose_in "$CADDY" up --detach --wait >/dev/null 2>&1 || fail "the shared Caddy did not start again" -serves "$DOMAIN_A" -serves "$DOMAIN_B" -untouched "$A" "$before_a" -untouched "$B" "$before_b" -ok "both answer after a restart and after down and up; neither site's containers changed" - -step "Removing bravo removes its routes, and leaves alpha untouched" run gd "$B" backup expect_status 0 backup_b=$(find "$B/backups" -mindepth 1 -maxdepth 1 | sort | tail -1) -run gd "$B" remove -expect_status 2 -expect_output 'Run it again with --yes' -run gd "$B" remove --yes -expect_status 0 -[[ ! -e $CADDY/caddy/sites/ghost-bravo-e2e-test.caddy ]] || fail "bravo's routes are still there" -[[ -f $CADDY/caddy/sites/ghost-alpha-e2e-test.caddy ]] || fail "alpha's routes went too" +out=$(compose_in "$B" down 2>&1) || fail "bravo did not come down" "$out" [[ -z $(compose_in "$B" ps --all -q) ]] || fail "bravo's containers are still there" -[[ -f $B/.env ]] || fail "bravo's directory was not kept" +docker network inspect ghost-ingress >/dev/null 2>&1 || fail "taking a site down removed the shared Caddy's network" [[ $(through "$DOMAIN_B") != "https://$DOMAIN_B/" ]] || fail "bravo still answers" serves "$DOMAIN_A" untouched "$A" "$before_a" +unchanged "$shared_before" run gd "$A" list expect_output '^ghost-alpha-e2e-test +shared-caddy ' refute_output 'ghost-bravo-e2e-test' -ok "bravo removed with its routes; alpha's containers as they were, and served" - -step "Restoring bravo's backup writes its routes back" run gd "$B" restore --yes "$backup_b" expect_status 0 -expect_output "the backup's, written to" -[[ -f $CADDY/caddy/sites/ghost-bravo-e2e-test.caddy ]] || fail "bravo's routes were not written back" serves "$DOMAIN_B" serves "$DOMAIN_A" untouched "$A" "$before_a" -ok "bravo restored behind the shared Caddy, with the routes its backup held; alpha untouched" +unchanged "$shared_before" +before_b=$(containers "$B") +ok "bravo taken down and restored behind the shared Caddy; alpha and the shared Caddy as they were" + +step "Restarting, and recreating, the shared Caddy brings both back" +compose_in "$CADDY" restart caddy >/dev/null 2>&1 || fail "Caddy did not restart" +serves "$DOMAIN_A" +serves "$DOMAIN_B" +out=$(compose_in "$CADDY" down 2>&1) || fail "the shared Caddy did not come down" "$out" +docker network inspect ghost-ingress >/dev/null 2>&1 || fail "taking the shared Caddy down removed its network" +compose_in "$CADDY" up --detach --wait >/dev/null 2>&1 || fail "the shared Caddy did not start again" +serves "$DOMAIN_A" +serves "$DOMAIN_B" +untouched "$A" "$before_a" +untouched "$B" "$before_b" +ok "both answer after a restart and after down and up; neither site's containers changed" passed 'All shared Caddy checks passed.' From ff6f9a9d7d0ff781f003a693639ca4511e5c5e0b Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 6 Dec 2026 17:24:21 +0000 Subject: [PATCH 10/15] Documented what to keep a copy of in the shared Caddy's directory (S13) ref https://linear.app/ghost/issue/PLA-484 The docs said the shared Caddy has no backup because it holds no data, which is true of sites' data but leaves out the two directories an operator may have edited, and which install --infra does not write again: caddy/global/, where a DNS provider's token may be, and caddy/custom/. --- docs/caddy.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/docs/caddy.md b/docs/caddy.md index d46db78e..8f7d7fc4 100644 --- a/docs/caddy.md +++ b/docs/caddy.md @@ -235,6 +235,22 @@ again when it had been recreated. It never updates the sites behind it, and their own `self-update` never touches it; each site's own Caddy is updated with the site. +### What to keep a copy of + +`./ghost-docker backup` is a site's command, and the shared Caddy's directory +has none: it holds no site's data, and `install --infra` sets it up again. +Two things in it are yours, and are not written again: + +- `caddy/global/*.caddy`: the ACME account, and any other global options, + such as a DNS provider, whose file may hold an API token. +- `caddy/custom/*.caddy`: sites of your own that are not Ghost sites. + +Keep a copy of those if you have edited them, and of `compose.override.yml` +if you wrote one. The certificates, in the `caddy_data` volume, need no copy: +Caddy obtains each again when its domain is next asked for. On a server with +many sites, that is many certificates at once, which Let's Encrypt's limits +can slow down; Caddy retries until it has them. + ### Capacity Each site's own Caddy uses little memory (about 15 MB idle), and the shared From efa836fe3bf6617d9fa1238f3bd94608c263ddfe Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 6 Dec 2026 17:52:01 +0000 Subject: [PATCH 11/15] Updated ActivityPub to 1.3.7 to match main main moved to ActivityPub 1.3.7 in #483, whose migrations the 1.3.0 migrations image on this branch does not know. A main site that has run them fails its migration to this layout at activitypub-migrate, as the "Migration from the released main layout" e2e job now does. --- compose.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/compose.yml b/compose.yml index e2b49908..56438535 100644 --- a/compose.yml +++ b/compose.yml @@ -261,7 +261,7 @@ services: - traffic-analytics-${COMPOSE_PROJECT_NAME:-ghost} activitypub: - image: ghcr.io/tryghost/activitypub:1.3.0@sha256:59f0a7470df4ee27b609bd97f4189bf3c6c3f3ecf87f434bbe338fafd5f80070 + image: ghcr.io/tryghost/activitypub:1.3.7@sha256:5a38227c42b9f2f2beb9add2b2ddfdfe922b63579e474819f3d67f341ca168c0 restart: ${RESTART_POLICY:-unless-stopped} profiles: [activitypub] labels: @@ -334,7 +334,7 @@ services: # or failed job stays stopped instead of being restarted by the daemon. activitypub-migrate: - image: ghcr.io/tryghost/activitypub-migrations:1.3.0@sha256:ff5bbf14b71494a95611c6e799d981435b744116c52ad88d20be1d4fef43fa80 + image: ghcr.io/tryghost/activitypub-migrations:1.3.7@sha256:99cb03c660fd7681678f77fd10a3b5e7c86b7d73e27962d47b11043f32e602fb restart: "no" profiles: [activitypub] labels: From d97e459eae68a9911f0f0d29976d070a205f4949 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 6 Dec 2026 17:52:01 +0000 Subject: [PATCH 12/15] Fixed the backup e2e job for a Ghost image without Casper The backup scenario made its theme by copying Casper, which the Ghost image stopped shipping in 6.81: content/themes holds only Source there. It copies Source instead, which every image this layout installs has. --- tests/e2e/backup.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/e2e/backup.sh b/tests/e2e/backup.sh index 75586e53..1ebd9db5 100755 --- a/tests/e2e/backup.sh +++ b/tests/e2e/backup.sh @@ -185,7 +185,7 @@ POST_ID=$(jq -er '.posts[0].id' <<<"$body") # shellcheck disable=SC2016 # expanded by the container's shell compose_in "$A" exec -T --user ghost ghost sh -c \ 'mkdir -p "$GHOST_CONTENT/images/2026/10" && printf "backed-up image" >"$GHOST_CONTENT/images/2026/10/marker.png" && - cp -r "$GHOST_CONTENT/themes/casper" "$GHOST_CONTENT/themes/e2e-theme"' || + cp -r "$GHOST_CONTENT/themes/source" "$GHOST_CONTENT/themes/e2e-theme"' || fail "writing the image and the theme failed" run gd "$A" config set ghost.env "$SETTING_KEY" "$SETTING" expect_status 0 From 3db4cdedc4f96c06643f9c64bbc34c27214214be Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 6 Dec 2026 18:12:13 +0000 Subject: [PATCH 13/15] Checked a site's domains and its shared Caddy wherever it joins, not only at install (S13) ref https://linear.app/ghost/issue/PLA-484 Review found several cases of one rule kept in one caller. Each is moved to where it holds for every caller: - A domain is one site's on the shared network. Only install asked, and only before writing. The question is now heldByAnother in shared.ts: install and restore ask it before they change anything, and verification asks again once the site's Caddy has joined, so the later of two sites started at once finds the other, and so does a site brought up after another took its domain. - A network with no Caddy on it was taken for a shared Caddy by install and restore, which wrote and started a site nothing would serve. refuseWithoutContainer refuses it in both. - install --infra was checked against the site's payload and given a port for Ghost, as a site layout. It is checked against its own stack, and asks for Caddy's ports alone. - The files installation generates were in no conflict check, so one already there was overwritten, and removed by a failed install. They are checked with the payload. docs/caddy.md still said a site's routes go into the shared Caddy's directory, and that an unknown name is answered 502: it fails at TLS. --- docs/architecture.md | 7 ++- docs/caddy.md | 22 +++++--- manager/src/commands/install.ts | 89 ++++++++++++++++++++------------- manager/src/restore.ts | 28 ++++++++--- manager/src/shared.ts | 74 ++++++++++++++++++++++----- manager/src/verify.ts | 22 +++++++- manager/test/backup.test.ts | 49 ++++++++++++++++++ manager/test/shared.test.ts | 72 +++++++++++++++++++++++++- 8 files changed, 293 insertions(+), 70 deletions(-) diff --git a/docs/architecture.md b/docs/architecture.md index cf34ff87..e580a015 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -138,8 +138,11 @@ the site's domains as its aliases on the shared network. The site's routes and Caddy files stay in its own directory, so the file inventory, backup, restore and `self-update` treat them as a single site's, and nothing is ever written in the shared Caddy's directory for a site. Before any write, an -install refuses a domain another site's Caddy has on the network. A restore -refuses a backup of such a site on a server with no shared Caddy. +install or a restore refuses a domain another site's Caddy has on the +network, and a shared Caddy that is missing or has no container. Nothing +locks across sites, so verification asks again once the site's Caddy has +joined (`heldByAnother` in `src/shared.ts`): of two sites started at once, +the one that joins later finds the other there. `src/bundle/manifest.ts` defines the migration bundle schema and depends only on zod so the exporter can share it. Import policy stays outside that schema. diff --git a/docs/caddy.md b/docs/caddy.md index 8f7d7fc4..17fa8d55 100644 --- a/docs/caddy.md +++ b/docs/caddy.md @@ -2,9 +2,9 @@ `./ghost-docker install --domain` writes this site's routes into `caddy/sites/site.caddy`, once. From then on the file is yours, as the nginx -file Ghost-CLI generated was: the manager never rewrites it. On a server with -[the shared Caddy](#the-shared-caddy), the routes go into the shared Caddy's -directory instead, in a file named for the site. +file Ghost-CLI generated was: the manager never rewrites it. That is so on a +server with [the shared Caddy](#the-shared-caddy) too: each site behind it +keeps its routes in its own directory. ## Layout @@ -139,7 +139,9 @@ certificate, and passes each request, whole, to that site's own Caddy. `example.com.ghost.internal`. Nothing else of the site is on that network: not Ghost, not MySQL. - A name no site has is never passed anywhere: `.ghost.internal` resolves on - that network only, and the request is answered `502`. + that network only. The shared Caddy obtains no certificate for such a name, + so a request for it fails at TLS. A name whose site is down, with its + certificate already obtained, is answered `502`. So installing, changing or removing a site writes nothing in the shared Caddy's directory and never reloads or restarts it. After editing a site's @@ -209,10 +211,14 @@ Caddy only when you would trust them on one server anyway, as with Ghost-CLI. The shared Caddy's `caddy_data` volume holds every site's certificates. -Two sites cannot share a domain. `install` refuses a domain another site's -Caddy has, running or stopped. A site taken down with `docker compose down` -holds no name until it is up again, so do not install another site on its -domain while you mean to bring it back. +Two sites cannot share a domain. `install` and `restore` refuse a domain +another site's Caddy has, running or stopped, before they change anything. +A site taken down with `docker compose down` holds no name until it is up +again, so another site can be installed on its domain meanwhile. Whenever a +site is verified (after an install, a restore or an update, and by `check`), +a domain another site also holds is an error named `ingress`: an install +that finds one removes what it created, which is also what happens to the +later of two installs started at once for one domain. ### Restarting and updating it diff --git a/manager/src/commands/install.ts b/manager/src/commands/install.ts index 019ffd0d..3279e9f6 100644 --- a/manager/src/commands/install.ts +++ b/manager/src/commands/install.ts @@ -67,6 +67,7 @@ import { INFRA_PROJECT_LABEL, INGRESS_NETWORK, refuseTaken, + refuseWithoutContainer, type SharedCaddy, } from '../shared.ts'; import { takenPorts } from '../ports.ts'; @@ -436,7 +437,7 @@ export const installCommand = defineCommand({ const context = siteContext(io); const dir = context.siteDir; if (flags.infra) { - return installInfra(refuseOccupied(io, context, dir), flags, release); + return installInfra(refuseOccupied(io, context, dir, true), flags, release); } await clearUnfinishedImport(io, context, dir, flags.import !== undefined); const target = refuseOccupied(io, context, dir); @@ -465,8 +466,12 @@ export const installCommand = defineCommand({ }, }); -/** Refuses a directory that already holds a site, or files the payload would write over. */ -function refuseOccupied(io: Io, context: Context, dir: string): Target { +/** The files installation writes that are in no payload, by what is installed. */ +const ACME_FILE = join('caddy', 'global', 'acme.caddy'); +const GENERATED = { site: [SITE_FILE, SHARED_GLOBAL_FILE], infra: [ACME_FILE] }; + +/** Refuses a directory that already holds a site, or files installation would write over. */ +function refuseOccupied(io: Io, context: Context, dir: string, infra = false): Target { for (const file of [ENV_FILE, META_FILE]) { if (existsSync(join(dir, file))) { throw new CliError( @@ -476,16 +481,19 @@ function refuseOccupied(io: Io, context: Context, dir: string): Target { } } const clone = isCheckout(context, dir); - const stack = stackDir(io.env); + const stack = infra ? infraStackDir(io.env) : stackDir(io.env); const files = clone ? [] : payloadFiles(stack); - if (!clone) { - const conflicts = payloadConflicts(dir, files); - if (conflicts.length > 0) { - throw new CliError( - `${dir} already has ${conflicts.slice(0, 5).join(', ')}${conflicts.length > 5 ? ', …' : ''}, which installation would write.\n` + - ' Install into a new, empty directory, or move these aside. Nothing has been changed.', - ); - } + // The payload, and what installation generates beside it, which a + // failed one would otherwise remove as its own. + const conflicts = [ + ...(clone ? [] : payloadConflicts(dir, files)), + ...(infra ? GENERATED.infra : GENERATED.site).filter((file) => existsSync(join(dir, file))), + ]; + if (conflicts.length > 0) { + throw new CliError( + `${dir} already has ${conflicts.slice(0, 5).join(', ')}${conflicts.length > 5 ? ', …' : ''}, which installation would write.\n` + + ' Install into a new, empty directory, or move these aside. Nothing has been changed.', + ); } for (const data of [...DATA_DIRS, MAILPIT_DATA_DIR]) { const path = join(dir, data); @@ -519,6 +527,7 @@ async function prepare( // installed behind it. const shared = intent.layout === 'production' ? await findSharedCaddy(io) : null; if (shared !== null) { + refuseWithoutContainer(shared); if (flags.email !== undefined) { throw new UsageError( `--email is the ACME account of the Caddy that obtains certificates, which for this site is\n` + @@ -611,18 +620,41 @@ async function sitePorts( : null; const wanted = [ port, - // Caddy's, for a site with its own, or the shared Caddy itself. - ...(layout === 'production' || layout === INFRA_PROFILE - ? [PRODUCTION_PORTS.http, PRODUCTION_PORTS.https] - : []), + // Caddy's, for a site with its own. The shared Caddy asks for its own (installInfra). + ...(layout === 'production' ? [PRODUCTION_PORTS.http, PRODUCTION_PORTS.https] : []), ]; + refuseHeldPorts(io, taken, wanted, port); + // A running container's port was refused above, so whatever listens here + // is not Docker publishing this daemon's own port. + if (requested !== undefined && (await io.hostListens(port))) { + throw new CliError( + `port ${port} is already in use on this host by something outside Docker, such as a\n` + + ' Ghost-CLI site (`ghost ls` lists those). Docker here would publish the site on it\n' + + ' anyway, and the other program would keep answering. Choose another port with --port.\n' + + ' Nothing has been changed.', + ); + } + return { port, mailpitPort }; +} + +/** + * Refuses ports a running container holds, and warns of ones a stopped + * container would take back. `ghost` is Ghost's among them, for a site; the + * shared Caddy has no Ghost, and asks for Caddy's alone. + */ +function refuseHeldPorts( + io: Io, + taken: Awaited>, + wanted: readonly number[], + ghost?: number, +): void { const holders = taken.holders(wanted); if (holders.size > 0) { throw new CliError( `${[...holders.values()].join('\n ')}\n` + - (holders.has(port) + (ghost !== undefined && holders.has(ghost) ? ` Choose another port for Ghost with --port.` - : ' A production site needs ports 80 and 443 for Caddy. Free them first.') + + : ' Caddy needs ports 80 and 443. Free them first.') + '\n Nothing was stopped. Nothing has been changed.', ); } @@ -634,17 +666,6 @@ async function sitePorts( detail, })), ); - // A running container's port was refused above, so whatever listens here - // is not Docker publishing this daemon's own port. - if (requested !== undefined && (await io.hostListens(port))) { - throw new CliError( - `port ${port} is already in use on this host by something outside Docker, such as a\n` + - ' Ghost-CLI site (`ghost ls` lists those). Docker here would publish the site on it\n' + - ' anyway, and the other program would keep answering. Choose another port with --port.\n' + - ' Nothing has been changed.', - ); - } - return { port, mailpitPort }; } /** The first port no container publishes and, where that can be told, nothing on the host holds. */ @@ -878,9 +899,6 @@ async function startAndVerify({ io, dir, layout }: Site, created: Created) { // --- The shared Caddy ------------------------------------------------------------ -/** The shared Caddy's ACME account, written when --email names one. */ -const ACME_FILE = join('caddy', 'global', 'acme.caddy'); - /** * `install --infra`: the shared Caddy, alone, in its own directory and * project, on a network of its own that each production site installed after @@ -888,7 +906,7 @@ const ACME_FILE = join('caddy', 'global', 'acme.caddy'); * its metadata records the stack files, for self-update. */ async function installInfra(target: Target, flags: Flags, requested: Requested): Promise { - const { io, context, dir, clone } = target; + const { io, context, dir, clone, stack, files } = target; const release = releaseOf(requested, io.env); const existing = await findSharedCaddy(io); if (existing !== null) { @@ -904,9 +922,8 @@ async function installInfra(target: Target, flags: Flags, requested: Requested): ' directory is a checkout of the repository. Nothing has been changed.', ); } - const stack = infraStackDir(io.env); await preflight(io, context); - await sitePorts(io, INFRA_PROFILE, undefined, false); + refuseHeldPorts(io, await takenPorts(io), [PRODUCTION_PORTS.http, PRODUCTION_PORTS.https]); const pin = await io.busy('Resolving the manager image', () => managerPin(io, context)); const project = flags.name ?? INFRA_PROJECT; await refuseForeignProject(io, project, dir); @@ -914,7 +931,7 @@ async function installInfra(target: Target, flags: Flags, requested: Requested): const created = new Created(io, context, dir); try { heading(io, 'Writing the shared Caddy'); - writePayload(dir, stack, payloadFiles(stack), created); + writePayload(dir, stack, files, created); ok(io, 'stack files', 'compose.yml and caddy/ from the manager image'); writeLauncher(dir, io.env, { image: pin, channel: release.channel }, created); ok(io, 'ghost-docker', `the launcher, pinned to ${pin}`); diff --git a/manager/src/restore.ts b/manager/src/restore.ts index 0965ac14..062c11dc 100644 --- a/manager/src/restore.ts +++ b/manager/src/restore.ts @@ -49,7 +49,11 @@ import { SHARED_CADDY_PROFILE, siteFacts, } from './site.ts'; -import { findSharedCaddy } from './shared.ts'; +import { + findSharedCaddy, + refuseTaken as refuseTakenDomains, + refuseWithoutContainer, +} from './shared.ts'; import { verifySite } from './verify.ts'; /** `over`: the backup's own site, replaced. `fresh`: a new, empty directory. */ @@ -85,7 +89,7 @@ export async function restoreSite({ io, context, root, yes }: RestoreInput): Pro await refuseOtherCommit(io, dir, manifest); } await refuseOtherConfiguration(io, root, dir, manifest); - await refuseWithoutSharedCaddy(io, root); + await refuseWithoutSharedCaddy(io, root, manifest.site.project); if (existsSync(join(dir, RESTORE_DIR))) { throw new CliError( `${join(dir, RESTORE_DIR)} is left from a restore that did not finish, and holds the site as\n` + @@ -333,20 +337,28 @@ function restoredEnv(text: string, dir: string, manifest: BackupManifest): strin /** * A site that was behind the shared Caddy is restored behind one: its own * Caddy publishes no port and joins the shared Caddy's network, which must - * exist. Its routes are in the backup, with the rest of the site's files. + * exist, with the shared Caddy on it. Its domains must be no other site's + * there: one installed for them since the backup would share their names + * with this one, and be answered with either. */ -async function refuseWithoutSharedCaddy(io: Io, root: string): Promise { +async function refuseWithoutSharedCaddy(io: Io, root: string, project: string): Promise { const settings = env.toRecord(readIfExists(join(root, SITE_FILES_DIR, ENV_FILE)) ?? ''); - if ( - hasProfile(settings.COMPOSE_PROFILES ?? '', SHARED_CADDY_PROFILE) && - (await findSharedCaddy(io)) === null - ) { + if (!hasProfile(settings.COMPOSE_PROFILES ?? '', SHARED_CADDY_PROFILE)) { + return; + } + const shared = await findSharedCaddy(io); + if (shared === null) { throw new CliError( 'this backup is of a site behind the shared Caddy, and this server has none.\n' + ' Set one up first with ./ghost-docker install --infra, in a directory of its own\n' + ' (docs/caddy.md#the-shared-caddy). Nothing has been changed.', ); } + refuseWithoutContainer(shared); + const names = [settings.INGRESS_HOST, settings.INGRESS_ADMIN_HOST].filter( + (name): name is string => name !== undefined && name !== '', + ); + await refuseTakenDomains(io, shared, project, names); } async function refuseOtherConfiguration( diff --git a/manager/src/shared.ts b/manager/src/shared.ts index c529bf29..c2f43a8f 100644 --- a/manager/src/shared.ts +++ b/manager/src/shared.ts @@ -74,17 +74,44 @@ export const describeShared = (shared: SharedCaddy): string => `the shared Caddy${shared.dir ? ` in ${shared.dir}` : ''}`; /** - * Refuses a site whose domains another site behind the shared Caddy already - * answers to, before anything is written. Docker would attach both, and - * answer the name with either. Every site's Caddy counts, running or not; - * one taken down with `docker compose down` holds no name until it is up. + * A network left with no Caddy on it is not a shared Caddy a site can go + * behind: nothing would serve the site. Refused before anything is written, + * wherever a site is about to join it. */ -export async function refuseTaken( +export function refuseWithoutContainer(shared: SharedCaddy): void { + if (shared.container === null) { + throw new CliError( + `${describeShared(shared)} has no Caddy container: only its network, ${shared.network}, is left.\n` + + ' Start it first, in its directory (docker compose up -d), or, if it is gone for good,\n' + + ` remove the network: docker network rm ${shared.network}. Nothing has been changed.`, + ); + } +} + +/** Another site's Caddy answering to some of a site's domains on the shared network. */ +export interface Holder { + readonly domains: readonly string[]; + readonly project: string; + /** Its directory on the host, when its container says. */ + readonly dir: string | undefined; +} + +/** + * The other site, if any, whose Caddy answers on the shared network to one of + * `domains`. Docker attaches both and answers the name with either, so a + * domain is one site's. Every site's Caddy counts, running or not; one taken + * down with `docker compose down` holds no name until it is up. + * + * Asked before a site is written (refuseTaken) and again once its Caddy has + * joined (verify.ts): of two sites started at once, the one that joins later + * always finds the other there. + */ +export async function heldByAnother( io: Io, - shared: SharedCaddy, + network: string, project: string, domains: readonly string[], -): Promise { +): Promise { const wanted = new Map( domains .map((domain) => domain.toLowerCase()) @@ -99,16 +126,37 @@ export async function refuseTaken( for (const container of others) { const detail = await inspectContainer(io.docker, container.id); const names = - detail?.endpoints.find((endpoint) => endpoint.network === shared.network)?.names ?? []; + detail?.endpoints.find((endpoint) => endpoint.network === network)?.names ?? []; const taken = names .map((alias) => wanted.get(alias.toLowerCase())) .filter((domain) => domain !== undefined); if (taken.length > 0) { - const where = container.labels[WORKING_DIR_LABEL]; - throw new CliError( - `${taken.join(' and ')} ${taken.length > 1 ? 'are' : 'is'} already served behind the shared Caddy, by the site ${container.labels[PROJECT_LABEL] ?? container.name}` + - `${where ? `\n in ${where}` : ''}. Two sites cannot share a domain. Nothing has been changed.`, - ); + return { + domains: [...new Set(taken)], + project: container.labels[PROJECT_LABEL] ?? container.name, + dir: container.labels[WORKING_DIR_LABEL], + }; } } + return null; +} + +/** How to say whose a domain is. */ +export const describeHolder = ({ domains, project, dir }: Holder): string => + `${domains.join(' and ')} ${domains.length > 1 ? 'are' : 'is'} already served behind the shared Caddy, by the site ${project}` + + `${dir ? `\n in ${dir}` : ''}`; + +/** Refuses a site whose domains another site holds, before anything is written. */ +export async function refuseTaken( + io: Io, + shared: SharedCaddy, + project: string, + domains: readonly string[], +): Promise { + const holder = await heldByAnother(io, shared.network, project, domains); + if (holder !== null) { + throw new CliError( + `${describeHolder(holder)}. Two sites cannot share a domain. Nothing has been changed.`, + ); + } } diff --git a/manager/src/verify.ts b/manager/src/verify.ts index 73a21ddd..9c223aac 100644 --- a/manager/src/verify.ts +++ b/manager/src/verify.ts @@ -9,7 +9,7 @@ import type { Io } from './io.ts'; import { NetworkUnavailable, type SiteNetwork } from './network.ts'; import { CliError } from './errors.ts'; import { failed, heading, printChecks, type Check } from './report.ts'; -import { findSharedCaddy, INGRESS_NETWORK } from './shared.ts'; +import { describeHolder, findSharedCaddy, heldByAnother, INGRESS_NETWORK } from './shared.ts'; import { hasProfile, caddyServiceOf, @@ -212,7 +212,8 @@ export async function verifyIngress( ]; // Behind the shared Caddy, the site's own Caddy serves it, and the shared // one, in another project, is what the site is asked through. - const shared = site.layout === SHARED_CADDY_PROFILE ? await sharedCaddyOf(io, checks) : null; + const shared = + site.layout === SHARED_CADDY_PROFILE ? await sharedCaddyOf(io, site, checks) : null; const caddy = shared === null ? state('caddy') : shared.state; if (production) { checks.push( @@ -323,6 +324,7 @@ const healthOf = (status: string): string => */ async function sharedCaddyOf( io: Io, + site: SiteFacts, checks: Check[], ): Promise<{ state: ServiceState | undefined } | null> { const shared = await findSharedCaddy(io); @@ -335,6 +337,22 @@ async function sharedCaddyOf( ); return { state: undefined }; } + // Checked again now that this site's Caddy has joined: a site started at + // the same time, or while this one was down, may hold the same names. + const holder = await heldByAnother( + io, + shared.network, + site.settings.get('COMPOSE_PROJECT_NAME') ?? '', + [site.domain, site.adminDomain].filter(Boolean), + ); + if (holder !== null) { + checks.push( + error( + 'ingress', + `${describeHolder(holder)}: requests for a shared domain reach either site. Take one of the two down`, + ), + ); + } const { container } = shared; if (container === null) { checks.push( diff --git a/manager/test/backup.test.ts b/manager/test/backup.test.ts index 540ff6b8..94e4a7a3 100644 --- a/manager/test/backup.test.ts +++ b/manager/test/backup.test.ts @@ -19,6 +19,7 @@ import { tmpdir } from 'node:os'; import { createHash } from 'node:crypto'; import { join } from 'node:path'; import { afterEach, beforeEach, describe, test } from 'node:test'; +import { CADDY, fakeShared, sharedApi, siteCaddy, type FakeShared } from './shared-caddy.ts'; import * as tar from 'tar'; import { backupId, parseCounts } from '../src/backup.ts'; import { readBackupManifest } from '../src/backup/manifest.ts'; @@ -1034,6 +1035,54 @@ describe('restore and the overrides', () => { }); }); +describe('restore of a site behind the shared Caddy', () => { + let shared: FakeShared; + let root: string; + + beforeEach(async () => { + root = await backUp(); + editBackupEnv(root, (text) => + env.set( + env.set(text, 'COMPOSE_PROFILES', 'shared-caddy'), + 'INGRESS_HOST', + 'example.com', + ), + ); + shared = fakeShared(); + const rest = h.daemon.api!; + const caddy = sharedApi(shared, () => h.daemon.containers ?? []); + h.daemon.api = (request) => caddy(request) ?? rest(request); + h.daemon.containers = [CADDY]; + compose.length = 0; + }); + + const refused = async (pattern: RegExp) => { + const result = await h.run('restore', '--yes', root); + assert.equal(result.code, 1); + assert.match(result.stderr, pattern); + assert.match(result.stderr, /Nothing has been changed/); + assert.deepEqual(composed('up'), []); + assert.deepEqual(composed('down'), []); + }; + + test('a server with no shared Caddy is refused before anything changes', async () => { + shared.exists = false; + await refused(/a site behind the shared Caddy, and this server has none/); + }); + + test('so is one whose network is left with no Caddy on it', async () => { + h.daemon.containers = []; + await refused(/the shared Caddy in \/srv\/caddy has no Caddy container/); + }); + + test('so is a domain another site has taken since the backup', async () => { + h.daemon.containers = [CADDY, siteCaddy('ghost-newer', ['example.com'])]; + await refused( + /example\.com is already served behind the shared Caddy, by the site ghost-newer/, + ); + }); +}); + describe('restore into a new directory', () => { let fresh: string; diff --git a/manager/test/shared.test.ts b/manager/test/shared.test.ts index 17c7f1c9..6601e4b1 100644 --- a/manager/test/shared.test.ts +++ b/manager/test/shared.test.ts @@ -5,7 +5,7 @@ // several sites on one server tests/e2e/shared-caddy.sh. import assert from 'node:assert/strict'; import { execFileSync } from 'node:child_process'; -import { existsSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; import { afterEach, beforeEach, describe, test } from 'node:test'; import * as env from '../src/env.ts'; @@ -124,6 +124,37 @@ describe('install --infra', () => { assert.equal(shared.created, null); }); + test('it needs no port for Ghost, however many are taken', async () => { + ps = () => + JSON.stringify({ ID: 'c', Service: 'caddy', State: 'running', Health: 'healthy' }); + h.daemon.containers = [ + { + ...CADDY, + Id: 'g', + Names: ['/ghosts'], + Labels: {}, + Ports: Array.from({ length: 200 }, (_, index) => ({ + PrivatePort: 2368, + PublicPort: 2368 + index, + Type: 'tcp', + })), + }, + ]; + const result = await h.run('install', '--infra'); + assert.equal(result.code, 0, result.stderr); + }); + + test('an ACME account already in the directory is kept, and the install refused', async () => { + const path = join(h.dir, 'caddy', 'global', 'acme.caddy'); + mkdirSync(join(h.dir, 'caddy', 'global'), { recursive: true }); + writeFileSync(path, 'email mine@example.com\n'); + const result = await h.run('install', '--infra', '--email', 'ops@example.com'); + assert.equal(result.code, 1); + assert.match(result.stderr, /already has caddy\/global\/acme\.caddy/); + assert.equal(readFileSync(path, 'utf8'), 'email mine@example.com\n'); + assert.equal(shared.created, null); + }); + test('it takes no site options', async () => { const result = await h.run( 'install', @@ -486,6 +517,24 @@ describe('a production install on a server with the shared Caddy', () => { assert.deepEqual(files(), []); }); + test('a network left with no Caddy on it is refused before anything is written', async () => { + h.daemon.containers = []; + const result = await h.run('install', '--domain', 'example.com', '--no-start'); + assert.equal(result.code, 1); + assert.match(result.stderr, /has no Caddy container: only its network, ghost-ingress/); + assert.deepEqual(files(), []); + }); + + test('a file it would generate is the operator’s if it is there, and is kept', async () => { + const path = join(h.dir, 'caddy', 'global', 'shared-caddy.caddy'); + mkdirSync(join(h.dir, 'caddy', 'global'), { recursive: true }); + writeFileSync(path, '# mine\n'); + const result = await h.run('install', '--domain', 'example.com', '--no-start'); + assert.equal(result.code, 1); + assert.match(result.stderr, /already has caddy\/global\/shared-caddy\.caddy/); + assert.equal(readFileSync(path, 'utf8'), '# mine\n'); + }); + test('--email is the shared Caddy’s to set', async () => { const result = await h.run( 'install', @@ -608,6 +657,27 @@ describe('verification', () => { assert.equal(missing.status, 'error'); assert.match(missing.detail, /this server has none/); }); + + test('a domain another site also answers to is an error, whenever it is found', async () => { + sharedCaddyEnv(); + ps = () => running('ghost', 'caddy-internal'); + h.daemon.https = () => answer; + h.daemon.containers = [CADDY, siteCaddy('ghost-other-com', ['example.com'])]; + const checks = await verifyIngress(h.io(), siteFacts(h.dir, readSettings(h.dir)!)); + const ingress = checks.find((check) => check.label === 'ingress')!; + assert.equal(ingress.status, 'error'); + assert.match( + ingress.detail, + /example\.com is already served behind the shared Caddy, by the site ghost-other-com/, + ); + // The site's own Caddy is not another's. + h.daemon.containers = [CADDY, siteCaddy('ghost-example-com', ['example.com'])]; + const own = await verifyIngress(h.io(), siteFacts(h.dir, readSettings(h.dir)!)); + assert.equal( + own.find((check) => check.label === 'ingress'), + undefined, + ); + }); }); describe('list', () => { From 4109505eebe29e6ad8156d537d7548d459be8ac9 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 6 Dec 2026 18:26:23 +0000 Subject: [PATCH 14/15] Asked Compose and Docker for a site's names on the shared network (S13) ref https://linear.app/ghost/issue/PLA-484 The domain check took a site's names from its settings, which know its domain and admin domain. A name added in compose.override.yml, as the docs describe, was never asked about, so restore and check passed a site holding another's domain. The names now come from where they are decided: restore reads the aliases Compose resolves from the backup's files, and verification reads the ones Docker has on the site's Caddy. docs/caddy.md said the later of two installs started at once is the one removed. The later to join always is; the earlier can be too. --- docs/caddy.md | 9 ++++++--- manager/src/compose.ts | 4 ++++ manager/src/resolved.ts | 5 +++++ manager/src/restore.ts | 32 +++++++++++++++++++++++--------- manager/src/shared.ts | 15 +++++++++++++++ manager/src/verify.ts | 22 +++++++++++++++++++--- manager/test/backup.test.ts | 23 +++++++++++++++++++++++ manager/test/services.test.ts | 2 +- manager/test/shared.test.ts | 24 ++++++++++++++++++++++++ 9 files changed, 120 insertions(+), 16 deletions(-) diff --git a/docs/caddy.md b/docs/caddy.md index 17fa8d55..a4781992 100644 --- a/docs/caddy.md +++ b/docs/caddy.md @@ -216,9 +216,12 @@ another site's Caddy has, running or stopped, before they change anything. A site taken down with `docker compose down` holds no name until it is up again, so another site can be installed on its domain meanwhile. Whenever a site is verified (after an install, a restore or an update, and by `check`), -a domain another site also holds is an error named `ingress`: an install -that finds one removes what it created, which is also what happens to the -later of two installs started at once for one domain. +a domain another site also holds is an error named `ingress`, and an +install that finds one removes what it created. So two installs started at +once for one domain never both succeed: the one whose Caddy joins later +always finds the other, and the earlier may find it too, in which case both +are removed. A name added in `compose.override.yml` is checked like the +site's own. ### Restarting and updating it diff --git a/manager/src/compose.ts b/manager/src/compose.ts index ae1bccb5..f4451bfd 100644 --- a/manager/src/compose.ts +++ b/manager/src/compose.ts @@ -322,6 +322,10 @@ const resolvedService = z.looseObject({ environment: z.record(z.string(), z.union([z.string(), z.null()])).optional(), volumes: z.array(resolvedMount).default([]), labels: z.record(z.string(), z.string()).default({}), + // By network; null for one joined with no settings. + networks: z + .record(z.string(), z.looseObject({ aliases: z.array(z.string()).default([]) }).nullable()) + .default({}), }); const resolvedProject = z.looseObject({ diff --git a/manager/src/resolved.ts b/manager/src/resolved.ts index 625b7a3c..16a95992 100644 --- a/manager/src/resolved.ts +++ b/manager/src/resolved.ts @@ -39,6 +39,8 @@ export interface ResolvedService { readonly image: string | null; readonly mounts: readonly Mount[]; readonly lifecycle: Lifecycle; + /** Every name it is given on its networks, an override's included. */ + readonly aliases: readonly string[]; } export interface ResolvedSite { @@ -89,6 +91,9 @@ export async function resolveConfig( })), lifecycle: definition.labels[LIFECYCLE_LABEL] === 'one-shot' ? 'one-shot' : 'long-running', + aliases: Object.values(definition.networks).flatMap( + (network) => network?.aliases ?? [], + ), }; } const files = inputs?.files ?? siteComposeFiles(dir); diff --git a/manager/src/restore.ts b/manager/src/restore.ts index 062c11dc..79793bc2 100644 --- a/manager/src/restore.ts +++ b/manager/src/restore.ts @@ -34,7 +34,7 @@ import { stopServices, } from './recovery.ts'; import { heading, ok, printChecks, warn } from './report.ts'; -import { insideSite, resolveConfig, resolveSite } from './resolved.ts'; +import { insideSite, resolveConfig, resolveSite, type ResolvedSite } from './resolved.ts'; import { COMPOSE_FILE, COMPOSE_OVERRIDE_FILE, @@ -48,9 +48,11 @@ import { RESTORE_DIR, SHARED_CADDY_PROFILE, siteFacts, + INTERNAL_CADDY, } from './site.ts'; import { findSharedCaddy, + ingressDomains, refuseTaken as refuseTakenDomains, refuseWithoutContainer, } from './shared.ts'; @@ -88,8 +90,8 @@ export async function restoreSite({ io, context, root, yes }: RestoreInput): Pro if (manifest.site.source === 'checkout') { await refuseOtherCommit(io, dir, manifest); } - await refuseOtherConfiguration(io, root, dir, manifest); - await refuseWithoutSharedCaddy(io, root, manifest.site.project); + const resolved = await refuseOtherConfiguration(io, root, dir, manifest); + await refuseWithoutSharedCaddy(io, root, resolved); if (existsSync(join(dir, RESTORE_DIR))) { throw new CliError( `${join(dir, RESTORE_DIR)} is left from a restore that did not finish, and holds the site as\n` + @@ -341,7 +343,11 @@ function restoredEnv(text: string, dir: string, manifest: BackupManifest): strin * there: one installed for them since the backup would share their names * with this one, and be answered with either. */ -async function refuseWithoutSharedCaddy(io: Io, root: string, project: string): Promise { +async function refuseWithoutSharedCaddy( + io: Io, + root: string, + resolved: ResolvedSite, +): Promise { const settings = env.toRecord(readIfExists(join(root, SITE_FILES_DIR, ENV_FILE)) ?? ''); if (!hasProfile(settings.COMPOSE_PROFILES ?? '', SHARED_CADDY_PROFILE)) { return; @@ -355,10 +361,17 @@ async function refuseWithoutSharedCaddy(io: Io, root: string, project: string): ); } refuseWithoutContainer(shared); - const names = [settings.INGRESS_HOST, settings.INGRESS_ADMIN_HOST].filter( - (name): name is string => name !== undefined && name !== '', - ); - await refuseTakenDomains(io, shared, project, names); + // Every name the restored Caddy would hold, as Compose resolves the + // backup's files: an override's are among them. + const names = [ + ...new Set([ + ...[settings.INGRESS_HOST, settings.INGRESS_ADMIN_HOST].filter( + (name): name is string => name !== undefined && name !== '', + ), + ...ingressDomains(resolved.services[INTERNAL_CADDY]?.aliases ?? []), + ]), + ]; + await refuseTakenDomains(io, shared, resolved.project, names); } async function refuseOtherConfiguration( @@ -366,7 +379,7 @@ async function refuseOtherConfiguration( root: string, dir: string, manifest: BackupManifest, -): Promise { +): Promise { const text = readIfExists(join(root, SITE_FILES_DIR, ENV_FILE)); if (text === undefined) { throw new CliError(`the backup holds no ${ENV_FILE}. Nothing has been changed.`); @@ -417,6 +430,7 @@ async function refuseOtherConfiguration( throw new CliError(`in the backup's configuration, ${(error as Error).message}`); } ok(io, 'configuration', "the backup's resolves the images it records"); + return resolved; } /** diff --git a/manager/src/shared.ts b/manager/src/shared.ts index c2f43a8f..c5723b45 100644 --- a/manager/src/shared.ts +++ b/manager/src/shared.ts @@ -88,6 +88,21 @@ export function refuseWithoutContainer(shared: SharedCaddy): void { } } +/** + * The domains among a Caddy's names on the shared network: the site's own, + * and any an override adds (docs/caddy.md). What Compose resolves or Docker + * reports is asked, not the site's settings, which know only the first two. + */ +export const ingressDomains = (names: readonly string[]): string[] => [ + ...new Set( + names + .map((name) => name.toLowerCase()) + .filter((name) => name.endsWith(INGRESS_SUFFIX)) + .map((name) => name.slice(0, -INGRESS_SUFFIX.length)) + .filter((domain) => domain !== ''), + ), +]; + /** Another site's Caddy answering to some of a site's domains on the shared network. */ export interface Holder { readonly domains: readonly string[]; diff --git a/manager/src/verify.ts b/manager/src/verify.ts index 9c223aac..dcad262c 100644 --- a/manager/src/verify.ts +++ b/manager/src/verify.ts @@ -5,11 +5,18 @@ // manager loopback is not host loopback. See docs/architecture.md#verification-and-service-access. import { ServiceUnreachable, type HttpsAnswer } from './clients.ts'; import { composePs, type ServiceState } from './compose.ts'; +import { inspectContainer } from './docker/client.ts'; import type { Io } from './io.ts'; import { NetworkUnavailable, type SiteNetwork } from './network.ts'; import { CliError } from './errors.ts'; import { failed, heading, printChecks, type Check } from './report.ts'; -import { describeHolder, findSharedCaddy, heldByAnother, INGRESS_NETWORK } from './shared.ts'; +import { + describeHolder, + findSharedCaddy, + heldByAnother, + ingressDomains, + INGRESS_NETWORK, +} from './shared.ts'; import { hasProfile, caddyServiceOf, @@ -18,6 +25,7 @@ import { readSettings, siteFacts, type SiteFacts, + INTERNAL_CADDY, } from './site.ts'; const describeState = (state: ServiceState | undefined): string => @@ -213,7 +221,9 @@ export async function verifyIngress( // Behind the shared Caddy, the site's own Caddy serves it, and the shared // one, in another project, is what the site is asked through. const shared = - site.layout === SHARED_CADDY_PROFILE ? await sharedCaddyOf(io, site, checks) : null; + site.layout === SHARED_CADDY_PROFILE + ? await sharedCaddyOf(io, site, state(INTERNAL_CADDY), checks) + : null; const caddy = shared === null ? state('caddy') : shared.state; if (production) { checks.push( @@ -325,6 +335,7 @@ const healthOf = (status: string): string => async function sharedCaddyOf( io: Io, site: SiteFacts, + caddy: ServiceState | undefined, checks: Check[], ): Promise<{ state: ServiceState | undefined } | null> { const shared = await findSharedCaddy(io); @@ -339,11 +350,16 @@ async function sharedCaddyOf( } // Checked again now that this site's Caddy has joined: a site started at // the same time, or while this one was down, may hold the same names. + // Its Caddy's names as Docker has them, which an override may add to. + const own = caddy === undefined ? null : await inspectContainer(io.docker, caddy.ID); + const held = own?.endpoints.find((endpoint) => endpoint.network === shared.network)?.names; const holder = await heldByAnother( io, shared.network, site.settings.get('COMPOSE_PROJECT_NAME') ?? '', - [site.domain, site.adminDomain].filter(Boolean), + [...new Set([site.domain, site.adminDomain, ...ingressDomains(held ?? [])])].filter( + Boolean, + ), ); if (holder !== null) { checks.push( diff --git a/manager/test/backup.test.ts b/manager/test/backup.test.ts index 94e4a7a3..8aa2d2db 100644 --- a/manager/test/backup.test.ts +++ b/manager/test/backup.test.ts @@ -1075,6 +1075,29 @@ describe('restore of a site behind the shared Caddy', () => { await refused(/the shared Caddy in \/srv\/caddy has no Caddy container/); }); + test('so is a name its override adds, as Compose resolves the backup', async () => { + const run = h.daemon.composeRun!; + h.daemon.composeRun = (args, ...rest) => { + const result = run(args, ...rest); + if (args[0] !== 'config') { + return result; + } + const project = JSON.parse(result!.stdout); + project.services['caddy-internal'] = { + networks: { + ingress: { + aliases: ['example.com.ghost.internal', 'www.example.com.ghost.internal'], + }, + }, + }; + return ok(JSON.stringify(project)); + }; + h.daemon.containers = [CADDY, siteCaddy('ghost-newer', ['www.example.com'])]; + await refused( + /www\.example\.com is already served behind the shared Caddy, by the site ghost-newer/, + ); + }); + test('so is a domain another site has taken since the backup', async () => { h.daemon.containers = [CADDY, siteCaddy('ghost-newer', ['example.com'])]; await refused( diff --git a/manager/test/services.test.ts b/manager/test/services.test.ts index d6446960..e661d3c7 100644 --- a/manager/test/services.test.ts +++ b/manager/test/services.test.ts @@ -14,7 +14,7 @@ const configured = (services: Record): ResolvedSite => ({ services: Object.fromEntries( Object.entries(services).map(([name, lifecycle]) => [ name, - { image: `${name}:1`, mounts: [], lifecycle }, + { image: `${name}:1`, mounts: [], lifecycle, aliases: [] }, ]), ), }); diff --git a/manager/test/shared.test.ts b/manager/test/shared.test.ts index 6601e4b1..f262aea8 100644 --- a/manager/test/shared.test.ts +++ b/manager/test/shared.test.ts @@ -678,6 +678,30 @@ describe('verification', () => { undefined, ); }); + test('a name its override adds is asked about too, as Docker has it', async () => { + sharedCaddyEnv(); + ps = () => + ['ghost', 'caddy-internal'] + .map((Service) => + JSON.stringify({ + ID: Service === 'ghost' ? 'ghost' : 'caddy-of-ghost-example-com', + Service, + State: 'running', + Health: 'healthy', + }), + ) + .join('\n'); + h.daemon.https = () => answer; + h.daemon.containers = [ + CADDY, + siteCaddy('ghost-example-com', ['example.com', 'www.example.com']), + siteCaddy('ghost-other-com', ['www.example.com']), + ]; + const checks = await verifyIngress(h.io(), siteFacts(h.dir, readSettings(h.dir)!)); + const ingress = checks.find((check) => check.label === 'ingress')!; + assert.equal(ingress?.status, 'error'); + assert.match(ingress.detail, /www\.example\.com is already served/); + }); }); describe('list', () => { From 52ae3ced72c3fd3fc9276c45230d5c05e8f7016c Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 6 Dec 2026 18:27:59 +0000 Subject: [PATCH 15/15] Corrected what is said of two installs started at once for one domain (S13) ref https://linear.app/ghost/issue/PLA-484 The docs and a comment said the install whose Caddy joins later always finds the other. It need not: the earlier can find the later, be removed, and leave the later to pass. What holds is that the two are never both verified, and that --no-start verifies nothing. --- docs/architecture.md | 5 +++-- docs/caddy.md | 10 ++++++---- manager/src/shared.ts | 5 +++-- 3 files changed, 12 insertions(+), 8 deletions(-) diff --git a/docs/architecture.md b/docs/architecture.md index e580a015..a0891404 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -141,8 +141,9 @@ written in the shared Caddy's directory for a site. Before any write, an install or a restore refuses a domain another site's Caddy has on the network, and a shared Caddy that is missing or has no container. Nothing locks across sites, so verification asks again once the site's Caddy has -joined (`heldByAnother` in `src/shared.ts`): of two sites started at once, -the one that joins later finds the other there. +joined (`heldByAnother` in `src/shared.ts`): two sites started at once +are never both verified, since one that passed is still on the network when +the other is asked. Either may be the one that fails, or both. `src/bundle/manifest.ts` defines the migration bundle schema and depends only on zod so the exporter can share it. Import policy stays outside that schema. diff --git a/docs/caddy.md b/docs/caddy.md index a4781992..331bdda8 100644 --- a/docs/caddy.md +++ b/docs/caddy.md @@ -218,10 +218,12 @@ again, so another site can be installed on its domain meanwhile. Whenever a site is verified (after an install, a restore or an update, and by `check`), a domain another site also holds is an error named `ingress`, and an install that finds one removes what it created. So two installs started at -once for one domain never both succeed: the one whose Caddy joins later -always finds the other, and the earlier may find it too, in which case both -are removed. A name added in `compose.override.yml` is checked like the -site's own. +once for one domain are never both left serving it: an install that +succeeded is still on the network when the other is verified. Which of the +two is removed is not decided by which started first, and both can be. An +install with `--no-start` starts and verifies nothing, so this holds for it +only from its first `check`. A name added in `compose.override.yml` is +checked like the site's own. ### Restarting and updating it diff --git a/manager/src/shared.ts b/manager/src/shared.ts index c5723b45..f398bc73 100644 --- a/manager/src/shared.ts +++ b/manager/src/shared.ts @@ -118,8 +118,9 @@ export interface Holder { * down with `docker compose down` holds no name until it is up. * * Asked before a site is written (refuseTaken) and again once its Caddy has - * joined (verify.ts): of two sites started at once, the one that joins later - * always finds the other there. + * joined (verify.ts). Two sites started at once cannot both pass that: one + * that passed is still on the network when the other asks. Either may be the + * one that fails, or both; nothing locks across sites. */ export async function heldByAnother( io: Io,