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 275f0ca5..e0655d3a 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 (`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"`. # 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 e7ecb534..56438535 100644 --- a/compose.yml +++ b/compose.yml @@ -15,6 +15,8 @@ # 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). @@ -35,7 +37,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 @@ -114,7 +116,7 @@ services: 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 @@ -186,7 +188,7 @@ services: networks: - ghost_network - caddy: + caddy: &caddy image: caddy:2.10.2-alpine@sha256:953131cfea8e12bfe1c631a36308e9660e4389f0c3dfb3be957044d3ac92d446 restart: ${RESTART_POLICY:-unless-stopped} profiles: [production] @@ -217,6 +219,22 @@ services: networks: - 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 restart: ${RESTART_POLICY:-unless-stopped} @@ -243,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: @@ -316,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: @@ -413,3 +431,10 @@ volumes: networks: ghost_network: + # The shared Caddy's network, which `install --infra` creates and no Compose + # project owns. Only a site behind the shared Caddy uses it. + 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/docs/architecture.md b/docs/architecture.md index 71e2ac75..a0891404 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,26 @@ 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`, 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 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`): 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. `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..331bdda8 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. 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 @@ -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,180 @@ 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, 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 --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. 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 + +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. 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 +routes, reload that site's Caddy, in the site's directory: + +```bash +docker compose exec caddy-internal caddy reload --config /etc/caddy/Caddyfile +``` + +`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`. + +`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. + +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' 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. + +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`, and an +install that finds one removes what it created. So two installs started at +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 + +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; 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 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. + +### 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 +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; +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 a50631b5..2c38d110 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -107,16 +107,23 @@ 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`, `caddy-internal` | [The shared Caddy](caddy.md#the-shared-caddy), through the site's own Caddy, which publishes no port | `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. 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: @@ -269,7 +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. `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/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 298995c6..ea5671aa 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] [--email you@example.com] [--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 @@ -304,6 +307,35 @@ 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`. 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 **Installation never stops or reconfigures anything already running.** @@ -311,9 +343,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 @@ -361,7 +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). +[caddy.md](caddy.md). Behind the shared Caddy, the site's Caddy is the +service `caddy-internal`, and is what you reload. ## update @@ -409,7 +443,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..51ff231f 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,16 @@ 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`: 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 @@ -56,6 +66,25 @@ 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: +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)). + ## How a site is verified Each service is judged by its own health check, which `up --wait` already @@ -71,6 +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 | 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` | @@ -98,8 +128,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. @@ -374,7 +404,8 @@ 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 +Caddy's certificates, which Caddy obtains again when the site starts (behind +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 @@ -446,7 +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. 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 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 844840a5..e0648c00 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. */ @@ -179,6 +186,9 @@ function notIncluded(site: SiteFacts): string[] { "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', 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/commands/common.ts b/manager/src/commands/common.ts index c96378cf..42b19a77 100644 --- a/manager/src/commands/common.ts +++ b/manager/src/commands/common.ts @@ -8,10 +8,11 @@ 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, + 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) { @@ -90,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/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 cce22ed8..3279e9f6 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'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 @@ -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, 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'; import { defineCommand, flag, refused } from '../command.ts'; import { findingErrors, validate } from '../config.ts'; @@ -28,12 +31,13 @@ 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, managerPin, payloadConflicts, + infraStackDir, payloadFiles, stackDir, writeLauncher, @@ -45,13 +49,27 @@ import { ENV_FILE, generatedSettings, GHOST_ENV_FILE, + INFRA_PROFILE, + INTERNAL_CADDY, MAILPIT_DATA_DIR, + SHARED_CADDY_PROFILE, META_FILE, profileConflict, NO_CADDY_PROFILE, type Layout, type SiteMode, } from '../site.ts'; +import { + describeShared, + findSharedCaddy, + INFRA_DIR_LABEL, + INFRA_PROJECT, + INFRA_PROJECT_LABEL, + INGRESS_NETWORK, + refuseTaken, + refuseWithoutContainer, + 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 +224,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 +253,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 +262,29 @@ 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], + ['--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 +417,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 +436,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, true), flags, release); + } await clearUnfinishedImport(io, context, dir, flags.import !== undefined); const target = refuseOccupied(io, context, dir); @@ -414,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( @@ -425,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); @@ -464,9 +523,23 @@ 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) { + 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` + + ` ${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; const { port, mailpitPort } = await sitePorts( io, - intent.layout, + layout, flags.port, intent.services.includes('mailpit'), ); @@ -488,11 +561,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 +576,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,15 +620,41 @@ async function sitePorts( : null; const wanted = [ port, + // 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.', ); } @@ -562,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. */ @@ -628,7 +721,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' || 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(); @@ -731,24 +824,33 @@ 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. 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. + */ +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 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'), + shared, }); ok( io, SITE_FILE, - `routes for ${[domain, adminDomain].filter(Boolean).join(' and ')}; yours to edit`, + `routes for ${[domain, adminDomain].filter(Boolean).join(' and ')}${shared ? ', served to the shared Caddy over HTTP' : ''}; yours to edit`, ); } @@ -777,14 +879,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.') + @@ -795,6 +897,159 @@ 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, stack, files } = 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.`, + ); + } + 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.', + ); + } + await preflight(io, context); + 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); + + const created = new Created(io, context, dir); + try { + heading(io, 'Writing the shared Caddy'); + 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}`); + 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`); + } + 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), + }), + '# 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, + ); + ok(io, ENV_FILE, 'the shared Caddy\u2019s settings'); + // No project owns it, so taking the shared Caddy down leaves its members attached. + 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 Caddy of each site behind it joins`); + created.file(join(dir, META_FILE)); + writeMetadata( + dir, + infraMetadata({ + channel: release.channel, + source: '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: its own Caddy joins this one, which', + 'obtains its certificate when the domain is first asked for.', + ]), + '', + ].join('\n'), + ); + return EXIT.ok; +} + // --- The outcome ---------------------------------------------------------------- /** @@ -891,6 +1146,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 + ? [] + : [ + ` Ingress ${describeShared(site.shared)}, through this site's ${INTERNAL_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/self-update.ts b/manager/src/commands/self-update.ts index a7717a4d..7a7cbaf3 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 { refuseForeignProject } from '../project.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 { @@ -33,16 +36,26 @@ import { LAUNCHER, launcherContent, managerPin, + infraStackDir, payloadFiles, 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 +73,7 @@ import { releaseOption, requestedRelease, type ManagerRelease, + type Requested, } from './common.ts'; /** How long pulling a release's images may take. */ @@ -125,7 +139,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 +196,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 +309,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 +325,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 +372,212 @@ 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; none + * of them writes anything here. + */ +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 = infraStackDir(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'); + // A project another directory owns would be recreated as this one's. + await refuseForeignProject(io, site.settings.get('COMPOSE_PROJECT_NAME') || '', dir); + + 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`, + ); + // 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', + () => + 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'); + 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; + try { + heading(io, 'Writing the stack'); + writePayloadChanges(io, dir, stack, payload); + await requireValid(io, dir, 'this release'); + 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`, + ); + 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.' : ''), + ); + } + // Nothing loads the written files before Caddy is restarted on them. + 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` + + ' 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.`, + ); + } + } + snapshot.remove(); + throw new CliError( + `the update failed; the shared Caddy is back on ${describeStack(from)}${started ? ', and running' : ', which it never stopped running'}.`, + ); + } + 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; +} + +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); + // `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', + () => compose(io, { dir })`exec -T caddy ${RELOAD.split(' ')}`, + ); + if (reload.exitCode !== 0) { + throw new CliError( + `Caddy did not load its configuration, and keeps serving the one it had: ${composeError(reload)}`, + ); + } +} + /** --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 +596,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 +617,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 +691,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..6ac8feb8 100644 --- a/manager/src/commands/site.ts +++ b/manager/src/commands/site.ts @@ -14,7 +14,15 @@ 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 { SERVICE_LABEL } from '../shared.ts'; +import { + hasProfile, + INFRA_PROFILE, + INTERNAL_CADDY, + 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 +318,19 @@ 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 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 behind = + modes.get(project) === SHARED_CADDY_PROFILE || + container.labels[SERVICE_LABEL] === INTERNAL_CADDY; + modes.set( + project, + behind ? SHARED_CADDY_PROFILE : (container.labels['org.ghost.docker.mode'] ?? ''), + ); + } const sites = projects .filter((project) => modes.has(project.name)) .sort((a, b) => a.name.localeCompare(b.name)); @@ -323,11 +338,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 holds\n` + + 'ports 80 and 443 and passes each request to the site\u2019s own Caddy.\n', + ); + } } io.stdout( '\nOnly sites whose containers exist are listed, stopped ones included. There is no\n' + 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/config.ts b/manager/src/config.ts index 81e2bfa4..ebc2ff97 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'], + /** 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. */ @@ -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(...ingressNames(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,61 @@ export async function validateEnv(io: Io, dir: string): Promise { return findings; } +/** + * The shared Caddy's directory: Caddy alone, so `infra` and nothing else. + */ +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) { + 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; +} + +/** + * 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 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 * both are detected rather than listed: diff --git a/manager/src/docker/client.ts b/manager/src/docker/client.ts index 0d5c1076..9b40f061 100644 --- a/manager/src/docker/client.ts +++ b/manager/src/docker/client.ts @@ -446,6 +446,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 { 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..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,12 +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/. + * 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': [], + infra: [], }; /** @@ -45,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/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 a61e9458..79793bc2 100644 --- a/manager/src/restore.ts +++ b/manager/src/restore.ts @@ -34,18 +34,28 @@ 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, DATA_DIRS, ENV_FILE, + hasProfile, + INFRA_PROFILE, MAILPIT_DATA_DIR, META_FILE, readSettings, RESTORE_DIR, + SHARED_CADDY_PROFILE, siteFacts, + INTERNAL_CADDY, } from './site.ts'; +import { + findSharedCaddy, + ingressDomains, + refuseTaken as refuseTakenDomains, + refuseWithoutContainer, +} from './shared.ts'; import { verifySite } from './verify.ts'; /** `over`: the backup's own site, replaced. `fresh`: a new, empty directory. */ @@ -80,7 +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); + 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` + @@ -325,12 +336,50 @@ 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, 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, + resolved: ResolvedSite, +): 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\n' + + ' (docs/caddy.md#the-shared-caddy). Nothing has been changed.', + ); + } + refuseWithoutContainer(shared); + // 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( io: Io, 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.`); @@ -381,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; } /** @@ -619,7 +669,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..f398bc73 --- /dev/null +++ b/manager/src/shared.ts @@ -0,0 +1,178 @@ +// 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 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. +// +// 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 { + inspectContainer, + inspectNetwork, + listContainers, + type ContainerFacts, +} 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'; +/** 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'; + +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}` : ''}`; + +/** + * 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 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.`, + ); + } +} + +/** + * 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[]; + 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). 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, + network: string, + project: string, + domains: readonly string[], +): Promise { + const wanted = new Map( + domains + .map((domain) => domain.toLowerCase()) + .map((domain) => [`${domain}${INGRESS_SUFFIX}`, domain]), + ); + 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 === network)?.names ?? []; + const taken = names + .map((alias) => wanted.get(alias.toLowerCase())) + .filter((domain) => domain !== undefined); + if (taken.length > 0) { + 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/site.ts b/manager/src/site.ts index fb3a6be5..4559cbd9 100644 --- a/manager/src/site.ts +++ b/manager/src/site.ts @@ -56,26 +56,50 @@ 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): 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'; /** 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 +107,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,7 +204,7 @@ 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 }; readonly database: { readonly user: string; @@ -204,6 +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 } : {}), + ...(layoutOf(input.profiles.join(',')) === SHARED_CADDY_PROFILE + ? ingressHosts(input.url, input.adminUrl) + : {}), DATABASE_HOST: 'db', DATABASE_PORT: '3306', DATABASE_NAME: 'ghost', @@ -213,6 +244,15 @@ export function generatedSettings(input: { }); } +/** + * 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. */ export const hostOf = (url: string): string => { try { @@ -226,7 +266,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..d4c465fa 100644 --- a/manager/src/undo.ts +++ b/manager/src/undo.ts @@ -13,6 +13,7 @@ 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 { removeNetwork } from './docker/client.ts'; import { DATA_DIRS, ENV_FILE, GHOST_ENV_FILE, META_FILE } from './site.ts'; const journalSchema = z.object({ @@ -30,6 +31,8 @@ export class Created implements Written { readonly data: string[] = []; /** Compose has created something for this project: a network, containers, volumes. */ project = 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; @@ -103,6 +106,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())); } 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 d28faa0b..dcad262c 100644 --- a/manager/src/verify.ts +++ b/manager/src/verify.ts @@ -5,11 +5,28 @@ // 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 { hasProfile, NO_CADDY_PROFILE, readSettings, siteFacts, type SiteFacts } from './site.ts'; +import { + describeHolder, + findSharedCaddy, + heldByAnother, + ingressDomains, + INGRESS_NETWORK, +} from './shared.ts'; +import { + hasProfile, + caddyServiceOf, + NO_CADDY_PROFILE, + SHARED_CADDY_PROFILE, + readSettings, + siteFacts, + type SiteFacts, + INTERNAL_CADDY, +} from './site.ts'; const describeState = (state: ServiceState | undefined): string => state ? [state.State, state.Health].filter(Boolean).join(', ') : 'no container'; @@ -192,7 +209,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 +218,30 @@ export async function verifyIngress( const checks: Check[] = [ healthy('ghost', state('ghost'), 'its Admin API answers inside the container'), ]; + // 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, state(INTERNAL_CADDY), checks) + : null; + const caddy = shared === null ? state('caddy') : shared.state; if (production) { checks.push( healthy( 'caddy', - state('caddy'), + state(caddyServiceOf(site.layout) ?? 'caddy'), 'its admin API answers, with its configuration loaded', ), ); + 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 = site.adminDomain !== '' && site.adminDomain !== site.domain ? site.adminDomain : null; @@ -230,15 +264,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 +309,93 @@ 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. + * A server with no shared Caddy is reported in `checks`. + */ +async function sharedCaddyOf( + io: Io, + site: SiteFacts, + caddy: ServiceState | undefined, + checks: Check[], +): Promise<{ state: ServiceState | undefined } | 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 }; + } + // 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') ?? '', + [...new Set([site.domain, site.adminDomain, ...ingressDomains(held ?? [])])].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( + error( + 'shared caddy', + `it has no container: start it in ${shared.dir || 'its directory'}`, + ), + ); + return { state: undefined }; + } + return { + 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', + })), + }, + }; +} + /** 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/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 540ff6b8..8aa2d2db 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,77 @@ 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 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( + /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/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..d573bf23 --- /dev/null +++ b/manager/test/integration/shared.test.ts @@ -0,0 +1,172 @@ +// 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 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 { readFileSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { after, before, test } from 'node:test'; +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 { refuseTaken, 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]!; + +let infra: TestSite; +let delta: TestSite; +let shared: SharedCaddy; + +/** + * 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", "--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 + start_period: 0s + ports: !reset [] +`; + +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', + 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. + 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_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, + }), + }); + 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`], + }); + 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); +}); + +/** `name` asked of the shared Caddy over TLS, from its network. */ +const ask = (name: string, attempts = 30): Promise => + io.siteNetwork( + [ + { + ID: shared.container!.id, + Service: 'caddy', + State: 'running', + Health: 'healthy', + ExitCode: 0, + Publishers: [], + }, + ], + ['caddy'], + async (network) => { + assert.equal(network.name, INGRESS); + // 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: name, + path: '/ghost/api/admin/site/', + }); + } catch (error) { + if (attempt >= attempts) { + throw error; + } + await new Promise((resolve) => setTimeout(resolve, 1000)); + } + } + }, + ); + +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 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 && + /delta\.test is already served behind the shared Caddy/.test(error.message), + ); + await refuseTaken(io, shared, named('echo'), ['echo.test']); + await refuseTaken(io, shared, delta.project, ['delta.test']); +}); + +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 a312256c..893275e7 100644 --- a/manager/test/integration/site.ts +++ b/manager/test/integration/site.ts @@ -68,15 +68,23 @@ export interface SiteOptions { readonly override?: string; /** caddy/sites/site.caddy. */ 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( @@ -88,6 +96,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/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-caddy.ts b/manager/test/shared-caddy.ts new file mode 100644 index 00000000..e902f10f --- /dev/null +++ b/manager/test/shared-caddy.ts @@ -0,0 +1,113 @@ +// A shared Caddy as the daemon shows it, for tests of the sites behind it: +// 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 { json } from './helpers.ts'; + +export const INFRA_DIR = '/srv/caddy'; + +/** The shared Caddy's network as the daemon would show it. */ +export interface FakeShared { + exists: boolean; + /** The labels the network was created with, when the manager created it. */ + created: Record | null; + /** Another installation creates the network first. */ + raced: boolean; +} + +export const fakeShared = (): FakeShared => ({ exists: true, created: null, raced: 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' }, + ], +}; + +/** 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, { + 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) { + 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) }; + } + return undefined; + }; +} diff --git a/manager/test/shared.test.ts b/manager/test/shared.test.ts new file mode 100644 index 00000000..f262aea8 --- /dev/null +++ b/manager/test/shared.test.ts @@ -0,0 +1,855 @@ +// 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` 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'; +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'; +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, siteCaddy, type FakeShared } from './shared-caddy.ts'; +import { imageApi, imageStack, rootContainer } from './site.ts'; + +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.containers ?? []); + 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, + http: settings().HTTP_PORT, + url: settings().URL, + }, + { + profiles: 'infra', + mode: 'infra', + project: 'ghost-infra', + http: '80', + url: undefined, + }, + ); + // Caddy's files, and nothing of a site's: no Ghost or MySQL. + assert.deepEqual(files(), [ + '.env', + '.ghost-docker.json', + 'caddy', + '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')), 'it holds no site\u2019s routes'); + 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 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', + '--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('--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); + 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(), []); + }); + + test('a network another installation created meanwhile is not removed', async () => { + shared.raced = 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', () => { + 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) => + 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 = []; + h.env.GD_VERSION_FILE = `${h.env.GD_STACK_DIR!}-version.json`; + manager = FIRST; + const images = imageApi({ manager: () => manager }); + const caddy = sharedApi(shared, () => h.daemon.containers ?? []); + 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(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, FILE), '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]), + ['pull', 'config', 'up', 'exec', 'ps'], + ); + assert.deepEqual( + compose.find((args) => args[0] === 'exec'), + ['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'))); + 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, 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\/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, FILE), '# mine\n'); + const result = await h.run('self-update'); + assert.equal(result.code, 0, result.stderr); + 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, 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, FILE), '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 configuration Caddy will not reload is put back, and the old one loaded again', async () => { + const before = readFileSync(join(h.dir, FILE), '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, 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, FILE), '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, FILE), 'utf8'), before); + assert.deepEqual( + compose.map((args) => args[0]), + ['pull'], + ); + assert.equal(metadata().stack.version, 'v0.1.0-beta.1'); + }); + + 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); + 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, which it never stopped running/); + assert.equal(readFileSync(join(h.dir, FILE), 'utf8'), before); + assert.deepEqual( + compose.map((args) => args[0]), + ['pull', 'config'], + ); + assert.ok(!existsSync(join(h.dir, '.ghost-docker-update'))); + }); + + 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]*may be unreachable/); + 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.containers ?? []); + 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); + 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: 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', + ); + assert.equal(result.code, 0, result.stderr); + const values = settings(); + assert.equal(values.COMPOSE_PROFILES, 'shared-caddy,activitypub'); + assert.equal(values.SITE_MODE, 'production'); + // 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); + 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/); + 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/, + ); + const metadata = JSON.parse(readFileSync(join(h.dir, '.ghost-docker.json'), 'utf8')); + assert.equal(metadata.mode, 'production'); + 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('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 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', + '--no-start', + ); + assert.equal(result.code, 1); + assert.match( + result.stderr, + /www\.example\.com is already served behind the shared Caddy, by the site ghost-other-com\n {2}in \/srv\/ghost-other-com/, + ); + assert.deepEqual(files(), []); + }); + + 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, /example\.com is already served behind 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', + '--domain', + 'example.com', + '--email', + 'me@example.com', + '--no-start', + ); + assert.equal(result.code, 2); + assert.match( + result.stderr, + /--email is the ACME account[\s\S]*the shared Caddy in \/srv\/caddy/, + ); + 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_HOST, undefined); + }); + + 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_HOST, undefined); + }); +}); + +describe('a server without one', () => { + 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_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'))); + }); +}); + +/** 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_HOST', 'example.com'], + ]), + { mode: 0o600 }, + ); + +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, + }, + }; + 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(); + ps = () => running('ghost', 'caddy-internal'); + 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.caddy?.status, 'ok', by.caddy?.detail ?? ''); + assert.equal(by['shared caddy']?.status, 'ok'); + 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('its own Caddy stopped, or a shared Caddy that is gone, are errors', async () => { + sharedCaddyEnv(); + ps = () => running('ghost'); + h.daemon.https = () => answer; + let checks = await verifyIngress(h.io(), siteFacts(h.dir, readSettings(h.dir)!)); + 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')!; + 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, + ); + }); + 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', () => { + 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: [], + }, + siteCaddy('ghost-example-com', ['example.com']), + { + 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: [], + }, + ]; + 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", async () => { + writeFileSync( + join(h.dir, '.env'), + env.serializeAll([ + ['COMPOSE_PROFILES', 'infra'], + ['SITE_MODE', 'infra'], + ['COMPOSE_PROJECT_NAME', 'ghost-infra'], + ['PROJECT_DIR', h.dir], + ]), + { 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'], + ]), + { 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, + /PROJECT_DIR is required for the shared Caddy/, + ); + }); + + 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(); + 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/, + ); + // 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( + admin.stdout + admin.stderr, + /INGRESS_ADMIN_HOST must be admin\.example\.com, the host of ADMIN_URL/, + ); + write({ + ...values, + ADMIN_URL: 'https://admin.example.com', + INGRESS_ADMIN_HOST: 'admin.example.com', + }); + const both = await h.run('config', 'validate'); + assert.equal(both.code, 0, both.stdout + both.stderr); + }); +}); + +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])), + ]; + // 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/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 diff --git a/tests/e2e/shared-caddy.sh b/tests/e2e/shared-caddy.sh new file mode 100755 index 00000000..3c8c6f4b --- /dev/null +++ b/tests/e2e/shared-caddy.sh @@ -0,0 +1,273 @@ +#!/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, 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 +# 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 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 + 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}}' +} + +# 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() { + [[ $(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 && ! -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' ]] || + 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" +[[ $(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 '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" + # 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 +[[ -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 'ok +caddy +healthy' +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 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 "$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") +shared_before=$(shared_caddy) + +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" +unchanged "$shared_before" +[[ $(through "$DOMAIN_B") == "https://$DOMAIN_B/" ]] || fail "bravo no longer answers" +ok "alpha updated; bravo's containers and the shared Caddy as they were" + +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) +# 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" +unchanged "$shared_before" +ok "restored $(basename "$backup"); bravo's containers and the shared Caddy as they were" + +step "Taking bravo down, and restoring it, leaves alpha and the shared Caddy untouched" +before_a=$(containers "$A") +run gd "$B" backup +expect_status 0 +backup_b=$(find "$B/backups" -mindepth 1 -maxdepth 1 | sort | tail -1) +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" +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' +run gd "$B" restore --yes "$backup_b" +expect_status 0 +serves "$DOMAIN_B" +serves "$DOMAIN_A" +untouched "$A" "$before_a" +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.'