diff --git a/.env.example b/.env.example index 275f0ca5..97070831 100644 --- a/.env.example +++ b/.env.example @@ -12,7 +12,8 @@ # interpolated by accident. # --- Site mode ------------------------------------------------------------- -# Exactly one site mode must be selected: `local` or `production`. +# Exactly one site mode must be selected: `local` or `production`, or `shared-caddy` +# for a production site behind the shared Caddy (docs/caddy.md#the-shared-caddy). # Optional per-site profiles are added to the same list: `analytics`, # `activitypub`, `supervisor`, and for a local site `mailpit`. Profiles are additive; adding # an optional profile never changes the site mode. @@ -73,6 +74,12 @@ GHOST_PORT="2368" HTTP_PORT="80" HTTPS_PORT="443" +# Behind the shared Caddy, and in its own directory: its network, which the +# manager created and no Compose project owns. Unset, a site with its own +# Caddy gets a network of its own. +# INGRESS_NETWORK="ghost-ingress" +# INGRESS_EXTERNAL="true" + # --- Lifecycle ------------------------------------------------------------ # Applied to long-running services only. One-shot jobs keep `restart: "no"`. # production: unless-stopped diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 954ceaeb..cc968c0b 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -123,6 +123,7 @@ jobs: - { name: Ghost nightly channel, script: ghost-nightly } - { name: Migration from the released main layout, script: migrate-main } - { name: Backup and restore, script: backup } + - { name: Shared Caddy, script: shared-caddy } - { name: Import, script: import, node: "22" } steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 diff --git a/README.md b/README.md index 0a6333be..e3f4465c 100644 --- a/README.md +++ b/README.md @@ -61,7 +61,8 @@ Linux. There is no native Windows launcher. ## Site modes `install --local` selects Ghost and MySQL on loopback. A production install -adds Caddy with automatic HTTPS. [Configuration](docs/configuration.md#site-modes-and-profiles) +adds Caddy with automatic HTTPS; several production sites on one server share +one Caddy, set up with `install --infra` ([caddy.md](docs/caddy.md#the-shared-caddy)). [Configuration](docs/configuration.md#site-modes-and-profiles) defines the modes and optional profiles; [installation](docs/install.md#optional-services) explains how to enable them. diff --git a/compose.yml b/compose.yml index 3938f188..c77048bc 100644 --- a/compose.yml +++ b/compose.yml @@ -11,10 +11,18 @@ # credentials (MySQL root) that Ghost must not receive. # # Site modes are selected through COMPOSE_PROFILES and are additive: -# local ghost + db, Ghost published on 127.0.0.1:${GHOST_PORT} -# production ghost + db + caddy (HTTPS ingress) -# no-caddy ghost + db, a production site behind the operator's own proxy -# (nginx, Apache) on 127.0.0.1:${GHOST_PORT} +# local ghost + db, Ghost published on 127.0.0.1:${GHOST_PORT} +# production ghost + db + caddy (HTTPS ingress) +# no-caddy ghost + db, a production site behind the operator's own proxy +# (nginx, Apache) on 127.0.0.1:${GHOST_PORT} +# shared-caddy ghost + db, a production site behind the shared Caddy +# and `infra` is the shared Caddy's own directory: caddy alone, for the +# sites' routes (docs/caddy.md#the-shared-caddy). +# +# Variables a site needs and the shared Caddy does not are not `:?`-guarded, +# because Compose interpolates services its profiles leave out too: +# `./ghost-docker config validate` requires them for a site. +# # Optional, per-site profiles: analytics, activitypub, and for local sites # mailpit, and `supervisor`, which runs Ghost updates asked for in Ghost Admin # (docs/upgrade-supervisor.md). @@ -35,7 +43,7 @@ services: # Do not alter this without updating the Tinybird Sync container as well image: ${GHOST_IMAGE_REF:-${GHOST_IMAGE:-ghost}:${GHOST_VERSION:-6-next-alpine}} restart: ${RESTART_POLICY:-unless-stopped} - profiles: [local, production, no-caddy] + profiles: [local, production, no-caddy, shared-caddy] labels: <<: *site-labels org.ghost.docker.lifecycle: long-running @@ -51,7 +59,7 @@ services: # Container-owned keys. These override anything set in ghost.env. environment: NODE_ENV: ${NODE_ENV:-production} - url: ${URL:?URL is required (for example https://example.com or http://localhost:2368)} + url: ${URL:-} admin__url: ${ADMIN_URL:-} server__host: 0.0.0.0 server__port: "2368" @@ -60,9 +68,9 @@ services: database__connection__host: ${DATABASE_HOST:-db} database__connection__port: ${DATABASE_PORT:-3306} database__connection__user: ${DATABASE_USER:-ghost} - database__connection__password: ${DATABASE_PASSWORD:?DATABASE_PASSWORD is required} + database__connection__password: ${DATABASE_PASSWORD:-} database__connection__database: ${DATABASE_NAME:-ghost} - tinybird__tracker__endpoint: ${URL}/.ghost/analytics/api/v1/page_hit + tinybird__tracker__endpoint: ${URL:-}/.ghost/analytics/api/v1/page_hit tinybird__tracker__datasource: analytics_events tinybird__adminToken: ${TINYBIRD_ADMIN_TOKEN:-} tinybird__workspaceId: ${TINYBIRD_WORKSPACE_ID:-} @@ -110,11 +118,14 @@ services: # Unique alias. Generated proxy routes and helper clients address Ghost # through this name, never through the bare `ghost` service name. - ghost-${COMPOSE_PROJECT_NAME:-ghost} + ingress: + aliases: + - ghost-${COMPOSE_PROJECT_NAME:-ghost} db: image: mysql:8.0.44@sha256:f37951fc3753a6a22d6c7bf6978c5e5fefcf6f31814d98c582524f98eae52b21 restart: ${RESTART_POLICY:-unless-stopped} - profiles: [local, production, no-caddy] + profiles: [local, production, no-caddy, shared-caddy] labels: <<: *site-labels org.ghost.docker.lifecycle: long-running @@ -122,9 +133,9 @@ services: expose: - "3306" environment: - MYSQL_ROOT_PASSWORD: ${DATABASE_ROOT_PASSWORD:?DATABASE_ROOT_PASSWORD is required} + MYSQL_ROOT_PASSWORD: ${DATABASE_ROOT_PASSWORD:-} MYSQL_USER: ${DATABASE_USER:-ghost} - MYSQL_PASSWORD: ${DATABASE_PASSWORD:?DATABASE_PASSWORD is required} + MYSQL_PASSWORD: ${DATABASE_PASSWORD:-} MYSQL_DATABASE: ${DATABASE_NAME:-ghost} MYSQL_MULTIPLE_DATABASES: ${DATABASE_EXTRA_DATABASES:-activitypub} volumes: @@ -186,10 +197,12 @@ services: networks: - ghost_network + # A production site's own Caddy, or with `infra`, the shared Caddy, which + # serves the members' routes from caddy/sites/. caddy: image: caddy:2.10.2-alpine@sha256:953131cfea8e12bfe1c631a36308e9660e4389f0c3dfb3be957044d3ac92d446 restart: ${RESTART_POLICY:-unless-stopped} - profiles: [production] + profiles: [production, infra] labels: <<: *site-labels org.ghost.docker.lifecycle: long-running @@ -214,8 +227,11 @@ services: depends_on: ghost: condition: service_started + # The shared Caddy has no Ghost of its own. + required: false + # Only what Caddy routes to is on this network: never MySQL. networks: - - ghost_network + - ingress traffic-analytics: image: ghost/traffic-analytics:1.0.450@sha256:33c0ff8a369040e1455b790cf1711c2ea7f3174bcd26230dc9f7fc77b401816c @@ -241,6 +257,9 @@ services: ghost_network: aliases: - traffic-analytics-${COMPOSE_PROJECT_NAME:-ghost} + ingress: + aliases: + - traffic-analytics-${COMPOSE_PROJECT_NAME:-ghost} activitypub: image: ghcr.io/tryghost/activitypub:1.2.16@sha256:b440548b8a87eaf70c9440d4b157beee4898b85ba4294509926517a85e7573c7 @@ -260,10 +279,10 @@ services: MYSQL_HOST: ${DATABASE_HOST:-db} MYSQL_PORT: ${DATABASE_PORT:-3306} MYSQL_USER: ${DATABASE_USER:-ghost} - MYSQL_PASSWORD: ${DATABASE_PASSWORD:?DATABASE_PASSWORD is required} + MYSQL_PASSWORD: ${DATABASE_PASSWORD:-} MYSQL_DATABASE: ${ACTIVITYPUB_DATABASE_NAME:-activitypub} LOCAL_STORAGE_PATH: /opt/activitypub/content/images/activitypub - LOCAL_STORAGE_HOSTING_URL: ${URL}/content/images/activitypub + LOCAL_STORAGE_HOSTING_URL: ${URL:-}/content/images/activitypub depends_on: db: condition: service_healthy @@ -273,6 +292,9 @@ services: ghost_network: aliases: - activitypub-${COMPOSE_PROJECT_NAME:-ghost} + ingress: + aliases: + - activitypub-${COMPOSE_PROJECT_NAME:-ghost} # Local sites only: catches the mail Ghost sends (staff invites, password # resets, member sign-in links) and shows it in a web inbox. Newsletters go @@ -324,7 +346,7 @@ services: org.ghost.docker.lifecycle: one-shot logging: *default-logging environment: - MYSQL_DB: mysql://${DATABASE_USER:-ghost}:${DATABASE_PASSWORD:?DATABASE_PASSWORD is required}@tcp(${DATABASE_HOST:-db}:${DATABASE_PORT:-3306})/${ACTIVITYPUB_DATABASE_NAME:-activitypub} + MYSQL_DB: mysql://${DATABASE_USER:-ghost}:${DATABASE_PASSWORD:-}@tcp(${DATABASE_HOST:-db}:${DATABASE_PORT:-3306})/${ACTIVITYPUB_DATABASE_NAME:-activitypub} depends_on: db: condition: service_healthy @@ -413,3 +435,10 @@ volumes: networks: ghost_network: + # What Caddy reaches the site's services on. A site with its own Caddy gets + # one of its own. Behind the shared Caddy, and in its directory, it is the + # shared Caddy's network, which the manager creates and no project owns + # (`.env` names it). + ingress: + name: ${INGRESS_NETWORK:-${COMPOSE_PROJECT_NAME:-ghost}_ingress} + external: ${INGRESS_EXTERNAL:-false} diff --git a/docs/architecture.md b/docs/architecture.md index 71e2ac75..8b3db562 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,22 @@ sites installed before, keeping any file in them that was edited. Caddy routes a `templates/site.caddy`, then belong to the operator. [caddy.md](caddy.md) owns route edits and reload instructions. +`src/shared.ts` is the shared Caddy: one Caddy project per daemon (`install +--infra`, the `infra` profile, and metadata of the `infra` mode with no +Ghost, so that `self-update` can keep its stack files and launcher current +without a backup, as it holds no data), on a network the manager creates +and labels with its directory, so no Compose project's `down` removes it. A +production install finds it by that network and selects the `shared-caddy` profile: Caddy's +own payload is left out, and its routes are a file in the shared Caddy's +`caddy/sites/`. The manager cannot see that directory, so it reads and writes +it through the running Caddy container (Engine API exec), as the directory's +owner; Caddy validates the whole configuration before it is reloaded, and +routes it refuses are removed. Duplicate domains (from Caddy's loaded +configuration) and projects (a routes file of that name) are refused before +any write. `remove` and a failed install's undo take a site's routes out +again. A site's backup holds a copy (`routes.caddy`), which a restore writes +back when the shared Caddy has none for the project. + `src/bundle/manifest.ts` defines the migration bundle schema and depends only on zod so the exporter can share it. Import policy stays outside that schema. `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..304ce261 100644 --- a/docs/caddy.md +++ b/docs/caddy.md @@ -2,7 +2,9 @@ `./ghost-docker install --domain` writes this site's routes into `caddy/sites/site.caddy`, once. From then on the file is yours, as the nginx -file Ghost-CLI generated was: the manager never rewrites it. +file Ghost-CLI generated was: the manager never rewrites it. On a server with +[the shared Caddy](#the-shared-caddy), the routes go into the shared Caddy's +directory instead, in a file named for the site. ## Layout @@ -32,8 +34,8 @@ A site moved from `main` keeps its own Caddyfile as `caddy/sites/site.caddy` main's snippets, which take no arguments, from `caddy/sites/legacy-snippets/`, and proxies to bare service names (`ghost:2368`), which resolve on the site's own network. Both keep working. Moving to this layout's snippets and aliases, -as `install` writes them, is optional, and is needed before the site joins a -shared Caddy. +as `install` writes them, is optional, and is needed before the site could +join a shared Caddy. ## Changing routes @@ -92,3 +94,120 @@ ActivityPub routes are always present. With the `activitypub` profile they point at this site's own service; otherwise at the hosted service, `https://ap.ghost.org`. ActivityPub, its migration job, database grants, storage and serving URL all belong to the site. + +## The shared Caddy + +Only one program can hold ports 80 and 443, so several production sites on +one server share one Caddy, as Ghost-CLI's sites shared one nginx. Everything +else stays each site's own: Ghost, MySQL, ActivityPub, analytics, backups, +updates and restores work exactly as they do for a site on its own. A local +site never uses the shared Caddy, and a server without one runs each +production site with its own Caddy, as before. + +Set it up once, in a directory of its own, before the sites: + +```bash +mkdir ~/caddy && cd ~/caddy +curl -fsSL https://docker.ghost.org/install.sh | bash -s -- install --infra +``` + +Then install each site as usual, each in its own directory. On a server with +the shared Caddy, `install --domain` joins it: the site has no Caddy of its +own, and its routes are written to the shared Caddy's +`caddy/sites/.caddy`, which Caddy validates and loads before the +site starts. Its first line, `# ghost-docker install `, names the +write, so a failed install removes the file only while it is still that +write's. A site installed `--no-caddy` does not join it. `` is the site's `COMPOSE_PROJECT_NAME`. A domain the +shared Caddy already serves, or a project that already has routes there, is +refused before anything is written. An existing site cannot be moved behind +the shared Caddy yet; it keeps its own Caddy, which needs 80 and 443, so set +the shared Caddy up on a server before its first production site. + +| Path, in the shared Caddy's directory | Owner | +| --- | --- | +| `caddy/sites/.caddy` | one per site behind it: written by that site's `install`, then yours | +| `caddy/custom/*.caddy`, `caddy/global/*.caddy` | yours, as for a single site | + +Edit a site's routes as described above, then reload the shared Caddy, in +its directory: + +```bash +docker compose exec caddy caddy reload --config /etc/caddy/Caddyfile +``` + +A configuration Caddy does not load is not applied: every site keeps being +served as before, and Caddy says why. `./ghost-docker check` in a site's +directory reports the shared Caddy's health, the site's routes file, and +HTTPS through it. `./ghost-docker list` shows the shared Caddy as `infra`, +and each site behind it as `shared-caddy`. + +`./ghost-docker remove`, in a site's directory, removes its routes file, +reloads the shared Caddy, and takes the site's containers down; no other site +is touched. The site's directory, data and backups stay until you delete them. +A site's backup holds its routes, read from the shared Caddy. Restoring it +keeps the routes the shared Caddy has for the project, since they may have +been edited since, and otherwise writes the backup's back: a site removed, or +moved to a new server with a shared Caddy of its own, comes back with them. +The shared Caddy's own directory has no backup; it holds no data, and +`install --infra` sets it up again, with your edits to its Caddyfile and +snippets yours to keep. + +### How it is connected + +The shared Caddy is its own Compose project (`ghost-infra` unless `--name` +says otherwise), with the `infra` profile. `install --infra` creates the +network `ghost-ingress`, which belongs to no Compose project, so taking the +shared Caddy down never takes it away from the sites. Each site behind it +selects the `shared-caddy` profile, and its Ghost, ActivityPub and analytics join +`ghost-ingress` under their unique aliases (`ghost-:2368` and so +on), which is why routes always use them. MySQL and every one-shot job stay on +the site's own network. + +Ghost is still published on the site's loopback port, so a site behind the +shared Caddy can be reached without it, for example from your own proxy. + +### What it trusts + +The shared network is not isolation between sites. Every container on it can +reach every other site's Ghost, ActivityPub and analytics, and a site's bare +service names (`ghost`, `activitypub`) answer for every site on it, which is +why nothing routes by them. MySQL is never on it. Run sites behind one Caddy +only when you would trust them on one server anyway, as with Ghost-CLI. + +The shared Caddy's directory holds every site's routes, and its `caddy_data` +volume their certificates. Its `caddy/` is writable by whoever installed it, and the manager writes a site's +routes as the owner of `caddy/sites/`. + +### Restarting and updating it + +Restarting the shared Caddy (`docker compose restart`, or `down` then +`up -d`, in its directory) interrupts every site behind it for those seconds, +and brings each back with its routes; certificates are kept in its +`caddy_data` volume. A site's own operations (`update`, `self-update`, +`backup`, `restore`, `docker compose down`) never restart it. + +Its Caddy image is pinned in its `compose.yml`, by the release it runs. +`./ghost-docker self-update`, in its directory, moves it to a newer release as +for a site: untouched stack files are replaced, edited ones kept beside the +release's `.new`, and the launcher re-pinned; then Caddy is recreated, which +restarts it as above, reloads its configuration (so a changed Caddyfile or +snippet is loaded even when the container was not recreated), and must pass +its health check. Its reloads and those of each site's `install` and `remove` +take turns, through a lock on `caddy/sites/` inside the container, so none +loads a configuration read before another site's routes were written. There is no backup, +because it holds no data. The release's images are pulled before any file is +written, so one that cannot be pulled changes nothing. Once files are written, +a site's reload can load them, so a failed update puts its files back and +reloads them into Caddy, or starts the previous Caddy again when it had been +recreated. It never updates the sites behind it, and their own +`self-update` never touches it. + +### Capacity + +Caddy itself costs little per site: a few routes, and a certificate it renews +in the background. What limits a server is each site's own Ghost and MySQL, +and ActivityPub and analytics where selected, which cost what they would on a +server of their own ([configuration.md](configuration.md#site-modes-and-profiles) +lists the optional services' costs). Size the server for the sum of them. +Let's Encrypt limits how many certificates one account obtains per hour; +installing many sites at once can reach it, and Caddy retries later. diff --git a/docs/configuration.md b/docs/configuration.md index a50631b5..b66207b3 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -107,16 +107,22 @@ value in either file may be a credential. ## Site modes and profiles Site mode is selected through `COMPOSE_PROFILES`, and exactly one of `local`, -`production` or `no-caddy` must be present: +`production`, `no-caddy` or `shared-caddy` must be present: | Profile | Services | Ingress | `SITE_MODE` | | --- | --- | --- | --- | | `local` | `ghost`, `db` | Ghost on `127.0.0.1:${GHOST_PORT}` | `local` | | `production` | `ghost`, `db`, `caddy` | Caddy on `${HTTP_PORT}` / `${HTTPS_PORT}` | `production` | | `no-caddy` | `ghost`, `db` | [Your own proxy](#your-own-proxy), to Ghost on `127.0.0.1:${GHOST_PORT}` | `production` | +| `shared-caddy` | `ghost`, `db` | [The shared Caddy](caddy.md#the-shared-caddy), on its network `${INGRESS_NETWORK}` | `production` | -A `no-caddy` site is a production site in every other way: backup, restore, -update, `self-update` and the upgrade supervisor treat it as one. +A `no-caddy` or `shared-caddy` site is a production site in every other way: +backup, restore, update, `self-update` and the upgrade supervisor treat it as +one, and production's rules below apply to it. The shared Caddy's own +directory selects `infra`, and nothing else: Caddy alone, with no site. Its +`.env` needs no Ghost or database settings, so compose.yml guards none of +them with `:?` (Compose interpolates the services a profile leaves out too); +`config validate` requires them for a site instead. Optional per-site profiles are added to the same list and are purely additive. Adding one never changes the site mode: @@ -269,7 +275,13 @@ Each service has a unique alias suffixed with the project name: - `mailpit-${COMPOSE_PROJECT_NAME}:1025` (SMTP) Generated proxy routes and helper clients use these, never the bare service -name. `COMPOSE_PROJECT_NAME` is the site's stable identity and is kept +name. Ghost, ActivityPub and analytics are also on the `ingress` network, under +the same aliases, which is all Caddy reaches: never MySQL. A site with its own +Caddy has an `ingress` network of its own. Behind the shared Caddy it is the +shared Caddy's, `ghost-ingress`, which `.env` names (`INGRESS_NETWORK`, with +`INGRESS_EXTERNAL=true`, since the manager created it and no Compose project +owns it); there every site's bare service names answer for every site, so +only the unique aliases identify one. `COMPOSE_PROJECT_NAME` is the site's stable identity and is kept independent of the directory name. `install` chooses it once: the domain's in production, and locally the directory's name and a random pair (`ghost-local-blog-secondary-roadrunner`) that no project on the daemon has, diff --git a/docs/ghost-cli-replacement.md b/docs/ghost-cli-replacement.md index 4090a36f..13d52cb9 100644 --- a/docs/ghost-cli-replacement.md +++ b/docs/ghost-cli-replacement.md @@ -12,7 +12,6 @@ Linear](https://linear.app/ghost/issue/PLA-412). | Outcome | Remaining work | Dependencies | | --- | --- | --- | | Tagged single-site production | S12 qualification | Existing image self-update, local and production import, backup and restore | -| Several sites behind shared Caddy | S13 | Existing backup/restore and released-main migration | | Later extensions | S11 file secrets, S14 service references, S15 nightly transitions, S16 Redis | See each step | Qualify production on Linux with rootful Docker Engine. Local qualification also covers @@ -42,12 +41,12 @@ environment-based installs, older imports, restart, and restore still work. Repo: ghost-docker, with cross-repo fixtures. Deps: existing install, local and production import, backup/restore, self-update, released-main migration, and the upgrade supervisor with -Ghost Admin's updates; qualify S13 and S11 when they have shipped. +Ghost Admin's updates, and the shared Caddy; qualify S11 when it has shipped. Gates the first stable tag and merging `next-docker` into `main`. Include the launcher on Linux, macOS and WSL2. Consolidate CI and qualify the actual minimum supported tools and image versions. Run fresh local/production install, optional-service variants, CLI migration, legacy stack update, Ghost upgrade/recovery, supervisor/Admin, and restore -scenarios. On a site with analytics, `update` must rerun Tinybird sync from the new +scenarios, and several sites behind the shared Caddy. On a site with analytics, `update` must rerun Tinybird sync from the new image and the deploy must succeed; it needs a Tinybird login, so it is run by hand. Before merging, pin the migration tests' `GD_RELEASED_MAIN` (default `origin/main`, in `manager/test/site.ts`, `tests/e2e/migrate-main.sh` and the manager CI job) to `main`'s last commit, and rerun them. Include Linux runtime tests and macOS-compatible shell/configuration checks. @@ -59,37 +58,11 @@ README/help include quick starts, prerequisites, version/compatibility policy, backup/restore, migration losses and cutover, custom proxy configuration, diagnostics, and uninstall. Document deletion of bind-mounted data separately from `down -v`, with explicit recovery consequences. Explain command equivalences without claiming full CLI -parity for unsupported features. Describe shared infra according to whether S13 has -shipped. - -### S13 — Optional shared Caddy - -Repo: ghost-docker. Depends on backup/restore for new member sites; converting an -existing site into a member (PLA-504) starts from a site on this layout, which the -released-main migration provides. Several sites on one server, as -Ghost-CLI ran several sites behind one nginx. 80 and 443 can belong to one Caddy only, -so that Caddy is shared; everything else stays per site, MySQL included, so backup, -restore, upgrade and import are unchanged. - -- `install --infra` sets up the shared Caddy once: a Compose project of its own, - with an external network each member site's Ghost (and optional services) also - joins. Infra-only configuration must resolve without a Ghost `URL`; review - required-variable guards and the profile validation when adding this mode. `install --domain` on a server that has it adds the site as a member - instead of starting a Caddy of its own. -- Each member's routes are a file in the shared Caddy's `sites/` directory, - written once by its install and then the operator's, as for a single-site install. Upstreams are - the member's unique aliases, described in [configuration.md](configuration.md#service-names-on-the-network). -- `list` shows the members; removing a site removes its routes file. -- Ghost publishes on loopback as before, so a member can still be reached - without Caddy. - -Acceptance: a shared Caddy with two members on different Ghost versions, each with its -own optional services; upgrading, restoring or removing one leaves the other untouched; -a duplicate domain is refused; a Caddy restart brings both back. +parity for unsupported features. ### S14 — Service images as full references -Repo: ghost-docker. Deps: S12; independent of S13. Give every service a full, +Repo: ghost-docker. Deps: S12. Give every service a full, registry-qualified reference behind an `.env` variable, pinned by the release with its digest. `config set` selects a mirror or another registry. There is no registry selector or separate registry state: the reference is the choice. @@ -142,7 +115,7 @@ supervisor's status. Repo: ghost-docker, verifying behavior against supported Ghost versions. Deps: S12 and existing configuration, installer, backup, upgrade, and secret interfaces; independent -of S13-S15. Follow the requirements below. Add `install --with redis` and the `redis` +of S14 and S15. Follow the requirements below. Add `install --with redis` and the `redis` profile for existing sites, with the service, version-aware Ghost cache wiring, private network, healthchecks, credentials, resource policy, diagnostics, and enable/disable steps. Keep Redis per-site even when shared infra exists. Default installs are @@ -157,8 +130,8 @@ Acceptance: `--with redis` installs, local and production, use Redis; default in start no Redis and behave as before; enabling and disabling it on an existing site keeps operator overrides. Verify real cache reads/writes and invalidation, resource limits, restart/outage/reconnect, upgrade/restore behavior, secret handling, and supported Ghost -version coverage. If S13 has shipped, verify two sites do not share cache data or expose -Redis through the shared ingress network. Specify cache rebuilding/persistence behavior +version coverage. Verify two sites behind the shared Caddy do not share cache data or +expose Redis through its network, `ghost-ingress`. Specify cache rebuilding/persistence behavior explicitly. Do not wire speculative traffic-analytics/ActivityPub consumers until their released interfaces exist and their cache-versus-durable-state requirements are established. @@ -193,5 +166,5 @@ support. Before wiring any such consumer, verify its released configuration cont distinguish disposable cache from durable queues/counters/salts/other state. Durable state needs appropriate persistence, eviction, isolation, backup/restore, and upgrade policy; separate instances when policies differ. Key prefixes or Redis logical DBs alone -do not isolate memory/eviction/durability policies. Redis remains per-site if a shared -Caddy (S13) is in use. +do not isolate memory/eviction/durability policies. Redis remains per-site behind the +shared Caddy. diff --git a/docs/install.md b/docs/install.md index 4385dfc0..a0809ce0 100644 --- a/docs/install.md +++ b/docs/install.md @@ -22,7 +22,8 @@ and curl for the install command above. Production is supported on Linux with ro see [Windows](#windows). **One directory is one site.** The site directory is the current directory, or -`--dir PATH`. +`--dir PATH`. Several production sites on one server share one Caddy; see +[Several sites on one server](#several-sites-on-one-server). ## Releases @@ -56,6 +57,7 @@ ghost-docker install [--local | --domain example.com [--admin-domain admin.examp [--channel stable|beta | --release vX.Y.Z] [--no-prompt] [--no-start] ghost-docker install --import BUNDLE [--name NAME] [--port 2368] [--with mailpit] [--no-prompt] [--no-start] ghost-docker install --import BUNDLE [--domain DOMAIN] [--admin-domain DOMAIN] [--email EMAIL | --no-caddy] [--no-start] +ghost-docker install --infra [--name NAME] [--channel stable|beta | --release vX.Y.Z] [--no-start] ``` | Option | Meaning | @@ -75,6 +77,7 @@ ghost-docker install --import BUNDLE [--domain DOMAIN] [--admin-domain DOMAIN] [ | `--no-prompt` | Never ask: every input must be an option. | | `--no-start` | Write the configuration and routes; start nothing. | | `--import BUNDLE` | Import a Ghost-CLI site; see [Importing a Ghost-CLI site](#importing-a-ghost-cli-site). | +| `--infra` | Set up the shared Caddy in this directory, for several production sites; see [Several sites on one server](#several-sites-on-one-server). | `install` refuses a directory that already holds a site or data, checks the host first (as `./ghost-docker doctor` does), generates fresh database @@ -302,6 +305,32 @@ docker compose up -d Remove the copy when you are done: `docker compose down`, then delete the directory, with `sudo` because MySQL owns `data/mysql`. For the real move, export again with the source stopped, to a new path. +## Several sites on one server + +As Ghost-CLI ran several sites behind one nginx, several production sites run +behind one shared Caddy: it alone holds 80 and 443. Each site keeps its own +directory, Ghost, MySQL and optional services, and is backed up, updated and +restored on its own. Set the shared Caddy up first, in a directory of its own: + +```bash +mkdir ~/caddy && cd ~/caddy +curl -fsSL https://docker.ghost.org/install.sh | bash -s -- install --infra + +mkdir ~/blog && cd ~/blog +curl -fsSL https://docker.ghost.org/install.sh | bash -s -- install --domain blog.example.com +mkdir ~/shop && cd ~/shop +curl -fsSL https://docker.ghost.org/install.sh | bash -s -- install --domain shop.example.com +``` + +On a server with the shared Caddy, every production install joins it, except +one with `--no-caddy`, and its routes are written to the shared Caddy's +`caddy/sites/`. A domain it already +serves is refused. `./ghost-docker remove`, in a site's directory, removes its +routes and takes it down, leaving the other sites alone. A site installed with +a Caddy of its own cannot be moved behind the shared Caddy yet. The trust +model, restarts, updates and capacity are in +[caddy.md](caddy.md#the-shared-caddy). + ## Ports, and your existing proxy **Installation never stops or reconfigures anything already running.** @@ -309,9 +338,10 @@ directory, with `sudo` because MySQL owns `data/mysql`. For the real move, expor - A port `install` chooses skips ports other containers publish, and on macOS ports other programs hold too. A busy port you ask for with `--port` is an error. -- A production site needs 80 and 443 for Caddy. If anything holds them, - installation fails, names the port, and leaves the directory as it was. A - site installed `--no-caddy` does not use them. +- A production site needs 80 and 443 for Caddy, unless the server has the + shared Caddy. If anything holds them, installation fails, names the port, + and leaves the directory as it was. A site installed `--no-caddy` does not + use them. **On Linux, use Docker Engine 28 or later.** Ghost (and Mailpit) are published on `127.0.0.1` only, but older engines let other machines on the local network @@ -350,6 +380,7 @@ How ports are detected on each platform: [Ports](reference.md#ports). ./ghost-docker self-update # ghost-docker itself; see below ./ghost-docker backup # the databases, content and configuration, into backups/ ./ghost-docker restore backups/ +./ghost-docker remove # take the site down; its directory and data stay ``` `check` exits non-zero when anything is wrong. A new production site whose DNS @@ -359,7 +390,8 @@ is verified](reference.md#how-a-site-is-verified). The routes are a file you edit, `caddy/sites/site.caddy`, followed by `docker compose exec caddy caddy reload --config /etc/caddy/Caddyfile`; see -[caddy.md](caddy.md). +[caddy.md](caddy.md). Behind the shared Caddy, they are in its directory +instead, and it is reloaded there. ## update @@ -407,7 +439,9 @@ ghost-docker self-update [--check] [--no-backup] [--channel stable|beta | --to v Updates ghost-docker itself (the stack's files and the manager image) to the newest release on the site's channel. **It never changes Ghost**; use [`update`](#update) for that. If a release needs a newer Ghost than the site -runs, it stops first and says so. +runs, it stops first and says so. In the shared Caddy's directory it updates +the shared Caddy, which restarts it for every site behind it; see +[caddy.md](caddy.md#restarting-and-updating-it). | Option | Meaning | | --- | --- | diff --git a/docs/reference.md b/docs/reference.md index b7c613c5..e31c51aa 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -16,8 +16,8 @@ happens underneath them. path), and disk and memory, which warn rather than refuse. 3. **Ports Docker knows about.** The default port skips any that a container publishes. An explicit `--port`, or 80 and 443 for a production site with - Caddy, that - a container publishes is an error naming the container. Nothing is + a Caddy of its own, that a container publishes is an error naming the + container. Nothing is stopped. Ports held by anything else are found when the services start; see [Ports](#ports). 4. **The exact Ghost image.** The requested tag is pulled, and the pulled @@ -41,6 +41,15 @@ happens underneath them. the site's domains, its network aliases and every snippet argument. It is yours from then on; see [caddy.md](caddy.md). With `--no-caddy`, nothing: the routing is your proxy's ([configuration.md](configuration.md#your-own-proxy)). + On a server with [the shared Caddy](caddy.md#the-shared-caddy), the site + selects the `shared-caddy` profile instead of `production` and has no Caddy + of its own: the routes are written to the shared Caddy's + `caddy/sites/.caddy`, through its running container, as the owner + of that directory, then Caddy validates its whole configuration and + reloads. Before anything is written, a shared Caddy that is not running, a + project that already has routes there, and a domain it already serves are + refused; routes Caddy does not accept are removed again. A `--no-caddy` + site never joins the shared Caddy. 8. **Metadata**: `.ghost-docker.json`, described in [architecture.md](architecture.md#installation-metadata). 9. **Start and verify**, unless `--no-start`: `docker compose up --wait`, so @@ -50,12 +59,41 @@ happens underneath them. running container is not readiness. **A failed installation removes what it created** — containers, network, -volumes, the data directories, `.env`, `ghost.env`, the metadata and the -written stack files — so the same command can simply be run again in the same +volumes, the data directories, `.env`, `ghost.env`, the metadata, the +written stack files and the site's routes in the shared Caddy — so the same command can simply be run again in the same directory. That covers a port conflict, a failed pull, a service that never becomes healthy, and a site that starts but cannot be reached. Before removing anything it prints the services' last log lines. +### install --infra + +Sets up [the shared Caddy](caddy.md#the-shared-caddy) in an empty directory: +`compose.yml`, `caddy/` and the launcher, an `.env` selecting the `infra` +profile, and the network `ghost-ingress`, labelled with the directory and +project, which no Compose project owns. It takes no site options, and writes +no `ghost.env` or data directories: there is no Ghost. Its metadata records +the `infra` mode, no Ghost, and the stack files, for `self-update`. It refuses a +daemon that already has the network, and 80 and 443 held by a container. +Caddy must start and pass its health check; a failure removes everything, +the network included. Site commands (`check`, `backup`, `update`, `restore`, +`remove`, ...) refuse its directory; `config`, `info` and `self-update` work +there. Its `self-update` takes no backup and pauses no writers: it writes the +release's files, recreates Caddy and waits for its health check, and on a +failure puts the files back and starts the previous Caddy (see +[caddy.md](caddy.md#restarting-and-updating-it)). + +## remove + +`./ghost-docker remove [--yes]` takes the site in this directory down and +leaves everything else on the server as it was. Behind the shared Caddy, it +first removes the site's `caddy/sites/.caddy` there and reloads the +shared Caddy, which must be running. Then `docker compose down` removes the +site's containers and networks; its volumes, directory, data and backups +stay, and `docker compose up -d` starts it again (behind the shared Caddy, +once its routes are back). It asks first, at a terminal; without one it needs +`--yes`. It holds the site's lock, so it is refused while a backup, restore or +update runs. + ## How a site is verified Each service is judged by its own health check, which `up --wait` already @@ -71,6 +109,7 @@ Each answer is reported for what it is: | https | An HTTPS request to Caddy's container for Ghost's `/ghost/api/admin/site/`, with the domain as its server name and Host, as a browser asks. **serving** means this site's Ghost answered through Caddy: Ghost reports its site's URL, and that must be the site's `URL` (by either name, the canonical one, not the admin domain). It names the certificate's issuer and expiry; a certificate from a CA browsers do not trust (staging, or Caddy's internal CA) is a `warning`. **pending** means Caddy has no certificate for the name yet, so Ghost could not be asked through it: Caddy obtains one once the domain's DNS reaches this host, `./ghost-docker check` reports the change, and `docker compose logs caddy` shows each attempt. Caddy answering with something other than Ghost (a broken route, a 502), another site's Ghost (a route to the wrong upstream), or an out-of-date certificate, is an `ERROR`. | `ok`, `warning`, `note` or `ERROR` | | admin https | With an admin domain of its own: the same, for that name. Ghost reached by the admin domain still reports the site's `URL`, which is what is checked. On the site's domain, Ghost answering the Admin API path with a redirect to the admin domain counts as Ghost answering; the admin domain's own answer then names the site. | `ok`, `warning`, `note` or `ERROR` | | ingress | With `--no-caddy` (the `no-caddy` profile), in place of **caddy** and **https**: the site is served by your own proxy, which the manager cannot reach from its container, so it is not checked. The note names the URL and the loopback port the proxy must pass it to with `X-Forwarded-Proto: https`. | `note` | +| shared caddy, routes | Behind [the shared Caddy](caddy.md#the-shared-caddy), in place of **caddy**: the shared Caddy's health check, from its container, and that its `caddy/sites/.caddy` exists. A server without the shared Caddy's network is an `ERROR`. **https** then asks the shared Caddy, on its network. | `ok` or `ERROR` | | mailpit | With `--with mailpit`: its health check. The check names `mailpit-${COMPOSE_PROJECT_NAME}:1025`, where Ghost sends mail. | `ok` or `ERROR` | | published ports | The ports Docker says it published. A container cannot reach the host's own loopback interface, so they are not checked from there (the **https** request goes to Caddy's container, not to the host's ports): opening the URL is that check. | `note` | @@ -98,8 +137,8 @@ offered; for a private name, put `tls internal` in a `caddy/custom/` file. records its port, and a new site may be given the same one. - A port you *asked for* does not: `--port` on a busy port is an error, because a site at an address nothing else expects is worse than a refusal. -- A production site needs 80 and 443 for Caddy; one installed `--no-caddy` - does not. If a container holds them, installation +- A production site needs 80 and 443 for Caddy; one installed `--no-caddy`, + or behind the shared Caddy, does not. If a container holds them, installation stops before writing anything and names it. If another program holds them, Docker refuses to start Caddy; the error names the port, says nothing that was running was stopped, and the directory is as it was. @@ -363,6 +402,7 @@ self-update. Compose files you used with `-f` by hand, such as | `database/ghost.sql` | A `mysqldump` of Ghost's database, taken as the site's own database user in one consistent snapshot. | | `database/activitypub.sql` | ActivityPub's database, when the `activitypub` profile is on. | | `content.tar.gz` | The content directory, `data/ghost`: images, media, files, themes, settings. | +| `routes.caddy` | Behind the shared Caddy: the site's routes, its `caddy/sites/.caddy` there, without the marker line its install wrote. When the shared Caddy cannot be read, the backup warns and holds none. | | `site/` | `.env`, `ghost.env`, `.ghost-docker.json`, `compose.override.yml` and the overrides `COMPOSE_FILE` names, `caddy/sites/`, `caddy/custom/`, `caddy/global/` and, for a site installed from the image, the stack's files and the launcher the site ran. | A backup is **checked** before it counts as one: every dump is loaded into a @@ -374,8 +414,9 @@ is an error, not a backup:** `backup` exits `1` and leaves nothing in `backups/`. What a backup cannot hold is named in its manifest and in the summary: -Caddy's certificates, which Caddy obtains again when the site starts; the -Tinybird workspace and analytics data outside the site; Mailpit's inbox. +Caddy's certificates, which Caddy obtains again when the site starts (behind +the shared Caddy, its own configuration and certificates); the Tinybird +workspace and analytics data outside the site; Mailpit's inbox. ### What a backup captures @@ -446,7 +487,10 @@ In order: project and busy ports are refused, named, and never stopped. The backup's configuration (for a clone, with the clone's `compose.yml`) is resolved outside the site, and must name exactly the images the backup - records and mount the data where restore loads it. Nothing has changed. + records and mount the data where restore loads it. Behind the shared + Caddy, it must be running; routes it already has for the project are kept, + and otherwise the backup must hold them, for domains it does not already + serve. Nothing has changed. 2. **The lock**, then every image the backup records is pulled before anything stops, and each service that was running must get, by its image ID or a registry digest, the very image it ran. A reference that names another @@ -466,6 +510,8 @@ In order: 5. **The databases.** MySQL starts on an empty data directory, which creates the site's databases and user from the restored `.env`; each dump is loaded as the site's user, and every table's rows must match the manifest. + Behind the shared Caddy, the backup's routes, when it has none for the + project, are written into it, validated and loaded, as an install's are. 6. **Start and verify.** `up --wait`, then the site is verified through its ingress as `check` does. `.ghost-docker-restore/` is removed. diff --git a/manager/src/backup.ts b/manager/src/backup.ts index 844840a5..addd253c 100644 --- a/manager/src/backup.ts +++ b/manager/src/backup.ts @@ -23,12 +23,14 @@ import { DATABASE_NAME, MANIFEST_FILE, readBackupManifest, + ROUTES_FILE, SITE_FILES_DIR, type BackupManifest, } from './backup/manifest.ts'; import { compose, composeError, composeOverrides, composePs, composeUp } from './compose.ts'; import { runOnce } from './docker/client.ts'; -import { CliError } from './errors.ts'; +import { CliError, describeError } from './errors.ts'; +import { describeShared, findSharedCaddy, readRoutes, routesPath } from './shared.ts'; import { WriterPause } from './writers.ts'; import { atomicWrite, copyPresent, filesUnder, PRIVATE } from './fs.ts'; import { DATABASE_MS, tableCount, withSiteDatabase } from './import/database.ts'; @@ -44,7 +46,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. */ @@ -170,11 +179,49 @@ export function siteOverrides(resolved: ResolvedSite): string[] { }); } +/** + * Behind the shared Caddy, the site's routes, copied into the backup so a + * restore can write them back. They are the shared Caddy's files, read + * through its container; one that cannot be read leaves the backup without + * them, with a warning, rather than failing it. + */ +async function captureRoutes(io: Io, project: string, partial: string): Promise { + try { + const shared = await findSharedCaddy(io); + if (shared === null) { + warn(io, 'routes', 'this server has no shared Caddy, so the backup holds no routes'); + return false; + } + const routes = await readRoutes(io, shared, project); + if (routes === null) { + warn( + io, + 'routes', + `${routesPath(shared, project)} does not exist, so the backup holds no routes`, + ); + return false; + } + atomicWrite(join(partial, ROUTES_FILE), routes, PRIVATE); + ok(io, 'routes', `${routesPath(shared, project)}, from ${describeShared(shared)}`); + return true; + } catch (failure) { + warn(io, 'routes', `${describeError(failure)}\n The backup holds no routes.`); + return false; + } +} + /** What the site has that a backup cannot hold, for the manifest and the summary. */ -function notIncluded(site: SiteFacts): string[] { +function notIncluded(site: SiteFacts, routes: boolean): string[] { const profiles = site.settings.get('COMPOSE_PROFILES') ?? ''; const lines: string[] = []; - if (site.layout === 'production') { + if (site.layout === SHARED_CADDY_PROFILE) { + if (!routes) { + lines.push("its routes, which could not be read from the shared Caddy's caddy/sites/"); + } + lines.push( + "the shared Caddy's own configuration and its certificates, which are not the site's", + ); + } else if (site.layout === 'production') { lines.push( "Caddy's certificates and state, which Caddy obtains again when the site starts", ); @@ -466,6 +513,10 @@ export async function takeBackup({ `${copied} files and directories: configuration, metadata, Caddy${overrides.length > 0 ? `, ${overrides.join(', ')}` : ''}`, ); + const routes = + site.layout === SHARED_CADDY_PROFILE && + (await captureRoutes(io, metadata.site.project, partial)); + // Captured: the site runs again before the slower checks, unless the // caller keeps it paused. await resume(); @@ -551,8 +602,9 @@ export async function takeBackup({ running: ran, databases: manifestDatabases, content: { file: CONTENT_ARCHIVE, entries }, + ...(routes ? { routes: ROUTES_FILE } : {}), files, - notIncluded: notIncluded(site), + notIncluded: notIncluded(site, routes), }; atomicWrite( join(partial, MANIFEST_FILE), @@ -590,7 +642,11 @@ export async function readBackup(io: Io, root: string): Promise throw new CliError(`${read.reason}. Nothing has been changed.`); } const { manifest } = read; - const wanted = [manifest.content.file, ...manifest.databases.map((database) => database.file)]; + const wanted = [ + manifest.content.file, + ...manifest.databases.map((database) => database.file), + ...(manifest.routes === undefined ? [] : [manifest.routes]), + ]; for (const file of wanted) { if (!(file in manifest.files)) { throw new CliError( diff --git a/manager/src/backup/manifest.ts b/manager/src/backup/manifest.ts index a04ba748..f6799de2 100644 --- a/manager/src/backup/manifest.ts +++ b/manager/src/backup/manifest.ts @@ -6,6 +6,9 @@ import { readIfExists } from '../fs.ts'; export const BACKUP_FORMAT = 'ghost-docker-backup'; export const BACKUP_VERSION = 1; + +/** Behind the shared Caddy, the site's routes, in the backup (manifest `routes`). */ +export const ROUTES_FILE = 'routes.caddy'; export const MANIFEST_FILE = 'manifest.json'; /** The content directory, as a gzipped tarball of its contents. */ export const CONTENT_ARCHIVE = 'content.tar.gz'; @@ -85,6 +88,12 @@ export const backupManifestSchema = z.strictObject({ file: inside, entries: z.number().int().nonnegative(), }), + /** + * Behind the shared Caddy: the site's routes, as its caddy/sites/.caddy + * held them, without the marker line its install wrote. A restore writes + * them back when the shared Caddy has none for the project. + */ + routes: inside.optional(), /** SHA-256 of every file in the backup but this one, by path. */ files: z.record(inside, z.string().regex(/^[0-9a-f]{64}$/)), /** What the site has that this backup does not, for a person to read. */ diff --git a/manager/src/cli.ts b/manager/src/cli.ts index fd010a10..44cab024 100644 --- a/manager/src/cli.ts +++ b/manager/src/cli.ts @@ -9,6 +9,7 @@ import { backupCommand, restoreCommand } from './commands/backup.ts'; import { getCommand, setCommand, validateCommand } from './commands/config.ts'; import { doctorCommand } from './commands/doctor.ts'; import { installCommand } from './commands/install.ts'; +import { removeCommand } from './commands/remove.ts'; import { checkCommand, infoCommand, listCommand } from './commands/site.ts'; import { selfUpdateCommand } from './commands/self-update.ts'; import { supervisorRunCommand } from './commands/supervisor.ts'; @@ -31,6 +32,7 @@ const COMMANDS: Record = { 'supervisor run': supervisorRunCommand, backup: backupCommand, restore: restoreCommand, + remove: removeCommand, version: versionCommand, doctor: doctorCommand, help: defineCommand({ diff --git a/manager/src/commands/common.ts b/manager/src/commands/common.ts index c96378cf..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 d0a15acd..ed56d4ae 100644 --- a/manager/src/commands/install.ts +++ b/manager/src/commands/install.ts @@ -1,5 +1,7 @@ // `install`: a local or production site, configured, started and verified. -// A production site has Caddy, or with --no-caddy, the operator's own proxy. +// A production site has Caddy, or with --no-caddy, the operator's own proxy; +// with --infra, the shared Caddy (shared.ts), and on a server that has one, a +// production site behind it. // `run` takes the parts in order, each a function of its own: refusals that // need nothing; with --import, the bundle (import.ts); preflight, ports, the // exact Ghost image and a free project name, still changing nothing; then @@ -9,8 +11,9 @@ import { randomBytes } from 'node:crypto'; import { existsSync, readdirSync } from 'node:fs'; import { join } from 'node:path'; -import { ACME_EMAIL, isHostname, SITE_FILE, writeRoutes } from '../caddy.ts'; -import { ALL_PROFILES, compose, upAndWait } from '../compose.ts'; +import { ACME_EMAIL, isHostname, renderRoutes, SITE_FILE, writeRoutes } from '../caddy.ts'; +import { ALL_PROFILES, compose, composePs, upAndWait } from '../compose.ts'; +import { createNetwork, MANAGED_LABEL } from '../docker/client.ts'; import { z } from 'zod'; import { defineCommand, flag, refused } from '../command.ts'; import { findingErrors, validate } from '../config.ts'; @@ -28,7 +31,7 @@ import { } from '../ghost.ts'; import { clearUnfinishedImport, Importing, importConflict } from '../import.ts'; import type { Io, Prompter } from '../io.ts'; -import { installationMetadata, writeMetadata } from '../meta.ts'; +import { infraMetadata, installationMetadata, writeMetadata } from '../meta.ts'; import { isCheckout, makeDirectories, @@ -45,13 +48,29 @@ import { ENV_FILE, generatedSettings, GHOST_ENV_FILE, + ingressSettings, + INFRA_PROFILE, MAILPIT_DATA_DIR, + SHARED_CADDY_PROFILE, META_FILE, profileConflict, NO_CADDY_PROFILE, type Layout, type SiteMode, } from '../site.ts'; +import { + addRoutes, + describeShared, + findSharedCaddy, + INFRA_DIR_LABEL, + INFRA_PROJECT, + INFRA_PROJECT_LABEL, + INGRESS_NETWORK, + refuseTaken, + routesPath, + runningCaddy, + type SharedCaddy, +} from '../shared.ts'; import { takenPorts } from '../ports.ts'; import { knownProjects, PROJECT_NAME, projectName, refuseForeignProject } from '../project.ts'; import { Created } from '../undo.ts'; @@ -206,6 +225,9 @@ const options = z release: releaseOption( 'Install this release, vX.Y.Z or vX.Y.Z-beta.N. The launcher resolves it.', ), + infra: flag( + 'Set up the shared Caddy in this directory, for several production sites on this server; each later production install joins it, unless --no-caddy. See docs/caddy.md.', + ), noPrompt: flag('Never ask: every input must be an option.'), noStart: flag('Write the configuration and routes; start nothing.'), }) @@ -232,7 +254,8 @@ const options = z (flags.ghostImage !== undefined && flags.import !== undefined ? '--ghost-image cannot be combined with --import: an import runs on the published Ghost release' : null) ?? - (flags.import === undefined ? null : importConflict(flags)); + (flags.import === undefined ? null : importConflict(flags)) ?? + (flags.infra ? infraConflict(flags) : null); if (conflict !== null) { ctx.addIssue({ code: 'custom', message: conflict }); } @@ -240,6 +263,30 @@ const options = z type Flags = z.output; +/** The options --infra cannot take: it sets up Caddy alone, for sites installed after it. */ +function infraConflict(flags: Flags): string | null { + const given = ( + [ + ['--local', flags.local], + ['--domain', flags.domain !== undefined], + ['--admin-domain', flags.adminDomain !== undefined], + ['--no-caddy', flags.noCaddy], + ['--email', flags.email !== undefined], + ['--port', flags.port !== undefined], + ['--version', flags.version !== undefined], + ['--ghost-image', flags.ghostImage !== undefined], + ['--ghost-channel', flags.ghostChannel !== 'stable'], + ['--with', flags.with.length > 0], + ['--import', flags.import !== undefined], + ] as const + ) + .filter(([, set]) => set) + .map(([option]) => option); + return given.length === 0 + ? null + : `--infra sets up the shared Caddy alone, so it takes no ${given.join(', ')}; install each site afterwards, in its own directory`; +} + // --- What to install --------------------------------------------------------- interface Plan { @@ -372,8 +419,12 @@ interface Site extends Target { /** The manager image the launcher is pinned to; none in a checkout. */ readonly pin: string | null; readonly project: string; + /** Its intent's layout, or behind the shared Caddy, `shared-caddy`. */ + readonly layout: Layout; readonly profiles: string; readonly production: boolean; + /** The shared Caddy this production site is installed behind, if the server has one. */ + readonly shared: SharedCaddy | null; readonly url: string; /** This manager's release, and the channel the site follows. */ readonly release: ManagerRelease; @@ -387,6 +438,9 @@ export const installCommand = defineCommand({ const release = requestedRelease(flags.channel, flags.release, '--release'); const context = siteContext(io); const dir = context.siteDir; + if (flags.infra) { + return installInfra(refuseOccupied(io, context, dir), flags, release); + } await clearUnfinishedImport(io, context, dir, flags.import !== undefined); const target = refuseOccupied(io, context, dir); @@ -464,9 +518,17 @@ async function prepare( if (intent.services.includes('supervisor')) { await refuseUnsupportedDaemon(io, context); } + // A production site with Caddy, on a server with the shared Caddy, is + // installed behind it. + const shared = intent.layout === 'production' ? await findSharedCaddy(io) : null; + if (shared !== null) { + runningCaddy(shared); + ok(io, 'shared caddy', `${describeShared(shared)} will serve this site`); + } + const layout: Layout = shared === null ? intent.layout : SHARED_CADDY_PROFILE; const { port, mailpitPort } = await sitePorts( io, - intent.layout, + layout, flags.port, intent.services.includes('mailpit'), ); @@ -488,11 +550,14 @@ async function prepare( // A production name is the domain's, and --name is the operator's: another // directory may already have either. await refuseForeignProject(io, project, dir); + if (shared !== null) { + await refuseTaken(io, shared, project, [intent.domain, intent.adminDomain].filter(Boolean)); + } const production = intent.mode === 'production'; return { ...target, - files: clone ? [] : payloadFiles(target.stack, intent.layout), + files: clone ? [] : payloadFiles(target.stack, layout), flags, intent, port, @@ -500,8 +565,10 @@ async function prepare( ghost, pin, project, - profiles: [intent.layout, ...intent.services].join(','), + layout, + profiles: [layout, ...intent.services].join(','), production, + shared, url: production ? `https://${intent.domain}` : `http://localhost:${port}`, release, }; @@ -542,7 +609,10 @@ async function sitePorts( : null; const wanted = [ port, - ...(layout === 'production' ? [PRODUCTION_PORTS.http, PRODUCTION_PORTS.https] : []), + // Caddy's, for a site with its own, or the shared Caddy itself. + ...(layout === 'production' || layout === INFRA_PROFILE + ? [PRODUCTION_PORTS.http, PRODUCTION_PORTS.https] + : []), ]; const holders = taken.holders(wanted); if (holders.size > 0) { @@ -606,7 +676,7 @@ async function createSite(site: Site, created: Created, importing: Importing | n makeDataDirectories(site, created, importing !== null); await validateConfiguration(site); await importing?.load(created, site.profiles, site.ghost.version); - writeSiteRoutes(site, created); + await writeSiteRoutes(site, created); writeSiteMetadata(site, created); if (site.flags.noStart) { site.io.stdout('\nNot starting: --no-start was given.\n'); @@ -628,7 +698,7 @@ function writeStack(site: Site, created: Created) { ok( io, 'stack files', - `compose.yml, ${site.intent.layout === 'production' ? 'caddy/, mysql-init/, tinybird/' : 'mysql-init/'} from the manager image`, + `compose.yml, ${site.layout === 'production' ? 'caddy/, mysql-init/, tinybird/' : site.layout === SHARED_CADDY_PROFILE ? 'mysql-init/, tinybird/' : 'mysql-init/'} from the manager image`, ); writeLauncher(dir, io.env, { image: pin!, channel: site.release.channel }, created); created.save(); @@ -648,6 +718,7 @@ function writeEnv(site: Site, created: Created) { port: site.port, mailpitPort: site.mailpitPort, ports: { http: String(PRODUCTION_PORTS.http), https: String(PRODUCTION_PORTS.https) }, + ingress: site.shared?.network ?? null, database: { user: 'ghost', password: secret(), rootPassword: secret() }, }); if (intent.services.includes('supervisor')) { @@ -721,25 +792,45 @@ async function validateConfiguration({ io, dir, intent }: Site) { ok(io, 'configuration', `.env and ghost.env are valid for a ${intent.mode} site`); } -/** A production site's Caddy routes. Written once; from here on the file is the operator's. */ -function writeSiteRoutes({ io, dir, project, intent }: Site, created: Created) { - if (intent.layout !== 'production') { +/** + * A production site's Caddy routes, in its own caddy/sites/, or behind the + * shared Caddy in the shared Caddy's, which then validates and reloads them. + * Written once; from here on the file is the operator's. + */ +async function writeSiteRoutes( + { io, dir, layout, project, intent, shared }: Site, + created: Created, +) { + if (layout !== 'production' && layout !== SHARED_CADDY_PROFILE) { return; } const { domain, adminDomain, email, services } = intent; - created.file(join(dir, SITE_FILE)); - writeRoutes(dir, { + const routes = { project, domain, adminDomain, email, activitypub: services.includes('activitypub'), - }); - ok( - io, - SITE_FILE, - `routes for ${[domain, adminDomain].filter(Boolean).join(' and ')}; yours to edit`, - ); + }; + const names = [domain, adminDomain].filter(Boolean).join(' and '); + if (shared !== null) { + // Claimed once written: a file another installation wrote is refused, never removed. + await io.busy('Adding the routes to the shared Caddy', () => + addRoutes(io, shared, project, renderRoutes(routes), (token) => { + created.routes = token ?? false; + created.save(); + }), + ); + ok( + io, + 'routes', + `${routesPath(shared, project)}: routes for ${names}, loaded by the shared Caddy; yours to edit`, + ); + return; + } + created.file(join(dir, SITE_FILE)); + writeRoutes(dir, routes); + ok(io, SITE_FILE, `routes for ${names}; yours to edit`); } function writeSiteMetadata(site: Site, created: Created) { @@ -767,14 +858,14 @@ function writeSiteMetadata(site: Site, created: Created) { ok(io, META_FILE, 'installation metadata'); } -async function startAndVerify({ io, dir, intent }: Site, created: Created) { +async function startAndVerify({ io, dir, layout }: Site, created: Created) { heading(io, 'Starting the services'); created.project = true; await upAndWait( io, dir, 'Pulling images, starting the services and waiting for them to be healthy', - (intent.layout === 'production' + (layout === 'production' ? ' If a port is already in use, choose another for Ghost with --port; a production\n' + ' site needs 80 and 443 free for Caddy.' : ' If a port is already in use, choose another for Ghost with --port.') + @@ -785,6 +876,151 @@ async function startAndVerify({ io, dir, intent }: Site, created: Created) { await verifySite(io, dir); } +// --- The shared Caddy ------------------------------------------------------------ + +/** + * `install --infra`: the shared Caddy, alone, in its own directory and + * project, on a network of its own that each production site installed after + * it joins. Nothing about a site is written, and there is no Ghost to resolve; + * its metadata records the stack files, for self-update. + */ +async function installInfra(target: Target, flags: Flags, requested: Requested): Promise { + const { io, context, dir, clone } = target; + const release = releaseOf(requested, io.env); + const existing = await findSharedCaddy(io); + if (existing !== null) { + throw new CliError( + `this server already has ${describeShared(existing)}, on the network ${existing.network}.\n` + + ' Install each production site in its own directory; it joins that Caddy. If that directory no\n' + + ` longer holds it, remove the network first: docker network rm ${existing.network}. Nothing has been changed.`, + ); + } + await preflight(io, context); + await sitePorts(io, INFRA_PROFILE, undefined, false); + const pin = clone + ? null + : await io.busy('Resolving the manager image', () => managerPin(io, context)); + const project = flags.name ?? INFRA_PROJECT; + await refuseForeignProject(io, project, dir); + + const created = new Created(io, context, dir); + try { + heading(io, 'Writing the shared Caddy'); + if (!clone) { + const files = payloadFiles(target.stack, INFRA_PROFILE); + writePayload(dir, target.stack, files, created); + ok(io, 'stack files', 'compose.yml and caddy/ from the manager image'); + writeLauncher(dir, io.env, { image: pin!, channel: release.channel }, created); + ok(io, 'ghost-docker', `the launcher, pinned to ${pin!}`); + } + // Where the members' routes go; Caddy mounts caddy/ whole. + makeDirectories(join(dir, 'caddy', 'sites'), created.directories); + const path = join(dir, ENV_FILE); + created.file(path); + atomicWrite( + path, + env.serializeAll( + Object.entries({ + COMPOSE_PROFILES: INFRA_PROFILE, + SITE_MODE: INFRA_PROFILE, + COMPOSE_PROJECT_NAME: project, + PROJECT_DIR: dir, + RESTART_POLICY: 'unless-stopped', + HTTP_PORT: String(PRODUCTION_PORTS.http), + HTTPS_PORT: String(PRODUCTION_PORTS.https), + ...ingressSettings(INGRESS_NETWORK), + }), + '# The shared Caddy: Caddy alone, serving the production sites on this server.\n' + + '# Their routes are in caddy/sites/, one file each; see docs/caddy.md.\n', + ), + PRIVATE, + ); + ok(io, ENV_FILE, 'the shared Caddy\u2019s settings'); + // No project owns it, so taking the shared Caddy down leaves its members attached. + await createNetwork(io.docker, INGRESS_NETWORK, { + [MANAGED_LABEL.split('=')[0]!]: 'true', + [INFRA_DIR_LABEL]: dir, + [INFRA_PROJECT_LABEL]: project, + }); + // Only now: one another installation created meanwhile is not this one's to remove. + created.network = INGRESS_NETWORK; + ok(io, 'network', `${INGRESS_NETWORK}, which the services of each site behind it join`); + created.file(join(dir, META_FILE)); + writeMetadata( + dir, + infraMetadata({ + channel: clone ? null : release.channel, + source: clone ? 'checkout' : 'image', + stack: { version: release.version, image: pin }, + project, + dir, + payload: created.checksums, + }), + ); + ok(io, META_FILE, 'installation metadata, which self-update keeps current'); + const findings = await io.busy('Validating the configuration', () => validate(io, dir)); + const errors = findingErrors(findings); + if (errors) { + throw new CliError( + `the generated configuration did not validate; please report this:\n${errors}`, + ); + } + if (flags.noStart) { + io.stdout('\nNot starting: --no-start was given.\n'); + } else { + heading(io, 'Starting the shared Caddy'); + created.project = true; + await upAndWait( + io, + dir, + 'Pulling Caddy, starting it and waiting for it to be healthy', + ' The shared Caddy needs ports 80 and 443 free. Nothing that was already running was stopped.', + ); + const caddy = (await composePs(io, dir))?.find((state) => state.Service === 'caddy'); + if (caddy?.Health !== 'healthy') { + throw new CliError('Caddy started, but it is not healthy'); + } + ok(io, 'caddy', 'healthy: its admin API answers, with its configuration loaded'); + } + } catch (error) { + io.stderr( + `\n${describeError(error)}\n\nThe installation did not complete. Removing what it created\n`, + ); + const leftovers = await io.busy('Removing what the installation created', () => + created.remove(), + ); + io.stderr( + leftovers.length > 0 + ? `Some of it could not be removed:\n${leftovers.map((item) => ` ${item}\n`).join('')}` + : `${dir} is as it was before. Nothing that was already running was stopped.\n`, + ); + throw new CliError( + 'installation failed; fix the error above and run the same command again.', + ); + } + io.stdout( + [ + '', + 'The shared Caddy is installed.', + '', + ` Project ${project} (${INFRA_PROFILE}), in ${dir}`, + ` Network ${INGRESS_NETWORK}`, + '', + flags.noStart + ? 'Nothing is running. Start it with: docker compose up -d' + : 'It serves no site yet. Install each production site in a directory of its own with', + ...(flags.noStart + ? [] + : [ + './ghost-docker install --domain example.com: it joins this Caddy, and its routes', + 'are written to caddy/sites/ here.', + ]), + '', + ].join('\n'), + ); + return EXIT.ok; +} + // --- The outcome ---------------------------------------------------------------- /** @@ -881,6 +1117,11 @@ function printSummary(site: Site, importing: Importing | null) { ` Ghost Admin ${admin}/ghost/`, ` Project ${site.project} (${site.profiles}), in ${site.dir}`, ` Ghost ${ghost.version}, ${ghost.reference}`, + ...(site.shared === null + ? [] + : [ + ` Routes ${routesPath(site.shared, site.project)}, served by the shared Caddy`, + ]), ...(ghostChannelOf(ghost.image) === 'nightly' ? [ ` Channel nightly: a build of Ghost's main branch, for testing, ${production ? 'which this production site should not run' : 'never for production'}`, diff --git a/manager/src/commands/remove.ts b/manager/src/commands/remove.ts new file mode 100644 index 00000000..e5e67b0d --- /dev/null +++ b/manager/src/commands/remove.ts @@ -0,0 +1,111 @@ +// `remove`: a site taken down, and behind the shared Caddy, its routes taken +// out of it, so every other site behind it is left as it was. The site's +// directory, data and backups stay, for the operator to keep or delete. +import { z } from 'zod'; +import { defineCommand, flag } from '../command.ts'; +import { ALL_PROFILES, composeDown, composeError } from '../compose.ts'; +import { CliError, EXIT, UsageError } from '../errors.ts'; +import type { Io } from '../io.ts'; +import { acquireLock } from '../lock.ts'; +import { refuseForeignProject } from '../project.ts'; +import { ok } from '../report.ts'; +import { + describeShared, + findSharedCaddy, + INGRESS_NETWORK, + removeRoutes, + routesPath, + runningCaddy, +} from '../shared.ts'; +import { SHARED_CADDY_PROFILE } from '../site.ts'; +import { installedSite } from './common.ts'; + +export const removeCommand = defineCommand({ + brief: 'Take the site down, and behind the shared Caddy, remove its routes from it. Its directory and data stay. See docs/install.md.', + options: z.object({ + yes: flag('Remove the site without asking first.'), + }), + async run(flags, _positionals, io) { + const { site } = installedSite(io); + const dir = site.dir; + const project = site.settings.get('COMPOSE_PROJECT_NAME') || ''; + await refuseForeignProject(io, project, dir); + const shared = site.layout === SHARED_CADDY_PROFILE ? await findSharedCaddy(io) : null; + if (site.layout === SHARED_CADDY_PROFILE && shared === null) { + // Its routes may still be in the shared Caddy's directory, which only + // the running shared Caddy lets the manager change. + throw new CliError( + `this site is behind the shared Caddy, and this server has none (no ${INGRESS_NETWORK} network),\n` + + ' so its routes cannot be removed. Start the shared Caddy and run this again, or take the\n' + + ' site down alone with docker compose down and remove its routes file by hand.\n' + + ' Nothing has been changed.', + ); + } + if (shared !== null) { + runningCaddy(shared); + } + await confirm(io, dir, project, flags.yes); + + const lock = acquireLock(dir, 'remove'); + try { + if (shared !== null) { + await io.busy('Removing the routes from the shared Caddy', () => + removeRoutes(io, shared, project), + ); + ok( + io, + 'routes', + `${routesPath(shared, project)} removed; ${describeShared(shared)} reloaded without them`, + ); + } + const down = await io.busy("Stopping and removing the site's containers", () => + composeDown(io, dir, { profiles: ALL_PROFILES }), + ); + if (down.exitCode !== 0) { + throw new CliError( + `docker compose down failed: ${composeError(down, 4)}\n` + + (shared === null + ? '' + : ` Its routes are already gone from ${describeShared(shared)}, so the site is not\n` + + ' served until this finishes.\n') + + ' Run it again in this directory once the cause is fixed.', + ); + } + ok(io, 'services', `the containers and networks of ${project} are removed`); + } finally { + lock.release(); + } + io.stdout( + `\nThe site is removed. ${dir} still holds its configuration, data and backups:\n` + + 'docker compose up -d starts it again' + + (shared === null + ? '' + : `, once its routes are back in ${routesPath(shared, project)}`) + + '.\nTo delete it for good, remove the directory (with sudo: MySQL owns data/mysql).\n', + ); + return EXIT.ok; + }, +}); + +/** Taking a site down is never a surprise: it is asked, or --yes says so. */ +async function confirm(io: Io, dir: string, project: string, yes: boolean) { + if (yes) { + return; + } + if (io.prompt === null) { + throw new UsageError( + `remove takes down the site in ${dir} (${project}).\n` + + ' Run it again with --yes to go ahead. Nothing has been changed.', + ); + } + const answer = await io.prompt.choose( + `Take down ${project} and remove its containers? Its directory and data stay.`, + [ + { name: 'No, change nothing', value: 'no' }, + { name: 'Yes, remove the site', value: 'yes' }, + ], + ); + if (answer !== 'yes') { + throw new CliError('the removal was cancelled. Nothing has been changed.'); + } +} diff --git a/manager/src/commands/self-update.ts b/manager/src/commands/self-update.ts index a7717a4d..398775da 100644 --- a/manager/src/commands/self-update.ts +++ b/manager/src/commands/self-update.ts @@ -12,11 +12,14 @@ 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 { RELOAD } from '../shared.ts'; import { atomicWrite } from '../fs.ts'; import type { Io } from '../io.ts'; import { isReleasedMainLayout, migrateReleasedMain } from '../legacy.ts'; @@ -26,6 +29,7 @@ import { requireMetadata, siteFiles, writeMetadata, + type AnyMetadata, type Metadata, } from '../meta.ts'; import { @@ -37,12 +41,21 @@ import { sha256, stackDir, } from '../payload.ts'; -import { describeServices } from '../recovery.ts'; +import { describeServices, Snapshot } from '../recovery.ts'; import { compareReleases, isRelease } from '../release.ts'; import { resolveSite } from '../resolved.ts'; import { heading, note, ok } from '../report.ts'; import * as env from '../env.ts'; -import { COMPOSE_FILE, ENV_FILE, META_FILE, type Layout, type SiteFacts } from '../site.ts'; +import { + COMPOSE_FILE, + ENV_FILE, + INFRA_PROFILE, + isInfra, + META_FILE, + UPDATE_DIR, + type Layout, + type SiteFacts, +} from '../site.ts'; import { reportNeedsOperator, reportRestored, @@ -60,6 +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,220 @@ export const selfUpdateCommand = defineCommand({ }, }); +/** A checkout is updated with git; a site from the image only by its own launcher's manager. */ +function refuseCheckouts(source: AnyMetadata['source'], running: Context['source']): void { + if (source === 'checkout') { + throw new CliError( + 'this site is a checkout of the repository, and self-update updates only a site installed\n' + + ' from the manager image. Update a checkout with git and Compose, in the site directory:\n' + + ' ./ghost-docker backup\n' + + ' git fetch --tags && git checkout \n' + + ' ./ghost-docker config validate\n' + + ' docker compose pull --ignore-buildable\n' + + ' docker compose up -d --wait\n' + + ' ./ghost-docker check\n' + + ' If the site does not come back, check out the commit it ran and restore the backup.\n' + + ' Nothing has been changed.', + ); + } + if (running === 'checkout') { + throw new CliError( + 'this site was installed from the manager image, and this manager was built from a checkout.\n' + + ' Run the site’s own ./ghost-docker self-update. Nothing has been changed.', + ); + } +} + +// --- The shared Caddy ------------------------------------------------------------- + +/** + * The shared Caddy's directory (shared.ts): its stack files and launcher, then + * Caddy recreated on the release's image. It holds no data, only Caddy's + * certificates in a volume `up` keeps, so there is no backup, and a failure + * puts the files back and starts the previous Caddy again: nothing it ran on + * the new files can have changed anything the old ones depend on. Every site + * behind it is unreachable while Caddy restarts, and updates on its own. + */ +async function updateInfra( + io: Io, + context: Context, + site: SiteFacts, + requested: Requested, + check: boolean, +): Promise { + const dir = site.dir; + const read = readMetadata(dir); + if (read.state !== 'present' || read.metadata.mode !== INFRA_PROFILE) { + throw new CliError( + read.state === 'invalid' + ? `${read.reason}. Nothing has been changed.` + : `${dir} holds the shared Caddy, but has no ${META_FILE} recording its files, so self-update\n` + + ' cannot tell them from yours. Nothing has been changed.', + ); + } + const metadata = read.metadata; + refuseCheckouts(metadata.source, context.source); + + const release = releaseOf(requested, io.env); + const from: Stack = { version: metadata.stack.version, image: metadata.stack.image }; + const image = await io.busy('Resolving the manager image', () => managerPin(io, context)); + const to: Stack = { version: release.version, image }; + const decided = compare(from, to); + if (typeof decided === 'object') { + throw new CliError(`${decided.unordered}. Nothing has been changed.`); + } + const stack = stackDir(io.env); + const payload = planPayload(dir, stack, INFRA_PROFILE, metadata.payload); + if (check) { + io.stdout( + `The shared Caddy runs ${describeStack(from)}. This release is ${describeStack(to)}.\n`, + ); + if (decided === 'newer') { + io.stdout('An update is available. Caddy restarts with it.\n'); + describeChanges(io, payload, to); + } else { + io.stdout( + decided === 'current' + ? 'It is up to date.\n' + : 'That is older, and update would refuse it.\n', + ); + } + return EXIT.ok; + } + if (decided === 'current') { + io.stdout(`The shared Caddy already runs ${describeStack(to)}. Nothing to update.\n`); + return EXIT.ok; + } + if (decided === 'downgrade') { + throw new CliError( + `the shared Caddy runs ${describeStack(from)}, which is newer than ${describeStack(to)}. An update\n` + + ' never moves to an older release. Nothing has been changed.', + ); + } + refuseUnfinished(dir, 'self-update'); + // 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: a site's install or remove reloads the + // shared Caddy from this directory's files at any moment, so a written + // file is live from then on, and a failure after it needs a reload. + heading(io, 'Pulling the release’s images'); + const pull = await io.busy( + 'Pulling the images this release names', + () => + compose(io, { + dir, + composeFile: join(stack, COMPOSE_FILE), + timeout: PULL_MS, + })`pull --quiet --ignore-buildable`, + ); + if (pull.exitCode !== 0) { + throw new CliError( + `the images could not be pulled: ${composeError(pull)}. Nothing has been changed.`, + ); + } + ok(io, 'images', 'pulled, while Caddy kept running'); + heading(io, 'Keeping the current files'); + // Not the sites' routes: the update never writes them, and a site + // installed meanwhile adds its own, which putting files back would lose. + const snapshot = new Snapshot( + dir, + touched(metadata, payload).filter((path) => path !== join('caddy', 'sites')), + ); + snapshot.take(); + ok(io, UPDATE_DIR, 'the configuration, the metadata and the files this update writes'); + let started = false; + try { + heading(io, 'Writing the stack'); + writePayloadChanges(io, dir, stack, payload); + await requireValid(io, dir, 'this release'); + 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.' : ''), + ); + } + try { + if (started) { + await caddyUp(io, dir, `Starting ${describeStack(from)}'s Caddy again`); + } else { + // Never restarted, but a site's reload may have loaded the + // written files: load the ones put back. + await reloadCaddy(io, dir); + } + } catch (again) { + throw new CliError( + `the files are ${describeStack(from)}'s again, but Caddy did not ${started ? 'start on' : 'load'} them: ${describeError(again)}\n` + + ' Sites behind it may be unreachable, or served by the release that failed, until it\n' + + ` does: docker compose up -d, then docker compose exec caddy ${RELOAD.join(' ')},\n` + + ` and docker compose logs caddy, in ${dir}. The files as they were are in ${UPDATE_DIR}/files;\n` + + ` remove ${UPDATE_DIR} once Caddy runs on them.`, + ); + } + snapshot.remove(); + throw new CliError( + `the update failed; the shared Caddy is back on ${describeStack(from)}${started ? ', and running' : ', with its configuration loaded again'}.`, + ); + } + snapshot.remove(); + } finally { + lock.release(); + } + io.stdout( + `\nUpdated the shared Caddy from ${describeStack(from)} to ${describeStack(to)}.\n` + + 'Each site behind it keeps its own release; update each with its own ./ghost-docker self-update.\n', + ); + return EXIT.ok; +} + +/** `up --wait`, and Caddy healthy by its own check. */ +async function caddyUp(io: Io, dir: string, spinner: string): Promise { + await upAndWait(io, dir, spinner); + // `up` recreates Caddy only when its service changed; a Caddyfile or + // snippet it mounts is loaded only by a reload. + await reloadCaddy(io, dir); + const caddy = (await composePs(io, dir))?.find((state) => state.Service === 'caddy'); + if (caddy?.Health !== 'healthy') { + throw new CliError('Caddy started, but it is not healthy'); + } + ok(io, 'caddy', 'healthy: its admin API answers, with its configuration loaded'); +} + +/** The running Caddy's configuration loaded from the directory's files. */ +async function reloadCaddy(io: Io, dir: string): Promise { + const reload = await io.busy( + 'Loading the configuration', + // One at a time with the sites' route changes (shared.ts RELOAD). + () => compose(io, { dir })`exec -T caddy ${[...RELOAD]}`, + ); + 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 +604,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 +625,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 +699,19 @@ async function apply(update: Update, backup: boolean): Promise { /** The launcher pinned to this image, then the metadata. */ function record({ io, site, metadata, from, to, release, payload }: Update): void { - const dir = site.dir; + recordStack(io, site.dir, metadata, from, to, release, payload); +} + +/** What `record` writes for any metadata: the launcher pinned, then the stack recorded. */ +function recordStack( + io: Io, + dir: string, + metadata: AnyMetadata, + from: Stack, + to: Stack, + release: ManagerRelease, + payload: Payload, +): void { const checksums = { ...payload.checksums }; const launcher = join(dir, LAUNCHER); const present = checksumOf(launcher); diff --git a/manager/src/commands/site.ts b/manager/src/commands/site.ts index 746f8499..2f3a7b60 100644 --- a/manager/src/commands/site.ts +++ b/manager/src/commands/site.ts @@ -14,7 +14,14 @@ import { describeMetadata, readMetadata } from '../meta.ts'; import { foreignProject, PROJECT_LABEL } from '../project.ts'; import { failed, printChecks, type Check } from '../report.ts'; import { imageDrift, observeSite, resolveSite, type ResolvedSite } from '../resolved.ts'; -import { hasProfile, readSettings, RESTORE_DIR } from '../site.ts'; +import { INGRESS_NETWORK } from '../shared.ts'; +import { + hasProfile, + INFRA_PROFILE, + SHARED_CADDY_PROFILE, + readSettings, + RESTORE_DIR, +} from '../site.ts'; import { verifyIngress } from '../verify.ts'; import { installedSite } from './common.ts'; import { collect } from './doctor.ts'; @@ -310,12 +317,22 @@ export const listCommand = defineCommand({ io.stderr('error: docker compose ls failed\n'); return EXIT.failure; } - const modes = new Map( - containers.map((container) => [ - container.labels[PROJECT_LABEL] ?? '', - container.labels['org.ghost.docker.mode'] ?? '', - ]), - ); + // The shared Caddy's mode is infra; a production site any of whose + // containers is on its network is behind it. + const modes = new Map(); + for (const container of containers) { + const project = container.labels[PROJECT_LABEL] ?? ''; + const mode = container.labels['org.ghost.docker.mode'] ?? ''; + modes.set( + project, + mode === INFRA_PROFILE + ? INFRA_PROFILE + : modes.get(project) === SHARED_CADDY_PROFILE || + (mode === 'production' && container.networks.includes(INGRESS_NETWORK)) + ? SHARED_CADDY_PROFILE + : mode, + ); + } const sites = projects .filter((project) => modes.has(project.name)) .sort((a, b) => a.name.localeCompare(b.name)); @@ -323,11 +340,17 @@ export const listCommand = defineCommand({ io.stdout('No ghost-docker site has containers on this host.\n'); } else { const row = (...cells: string[]) => - `${cells[0]!.padEnd(28)} ${cells[1]!.padEnd(11)} ${cells[2]!.padEnd(20)} ${cells[3]}\n`; + `${cells[0]!.padEnd(28)} ${cells[1]!.padEnd(12)} ${cells[2]!.padEnd(20)} ${cells[3]}\n`; io.stdout(row('SITE', 'MODE', 'STATUS', 'DIRECTORY')); for (const site of sites) { io.stdout(row(site.name, modes.get(site.name)!, site.status, site.dir)); } + if ([...modes.values()].includes(SHARED_CADDY_PROFILE)) { + io.stdout( + `\n${SHARED_CADDY_PROFILE} is a production site behind the shared Caddy (${INFRA_PROFILE}), which serves\n` + + "its routes from a file named for it in the shared Caddy's caddy/sites/.\n", + ); + } } io.stdout( '\nOnly sites whose containers exist are listed, stopped ones included. There is no\n' + diff --git a/manager/src/config.ts b/manager/src/config.ts index 81e2bfa4..d2df7432 100644 --- a/manager/src/config.ts +++ b/manager/src/config.ts @@ -10,14 +10,18 @@ import { CliError } from './errors.ts'; import { modeOf, readIfExists } from './fs.ts'; import type { Io } from './io.ts'; import { ok, type Check } from './report.ts'; +import { INGRESS_NETWORK } from './shared.ts'; import { COMPOSE_OVERRIDE_FILE, ENV_EXAMPLE_FILE, ENV_FILE, GHOST_ENV_FILE, + hasProfile, hostOf, + INFRA_PROFILE, layoutOf, MODE_PROFILE_NAMES, + SHARED_CADDY_PROFILE, OPTIONAL_PROFILES, profileConflict, siteMode, @@ -33,14 +37,11 @@ export interface Finding { /** Keys required in `.env` that nothing else would catch, by mode. */ export const REQUIRED_KEYS = { - common: [ - 'COMPOSE_PROFILES', - 'COMPOSE_PROJECT_NAME', - 'SITE_MODE', - 'PROJECT_DIR', - 'GHOST_VERSION', - ], - production: ['URL'], + common: ['COMPOSE_PROFILES', 'COMPOSE_PROJECT_NAME', 'SITE_MODE', 'PROJECT_DIR'], + /** compose.yml does not `:?`-guard these: the shared Caddy's directory has none. */ + site: ['GHOST_VERSION', 'URL', 'DATABASE_PASSWORD', 'DATABASE_ROOT_PASSWORD'], + /** Behind the shared Caddy, and in its own directory. */ + shared: ['INGRESS_NETWORK'], } 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,11 @@ export async function validateEnv(io: Io, dir: string): Promise { ); } + const behindSharedCaddy = hasProfile(profiles, SHARED_CADDY_PROFILE); const required = [ ...REQUIRED_KEYS.common, - ...(mode === 'production' ? REQUIRED_KEYS.production : []), + ...REQUIRED_KEYS.site, + ...(behindSharedCaddy ? REQUIRED_KEYS.shared : []), ]; for (const key of required) { if (values[key] === undefined) { @@ -159,6 +169,10 @@ export async function validateEnv(io: Io, dir: string): Promise { } } + if (behindSharedCaddy) { + findings.push(...externalIngress(file, values)); + } + // The extra databases are created once, on first initialisation. A custom // ActivityPub database name that is not in that list never exists. const activitypubDatabase = values.ACTIVITYPUB_DATABASE_NAME; @@ -217,6 +231,62 @@ export async function validateEnv(io: Io, dir: string): Promise { return findings; } +/** + * The shared Caddy's directory: Caddy alone, so `infra` and nothing else, + * on the network the manager created for it. + */ +function validateInfra(file: string, values: Record): Finding[] { + const findings: Finding[] = []; + const profiles = splitProfiles(values.COMPOSE_PROFILES ?? ''); + if (profiles.length !== 1) { + findings.push( + error( + file, + `COMPOSE_PROFILES=${values.COMPOSE_PROFILES} selects the shared Caddy (${INFRA_PROFILE}), which runs Caddy alone: remove ${profiles.filter((profile) => profile !== INFRA_PROFILE).join(', ')}`, + ), + ); + } + if (values.SITE_MODE && values.SITE_MODE !== INFRA_PROFILE) { + findings.push( + error( + file, + `SITE_MODE=${values.SITE_MODE} does not match COMPOSE_PROFILES (${INFRA_PROFILE})`, + ), + ); + } + for (const key of [...REQUIRED_KEYS.common, ...REQUIRED_KEYS.shared]) { + if (values[key] === undefined) { + findings.push(error(file, `${key} is required for the shared Caddy`)); + } else if (values[key] === '') { + findings.push(error(file, `${key} is empty`)); + } + } + return [...findings, ...externalIngress(file, values)]; +} + +/** + * The shared Caddy's network is the manager's, so Compose must not create or + * remove it; and it is the one the manager finds the shared Caddy by. + */ +const externalIngress = (file: string, values: Record): Finding[] => [ + ...(values.INGRESS_NETWORK && values.INGRESS_NETWORK !== INGRESS_NETWORK + ? [ + error( + file, + `INGRESS_NETWORK must be ${INGRESS_NETWORK}, the shared Caddy's network: got ${values.INGRESS_NETWORK}`, + ), + ] + : []), + ...(values.INGRESS_EXTERNAL === 'true' + ? [] + : [ + error( + file, + `INGRESS_EXTERNAL must be true: ${values.INGRESS_NETWORK || 'the network'} is the shared Caddy's, which no Compose project creates or removes`, + ), + ]), +]; + /** * `ghost.env` holds Ghost application settings only. Two mistakes matter, and * both are detected rather than listed: diff --git a/manager/src/docker/client.ts b/manager/src/docker/client.ts index 0d5c1076..9ea969b5 100644 --- a/manager/src/docker/client.ts +++ b/manager/src/docker/client.ts @@ -8,6 +8,7 @@ import { DaemonTimeout, DaemonUnreachable, type DockerRequest, + type DockerResponse, type DockerTransport, } from './transport.ts'; @@ -217,6 +218,12 @@ const containerSummary = z.object({ Image: z.string().default(''), ImageID: z.string().default(''), Labels: z.record(z.string(), z.string()).nullable().default({}), + NetworkSettings: z + .looseObject({ + Networks: z.record(z.string(), z.unknown()).nullable().default({}), + }) + .nullable() + .default({ Networks: {} }), Ports: z .array( z.object({ @@ -244,6 +251,8 @@ export interface ContainerFacts { readonly labels: Readonly>; /** Host ports the container publishes. */ readonly publishedPorts: readonly number[]; + /** The names of the networks it is attached to. */ + readonly networks: readonly string[]; } /** `docker ps`, or with `all` `docker ps -a`, optionally filtered by label. */ @@ -275,6 +284,7 @@ export async function listContainers( ), ), ], + networks: Object.keys(container.NetworkSettings?.Networks ?? {}), })); } @@ -446,6 +456,74 @@ export async function disconnectNetwork( } } +const networkInspect = z.object({ + Id: z.string(), + Name: z.string(), + Labels: z.record(z.string(), z.string()).nullable().default({}), +}); + +export interface NetworkFacts { + readonly id: string; + readonly name: string; + readonly labels: Readonly>; +} + +/** `docker network inspect`, or null when the daemon has no network by that name. */ +export async function inspectNetwork( + docker: DockerTransport, + name: string, +): Promise { + try { + const network = await call( + docker, + { method: 'GET', path: `/networks/${encodeURIComponent(name)}` }, + networkInspect, + ); + // The daemon also matches an ID or its prefix; only the name counts. + return network.Name === name + ? { id: network.Id, name: network.Name, labels: network.Labels ?? {} } + : null; + } catch (error) { + if (error instanceof DaemonError && error.status === 404) { + return null; + } + throw error; + } +} + +/** `docker network create --label ...`: a bridge network. Returns its ID. */ +export async function createNetwork( + docker: DockerTransport, + name: string, + labels: Readonly>, +): Promise { + const network = await call( + docker, + { + method: 'POST', + path: '/networks/create', + body: { Name: name, Driver: 'bridge', Labels: labels, CheckDuplicate: true }, + }, + created, + ); + return network.Id; +} + +/** `docker network rm`. A network that is already gone is not an error. */ +export async function removeNetwork(docker: DockerTransport, name: string): Promise { + try { + await call( + docker, + { method: 'DELETE', path: `/networks/${encodeURIComponent(name)}` }, + z.unknown(), + ); + } catch (error) { + if (!(error instanceof DaemonError && error.status === 404)) { + throw error; + } + } +} + // --- One-shot containers ---------------------------------------------------- export interface Bind { @@ -564,6 +642,73 @@ export async function runOnce(docker: DockerTransport, spec: RunSpec): Promise { + let id: string; + try { + id = ( + await call( + docker, + { + method: 'POST', + path: `/containers/${encodeURIComponent(container)}/exec`, + body: { + Cmd: [...cmd], + AttachStdout: true, + AttachStderr: true, + Tty: false, + ...(user ? { User: user } : {}), + }, + }, + created, + ) + ).Id; + } catch (error) { + if (error instanceof DaemonError) { + return { status: null, stdout: '', stderr: error.message, timedOut: false }; + } + throw error; + } + let output: DockerResponse; + try { + output = await docker({ + method: 'POST', + path: `/exec/${id}/start`, + body: { Detach: false, Tty: false }, + timeoutMs, + }); + } catch (error) { + if (error instanceof DaemonTimeout) { + return { status: null, stdout: '', stderr: '', timedOut: true }; + } + throw error; + } + if (output.status >= 400) { + return { status: null, stdout: '', stderr: output.body.toString('utf8'), timedOut: false }; + } + const { stdout, stderr } = demultiplex(output.body); + const state = await call(docker, { method: 'GET', path: `/exec/${id}/json` }, execInspect); + return { status: state.Running ? null : state.ExitCode, stdout, stderr, timedOut: false }; +} + /** * The log stream of a container without a TTY: frames of an 8-byte header * (stream type, three zero bytes, big-endian payload length) and a payload. diff --git a/manager/src/legacy.ts b/manager/src/legacy.ts index b6ca6779..8b137d2b 100644 --- a/manager/src/legacy.ts +++ b/manager/src/legacy.ts @@ -316,6 +316,7 @@ async function prepare( port, mailpitPort: null, ports: { http: old.HTTP_PORT || '80', https: old.HTTPS_PORT || '443' }, + ingress: null, database: { user: old.DATABASE_USER || 'ghost', password: old.DATABASE_PASSWORD!, diff --git a/manager/src/meta.ts b/manager/src/meta.ts index 05fa4106..64979fdf 100644 --- a/manager/src/meta.ts +++ b/manager/src/meta.ts @@ -3,7 +3,7 @@ import { join } from 'node:path'; import { z } from 'zod'; import { atomicWrite, PRIVATE, readIfExists } from './fs.ts'; -import { META_FILE, OPERATOR_FILES, SITE_MODES } from './site.ts'; +import { INFRA_PROFILE, META_FILE, OPERATOR_FILES, SITE_MODES } from './site.ts'; import { CliError } from './errors.ts'; export const SCHEMA_VERSION = 1; @@ -11,12 +11,12 @@ export const SCHEMA_VERSION = 1; /** A field nobody supplied is null, so "not known" and "empty" stay distinct. */ const nullable = z.string().min(1).nullable(); -export const metadataSchema = z.strictObject({ +/** What a site's and the shared Caddy's metadata have alike. */ +const common = { schemaVersion: z.literal(SCHEMA_VERSION), installedAt: z.iso.datetime(), /** When `self-update` last completed; null until it has. */ updatedAt: z.iso.datetime().nullable(), - mode: z.enum(SITE_MODES), channel: z.enum(['stable', 'beta', 'edge']).nullable(), // `image`: the payload was written from the manager image. `checkout`: the // site is a clone of the repository and its files are used in place. @@ -32,6 +32,18 @@ export const metadataSchema = z.strictObject({ */ previous: z.strictObject({ version: nullable, image: nullable }).nullable(), }), + profiles: z.array(z.string().min(1)), + /** + * SHA-256 of every file the manager wrote from the image's payload, by + * path relative to the site. An update replaces an untouched file and + * never silently replaces an edited one (docs/architecture.md#releases-and-compatibility). Empty in clone mode. + */ + payload: z.record(z.string(), z.string().regex(/^[0-9a-f]{64}$/)), +}; + +export const metadataSchema = z.strictObject({ + ...common, + mode: z.enum(SITE_MODES), site: z.strictObject({ project: z.string().min(1), dir: z.string().startsWith('/'), @@ -45,16 +57,33 @@ export const metadataSchema = z.strictObject({ version: z.string().min(1), digest: z.string().regex(/^sha256:[0-9a-f]{64}$/), }), - profiles: z.array(z.string().min(1)), - /** - * SHA-256 of every file the manager wrote from the image's payload, by - * path relative to the site. An update replaces an untouched file and - * never silently replaces an edited one (docs/architecture.md#releases-and-compatibility). Empty in clone mode. - */ - payload: z.record(z.string(), z.string().regex(/^[0-9a-f]{64}$/)), }); +/** + * The shared Caddy's directory (shared.ts): the stack files and launcher + * `self-update` keeps current, and no site or Ghost. + */ +export const infraMetadataSchema = z.strictObject({ + ...common, + mode: z.literal(INFRA_PROFILE), + site: z.strictObject({ + project: z.string().min(1), + dir: z.string().startsWith('/'), + }), + ghost: z.null(), +}); + +/** A site's metadata: what every command about a site works from. */ export type Metadata = z.infer; +export type InfraMetadata = z.infer; +/** Whatever `.ghost-docker.json` holds. */ +export type AnyMetadata = Metadata | InfraMetadata; + +/** The schema a document's `mode` selects, so a mismatch names its fields. */ +const schemaOf = (document: unknown) => + (document as { mode?: unknown } | null)?.mode === INFRA_PROFILE + ? infraMetadataSchema + : metadataSchema; /** A moment as metadata, locks and backups record it: ISO 8601 to the second. */ export const isoSeconds = (date = new Date()): string => @@ -66,6 +95,11 @@ export const isoSeconds = (date = new Date()): string => */ export function requireMetadata(dir: string, why: string): Metadata { const read = readMetadata(dir); + if (read.state === 'present' && read.metadata.mode === INFRA_PROFILE) { + throw new CliError( + `${dir} holds the shared Caddy, not a site, and ${why}. Nothing has been changed.`, + ); + } if (read.state === 'absent') { throw new CliError( `${dir} has no ${META_FILE}, so it was not installed by ./ghost-docker install, and ${why}.\n` + @@ -75,7 +109,7 @@ export function requireMetadata(dir: string, why: string): Metadata { if (read.state === 'invalid') { throw new CliError(`${read.reason}. Nothing has been changed.`); } - return read.metadata; + return read.metadata as Metadata; } /** @@ -86,7 +120,7 @@ export function requireMetadata(dir: string, why: string): Metadata { * images this one did. */ export const siteFiles = ( - metadata: Metadata | null, + metadata: Pick | null, overrides: readonly string[] = [], ): string[] => [ ...new Set([ @@ -98,7 +132,7 @@ export const siteFiles = ( export type MetadataRead = | { state: 'absent' } - | { state: 'present'; metadata: Metadata } + | { state: 'present'; metadata: AnyMetadata } | { state: 'invalid'; reason: string }; export const metaPath = (dir: string): string => join(dir, META_FILE); @@ -128,7 +162,7 @@ export function readMetadata(dir: string): MetadataRead { : ''), }; } - const parsed = metadataSchema.safeParse(document); + const parsed = schemaOf(document).safeParse(document); if (!parsed.success) { const where = parsed.error.issues.map((issue) => issue.path.join('.') || '(root)'); return { @@ -167,13 +201,42 @@ export function installationMetadata( }; } +/** The shared Caddy's metadata as `install --infra` first writes it. */ +export function infraMetadata(input: { + readonly channel: InfraMetadata['channel']; + readonly source: InfraMetadata['source']; + readonly stack: { readonly version: string | null; readonly image: string | null }; + readonly project: string; + readonly dir: string; + readonly payload: Record; +}): InfraMetadata { + return { + schemaVersion: SCHEMA_VERSION, + installedAt: isoSeconds(), + updatedAt: null, + mode: INFRA_PROFILE, + channel: input.channel, + source: input.source, + stack: { + version: input.stack.version, + ref: input.source === 'checkout' ? null : input.stack.version, + image: input.stack.image, + previous: null, + }, + site: { project: input.project, dir: input.dir }, + ghost: null, + profiles: [INFRA_PROFILE], + payload: input.payload, + }; +} + /** * Validated before it is written, so a bad document never replaces a good * one. Two writes of the same document are the same bytes: the parse orders * the objects' keys as the schema does, and `payload`, a record, is sorted. */ -export function writeMetadata(dir: string, metadata: Metadata): void { - const valid = metadataSchema.parse(metadata); +export function writeMetadata(dir: string, metadata: AnyMetadata): void { + const valid = schemaOf(metadata).parse(metadata); valid.payload = Object.fromEntries( Object.entries(valid.payload).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)), ); @@ -203,10 +266,14 @@ export function describeMetadata(read: MetadataRead): string[] { ...(m.stack.previous ? [`previous ${unknown(m.stack.previous.version)}`] : []), `project ${m.site.project}`, `directory ${m.site.dir}`, - `url ${m.site.url}`, - ...(m.site.adminDomain ? [`admin domain ${m.site.adminDomain}`] : []), - `ghost ${m.ghost.version} (${m.ghost.image}:${m.ghost.tag})`, - `ghost image ${m.ghost.image}@${m.ghost.digest}`, + ...(m.mode === INFRA_PROFILE + ? ['the shared Caddy: no site, and no Ghost'] + : [ + `url ${m.site.url}`, + ...(m.site.adminDomain ? [`admin domain ${m.site.adminDomain}`] : []), + `ghost ${m.ghost.version} (${m.ghost.image}:${m.ghost.tag})`, + `ghost image ${m.ghost.image}@${m.ghost.digest}`, + ]), `profiles ${m.profiles.join(',')}`, ]; } diff --git a/manager/src/payload.ts b/manager/src/payload.ts index d6af9a1f..111499d6 100644 --- a/manager/src/payload.ts +++ b/manager/src/payload.ts @@ -32,12 +32,16 @@ export const isCheckout = (context: Context, dir: string): boolean => /** * The top-level payload entries a directory of each layout does without: a * site with no Caddy has no routes, and cannot select analytics, whose - * Tinybird jobs are built from tinybird/. + * Tinybird jobs are built from tinybird/; a site behind the shared Caddy has + * its routes in the shared Caddy's directory; and that directory runs Caddy + * alone. */ const UNUSED: Record = { local: ['caddy', 'tinybird'], production: [], 'no-caddy': ['caddy', 'tinybird'], + 'shared-caddy': ['caddy'], + infra: ['mysql-init', 'tinybird', 'ghost.env.example'], }; /** diff --git a/manager/src/restore.ts b/manager/src/restore.ts index a61e9458..728c74e6 100644 --- a/manager/src/restore.ts +++ b/manager/src/restore.ts @@ -1,7 +1,15 @@ // Restore validates the inputs it will write before replacing the site. // After writing begins, failure needs the operator; recovery instructions must // name only copies that exist. See docs/architecture.md#restore. -import { cpSync, existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync } from 'node:fs'; +import { + cpSync, + existsSync, + mkdirSync, + mkdtempSync, + readdirSync, + readFileSync, + rmSync, +} from 'node:fs'; import { tmpdir } from 'node:os'; import { basename, dirname, join } from 'node:path'; import { backupSiteFiles, readBackup, refuseMovedData } from './backup.ts'; @@ -40,12 +48,26 @@ import { COMPOSE_OVERRIDE_FILE, DATA_DIRS, ENV_FILE, + hasProfile, + INFRA_PROFILE, MAILPIT_DATA_DIR, + SHARED_CADDY_PROFILE, META_FILE, readSettings, RESTORE_DIR, siteFacts, } from './site.ts'; +import { + addRoutes, + describeShared, + findSharedCaddy, + refuseTaken as refuseServed, + routeFiles, + routesFile, + routesPath, + runningCaddy, + type SharedCaddy, +} from './shared.ts'; import { verifySite } from './verify.ts'; /** `over`: the backup's own site, replaced. `fresh`: a new, empty directory. */ @@ -71,6 +93,7 @@ export async function restoreSite({ io, context, root, yes }: RestoreInput): Pro ); const target = classify(context, dir, manifest); + const routes = await refuseWithoutRoutes(io, root, manifest); if (target === 'fresh') { await refuseTaken(io, root, manifest); } else { @@ -122,6 +145,16 @@ export async function restoreSite({ io, context, root, yes }: RestoreInput): Pro writeSiteFiles(io, root, dir, manifest, pin === null ? null : pulled.get(pin)!); await checkImages(io, dir, manifest); await loadBackupData(io, root, dir, manifest); + if (routes !== null) { + await io.busy('Writing the routes into the shared Caddy', () => + addRoutes(io, routes.shared, manifest.site.project, routes.text), + ); + ok( + io, + 'routes', + `${routesPath(routes.shared, manifest.site.project)}, from the backup; the shared Caddy reloaded`, + ); + } heading(io, 'Starting the services'); await upAndWait(io, dir, 'Starting the services and waiting for them to be healthy'); @@ -383,6 +416,60 @@ async function refuseOtherConfiguration( ok(io, 'configuration', "the backup's resolves the images it records"); } +/** + * A site that was behind the shared Caddy is restored behind it: the shared + * Caddy must run, and serve the site's routes. Routes it already has are + * kept, as the operator may have edited them since; otherwise the backup's + * are written back (returned here, written once the site's data is), when + * no other site serves their domains. A backup without routes needs them in + * place first. + */ +async function refuseWithoutRoutes( + io: Io, + root: string, + manifest: BackupManifest, +): Promise<{ shared: SharedCaddy; text: string } | null> { + const settings = env.toRecord(readIfExists(join(root, SITE_FILES_DIR, ENV_FILE)) ?? ''); + if (!hasProfile(settings.COMPOSE_PROFILES ?? '', SHARED_CADDY_PROFILE)) { + return null; + } + const project = manifest.site.project; + const shared = await findSharedCaddy(io); + if (shared === null) { + throw new CliError( + `this backup is of a site behind the shared Caddy, and this server has none.\n` + + ' Set one up first with ./ghost-docker install --infra, in a directory of its own' + + (manifest.routes === undefined + ? `, and put\n the site's routes in its caddy/sites/${routesFile(project)}` + : '; the restore\n writes the routes the backup holds') + + '. Nothing has been changed.', + ); + } + if ((await routeFiles(io, runningCaddy(shared))).includes(routesFile(project))) { + ok( + io, + 'routes', + `${routesPath(shared, project)}, kept as it is, in ${describeShared(shared)}`, + ); + return null; + } + if (manifest.routes === undefined) { + throw new CliError( + `this backup is of a site behind the shared Caddy, which has no routes for it:\n` + + ` ${routesPath(shared, project)} does not exist, and the backup holds none. Put them back\n` + + ' (or write them as docs/caddy.md describes), then run the restore again. Nothing has\n' + + ' been changed.', + ); + } + const domains = [settings.URL, settings.ADMIN_URL] + .filter((url): url is string => Boolean(url)) + .map((url) => URL.parse(url)?.hostname) + .filter((host): host is string => Boolean(host)); + await refuseServed(io, shared, project, domains); + ok(io, 'routes', `the backup's, written to ${routesPath(shared, project)} once the data is`); + return { shared, text: readFileSync(join(root, manifest.routes), 'utf8') }; +} + /** * A site restored into a new directory keeps its project name and its ports, * so nothing running on this daemon may already use them; a stopped site @@ -619,7 +706,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..48148c96 --- /dev/null +++ b/manager/src/shared.ts @@ -0,0 +1,352 @@ +// The shared Caddy: one Caddy for several production sites on a server, as +// Ghost-CLI ran several sites behind one nginx. Only one process can hold 80 +// and 443, so Caddy is shared; everything else, MySQL included, stays per +// site. It is a Compose project of its own (`install --infra`), on a network +// the manager creates and no project owns, which each site's Ghost and +// optional services join under their unique aliases. The network's labels say +// where the shared Caddy's directory is. +// +// Each site's routes are a file in that directory's caddy/sites/, named for +// the site's project. The manager cannot see that directory, only its own +// site's, so it reads and writes it through the running Caddy container, which +// mounts it: what is written is exactly what Caddy reads. See docs/caddy.md. +import { randomUUID } from 'node:crypto'; +import { CliError } from './errors.ts'; +import { + execInContainer, + inspectNetwork, + listContainers, + type ContainerFacts, +} from './docker/client.ts'; +import type { RunResult } from './docker/client.ts'; +import type { Io } from './io.ts'; +import { PROJECT_LABEL, WORKING_DIR_LABEL } from './project.ts'; + +/** The shared Caddy's network. One per daemon, as 80 and 443 are. */ +export const INGRESS_NETWORK = 'ghost-ingress'; +/** The network's labels: the shared Caddy's directory and project. */ +export const INFRA_DIR_LABEL = 'org.ghost.docker.infra.dir'; +export const INFRA_PROJECT_LABEL = 'org.ghost.docker.infra.project'; +/** The label Compose gives each container its service's name. */ +export const SERVICE_LABEL = 'com.docker.compose.service'; +/** The default project name of the shared Caddy. */ +export const INFRA_PROJECT = 'ghost-infra'; + +/** Where the shared Caddy container mounts the sites' routes. */ +const SITES = '/etc/caddy/sites'; +const CADDYFILE = '/etc/caddy/Caddyfile'; + +/** + * `caddy reload` in the shared Caddy's container, one at a time. A reload + * reads the configuration, routes included, then loads it: a reload that read + * before another site's routes were written, and loaded after that site's own + * reload, would drop them from the running Caddy. Each site's manager and the + * shared Caddy's self-update see none of each other's directories, so the + * lock is taken in the container, on the sites' directory itself (busybox + * flock locks a directory), which leaves no file behind. + */ +export const RELOAD = ['flock', SITES, 'caddy', 'reload', '--config', CADDYFILE] as const; + +export interface SharedCaddy { + readonly network: string; + /** The shared Caddy's directory on the host. */ + readonly dir: string; + readonly project: string; + /** Its Caddy container, running or not; null when it has none. */ + readonly container: ContainerFacts | null; +} + +/** The shared Caddy on this daemon, or null when there is none. */ +export async function findSharedCaddy(io: Io): Promise { + const network = await inspectNetwork(io.docker, INGRESS_NETWORK); + if (network === null) { + return null; + } + const project = network.labels[INFRA_PROJECT_LABEL] ?? ''; + const [container] = + project === '' + ? [] + : await listContainers(io.docker, { + all: true, + labels: [`${PROJECT_LABEL}=${project}`, `${SERVICE_LABEL}=caddy`], + }); + return { + network: network.name, + dir: container?.labels[WORKING_DIR_LABEL] ?? network.labels[INFRA_DIR_LABEL] ?? '', + project, + container: container ?? null, + }; +} + +/** How to name the shared Caddy to a person. */ +export const describeShared = (shared: SharedCaddy): string => + `the shared Caddy${shared.dir ? ` in ${shared.dir}` : ''}`; + +/** + * The shared Caddy's container, which must be running for its routes to be + * read or changed; otherwise a CliError saying how to start it. + */ +export function runningCaddy(shared: SharedCaddy): ContainerFacts { + const { container } = shared; + if (container === null || container.state !== 'running') { + throw new CliError( + `${describeShared(shared)} is not running, so its routes cannot be read or changed.\n` + + ` Start it in its directory: cd ${shared.dir || ''} && docker compose up -d\n` + + ' Nothing has been changed.', + ); + } + return container; +} + +/** A site's routes file, in the shared Caddy's caddy/sites/. */ +export const routesFile = (project: string): string => `${project}.caddy`; + +/** The routes file, as a person finds it on the host. */ +export const routesPath = (shared: SharedCaddy, project: string): string => + `${shared.dir || ''}/caddy/sites/${routesFile(project)}`; + +const inCaddy = ( + io: Io, + caddy: ContainerFacts, + cmd: readonly string[], + user?: string, +): Promise => execInContainer(io.docker, caddy.id, { cmd, user }); + +/** What a command in the Caddy container said when it failed, for an error. */ +const said = (result: RunResult): string => + (result.stderr.trim() || result.stdout.trim() || 'no output') + .split('\n') + .slice(-8) + .map((line) => ` ${line}`) + .join('\n'); + +/** Every host name the shared Caddy's loaded configuration matches, lowercase. */ +export async function servedHosts(io: Io, caddy: ContainerFacts): Promise> { + // Its admin API listens inside the container only, as the health check uses it. + const result = await inCaddy(io, caddy, [ + 'wget', + '-q', + '-O', + '-', + 'http://127.0.0.1:2019/config/', + ]); + if (result.status !== 0) { + throw new CliError( + `the shared Caddy's configuration could not be read from its admin API:\n${said(result)}`, + ); + } + const hosts = new Set(); + const walk = (value: unknown): void => { + if (Array.isArray(value)) { + value.forEach(walk); + } else if (value !== null && typeof value === 'object') { + for (const [key, inner] of Object.entries(value)) { + if (key === 'host' && Array.isArray(inner)) { + for (const host of inner) { + if (typeof host === 'string') { + hosts.add(host.toLowerCase()); + } + } + } else { + walk(inner); + } + } + } + }; + walk(result.stdout.trim() === '' ? null : JSON.parse(result.stdout)); + return hosts; +} + +/** The files in the shared Caddy's caddy/sites/. */ +export async function routeFiles(io: Io, caddy: ContainerFacts): Promise { + const result = await inCaddy(io, caddy, ['ls', '-1A', SITES]); + if (result.status !== 0) { + throw new CliError(`the shared Caddy's ${SITES} could not be listed:\n${said(result)}`); + } + return result.stdout.split('\n').filter((line) => line !== ''); +} + +/** The marker line an install writes first in its routes (routesMarker). */ +const MARKER_LINE = /^# ghost-docker install [0-9a-f-]+\n/; + +/** + * A site's routes as the shared Caddy holds them, without the marker line + * of the install that wrote them, or null when it has none: what a backup + * keeps, and what a restore writes back with addRoutes. + */ +export async function readRoutes( + io: Io, + shared: SharedCaddy, + project: string, +): Promise { + const caddy = runningCaddy(shared); + if (!(await routeFiles(io, caddy)).includes(routesFile(project))) { + return null; + } + const read = await inCaddy(io, caddy, ['cat', `${SITES}/${routesFile(project)}`]); + if (read.status !== 0) { + throw new CliError(`${routesPath(shared, project)} could not be read: +${said(read)}`); + } + return read.stdout.replace(MARKER_LINE, ''); +} + +/** + * Refuses a site whose project already has routes in the shared Caddy, or + * whose domains it already serves, for whichever site: before anything is + * written. Caddy would also refuse a second block for one address, but only + * once the file was there. + */ +export async function refuseTaken( + io: Io, + shared: SharedCaddy, + project: string, + domains: readonly string[], +): Promise { + const caddy = runningCaddy(shared); + if ((await routeFiles(io, caddy)).includes(routesFile(project))) { + throw new CliError( + `${routesPath(shared, project)} already exists: the project ${project} already has routes in\n` + + ' the shared Caddy. Choose another name with --name, or remove that site first\n' + + ' (./ghost-docker remove, in its directory). Nothing has been changed.', + ); + } + const served = await servedHosts(io, caddy); + const taken = domains + .map((domain) => domain.toLowerCase()) + .filter((domain) => served.has(domain)); + if (taken.length > 0) { + throw new CliError( + `the shared Caddy already serves ${taken.join(' and ')}, for another site or in its own\n` + + ` configuration (${shared.dir || 'its directory'}/caddy). Two sites cannot share a domain.\n` + + ' Nothing has been changed.', + ); + } +} + +/** + * The first line of routes an installation wrote: which write they are, so + * undoing it removes them only while they are still that write's. + */ +export const routesMarker = (token: string): string => `# ghost-docker install ${token}`; + +/** + * Writes a site's routes into the shared Caddy, owned by whoever owns its + * caddy/sites/, has Caddy validate its whole configuration with them, and + * reloads it. Routes Caddy refuses are removed again, and Caddy keeps serving + * what it served. + * + * `owned` is told the token of the write before it is made, since a write + * whose result is unknown may have happened, and null once the file is + * certainly not this write's: an existing one is never replaced, and routes + * Caddy refused are removed. Undo then removes the file only if it is still + * marked with that token (removeRoutes). + */ +export async function addRoutes( + io: Io, + shared: SharedCaddy, + project: string, + routes: string, + owned: (token: string | null) => void = () => undefined, +): Promise { + const caddy = runningCaddy(shared); + const owner = await inCaddy(io, caddy, ['stat', '-c', '%u:%g', SITES]); + if (owner.status !== 0) { + throw new CliError(`the shared Caddy's ${SITES} could not be read:\n${said(owner)}`); + } + const file = `${SITES}/${routesFile(project)}`; + const token = randomUUID(); + owned(token); + // Written beside it under a name of this writer's that the Caddyfile's + // *.caddy does not import, then linked into place: a link, unlike a + // rename, fails when the file exists, so another site's is never replaced + // and Caddy never reads half a file. + const write = await inCaddy( + io, + caddy, + [ + 'sh', + '-c', + 'umask 022 && t="$2.$$.new" && printf "%s" "$1" > "$t" && ln "$t" "$2"; s=$?; rm -f "$t"; exit $s', + 'sh', + `${routesMarker(token)}\n${routes}`, + file, + ], + owner.stdout.trim(), + ); + if (write.status !== 0) { + // A status means it did not happen; none, that it may have. + if (write.status !== null) { + owned(null); + } + throw new CliError(`the routes could not be written to the shared Caddy:\n${said(write)}`); + } + const valid = await inCaddy(io, caddy, ['caddy', 'validate', '--config', CADDYFILE]); + if (valid.status !== 0) { + const removed = await inCaddy(io, caddy, ['rm', '-f', file], owner.stdout.trim()); + if (removed.status !== 0) { + throw new CliError( + `the shared Caddy does not accept its configuration with these routes, and they could not\n` + + ` be removed again: remove ${routesPath(shared, project)} by hand. Until then Caddy keeps\n` + + ` serving, but will not start again. Caddy said:\n${said(valid)}`, + ); + } + owned(null); + throw new CliError( + `the shared Caddy does not accept its configuration with these routes, so they were removed\n` + + ` again; Caddy still serves what it served. Caddy said:\n${said(valid)}`, + ); + } + await reloadCaddy(io, shared); +} + +/** + * Removes a site's routes from the shared Caddy and reloads it. Routes + * that are already gone are not an error. With a token, only routes that + * write made (routesMarker) are removed: undoing an install never takes + * another's. + */ +export async function removeRoutes( + io: Io, + shared: SharedCaddy, + project: string, + token?: string, +): Promise { + const caddy = runningCaddy(shared); + const file = `${SITES}/${routesFile(project)}`; + const removed = await inCaddy( + io, + caddy, + token === undefined + ? ['rm', '-f', file] + : [ + 'sh', + '-c', + 'if head -n 1 "$2" 2>/dev/null | grep -qxF "$1"; then rm -f "$2"; fi', + 'sh', + routesMarker(token), + file, + ], + ); + if (removed.status !== 0) { + throw new CliError( + `${routesPath(shared, project)} could not be removed:\n${said(removed)}`, + ); + } + await reloadCaddy(io, shared); +} + +/** + * `caddy reload`: the configuration loads whole, or Caddy says why and keeps + * serving the one it had. + */ +export async function reloadCaddy(io: Io, shared: SharedCaddy): Promise { + const caddy = runningCaddy(shared); + const reloaded = await inCaddy(io, caddy, RELOAD); + if (reloaded.status !== 0) { + throw new CliError( + `the shared Caddy did not load its configuration, and keeps serving the one it had.\n` + + ` Caddy said:\n${said(reloaded)}`, + ); + } +} diff --git a/manager/src/site.ts b/manager/src/site.ts index fb3a6be5..ec0c6bc3 100644 --- a/manager/src/site.ts +++ b/manager/src/site.ts @@ -56,26 +56,44 @@ export type SiteMode = (typeof SITE_MODES)[number]; * host: Ghost and MySQL, no Caddy. Its mode is production. */ export const NO_CADDY_PROFILE = 'no-caddy'; +/** + * A production site behind the shared Caddy (shared.ts): Ghost and MySQL of + * its own, its routes in the shared Caddy's directory. Its mode is production. + */ +export const SHARED_CADDY_PROFILE = 'shared-caddy'; +/** The shared Caddy's own directory: Caddy alone, and no site. */ +export const INFRA_PROFILE = 'infra'; /** The profiles that select a site's mode, and the mode each selects. */ const MODE_PROFILES: Readonly> = { local: 'local', production: 'production', [NO_CADDY_PROFILE]: 'production', + [SHARED_CADDY_PROFILE]: 'production', }; export const MODE_PROFILE_NAMES = Object.keys(MODE_PROFILES); /** - * What a directory's files are for: a site of either mode, or a production - * site behind the operator's own proxy. The stack files each one needs differ - * (payload.ts), and only a production layout has Caddy. + * What a directory's files are for: a site of either mode, a production site + * behind the operator's own proxy or behind the shared Caddy, or the shared + * Caddy itself. The stack files each one needs differ (payload.ts), and only a + * production layout has a Caddy of its own. */ -export type Layout = SiteMode | typeof NO_CADDY_PROFILE; +export type Layout = + | SiteMode + | typeof NO_CADDY_PROFILE + | typeof SHARED_CADDY_PROFILE + | typeof INFRA_PROFILE; /** The layout COMPOSE_PROFILES selects; a production one unless it says otherwise. */ export function layoutOf(profiles: string): Layout { const selected = splitProfiles(profiles); - for (const layout of [NO_CADDY_PROFILE, 'local'] as const) { + for (const layout of [ + INFRA_PROFILE, + NO_CADDY_PROFILE, + SHARED_CADDY_PROFILE, + 'local', + ] as const) { if (selected.includes(layout)) { return layout; } @@ -83,6 +101,10 @@ export function layoutOf(profiles: string): Layout { return 'production'; } +/** Does this `.env` belong to the shared Caddy's directory rather than a site? */ +export const isInfra = (settings: SiteSettings): boolean => + hasProfile(settings.get('COMPOSE_PROFILES') ?? '', INFRA_PROFILE); + /** Additive, per-site. `supervisor` runs the upgrade supervisor (docs/upgrade-supervisor.md). */ export const OPTIONAL_PROFILES = ['analytics', 'activitypub', 'mailpit', 'supervisor'] as const; @@ -176,8 +198,10 @@ export function generatedSettings(input: { >; readonly port: number; readonly mailpitPort: number | null; - /** Caddy's, written for a production site with Caddy. */ + /** Caddy's, written for a production site with a Caddy of its own. */ readonly ports: { readonly http: string; readonly https: string }; + /** The shared Caddy's network, for a site behind it; null for one with its own. */ + readonly ingress: string | null; readonly database: { readonly user: string; readonly password: string; @@ -204,6 +228,7 @@ export function generatedSettings(input: { ...(input.mailpitPort === null ? {} : { MAILPIT_PORT: String(input.mailpitPort) }), RESTART_POLICY: production ? 'unless-stopped' : 'no', ...(caddy ? { HTTP_PORT: input.ports.http, HTTPS_PORT: input.ports.https } : {}), + ...(input.ingress === null ? {} : ingressSettings(input.ingress)), DATABASE_HOST: 'db', DATABASE_PORT: '3306', DATABASE_NAME: 'ghost', @@ -213,6 +238,12 @@ export function generatedSettings(input: { }); } +/** What puts a directory's services on the shared Caddy's network, which it does not create. */ +export const ingressSettings = (network: string): Record => ({ + INGRESS_NETWORK: network, + INGRESS_EXTERNAL: 'true', +}); + /** The hostname a URL names, or '' when it is not a URL. */ export const hostOf = (url: string): string => { try { @@ -226,7 +257,10 @@ export const hostOf = (url: string): string => { export interface SiteFacts { readonly dir: string; readonly mode: SiteMode | null; - /** Whether Caddy serves it ('production'), or the operator's own proxy ('no-caddy'). */ + /** + * Whether its own Caddy serves it ('production'), the shared Caddy + * ('shared-caddy'), or the operator's own proxy ('no-caddy'). + */ readonly layout: Layout; /** The hosts of URL and ADMIN_URL: what Caddy should serve, in production. */ readonly domain: string; diff --git a/manager/src/undo.ts b/manager/src/undo.ts index 0e2d8a56..052a5249 100644 --- a/manager/src/undo.ts +++ b/manager/src/undo.ts @@ -13,13 +13,17 @@ import { removeAsRoot } from './asroot.ts'; import { atomicWrite, PRIVATE, readIfExists } from './fs.ts'; import type { Io } from './io.ts'; import type { Written } from './payload.ts'; -import { DATA_DIRS, ENV_FILE, GHOST_ENV_FILE, META_FILE } from './site.ts'; +import { removeNetwork } from './docker/client.ts'; +import { findSharedCaddy, removeRoutes, routesFile, routesPath } from './shared.ts'; +import { DATA_DIRS, ENV_FILE, GHOST_ENV_FILE, META_FILE, readSettings } from './site.ts'; const journalSchema = z.object({ files: z.array(z.string().startsWith('/')), directories: z.array(z.string().startsWith('/')), data: z.array(z.string().startsWith('/')), project: z.boolean(), + // A write's token (shared.ts routesMarker), or true for whatever is there. + routes: z.union([z.string(), z.boolean()]).default(false), }); export class Created implements Written { @@ -30,6 +34,14 @@ export class Created implements Written { readonly data: string[] = []; /** Compose has created something for this project: a network, containers, volumes. */ project = false; + /** + * The site's routes in the shared Caddy, named for its project + * (shared.ts): the token of the write that may have made them, or true + * for whatever file is there. + */ + routes: string | boolean = false; + /** The shared Caddy's network, created by `install --infra`. */ + network: string | null = null; /** The import marker, when this is an import. */ journal: string | null = null; @@ -59,6 +71,8 @@ export class Created implements Written { directories: [], data: DATA_DIRS.map((data) => join(dir, data)), project: true, + // Named for this site's project, which no other site's can have. + routes: true, }; } // Only ever inside this site directory, whatever the file says. @@ -67,6 +81,7 @@ export class Created implements Written { created.directories.push(...recorded.directories.filter(inside)); created.data.push(...recorded.data.filter(inside)); created.project = recorded.project && existsSync(join(dir, ENV_FILE)); + created.routes = recorded.routes; return created; } @@ -80,16 +95,19 @@ export class Created implements Written { if (this.journal === null) { return; } - const { files, directories, data, project } = this; + const { files, directories, data, project, routes } = this; atomicWrite( this.journal, - `${JSON.stringify({ files, directories, data, project }, null, 2)}\n`, + `${JSON.stringify({ files, directories, data, project, routes }, null, 2)}\n`, PRIVATE, ); } async remove(): Promise { const leftovers: string[] = []; + if (this.routes) { + leftovers.push(...(await this.removeRoutes())); + } if (this.project) { // Every profile, so whatever was started is found; the .env it // interpolates is still in place. @@ -103,6 +121,11 @@ export class Created implements Written { ); } } + if (this.network !== null) { + await removeNetwork(this.io.docker, this.network).catch((error: unknown) => + leftovers.push(`the network ${this.network} (${(error as Error).message})`), + ); + } if (this.data.length > 0) { leftovers.push(...(await this.removeData())); } @@ -128,6 +151,34 @@ export class Created implements Written { return leftovers; } + /** The site's routes in the shared Caddy, which is reloaded without them. */ + private async removeRoutes(): Promise { + const project = readSettings(this.dir)?.get('COMPOSE_PROJECT_NAME') ?? ''; + if (project === '') { + return []; + } + let shared = null; + try { + shared = await findSharedCaddy(this.io); + if (shared === null) { + return []; + } + await removeRoutes( + this.io, + shared, + project, + typeof this.routes === 'string' ? this.routes : undefined, + ); + return []; + } catch (error) { + const path = + shared === null + ? `${routesFile(project)} in the shared Caddy` + : routesPath(shared, project); + return [`${path} (${(error as Error).message.split('\n')[0]})`]; + } + } + /** MySQL's data directory belongs to MySQL's user once it has run (asroot.ts). */ private async removeData(): Promise { const left = await removeAsRoot( diff --git a/manager/src/verify.ts b/manager/src/verify.ts index d28faa0b..874da605 100644 --- a/manager/src/verify.ts +++ b/manager/src/verify.ts @@ -9,7 +9,22 @@ import type { Io } from './io.ts'; import { NetworkUnavailable, type SiteNetwork } from './network.ts'; import { CliError } from './errors.ts'; import { failed, heading, printChecks, type Check } from './report.ts'; -import { hasProfile, NO_CADDY_PROFILE, readSettings, siteFacts, type SiteFacts } from './site.ts'; +import { + describeShared, + findSharedCaddy, + INGRESS_NETWORK, + routeFiles, + routesFile, + routesPath, +} from './shared.ts'; +import { + hasProfile, + NO_CADDY_PROFILE, + SHARED_CADDY_PROFILE, + readSettings, + siteFacts, + type SiteFacts, +} from './site.ts'; const describeState = (state: ServiceState | undefined): string => state ? [state.State, state.Health].filter(Boolean).join(', ') : 'no container'; @@ -192,7 +207,8 @@ export async function verifyIngress( site: SiteFacts, known?: readonly ServiceState[] | null, ): Promise { - const production = site.layout === 'production'; + // Served by a Caddy: its own, or the shared one. + const production = site.layout === 'production' || site.layout === SHARED_CADDY_PROFILE; const withMailpit = hasProfile(site.settings.get('COMPOSE_PROFILES') ?? '', 'mailpit'); // `check` has the service states already. const services = known ?? (await composePs(io, site.dir)); @@ -200,14 +216,21 @@ export async function verifyIngress( const checks: Check[] = [ healthy('ghost', state('ghost'), 'its Admin API answers inside the container'), ]; + // Behind the shared Caddy, Caddy is, in another project. + const shared = + site.layout === SHARED_CADDY_PROFILE ? await sharedCaddyOf(io, site, checks) : null; + const caddy = shared === null ? state('caddy') : shared.state; if (production) { checks.push( healthy( - 'caddy', - state('caddy'), + shared === null ? 'caddy' : 'shared caddy', + caddy, 'its admin API answers, with its configuration loaded', ), ); + if (shared?.routes) { + checks.push(shared.routes); + } // The domain, and the admin domain when it has one of its own. const adminElsewhere = site.adminDomain !== '' && site.adminDomain !== site.domain ? site.adminDomain : null; @@ -230,15 +253,19 @@ export async function verifyIngress( } else { try { checks.push( - ...(await io.siteNetwork(services ?? [], ['caddy'], async (network) => { - const answers: Check[] = []; - for (const [label, name, elsewhere] of names) { - answers.push( - await https(io, network, label, name, expected, elsewhere), - ); - } - return answers; - })), + ...(await io.siteNetwork( + caddy === undefined ? [] : [caddy], + ['caddy'], + async (network) => { + const answers: Check[] = []; + for (const [label, name, elsewhere] of names) { + answers.push( + await https(io, network, label, name, expected, elsewhere), + ); + } + return answers; + }, + )), ); } catch (failure) { if (!(failure instanceof NetworkUnavailable)) { @@ -271,13 +298,84 @@ export async function verifyIngress( label: 'published ports', detail: `Docker publishes Ghost on ${publishedPorts(services, 'ghost')}` + - (production ? ` and Caddy on ${publishedPorts(services, 'caddy')}` : '') + + (production + ? ` and ${shared === null ? 'Caddy' : 'the shared Caddy'} on ${publishedPorts(shared === null ? services : [shared.state].filter((each) => each !== undefined), 'caddy')}` + : '') + (withMailpit ? `, and Mailpit's inbox on ${publishedPorts(services, 'mailpit')}` : '') + '; a container cannot reach the host, so open the URL to see them from there', }); return checks; } +/** The health Docker reports in a container's status: `Up 2 minutes (healthy)`. */ +const healthOf = (status: string): string => + /\(healthy\)/.test(status) + ? 'healthy' + : /\(unhealthy\)/.test(status) + ? 'unhealthy' + : /\(health: starting\)/.test(status) + ? 'starting' + : ''; + +/** + * The shared Caddy a site is behind: its container as `ps` would report it, + * and whether this site's routes are in its directory. A server with no + * shared Caddy is reported in `checks`. + */ +async function sharedCaddyOf( + io: Io, + site: SiteFacts, + checks: Check[], +): Promise<{ state: ServiceState | undefined; routes: Check | null } | null> { + const shared = await findSharedCaddy(io); + if (shared === null) { + checks.push( + error( + 'shared caddy', + `this site is behind the shared Caddy (${SHARED_CADDY_PROFILE} in COMPOSE_PROFILES), and this server has none: its network ${INGRESS_NETWORK} does not exist`, + ), + ); + return { state: undefined, routes: null }; + } + const { container } = shared; + const state: ServiceState | undefined = + container === null + ? undefined + : { + ID: container.id, + Service: 'caddy', + State: container.state, + Health: healthOf(container.status), + ExitCode: 0, + Publishers: container.publishedPorts.map((port) => ({ + URL: '', + TargetPort: 0, + PublishedPort: port, + Protocol: 'tcp', + })), + }; + if (container?.state !== 'running') { + return { state, routes: null }; + } + const project = site.settings.get('COMPOSE_PROJECT_NAME') || ''; + const path = routesPath(shared, project); + const present = (await routeFiles(io, container).catch(() => null))?.includes( + routesFile(project), + ); + return { + state, + routes: + present === undefined + ? error('routes', `the shared Caddy's caddy/sites/ could not be listed`) + : present + ? ok('routes', `${path}, in ${describeShared(shared)}`) + : error( + 'routes', + `${path} does not exist, so the shared Caddy has no routes of this site's`, + ), + }; +} + /** A site just started, verified and reported; a failure is a CliError. */ export async function verifySite(io: Io, dir: string): Promise { heading(io, 'Verifying the site'); diff --git a/manager/test/backup.test.ts b/manager/test/backup.test.ts index 540ff6b8..5c39b6fd 100644 --- a/manager/test/backup.test.ts +++ b/manager/test/backup.test.ts @@ -34,6 +34,7 @@ import { type Harness, type ProgramResult, } from './helpers.ts'; +import { CADDY, fakeShared, sharedApi, type FakeShared } from './shared-caddy.ts'; import { imageApi, imageStack, INDEX, REFERENCE, resolvedProject, rootContainer } from './site.ts'; const MANAGER = `sha256:${'2'.repeat(64)}`; @@ -566,6 +567,124 @@ describe('backup records what the site runs', () => { }); }); +describe('a site behind the shared Caddy', () => { + const ROUTES = 'example.com {\n\treverse_proxy ghost-example-com-ghost:2368\n}\n'; + let shared: FakeShared; + let project: string; + const routesFile = () => `${project}.caddy`; + + beforeEach(() => { + project = env.toRecord(readSite('.env')).COMPOSE_PROJECT_NAME!; + // The site as an install behind the shared Caddy leaves it. + const profiles = env.toRecord(readSite('.env')).COMPOSE_PROFILES!; + setEnv('COMPOSE_PROFILES', profiles.replace('production', 'shared-caddy')); + setEnv('INGRESS_NETWORK', 'ghost-ingress'); + setEnv('INGRESS_EXTERNAL', 'true'); + shared = fakeShared(); + shared.sites.set(routesFile(), `# ghost-docker install ${'a'.repeat(8)}-0000\n${ROUTES}`); + const site = h.daemon.api; + const caddy = sharedApi(shared); + h.daemon.api = (request) => caddy(request) ?? site!(request); + h.daemon.containers = [CADDY]; + }); + + test('its backup holds its routes, without their marker line', async () => { + const root = await backUp(); + const manifest = JSON.parse(readFileSync(join(root, 'manifest.json'), 'utf8')); + assert.equal(manifest.routes, 'routes.caddy'); + assert.equal(readFileSync(join(root, 'routes.caddy'), 'utf8'), ROUTES); + assert.ok(manifest.files['routes.caddy']); + assert.ok(!manifest.notIncluded.some((line: string) => /its routes/.test(line))); + }); + + test('routes the shared Caddy does not have leave the backup without them, and say so', async () => { + shared.sites.clear(); + const result = await h.run('backup'); + assert.equal(result.code, 0, result.stderr); + assert.match( + result.stdout + result.stderr, + /does not exist, so the backup holds no routes/, + ); + const manifest = JSON.parse( + readFileSync(join(h.dir, 'backups', backups()[0]!, 'manifest.json'), 'utf8'), + ); + assert.equal(manifest.routes, undefined); + assert.ok(manifest.notIncluded.some((line: string) => /its routes/.test(line))); + }); + + test("a restore writes the backup's routes back when the shared Caddy has none", async () => { + const root = await backUp(); + // The site was removed, its routes with it. + shared.sites.clear(); + const result = await h.run('restore', '--yes', root); + assert.equal(result.code, 0, result.stderr); + assert.match(result.stdout, /the backup's, written to/); + const written = shared.sites.get(routesFile()); + assert.ok(written !== undefined, result.stderr); + assert.match(written, /^# ghost-docker install [0-9a-f-]+\n/); + assert.equal(written.replace(/^.*\n/, ''), ROUTES); + assert.ok(shared.execs.some(({ cmd }) => cmd.includes('reload'))); + }); + + test('a restore keeps the routes the shared Caddy has', async () => { + const root = await backUp(); + const edited = `# ghost-docker install ${'b'.repeat(8)}\nexample.com {\n\trespond 503\n}\n`; + shared.sites.set(routesFile(), edited); + const result = await h.run('restore', '--yes', root); + assert.equal(result.code, 0, result.stderr); + assert.match(result.stdout, /kept as it is/); + assert.equal(shared.sites.get(routesFile()), edited); + }); + + test('a backup without routes is refused while the shared Caddy has none', async () => { + shared.sites.clear(); + const result = await h.run('backup'); + assert.equal(result.code, 0, result.stderr); + const root = join(h.dir, 'backups', backups()[0]!); + const restored = await h.run('restore', '--yes', root); + assert.equal(restored.code, 1); + assert.match( + restored.stderr, + /has no routes for it[\s\S]*the backup holds none[\s\S]*Nothing has/, + ); + }); + + test('routes with no checksum are refused before anything changes', async () => { + const root = await backUp(); + const manifest = JSON.parse(readFileSync(join(root, 'manifest.json'), 'utf8')); + delete manifest.files['routes.caddy']; + writeFileSync(join(root, 'manifest.json'), JSON.stringify(manifest)); + writeFileSync( + join(root, 'routes.caddy'), + 'example.com {\n\trespond "not the backup\'s"\n}\n', + ); + shared.sites.clear(); + shared.execs.length = 0; + const before = readSite('.env'); + const restored = await h.run('restore', '--yes', root); + assert.equal(restored.code, 1); + assert.match( + restored.stderr, + /lists no checksum for routes\.caddy\. Nothing has been changed/, + ); + assert.equal(readSite('.env'), before); + assert.equal(shared.sites.size, 0); + assert.deepEqual(shared.execs, []); + }); + + test("routes whose domain another site's routes serve are refused before anything changes", async () => { + const root = await backUp(); + shared.sites.clear(); + shared.hosts = new Set(['example.com']); + const env = readSite('.env'); + const restored = await h.run('restore', '--yes', root); + assert.equal(restored.code, 1); + assert.match(restored.stderr, /already serves example\.com/); + assert.equal(readSite('.env'), env); + assert.equal(shared.sites.size, 0); + }); +}); + describe('restore over the site', () => { test('puts the backup back, pinned, and removes the site it replaced once verified', async () => { const root = await backUp(); diff --git a/manager/test/config.test.ts b/manager/test/config.test.ts index fb61bf2d..21d0cdf0 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:\/\//); @@ -143,10 +143,11 @@ describe('.env', () => { assert.match(result.errors, /warning .*mode is 0644; it holds credentials/); }); - test('Compose guards URL itself, so validation does not list it twice', async () => { + test('a local site needs URL too: compose.yml no longer guards it', async () => { makeSite(h, { ...LOCAL, URL: undefined }); const result = await validate(); - assert.doesNotMatch(result.errors, /\.env +URL is required/); + assert.equal(result.code, 1); + assert.match(result.errors, /URL is required for mode local/); }); }); diff --git a/manager/test/integration/shared.test.ts b/manager/test/integration/shared.test.ts new file mode 100644 index 00000000..4465e2cc --- /dev/null +++ b/manager/test/integration/shared.test.ts @@ -0,0 +1,178 @@ +// The shared Caddy, against the real daemon and a real Caddy: a site's +// routes written, validated and loaded through the running container, its +// Ghost reached by its unique alias on the shared network, a taken domain or +// project refused, routes Caddy refuses taken out again, and removal. +// +// The shared Caddy here is the stack's own compose.yml with the `infra` +// profile, on a network of this run's rather than the real one. The site's +// Ghost is a stand-in that answers as a Ghost of its URL would: the real one +// is tests/e2e/shared-caddy.sh's. +import assert from 'node:assert/strict'; +import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { after, before, test } from 'node:test'; +import { renderRoutes } from '../../src/caddy.ts'; +import { listContainers } from '../../src/docker/client.ts'; +import { CliError } from '../../src/errors.ts'; +import { PROJECT_LABEL } from '../../src/project.ts'; +import { + addRoutes, + refuseTaken, + removeRoutes, + routeFiles, + servedHosts, + SERVICE_LABEL, + type SharedCaddy, +} from '../../src/shared.ts'; +import { makeSite, named, realIo, type TestSite } from './site.ts'; + +const io = realIo(); +const INGRESS = named('ingress'); +const CADDY_IMAGE = /image: (caddy:\S+)/.exec( + readFileSync(join(import.meta.dirname, '..', '..', '..', 'compose.yml'), 'utf8'), +)![1]!; + +const ingress: [string, string][] = [ + ['INGRESS_NETWORK', INGRESS], + ['INGRESS_EXTERNAL', 'true'], +]; + +let infra: TestSite; +let delta: TestSite; +let shared: SharedCaddy; + +/** Delta's Ghost: Caddy answering every request as Ghost's site endpoint does. */ +const STAND_IN = `services: + ghost: + image: ${CADDY_IMAGE} + command: ["caddy", "respond", "--listen", ":2368", "--body", '{"site":{"url":"https://delta.test/"}}'] + healthcheck: + test: [CMD, wget, -q, -O, /dev/null, "http://127.0.0.1:2368/"] + interval: 1s + start_period: 0s + ports: !reset [] +`; + +const routes = (project: string, domain: string) => + renderRoutes({ project, domain, adminDomain: '', email: '', activitypub: false }); + +before( + async () => { + const created = await io.docker({ + method: 'POST', + path: '/networks/create', + body: { Name: INGRESS }, + }); + assert.equal(created.status, 201, created.body.toString()); + infra = makeSite(io, 'shared-caddy', { profiles: 'infra', env: ingress }); + // Certificates from Caddy's own CA at once, rather than ACME's. + mkdirSync(join(infra.dir, 'caddy', 'global'), { recursive: true }); + writeFileSync(join(infra.dir, 'caddy', 'global', 'test.caddy'), 'local_certs\n'); + delta = makeSite(io, 'behind-delta', { + profiles: 'shared-caddy', + url: 'https://delta.test', + env: ingress, + override: STAND_IN, + }); + await Promise.all([infra.up('caddy'), delta.up('ghost')]); + const [container] = await listContainers(io.docker, { + labels: [`${PROJECT_LABEL}=${infra.project}`, `${SERVICE_LABEL}=caddy`], + }); + shared = { + network: INGRESS, + dir: infra.dir, + project: infra.project, + container: container!, + }; + }, + { timeout: 1_200_000 }, +); + +after(async () => { + for (const site of [delta, infra]) { + await site?.down(); + } + await io.docker({ method: 'DELETE', path: `/networks/${INGRESS}` }).catch(() => undefined); +}); + +const sitesFile = (name: string) => join(infra.dir, 'caddy', 'sites', name); + +test("a site's routes are written as the directory's owner, validated and loaded", async () => { + await addRoutes(io, shared, delta.project, routes(delta.project, 'delta.test')); + const file = sitesFile(`${delta.project}.caddy`); + assert.ok(existsSync(file)); + const owner = statSync(join(infra.dir, 'caddy', 'sites')); + assert.equal(statSync(file).uid, owner.uid); + assert.ok(!existsSync(`${file}.new`)); + assert.ok((await servedHosts(io, shared.container!)).has('delta.test')); +}); + +test("the site's Ghost answers through the shared Caddy, by its alias on the shared network", async () => { + const answer = await io.siteNetwork( + [ + { + ID: shared.container!.id, + Service: 'caddy', + State: 'running', + Health: 'healthy', + ExitCode: 0, + Publishers: [], + }, + ], + ['caddy'], + async (network) => { + assert.equal(network.name, INGRESS); + // Caddy issues its internal certificate in the background. + for (let attempt = 0; ; attempt += 1) { + try { + return await io.clients.https({ + host: network.address('caddy')!.host, + port: 443, + servername: 'delta.test', + path: '/ghost/api/admin/site/', + }); + } catch (error) { + if (attempt === 30) { + throw error; + } + await new Promise((resolve) => setTimeout(resolve, 1000)); + } + } + }, + ); + assert.equal(answer.status, 200); + assert.match(answer.body, /"url":"https:\/\/delta\.test\/"/); +}); + +test('a taken project or domain is refused before anything is written', async () => { + const before = await routeFiles(io, shared.container!); + await assert.rejects( + refuseTaken(io, shared, delta.project, ['other.test']), + (error: unknown) => error instanceof CliError && /already has routes/.test(error.message), + ); + await assert.rejects( + refuseTaken(io, shared, named('echo'), ['other.test', 'DELTA.test']), + (error: unknown) => + error instanceof CliError && /already serves delta\.test/.test(error.message), + ); + await refuseTaken(io, shared, named('echo'), ['echo.test']); + assert.deepEqual(await routeFiles(io, shared.container!), before); +}); + +test('routes Caddy refuses are taken out again, and Caddy keeps serving', async () => { + const project = named('broken'); + await assert.rejects( + addRoutes(io, shared, project, 'broken.test {\n\treverse_proxy {\n'), + (error: unknown) => error instanceof CliError && /does not accept/.test(error.message), + ); + assert.ok(!existsSync(sitesFile(`${project}.caddy`))); + assert.ok((await servedHosts(io, shared.container!)).has('delta.test')); +}); + +test('removing a site removes its routes, and Caddy reloads without them', async () => { + await removeRoutes(io, shared, delta.project); + assert.ok(!existsSync(sitesFile(`${delta.project}.caddy`))); + assert.ok(!(await servedHosts(io, shared.container!)).has('delta.test')); + // Already gone is not an error. + await removeRoutes(io, shared, delta.project); +}); diff --git a/manager/test/integration/site.ts b/manager/test/integration/site.ts index a312256c..4e34702c 100644 --- a/manager/test/integration/site.ts +++ b/manager/test/integration/site.ts @@ -68,6 +68,8 @@ export interface SiteOptions { readonly override?: string; /** caddy/sites/site.caddy. */ readonly caddy?: string; + /** More `.env` settings. */ + readonly env?: readonly [string, string][]; } export function makeSite(io: Io, name: string, options: SiteOptions): TestSite { @@ -88,6 +90,7 @@ export function makeSite(io: Io, name: string, options: SiteOptions): TestSite { ['URL', options.url ?? 'http://localhost:2368'], ['DATABASE_PASSWORD', secret()], ['DATABASE_ROOT_PASSWORD', secret()], + ...(options.env ?? []), ]), { mode: 0o600 }, ); diff --git a/manager/test/shared-caddy.ts b/manager/test/shared-caddy.ts new file mode 100644 index 00000000..03046c58 --- /dev/null +++ b/manager/test/shared-caddy.ts @@ -0,0 +1,187 @@ +// A shared Caddy as the daemon shows it, for tests of the sites behind it: +// its network, its container, and the files in its caddy/sites/. +import assert from 'node:assert/strict'; +import type { DockerRequest, DockerResponse } from '../src/docker/transport.ts'; +import { frame } from '../src/docker/client.ts'; +import { json } from './helpers.ts'; + +export const INFRA_DIR = '/srv/caddy'; + +/** A shared Caddy as the daemon would show it: its network, its container, and the files it mounts. */ +export interface FakeShared { + /** Files in its caddy/sites/, by name. */ + sites: Map; + /** Host names its loaded configuration matches. */ + hosts: Set; + running: boolean; + /** What `caddy validate` says: null accepts. */ + refuse: string | null; + /** Each command run in its container, with the user it ran as. */ + execs: { cmd: string[]; user: string }[]; + /** The labels the network was created with, when the manager created it. */ + created: Record | null; + exists: boolean; + /** Another installation, creating the network or a routes file first. */ + raced: { network?: boolean; routes?: string }; + /** A routes write that runs, but whose result the daemon never reports. */ + lost: boolean; +} + +export function fakeShared(): FakeShared { + return { + sites: new Map(), + hosts: new Set(), + running: true, + refuse: null, + execs: [], + created: null, + exists: true, + raced: {}, + lost: false, + }; +} + +export const CADDY = { + Id: 'shared-caddy', + Names: ['/ghost-infra-caddy-1'], + State: 'running', + Status: 'Up 2 minutes (healthy)', + Labels: { + 'org.ghost.docker.managed': 'true', + 'org.ghost.docker.mode': 'infra', + 'com.docker.compose.project': 'ghost-infra', + 'com.docker.compose.project.working_dir': INFRA_DIR, + 'com.docker.compose.service': 'caddy', + }, + Ports: [ + { PrivatePort: 80, PublicPort: 80, Type: 'tcp' }, + { PrivatePort: 443, PublicPort: 443, Type: 'tcp' }, + ], + NetworkSettings: { Networks: { 'ghost-ingress': {} } }, +}; + +/** The daemon's answers about the shared Caddy: its network, and commands run in its container. */ +export function sharedApi(shared: FakeShared) { + let pending: { cmd: string[]; user: string } | null = null; + let status = 0; + return (request: DockerRequest): DockerResponse | undefined => { + const { method, path } = request; + if (path === '/networks/ghost-ingress' && method === 'GET') { + return shared.exists + ? json(200, { + Id: 'ingress-id', + Name: 'ghost-ingress', + Labels: shared.created ?? { + 'org.ghost.docker.infra.dir': INFRA_DIR, + 'org.ghost.docker.infra.project': 'ghost-infra', + }, + }) + : json(404, { message: 'network ghost-ingress not found' }); + } + if (path === '/networks/create' && method === 'POST') { + const body = request.body as { Name: string; Labels: Record }; + assert.equal(body.Name, 'ghost-ingress'); + if (shared.raced.network) { + shared.exists = true; + return json(409, { message: 'network with name ghost-ingress already exists' }); + } + shared.created = body.Labels; + shared.exists = true; + return json(201, { Id: 'ingress-id' }); + } + if (path === '/networks/ghost-ingress' && method === 'DELETE') { + shared.exists = false; + shared.created = null; + return { status: 204, body: Buffer.alloc(0) }; + } + if (path === '/containers/shared-caddy/exec' && method === 'POST') { + const body = request.body as { Cmd: string[]; User?: string }; + pending = { cmd: body.Cmd, user: body.User ?? '' }; + shared.execs.push(pending); + return json(201, { Id: 'exec-1' }); + } + if (path === '/exec/exec-1/start') { + const { stdout, code } = run(shared, pending!); + status = code; + if (shared.lost && pending!.cmd[0] === 'sh' && !pending!.cmd[2]!.includes('grep')) { + return { status: 500, body: Buffer.from('connection reset') }; + } + return { status: 200, body: frame(code === 0 ? 1 : 2, stdout) }; + } + if (path === '/exec/exec-1/json') { + return json(200, { Running: false, ExitCode: status }); + } + return undefined; + }; +} + +/** A command in the shared Caddy's container, done to the fake's files. */ +function run(shared: FakeShared, { cmd }: { cmd: string[] }): { stdout: string; code: number } { + const name = (path: string) => path.replace('/etc/caddy/sites/', ''); + switch (cmd[0]) { + case 'flock': + // Reloads are serialized on the sites' directory. + assert.equal(cmd[1], '/etc/caddy/sites'); + return run(shared, { cmd: cmd.slice(2) }); + case 'wget': { + const routes = [...shared.hosts].map((host) => ({ match: [{ host: [host] }] })); + return { + stdout: JSON.stringify({ apps: { http: { servers: { srv0: { routes } } } } }), + code: 0, + }; + } + case 'ls': + return { + stdout: [...shared.sites.keys()].map((file) => `${file}\n`).join(''), + code: 0, + }; + case 'cat': { + const routes = shared.sites.get(name(cmd[1]!)); + return routes === undefined + ? { stdout: `cat: ${cmd[1]}: No such file`, code: 1 } + : { stdout: routes, code: 0 }; + } + case 'stat': + return { stdout: '1000:1000\n', code: 0 }; + case 'sh': { + // sh -c SCRIPT sh MARKER FILE: removes the file if it is that write's. + if (cmd[2]!.includes('grep')) { + if (shared.sites.get(name(cmd[5]!))?.split('\n')[0] === cmd[4]) { + shared.sites.delete(name(cmd[5]!)); + } + return { stdout: '', code: 0 }; + } + // sh -c SCRIPT sh ROUTES FILE, which never overwrites a file. + if (shared.raced.routes !== undefined) { + shared.sites.set(name(cmd[5]!), shared.raced.routes); + } + if (shared.sites.has(name(cmd[5]!))) { + return { stdout: '', code: 1 }; + } + shared.sites.set(name(cmd[5]!), cmd[4]!); + return { stdout: '', code: 0 }; + } + case 'rm': + shared.sites.delete(name(cmd.at(-1)!)); + return { stdout: '', code: 0 }; + case 'caddy': + if (cmd[1] === 'validate' && shared.refuse !== null) { + return { stdout: shared.refuse, code: 1 }; + } + if (cmd[1] === 'reload') { + // What the files now serve. + shared.hosts = new Set( + [...shared.sites.values()].flatMap( + (routes) => + /^([^\s#{][^{]*)\{/m + .exec(routes)?.[1]! + .split(',') + .map((host) => host.trim()) ?? [], + ), + ); + } + return { stdout: '', code: 0 }; + default: + return { stdout: `unexpected: ${cmd.join(' ')}`, code: 127 }; + } +} diff --git a/manager/test/shared.test.ts b/manager/test/shared.test.ts new file mode 100644 index 00000000..4e6b7817 --- /dev/null +++ b/manager/test/shared.test.ts @@ -0,0 +1,909 @@ +// The shared Caddy, against a scripted daemon and Compose: `install --infra`, +// a production install joining it, the refusals before anything is written, +// and `list`, `check`, `remove` and `config validate` knowing about it. What +// the real Caddy does with the routes is test/integration/shared.test.ts, and +// several sites on one server tests/e2e/shared-caddy.sh. +import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; +import { existsSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { afterEach, beforeEach, describe, test } from 'node:test'; +import * as env from '../src/env.ts'; +import { payloadFiles } from '../src/payload.ts'; +import { layoutOf, readSettings, siteFacts, siteMode } from '../src/site.ts'; +import { verifyIngress } from '../src/verify.ts'; +import { failed, harness, ok, type Harness } from './helpers.ts'; +import { CADDY, fakeShared, sharedApi, type FakeShared } from './shared-caddy.ts'; +import { 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.api = (request) => images(request) ?? caddy(request); + h.daemon.run = rootContainer; + h.daemon.containers = [CADDY]; + h.daemon.composeRun = (args) => { + compose.push(args); + switch (args[0]) { + case 'config': + return ok(JSON.stringify({ services: { ghost: { environment: {} } } })); + case 'ps': + return ok(ps()); + default: + return ok(''); + } + }; +}); +afterEach(() => h.cleanup()); + +const settings = () => env.toRecord(readFileSync(join(h.dir, '.env'), 'utf8')); +const files = () => + readdirSync(h.dir) + .filter((name) => name !== '.ghost-docker-probe') + .sort(); + +describe('install --infra', () => { + beforeEach(() => { + shared.exists = false; + h.daemon.containers = []; + }); + + test('sets up Caddy alone, on a network no project owns, labelled with where it is', async () => { + ps = () => + JSON.stringify({ ID: 'c', Service: 'caddy', State: 'running', Health: 'healthy' }); + const result = await h.run('install', '--infra'); + assert.equal(result.code, 0, result.stderr); + assert.deepEqual(shared.created, { + 'org.ghost.docker.managed': 'true', + 'org.ghost.docker.infra.dir': h.dir, + 'org.ghost.docker.infra.project': 'ghost-infra', + }); + assert.deepEqual( + { + profiles: settings().COMPOSE_PROFILES, + mode: settings().SITE_MODE, + project: settings().COMPOSE_PROJECT_NAME, + network: settings().INGRESS_NETWORK, + external: settings().INGRESS_EXTERNAL, + http: settings().HTTP_PORT, + url: settings().URL, + }, + { + profiles: 'infra', + mode: 'infra', + project: 'ghost-infra', + network: 'ghost-ingress', + external: 'true', + http: '80', + url: undefined, + }, + ); + // Caddy's files, and nothing of a site's: no Ghost or MySQL. + assert.deepEqual(files(), [ + '.env', + '.env.example', + '.ghost-docker.json', + 'caddy', + 'compose.ipv6.yml', + 'compose.yml', + 'ghost-docker', + ]); + const metadata = JSON.parse(readFileSync(join(h.dir, '.ghost-docker.json'), 'utf8')); + assert.equal(metadata.mode, 'infra'); + assert.equal(metadata.ghost, null); + assert.deepEqual(metadata.site, { project: 'ghost-infra', dir: h.dir }); + assert.ok(metadata.payload['caddy/Caddyfile'] && metadata.payload['ghost-docker']); + assert.ok(!Object.keys(metadata.payload).some((file) => file.startsWith('mysql-init/'))); + assert.ok(existsSync(join(h.dir, 'caddy', 'sites'))); + assert.ok(compose.some((args) => args[0] === 'up')); + assert.match(result.stdout, /The shared Caddy is installed/); + }); + + test('a server has one: a second is refused before anything is written', async () => { + shared.exists = true; + const result = await h.run('install', '--infra'); + assert.equal(result.code, 1); + assert.match(result.stderr, /already has the shared Caddy in \/srv\/caddy/); + assert.deepEqual(files(), []); + }); + + test('80 and 443 must be free', async () => { + h.daemon.containers = [{ ...CADDY, Id: 'p', Names: ['/operators-proxy'], Labels: {} }]; + const result = await h.run('install', '--infra'); + assert.equal(result.code, 1); + assert.match( + result.stderr, + /port 80 is already in use by the Docker container operators-proxy/, + ); + assert.equal(shared.created, null); + }); + + test('it takes no site options', async () => { + const result = await h.run( + 'install', + '--infra', + '--domain', + 'example.com', + '--with', + 'activitypub', + ); + assert.equal(result.code, 2); + assert.match( + result.stderr, + /--infra sets up the shared Caddy alone, so it takes no --domain, --with/, + ); + }); + + test('it is Caddy, so it takes no --no-caddy', async () => { + const result = await h.run('install', '--infra', '--no-caddy'); + assert.equal(result.code, 2); + assert.match(result.stderr, /so it takes no --no-caddy/); + }); + + test('a failed start removes the network with everything else', async () => { + h.daemon.composeRun = (args) => + args[0] === 'up' ? failed(1, 'Bind for 0.0.0.0:80 failed') : ok(''); + const result = await h.run('install', '--infra'); + assert.equal(result.code, 1); + assert.equal(shared.exists, false); + assert.deepEqual(files(), []); + }); + + test('a network another installation created meanwhile is not removed', async () => { + shared.raced.network = true; + const result = await h.run('install', '--infra'); + assert.equal(result.code, 1); + assert.equal(shared.exists, true); + assert.deepEqual(files(), []); + }); +}); + +describe('self-update of the shared Caddy', () => { + const FIRST = `sha256:${'2'.repeat(64)}`; + const SECOND = `sha256:${'3'.repeat(64)}`; + let manager: string; + let up: () => ReturnType; + const release = (version: string) => + writeFileSync(h.env.GD_VERSION_FILE!, JSON.stringify({ version, commit: 'c'.repeat(40) })); + const metadata = () => JSON.parse(readFileSync(join(h.dir, '.ghost-docker.json'), 'utf8')); + + beforeEach(async () => { + shared.exists = false; + h.daemon.containers = []; + const stack = h.env.GD_STACK_DIR!; + h.env.GD_VERSION_FILE = `${stack}-version.json`; + manager = FIRST; + const images = imageApi({ manager: () => manager }); + const caddy = sharedApi(shared); + h.daemon.api = (request) => images(request) ?? caddy(request); + up = () => ok(''); + ps = () => + JSON.stringify({ ID: 'c', Service: 'caddy', State: 'running', Health: 'healthy' }); + h.daemon.composeRun = (args) => { + compose.push(args); + switch (args[0]) { + case 'config': + return ok(JSON.stringify({ services: { caddy: {} } })); + case 'ps': + return ok(ps()); + case 'up': + return up(); + default: + return ok(''); + } + }; + release('v0.1.0-beta.1'); + h.env.GD_CHANNEL = 'beta'; + const installed = await h.run('install', '--infra'); + assert.equal(installed.code, 0, installed.stderr); + compose.length = 0; + // The next release: a new image, with a changed snippet. + release('v0.1.0-beta.2'); + manager = SECOND; + writeFileSync(join(stack, 'caddy', 'snippets', 'Logging'), '# changed in beta.2\n'); + }); + + test('moves its files and launcher to the release, and recreates Caddy, with no backup', async () => { + const result = await h.run('self-update'); + assert.equal(result.code, 0, result.stderr); + assert.equal( + readFileSync(join(h.dir, 'caddy', 'snippets', 'Logging'), 'utf8'), + '# changed in beta.2\n', + ); + assert.match( + readFileSync(join(h.dir, 'ghost-docker'), 'utf8'), + new RegExp(`GD_PINNED_IMAGE="${SECOND}"`), + ); + const after = metadata(); + assert.equal(after.mode, 'infra'); + assert.deepEqual(after.stack.previous, { version: 'v0.1.0-beta.1', image: FIRST }); + assert.equal(after.stack.version, 'v0.1.0-beta.2'); + assert.deepEqual( + compose.map((args) => args[0]), + ['pull', 'config', 'up', 'exec', 'ps'], + ); + // Serialized with the sites' route changes. + assert.deepEqual( + compose.find((args) => args[0] === 'exec'), + [ + 'exec', + '-T', + 'caddy', + 'flock', + '/etc/caddy/sites', + 'caddy', + 'reload', + '--config', + '/etc/caddy/Caddyfile', + ], + ); + assert.ok(!existsSync(join(h.dir, 'backups'))); + assert.ok(!existsSync(join(h.dir, '.ghost-docker-update'))); + assert.ok(!existsSync(join(h.dir, '.ghost-docker.lock'))); + assert.match( + result.stdout, + /Updated the shared Caddy from v0\.1\.0-beta\.1 to v0\.1\.0-beta\.2/, + ); + }); + + test('--check says what it would change, and changes nothing', async () => { + const before = readFileSync(join(h.dir, 'caddy', 'snippets', 'Logging'), 'utf8'); + const result = await h.run('self-update', '--check'); + assert.equal(result.code, 0, result.stderr); + assert.match(result.stdout, /An update is available\. Caddy restarts with it\./); + assert.match(result.stdout, /caddy\/snippets\/Logging: replaced/); + assert.equal(readFileSync(join(h.dir, 'caddy', 'snippets', 'Logging'), 'utf8'), before); + assert.deepEqual(compose, []); + }); + + test("an edited file is kept, with the release's beside it", async () => { + writeFileSync(join(h.dir, 'caddy', 'snippets', 'Logging'), '# mine\n'); + const result = await h.run('self-update'); + assert.equal(result.code, 0, result.stderr); + assert.equal(readFileSync(join(h.dir, 'caddy', 'snippets', 'Logging'), 'utf8'), '# mine\n'); + assert.equal( + readFileSync(join(h.dir, 'caddy', 'snippets', 'Logging.new'), 'utf8'), + '# changed in beta.2\n', + ); + }); + + test('a Caddy that does not become healthy is put back on the files it ran', async () => { + const before = readFileSync(join(h.dir, 'caddy', 'snippets', 'Logging'), 'utf8'); + let ups = 0; + up = () => (ups++ === 0 ? failed(1, 'container caddy is unhealthy') : ok('')); + const result = await h.run('self-update'); + assert.equal(result.code, 1); + assert.match(result.stderr, /is back on v0\.1\.0-beta\.1, and running/); + assert.equal(readFileSync(join(h.dir, 'caddy', 'snippets', 'Logging'), 'utf8'), before); + assert.match( + readFileSync(join(h.dir, 'ghost-docker'), 'utf8'), + new RegExp(`GD_PINNED_IMAGE="${FIRST}"`), + ); + assert.equal(metadata().stack.version, 'v0.1.0-beta.1'); + assert.equal(compose.filter((args) => args[0] === 'up').length, 2); + assert.ok(!existsSync(join(h.dir, '.ghost-docker-update'))); + assert.ok(!existsSync(join(h.dir, '.ghost-docker.lock'))); + }); + + test('a configuration Caddy will not reload is put back, and the old one loaded again', async () => { + const before = readFileSync(join(h.dir, 'caddy', 'snippets', 'Logging'), 'utf8'); + let reloads = 0; + h.daemon.composeRun = (args) => { + compose.push(args); + if (args[0] === 'exec') { + return reloads++ === 0 ? failed(1, 'adapting config: unknown directive') : ok(''); + } + if (args[0] === 'config') { + return ok(JSON.stringify({ services: { caddy: {} } })); + } + return args[0] === 'ps' ? ok(ps()) : ok(''); + }; + const result = await h.run('self-update'); + assert.equal(result.code, 1); + assert.match(result.stderr, /did not load its configuration[\s\S]*unknown directive/); + assert.match(result.stderr, /is back on v0\.1\.0-beta\.1, and running/); + assert.equal(readFileSync(join(h.dir, 'caddy', 'snippets', 'Logging'), 'utf8'), before); + assert.equal(reloads, 2); + }); + + test('images it cannot pull refuse the update before any file is written', async () => { + const before = readFileSync(join(h.dir, 'caddy', 'snippets', 'Logging'), 'utf8'); + h.daemon.composeRun = (args) => { + compose.push(args); + return args[0] === 'pull' ? failed(1, 'manifest unknown') : ok(''); + }; + const result = await h.run('self-update'); + assert.equal(result.code, 1); + assert.match(result.stderr, /could not be pulled[\s\S]*Nothing has been changed/); + assert.equal(readFileSync(join(h.dir, 'caddy', 'snippets', 'Logging'), 'utf8'), before); + assert.deepEqual( + compose.map((args) => args[0]), + ['pull'], + ); + assert.equal(metadata().stack.version, 'v0.1.0-beta.1'); + }); + + test("a failure before Caddy restarts reloads the old files, which a site's reload may have replaced", async () => { + const before = readFileSync(join(h.dir, 'caddy', 'snippets', 'Logging'), 'utf8'); + let live = before; + h.daemon.composeRun = (args) => { + compose.push(args); + switch (args[0]) { + case 'config': + // A site installs meanwhile, and its reload loads the + // release's files; then the release does not validate. + live = readFileSync(join(h.dir, 'caddy', 'snippets', 'Logging'), 'utf8'); + return failed(1, 'services.caddy: invalid'); + case 'exec': + live = readFileSync(join(h.dir, 'caddy', 'snippets', 'Logging'), 'utf8'); + return ok(''); + case 'ps': + return ok(ps()); + default: + return ok(''); + } + }; + const result = await h.run('self-update'); + assert.equal(result.code, 1); + assert.match( + result.stderr, + /back on v0\.1\.0-beta\.1, with its configuration loaded again/, + ); + assert.equal(live, before); + assert.equal(compose.filter((args) => args[0] === 'up').length, 0); + assert.deepEqual(compose.at(-1)!.slice(0, 5), [ + 'exec', + '-T', + 'caddy', + 'flock', + '/etc/caddy/sites', + ]); + assert.ok(!existsSync(join(h.dir, '.ghost-docker-update'))); + }); + + test('a Caddy that will not reload the old files is left for the operator', async () => { + h.daemon.composeRun = (args) => { + compose.push(args); + if (args[0] === 'config') { + return failed(1, 'services.caddy: invalid'); + } + return args[0] === 'exec' ? failed(1, 'container caddy is not running') : ok(''); + }; + const result = await h.run('self-update'); + assert.equal(result.code, 1); + assert.match(result.stderr, /Caddy did not load them[\s\S]*not running/); + assert.ok(existsSync(join(h.dir, '.ghost-docker-update', 'files'))); + }); + + test('a Caddy that will not start again either is left for the operator, with the files kept', async () => { + up = () => failed(1, 'Bind for 0.0.0.0:443 failed'); + const result = await h.run('self-update'); + assert.equal(result.code, 1); + assert.match(result.stderr, /Caddy did not start on them[\s\S]*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.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: no Caddy of its own, its routes in the shared Caddy, loaded', async () => { + const result = await h.run( + 'install', + '--domain', + 'example.com', + '--with', + 'activitypub', + '--no-start', + ); + assert.equal(result.code, 0, result.stderr); + const values = settings(); + assert.equal(values.COMPOSE_PROFILES, 'shared-caddy,activitypub'); + assert.equal(values.SITE_MODE, 'production'); + assert.equal(values.INGRESS_NETWORK, 'ghost-ingress'); + assert.equal(values.INGRESS_EXTERNAL, 'true'); + assert.equal(values.HTTP_PORT, undefined); + assert.ok(!existsSync(join(h.dir, 'caddy')), 'a site behind it has no caddy/ of its own'); + const routes = shared.sites.get('ghost-example-com.caddy')!; + assert.match(routes, /^example\.com \{$/m); + assert.match(routes, /reverse_proxy ghost-ghost-example-com:2368/); + assert.match(routes, /ActivityPub activitypub-ghost-example-com:8080/); + // Written as whoever owns caddy/sites/, then validated, then loaded. + const commands = shared.execs.map( + ({ cmd, user }) => `${cmd[0]} ${cmd[1]}${user ? ` as ${user}` : ''}`, + ); + assert.deepEqual(commands.slice(-4), [ + 'stat -c', + 'sh -c as 1000:1000', + 'caddy validate', + 'flock /etc/caddy/sites', + ]); + assert.ok(shared.hosts.has('example.com')); + const metadata = JSON.parse(readFileSync(join(h.dir, '.ghost-docker.json'), 'utf8')); + assert.equal(metadata.mode, 'production'); + assert.ok(!Object.keys(metadata.payload).some((file) => file.startsWith('caddy/'))); + assert.match( + result.stdout, + /Routes +\/srv\/caddy\/caddy\/sites\/ghost-example-com\.caddy, served by the shared Caddy/, + ); + }); + + test('80 and 443 are the shared Caddy’s, and not asked for', async () => { + const result = await h.run('install', '--domain', 'example.com', '--no-start'); + assert.equal(result.code, 0, result.stderr); + }); + + test('a domain it already serves is refused before anything is written', async () => { + shared.hosts.add('www.example.com'); + const result = await h.run( + 'install', + '--domain', + 'blog.example.com', + '--admin-domain', + 'www.example.com', + '--no-start', + ); + assert.equal(result.code, 1); + assert.match(result.stderr, /already serves www\.example\.com/); + assert.deepEqual(files(), []); + assert.equal(shared.sites.size, 0); + }); + + test('a project that already has routes is refused before anything is written', async () => { + shared.sites.set('ghost-example-com.caddy', 'routes of another directory'); + const result = await h.run('install', '--domain', 'example.com', '--no-start'); + assert.equal(result.code, 1); + assert.match( + result.stderr, + /ghost-example-com\.caddy already exists: the project ghost-example-com already has routes/, + ); + assert.match(result.stderr, /--name/); + assert.deepEqual(files(), []); + assert.equal(shared.sites.get('ghost-example-com.caddy'), 'routes of another directory'); + }); + + test('routes another installation wrote meanwhile are refused, and left alone', async () => { + shared.raced.routes = 'routes of another directory'; + const result = await h.run('install', '--domain', 'example.com', '--no-start'); + assert.equal(result.code, 1); + assert.match(result.stderr, /could not be written to the shared Caddy/); + assert.equal(shared.sites.get('ghost-example-com.caddy'), 'routes of another directory'); + assert.deepEqual(files(), []); + }); + + test('routes written with no result reported are still undone, by their marker', async () => { + shared.lost = true; + const result = await h.run('install', '--domain', 'example.com', '--no-start'); + assert.equal(result.code, 1); + assert.match(result.stderr, /could not be written to the shared Caddy/); + assert.equal(shared.sites.size, 0); + assert.deepEqual(files(), []); + }); + + test("another's routes are left alone when a write's result is unknown", async () => { + shared.lost = true; + shared.raced.routes = 'routes of another directory'; + const result = await h.run('install', '--domain', 'example.com', '--no-start'); + assert.equal(result.code, 1); + assert.equal(shared.sites.get('ghost-example-com.caddy'), 'routes of another directory'); + }); + + test('a stopped shared Caddy is refused, saying how to start it', async () => { + h.daemon.containers = [{ ...CADDY, State: 'exited' }]; + const result = await h.run('install', '--domain', 'example.com', '--no-start'); + assert.equal(result.code, 1); + assert.match( + result.stderr, + /the shared Caddy in \/srv\/caddy is not running[\s\S]*cd \/srv\/caddy && docker compose up -d/, + ); + assert.deepEqual(files(), []); + }); + + test('routes Caddy refuses are removed with everything else the installation created', async () => { + shared.refuse = 'Error: adapting config using caddyfile: ambiguous site definition'; + // Removed once, by addRoutes: the file is then not this install's to undo. + const removals = () => shared.execs.filter(({ cmd }) => cmd[0] === 'rm').length; + const result = await h.run('install', '--domain', 'example.com', '--no-start'); + assert.equal(result.code, 1); + assert.match( + result.stderr, + /does not accept its configuration[\s\S]*ambiguous site definition/, + ); + assert.equal(shared.sites.size, 0); + assert.deepEqual(files(), []); + assert.equal(removals(), 1); + }); + + test('a local site never joins it', async () => { + const result = await h.run('install', '--local', '--no-start'); + assert.equal(result.code, 0, result.stderr); + assert.equal(settings().COMPOSE_PROFILES, 'local'); + assert.equal(settings().INGRESS_NETWORK, undefined); + assert.deepEqual(shared.execs, []); + }); + + test('a site behind your own proxy never joins it', async () => { + const result = await h.run( + 'install', + '--domain', + 'example.com', + '--no-caddy', + '--no-start', + ); + assert.equal(result.code, 0, result.stderr); + assert.equal(settings().COMPOSE_PROFILES, 'no-caddy'); + assert.equal(settings().INGRESS_NETWORK, undefined); + assert.deepEqual(shared.execs, []); + assert.equal(shared.sites.size, 0); + }); +}); + +describe('a server without one', () => { + test('a production site gets a Caddy and a network of its own, as before', async () => { + shared.exists = false; + h.daemon.containers = []; + const result = await h.run('install', '--domain', 'example.com', '--no-start'); + assert.equal(result.code, 0, result.stderr); + assert.equal(settings().COMPOSE_PROFILES, 'production'); + assert.equal(settings().INGRESS_NETWORK, undefined); + assert.ok(existsSync(join(h.dir, 'caddy', 'sites', 'site.caddy'))); + }); +}); + +/** A .env behind the shared Caddy, as install writes it. */ +const sharedCaddyEnv = (project = 'ghost-example-com') => + writeFileSync( + join(h.dir, '.env'), + env.serializeAll([ + ['COMPOSE_PROFILES', 'shared-caddy'], + ['SITE_MODE', 'production'], + ['COMPOSE_PROJECT_NAME', project], + ['PROJECT_DIR', h.dir], + ['URL', 'https://example.com'], + ['GHOST_VERSION', '6-next-alpine'], + ['DATABASE_PASSWORD', 'a'], + ['DATABASE_ROOT_PASSWORD', 'b'], + ['INGRESS_NETWORK', 'ghost-ingress'], + ['INGRESS_EXTERNAL', 'true'], + ]), + { mode: 0o600 }, + ); + +describe('remove', () => { + test("a site's routes are removed and the shared Caddy reloaded, then the site is taken down", async () => { + sharedCaddyEnv(); + shared.sites.set('ghost-example-com.caddy', 'example.com {\n}\n'); + shared.sites.set('ghost-other-com.caddy', 'other.com {\n}\n'); + const result = await h.run('remove', '--yes'); + assert.equal(result.code, 0, result.stderr); + assert.deepEqual([...shared.sites.keys()], ['ghost-other-com.caddy']); + assert.deepEqual(shared.execs.map(({ cmd }) => cmd[0]).slice(-2), ['rm', 'flock']); + assert.ok(compose.some((args) => args[0] === 'down' && !args.includes('--volumes'))); + assert.ok(existsSync(join(h.dir, '.env')), 'the directory and its data stay'); + assert.match(result.stdout, /still holds its configuration, data and backups/); + }); + + test('a server whose shared Caddy is gone is refused, as its routes cannot be removed', async () => { + sharedCaddyEnv(); + shared.exists = false; + const result = await h.run('remove', '--yes'); + assert.equal(result.code, 1); + assert.match(result.stderr, /this server has none \(no ghost-ingress network\)/); + assert.ok(!compose.some((args) => args[0] === 'down')); + }); + + test('a failed docker compose down says the routes are already gone', async () => { + sharedCaddyEnv(); + shared.sites.set('ghost-example-com.caddy', 'example.com {\n}\n'); + h.daemon.composeRun = (args) => (args[0] === 'down' ? failed(1, 'daemon gone') : ok('')); + const result = await h.run('remove', '--yes'); + assert.equal(result.code, 1); + assert.match(result.stderr, /Its routes are already gone from the shared Caddy/); + assert.equal(shared.sites.size, 0); + }); + + test('it is asked, or --yes says so', async () => { + sharedCaddyEnv(); + shared.sites.set('ghost-example-com.caddy', 'x'); + const result = await h.run('remove'); + assert.equal(result.code, 2); + assert.match(result.stderr, /Run it again with --yes/); + assert.equal(shared.sites.size, 1); + assert.ok(!compose.some((args) => args[0] === 'down')); + }); + + test('the shared Caddy itself is not a site', async () => { + writeFileSync( + join(h.dir, '.env'), + env.serializeAll([ + ['COMPOSE_PROFILES', 'infra'], + ['SITE_MODE', 'infra'], + ]), + ); + const result = await h.run('remove', '--yes'); + assert.equal(result.code, 1); + assert.match(result.stderr, /holds the shared Caddy, not a site/); + }); +}); + +describe('verification', () => { + const answer = { + status: 200, + body: JSON.stringify({ site: { url: 'https://example.com/' } }), + location: null, + certificate: { + issuer: "Let's Encrypt", + covers: true, + validTo: '2027-01-07T12:00:00.000Z', + expired: false, + untrusted: null, + }, + }; + + test("a site behind it is asked for through the shared Caddy, whose routes file is this site's", async () => { + sharedCaddyEnv(); + shared.sites.set('ghost-example-com.caddy', 'example.com {\n}\n'); + ps = () => + JSON.stringify({ ID: 'g', Service: 'ghost', State: 'running', Health: 'healthy' }); + h.daemon.https = ({ host, servername }) => { + assert.equal(host, 'caddy-ghost-example-com'); + assert.equal(servername, 'example.com'); + return answer; + }; + const checks = await verifyIngress(h.io(), siteFacts(h.dir, readSettings(h.dir)!)); + const by = Object.fromEntries(checks.map((check) => [check.label, check])); + assert.equal(by['shared caddy']?.status, 'ok'); + assert.equal(by.routes?.status, 'ok'); + assert.match(by.routes!.detail, /\/srv\/caddy\/caddy\/sites\/ghost-example-com\.caddy/); + assert.equal(by.https?.status, 'ok', by.https?.detail ?? ''); + assert.match( + by['published ports']!.detail, + /the shared Caddy on 0\.0\.0\.0:80, 0\.0\.0\.0:443/, + ); + }); + + test('routes that are gone, or a shared Caddy that is gone, are errors', async () => { + sharedCaddyEnv(); + ps = () => + JSON.stringify({ ID: 'g', Service: 'ghost', State: 'running', Health: 'healthy' }); + h.daemon.https = () => answer; + let checks = await verifyIngress(h.io(), siteFacts(h.dir, readSettings(h.dir)!)); + assert.match( + checks.find((check) => check.label === 'routes')!.detail, + /ghost-example-com\.caddy does not exist/, + ); + shared.exists = false; + checks = await verifyIngress(h.io(), siteFacts(h.dir, readSettings(h.dir)!)); + const missing = checks.find((check) => check.label === 'shared caddy')!; + assert.equal(missing.status, 'error'); + assert.match(missing.detail, /this server has none/); + }); +}); + +describe('list', () => { + test('shows the shared Caddy and the sites behind it', async () => { + h.daemon.containers = [ + CADDY, + { + Id: 'm', + Names: ['/ghost-example-com-ghost-1'], + Labels: { + 'org.ghost.docker.managed': 'true', + 'org.ghost.docker.mode': 'production', + 'com.docker.compose.project': 'ghost-example-com', + }, + Ports: [], + NetworkSettings: { + Networks: { 'ghost-example-com_ghost_network': {}, 'ghost-ingress': {} }, + }, + }, + { + Id: 's', + Names: ['/ghost-solo-com-ghost-1'], + Labels: { + 'org.ghost.docker.managed': 'true', + 'org.ghost.docker.mode': 'production', + 'com.docker.compose.project': 'ghost-solo-com', + }, + Ports: [], + NetworkSettings: { Networks: { 'ghost-solo-com_ingress': {} } }, + }, + ]; + h.daemon.composeRun = (args) => + args[0] === 'ls' + ? ok( + JSON.stringify( + ['ghost-infra', 'ghost-example-com', 'ghost-solo-com'].map((name) => ({ + Name: name, + Status: 'running(1)', + ConfigFiles: `/srv/${name}/compose.yml`, + })), + ), + ) + : undefined; + const result = await h.run('list'); + assert.equal(result.code, 0, result.stderr); + assert.match(result.stdout, /^ghost-example-com +shared-caddy /m); + assert.match(result.stdout, /^ghost-infra +infra /m); + assert.match(result.stdout, /^ghost-solo-com +production /m); + assert.match(result.stdout, /shared-caddy is a production site behind the shared Caddy/); + }); +}); + +describe('config validate', () => { + test("the shared Caddy's .env needs no Ghost, but its network", async () => { + writeFileSync( + join(h.dir, '.env'), + env.serializeAll([ + ['COMPOSE_PROFILES', 'infra'], + ['SITE_MODE', 'infra'], + ['COMPOSE_PROJECT_NAME', 'ghost-infra'], + ['PROJECT_DIR', h.dir], + ['INGRESS_NETWORK', 'ghost-ingress'], + ['INGRESS_EXTERNAL', 'true'], + ]), + { mode: 0o600 }, + ); + const valid = await h.run('config', 'validate'); + assert.equal(valid.code, 0, valid.stdout + valid.stderr); + assert.match(valid.stdout, /valid for the shared Caddy/); + + writeFileSync( + join(h.dir, '.env'), + env.serializeAll([ + ['COMPOSE_PROFILES', 'infra,activitypub'], + ['SITE_MODE', 'infra'], + ['COMPOSE_PROJECT_NAME', 'ghost-infra'], + ['PROJECT_DIR', h.dir], + ]), + { mode: 0o600 }, + ); + const invalid = await h.run('config', 'validate'); + assert.equal(invalid.code, 1); + assert.match(invalid.stdout + invalid.stderr, /runs Caddy alone: remove activitypub/); + assert.match( + invalid.stdout + invalid.stderr, + /INGRESS_NETWORK is required for the shared Caddy/, + ); + assert.match(invalid.stdout + invalid.stderr, /INGRESS_EXTERNAL must be true/); + }); + + test('a site behind it is a production site, and must be on the shared network', async () => { + sharedCaddyEnv(); + const valid = await h.run('config', 'validate'); + assert.equal(valid.code, 0, valid.stdout + valid.stderr); + assert.match(valid.stdout, /valid for a production site/); + + const values = settings(); + delete values.INGRESS_EXTERNAL; + writeFileSync(join(h.dir, '.env'), env.serializeAll(Object.entries(values)), { + mode: 0o600, + }); + const invalid = await h.run('config', 'validate'); + assert.equal(invalid.code, 1); + assert.match(invalid.stdout + invalid.stderr, /INGRESS_EXTERNAL must be true/); + + writeFileSync( + join(h.dir, '.env'), + env.serializeAll( + Object.entries({ ...values, INGRESS_EXTERNAL: 'true', INGRESS_NETWORK: 'other' }), + ), + { mode: 0o600 }, + ); + const elsewhere = await h.run('config', 'validate'); + assert.equal(elsewhere.code, 1); + assert.match( + elsewhere.stdout + elsewhere.stderr, + /INGRESS_NETWORK must be ghost-ingress, the shared Caddy's network: got other/, + ); + }); + + test('a site needs its database passwords, which compose.yml no longer guards', async () => { + sharedCaddyEnv(); + const values = settings(); + delete values.DATABASE_ROOT_PASSWORD; + writeFileSync(join(h.dir, '.env'), env.serializeAll(Object.entries(values)), { + mode: 0o600, + }); + const result = await h.run('config', 'validate'); + assert.equal(result.code, 1); + assert.match(result.stdout + result.stderr, /DATABASE_ROOT_PASSWORD is required/); + }); +}); + +describe('the pieces', () => { + test('shared-caddy selects production; infra selects no site mode', () => { + assert.equal(siteMode('shared-caddy,activitypub'), 'production'); + assert.equal(siteMode('shared-caddy,production'), null); + assert.equal(siteMode('infra'), null); + assert.equal(layoutOf('shared-caddy,analytics'), 'shared-caddy'); + assert.equal(layoutOf('infra'), 'infra'); + assert.equal(layoutOf('production'), 'production'); + assert.equal(layoutOf('local,mailpit'), 'local'); + }); + + test("each layout's stack files", () => { + const stack = h.env.GD_STACK_DIR!; + const tops = (layout: Parameters[1]) => [ + ...new Set(payloadFiles(stack, layout).map((file) => file.split('/')[0])), + ]; + assert.deepEqual(tops('infra'), [ + '.env.example', + 'caddy', + 'compose.ipv6.yml', + 'compose.yml', + ]); + assert.ok(!tops('shared-caddy').includes('caddy')); + assert.ok(tops('shared-caddy').includes('tinybird')); + assert.ok(tops('production').includes('caddy')); + }); +}); diff --git a/tests/e2e/shared-caddy.sh b/tests/e2e/shared-caddy.sh new file mode 100755 index 00000000..e7f09059 --- /dev/null +++ b/tests/e2e/shared-caddy.sh @@ -0,0 +1,267 @@ +#!/usr/bin/env bash +# Several production sites behind one shared Caddy, against real containers. +# +# tests/e2e/shared-caddy.sh +# +# Builds the manager image from this checkout, sets up the shared Caddy with +# `install --infra`, and installs two production sites behind it: one on +# Ghost 6.61.0 with ActivityPub, one on the newest Ghost 6, each with its own +# MySQL. Caddy serves them with its own test CA under names curl resolves to +# this host. A third site asking for a domain the shared Caddy already serves +# is refused before anything is written. Then each operation on one site is +# checked to leave the other as it was, the same containers serving the same +# routes: updating the first site's Ghost, backing it up and restoring it over +# itself, restarting and recreating the shared Caddy (both sites come back), +# and removing the second site, whose routes go with it, then restoring it +# from its backup, which holds them. The shared Caddy's +# own directory answers self-update; moving it between releases is unit-tested. +# +# It pulls images, starts containers and binds ports 80 and 443 (it fails +# when something else holds them, or is skipped with GD_E2E_ALLOW_SKIP=1). It +# needs jq and curl. Exits non-zero at the first check that fails, naming it. +set -euo pipefail + +ROOT=$(CDPATH='' cd -- "$(dirname -- "$0")/../.." && pwd -P) +IMAGE=ghost-docker:e2e-shared-caddy +FROM=6.61.0 +DOMAIN_A=alpha-e2e.test +DOMAIN_B=bravo-e2e.test + +# What this host cannot run fails the run, unless GD_E2E_ALLOW_SKIP=1. +# shellcheck source=/dev/null +source "$ROOT/tests/e2e/lib.sh" +require_docker +port_free() { ! (exec 3<>"/dev/tcp/127.0.0.1/$1") 2>/dev/null; } +if ! port_free 80 || ! port_free 443; then + skip "something on this host already holds 80 or 443" + passed "Nothing ran: the shared Caddy is on 80 and 443." + exit 0 +fi +if docker network inspect ghost-ingress >/dev/null 2>&1; then + skip "this daemon already has a shared Caddy (the network ghost-ingress)" + passed "Nothing ran: a daemon has one shared Caddy." + exit 0 +fi +for tool in jq curl; do + command -v "$tool" >/dev/null || { + printf 'shared-caddy.sh needs %s\n' "$tool" >&2 + exit 1 + } +done + +work_dir shared-caddy +SITES=() +SITE="" + +# The members first, then the shared Caddy and its network, then every +# directory, removed as root: MySQL's data belongs to MySQL's user. +teardown() { + local site + for site in ${SITES[@]+"${SITES[@]}"}; do + [[ -f $site/.env ]] && docker compose --project-directory "$site" -f "$site/compose.yml" \ + down --volumes --remove-orphans --timeout 5 >/dev/null 2>&1 + done + [[ -f ${CADDY:-}/.env ]] && docker compose --project-directory "$CADDY" -f "$CADDY/compose.yml" \ + down --volumes --remove-orphans --timeout 5 >/dev/null 2>&1 + docker network rm ghost-ingress >/dev/null 2>&1 + docker run --rm --user 0 --entrypoint rm -v "$WORK:/work" "$IMAGE" -rf /work/sites >/dev/null 2>&1 +} + +on_fail() { + [[ -z ${CADDY:-} ]] || docker compose --project-directory "$CADDY" -f "$CADDY/compose.yml" \ + logs --no-color --tail 40 caddy >&2 2>&1 || true +} + +# gd SITE ARGS... -- a site's own launcher, on the image built here. +gd() { GD_IMAGE=$IMAGE "$1/ghost-docker" --dir "$@"; } + +# through DOMAIN -- what Ghost's site endpoint answers for DOMAIN, through the +# shared Caddy on this host's port 443, trusting its test CA as told to. +through() { + curl --disable --silent --insecure --noproxy '*' --max-time 20 --resolve "$1:443:127.0.0.1" \ + "https://$1/ghost/api/admin/site/" | jq -r '.site.url' 2>/dev/null || true +} + +# serves DOMAIN -- Ghost for DOMAIN answers through the shared Caddy, waiting +# for Caddy's certificate and for Ghost to boot. +serves() { + local tries=0 + until [[ $(through "$1") == "https://$1/" ]]; do + tries=$((tries + 1)) + ((tries < 90)) || fail "Ghost for $1 does not answer through the shared Caddy" "$(through "$1")" + sleep 2 + done +} + +# containers SITE -- each of the site's containers, with when it started. +containers() { + compose_in "$1" ps --all -q | sort | xargs docker inspect --format '{{.Id}} {{.State.StartedAt}}' +} + +# routes -- the shared Caddy's routes files, with their checksums. +routes() { (cd "$CADDY/caddy/sites" && find . -type f | sort | xargs shasum -a 256); } + +# untouched SITE BEFORE -- SITE's containers are the ones there were, as they were. +untouched() { + [[ $(containers "$1") == "$2" ]] || fail "$(basename "$1")'s containers changed" "$(containers "$1")" +} + +printf 'Docker: %s on %s\n' "$(docker info --format '{{.OperatingSystem}}')" "$(uname -s)" + +step "Build the manager image, and set up the shared Caddy" +run docker build --quiet --file "$ROOT/manager/Dockerfile" --tag "$IMAGE" "$ROOT" +expect_status 0 +mkdir -p "$WORK/launcher-only" "$WORK/sites/caddy/caddy/global" +cp "$ROOT/ghost-docker" "$WORK/launcher-only/ghost-docker" +CADDY=$WORK/sites/caddy +# Caddy's own CA for the names, at once: a test fixture standing in for the +# CA a real domain gets. +printf 'local_certs\n' >"$CADDY/caddy/global/test-ca.caddy" +run env GD_IMAGE=$IMAGE "$WORK/launcher-only/ghost-docker" --dir "$CADDY" install --infra +expect_status 0 +expect_output 'The shared Caddy is installed' +[[ $(setting "$CADDY" COMPOSE_PROFILES) == infra ]] || fail "the shared Caddy's profiles are not infra" +[[ ! -e $CADDY/ghost.env && ! -e $CADDY/mysql-init && ! -e $CADDY/data ]] || fail "the shared Caddy has a site's files" +[[ $(docker network inspect ghost-ingress --format '{{index .Labels "org.ghost.docker.infra.dir"}}') == "$CADDY" ]] || + fail "the network does not say where the shared Caddy is" +[[ $(compose_in "$CADDY" ps --format '{{.Service}} {{.Health}}') == 'caddy healthy' ]] || + fail "Caddy is not the only service, or not healthy" "$(compose_in "$CADDY" ps)" +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 'served by the shared Caddy' +new_site bravo +B=$SITE +run env GD_IMAGE=$IMAGE "$WORK/launcher-only/ghost-docker" --dir "$B" install --domain "$DOMAIN_B" --no-prompt +expect_status 0 +for site in "$A" "$B"; do + [[ $(setting "$site" COMPOSE_PROFILES) == shared-caddy* ]] || fail "$site is not behind the shared Caddy" + [[ ! -e $site/caddy ]] || fail "$site has a Caddy of its own" + [[ -z $(compose_in "$site" ps -q caddy) ]] || fail "$site runs a Caddy" + [[ -n $(compose_in "$site" ps -q db) ]] || fail "$site has no MySQL of its own" +done +[[ -f $CADDY/caddy/sites/ghost-alpha-e2e-test.caddy && -f $CADDY/caddy/sites/ghost-bravo-e2e-test.caddy ]] || + fail "the routes are not in the shared Caddy" "$(ls "$CADDY/caddy/sites")" +[[ -n $(compose_in "$A" ps -q activitypub) ]] || fail "alpha's ActivityPub is not running" +version_a=$(compose_in "$A" exec -T ghost printenv GHOST_VERSION) +version_b=$(compose_in "$B" exec -T ghost printenv GHOST_VERSION) +[[ $version_a == "$FROM" && $version_b != "$FROM" ]] || fail "the sites run $version_a and $version_b" +serves "$DOMAIN_A" +serves "$DOMAIN_B" +for site in "$A" "$B"; do + run gd "$site" check + expect_status 0 + expect_output 'shared caddy +healthy' + expect_output 'routes +.*\.caddy, in the shared Caddy' +done +run gd "$A" list +expect_status 0 +expect_output '^ghost-infra +infra ' +expect_output '^ghost-alpha-e2e-test +shared-caddy ' +expect_output '^ghost-bravo-e2e-test +shared-caddy ' +ok "alpha on Ghost $version_a with ActivityPub, bravo on Ghost $version_b; both served, check passes" + +step "A domain the shared Caddy serves is refused before anything is written" +new_site charlie +run env GD_IMAGE=$IMAGE "$WORK/launcher-only/ghost-docker" --dir "$SITE" install --domain "www.$DOMAIN_B" \ + --admin-domain "$DOMAIN_A" --no-prompt +expect_status 1 +expect_output "already serves $DOMAIN_A" +[[ -z $(find "$SITE" -mindepth 1 -not -name .ghost-docker-probe) ]] || + fail "the refused install wrote into its directory" "$(ls -A "$SITE")" +ok "refused, and $SITE is empty" + +before_b=$(containers "$B") +routes_before=$(routes) + +step "Updating alpha's Ghost leaves bravo untouched" +run gd "$A" update +expect_status 0 +expect_output "Updated Ghost from $FROM to " +[[ $(compose_in "$A" exec -T ghost printenv GHOST_VERSION) != "$FROM" ]] || fail "alpha still runs $FROM" +serves "$DOMAIN_A" +untouched "$B" "$before_b" +[[ $(routes) == "$routes_before" ]] || fail "the routes changed" "$(routes)" +[[ $(through "$DOMAIN_B") == "https://$DOMAIN_B/" ]] || fail "bravo no longer answers" +ok "alpha updated; bravo's containers and every route as they were" + +step "Backing alpha up and restoring it over itself leaves bravo untouched" +run gd "$A" backup +expect_status 0 +backup=$(find "$A/backups" -mindepth 1 -maxdepth 1 | sort | tail -1) +jq -e '.routes == "routes.caddy"' "$backup/manifest.json" >/dev/null || + fail "the backup does not hold alpha's routes" "$(cat "$backup/manifest.json")" +[[ $(tail -n +2 "$CADDY/caddy/sites/ghost-alpha-e2e-test.caddy") == "$(cat "$backup/routes.caddy")" ]] || + fail "the backup's routes are not alpha's, without their marker line" "$(cat "$backup/routes.caddy")" +run gd "$A" restore --yes "$backup" +expect_status 0 +serves "$DOMAIN_A" +untouched "$B" "$before_b" +[[ $(routes) == "$routes_before" ]] || fail "the routes changed" "$(routes)" +ok "restored $(basename "$backup"); bravo's containers and every route as they were" + +step "Restarting, and recreating, the shared Caddy brings both back" +before_a=$(containers "$A") +compose_in "$CADDY" restart caddy >/dev/null 2>&1 || fail "Caddy did not restart" +serves "$DOMAIN_A" +serves "$DOMAIN_B" +out=$(compose_in "$CADDY" down 2>&1) || fail "the shared Caddy did not come down" "$out" +docker network inspect ghost-ingress >/dev/null 2>&1 || fail "taking the shared Caddy down removed its network" +compose_in "$CADDY" up --detach --wait >/dev/null 2>&1 || fail "the shared Caddy did not start again" +serves "$DOMAIN_A" +serves "$DOMAIN_B" +untouched "$A" "$before_a" +untouched "$B" "$before_b" +ok "both answer after a restart and after down and up; neither site's containers changed" + +step "Removing bravo removes its routes, and leaves alpha untouched" +run gd "$B" backup +expect_status 0 +backup_b=$(find "$B/backups" -mindepth 1 -maxdepth 1 | sort | tail -1) +run gd "$B" remove +expect_status 2 +expect_output 'Run it again with --yes' +run gd "$B" remove --yes +expect_status 0 +[[ ! -e $CADDY/caddy/sites/ghost-bravo-e2e-test.caddy ]] || fail "bravo's routes are still there" +[[ -f $CADDY/caddy/sites/ghost-alpha-e2e-test.caddy ]] || fail "alpha's routes went too" +[[ -z $(compose_in "$B" ps --all -q) ]] || fail "bravo's containers are still there" +[[ -f $B/.env ]] || fail "bravo's directory was not kept" +[[ $(through "$DOMAIN_B") != "https://$DOMAIN_B/" ]] || fail "bravo still answers" +serves "$DOMAIN_A" +untouched "$A" "$before_a" +run gd "$A" list +expect_output '^ghost-alpha-e2e-test +shared-caddy ' +refute_output 'ghost-bravo-e2e-test' +ok "bravo removed with its routes; alpha's containers as they were, and served" + +step "Restoring bravo's backup writes its routes back" +run gd "$B" restore --yes "$backup_b" +expect_status 0 +expect_output "the backup's, written to" +[[ -f $CADDY/caddy/sites/ghost-bravo-e2e-test.caddy ]] || fail "bravo's routes were not written back" +serves "$DOMAIN_B" +serves "$DOMAIN_A" +untouched "$A" "$before_a" +ok "bravo restored behind the shared Caddy, with the routes its backup held; alpha untouched" + +passed 'All shared Caddy checks passed.'