diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 0fa16728..d6bae3f0 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -135,6 +135,11 @@ updates: interval: weekly cooldown: default-days: 3 + # PostgreSQL majors move data (docs/RUNNING.md, "PostgreSQL 18"): a new major needs a + # written migration, and the 17 dump one-shot must stay on 17. + ignore: + - dependency-name: "postgres" + update-types: ["version-update:semver-major"] groups: actions: patterns: ["*"] @@ -150,15 +155,25 @@ updates: interval: weekly cooldown: default-days: 3 + # PostgreSQL majors move data (docs/RUNNING.md, "PostgreSQL 18"): a new major needs a + # written migration, and the 17 dump one-shot must stay on 17. + ignore: + - dependency-name: "postgres" + update-types: ["version-update:semver-major"] commit-message: prefix: "chore(deps)" - # Pinned images in the optional compose files (rspamd). + # Pinned images in the optional compose files (rspamd, the replica overlay's PostgreSQL). - package-ecosystem: docker-compose directory: / schedule: interval: weekly cooldown: default-days: 3 + # PostgreSQL majors move data (docs/RUNNING.md, "PostgreSQL 18"): a new major needs a + # written migration, and the 17 dump one-shot must stay on 17. + ignore: + - dependency-name: "postgres" + update-types: ["version-update:semver-major"] commit-message: prefix: "chore(deps)" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 64c0507c..7b8f35b2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -273,7 +273,7 @@ jobs: # The store, backup, restore and migration suites, the poller, and internal/api (held and # scheduled sends live in its global state store), again with every store on a - # Postgres 17 service (UTF8, C locale, as docs/RUNNING.md requires). Each test opens + # Postgres 18 service (UTF8, C locale, as docs/RUNNING.md requires). Each test opens # a schema of its own (dbbackend's test hook); tests about SQLite files skip, visibly # in -v output. internal/api is sharded by test name as in backend-api-test. backend-postgres-test: @@ -287,7 +287,7 @@ jobs: leg: [stores, api-1, api-2] services: postgres: - image: postgres:17@sha256:3b0cda93be7c8dba2ed484d19393d93845dc3dafb88973e248ba8e6d99d784e1 + image: postgres:18.7-trixie@sha256:c699303802144847d238196173655dbbecf7a96aeca1565f2b02eb671a1f0b6b env: POSTGRES_HOST_AUTH_METHOD: trust POSTGRES_INITDB_ARGS: --locale=C --encoding=UTF8 @@ -769,6 +769,12 @@ jobs: - name: replica cutover (SQLite -> PostgreSQL -> two replicas) run: bash scripts/check-replica-cutover.sh kypost-server:ci + # The replica overlay's PostgreSQL, seeded on 17 with the previous compose files, moves + # to 18 on the next up -d over the running 17; a dump beside a live 17 refuses; passwords + # from another container; rollback, rerun, a bad dump and a fresh install. Needs no image. + - name: replica PostgreSQL 17 -> 18 upgrade + run: bash scripts/test-postgres-17-to-18.sh + - name: container logs if: always() run: | diff --git a/CHANGELOG.md b/CHANGELOG.md index ab011a94..0617681e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,7 @@ non-prerelease version. ## Unreleased - In table mode (not startable yet), skip the one-host boot-ID and volume-ID checks and refuse to start instead while any store still lives on the host's disk; refuse a plain listener, a database URL without `sslmode=verify-full` or with unbounded dead-connection keepalives off loopback, cleartext Ollama, push relays or KyIdentity, and `ALLOW_INSECURE_SMTP`. Ordinary installs are unchanged. +- Move the replica overlay's database to PostgreSQL 18. An install on 17 moves by itself on the next `up`: a one-shot dumps the 17 volume, which is kept for rollback, and 18 restores it once before starting. Needs about twice the data in free space; see [PostgreSQL 18](docs/RUNNING.md#postgresql-18). CI now tests on PostgreSQL 18. - CI now runs the poller and health tests on PostgreSQL, and fails when a package whose tests use the database is left out of the PostgreSQL job. The quiet-mailbox tests now check that PostgreSQL mailboxes are polled on every pass, as documented, instead of expecting the SQLite-only skip. - Share the proof-of-work escalation across table-mode replicas, and run one mail import or export per organization at a time across replicas on a multi-tenant server. Single installs are unchanged. - In table mode, claim each incoming message across hosts before the poller works on it, so a daemon resuming after a freeze and the new owner never both label, record and push one message; the own-address send-as probe is mailed once. Ordinary installs are unchanged. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b4aee49e..8c274062 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -170,11 +170,11 @@ if a job is genuinely flaky, that is a bug to fix in the job. |---|---| | `ci-backend-api` | `gofmt -l`, `go vet`, two builds of the release binary that must be byte-identical, `golangci-lint`, `govulncheck`, `deadcode` (nothing unreachable from `cmd/` beyond `backend/deadcode.allow`), `go test -race ./internal/api/...`, then again with `GODEBUG=fips140=on` ([strong-key profile](docs/STRONG-CRYPTO.md)) | | `ci-backend-other` | Same lint gates, `go test -race` on every other backend package, again with `GODEBUG=fips140=on`, then 20-second fuzz runs for rules, redaction, reply threading and IMAP header records | -| `ci-backend-postgres` | `go test -race` on the store, backup, restore and migration packages, the poller (`internal/processor`), `internal/health` and `internal/api` (two shards) with every store on a digest-pinned `postgres:17` service (UTF8, C locale) through `KYPOST_TEST_DATABASE_URL`; the stores leg fails when a package whose tests import `dbbackend` is not on its list; green only when every leg (`ci-backend-postgres (stores)`, `(api-1)`, `(api-2)`) passed | +| `ci-backend-postgres` | `go test -race` on the store, backup, restore and migration packages, the poller (`internal/processor`), `internal/health` and `internal/api` (two shards) with every store on a digest-pinned `postgres:18` service (UTF8, C locale) through `KYPOST_TEST_DATABASE_URL`; the stores leg fails when a package whose tests import `dbbackend` is not on its list; green only when every leg (`ci-backend-postgres (stores)`, `(api-1)`, `(api-2)`) passed | | `ci-frontend` | `npm audit --omit=dev --audit-level=low` (blocking), `tsc --noEmit`, ESLint (rules-of-hooks errors block), `vitest`, `vite build` | | `ci-relay` | Typecheck both relay Workers, `node --test` on the relay and one-message receiving Worker behaviour suites, disposable workerd/R2 capture and pickup qualification | | `ci-scripts` | Shell syntax and shellcheck, CI Go/Node pins equal the Dockerfile builder tags, the `.env.example`-reaches-Compose and `supervisord.conf` log-file checks, setup-wizard definition-only input/dotenv/Compose checks, receiver launcher refusal checks, pinned Rspamd effective-config/socket/clean/GTUBE/privacy qualification, the `update-host` and model-installer self-checks, `compose config`, the strong-key overlay changing nothing but `GODEBUG`, the cumulative Supervisor shutdown budget, the live-main publish-gate regression, and the workflow shape assertions that keep the release and `:main` publish gates from being quietly deleted | -| `ci-docker` | `docker build`, private-root real-entrypoint regression, real Supervisor serial-drain regression, container reaches `healthy` with the optional receiver stopped by default, and the entrypoint still refuses a non-loopback cleartext bind | +| `ci-docker` | `docker build`, private-root real-entrypoint regression, real Supervisor serial-drain regression, container reaches `healthy` with the optional receiver stopped by default, the entrypoint still refuses a non-loopback cleartext bind, the replica cutover, and the replica overlay's PostgreSQL 17 → 18 move on real data (`scripts/test-postgres-17-to-18.sh`) | Notes that trip people up: diff --git a/backend/AGENTS.md b/backend/AGENTS.md index 00524a6e..81698c7e 100644 --- a/backend/AGENTS.md +++ b/backend/AGENTS.md @@ -605,7 +605,7 @@ This list is the CI gate. `ci-backend-checks` runs the static steps, the release - `go list -deps -test ./... | grep '^golang.org/x/crypto/openpgp'` must print nothing (`ci-backend-checks`). `osv-scanner.toml` ignores GO-2026-5932 (x/crypto/openpgp unmaintained) only because of this; PGP uses `github.com/ProtonMail/go-crypto`. Never import x/crypto/openpgp; if that changes, drop the ignore - `go tool -modfile=../tools/go.mod deadcode -test=false ./cmd/...` (`ci-backend-checks`) must report exactly the functions `deadcode.allow` lists. Delete code nothing in `cmd/` reaches; test-only code goes in a `_test.go` file or a `*test` package (`pgpmail/pgpmailtest`, `sso/ssotest`). The allow list is only for hooks other packages' tests call to reach unexported state - `go build -buildvcs=false ./...` must succeed with zero errors -- With a throwaway `postgres:17` (UTF8, C locale), `KYPOST_TEST_DATABASE_URL=postgres://postgres@localhost:5432/postgres?sslmode=disable go test -race -count=1 -timeout=30m -p 2 ./internal/dbbackend/... ./internal/state/... ./internal/mailbox/... ./internal/ingress/... ./internal/cfreceiving/... ./internal/sso/... ./internal/backup/... ./internal/app/... ./internal/worker/... ./internal/replica/... ./internal/mfa/... ./internal/captcha/... ./internal/kycalendar/... ./internal/suitepair/... ./internal/tenancy/... ./internal/vol/... ./internal/volumes/... ./internal/users/... ./internal/contacts/... ./internal/processor/... ./internal/health/...` must pass, and so must `go test -race -count=1 -timeout=30m ./internal/api/` with the same variable (`ci-backend-postgres`, which shards `internal/api` in two, and fails its stores leg when a package whose tests import `dbbackend` is missing from that list): every store runs on Postgres, one schema per test path; tests about SQLite files, WAL or restore staging skip and say so in `-v` output. Without the variable those Postgres-only tests skip. +- With a throwaway `postgres:18` (UTF8, C locale), `KYPOST_TEST_DATABASE_URL=postgres://postgres@localhost:5432/postgres?sslmode=disable go test -race -count=1 -timeout=30m -p 2 ./internal/dbbackend/... ./internal/state/... ./internal/mailbox/... ./internal/ingress/... ./internal/cfreceiving/... ./internal/sso/... ./internal/backup/... ./internal/app/... ./internal/worker/... ./internal/replica/... ./internal/mfa/... ./internal/captcha/... ./internal/kycalendar/... ./internal/suitepair/... ./internal/tenancy/... ./internal/vol/... ./internal/volumes/... ./internal/users/... ./internal/contacts/... ./internal/processor/... ./internal/health/...` must pass, and so must `go test -race -count=1 -timeout=30m ./internal/api/` with the same variable (`ci-backend-postgres`, which shards `internal/api` in two, and fails its stores leg when a package whose tests import `dbbackend` is missing from that list): every store runs on Postgres, one schema per test path; tests about SQLite files, WAL or restore staging skip and say so in `-v` output. Without the variable those Postgres-only tests skip. - `go test -race -count=1 -timeout=20m ./...` must pass. The sorter parity test and the poller's hybrid tests skip unless `EMBED_MODEL_DIR` points at the pinned model; the `ci-backend-other` legs download it using the Dockerfile's `EMBED_*` ARG pins, so set it locally too or those tests prove nothing. The `-timeout` is not optional: `internal/api` alone exceeds Go's default 600s under `-race`, which is why CI splits it into its own shards and passes `-timeout=20m`. Running plain `go test -race ./...` locally reports a timeout that CI would not see - `GOTOOLCHAIN=go1.26.9 go test -race ./internal/sso ./internal/api -run '^TestReleaseFloor' -count=1` checks monotonic durable release floors, the refusal rule, snapshot validation, webhook refusal of stale activations while queued deletions apply, direct allocation refusal, unchanged active rows passing, and the worker quietly refusing administrator provisioning, unpublished allocation and reallocation of a repaired account while the disable path converges. diff --git a/docker-compose.replicas.yml b/docker-compose.replicas.yml index 8e57f3e6..21cc14e0 100644 --- a/docker-compose.replicas.yml +++ b/docker-compose.replicas.yml @@ -54,9 +54,31 @@ services: ollama: condition: service_started + # PostgreSQL 17 installs move to 18 on the next `up`: this one-shot dumps the 17 volume + # (kypost_pgdata, only read) into the 18 volume once, and the 18 service restores it before + # it starts (docs/RUNNING.md, "PostgreSQL 18"). Fresh installs have nothing to dump. + postgres-17-dump: + image: postgres:17.12-alpine3.24@sha256:f9cf3e1f0066f0eb0c48707d864f0ac5941e9ff454a072077d97a4d278d07d73 + restart: "no" + network_mode: none + # A SIGKILLed 17 leaves postmaster.pid, which the dump then refuses. + stop_grace_period: 2m + entrypoint: ["bash", "/ky/postgres-17-to-18.sh", "dump"] + environment: + POSTGRES_USER: kypost + OLD: /var/lib/postgresql/data + NEW: /pg18 + volumes: + - kypost_pgdata:/var/lib/postgresql/data + - kypost_postgres:/pg18 + - ./scripts/postgres-17-to-18.sh:/ky/postgres-17-to-18.sh:ro + postgres: - image: postgres:17-alpine@sha256:526f86d93c6ea08fd3f1fe5605650cacc781b2c6013169a0ad8f42c7d3d84f32 + image: postgres:18.7-alpine3.24@sha256:0115267ab5a509022df9319c77be365cef335adb71556c75f60f5360ee247e71 restart: unless-stopped + stop_grace_period: 2m + # Restores the 17 dump once, if there is one, then runs the image's own entrypoint. + entrypoint: ["bash", "/ky/postgres-17-to-18.sh", "restore"] environment: POSTGRES_USER: kypost POSTGRES_PASSWORD: ${KYPOST_POSTGRES_PASSWORD:?Set KYPOST_POSTGRES_PASSWORD in .env; there is no default} @@ -66,15 +88,21 @@ services: # Room for KYPOST_REPLICAS times the per-replica budget in docs/RUNNING.md. command: ["postgres", "-c", "max_connections=${KYPOST_POSTGRES_MAX_CONNECTIONS:-400}"] volumes: - - kypost_pgdata:/var/lib/postgresql/data + - kypost_postgres:/var/lib/postgresql + - ./scripts/postgres-17-to-18.sh:/ky/postgres-17-to-18.sh:ro healthcheck: - # The entrypoint's temporary initialization server has only a Unix socket. + # The entrypoint's temporary initialization and restore servers have only a Unix socket. test: ["CMD", "pg_isready", "-h", "127.0.0.1", "-U", "kypost", "-d", "kypost"] interval: 2s timeout: 2s retries: 15 + # A restore from 17 takes time in proportion to the data. + start_period: 1h networks: - database + depends_on: + postgres-17-dump: + condition: service_completed_successfully ollama: image: ollama/ollama:0.40.17@sha256:ccc42bcd3d5fcf7ab0d532b300382154e1a4da56fc666bdb313b78ebdd912754 @@ -112,7 +140,9 @@ services: ipv4_address: ${KYPOST_PROXY_IP:?Set KYPOST_PROXY_IP to the proxy address inside KYPOST_REPLICA_SUBNET} volumes: + # PostgreSQL 17's data, kept for rollback; remove it by hand once 18 checks out. kypost_pgdata: + kypost_postgres: networks: replicas: diff --git a/docs/RUNNING.md b/docs/RUNNING.md index ce446464..8a31dd9d 100644 --- a/docs/RUNNING.md +++ b/docs/RUNNING.md @@ -393,6 +393,61 @@ change: stop every replica, then run once with the new settings, and start again. The full list is in [CONFIGURATION.md](CONFIGURATION.md#replicas). +### PostgreSQL 18 + +The overlay's database is PostgreSQL 18. An install that ran 17 (its data is in the +`kypost_pgdata` volume) moves to 18 by itself on the next `up` after `git pull`; the script +it uses, `scripts/postgres-17-to-18.sh`, is mounted from your checkout. Run the usual upgrade, +`docker compose pull && docker compose stop kypost-server && docker compose up -d --wait`: + +1. The one-shot `postgres-17-dump` service (the 17 image, no network) starts 17 on + `kypost_pgdata` with a private socket, runs `pg_dumpall` into the new `kypost_postgres` + volume (`upgrade-from-17/dump.sql`) and stops 17. It writes nothing into `kypost_pgdata`; + 17 may replay its own log while it starts. +2. The `postgres` service (18) restores that dump into `18/docker.part`, renames it to + `18/docker` once complete and then starts as usual. Roles, passwords and the C/UTF8 + locale come across, so `KYPOST_DATABASE_URL` stays the same. The replicas wait until it + is healthy. + +Each step runs once: later `up`s see `18/docker` and do nothing. `docker compose ps -a` then +lists `postgres-17-dump` as `Exited (0)`, which is its healthy, finished state. A fresh install has nothing +to move and initialises 18 directly (the `kypost_pgdata` volume then stays empty). + +- **Disk:** about twice the 17 data free on the volumes' filesystem (the dump plus the new + cluster). With less, the dump stops with a message naming both sizes and writes nothing; + free space and `up` again. +- **Time:** a full dump, a reload and `ANALYZE`, so it grows with the data. The healthcheck + allows an hour before a failure counts; follow it with `docker compose logs -f postgres`. +- **If it fails:** the 18 service never starts on an empty or half-restored database. A + restore cut short is redone from the start on the next start. The logs name the error, and + `kypost_pgdata` is unchanged, so you can roll back. If 17 is still running on + `kypost_pgdata`, or was killed without a clean stop, the dump finds its `postmaster.pid` + and refuses: `up` stops 17 itself first, and both services get two minutes to shut down. + After a crash, start 17 once with the previous release and stop it, then `up` again. +- **Rollback:** stop every replica and `docker compose stop postgres`, check out the release + you came from (its `docker-compose.replicas.yml` runs 17 on `kypost_pgdata`) and + `docker compose up -d --wait`. Anything written on 18 is not in the 17 data. +- **Back to 18 after a rollback:** once 17 has run, the next `up` with this release stops + before 18 starts: the dump (`docker compose logs postgres-17-dump`) says 17 has run since + the move, because 18 lacks what 17 wrote since. This holds after the clean-up of the dump + too: the move's record, `18/moved-from-17.checkpoint`, sits beside the 18 cluster. Nothing + is deleted. Choose one, then `docker compose down` (keeps volumes) and `up` again: + - **Move 17 again** (keeps what 17 wrote, loses what was written on 18 before the + rollback): rename the old 18 cluster aside, `docker compose run --rm --no-deps + --entrypoint sh postgres -c 'mv /var/lib/postgresql/18 /var/lib/postgresql/18.replaced && + mv /var/lib/postgresql/upgrade-from-17 /var/lib/postgresql/upgrade-from-17.replaced'` + (leave out the second `mv` if you already removed the dump). The next `up` dumps and + restores 17 as the first time did. + - **Keep 18 as it is** (what 17 wrote since stays only in `kypost_pgdata`): + `docker compose run --rm --no-deps --entrypoint rm postgres /var/lib/postgresql/18/moved-from-17.checkpoint`. +- **Clean-up**, your choice, once 18 has checked out (sign in, read mail, run **Back up + now**): stop the stack (`docker compose down`, which keeps volumes), then remove the dump, + `docker compose run --rm --no-deps --entrypoint rm postgres -r /var/lib/postgresql/upgrade-from-17`, + which is safe and keeps rollback. Removing the 17 volume (`docker volume rm + _kypost_pgdata`) is a separate step; once it is gone, rollback means restoring a + backup. Nothing removes either automatically, nor the `18.replaced` and + `upgrade-from-17.replaced` directories a second move leaves (`rm -r` them the same way). + ### Restoring a replica deployment Restore into a new, empty database beside the old one, which stays untouched until the diff --git a/scripts/AGENTS.md b/scripts/AGENTS.md index 6a092080..c4ab4793 100644 --- a/scripts/AGENTS.md +++ b/scripts/AGENTS.md @@ -24,6 +24,7 @@ All files under `scripts/`. - `start-ollama.sh`: launches Ollama daemon on port 11434 - `pull-ollama-model.sh`: pulls the model named by `OLLAMA_MODEL` (docker-compose default: `nemotron-3-nano:4b`); requires Ollama daemon to be running first. It owns retries for an unwritable models dir, an unanswered Ollama API and a failed pull (15–60s backoff, then every 900s), exiting 0 once installed. Supervisor restarts unexpected exits only (`autorestart=unexpected`, `exitcodes=0`, `startsecs=0`). Keep the retry loop in-script so an ordinary pull failure never restarts the container. The daemon's classifier warm-up pulls only when `/api/show` says the model is missing, because a pre-populated cache the container cannot write is supported. Classification being down is reported as `classifierFailing` in `GET /api/health`, not as an unhealthy container. - `update-host.sh`: runs only on the Docker host. It refuses the replica overlay (it would recreate replicas in place, mixing versions) and prints the documented upgrade commands. It resolves the official image to a digest, verifies its GitHub attestation, locks, waits for health, and recreates the prior digest if the new container fails. It recreates with the compose files recorded on the running container (`com.docker.compose.project.config_files`, minus its own deleted `.kypost-update.*.yml` override; else `COMPOSE_FILE`, else the base file) so overlays survive, and re-points the local tag at the deployed digest after an update, a rollback or an already-current run so a plain `docker compose up -d` cannot downgrade. It never enters the image or receives the Docker socket. +- `postgres-17-to-18.sh`: the shared Ky PostgreSQL 17 → 18 kit, vendored byte for byte (`check-replicas-compose.py` pins its SHA-256; never edit it here, fix the kit and re-vendor). The replica overlay runs it twice: `dump` in the one-shot `postgres-17-dump` (17 image, no network), which dumps the kept 17 volume once into the 18 volume, and `restore` as the 18 service's entrypoint, which restores that dump into `18/docker.part`, renames it into place and execs the image's entrypoint. It never deletes or writes the 17 data. Since kit v3 the dump records 17's last checkpoint and refuses once 17 has run since (a rollback), naming the two operator choices in RUNNING.md. Kit v4 keeps it at `18/moved-from-17.checkpoint`, beside the 18 cluster, so removing `upgrade-from-17/` keeps it. - `test-relays.sh`: the canonical Cloudflare Worker test command, run by CI and by `npm test` in both push Worker packages. It discovers `*.test.mts` and `*.test.mjs` under `push-relay-shared/`, `worker/src/`, `worker-apns/src/` and `receiving-worker/`; it prunes `node_modules` and fails when it finds nothing. Install `worker/` dependencies first: the FCM key-floor fixture executes its locked native workerd with an explicit isolated provider service. - `install-auto-update.sh`: explicitly enables lingering, then installs a daily per-user systemd timer that calls `update-host.sh --auto`; it is opt-in and runs as the user already authorized to operate Docker, never as root from a mutable checkout. @@ -77,7 +78,8 @@ All files under `scripts/`. - `sh -n scripts/crash-exit.sh` parses; `docker compose config -q` fails without `KYPOST_BIND` and succeeds with it - `bash -n scripts/update-host.sh scripts/install-auto-update.sh` parses and `bash scripts/update-host.test.sh` covers no-op (bare-hex Compose IDs), overlay-preserving update with tag move, health-failure rollback and the replica overlay's refusal without Docker; do not run the installer in CI because it enables user lingering via `loginctl` and installs live units under `${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user` - `shellcheck scripts/*.sh` is clean (CI); silence a finding only with a targeted `# shellcheck disable=` naming the reason. `#!/bin/sh` scripts must also pass `sh -n` under dash -- `python3 scripts/check-replicas-compose.py` (ci-scripts) renders `docker-compose.yml` + `docker-compose.replicas.yml` with synthetic inputs, starting nothing: each required variable is named when missing; `KYPOST_REPLICAS` applies; no fixed name or app port; the three shared data volumes plus a per-container logs volume; PostgreSQL 17 digest-pinned, C/UTF8, internal network, no host port, operator password; HAProxy probes `/readyz` each second (2 fails, 2 passes) and its `set-timeout` rules equal docs/RUNNING.md's proxy table; `KYPOST_BIND` gates the proxy publish; no database URL in any argv; and the receiving, rspamd and lan-dns overlays refuse to render with it (their `x-single-container` guard on `KYPOST_PROXY_IP`). It also renders the hosted receiving profile: `docker-compose.hosted.yml` after the replica chain (each variable named when missing; two `receiving serve --tls` servers on the shared volumes, read-only and capability-free, published only on `KYPOST_RECEIVING_PUBLISH_IP`; each Rspamd in its own server's network namespace with the image pinned exactly as in `docker-compose.rspamd.yml`; no replica runs Maddy) and `docker-compose.mx.yml` alone (Maddy only, read-only binds, no volume, database or scanner). +- `bash scripts/test-postgres-17-to-18.sh` (ci-docker) seeds real 17 data with the previous commit's compose files (fetched by SHA); checks that a `run` of the dump beside the live 17 refuses on its `postmaster.pid` and writes nothing; then `up -d`s this tree's replica overlay database over the still-running 17 (no `down`) and asserts the dump ran, 18 with every row, both roles' passwords from another container on the database network (loopback inside the server is trust) with a wrong one refused, and the C/UTF8 locale; that the previous files still start 17 on the kept volume; that after a row written on 17 the next `up` refuses (the kit's `18/moved-from-17.checkpoint`), 18 stays down, RUNNING.md's "move 17 again" renames bring the row to 18 and keep `18.replaced` with its checkpoint, and "keep 18" (delete the checkpoint) is accepted and sticks; that another `up` neither dumps nor restores again; that a corrupt dump fails every start without ever creating `18/docker`; that after the documented clean-up of `upgrade-from-17/` (17 kept) 18 still starts and a later rollback that writes on 17 is still refused; that removing the 17 volume leaves 18 running; and that a fresh install initialises 18. It starts only the database services of its own projects. +- `python3 scripts/check-replicas-compose.py` (ci-scripts) renders `docker-compose.yml` + `docker-compose.replicas.yml` with synthetic inputs, starting nothing: each required variable is named when missing; `KYPOST_REPLICAS` applies; no fixed name or app port; the three shared data volumes plus a per-container logs volume; PostgreSQL 18 digest-pinned with the 17 dump one-shot (both images, the mounts, a 2m `stop_grace_period` on both and the vendored kit's checksum), C/UTF8, internal network, no host port, operator password; HAProxy probes `/readyz` each second (2 fails, 2 passes) and its `set-timeout` rules equal docs/RUNNING.md's proxy table; `KYPOST_BIND` gates the proxy publish; no database URL in any argv; and the receiving, rspamd and lan-dns overlays refuse to render with it (their `x-single-container` guard on `KYPOST_PROXY_IP`). It also renders the hosted receiving profile: `docker-compose.hosted.yml` after the replica chain (each variable named when missing; two `receiving serve --tls` servers on the shared volumes, read-only and capability-free, published only on `KYPOST_RECEIVING_PUBLISH_IP`; each Rspamd in its own server's network namespace with the image pinned exactly as in `docker-compose.rspamd.yml`; no replica runs Maddy) and `docker-compose.mx.yml` alone (Maddy only, read-only binds, no volume, database or scanner). - `bash scripts/check-replica-cutover.sh ` (ci-docker; shellcheck-clean) drives the documented replica cutover with a built image: SQLite seed (sign-in, first-run password change, `testdata/cutover-recovery-public.b64` pinned; `testdata/cutover-recovery-test-shares.txt` is its throwaway 2-of-3 kit), a clean stop with no `-wal`, `migrate-to-postgres --check` then the copy with the source digest unchanged and a repeat refused, two replicas behind HAProxy on a fixed loopback port, one sign-in proven on both replicas, the client address (a direct caller's forged `CF-Connecting-IP` dropped; the edge proxy's used, reaching HAProxy as `KyPost-Server`), one replica stopped with exit 0, Back up now and `backup-drill`, an upgrade's stop-and-start timed, KyPost's 503 page with every replica down, RUNNING.md's restore into a new empty database then sign-in, a container with a fresh config volume refused, and a changed `SERVER_BASE_URL` named in `docker compose logs`. Its own project, network and volumes are removed on exit; no relay, AI or outside host. `scripts/replica-cutover-client.py` is its stdlib HTTP client (derives the auth secret as the browser does; prints no secret). - `scripts/entrypoint.sh` creates `/run/kypost` for supervisord's per-container socket and pid, leaves a data root alone when it is already `kypost:kypost` `0700` (replicas share the volumes), and starts no bundled Ollama when `OLLAMA_BASE_URL` is not loopback. - `python3 scripts/check-strong-crypto-compose.py` renders five Compose chains with and without `docker-compose.strong-crypto.yml` and fails unless the only difference is `GODEBUG=fips140=on` on `kypost-server`. It starts nothing. diff --git a/scripts/check-replicas-compose.py b/scripts/check-replicas-compose.py index 570b502f..d21fbb73 100755 --- a/scripts/check-replicas-compose.py +++ b/scripts/check-replicas-compose.py @@ -59,12 +59,32 @@ def compose(chain, env): assert set(db["networks"]) == {"database"} and doc["networks"]["database"].get("internal") is True, "PostgreSQL is not on an internal network only" assert db["environment"]["POSTGRES_PASSWORD"] == required["KYPOST_POSTGRES_PASSWORD"], "PostgreSQL password is not the operator's" assert db["environment"]["POSTGRES_INITDB_ARGS"] == "--locale=C --encoding=UTF8" -assert re.fullmatch(r"postgres:17[\w.-]*@sha256:[0-9a-f]{64}", db["image"]), db["image"] +# PostgreSQL 18, moving a 17 volume on the first up (scripts/postgres-17-to-18.sh, the shared +# Ky kit, byte for byte; scripts/test-postgres-17-to-18.sh runs it). +kit = "/ky/postgres-17-to-18.sh" +assert hashlib.sha256((root / "scripts/postgres-17-to-18.sh").read_bytes()).hexdigest() == "195ae8684e34dd515158a88b1f76b918cf6e3f3c854ce83fe4fb190a5178cf06", \ + "scripts/postgres-17-to-18.sh differs from the shared Ky kit" +mounts = lambda svc: sorted((v.get("source", "").rsplit("/scripts/", 1)[-1], v["target"], bool(v.get("read_only"))) for v in svc["volumes"]) +assert db["image"] == "postgres:18.7-alpine3.24@sha256:0115267ab5a509022df9319c77be365cef335adb71556c75f60f5360ee247e71", db["image"] +assert "PGDATA" not in db["environment"], "PGDATA set: 18 keeps its data in /var/lib/postgresql/18/docker" +assert mounts(db) == [("kypost_postgres", "/var/lib/postgresql", False), ("postgres-17-to-18.sh", kit, True)], f"PostgreSQL 18 mounts {db['volumes']}" +assert db["entrypoint"] == ["bash", kit, "restore"] and db["command"][0] == "postgres", (db["entrypoint"], db["command"]) +assert db["depends_on"]["postgres-17-dump"]["condition"] == "service_completed_successfully", "18 starts before the 17 dump finished" +assert db["healthcheck"]["start_period"] == "1h0m0s", "a long restore would mark PostgreSQL unhealthy" +dump = services["postgres-17-dump"] +# A SIGKILLed 17 leaves postmaster.pid, which the kit's dump refuses. +assert db.get("stop_grace_period") == dump.get("stop_grace_period") == "2m0s", "PostgreSQL or the 17 dump can be SIGKILLed mid-shutdown" +assert dump["image"] == "postgres:17.12-alpine3.24@sha256:f9cf3e1f0066f0eb0c48707d864f0ac5941e9ff454a072077d97a4d278d07d73", dump["image"] +assert dump["entrypoint"] == ["bash", kit, "dump"] and dump["network_mode"] == "none" and dump["restart"] == "no", "the 17 dump is not an offline one-shot" +assert dump["environment"] == {"POSTGRES_USER": db["environment"]["POSTGRES_USER"], "OLD": "/var/lib/postgresql/data", "NEW": "/pg18"}, dump["environment"] +assert mounts(dump) == [("kypost_pgdata", "/var/lib/postgresql/data", False), ("kypost_postgres", "/pg18", False), ("postgres-17-to-18.sh", kit, True)], f"17 dump mounts {dump['volumes']}" +assert not any("kypost_pgdata" == v.get("source") for name, svc in services.items() if name != "postgres-17-dump" for v in svc.get("volumes", [])), \ + "only the 17 dump may mount the 17 volume" for name, svc in [("proxy", proxy), ("ollama", ollama)]: assert re.search(r"@sha256:[0-9a-f]{64}$", svc["image"]), f"{name} image is not pinned by digest" assert [p["host_ip"] for p in proxy["ports"]] == [required["KYPOST_BIND"]] and proxy["ports"][0]["target"] == 5866, "KYPOST_BIND does not gate the proxy publish" assert proxy["networks"]["replicas"]["ipv4_address"] == required["KYPOST_PROXY_IP"] -print("PASS replicas: PostgreSQL 17 digest-pinned, C/UTF8, internal network, no host port, operator password; KYPOST_BIND gates the proxy") +print("PASS replicas: PostgreSQL 18 digest-pinned, the 17 volume moved by the kit's one-shot dump and restore, C/UTF8, internal network, no host port, operator password; KYPOST_BIND gates the proxy") # No service carries the database URL in argv; the replicas read it from their environment. for name, svc in services.items(): diff --git a/scripts/postgres-17-to-18.sh b/scripts/postgres-17-to-18.sh new file mode 100755 index 00000000..263b42f8 --- /dev/null +++ b/scripts/postgres-17-to-18.sh @@ -0,0 +1,107 @@ +#!/bin/bash +# Moves a PostgreSQL 17 data directory to 18 by dump and restore. The 17 data is only read +# (starting 17 may replay its WAL); it is never deleted or reinitialised. +# dump in the postgres:17 image. OLD = the 17 data directory, NEW = the directory that the +# 18 container mounts at /var/lib/postgresql. Dumps OLD once into NEW/upgrade-from-17. +# restore in the postgres:18 image, as its entrypoint: restores that dump once into +# $PGDATA.part, renames it to $PGDATA, then runs the image's entrypoint with the args. +# Runs as root (compose) or as the postgres user (Kubernetes runAsUser 70). +set -Eeuo pipefail +mode=${1:-}; shift || true +new=${NEW:-/var/lib/postgresql} +dump_dir=$new/upgrade-from-17 +# 17's checkpoint as the dump left it. Beside the 18 cluster, so removing the dump keeps it, and +# renaming 18/ to move again takes it along. +moved=$new/18/moved-from-17.checkpoint +as_pg() { if [ "$(id -u)" = 0 ]; then gosu postgres "$@"; else "$@"; fi; } +sock=$(mktemp -d) +[ "$(id -u)" != 0 ] || chown postgres "$sock" + +case $mode in +dump) + old=${OLD:?set OLD to the PostgreSQL 17 data directory} + checkpoint() { LC_ALL=C as_pg pg_controldata "$old" | awk -F': *' '/^Latest checkpoint location/ { print $2 }'; } + # PostgreSQL's own lock check cannot see a server in another container (its PID 1 looks + # like our grandparent), so a 17 still running on OLD would get a second postmaster. + refuse_running() { + echo "postgres-17-to-18: $old/postmaster.pid exists: PostgreSQL 17 is running on it, or did not stop cleanly; stop it (start it once with the previous setup and stop it, if it crashed), then start again" >&2 + exit 1 + } + if [ -s "$new/18/docker/PG_VERSION" ] || [ -s "$dump_dir/dump.sql" ]; then + if [ ! -s "$old/PG_VERSION" ]; then echo "postgres-17-to-18: already done"; exit 0; fi + [ ! -e "$old/postmaster.pid" ] || refuse_running + # Moved by kit v2, which kept no checkpoint: take the current one as the moved state. + [ -s "$moved" ] || { mkdir -p "$(dirname "$moved")"; checkpoint > "$moved"; } + # Every start of 17 writes a new checkpoint. A changed one means 17 ran after the move (a + # rollback), so 18 lacks what 17 wrote since: never start 18 on it silently. + if [ "$(checkpoint)" = "$(cat "$moved")" ]; then echo "postgres-17-to-18: already done"; exit 0; fi + echo "postgres-17-to-18: PostgreSQL 17 has run on $old since it was moved to 18, so 18 lacks what 17 wrote since then. To move 17 again: stop everything, rename $new/18 (and $dump_dir, if it is there) with a suffix such as .replaced (nothing is deleted), then start again. To keep 18 as it is: delete $moved, then start again." >&2 + exit 1 + fi + if [ ! -s "$old/PG_VERSION" ]; then + echo "postgres-17-to-18: no PostgreSQL 17 data in $old, nothing to move"; exit 0 + fi + if [ "$(cat "$old/PG_VERSION")" != 17 ]; then + echo "postgres-17-to-18: $old holds PostgreSQL $(cat "$old/PG_VERSION"), expected 17" >&2; exit 1 + fi + [ ! -e "$old/postmaster.pid" ] || refuse_running + # The dump and the restored cluster each take at most about the size of the 17 data. + need=$(( $(du -sk "$old" | cut -f1) * 2 )) + free=$(df -Pk "$new" | awk 'NR == 2 { print $4 }') + if [ "$free" -lt "$need" ]; then + echo "postgres-17-to-18: $new has $((free / 1024)) MiB free, the move needs $((need / 1024)) MiB; free space or grow the volume, then start again" >&2 + exit 1 + fi + mkdir -p "$dump_dir" + [ "$(id -u)" != 0 ] || chown postgres "$new" "$dump_dir" + # No network, and a private socket that only trusts local connections. + printf 'local all all trust\n' > "$sock/hba" + [ "$(id -u)" != 0 ] || chown postgres "$sock/hba" + as_pg pg_ctl -D "$old" -w -t 3600 -l "$sock/log" \ + -o "-c listen_addresses= -c unix_socket_directories=$sock -c hba_file=$sock/hba" start || + { cat "$sock/log" >&2; exit 1; } + trap 'as_pg pg_ctl -D "$old" -m fast -w stop' EXIT + su=$(as_pg psql -h "$sock" -U "${POSTGRES_USER:-postgres}" -d template1 -XAtc "select rolname from pg_roles where oid = 10") + printf '%s\n' "$su" > "$dump_dir/superuser" + as_pg pg_dumpall -h "$sock" -U "$su" -f "$dump_dir/dump.sql.part" + as_pg sync "$dump_dir/dump.sql.part" + trap - EXIT + as_pg pg_ctl -D "$old" -m fast -w stop + mkdir -p "$new/18" + [ "$(id -u)" != 0 ] || chown postgres "$new/18" + checkpoint > "$moved" + mv "$dump_dir/dump.sql.part" "$dump_dir/dump.sql" + sync "$dump_dir" + echo "postgres-17-to-18: dumped $old into $dump_dir/dump.sql; the 17 data is kept" + ;; +restore) + final=${PGDATA:?} + if [ ! -s "$final/PG_VERSION" ] && [ -s "$dump_dir/dump.sql" ]; then + # shellcheck source=/dev/null # the image's entrypoint, only inside the postgres image + source /usr/local/bin/docker-entrypoint.sh + # initdb's superuser is the 17 cluster's bootstrap role, so the dump's roles map one to one. + POSTGRES_USER=$(cat "$dump_dir/superuser") + export POSTGRES_USER PGDATA=$final.part + rm -rf "$PGDATA" # a restore an earlier start did not finish; never the 17 data + docker_setup_env + docker_create_db_directories + as_pg bash -c 'source /usr/local/bin/docker-entrypoint.sh; docker_setup_env; docker_init_database_dir; pg_setup_hba_conf' + as_pg pg_ctl -D "$PGDATA" -w -o "-c listen_addresses= -c unix_socket_directories=$sock" start + # pg_dumpall writes CREATE ROLE for the role it ran as, which initdb already made: drop that + # one line, only in the roles section above the first \connect (row data comes later). + q=$(as_pg psql -h "$sock" -U "$POSTGRES_USER" -d postgres -XAtc "select quote_ident(current_user)") + awk -v skip="CREATE ROLE $q;" 'seen || $0 != skip { print } /^\\connect / { seen = 1 }' "$dump_dir/dump.sql" | + as_pg psql -h "$sock" -U "$POSTGRES_USER" -d postgres -X -q -v ON_ERROR_STOP=1 + as_pg vacuumdb -h "$sock" -U "$POSTGRES_USER" --all --analyze-only -q + as_pg pg_ctl -D "$PGDATA" -m fast -w stop + sync "$PGDATA" + mv "$PGDATA" "$final" + sync "$(dirname "$final")" + export PGDATA=$final + echo "postgres-17-to-18: restored $dump_dir/dump.sql into $final" + fi + rm -rf "$sock" + exec docker-entrypoint.sh "$@" + ;; +*) echo "usage: postgres-17-to-18.sh dump | restore postgres [args...]" >&2; exit 2 ;; +esac diff --git a/scripts/test-postgres-17-to-18.sh b/scripts/test-postgres-17-to-18.sh new file mode 100755 index 00000000..1cb8c61a --- /dev/null +++ b/scripts/test-postgres-17-to-18.sh @@ -0,0 +1,191 @@ +#!/usr/bin/env bash +# Proves the replica overlay's PostgreSQL 17 -> 18 move (docs/RUNNING.md, "PostgreSQL 18") on +# real data: a dump beside a running 17 refuses and writes nothing; the next `up -d` over a +# running 17 stack, seeded with the previous compose files, comes up on 18 with its rows, roles, +# passwords (a wrong one refused) and C locale; the 17 volume still starts 17 (rollback); back +# on 18 after writing on 17, the dump refuses and 18 stays down; the documented "move again" +# brings that row to 18 and keeps the replaced 18, and "keep 18" is accepted; a further `up` +# is a no-op; a dump that fails to restore never yields a cluster; after the documented clean-up +# of the dump (17 kept) 18 still starts and a later rollback is still refused; removing the 17 +# volume leaves 18 running; a fresh install initialises. Starts only the database services +# of its own Compose projects and removes them, their volumes and networks on exit. +# +# Usage: scripts/test-postgres-17-to-18.sh [commit whose compose files run PostgreSQL 17] +set -Eeuo pipefail +cd "$(dirname "$0")/.." +root=$PWD +prev=${1:-cf5c3c801b0b6f9769907fafb5b30b840b2352d2} +project="kyppg18$$" +fresh="${project}f" +work=$(mktemp -d) +P18=postgres:18.7-alpine3.24@sha256:0115267ab5a509022df9319c77be365cef335adb71556c75f60f5360ee247e71 + +cleanup() { + for p in "$project" "$fresh"; do + docker ps -aq --filter "label=com.docker.compose.project=$p" | xargs -r docker rm -f >/dev/null 2>&1 || true + docker volume ls -q --filter "label=com.docker.compose.project=$p" | xargs -r docker volume rm >/dev/null 2>&1 || true + docker network ls -q --filter "label=com.docker.compose.project=$p" | xargs -r docker network rm >/dev/null 2>&1 || true + done + rm -rf "$work" +} +trap cleanup EXIT +fail() { echo "FAIL: $*" >&2; "${new[@]}" logs postgres-17-dump postgres 2>&1 | tail -40 >&2 || true; exit 1; } + +git cat-file -e "$prev:docker-compose.replicas.yml" 2>/dev/null || git fetch -q --no-tags --depth=1 origin "$prev" +git show "$prev:docker-compose.yml" >"$work/old-base.yml" +git show "$prev:docker-compose.replicas.yml" >"$work/old-replicas.yml" +grep -q 'image: postgres:17' "$work/old-replicas.yml" || { echo "$prev does not run PostgreSQL 17" >&2; exit 1; } + +net=$((100 + $$ % 100)) +pg_pw=$(od -An -N16 -tx1 /dev/urandom | tr -d ' \n') +cat >"$work/env" </dev/null 2>"$work/up.err" || { cat "$work/up.err" >&2; return 1; }; } +down_db() { "$@" stop postgres >/dev/null 2>&1; "$@" rm -f postgres >/dev/null 2>&1; } +# From another container on the database network, as the replicas connect: inside the server +# container loopback is trust, so only this proves the password. +client() { docker run --rm --network "$1_database" -e PGPASSWORD="$2" "$P18" psql -h postgres -U "$3" -d kypost -XAtc "$4"; } +q() { client "$project" "${3:-$pg_pw}" "${2:-kypost}" "$1"; } +in_vol() { docker run --rm --network none -v "${project}_$1:/v" "$P18" sh -c "$2"; } + +echo "== 1. PostgreSQL 17 data, from the previous compose files" +up "${old[@]}" || fail "17 did not start from $prev" +"${old[@]}" exec -T postgres psql -U kypost -d kypost -X -q -v ON_ERROR_STOP=1 >/dev/null <<'SQL' +create role reader login password 'readerpass'; +create table t(id bigserial primary key, s text unique, j jsonb); +insert into t(s, j) select 'row' || g, jsonb_build_object('g', g) from generate_series(1, 50000) g; +create table c(x text primary key); +insert into c values ('a'), ('B'), ('é'); +grant select on c to reader; +SQL + +echo "== 1b. A dump beside the running 17 refuses and writes nothing" +out=$("${new[@]}" run --rm postgres-17-dump 2>&1) && fail "the dump ran beside a live 17: $out" +grep -q 'postmaster.pid exists' <<<"$out" || fail "no live-server message: $out" +in_vol kypost_postgres 'test ! -e /v/upgrade-from-17 && test ! -e /v/18' || fail "the dump beside a live 17 wrote to the 18 volume" +[ "$("${old[@]}" exec -T postgres psql -U kypost -d kypost -XAtc 'select count(*) from t')" = 50000 ] || fail "17 is not still serving" + +echo "== 2. The next up -d, with the 17 stack still running (no down), moves it to 18" +up "${new[@]}" || fail "18 did not start after the move" +# Compose recreates (stops) 17 before it starts the dump, so the dump ran and found no server. +"${new[@]}" logs postgres-17-dump 2>&1 | grep -q 'dumped /var/lib/postgresql/data' || fail "the dump did not run on up" +"${new[@]}" logs postgres 2>&1 | grep -q 'restored' || fail "18 did not restore the dump" +[ "$(q 'show server_version_num' | cut -c1-2)" = 18 ] || fail "not PostgreSQL 18" +[ "$(q "select count(*) || ',' || max(id) || ',' || sum((j->>'g')::int) from t")" = "50000,50000,1250025000" ] || fail "rows" +[ "$(q "select string_agg(x, ',' order by x) from c" reader readerpass)" = "B,a,é" ] || fail "reader password or C collation" +q 'select 1' kypost wrong-password >/dev/null 2>&1 && fail "a wrong password logged in" +q 'select 1' reader wrong-password >/dev/null 2>&1 && fail "a wrong reader password logged in" +[ "$(q "select datcollate || ',' || pg_encoding_to_char(encoding) from pg_database where datname = 'kypost'")" = C,UTF8 ] || fail "database locale" +[ "$(q 'show data_directory')" = /var/lib/postgresql/18/docker ] || fail "data directory" +[ "$(in_vol kypost_pgdata 'cat /v/PG_VERSION')" = 17 ] || fail "the 17 volume changed" + +echo "== 3. Rollback: the previous compose files start 17 on the kept volume; write on 17" +down_db "${new[@]}" +up "${old[@]}" || fail "17 no longer starts on its volume" +[ "$("${old[@]}" exec -T postgres psql -U kypost -d kypost -XAtc 'select count(*) from t')" = 50000 ] || fail "17 data changed" +"${old[@]}" exec -T postgres psql -U kypost -d kypost -XAtqc "insert into t(s) values ('written on 17 after the move')" +down_db "${old[@]}" + +echo "== 3b. Back to 18: the dump refuses because 17 ran since, and 18 does not start" +seen=$("${new[@]}" logs postgres-17-dump 2>&1 | wc -l) +up "${new[@]}" 2>/dev/null && fail "18 started without what 17 wrote after the move" +"${new[@]}" logs postgres-17-dump 2>&1 | tail -n +"$((seen + 1))" | grep -q 'has run on .* since it was moved to 18' || fail "no rollback message" +[ -z "$("${new[@]}" ps -q postgres)" ] || fail "18 is running after the refusal" + +echo "== 3c. Move again as documented: rename 18/ and upgrade-from-17/; 18 gets the new row" +"${new[@]}" down >/dev/null 2>&1 +"${new[@]}" run --rm --no-deps --entrypoint sh postgres -c 'mv /var/lib/postgresql/18 /var/lib/postgresql/18.replaced && + mv /var/lib/postgresql/upgrade-from-17 /var/lib/postgresql/upgrade-from-17.replaced' >/dev/null 2>&1 || fail "the move-again renames failed" +up "${new[@]}" || fail "18 did not start after moving again" +[ "$(q 'select count(*) from t')" = 50001 ] || fail "moving again lost the row written on 17" +in_vol kypost_postgres 'test -s /v/18.replaced/docker/PG_VERSION && test -s /v/18.replaced/moved-from-17.checkpoint && test -s /v/upgrade-from-17.replaced/dump.sql' || + fail "the replaced 18 cluster, its checkpoint or the dump is gone" + +echo "== 4. Another up is a no-op" +seen=$("${new[@]}" logs postgres-17-dump 2>&1 | wc -l) +down_db "${new[@]}" +up "${new[@]}" || fail "18 did not restart" +dumps=$("${new[@]}" logs postgres-17-dump 2>&1 | tail -n +"$((seen + 1))") +{ ! grep -q "dumped" <<<"$dumps" && grep -q "already done" <<<"$dumps"; } || fail "the second up dumped again: $dumps" +"${new[@]}" logs postgres 2>&1 | grep -q 'restored' && fail "the second up restored again" +[ "$(q 'select count(*) from t')" = 50001 ] || fail "rows after the second up" + +echo "== 4b. Keep 18 after a rollback: delete 18/moved-from-17.checkpoint, and it sticks" +down_db "${new[@]}" +up "${old[@]}" || fail "17 did not start for the keep-18 check" +down_db "${old[@]}" +up "${new[@]}" 2>/dev/null && fail "18 started after 17 ran again (keep-18 check)" +"${new[@]}" down >/dev/null 2>&1 +"${new[@]}" run --rm --no-deps --entrypoint rm postgres /var/lib/postgresql/18/moved-from-17.checkpoint >/dev/null 2>&1 || fail "the keep-18 rm failed" +up "${new[@]}" || fail "keep 18 was not accepted" +down_db "${new[@]}" +up "${new[@]}" || fail "keep 18 did not stick" +[ "$(q 'select count(*) from t')" = 50001 ] || fail "rows after keeping 18" + +echo "== 5. A dump that fails to restore never yields a cluster" +down_db "${new[@]}" +in_vol kypost_postgres 'mv /v/18/docker /v/18/docker.saved && cp /v/upgrade-from-17/dump.sql /v/dump.good && echo "THIS IS NOT SQL;" >> /v/upgrade-from-17/dump.sql' +"${new[@]}" up -d postgres >/dev/null 2>&1 +id=$("${new[@]}" ps -aq postgres) +for _ in $(seq 1 300); do + [ "$(docker inspect -f '{{.RestartCount}}' "$id")" -ge 2 ] && break + sleep 1 +done +[ "$(docker inspect -f '{{.RestartCount}}' "$id")" -ge 2 ] || fail "a bad dump did not fail twice" +[ "$(docker inspect -f '{{if .State.Health}}{{.State.Health.Status}}{{end}}' "$id")" != healthy ] || fail "a bad dump became healthy" +in_vol kypost_postgres 'test ! -e /v/18/docker' || fail "a bad dump produced a cluster" +down_db "${new[@]}" +in_vol kypost_postgres 'rm -rf /v/18/docker.part && mv /v/18/docker.saved /v/18/docker && mv /v/dump.good /v/upgrade-from-17/dump.sql' + +echo "== 6. The documented clean-up of the dump (17 kept): 18 still starts" +"${new[@]}" down >/dev/null 2>&1 +"${new[@]}" run --rm --no-deps --entrypoint rm postgres -r /var/lib/postgresql/upgrade-from-17 >/dev/null 2>&1 || fail "the dump clean-up rm failed" +up "${new[@]}" || fail "18 did not start after removing upgrade-from-17" +"${new[@]}" logs postgres-17-dump 2>&1 | tail -n 1 | grep -q 'already done' || fail "the dump did not accept the clean-up" +[ "$(q 'select count(*) from t')" = 50001 ] || fail "rows after the dump clean-up" + +echo "== 6b. A rollback after that clean-up is still refused on the way back to 18" +down_db "${new[@]}" +up "${old[@]}" || fail "17 did not start after the dump clean-up" +"${old[@]}" exec -T postgres psql -U kypost -d kypost -XAtqc "insert into t(s) values ('written on 17 after the clean-up')" +down_db "${old[@]}" +seen=$("${new[@]}" logs postgres-17-dump 2>&1 | wc -l) +up "${new[@]}" 2>/dev/null && fail "18 started after a rollback that followed the dump clean-up" +"${new[@]}" logs postgres-17-dump 2>&1 | tail -n +"$((seen + 1))" | grep -q 'has run on .* since it was moved to 18' || fail "no rollback message after the clean-up" +[ -z "$("${new[@]}" ps -q postgres)" ] || fail "18 is running after the refusal (clean-up)" +"${new[@]}" down >/dev/null 2>&1 +"${new[@]}" run --rm --no-deps --entrypoint rm postgres /var/lib/postgresql/18/moved-from-17.checkpoint >/dev/null 2>&1 || fail "the keep-18 rm failed (clean-up)" +up "${new[@]}" || fail "keep 18 was not accepted after the clean-up" + +echo "== 6c. Removing the 17 volume too leaves 18 running" +"${new[@]}" down >/dev/null 2>&1 +docker volume rm "${project}_kypost_pgdata" >/dev/null +up "${new[@]}" || fail "18 did not start after the clean-up" +[ "$(q 'select count(*) from t')" = 50001 ] || fail "rows after the clean-up" +in_vol kypost_postgres 'test ! -e /v/upgrade-from-17' || fail "the dump is back" +"${new[@]}" logs postgres-17-dump 2>&1 | tail -n 1 | grep -q 'already done' || fail "the dump ran again after the clean-up" + +echo "== 7. A fresh install initialises 18" +"${new[@]}" down >/dev/null 2>&1 # frees its database network +fresh_new=("${compose[@]}" -p "$fresh" -f docker-compose.yml -f docker-compose.replicas.yml) +sed -i "s/^KYPOST_NETWORK=.*/KYPOST_NETWORK=${fresh}-net/; s/^KYPOST_SUBNET=10.197/KYPOST_SUBNET=10.195/; s/^KYPOST_IP=10.197/KYPOST_IP=10.195/; s/^KYPOST_REPLICA_SUBNET=10.196/KYPOST_REPLICA_SUBNET=10.194/; s/^KYPOST_PROXY_IP=10.196/KYPOST_PROXY_IP=10.194/" "$work/env" +up "${fresh_new[@]}" || fail "a fresh 18 did not start" +"${fresh_new[@]}" logs postgres-17-dump 2>&1 | grep -q 'nothing to move' || fail "a fresh install did not skip the dump" +"${fresh_new[@]}" logs postgres 2>&1 | grep -q 'restored' && fail "a fresh install restored something" +[ "$(client "$fresh" "$pg_pw" kypost "select current_setting('data_directory') || ',' || datcollate from pg_database where datname = 'kypost'")" = /var/lib/postgresql/18/docker,C ] || + fail "fresh data directory or locale" +client "$fresh" wrong-password kypost 'select 1' >/dev/null 2>&1 && fail "a fresh install let a wrong password in" + +echo "PASS postgres 17 -> 18: dump beside a live 17 refused, move on up -d over a running 17, rows, roles, passwords, C locale, rollback to 17, re-upgrade refused, move again, keep 18, rerun, bad dump, clean-up of the dump then a refused rollback, 17 volume removed, fresh install"