From 3b89e5ab3a783fa5d14cdb8527d33e063139c972 Mon Sep 17 00:00:00 2001 From: Yoshiofthewire Date: Wed, 25 Nov 2026 17:48:11 -0500 Subject: [PATCH 1/2] chore(deps): PostgreSQL 18 with an automatic, non-destructive upgrade from 17 KyMessages' Matrix Postgres (Docker) and the replicated KyIdentity's database pod (Kubernetes) move to 18.7, pinned by digest. A 17 install moves on its next deploy by dump and restore with the suite's kit v2 (scripts/postgres-17-to-18.sh, byte for byte, sha256 2992644...): a 17.12 one-shot dumps the old data once, 18 restores it beside it, and the 17 data is only read, so the previous release still starts on it. - kymessage: postgres-17-dump one-shot (no network, restart "no") that postgres waits for; ./pgdata mounted at /var/lib/postgresql; the kit is a catalog file (pg-upgrade/). Its testdata copy of KyMessage's compose is fe88a59's. - Catalog: services others wait for with service_completed_successfully are Once: labelled, run by up, never asked to be running or healthy. Plain apps may bind files/. - upgrade.move gates on the target's layout, not versions: an unmoved install is backed up first where kyquickstart backup can, else needs --acknowledge-no-backup. - KyIdentity database pod: init container postgres-17-dump (17), the kit inline in the pod spec, claim at /var/lib/postgresql, 120 s grace. - CloudNativePG clusters stay on 17: there is no installer backup of a Cluster to take before its major upgrade. - scripts/test-postgres-17-to-18.sh (rendered kymessage Compose) and test-postgres-17-to-18-pod.sh (rendered pod spec in Docker), CI job "PostgreSQL 17 to 18 upgrade", required by release-image.yml. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 19 +++ .github/workflows/release-image.yml | 1 + AGENTS.md | 34 ++++- CHANGELOG.md | 7 + cmd/kyquickstart/release_test.go | 2 +- docs/guided-setup.md | 52 ++++++- .../catalog/apps/kyidentity/manifest.yaml | 7 +- .../catalog/apps/kymessage/compose.yaml.tmpl | 44 +++++- .../files/pg-upgrade/postgres-17-to-18.sh | 89 +++++++++++ internal/catalog/apps/kymessage/manifest.yaml | 17 ++- internal/catalog/catalog.go | 83 ++++++++-- internal/catalog/message_test.go | 23 ++- internal/catalog/postgres18_test.go | 112 ++++++++++++++ internal/catalog/render_kymessage_test.go | 46 ++++++ .../testdata/apps/dumpdemo/compose.yaml.tmpl | 3 +- .../testdata/apps/dumpdemo/manifest.yaml | 4 +- .../kymessage-docker-compose.matrix.yml | 75 +++++++-- .../catalog/testdata/rendered.golden.yaml | 1 + internal/cli/cli.go | 13 +- internal/cli/move_test.go | 80 ++++++++++ internal/cli/suite.go | 30 ++++ internal/dockerhost/app.go | 15 ++ internal/dockerhost/deploy.go | 4 +- internal/dockerhost/deploy_test.go | 24 ++- internal/dockerhost/manage.go | 4 +- internal/kube/postgres-17-to-18.sh | 89 +++++++++++ internal/kube/render_database_test.go | 25 +++ internal/kube/replicas.go | 37 ++++- internal/kube/replicas_test.go | 28 ++++ scripts/postgres-17-to-18.sh | 89 +++++++++++ scripts/test-postgres-17-to-18-pod.sh | 127 ++++++++++++++++ scripts/test-postgres-17-to-18.sh | 142 ++++++++++++++++++ 32 files changed, 1247 insertions(+), 79 deletions(-) create mode 100644 internal/catalog/apps/kymessage/files/pg-upgrade/postgres-17-to-18.sh create mode 100644 internal/catalog/postgres18_test.go create mode 100644 internal/catalog/render_kymessage_test.go create mode 100644 internal/cli/move_test.go create mode 100644 internal/kube/postgres-17-to-18.sh create mode 100644 internal/kube/render_database_test.go create mode 100755 scripts/postgres-17-to-18.sh create mode 100755 scripts/test-postgres-17-to-18-pod.sh create mode 100755 scripts/test-postgres-17-to-18.sh diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8e6b4ef1..42861b65 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -74,6 +74,25 @@ jobs: - run: make workflow-lint - run: scripts/check-no-binaries.sh + postgres-upgrade: + # The catalog's PostgreSQL 17 to 18 move on its real renderings: kymessage's Compose file + # and the replicated KyIdentity's database pod, each seeded with the previous catalog. + name: PostgreSQL 17 to 18 upgrade + if: github.event.pull_request.draft != true + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 # the scripts render the previous catalog from git + - uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0 + with: + go-version-file: go.mod + cache: false + - run: shellcheck scripts/postgres-17-to-18.sh scripts/test-postgres-17-to-18.sh scripts/test-postgres-17-to-18-pod.sh + - run: scripts/test-postgres-17-to-18.sh + - run: scripts/test-postgres-17-to-18-pod.sh + e2e-shard: # sshd in a container on the runner's Docker socket; deploys the hello fixture. Each kind # test builds its own cluster, so the suite splits by test name into parallel jobs, balanced diff --git a/.github/workflows/release-image.yml b/.github/workflows/release-image.yml index c741741c..01cc31b6 100644 --- a/.github/workflows/release-image.yml +++ b/.github/workflows/release-image.yml @@ -139,6 +139,7 @@ jobs: test (macos-latest, stable) vulncheck e2e + PostgreSQL 17 to 18 upgrade Runner image build & run run: | set -euo pipefail diff --git a/AGENTS.md b/AGENTS.md index ef6fed1e..f23bd6a8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -528,6 +528,12 @@ edge compatibility: `docs/redirect.md`. typed confirmation, never the app's `vol-` claims. It is `backup_required` where neither can run (no destination, named volumes, a root app on Kubernetes); any other upgrade needs an explicit, recorded acknowledgement. The manifest's `upgrade.note` is printed and recorded with it. + `upgrade.move` (Docker only; kymessage's PostgreSQL 17 to 18, owner decision 2026-11-25) + gates on the target, not the versions: while the app's directory holds `from` and lacks `to`, + a deploy is backed up first where `kyquickstart backup` can (one snapshot when the version + change takes one too) and otherwise refuses `ack_required` without `--acknowledge-no-backup`. + The suite's PostgreSQL 17 to 18 kit is `scripts/postgres-17-to-18.sh`, kept byte for byte (kit + v2) in kymessage's `files/pg-upgrade/` and `internal/kube/` (`TestPostgresKitIsVendoredByteForByte`). Uninstall keeps data and secrets, and on Kubernetes ends only once the app's pods are gone; Docker deploys, backups and lifecycle steps refuse a Compose project `kyq-` whose containers another root's directory made (another plan, or this one before its root moved), @@ -589,8 +595,10 @@ edge compatibility: `docs/redirect.md`. one-replica rule still hold for it; Deployment `app-replica` is the other pods, claimless and rolling; the Service selects both by `ky.serves`. The database is the operator's (`database_secret`: a labelled Secret in `kyq-kyidentity`, key `url`, never a `kyq-` name, - never read into state or output) or Deployment `database`, one Postgres pod on `vol-database` - that only the app's pods reach, where KyIdentity's role is not a superuser. Secret + never read into state or output) or Deployment `database`, one PostgreSQL 18 pod on + `vol-database` that only the app's pods reach, where KyIdentity's role is not a superuser. Its + init container `postgres-17-dump` (17 image) dumps an earlier release's 17 data (`private/pgdata`) + once, and the kit restores it into `private/18/docker` beside it; the 17 data is never written. Secret `kyq-replica-keys` (the four keys, generated by a single instance of the app's image on memory, and the bootstrap password) and `kyq-database` are written once and never replaced. `KYIDENTITY_RECOVERY_KEY_ID` comes only from the plan's owner-confirmed `recovery_key_id`. @@ -605,9 +613,10 @@ edge compatibility: `docs/redirect.md`. `database_instances: 3-5` beside `replicas`, never with `database_secret`, replaces Deployment `database` with a CloudNativePG `Cluster` of that name (`postgresql.cnpg.io/v1`, written through the dynamic client with strict field validation): the catalog's - `replicas.cluster_image` (a CloudNativePG operand image), required anti-affinity by node, - synchronous replication `ANY 1`, the same UTF8/C database and non-superuser owner, taken - from `kyq-database` (basic-auth here: `username`, `password`, `url`). The operator is the + `replicas.cluster_image` (a CloudNativePG operand image; PostgreSQL 17, since the installer + has no backup of a Cluster to take before CloudNativePG's major upgrade), required + anti-affinity by node, synchronous replication `ANY 1`, the same UTF8/C database and + non-superuser owner, taken from `kyq-database` (basic-auth here: `username`, `password`, `url`). The operator is the catalog's `cloudnative-pg` (next) or the cluster owner's: `DatabaseOperatorCheck` (preflight of a plan that does not install it, and apply's own error) refuses without it, and `Needs.DatabaseCluster` adds the `clusters` permission only to such a plan. KyIdentity connects to `database-rw` with `sslmode=verify-full` against the @@ -664,9 +673,12 @@ edge compatibility: `docs/redirect.md`. `ports:` entry starts with `{{forward…}}`, `{{forward_addr}}`, `{{media_address}}`, `{{smtp_address}}` (a `receiver` rendering's alone) or `127.0.0.1`: no bare or wildcard publication. Files in an app's catalog `files/` are written mode 0644 by deploy where its - Compose file binds them inside a bind directory, and are part of the deploy's input. A service in a Compose profile is a one-shot run - (`compose run --rm`), never part of `up` or health; a bind source inside a bind directory - must exist before deploy starts the app. + Compose file binds them inside a bind directory (a mail app's in its receiver rendering + only), and are part of the deploy's input. A service in a Compose profile is a one-shot run + (`compose run --rm`), never part of `up` or health. A service another waits for with + `service_completed_successfully` (`Once`, `restart: "no"`; kymessage's `postgres-17-dump`) + runs to completion in every `up`, carries the managed labels and is never asked to be running + or healthy. A bind source inside a bind directory must exist before deploy starts the app. Compose runs with `KYQ_UID`/`KYQ_GID` set to the target user's; `./` bind directories are created private by the driver before Compose, and no other relative bind source is accepted. KyMessages' Synapse sets `PYTHONPATH=/config` to load matrix-init's @@ -722,6 +734,12 @@ calls and kind nodes must carry their own explicit bounds. `FuzzStartRequest` (`internal/runner`). CI's `test (ubuntu-latest, stable)` leg runs each for a fixed execution count after `make ci`; a crasher found later goes under the package's `testdata/fuzz//`. +- CI's `PostgreSQL 17 to 18 upgrade` job (in `release-image.yml`'s REQUIRED list): + `scripts/test-postgres-17-to-18.sh` seeds a 17 install from the previous catalog's rendered + kymessage Compose file and moves it with this one (`up -d` over the running 17, a refused dump + beside a live 17, passwords over the network, rollback, rerun, a bad dump, a fresh install, a 17 + backup restored with the manifest's command); `scripts/test-postgres-17-to-18-pod.sh` runs the + previous and current database pod specs in Docker as a kubelet would (not Kubernetes itself). - `make workflow-lint`: needs Docker (CI runs it in `vulncheck`); actionlint v1.7.12 on every workflow and offline, digest-pinned zizmor (medium and up) on `release-image.yml` and `dependency-release.yml`. diff --git a/CHANGELOG.md b/CHANGELOG.md index 46eeae05..a5bd09b7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,13 @@ state directory, target data and target-held credentials; do not reset them as a ## Unreleased +- PostgreSQL 18 for KyMessages' Matrix stack (Docker) and the replicated KyIdentity's database + pod (Kubernetes), with an automatic dump and restore from 17 that keeps the 17 data. + **Upgrade impact:** a KyMessages install still on 17 is backed up first when its target has + a backup destination; without one, `apply`/`upgrade` needs `--acknowledge-no-backup`. Chat or + KyIdentity sign-in is down while the restore runs; the app's disk needs about twice the 17 + data free. Removing the 17 data afterwards is a manual step (`docs/guided-setup.md`). + CloudNativePG clusters stay on 17. - Follow KyPost, KyCalendar and KyYard `0.6.1.1` with verified release image digests. KyPost includes the receiving accelerator and file-lock/fsync fixes; KyCalendar and KyYard refresh their Alpine base. **Upgrade impact:** the selected apps restart on diff --git a/cmd/kyquickstart/release_test.go b/cmd/kyquickstart/release_test.go index a34bd922..7323339b 100644 --- a/cmd/kyquickstart/release_test.go +++ b/cmd/kyquickstart/release_test.go @@ -225,7 +225,7 @@ func TestReleaseWorkflow(t *testing.T) { } } } - for _, job := range []string{"test (ubuntu-latest, 1.26.x)", "test (macos-latest, stable)", "vulncheck", "e2e", "Runner image build & run"} { + for _, job := range []string{"test (ubuntu-latest, 1.26.x)", "test (macos-latest, stable)", "vulncheck", "e2e", "Runner image build & run", "PostgreSQL 17 to 18 upgrade"} { if !slices.Contains(strings.Split(required, "\n"), job) { t.Errorf("publish's REQUIRED list lacks %q", job) } diff --git a/docs/guided-setup.md b/docs/guided-setup.md index 21c5e787..feff9062 100644 --- a/docs/guided-setup.md +++ b/docs/guided-setup.md @@ -794,7 +794,7 @@ In namespace `kyq-kyidentity`, Pod Security `restricted`: ### The database -**The installer's (default).** Deployment `database`: one Postgres 17 pod on claim +**The installer's (default).** Deployment `database`: one PostgreSQL 18 pod on claim `vol-database` (2 GiB), created UTF8 with the C locale as KyIdentity requires. KyIdentity connects as a role that owns its database and is not a superuser. Only KyIdentity's pods can reach it, and it can reach nothing. Read this before choosing it: @@ -806,8 +806,21 @@ reach it, and it can reach nothing. Read this before choosing it: - **The connection is not encrypted.** It stays inside the cluster, between the pods the network policy names; a cluster whose network you do not trust needs your own Postgres with TLS. -- **The installer does not back it up** and does not upgrade it. KyIdentity's own backups - (below) are its only backup. +- **The installer does not back it up.** KyIdentity's own backups (below) are its only backup. +- **PostgreSQL 17 to 18.** A pod made by an earlier release ran 17 with its data in + `pgdata/` of the claim. The first apply of this release moves it on the same claim: init + container `postgres-17-dump` (the 17 image) dumps `pgdata/` once into `upgrade-from-17/`, + and the 18 container restores that dump into `18/docker` beside it before it starts, roles + and passwords included. The 17 data is only read. The claim needs about twice the 17 data + free; with less, the dump refuses, writes nothing and the pod stays in its init container + until the claim grows (`kubectl -n kyq-kyidentity logs deploy/database -c + postgres-17-dump`). A dump refuses too while `pgdata/postmaster.pid` exists, which only a 17 + that crashed leaves: start the previous release's pod once and let it stop. KyIdentity cannot + sign anyone in while the move runs, about as long as a restore of its data. To go back, apply + with the previous release: its 17 pod starts on the untouched `pgdata/`. Once satisfied, you + may delete `pgdata/` and `upgrade-from-17/` from the claim (for example from a debug pod + mounting it); nothing does it for you. No pre-upgrade backup is taken: there is none of this + database (above), and the 17 data stays as the way back. **The installer's, highly available (`database_instances`).** Owner amendment, 2026-11-13. `database_instances: 3` (3 to 5) replaces that one pod with a @@ -848,7 +861,8 @@ The first apply takes several minutes: the instances start one after another, ea the one before, and KyIdentity's pods start once all are ready (15 minutes at most, then apply stops and names the `kubectl describe` to read). The installer still does not back the database up: KyIdentity's own backups (below) are its only backup. It does not upgrade -Postgres across major versions. +Postgres across major versions: a `Cluster` stays on PostgreSQL 17 (17.12), supported until +November 2029, until the installer has a backup of it to take first. ### The CloudNativePG operator @@ -2394,14 +2408,36 @@ integrations: secret, taken while the stack runs. Restore starts Postgres, loads the dump (without the dump's `DROP ROLE`/`CREATE ROLE postgres`, which Postgres refuses for the role restoring it), starts MAS and the console, replays KyIdentity's removals (`replay_after: app`), and only then starts - Synapse, Element and LiveKit. + Synapse, Element and LiveKit. A dump of PostgreSQL 17 restores on 18. +- **PostgreSQL 18.** The stack's Postgres is 18, with its data in `pgdata/18/docker` of the app's + directory. An install made by an earlier release (17, data in `pgdata/pgdata`) moves on the + next `apply`, `install` or `upgrade` that deploys it, whatever the versions: + - **Backup first.** With a backup destination on the target, a `kyquickstart backup` + snapshot is taken before anything changes (step `kymessage.pre-upgrade-backup`); if it + fails, nothing is deployed. Without a destination the command refuses (`ack_required`) until + you pass `--acknowledge-no-backup`; the 17 data is kept either way. + - **The move.** Compose stops the 17 Postgres, the one-shot `postgres-17-dump` (the 17 image, + no network) dumps `pgdata/pgdata` once into `pgdata/upgrade-from-17`, and Postgres restores + it into `pgdata/18/docker` before it starts, roles and passwords included. The suite's + script that does both is `pg-upgrade/postgres-17-to-18.sh` (`scripts/postgres-17-to-18.sh`). + The 17 data is only read. Chat is down while it runs, about as long as a restore of the + backup's dump; past the app's 10-minute health wait apply fails, and a rerun waits again + while the restore finishes. + - **Space.** About twice the 17 data free on the app's disk; with less, the one-shot refuses, + writes nothing, and the stack does not start until there is room. It refuses too while + `pgdata/pgdata/postmaster.pid` exists, which only a crashed 17 leaves: start the previous + release once and stop it cleanly. + - **Going back.** Deploy the previous release (or restore the pre-upgrade snapshot): its 17 + starts on the untouched `pgdata/pgdata`. + - **Clean-up, your choice.** Once satisfied, `rm -r pgdata/pgdata pgdata/upgrade-from-17` in the + app's directory, as the target user. Nothing removes them for you. ### KyMessages: provenance, measurements and residuals - **Images.** The console image is KyMessage v0.4.4's, attested by `Busnes-app/KyMessage-Server` - `release-image.yml@refs/tags/v0.4.4` from commit `b0f2001e`. The five Matrix images are the - stock upstream builds KyMessage's `docker-compose.matrix.yml` pins by digest; no attestation - was found for them. + `release-image.yml@refs/tags/v0.4.4` from commit `b0f2001e`. The Matrix images, PostgreSQL 18 + and the 17 dump one-shot are the stock upstream builds KyMessage's `docker-compose.matrix.yml` + pins by digest; no attestation was found for them. - **Measured in the end-to-end test.** A chat-only person was locked 0-3 s after their sign-in. Offboarding refused the open session and its refresh token 0.6-2.6 s after the disable, for the owner's everyday account and for a person added later. Removing "KyMessages chat" alone diff --git a/internal/catalog/apps/kyidentity/manifest.yaml b/internal/catalog/apps/kyidentity/manifest.yaml index 38119237..b2d96efb 100644 --- a/internal/catalog/apps/kyidentity/manifest.yaml +++ b/internal/catalog/apps/kyidentity/manifest.yaml @@ -14,8 +14,10 @@ version: 0.6.1 # catalog-follow: v0.6.1 attested by Busnes-app/KyIdentity-server release-image.yml@refs/tags/v0.6.1 images: kyidentity: ghcr.io/busnes-app/kyidentity-server:0.6.1@sha256:270a4b3223b7753b2e3bd2eb8895a3c73c3e9469b4f6333991ca2fa1944c3b65 - # Kubernetes, with replicas and no database_secret in the plan: the Postgres they share. - postgres: postgres:17.6-alpine@sha256:ef257d85f76e48da1c64832459b59fcaba1a4dac97bf5d7450c77753542eee94 + # Kubernetes, with replicas and no database_secret in the plan: the Postgres they share, + # and the 17 its init container runs once to dump a 17 database for 18 to restore. + postgres: postgres:18.7-alpine3.24@sha256:0115267ab5a509022df9319c77be365cef335adb71556c75f60f5360ee247e71 + postgres_17: postgres:17.12-alpine3.24@sha256:f9cf3e1f0066f0eb0c48707d864f0ac5941e9ff454a072077d97a4d278d07d73 # The same, with database_instances in the plan: the CloudNativePG community's Postgres 17 # operand image (17.12 on Debian trixie, no extras), which the cluster's operator runs. postgres_cluster: ghcr.io/cloudnative-pg/postgresql:17.12-minimal-trixie@sha256:4ae89311e5031155a139a5c6d31a80f6deb135443711e61ff7df41cb549fdcaa @@ -68,5 +70,6 @@ kubernetes: replicas: since: 0.6.0.2 database_image: postgres + dump_image: postgres_17 database_size: 2Gi cluster_image: postgres_cluster diff --git a/internal/catalog/apps/kymessage/compose.yaml.tmpl b/internal/catalog/apps/kymessage/compose.yaml.tmpl index f03cc6c1..09b7afd6 100644 --- a/internal/catalog/apps/kymessage/compose.yaml.tmpl +++ b/internal/catalog/apps/kymessage/compose.yaml.tmpl @@ -118,10 +118,42 @@ services: KY_MATRIX_MEDIA_IP: "{{media_address}}" volumes: [./matrix:/matrix] + # PostgreSQL 18 keeps its data in pgdata/18/docker, beside the 17 data in pgdata/pgdata, + # which stays untouched. A 17 install moves on its next deploy: this one-shot dumps + # pgdata/pgdata once into pgdata/upgrade-from-17, then postgres restores that dump before it + # starts (KyMessage-Server's docker-compose.matrix.yml; pg-upgrade/postgres-17-to-18.sh is + # the suite's kit, scripts/postgres-17-to-18.sh). Without 17 data it does nothing. + postgres-17-dump: + image: {{ .Images.postgres_17 }} + user: "${KYQ_UID:?}:${KYQ_GID:?}" + entrypoint: ["bash", "/ky/postgres-17-to-18.sh", "dump"] + environment: + OLD: /v/pgdata + NEW: /v + network_mode: none + restart: "no" + # A clean stop removes postmaster.pid, without which the next dump refuses. + stop_grace_period: 2m + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + read_only: true + tmpfs: [/tmp] + shm_size: 128m + mem_limit: 512m + memswap_limit: 512m + cpus: 1 + pids_limit: 256 + volumes: + - ./pgdata:/v + - ./pg-upgrade/postgres-17-to-18.sh:/ky/postgres-17-to-18.sh:ro + postgres: image: {{ .Images.postgres }} user: "${KYQ_UID:?}:${KYQ_GID:?}" restart: unless-stopped + # Restores postgres-17-dump's dump once, then runs the image's own entrypoint. + entrypoint: ["bash", "/ky/postgres-17-to-18.sh", "restore"] + command: [postgres] cap_drop: [ALL] security_opt: [no-new-privileges:true] read_only: true @@ -134,20 +166,22 @@ services: stop_grace_period: 2m environment: POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password - # A subdirectory: initdb must own its directory. - PGDATA: /var/lib/postgresql/data/pgdata secrets: [postgres_password] networks: [matrix-db] volumes: - - ./pgdata:/var/lib/postgresql/data + - ./pgdata:/var/lib/postgresql - ./matrix/postgres:/docker-entrypoint-initdb.d:ro - # TCP, not the socket: during first-run init the temporary server listens on the socket only. + - ./pg-upgrade/postgres-17-to-18.sh:/ky/postgres-17-to-18.sh:ro + depends_on: + postgres-17-dump: {condition: service_completed_successfully} + # TCP, not the socket: during first-run init or the restore the temporary server listens on + # the socket only. The restore takes about as long as a restore of the backup's dump. healthcheck: test: ["CMD", "pg_isready", "-h", "127.0.0.1", "-U", "postgres", "-d", "postgres"] interval: 10s timeout: 5s retries: 30 - start_period: 60s + start_period: 1h start_interval: 2s synapse: diff --git a/internal/catalog/apps/kymessage/files/pg-upgrade/postgres-17-to-18.sh b/internal/catalog/apps/kymessage/files/pg-upgrade/postgres-17-to-18.sh new file mode 100644 index 00000000..85b7729b --- /dev/null +++ b/internal/catalog/apps/kymessage/files/pg-upgrade/postgres-17-to-18.sh @@ -0,0 +1,89 @@ +#!/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 +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} + if [ -s "$new/18/docker/PG_VERSION" ] || [ -s "$dump_dir/dump.sql" ]; then + echo "postgres-17-to-18: already done"; exit 0 + 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 + # 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. + if [ -e "$old/postmaster.pid" ]; then + 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 + fi + # 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" + 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/internal/catalog/apps/kymessage/manifest.yaml b/internal/catalog/apps/kymessage/manifest.yaml index 7a53205c..10dee200 100644 --- a/internal/catalog/apps/kymessage/manifest.yaml +++ b/internal/catalog/apps/kymessage/manifest.yaml @@ -5,13 +5,14 @@ version: 0.6.1 # kymessage: release image of v0.4.4 (commit b0f2001e3d3fd80093e6b2f5bd341168dc7517dd), attested by # Busnes-app/KyMessage-Server release-image.yml@refs/tags/v0.4.4 (gh attestation verify; the # attested gitCommit is v0.4.4^{commit}). -# The other five are the stock upstream images KyMessage's docker-compose.matrix.yml pins, by -# tag and digest in v0.4.4 (unchanged since v0.4.3); no attestation was found for them -# (provenance: KyMessage's compose). +# The others are the stock upstream images KyMessage's docker-compose.matrix.yml pins, by tag +# and digest (PostgreSQL 18.7 and the 17.12 dump one-shot since KyMessage-Server fe88a59, #152); +# no attestation was found for them (provenance: KyMessage's compose). # catalog-follow: v0.6.1 attested by Busnes-app/KyMessage-Server release-image.yml@refs/tags/v0.6.1 images: kymessage: ghcr.io/busnes-app/kymessage-server:0.6.1@sha256:766f9c9d1d6d36a5ed33f05e810f69f075fb8f8f0054b8d7eb95a4946766991d - postgres: postgres:17.6-alpine@sha256:ef257d85f76e48da1c64832459b59fcaba1a4dac97bf5d7450c77753542eee94 + postgres: postgres:18.7-alpine3.24@sha256:0115267ab5a509022df9319c77be365cef335adb71556c75f60f5360ee247e71 + postgres_17: postgres:17.12-alpine3.24@sha256:f9cf3e1f0066f0eb0c48707d864f0ac5941e9ff454a072077d97a4d278d07d73 synapse: ghcr.io/element-hq/synapse:v1.162.0@sha256:6b84a7bbac36f080b2d2e51e0289cf1b08b349598ea44a558df38d558f2c2311 mas: ghcr.io/element-hq/matrix-authentication-service:1.26.0@sha256:e089f1048a1d4a9a492ed17b9fe759100f1bd619407b001f5927928d88b780c4 element: ghcr.io/element-hq/element-web:v1.12.30@sha256:3e7dbd4424de9e11c812bc740acf2725b2abe66ea0d0802023b56fd85d3fa09a @@ -83,3 +84,11 @@ upgrade: min_from: 0.4.3 migrates_data: true data_since: 0.6.0.2 + # The catalog's deploy moves Postgres from 17 to 18 by itself (postgres-17-dump), keeping the + # 17 data in pgdata/pgdata: an install that has not moved is backed up first. + move: + from: pgdata/pgdata/PG_VERSION + to: pgdata/18/docker/PG_VERSION + what: >- + PostgreSQL 17 to 18 by dump and restore on its next start; the 17 data stays in + pgdata/pgdata and needs about twice its size free diff --git a/internal/catalog/catalog.go b/internal/catalog/catalog.go index 20585137..7291ce00 100644 --- a/internal/catalog/catalog.go +++ b/internal/catalog/catalog.go @@ -157,6 +157,18 @@ type Upgrade struct { // unchanged, so an upgrade from it or later migrates nothing. Empty: every upgrade migrates. DataSince string `yaml:"data_since"` Note string `yaml:"note"` // what the owner must check after upgrading to this version + // Move is a move of the data this catalog's deploy makes by itself, whatever the versions + // (PostgreSQL 17 to 18). Docker only. + Move *Move `yaml:"move"` +} + +// Move names the move by two files below the app's directory, each inside a bind +// directory: an app that holds From and lacks To has not moved yet. Its deploy is backed up +// first where kyquickstart can back it up, and otherwise needs --acknowledge-no-backup. +type Move struct { + From string `yaml:"from"` + To string `yaml:"to"` + What string `yaml:"what"` // the move, for the operator: "PostgreSQL 17 to 18 ..." } type Health struct { @@ -227,7 +239,10 @@ type Replicas struct { // Since is the first release that runs as replicas; an older pin refuses the plan's. Since string `yaml:"since"` DatabaseImage string `yaml:"database_image"` // a key of Images - DatabaseSize string `yaml:"database_size"` + // DumpImage is PostgreSQL 17, whose init container dumps a 17 database once for the 18 + // pod to restore (scripts/postgres-17-to-18.sh): a key of Images. + DumpImage string `yaml:"dump_image"` + DatabaseSize string `yaml:"database_size"` // ClusterImage is the Postgres of a plan's database_instances: a key of Images naming a // CloudNativePG operand image, which the operator can run and the official image is not. ClusterImage string `yaml:"cluster_image" json:",omitempty"` @@ -278,6 +293,9 @@ type App struct { Nested []string // Init are the services in a Compose profile: one-shot runs, never part of up. Init []string + // Once are the services up runs to completion before a service that waits for them + // (service_completed_successfully): never running, so health does not ask for them. + Once []string // Files are the catalog's files/ beside the template, by path below the app's directory // (rspamd/rspamd.conf). Deploy writes those its Compose file binds (Nested), readable by // every uid: a sidecar running as its own user reads them through the bind. @@ -290,8 +308,8 @@ type App struct { // rendering is one rendering of an app's Compose template. type rendering struct { - compose []byte - services, binds, nested, init []string + compose []byte + services, binds, nested, init, once []string } type Catalog map[string]App @@ -521,6 +539,9 @@ func loadApp(fsys fs.FS, dir string) (App, error) { if len(m.FromVolumes) > 0 { return App{}, errors.New("manifest.yaml: from_volumes needs compose.yaml.tmpl") } + if m.Upgrade.Move != nil { + return App{}, errors.New("manifest.yaml: upgrade: move needs compose.yaml.tmpl") + } return App{Manifest: m, Operator: operator}, nil case err != nil: return App{}, err @@ -547,7 +568,7 @@ func loadApp(fsys fs.FS, dir string) (App, error) { return App{}, fmt.Errorf("compose.yaml.tmpl: %w", err) } if mode == "" { - app.Compose, app.Services, app.Binds, app.Nested, app.Init = r.compose, r.services, r.binds, r.nested, r.init + app.Compose, app.Services, app.Binds, app.Nested, app.Init, app.Once = r.compose, r.services, r.binds, r.nested, r.init, r.once continue } if app.mail == nil { @@ -569,8 +590,8 @@ type templateData struct { } // render executes t for mail mode and checks the result. Only a "receiver" rendering may -// write the mail references or bind a file of files/, and every file of files/ must be bound -// by some rendering. +// write the mail references or, in a mail app, bind a file of files/; every file of files/ +// must be bound by the rendering that owns it. func (m Manifest) render(t *template.Template, mode string, files map[string][]byte) (rendering, error) { var buf bytes.Buffer if err := t.Execute(&buf, templateData{m, mode}); err != nil { @@ -590,22 +611,36 @@ func (m Manifest) render(t *template.Template, mode string, files map[string][]b if err := m.validateRoutes(b, c); err != nil { return rendering{}, fmt.Errorf("manifest.yaml: %w", err) } + if mv := m.Upgrade.Move; mv != nil { + inBind := func(p string) bool { + sub := bindRE.FindStringSubmatch("./" + p) + return sub != nil && sub[2] != "" && slices.Contains(c.binds, sub[1]) + } + if !inBind(mv.From) || !inBind(mv.To) || mv.From == mv.To || mv.What == "" || m.Kubernetes != nil { + return rendering{}, errors.New("manifest.yaml: upgrade: move needs from and to, two files inside bind directories, and what, on a Docker-only app") + } + } for _, ref := range mailRefs { if bytes.Contains(b, []byte(ref)) != (mode == MailReceiver) { return rendering{}, fmt.Errorf("%s belongs in the receiver rendering, which must write every mail reference", ref) } } + // A mail app's files are its receiver's; any other app's, its one rendering's. + owner := "" + if m.NativeMail != nil { + owner = MailReceiver + } for name := range files { - if mode == MailReceiver && !slices.Contains(c.nested, "./"+name) { + if mode == owner && !slices.Contains(c.nested, "./"+name) { return rendering{}, fmt.Errorf("files/%s is bound by no service", name) } } for _, n := range c.nested { - if _, ok := files[strings.TrimPrefix(n, "./")]; ok && mode != MailReceiver { + if _, ok := files[strings.TrimPrefix(n, "./")]; ok && mode != owner { return rendering{}, fmt.Errorf("only the receiver rendering binds files/%s", strings.TrimPrefix(n, "./")) } } - return rendering{b, c.services, c.binds, c.nested, c.init}, nil + return rendering{b, c.services, c.binds, c.nested, c.init, c.once}, nil } // loadFiles reads an app's files/ directory: regular files at most 64 KiB, by path below it. @@ -652,7 +687,7 @@ func (a App) WithMail(mode string, r MailRefs) (App, error) { return a, errors.New("only the receiver rendering takes mail references") } a.Compose = []byte(strings.NewReplacer(SMTPAddressRef, r.SMTPAddress, MailHostnameRef, r.Hostname, MaddyBinaryRef, r.MaddyBinary, ReceivingTLSRef, r.TLSDir).Replace(string(v.compose))) - a.Services, a.Binds, a.Nested, a.Init = v.services, v.binds, v.nested, v.init + a.Services, a.Binds, a.Nested, a.Init, a.Once = v.services, v.binds, v.nested, v.init, v.once a.mail = nil return a, nil } @@ -923,6 +958,8 @@ func (k Kubernetes) validate(images map[string]string, baseline, edge bool) erro return fmt.Errorf("replicas: database_image %q is not a key of images", r.DatabaseImage) case images[r.ClusterImage] == "": return fmt.Errorf("replicas: cluster_image %q is not a key of images", r.ClusterImage) + case images[r.DumpImage] == "": + return fmt.Errorf("replicas: dump_image %q is not a key of images", r.DumpImage) case !versionRE.MatchString(r.Since): return fmt.Errorf("replicas: since %q must be a release like 1.2.3 or 1.2.3.4", r.Since) case !sizeRE.MatchString(r.DatabaseSize): @@ -1201,6 +1238,7 @@ func compareVersions(a, b string) int { type composeFile struct { services []string // sorted, outside profiles init []string // sorted, in a profile + once []string // sorted, outside profiles: run to completion before a dependant volumes map[string]bool // named volumes and bind directories binds []string // sorted nested []string // sorted @@ -1225,6 +1263,9 @@ func checkCompose(b []byte, images map[string]string) (composeFile, error) { Volumes []any `yaml:"volumes"` Ports []any `yaml:"ports"` Profiles []string `yaml:"profiles"` + Restart string `yaml:"restart"` + // A list, or a map whose long form names a condition. + DependsOn any `yaml:"depends_on"` } `yaml:"services"` Volumes map[string]any `yaml:"volumes"` } @@ -1242,6 +1283,16 @@ func checkCompose(b []byte, images map[string]string) (composeFile, error) { for v := range c.Volumes { out.volumes[v] = true } + // A service another one waits for to complete runs once per up, never stays running. + once := map[string]bool{} + for _, s := range c.Services { + deps, _ := s.DependsOn.(map[string]any) + for dep, d := range deps { + if d, _ := d.(map[string]any); d["condition"] == "service_completed_successfully" { + once[dep] = true + } + } + } for name, s := range c.Services { if s.Build != nil { return composeFile{}, fmt.Errorf("service %s: build is not allowed", name) @@ -1249,9 +1300,15 @@ func checkCompose(b []byte, images map[string]string) (composeFile, error) { if !pinned[s.Image] { return composeFile{}, fmt.Errorf("service %s: image %q is not one of the manifest's pinned images", name, s.Image) } - if len(s.Profiles) > 0 { + switch { + case len(s.Profiles) > 0: out.init = append(out.init, name) - } else { + case once[name]: + if s.Restart != "no" { + return composeFile{}, fmt.Errorf(`service %s: a service others wait to complete needs restart: "no"`, name) + } + out.once = append(out.once, name) + default: out.services = append(out.services, name) } for _, p := range s.Ports { @@ -1288,7 +1345,7 @@ func checkCompose(b []byte, images map[string]string) (composeFile, error) { } } } - for _, l := range [][]string{out.services, out.init, out.binds, out.nested} { + for _, l := range [][]string{out.services, out.init, out.once, out.binds, out.nested} { sort.Strings(l) } if len(out.services) == 0 { diff --git a/internal/catalog/message_test.go b/internal/catalog/message_test.go index 482880ae..a12e64ab 100644 --- a/internal/catalog/message_test.go +++ b/internal/catalog/message_test.go @@ -47,6 +47,7 @@ type composeService struct { Environment map[string]string `yaml:"environment"` Ports []string `yaml:"ports"` Networks any `yaml:"networks"` + Volumes any `yaml:"volumes"` Build any `yaml:"build"` } @@ -112,7 +113,10 @@ func TestKyMessageEntry(t *testing.T) { if !slices.Equal(a.Backup.Stop, []string{"app"}) { t.Errorf("backup stops %v, want the console alone", a.Backup.Stop) } - if !slices.Equal(a.Binds, []string{"backups", "data", "matrix", "media", "pgdata"}) || !slices.Contains(a.Nested, "./matrix/mas/config.yaml") || !slices.Contains(a.Nested, "./matrix/element/kymessages-guest.html") { + if !slices.Equal(a.Once, []string{"postgres-17-dump"}) || a.Upgrade.Move == nil || a.Upgrade.Move.To != "pgdata/18/docker/PG_VERSION" { + t.Errorf("once %v, move %+v", a.Once, a.Upgrade.Move) + } + if !slices.Equal(a.Binds, []string{"backups", "data", "matrix", "media", "pg-upgrade", "pgdata"}) || !slices.Contains(a.Nested, "./matrix/mas/config.yaml") || !slices.Contains(a.Nested, "./matrix/element/kymessages-guest.html") { t.Errorf("binds %v nested %v", a.Binds, a.Nested) } b := a.Backup @@ -125,9 +129,9 @@ func TestKyMessageEntry(t *testing.T) { } // AC5: hardened services, internal-only Postgres and MAS admin, no secret in environment, -// within 3 GiB. +// within 3 GiB beside the one-shots, which finish before the services that wait for them. func TestKyMessageComposeHygiene(t *testing.T) { - _, services, networks := messageCompose(t) + a, services, networks := messageCompose(t) if !networks["matrix-db"]["internal"] || !networks["matrix-admin"]["internal"] { t.Fatalf("networks = %v", networks) } @@ -137,14 +141,17 @@ func TestKyMessageComposeHygiene(t *testing.T) { s.MemLimit == "" || s.MemLimit != s.MemSwap || s.PidsLimit == 0 || s.Privileged || len(s.CapAdd) > 0 || s.NetworkMode == "host" || s.Build != nil { t.Errorf("service %s is not hardened: %+v", name, s) } - if s.Healthcheck == nil && !slices.Equal(s.Profiles, []string{"init"}) { + once := slices.Contains(a.Once, name) + if s.Healthcheck == nil && !slices.Equal(s.Profiles, []string{"init"}) && !once { t.Errorf("service %s has no healthcheck", name) } // Compose refuses start_interval without start_period. if s.Healthcheck["start_interval"] != nil && s.Healthcheck["start_period"] == nil { t.Errorf("service %s: start_interval without start_period", name) } - total += memMiB(t, s.MemLimit) + if !once { + total += memMiB(t, s.MemLimit) + } for k, v := range s.Environment { if strings.HasPrefix(k, "KY_KYIDENTITY_") || k == "KY_SCIM_TOKEN" || k == "KY_ADMIN_PASSWORD" || k == "KY_BACKUP_KEEP" || k == "KY_BACKUP_DEPOSIT_INTERVAL" || k == "KY_SESSION_SECRET" || strings.HasPrefix(k, "KY_MATRIX_") && strings.HasSuffix(k, "SECRET") || strings.HasPrefix(k, "POSTGRES_PASSWORD") && k != "POSTGRES_PASSWORD_FILE" { @@ -342,8 +349,8 @@ func TestRoutesRejects(t *testing.T) { } } -// AC1: the five stock images are exactly the digests KyMessage's docker-compose.matrix.yml -// pins. The fixture is that file byte for byte (KyMessage-Server v0.4.4). +// AC1: the six stock images are exactly the digests KyMessage's docker-compose.matrix.yml +// pins. The fixture is that file byte for byte (KyMessage-Server fe88a59, PostgreSQL 18). func TestKyMessageStockImages(t *testing.T) { b, err := os.ReadFile("testdata/kymessage-docker-compose.matrix.yml") if err != nil { @@ -364,7 +371,7 @@ func TestKyMessageStockImages(t *testing.T) { } sort.Strings(upstream) sort.Strings(ours) - if len(upstream) != 5 || !slices.Equal(upstream, ours) { + if len(upstream) != 6 || !slices.Equal(upstream, ours) { t.Fatalf("stock images %v, upstream %v", ours, upstream) } } diff --git a/internal/catalog/postgres18_test.go b/internal/catalog/postgres18_test.go new file mode 100644 index 00000000..72b924a7 --- /dev/null +++ b/internal/catalog/postgres18_test.go @@ -0,0 +1,112 @@ +package catalog + +import ( + "bytes" + "crypto/sha256" + "encoding/hex" + "os" + "slices" + "strings" + "testing" + "testing/fstest" +) + +// kitSHA256 is the suite's PostgreSQL 17 to 18 kit v2 (ky-postgres-18): every copy in this +// repository is that file byte for byte. +const kitSHA256 = "2992644109716cd34297fbcb76eba8907f4a5e3031a12c05aade010e5ea2b571" + +func TestPostgresKitIsVendoredByteForByte(t *testing.T) { + vendored, err := os.ReadFile("../../scripts/postgres-17-to-18.sh") + if err != nil { + t.Fatal(err) + } + if sum := sha256.Sum256(vendored); hex.EncodeToString(sum[:]) != kitSHA256 { + t.Fatalf("scripts/postgres-17-to-18.sh is not kit v2: sha256 %x", sum) + } + if fi, err := os.Stat("../../scripts/postgres-17-to-18.sh"); err != nil || fi.Mode().Perm() != 0o755 { + t.Fatalf("scripts/postgres-17-to-18.sh mode: %v %v", fi.Mode(), err) + } + cat, err := Load(Embedded()) + if err != nil { + t.Fatal(err) + } + if got := cat["kymessage"].Files["pg-upgrade/postgres-17-to-18.sh"]; !bytes.Equal(got, vendored) { + t.Fatal("kymessage's pg-upgrade/postgres-17-to-18.sh differs from scripts/postgres-17-to-18.sh") + } +} + +// PostgreSQL 18 everywhere the catalog runs its own Postgres, and 17 only for the dumps. +func TestPostgres18Images(t *testing.T) { + const pg18 = "postgres:18.7-alpine3.24@sha256:0115267ab5a509022df9319c77be365cef335adb71556c75f60f5360ee247e71" + const pg17 = "postgres:17.12-alpine3.24@sha256:f9cf3e1f0066f0eb0c48707d864f0ac5941e9ff454a072077d97a4d278d07d73" + cat, err := Load(Embedded()) + if err != nil { + t.Fatal(err) + } + for _, app := range []string{"kymessage", "kyidentity"} { + if im := cat[app].Images; im["postgres"] != pg18 || im["postgres_17"] != pg17 { + t.Errorf("%s: postgres %s, postgres_17 %s", app, im["postgres"], im["postgres_17"]) + } + } + if r := cat["kyidentity"].Kubernetes.Replicas; r.DatabaseImage != "postgres" || r.DumpImage != "postgres_17" { + t.Errorf("replicas %+v", r) + } + _, services, _ := messageCompose(t) + dump, pg := services["postgres-17-dump"], services["postgres"] + if dump.NetworkMode != "none" || dump.Environment["OLD"] != "/v/pgdata" || dump.Environment["NEW"] != "/v" || !slices.Contains(asList(dump.Volumes), "./pgdata:/v") { + t.Errorf("postgres-17-dump = %+v", dump) + } + if _, ok := pg.Environment["PGDATA"]; ok || !slices.Contains(asList(pg.Volumes), "./pgdata:/var/lib/postgresql") || !slices.Contains(asList(pg.Volumes), "./pg-upgrade/postgres-17-to-18.sh:/ky/postgres-17-to-18.sh:ro") { + t.Errorf("postgres = %+v", pg) + } +} + +func TestOnceServices(t *testing.T) { + const waits = " init:\n image: {{ .Images.web }}\n restart: \"no\"\n db:\n image: {{ .Images.web }}\n depends_on:\n init: {condition: service_completed_successfully}\n other:\n image: {{ .Images.web }}\n depends_on: [db]\n" + cat, err := Load(fstest.MapFS{"a/manifest.yaml": {Data: []byte(manifest)}, "a/compose.yaml.tmpl": {Data: []byte(compose + waits)}}) + if err != nil { + t.Fatal(err) + } + if a := cat["a"]; !slices.Equal(a.Once, []string{"init"}) || !slices.Equal(a.Services, []string{"db", "other", "web"}) { + t.Fatalf("once %v, services %v", a.Once, a.Services) + } + _, err = Load(fstest.MapFS{"a/manifest.yaml": {Data: []byte(manifest)}, "a/compose.yaml.tmpl": {Data: []byte(compose + strings.Replace(waits, " restart: \"no\"\n", "", 1))}}) + if err == nil || !strings.Contains(err.Error(), `needs restart: "no"`) { + t.Fatalf("restarting one-shot: %v", err) + } +} + +// An app without native_mail binds its files/ in its one rendering, all of them. +func TestFilesOfPlainApp(t *testing.T) { + bound := compose + " volumes: [./conf/x.sh:/x.sh:ro]\n" + cat, err := Load(fstest.MapFS{"a/manifest.yaml": {Data: []byte(manifest)}, "a/compose.yaml.tmpl": {Data: []byte(bound)}, "a/files/conf/x.sh": {Data: []byte("x")}}) + if err != nil || string(cat["a"].Files["conf/x.sh"]) != "x" || !slices.Equal(cat["a"].Nested, []string{"./conf/x.sh"}) { + t.Fatalf("bound file: %v", err) + } + _, err = Load(fstest.MapFS{"a/manifest.yaml": {Data: []byte(manifest)}, "a/compose.yaml.tmpl": {Data: []byte(compose)}, "a/files/conf/x.sh": {Data: []byte("x")}}) + if err == nil || !strings.Contains(err.Error(), "files/conf/x.sh is bound by no service") { + t.Fatalf("unbound file: %v", err) + } +} + +func TestMoveRejects(t *testing.T) { + const binds = compose + " volumes: [./pgdata:/v]\n" + move := func(from, to string) string { + return "upgrade:\n move:\n from: " + from + "\n to: " + to + "\n what: x\n" + } + for name, c := range map[string]struct{ manifest, compose string }{ + "outside binds": {manifest + move("other/a", "pgdata/b"), binds}, + "bind itself": {manifest + move("pgdata", "pgdata/b"), binds}, + "same file": {manifest + move("pgdata/a", "pgdata/a"), binds}, + "absolute": {manifest + move("/pgdata/a", "pgdata/b"), binds}, + "no what": {manifest + strings.Replace(move("pgdata/a", "pgdata/b"), " what: x\n", "", 1), binds}, + "kubernetes": {manifest + kube + move("pgdata/a", "pgdata/b"), binds}, + } { + if _, err := Load(fstest.MapFS{"a/manifest.yaml": {Data: []byte(c.manifest)}, "a/compose.yaml.tmpl": {Data: []byte(c.compose)}}); err == nil || !strings.Contains(err.Error(), "move needs") { + t.Errorf("%s: %v", name, err) + } + } + if _, err := Load(fstest.MapFS{"a/manifest.yaml": {Data: []byte(manifest + move("pgdata/a", "pgdata/b"))}, "a/compose.yaml.tmpl": {Data: []byte(binds)}}); err != nil { + t.Fatal(err) + } +} diff --git a/internal/catalog/render_kymessage_test.go b/internal/catalog/render_kymessage_test.go new file mode 100644 index 00000000..25adcc46 --- /dev/null +++ b/internal/catalog/render_kymessage_test.go @@ -0,0 +1,46 @@ +package catalog + +import ( + "encoding/json" + "io/fs" + "os" + "path/filepath" + "testing" +) + +// TestWriteKyMessageCompose is scripts/test-postgres-17-to-18.sh's renderer, skipped unless +// KYQ_RENDER_TO names a directory. It writes kymessage's compose.yaml as deploy renders it, +// the catalog files that file binds, and backup.json (the manifest's backup and restore +// commands), from the apps directory KYQ_RENDER_APPS (the embedded catalog when unset). +func TestWriteKyMessageCompose(t *testing.T) { + to := os.Getenv("KYQ_RENDER_TO") + if to == "" { + t.Skip("KYQ_RENDER_TO is not set") + } + var fsys fs.FS = Embedded() + if d := os.Getenv("KYQ_RENDER_APPS"); d != "" { + fsys = os.DirFS(d) + } + a, err := loadApp(fsys, "kymessage") + if err != nil { + t.Fatal(err) + } + write := func(name string, b []byte, mode os.FileMode) { + p := filepath.Join(to, name) + if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, b, mode); err != nil { + t.Fatal(err) + } + } + write("compose.yaml", a.WithRoute(messageRoute).WithPrivateRecovery(false).Compose, 0o600) + for name, b := range a.Files { + write(name, b, 0o644) // as deploy writes them + } + b, err := json.Marshal(map[string][]string{"command": a.Backup.Command, "restore": a.Backup.RestoreCommand}) + if err != nil { + t.Fatal(err) + } + write("backup.json", b, 0o600) +} diff --git a/internal/catalog/testdata/apps/dumpdemo/compose.yaml.tmpl b/internal/catalog/testdata/apps/dumpdemo/compose.yaml.tmpl index d2cbddf2..873dec54 100644 --- a/internal/catalog/testdata/apps/dumpdemo/compose.yaml.tmpl +++ b/internal/catalog/testdata/apps/dumpdemo/compose.yaml.tmpl @@ -8,7 +8,8 @@ services: secrets: [db_password] # The entrypoint reads the secret as root, before it drops to postgres. entrypoint: ["/bin/sh", "-c", "POSTGRES_PASSWORD=$$(cat /run/secrets/db_password) || exit 1; export POSTGRES_PASSWORD; exec docker-entrypoint.sh postgres"] - volumes: ["pgdata:/var/lib/postgresql/data"] + # 18 keeps its data in 18/docker below the volume; a test run starts on a fresh volume. + volumes: ["pgdata:/var/lib/postgresql"] healthcheck: test: ["CMD", "pg_isready", "-U", "postgres"] interval: 2s diff --git a/internal/catalog/testdata/apps/dumpdemo/manifest.yaml b/internal/catalog/testdata/apps/dumpdemo/manifest.yaml index 5001d68d..8144dfd2 100644 --- a/internal/catalog/testdata/apps/dumpdemo/manifest.yaml +++ b/internal/catalog/testdata/apps/dumpdemo/manifest.yaml @@ -3,8 +3,8 @@ name: dumpdemo category: ky version: 1.0.0 images: - # docker buildx imagetools inspect docker.io/library/postgres:17.6-alpine (linux/amd64), 2026-10-19. - postgres: docker.io/library/postgres:17.6-alpine@sha256:747d5ed1fdeeb124b880fbe3d7c6557d2c4064ae41d6b6297d417882effce4be + # docker buildx imagetools inspect docker.io/library/postgres:18.7-alpine3.24 (index), 2026-11-25. + postgres: docker.io/library/postgres:18.7-alpine3.24@sha256:0115267ab5a509022df9319c77be365cef335adb71556c75f60f5360ee247e71 whoami: traefik/whoami:v1.11.0@sha256:200689790a0a0ea48ca45992e0450bc26ccab5307375b41c84dfc4f2475937ab secrets: [db_password] health: diff --git a/internal/catalog/testdata/kymessage-docker-compose.matrix.yml b/internal/catalog/testdata/kymessage-docker-compose.matrix.yml index 6c4c0dcd..2d4b24cc 100644 --- a/internal/catalog/testdata/kymessage-docker-compose.matrix.yml +++ b/internal/catalog/testdata/kymessage-docker-compose.matrix.yml @@ -13,9 +13,9 @@ # Images are the official upstream builds, pinned by tag and digest, configured only by files. # Postgres, Synapse and MAS run as the owner of ./matrix (KY_MATRIX_UID/GID, printed by # matrix-init) so its 0600 files stay unreadable to anyone else. -# Element's page loads the logo from /app-icon.png. Its nginx sends no CSP -# header and its own meta CSP allows img-src *; a proxy in front must not add an img-src that -# excludes the admin host. Route https:///.well-known/matrix/{client,server} to the +# Element's page loads the logo from /app-icon.png and its home page and marks +# from /element-home*. Its nginx sends no CSP header and its own meta CSP allows +# img-src * and connect-src *; a proxy in front must not add either that excludes the admin host. Route https:///.well-known/matrix/{client,server} to the # app (the server file answers only while federation is open). x-hardening: &hardening restart: unless-stopped @@ -23,6 +23,12 @@ x-hardening: &hardening cap_drop: [ALL] # A read-only bind of a path matrix-init made; a missing one refuses the start, never creates it. x-matrix-ro: &matrix-ro {type: bind, read_only: true, bind: {create_host_path: false}} +# Calls are on by default and need KY_MATRIX_RTC_HOST and KY_MATRIX_MEDIA_BIND_IP; Compose +# refuses to start without them (compose/calls-on.yml). Chat only: KY_MATRIX_CALLS=off and +# docker-compose.chat-only.yml (docs/CALLS.md). No wildcard default. Any other value of +# KY_MATRIX_CALLS names no file and is refused. +include: + - path: compose/calls-${KY_MATRIX_CALLS:-on}.yml services: # Serves /.well-known/matrix/{client,server} and the members' Open chat link. @@ -33,7 +39,9 @@ services: - KY_MATRIX_SERVER_NAME=${KY_MATRIX_SERVER_NAME:?Set KY_MATRIX_SERVER_NAME} - KY_MATRIX_HOST=${KY_MATRIX_HOST:?Set KY_MATRIX_HOST} - KY_MATRIX_CHAT_HOST=${KY_MATRIX_CHAT_HOST:?Set KY_MATRIX_CHAT_HOST} - - KY_MATRIX_RTC_HOST=${KY_MATRIX_RTC_HOST:?Set KY_MATRIX_RTC_HOST} + # on unless KY_MATRIX_CALLS=off; compose/calls-on.yml holds the RTC host to being set. + - KY_MATRIX_CALLS=${KY_MATRIX_CALLS:-on} + - KY_MATRIX_RTC_HOST=${KY_MATRIX_RTC_HOST:-} - KY_MATRIX_RTC_KEY_FILE=/matrix/secrets/livekit_api_key - KY_MATRIX_RTC_SECRET_FILE=/matrix/secrets/livekit_api_secret # The meeting-notes bot (docker-compose.notes.yml) authenticates with it; off until Settings. @@ -92,27 +100,57 @@ services: - {<<: *matrix-ro, source: ./matrix/secrets/kyidentity_client_secret, target: /matrix/secrets/kyidentity_client_secret} - matrix-media:/matrix-media:ro + # PostgreSQL 18 keeps its data in 18/docker of the same volume, beside the 17 data in pgdata/, + # which stays untouched (docs/CHAT-SETUP.md "PostgreSQL 18"). A 17 stack moves on its first + # start: this one-shot dumps pgdata/ once into upgrade-from-17/, then the postgres service + # restores that dump before it starts. Without 17 data it does nothing. + postgres-17-dump: + image: postgres:17.12-alpine3.24@sha256:f9cf3e1f0066f0eb0c48707d864f0ac5941e9ff454a072077d97a4d278d07d73 + user: "${KY_MATRIX_UID:?}:${KY_MATRIX_GID:?}" + entrypoint: ["bash", "/ky/postgres-17-to-18.sh", "dump"] + environment: + OLD: /v/pgdata + NEW: /v + network_mode: none + restart: "no" + # A clean stop removes postmaster.pid, without which the next dump refuses. + stop_grace_period: 2m + read_only: true + tmpfs: [/tmp] + security_opt: ["no-new-privileges:true"] + cap_drop: [ALL] + volumes: + - matrix-postgres:/v + - &pg-upgrade {type: bind, source: ./scripts/postgres-17-to-18.sh, target: /ky/postgres-17-to-18.sh, read_only: true, bind: {create_host_path: false}} + postgres: <<: *hardening - image: postgres:17.6-alpine@sha256:ef257d85f76e48da1c64832459b59fcaba1a4dac97bf5d7450c77753542eee94 + image: postgres:18.7-alpine3.24@sha256:0115267ab5a509022df9319c77be365cef335adb71556c75f60f5360ee247e71 user: "${KY_MATRIX_UID:?Set KY_MATRIX_UID (printed by matrix-init)}:${KY_MATRIX_GID:?Set KY_MATRIX_GID (printed by matrix-init)}" + # Restores postgres-17-dump's dump once, then runs the image's own entrypoint. + entrypoint: ["bash", "/ky/postgres-17-to-18.sh", "restore"] + command: [postgres] environment: POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password - # A subdirectory: the volume root belongs to the image's postgres user, and initdb must - # own its directory. - PGDATA: /var/lib/postgresql/data/pgdata secrets: [postgres_password] networks: [matrix-db] volumes: - - matrix-postgres:/var/lib/postgresql/data + - matrix-postgres:/var/lib/postgresql - ./matrix/postgres:/docker-entrypoint-initdb.d:ro - # TCP, not the socket: during first-run init the entrypoint's temporary server listens on - # the socket only, so this passes once init.sql has run and the real server is up. + - *pg-upgrade + depends_on: + postgres-17-dump: {condition: service_completed_successfully} + # Time for a clean shutdown, so a rollback to 17 or a restore never meets a crashed cluster. + stop_grace_period: 2m + # TCP, not the socket: during first-run init or the restore the temporary server listens on + # the socket only, so this passes once the real server is up. The restore takes about as + # long as a pg_dumpall restore of the data, hence the long start period. healthcheck: test: ["CMD", "pg_isready", "-h", "127.0.0.1", "-U", "postgres", "-d", "postgres"] interval: 5s timeout: 5s retries: 30 + start_period: 1h # The media volume starts root-owned (the image's /media); hand it to the Synapse user once # per start. Only CAP_CHOWN, no network. @@ -135,6 +173,9 @@ services: # The stock start.py passes these through; Synapse merges the files in order, so the # console-owned federation file sets listeners and the allow-list. command: ["run", "--config-path", "/config/homeserver.yaml", "--config-path", "/federation.yaml"] + # homeserver.yaml loads the meeting-guest confinement module, ky_guests.py in /config. + environment: + PYTHONPATH: /config networks: [default, matrix-db] volumes: - ./matrix/synapse:/config:ro @@ -186,6 +227,9 @@ services: # a copy made at start, so a console rename shows after `docker compose restart element` # (the restart keeps this bind's inode, which both writers update in place). - ./matrix/element/config.json:/app/config.json:ro + # The meeting-guest bootstrap page matrix-init renders (docs/KYCALENDAR.md "Guests"), served + # from Element's origin, where Element restores sessions from. Static; its CSP is its own. + - ./matrix/element/kymessages-guest.html:/app/kymessages-guest.html:ro depends_on: synapse: {condition: service_healthy} healthcheck: @@ -202,11 +246,14 @@ services: volumes: - {<<: *matrix-ro, source: ./matrix/livekit, target: /config} # Media bypasses the HTTP tunnel. Forward these two ports unchanged to this host. No - # wildcard default: the operator names the interface that may receive media. + # wildcard default: the operator names the interface that may receive media + # (compose/calls-on.yml; loopback only with KY_MATRIX_CALLS=off, which starts no LiveKit). + # The same port on both sides: LiveKit advertises what matrix-init wrote from the same + # KY_MATRIX_MEDIA_TCP_PORT/_UDP_PORT (default 7881/7882) in its ICE candidates. # 7880 signalling/admin stays private, reached by the proxy and KyMessages. ports: - - "${KY_MATRIX_MEDIA_BIND_IP:?set KY_MATRIX_MEDIA_BIND_IP to the host address for call media, or 0.0.0.0 for every interface}:7881:7881/tcp" - - "${KY_MATRIX_MEDIA_BIND_IP:?set KY_MATRIX_MEDIA_BIND_IP to the host address for call media, or 0.0.0.0 for every interface}:7882:7882/udp" + - "${KY_MATRIX_MEDIA_BIND_IP:-127.0.0.1}:${KY_MATRIX_MEDIA_TCP_PORT:-7881}:${KY_MATRIX_MEDIA_TCP_PORT:-7881}/tcp" + - "${KY_MATRIX_MEDIA_BIND_IP:-127.0.0.1}:${KY_MATRIX_MEDIA_UDP_PORT:-7882}:${KY_MATRIX_MEDIA_UDP_PORT:-7882}/udp" # One-shot, after `kymessages restore` and `kymessages matrix-init` (which recreates the # superuser password the capsule leaves out), against a fresh stack with only postgres up: diff --git a/internal/catalog/testdata/rendered.golden.yaml b/internal/catalog/testdata/rendered.golden.yaml index 00fcc442..4c6c51b3 100644 --- a/internal/catalog/testdata/rendered.golden.yaml +++ b/internal/catalog/testdata/rendered.golden.yaml @@ -321,6 +321,7 @@ kyidentity: replicas: since: 0.6.0.2 database_image: postgres + dump_image: postgres_17 database_size: 2Gi cluster_image: postgres_cluster kynotes: diff --git a/internal/cli/cli.go b/internal/cli/cli.go index 183be4b2..91889a6d 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -967,10 +967,21 @@ func (s *session) deploySteps(ctx context.Context) ([]engine.Step, error) { return nil, fmt.Errorf("%s: %w", name, err) } t := s.placed[name] - note, backupFrom, err := gate(name, s.cat[name], deployed, s.o.ReleaseSet, s.ack, s.preUpgradeRefusal(name, t)) + noBackup := s.preUpgradeRefusal(name, t) + note, backupFrom, err := gate(name, s.cat[name], deployed, s.o.ReleaseSet, s.ack, noBackup) if err != nil { return nil, err } + if sd, ok := d.(sshDriver); ok && deployed.Found { + unmoved, err := dockerhost.Unmoved(ctx, sd.app(name, s.cat[name], s.o.ReleaseSet)) + if err != nil { + return nil, fmt.Errorf("%s: %w", name, err) + } + from := installedVersion(deployed, s.cat[name], s.o.ReleaseSet) + if note, backupFrom, err = moveGate(name, s.cat[name], unmoved, from, note, backupFrom, s.ack, noBackup); err != nil { + return nil, err + } + } if note != "" { steps = append(steps, noteStep{id: name + ".upgrade", note: note}) } diff --git a/internal/cli/move_test.go b/internal/cli/move_test.go new file mode 100644 index 00000000..0bf49221 --- /dev/null +++ b/internal/cli/move_test.go @@ -0,0 +1,80 @@ +package cli + +import ( + "os" + "path/filepath" + "strings" + "testing" + "testing/fstest" + + "github.com/Busnes-app/kyquickstart/internal/engine" + "github.com/Busnes-app/kyquickstart/internal/managed" + "github.com/Busnes-app/kyquickstart/internal/suite" +) + +// An upgrade.move (kymessage's PostgreSQL 17 to 18) gates a deploy at the same version on +// what the target holds: with a destination it is backed up first, and a failed backup leaves +// the old files deployed; without one it needs --acknowledge-no-backup; once moved, nothing. +func TestUpgradeMoveBacksUpFirst(t *testing.T) { + f, _, k := backupFixture(t) + dir := filepath.Join(f.h.root, "dumpdemo") + m := string(dumpCatalog["dumpdemo/manifest.yaml"].Data) + "upgrade:\n move:\n from: files/old/PG_VERSION\n to: files/new/PG_VERSION\n what: the test move\n" + f.o.Catalog = fstest.MapFS{ + "dumpdemo/manifest.yaml": {Data: []byte(m)}, + "dumpdemo/compose.yaml.tmpl": {Data: append(dumpCatalog["dumpdemo/compose.yaml.tmpl"].Data, " environment: {MOVED: 'yes'}\n"...)}, + } + os.MkdirAll(filepath.Join(dir, "files", "old"), 0o700) + os.WriteFile(filepath.Join(dir, "files", "old", "PG_VERSION"), []byte("17\n"), 0o600) + deployed := func() bool { + b, _ := os.ReadFile(filepath.Join(dir, "compose.yaml")) + return strings.Contains(string(b), "MOVED") + } + + // The backup fails: nothing deployed. + k.match = "'backup' '--json'" + err := f.run("upgrade", "dumpdemo") + k.match = "" + if err == nil || !strings.Contains(err.Error(), "no upgrade: the pre-upgrade backup failed") || deployed() { + t.Fatalf("failed backup: %v, deployed %v\n%s", err, deployed(), f.out.String()) + } + // It succeeds: one snapshot, then the deploy. + if err := f.run("upgrade", "dumpdemo"); err != nil || !deployed() { + t.Fatalf("upgrade: %v, deployed %v\n%s", err, deployed(), f.out.String()) + } + backup, _ := engine.Read(filepath.Join(f.state, "results"), "dumpdemo.pre-upgrade-backup") + note, _ := engine.Read(filepath.Join(f.state, "results"), "dumpdemo.upgrade") + if backup.Status != "ok" || note.Diagnostics != "dumpdemo 1.0.0 moves the test move, after a verified pre-upgrade backup" { + t.Fatalf("backup %+v, note %q", backup, note.Diagnostics) + } + // Moved: the gate says nothing more. + os.MkdirAll(filepath.Join(dir, "files", "new"), 0o700) + os.WriteFile(filepath.Join(dir, "files", "new", "PG_VERSION"), []byte("18\n"), 0o600) + if err := f.run("upgrade", "dumpdemo"); err != nil || strings.Contains(f.out.String(), "pre-upgrade-backup") { + t.Fatalf("moved app gated again: %v\n%s", err, f.out.String()) + } +} + +func TestUpgradeMoveWithoutDestination(t *testing.T) { + f, _, _ := backupFixture(t) + dir := filepath.Join(f.h.root, "dumpdemo") + f.plan(t, "installation_id: "+installation+"\napps:\n - name: dumpdemo\n target: nas\n") + m := string(dumpCatalog["dumpdemo/manifest.yaml"].Data) + "upgrade:\n move:\n from: files/old/PG_VERSION\n to: files/new/PG_VERSION\n what: the test move\n" + f.o.Catalog = fstest.MapFS{"dumpdemo/manifest.yaml": {Data: []byte(m)}, "dumpdemo/compose.yaml.tmpl": dumpCatalog["dumpdemo/compose.yaml.tmpl"]} + os.MkdirAll(filepath.Join(dir, "files", "old"), 0o700) + os.WriteFile(filepath.Join(dir, "files", "old", "PG_VERSION"), []byte("17\n"), 0o600) + before, _ := os.ReadFile(filepath.Join(dir, "compose.kyq.yaml")) + + err := f.run("upgrade", "dumpdemo") + after, _ := os.ReadFile(filepath.Join(dir, "compose.kyq.yaml")) + if code(err) != suite.AckRequired || !strings.Contains(err.Error(), "moves the test move, and kyquickstart cannot back it up first here") || !strings.Contains(err.Error(), "--acknowledge-no-backup") || string(after) != string(before) { + t.Fatalf("no destination: %v\n%s", err, f.out.String()) + } + if err := f.run("upgrade", "dumpdemo", "--acknowledge-no-backup"); err != nil { + t.Fatal(err, f.out.String()) + } + note, _ := engine.Read(filepath.Join(f.state, "results"), "dumpdemo.upgrade") + b, _ := os.ReadFile(filepath.Join(dir, "compose.kyq.yaml")) + if note.Diagnostics != "dumpdemo 1.0.0 moves the test move; operator acknowledged no pre-upgrade backup" || !strings.Contains(string(b), managed.Label) { + t.Fatalf("note %q\n%s", note.Diagnostics, f.out.String()) + } +} diff --git a/internal/cli/suite.go b/internal/cli/suite.go index 5fcafab4..c6dc7e5a 100644 --- a/internal/cli/suite.go +++ b/internal/cli/suite.go @@ -691,6 +691,36 @@ func gate(name string, app catalog.App, d managed.Deployed, releaseSet string, a return note, backupFrom, nil } +// moveGate adds an app's upgrade.move to gate's decision when the app has not made it yet +// (unmoved): the deploy that makes it is backed up first where kyquickstart can, one backup +// for both, and otherwise needs ack. from is the installed version. +func moveGate(name string, app catalog.App, unmoved bool, from, note, backupFrom string, ack bool, noBackup error) (string, string, error) { + mv := app.Upgrade.Move + if mv == nil || !unmoved { + return note, backupFrom, nil + } + join := func(s string) string { + if note == "" { + return s + } + return note + "; " + s + } + switch { + case backupFrom != "": + return join("it also moves " + mv.What), backupFrom, nil + case noBackup == nil: + return join(fmt.Sprintf("%s %s moves %s, after a verified pre-upgrade backup", name, app.Version, mv.What)), from, nil + case !ack: + var se *suite.Error + reason := noBackup.Error() + if errors.As(noBackup, &se) { + reason = se.Message + } + return "", "", suite.Errorf(suite.AckRequired, "deploying %s %s moves %s, and kyquickstart cannot back it up first here: %s. Give the target a backup destination, or pass --acknowledge-no-backup to proceed without one", name, app.Version, mv.What, reason) + } + return join(fmt.Sprintf("%s %s moves %s; operator acknowledged no pre-upgrade backup", name, app.Version, mv.What)), "", nil +} + // noteStep changes nothing; its ok result records the note. type noteStep struct{ id, note string } diff --git a/internal/dockerhost/app.go b/internal/dockerhost/app.go index 5f49e86a..e5b60a4c 100644 --- a/internal/dockerhost/app.go +++ b/internal/dockerhost/app.go @@ -114,3 +114,18 @@ func (a App) ps(ctx context.Context) ([]container, error) { } return parsePS(out) } + +// Unmoved reports whether the app still has to make its catalog's upgrade.move: its +// directory holds the move's from file and lacks its to file. +func Unmoved(ctx context.Context, a App) (bool, error) { + mv := a.Catalog.Upgrade.Move + if mv == nil { + return false, nil + } + cmd := "cd " + remote.Quote(a.dir()) + " 2>/dev/null || exit 0; if [ -s " + remote.Quote(mv.From) + " ] && [ ! -s " + remote.Quote(mv.To) + " ]; then echo unmoved; fi" + out, err := a.Runner.Run(ctx, cmd, nil) + if err != nil { + return false, fmt.Errorf("read %s's data layout: %w", a.Name, err) + } + return strings.TrimSpace(string(out)) == "unmoved", nil +} diff --git a/internal/dockerhost/deploy.go b/internal/dockerhost/deploy.go index f34096ce..e8db8290 100644 --- a/internal/dockerhost/deploy.go +++ b/internal/dockerhost/deploy.go @@ -48,11 +48,11 @@ type edgeNetwork struct { Name string `yaml:"name"` } -// override is compose.kyq.yaml: labels on every service and, with an edge network, that +// override is compose.kyq.yaml: labels on every service but the profiles' and, with an edge network, that // network for service "app" beside its default one. func (a App) override(labels map[string]string) []byte { o := overrideFile{Services: map[string]overrideService{}} - for _, s := range a.Catalog.Services { + for _, s := range append(slices.Clone(a.Catalog.Services), a.Catalog.Once...) { o.Services[s] = overrideService{Labels: labels} } if a.EdgeNetwork != "" { diff --git a/internal/dockerhost/deploy_test.go b/internal/dockerhost/deploy_test.go index d1fce1d9..19065d00 100644 --- a/internal/dockerhost/deploy_test.go +++ b/internal/dockerhost/deploy_test.go @@ -39,11 +39,11 @@ func TestOverrideLabelsEveryService(t *testing.T) { Services map[string]struct{ Labels map[string]string } } a := App{Name: "hello"} - a.Catalog.Services = []string{"web", "db"} + a.Catalog.Services, a.Catalog.Once = []string{"web", "db"}, []string{"dump"} if err := yaml.Unmarshal(a.override(labels("rs-1", "1.2.3")), &o); err != nil { t.Fatal(err) } - for _, svc := range []string{"web", "db"} { + for _, svc := range []string{"web", "db", "dump"} { l := o.Services[svc].Labels if l[managed.Label] != managed.Value || l[managed.ReleaseSetLabel] != "rs-1" || l[managed.VersionLabel] != "1.2.3" { t.Errorf("%s labels = %v", svc, l) @@ -399,3 +399,23 @@ func TestFailedPullKeepsDeployedVersion(t *testing.T) { t.Fatalf("compose.yaml = %q, want the new layout", b) } } + +// Unmoved: the move's from file present and its to file absent, read on the target. +func TestUnmoved(t *testing.T) { + root := t.TempDir() + a := App{Name: "chat", Root: root, Runner: remote.Local{}} + a.Catalog.Upgrade.Move = &catalog.Move{From: "pgdata/pgdata/PG_VERSION", To: "pgdata/18/docker/PG_VERSION", What: "x"} + check := func(want bool) { + t.Helper() + if got, err := Unmoved(context.Background(), a); err != nil || got != want { + t.Fatalf("unmoved = %v, %v; want %v", got, err, want) + } + } + check(false) // no app directory: a fresh install + os.MkdirAll(filepath.Join(root, "chat", "pgdata", "pgdata"), 0o700) + os.WriteFile(filepath.Join(root, "chat", "pgdata", "pgdata", "PG_VERSION"), []byte("17\n"), 0o600) + check(true) + os.MkdirAll(filepath.Join(root, "chat", "pgdata", "18", "docker"), 0o700) + os.WriteFile(filepath.Join(root, "chat", "pgdata", "18", "docker", "PG_VERSION"), []byte("18\n"), 0o600) + check(false) +} diff --git a/internal/dockerhost/manage.go b/internal/dockerhost/manage.go index 88dad388..7a358b81 100644 --- a/internal/dockerhost/manage.go +++ b/internal/dockerhost/manage.go @@ -203,7 +203,9 @@ func (s unmanageStep) plan(ctx context.Context) (recreate, start []string, err e } lines := strings.Split(strings.TrimSpace(string(out)), "\n") valid := func(names []string) bool { - return !slices.ContainsFunc(names, func(n string) bool { return !slices.Contains(s.a.Catalog.Services, n) }) + return !slices.ContainsFunc(names, func(n string) bool { + return !slices.Contains(s.a.Catalog.Services, n) && !slices.Contains(s.a.Catalog.Once, n) + }) } if len(lines) != 2 || !strings.HasPrefix(lines[0], "recreate") || !strings.HasPrefix(lines[1], "start") { return nil, nil, fmt.Errorf("%s is not an unmanage record; inspect it by hand", s.record()) diff --git a/internal/kube/postgres-17-to-18.sh b/internal/kube/postgres-17-to-18.sh new file mode 100644 index 00000000..85b7729b --- /dev/null +++ b/internal/kube/postgres-17-to-18.sh @@ -0,0 +1,89 @@ +#!/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 +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} + if [ -s "$new/18/docker/PG_VERSION" ] || [ -s "$dump_dir/dump.sql" ]; then + echo "postgres-17-to-18: already done"; exit 0 + 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 + # 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. + if [ -e "$old/postmaster.pid" ]; then + 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 + fi + # 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" + 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/internal/kube/render_database_test.go b/internal/kube/render_database_test.go new file mode 100644 index 00000000..07296bfc --- /dev/null +++ b/internal/kube/render_database_test.go @@ -0,0 +1,25 @@ +package kube + +import ( + "encoding/json" + "os" + "testing" +) + +// TestWriteDatabasePod is scripts/test-postgres-17-to-18-pod.sh's renderer, skipped unless +// KYQ_RENDER_POD names a file: it writes the pod spec of the replicated KyIdentity's database +// Deployment as apply renders it. +func TestWriteDatabasePod(t *testing.T) { + to := os.Getenv("KYQ_RENDER_POD") + if to == "" { + t.Skip("KYQ_RENDER_POD is not set") + } + a, _, _ := replicatedApp(t, 2, "") + b, err := json.Marshal(render(a).Database.Spec.Template.Spec) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(to, b, 0o600); err != nil { + t.Fatal(err) + } +} diff --git a/internal/kube/replicas.go b/internal/kube/replicas.go index 8a1b074e..21073d74 100644 --- a/internal/kube/replicas.go +++ b/internal/kube/replicas.go @@ -3,6 +3,7 @@ package kube import ( "bytes" "context" + _ "embed" "errors" "fmt" "net/url" @@ -46,16 +47,24 @@ const ( superuserKey = "superuser-password" ) -// databaseCommand writes the first start's init script, then starts Postgres as the image -// does. The script gives the app a role that owns its database and nothing else, and keeps a -// failing statement, which would carry the password, out of the server log. +// postgresUpgrade is the suite's PostgreSQL 17 to 18 kit, scripts/postgres-17-to-18.sh byte +// for byte: the database pod's init container dumps a 17 data directory once with it, and +// its Postgres restores that dump before the image's entrypoint runs. +// +//go:embed postgres-17-to-18.sh +var postgresUpgrade string + +// databaseCommand writes the first start's init script, then starts Postgres through the +// kit, its $1, which runs the image's entrypoint. The script gives the app a role that owns +// its database and nothing else, and keeps a failing statement, which would carry the +// password, out of the server log. A restored 17 database brings its roles instead. const databaseCommand = `cat > /docker-entrypoint-initdb.d/10-app.sql <<'SQL' SET log_min_error_statement = panic; \set pw ` + "`cat /run/secrets/" + passwordKey + "`" + ` CREATE ROLE ` + databaseUser + ` LOGIN PASSWORD :'pw'; CREATE DATABASE ` + databaseUser + ` OWNER ` + databaseUser + ` ENCODING 'UTF8' LOCALE 'C' TEMPLATE template0; SQL -exec docker-entrypoint.sh postgres` +exec bash -c "$1" postgres-17-to-18.sh restore postgres` // replicaKeys are the four keys every replica must share: the variable that names each, and // its file in a single instance's data directory, which is also its key in the Secret. @@ -198,6 +207,8 @@ func database(o *objects, a App, meta func(string) metav1.ObjectMeta) { EnableServiceLinks: ptr.To(false), Affinity: spread, Tolerations: leaveDeadNode, + // A clean stop removes postmaster.pid, without which a 17 dump refuses. + TerminationGracePeriodSeconds: ptr.To(int64(120)), SecurityContext: &corev1.PodSecurityContext{ RunAsNonRoot: ptr.To(true), FSGroup: ptr.To(int64(postgresUID)), @@ -211,13 +222,25 @@ func database(o *objects, a App, meta func(string) metav1.ObjectMeta) { Resources: corev1.ResourceRequirements{Requests: initResources, Limits: initResources}, SecurityContext: restricted, VolumeMounts: []corev1.VolumeMount{{Name: claim, MountPath: "/volumes/" + databaseName}}, + }, { + // PostgreSQL 17 kept its data in pgdata/; 18 keeps it in 18/docker beside it. + // This dumps the 17 data once for the restore and never writes it. + Name: "postgres-17-dump", + Image: c.Images[k.Replicas.DumpImage], + Command: []string{"bash", "-c", postgresUpgrade, "postgres-17-to-18.sh", "dump"}, + Env: []corev1.EnvVar{{Name: "OLD", Value: "/v/pgdata"}, {Name: "NEW", Value: "/v"}}, + Resources: corev1.ResourceRequirements{Requests: corev1.ResourceList{corev1.ResourceCPU: resource.MustParse("100m"), corev1.ResourceMemory: databaseResources[corev1.ResourceMemory]}, Limits: databaseResources}, + SecurityContext: restricted, + VolumeMounts: []corev1.VolumeMount{ + {Name: claim, MountPath: "/v", SubPath: privateDir}, + {Name: "tmp", MountPath: "/tmp"}, + }, }}, Containers: []corev1.Container{{ Name: databaseName, Image: c.Images[k.Replicas.DatabaseImage], - Command: []string{"/bin/sh", "-ec", databaseCommand}, + Command: []string{"/bin/sh", "-ec", databaseCommand, "sh", postgresUpgrade}, Env: []corev1.EnvVar{ - {Name: "PGDATA", Value: "/var/lib/postgresql/data/pgdata"}, {Name: "POSTGRES_INITDB_ARGS", Value: "--encoding=UTF8 --locale=C"}, {Name: "POSTGRES_PASSWORD_FILE", Value: "/run/secrets/" + superuserKey}, }, @@ -230,7 +253,7 @@ func database(o *objects, a App, meta func(string) metav1.ObjectMeta) { StartupProbe: &corev1.Probe{ProbeHandler: listening, PeriodSeconds: 10, FailureThreshold: 180}, LivenessProbe: &corev1.Probe{ProbeHandler: listening, PeriodSeconds: 10, FailureThreshold: 6}, VolumeMounts: []corev1.VolumeMount{ - {Name: claim, MountPath: "/var/lib/postgresql/data", SubPath: privateDir}, + {Name: claim, MountPath: "/var/lib/postgresql", SubPath: privateDir}, {Name: "tmp", MountPath: "/tmp"}, {Name: "run", MountPath: "/var/run/postgresql"}, {Name: "initdb", MountPath: "/docker-entrypoint-initdb.d"}, diff --git a/internal/kube/replicas_test.go b/internal/kube/replicas_test.go index 7c4f9749..4be867e5 100644 --- a/internal/kube/replicas_test.go +++ b/internal/kube/replicas_test.go @@ -3,6 +3,7 @@ package kube import ( "context" "encoding/json" + "os" "path" "slices" "strings" @@ -152,6 +153,33 @@ func TestRenderReplicas(t *testing.T) { if strings.Contains(script, "SUPERUSER") || envOf(c)["POSTGRES_USER"].Value != "" { t.Error("the app's role must not be the superuser") } + // PostgreSQL 18 beside the 17 data on the same claim: the 17 image dumps pgdata/ once, the + // kit restores it, both from the vendored kit byte for byte (scripts/postgres-17-to-18.sh). + kit, err := os.ReadFile("../../scripts/postgres-17-to-18.sh") + if err != nil { + t.Fatal(err) + } + mounts := func(c corev1.Container) map[string]corev1.VolumeMount { + m := map[string]corev1.VolumeMount{} + for _, v := range c.VolumeMounts { + m[v.MountPath] = v + } + return m + } + if len(db.InitContainers) != 2 || db.InitContainers[0].Name != "private-volumes" { + t.Fatalf("init containers = %+v", db.InitContainers) + } + dump := db.InitContainers[1] + if dump.Name != "postgres-17-dump" || dump.Image != a.Catalog.Images["postgres_17"] || !strings.HasPrefix(a.Catalog.Images["postgres_17"], "postgres:17.") || + !slices.Equal(dump.Command, []string{"bash", "-c", string(kit), "postgres-17-to-18.sh", "dump"}) || envOf(dump)["OLD"].Value != "/v/pgdata" || envOf(dump)["NEW"].Value != "/v" || + mounts(dump)["/v"].SubPath != privateDir || mounts(dump)["/tmp"].Name != "tmp" || dump.SecurityContext != sc { + t.Fatalf("dump = %+v", dump) + } + if len(c.Command) != 5 || c.Command[4] != string(kit) || !strings.HasSuffix(script, `exec bash -c "$1" postgres-17-to-18.sh restore postgres`) || + mounts(c)["/var/lib/postgresql"].SubPath != privateDir || mounts(c)["/var/lib/postgresql/data"].Name != "" || envOf(c)["PGDATA"].Value != "" || + !strings.HasPrefix(c.Image, "postgres:18.") || *db.TerminationGracePeriodSeconds != 120 { + t.Fatalf("database = %+v", c) + } p := o.DatabasePolicy.Spec if len(p.PolicyTypes) != 2 || len(p.Egress) != 0 || len(p.Ingress) != 1 || p.Ingress[0].From[0].PodSelector.MatchLabels[servesLabel] != "kyidentity" || p.Ingress[0].From[0].NamespaceSelector != nil || p.Ingress[0].Ports[0].Port.IntValue() != 5432 || p.PodSelector.MatchLabels[nameLabel] != "kyidentity-database" { diff --git a/scripts/postgres-17-to-18.sh b/scripts/postgres-17-to-18.sh new file mode 100755 index 00000000..85b7729b --- /dev/null +++ b/scripts/postgres-17-to-18.sh @@ -0,0 +1,89 @@ +#!/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 +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} + if [ -s "$new/18/docker/PG_VERSION" ] || [ -s "$dump_dir/dump.sql" ]; then + echo "postgres-17-to-18: already done"; exit 0 + 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 + # 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. + if [ -e "$old/postmaster.pid" ]; then + 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 + fi + # 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" + 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-pod.sh b/scripts/test-postgres-17-to-18-pod.sh new file mode 100755 index 00000000..0f483210 --- /dev/null +++ b/scripts/test-postgres-17-to-18-pod.sh @@ -0,0 +1,127 @@ +#!/bin/bash +# Proves the replicated KyIdentity's database pod (internal/kube/replicas.go) moves from +# PostgreSQL 17 to 18 on its claim. It runs the pod specs apply renders, from the previous +# commit (PREV) and from this checkout, in Docker as a kubelet would (each init container in +# order, then Postgres; the claim's subPath as a volume subpath, emptyDirs as tmpfs, the +# Secret as a read-only volume, fsGroup as the claim's group, read-only root, uid 70). +# Asserts rows, the app role's password over the network and a wrong one refused, the C +# locale and checksums; a dump beside a live 17 refuses and writes nothing; 17 restarts on +# its untouched data; a rerun is a no-op; a fresh claim initialises. Not Kubernetes itself. +# NEW_SRC renders the new side from another source tree (mutation checks). +# usage: scripts/test-postgres-17-to-18-pod.sh (from the repository; needs Docker, Go, git) +set -Eeuo pipefail +repo=$(cd "$(dirname "$0")/.." && pwd) +PREV=${PREV:-950c3f8} # origin/master before PostgreSQL 18 +P18=postgres:18.7-alpine3.24@sha256:0115267ab5a509022df9319c77be365cef335adb71556c75f60f5360ee247e71 +work=$(mktemp -d "${TMPDIR:-/tmp}/kyq-pg18pod.XXXXXX") +id=kyqpg18pod$$ +cleanup() { + docker rm -f "$id-db" >/dev/null 2>&1 || true + docker volume rm -f "$id-claim" "$id-fresh" "$id-secret" >/dev/null 2>&1 || true + docker network rm "$id" >/dev/null 2>&1 || true + rm -rf "$work" +} +trap cleanup EXIT +fail() { echo "FAIL: $*" >&2; docker logs --tail 30 "$id-db" >&2 2>&1 || true; exit 1; } + +# The pod specs: this checkout's, and PREV's through the same renderer copied into it. +render() { (cd "$1" && KYQ_RENDER_POD=$2 go test ./internal/kube -run '^TestWriteDatabasePod$' -count=1 >/dev/null) || fail "render $2"; } +mkdir -p "$work/prev" +git -C "$repo" archive "$PREV" | tar -x -C "$work/prev" +cp "$repo/internal/kube/render_database_test.go" "$work/prev/internal/kube/" +render "$work/prev" "$work/old.json" +[ -z "${NEW_SRC:-}" ] || cp "$repo/internal/kube/render_database_test.go" "$NEW_SRC/internal/kube/" +render "${NEW_SRC:-$repo}" "$work/new.json" +grep -q 'postgres:17' "$work/old.json" || fail "$PREV's database pod is not on PostgreSQL 17" + +docker network create "$id" >/dev/null +# The Secret kyq-database: 0440, group 70 (fsGroup), as the kubelet projects it. +docker volume create "$id-secret" >/dev/null +docker run --rm -v "$id-secret:/s" "$P18" sh -c 'printf app-pw > /s/password && printf su-pw > /s/superuser-password && chown 0:70 /s/* && chmod 0440 /s/*' +claim() { docker volume create "$1" >/dev/null; docker run --rm -v "$1:/v" "$P18" chown 70:70 /v; } # fsGroup + +# pod [init]: the init containers in order, then (unless init) Postgres. +pod() { + python3 - "$1" "$2" "$id" "${3:-}" > "$work/run.sh" <<'PY' +import json, shlex, sys +spec, claim, id, only_init = json.load(open(sys.argv[1])), sys.argv[2], sys.argv[3], sys.argv[4] +vols = {v["name"]: v for v in spec["volumes"]} +gid = spec["securityContext"]["fsGroup"] +def run(c, detach): + sc = c["securityContext"] + a = ["docker", "run", "--name", id + "-db" if detach else id + "-init", "--network", id if detach else "none", + "--user", f'{sc["runAsUser"]}:{sc["runAsGroup"]}', "--group-add", str(gid), "--cap-drop", "ALL", + "--security-opt", "no-new-privileges", "--memory", c["resources"]["limits"]["memory"].replace("Mi", "m")] + a += ["-d"] if detach else ["--rm"] + if sc.get("readOnlyRootFilesystem"): + a.append("--read-only") + for e in c.get("env", []): + a += ["-e", f'{e["name"]}={e["value"]}'] + for m in c["volumeMounts"]: + v = vols[m["name"]] + if "persistentVolumeClaim" in v: + a += ["--mount", f'type=volume,src={claim},dst={m["mountPath"]}' + (f',volume-subpath={m["subPath"]}' if m.get("subPath") else "")] + elif "emptyDir" in v: + a += ["--mount", f'type=tmpfs,dst={m["mountPath"]},tmpfs-mode=1777'] + else: + a += ["--mount", f'type=volume,src={id}-secret,dst={m["mountPath"]},readonly'] + a += ["--entrypoint", c["command"][0], c["image"]] + c["command"][1:] + c.get("args", []) + print(shlex.join(a) + (" >/dev/null" if detach else "")) +for c in spec["initContainers"]: + run(c, False) +if not only_init: + run(spec["containers"][0], True) +PY + bash "$work/run.sh" +} +ready() { for _ in $(seq 1 120); do docker exec "$id-db" pg_isready -q -h 127.0.0.1 -U kyidentity -d kyidentity 2>/dev/null && return 0; [ "$(docker inspect -f '{{.State.Running}}' "$id-db")" = true ] || return 1; sleep 1; done; return 1; } +stop() { docker stop -t 120 "$id-db" >/dev/null; docker rm "$id-db" >/dev/null; } # the image's STOPSIGNAL, as containerd sends it +# Over the network from another container: the app's role and password (loopback is trust). +client() { docker run --rm --network "$id" -e PGPASSWORD="$1" "$P18" psql -h "$id-db" -U kyidentity -d kyidentity -XAtc "$2"; } +in_claim() { docker run --rm -v "$1:/v" "$P18" sh -c "$2"; } + +# 1. A 17 database from the previous pod spec, with rows. +claim "$id-claim" +pod "$work/old.json" "$id-claim" || fail "17 pod" +ready || fail "17 not ready" +client app-pw "create table users(id bigserial primary key, name text collate \"C\" unique, j jsonb); insert into users(name, j) select 'u' || g, jsonb_build_object('g', g) from generate_series(1, 20000) g" >/dev/null || fail "seed" + +# 2. The new pod's dump beside the live 17 refuses and writes nothing. +out=$(pod "$work/new.json" "$id-claim" init 2>&1) && fail "dump ran beside a live 17: $out" +grep -q postmaster.pid <<<"$out" || fail "no live-server message: $out" +in_claim "$id-claim" 'test ! -e /v/private/upgrade-from-17/dump.sql' || fail "dump written beside a live 17" + +# 3. The rollout: the old pod stops, the new one dumps, restores and serves 18. +stop +pod "$work/new.json" "$id-claim" || fail "18 pod" +ready || fail "18 not ready after the move" +[ "$(client app-pw 'show server_version_num' | cut -c1-2)" = 18 ] || fail "not 18" +[ "$(client app-pw "select count(*) || ',' || sum((j->>'g')::int) from users")" = "20000,200010000" ] || fail "rows" +[ "$(client app-pw "select datcollate from pg_database where datname = 'kyidentity'")" = C ] || fail "locale" +[ "$(client app-pw 'show data_checksums')" = on ] || fail "checksums" +[ "$(client app-pw 'select rolsuper from pg_roles where rolname = current_user')" = f ] || fail "app role became a superuser" +client wrong 'select 1' >/dev/null 2>&1 && fail "a wrong password logged in" +# shellcheck disable=SC2016 # expanded in the container +in_claim "$id-claim" '[ "$(stat -c %u /v/private/18/docker)" = 70 ] && [ -s /v/private/pgdata/PG_VERSION ]' || fail "layout" + +# 4. Rollback: the previous pod spec's 17 starts on its untouched data. +stop +{ pod "$work/old.json" "$id-claim" && ready; } || fail "17 no longer starts on its data" +[ "$(client app-pw 'select count(*) from users')" = 20000 ] || fail "17 data changed" +stop + +# 5. Rerun: nothing dumped or restored again. +out=$(pod "$work/new.json" "$id-claim" 2>&1) || fail "18 restart: $out" +grep -q 'already done' <<<"$out" || fail "rerun dumped again: $out" +ready || fail "18 not ready after a restart" +! grep -q 'postgres-17-to-18: restored' <<<"$(docker logs "$id-db" 2>&1)" || fail "rerun restored again" +stop + +# 6. A fresh claim: nothing to move, the app's role and database from the init script. +claim "$id-fresh" +out=$(pod "$work/new.json" "$id-fresh" 2>&1) || fail "fresh pod: $out" +grep -q 'nothing to move' <<<"$out" || fail "fresh claim did not skip the dump" +ready || fail "fresh 18 not ready" +[ "$(client app-pw 'show server_version_num' | cut -c1-2)" = 18 ] || fail "fresh role or password" +in_claim "$id-fresh" 'test -s /v/private/18/docker/PG_VERSION && test ! -e /v/private/pgdata' || fail "fresh data directory" +echo "PASS: database pod PostgreSQL 17 to 18 (live-17 refusal, move, passwords, rollback, rerun, fresh claim); Kubernetes itself unproven" diff --git a/scripts/test-postgres-17-to-18.sh b/scripts/test-postgres-17-to-18.sh new file mode 100755 index 00000000..5fcb26a0 --- /dev/null +++ b/scripts/test-postgres-17-to-18.sh @@ -0,0 +1,142 @@ +#!/bin/bash +# Proves the catalog kymessage's PostgreSQL 17 to 18 move on the Compose file deploy renders, +# as deploy lays it out (bind directories owned by the target user, who runs Postgres): a 17 +# install made with the previous catalog (PREV, a commit) moves on `up -d` over the running +# stack, rows, roles and passwords intact; a dump beside a live 17 refuses and writes nothing; +# 17 still starts on its untouched data; a rerun is a no-op; a bad dump never yields a +# cluster; a fresh install initialises; a 17 backup (the manifest's commands) restores on 18. +# NEW_APPS renders the new side from another apps directory (mutation checks). +# usage: scripts/test-postgres-17-to-18.sh (from the repository; needs Docker, Go, git) +set -Eeuo pipefail +repo=$(cd "$(dirname "$0")/.." && pwd) +PREV=${PREV:-950c3f8} # origin/master before PostgreSQL 18 +P18=postgres:18.7-alpine3.24@sha256:0115267ab5a509022df9319c77be365cef335adb71556c75f60f5360ee247e71 +work=$(mktemp -d "${TMPDIR:-/tmp}/kyq-pg18.XXXXXX") +id=kyqpg18$$ +cleanup() { + for d in app fresh restored; do + [ -f "$work/$d/compose.yaml" ] && docker compose -p "$id$d" --project-directory "$work/$d" -f "$work/$d/compose.yaml" down -t 30 >/dev/null 2>&1 || true + done + # Postgres wrote these as this user; nothing else to clean. + rm -rf "$work" +} +trap cleanup EXIT +fail() { echo "FAIL: $*" >&2; docker logs --tail 30 "${proj:-x}-postgres-1" >&2 2>&1 || true; exit 1; } + +# Render both sides with this checkout's renderer (internal/catalog/render_kymessage_test.go). +render() { (cd "$repo" && KYQ_RENDER_TO=$1 KYQ_RENDER_APPS=${2:-} go test ./internal/catalog -run '^TestWriteKyMessageCompose$' -count=1 >/dev/null) || fail "render $1"; } +mkdir -p "$work/prev-apps" +git -C "$repo" archive "$PREV" internal/catalog/apps | tar -x -C "$work/prev-apps" --strip-components=3 +render "$work/old" "$work/prev-apps" +render "$work/new" "${NEW_APPS:-}" +grep -q 'postgres:17' "$work/old/compose.yaml" || fail "$PREV's kymessage is not on PostgreSQL 17" + +# An app directory as deploy leaves it: private bind directories, the secret files, and the +# init script matrix-init writes (roles with passwords, databases with the C locale). +appdir() { + local d=$work/$1 + (umask 077 && mkdir -p "$d/pgdata" "$d/matrix/postgres" "$d/matrix/secrets" "$d/secrets" "$d/data/installer") + for s in matrix/secrets/postgres_password matrix/secrets/mas_admin_client_secret matrix/secrets/kybackup_db_password secrets/session_secret data/installer/directory_secret; do + printf 'pw-%s' "${s##*/}" > "$d/$s" + done + cat > "$d/matrix/postgres/init.sql" <<'SQL' +CREATE ROLE synapse LOGIN PASSWORD 'synapse-pw'; +CREATE DATABASE synapse OWNER synapse ENCODING 'UTF8' LOCALE 'C' TEMPLATE template0; +CREATE ROLE mas LOGIN PASSWORD 'mas-pw'; +CREATE DATABASE mas OWNER mas ENCODING 'UTF8' LOCALE 'C' TEMPLATE template0; +SQL +} +use() { # use : that side's compose.yaml and catalog files in the app dir + cp "$work/$2/compose.yaml" "$work/$1/compose.yaml" + if [ -d "$work/$2/pg-upgrade" ]; then (umask 077 && mkdir -p "$work/$1/pg-upgrade"); cp -p "$work/$2/pg-upgrade/"* "$work/$1/pg-upgrade/"; fi +} +compose() { local d=$1; shift; KYQ_UID=$(id -u) KYQ_GID=$(id -g) docker compose -p "$id$d" --project-directory "$work/$d" -f "$work/$d/compose.yaml" "$@"; } +healthy() { # wait for postgres healthy + for _ in $(seq 1 300); do + [ "$(docker inspect -f '{{.State.Health.Status}}' "$(compose "$1" ps -q postgres)" 2>/dev/null)" = healthy ] && return 0 + sleep 1 + done + return 1 +} +# Over matrix-db from another container: pg_hba's scram-sha-256 applies (loopback is trust). +client() { local d=$1 pw=$2 role=$3 db=$4; shift 4; docker run --rm --network "$id${d}_matrix-db" -e PGPASSWORD="$pw" "$P18" psql -h postgres -U "$role" -d "$db" -XAtc "$@"; } +in_app() { docker run --rm -u "$(id -u):$(id -g)" -v "$work/$1:/v" "$P18" sh -c "$2"; } + +# 1. A 17 install from the previous catalog, with Synapse-shaped rows. +proj=${id}app +appdir app; use app old +compose app up -d postgres >/dev/null 2>&1 || fail "17 did not start" +healthy app || fail "17 not healthy" +compose app exec -T postgres psql -U synapse -d synapse -X -q -v ON_ERROR_STOP=1 >/dev/null <<'SQL' +create table events(id bigserial primary key, room text, body jsonb); +insert into events(room, body) select 'r' || (g % 50), jsonb_build_object('g', g) from generate_series(1, 20000) g; +create table c(x text collate "C" primary key); +insert into c values ('a'), ('B'), ('é'); +SQL +# The manifest's backup, taken on 17, for step 8. +cmd=$(python3 -c 'import json,shlex,sys; print(shlex.join(json.load(open(sys.argv[1]))[sys.argv[2]]))' "$work/new/backup.json" command) +restore=$(python3 -c 'import json,shlex,sys; print(shlex.join(json.load(open(sys.argv[1]))[sys.argv[2]]))' "$work/new/backup.json" restore) +eval "compose app exec -T postgres $cmd" > "$work/backup-17.sql" && [ -s "$work/backup-17.sql" ] || fail "17 backup" + +# 2. A dump beside the live 17 refuses and writes nothing. +use app new +out=$(compose app run --rm --no-deps postgres-17-dump 2>&1) && fail "dump ran beside a live 17: $out" +grep -q postmaster.pid <<<"$out" || fail "no live-server message: $out" +[ ! -e "$work/app/pgdata/upgrade-from-17/dump.sql" ] || fail "dump written beside a live 17" + +# 3. The move: up -d over the running 17 stack, no down first. +compose app up -d postgres >/dev/null 2>&1 || fail "up with the new catalog" +healthy app || fail "18 not healthy after the move" +[ "$(client app synapse-pw synapse synapse 'show server_version_num' | cut -c1-2)" = 18 ] || fail "not 18" +[ "$(client app synapse-pw synapse synapse "select count(*) || ',' || sum((body->>'g')::int) from events")" = "20000,200010000" ] || fail "rows" +[ "$(client app synapse-pw synapse synapse "select string_agg(x, ',' order by x) from c")" = "B,a,é" ] || fail "C collation" +[ "$(client app mas-pw mas mas "select datcollate from pg_database where datname = 'mas'")" = C ] || fail "mas password or locale" +[ "$(client app pw-postgres_password postgres postgres 'show data_checksums')" = on ] || fail "checksums or superuser password" +client app wrong synapse synapse 'select 1' >/dev/null 2>&1 && fail "a wrong password logged in" +[ "$(stat -c %u "$work/app/pgdata/18/docker")" = "$(id -u)" ] || fail "18 data not the target user's" +[ -s "$work/app/pgdata/pgdata/PG_VERSION" ] || fail "17 data gone" + +# 4. Rollback: the previous catalog's 17 starts on its untouched data. +compose app down -t 30 >/dev/null 2>&1 +use app old +{ compose app up -d postgres >/dev/null 2>&1 && healthy app; } || fail "17 no longer starts on its data" +[ "$(compose app exec -T postgres psql -U synapse -d synapse -XAtc 'select count(*) from events')" = 20000 ] || fail "17 data changed" +compose app down -t 30 >/dev/null 2>&1 + +# 5. Rerun: nothing dumped or restored again. +use app new +{ compose app up -d postgres >/dev/null 2>&1 && healthy app; } || fail "18 did not restart" +grep -q 'already done' <<<"$(compose app logs postgres-17-dump 2>&1)" || fail "rerun dumped again" +! grep -q 'postgres-17-to-18: restored' <<<"$(compose app logs postgres 2>&1)" || fail "rerun restored again" +compose app down -t 30 >/dev/null 2>&1 + +# 6. A dump that fails to restore never yields a cluster, on any number of starts. +in_app app 'mv /v/pgdata/18/docker /v/pgdata/18/docker.saved && cp /v/pgdata/upgrade-from-17/dump.sql /v/dump.good && echo "THIS IS NOT SQL;" >> /v/pgdata/upgrade-from-17/dump.sql' +# Postgres restarts unless stopped: watch it fail for a while, then once more after a stop. +for _ in 1 2; do + compose app up -d postgres >/dev/null 2>&1 || true + for _ in $(seq 1 20); do + [ ! -e "$work/app/pgdata/18/docker" ] || fail "bad dump produced a cluster" + sleep 1 + done + grep -q 'THIS IS NOT SQL' <<<"$(compose app logs postgres 2>&1)" || fail "the bad dump was not tried" + compose app stop -t 30 >/dev/null 2>&1 +done +compose app down -t 30 >/dev/null 2>&1 +in_app app 'mv /v/dump.good /v/pgdata/upgrade-from-17/dump.sql && mv /v/pgdata/18/docker.saved /v/pgdata/18/docker' + +# 7. A fresh install: nothing to move, init.sql runs. +proj=${id}fresh +appdir fresh; use fresh new +{ compose fresh up -d postgres >/dev/null 2>&1 && healthy fresh; } || fail "fresh 18 did not start" +grep -q 'nothing to move' <<<"$(compose fresh logs postgres-17-dump 2>&1)" || fail "fresh install did not skip the dump" +[ -s "$work/fresh/pgdata/18/docker/PG_VERSION" ] && [ ! -e "$work/fresh/pgdata/pgdata" ] || fail "fresh data directory" +[ "$(client fresh synapse-pw synapse synapse 'select 1')" = 1 ] || fail "fresh init.sql" + +# 8. The 17 backup restores on 18 through the manifest's restore_command, as restore runs it. +proj=${id}restored +appdir restored; use restored new +{ compose restored up -d postgres >/dev/null 2>&1 && healthy restored; } || fail "restore target did not start" +eval "compose restored exec -T postgres $restore" < "$work/backup-17.sql" || fail "restore_command on 18" +[ "$(client restored synapse-pw synapse synapse 'select count(*) from events')" = 20000 ] || fail "restored rows" +echo "PASS: kymessage PostgreSQL 17 to 18 (up over running 17, live-17 refusal, passwords, rollback, rerun, bad dump, fresh, 17 backup on 18)" From 02e5c576a3f9d5dfe553d2c24c7840fc6469db2a Mon Sep 17 00:00:00 2001 From: Yoshiofthewire Date: Wed, 25 Nov 2026 18:30:07 -0500 Subject: [PATCH 2/2] fix(pg18): kit v4 rollback guard; exited-0 one-shots count as done Kit v4 (sha256 195ae86..., byte for byte in scripts/, kymessage's pg-upgrade/ and internal/kube/): after a rollback that ran 17, a return to 18 refuses instead of silently starting the older 18; the marker sits at 18/moved-from-17.checkpoint, so removing upgrade-from-17/ is safe. - dockerhost: a Once service that exited non-zero fails health, up and start at once with its last logs; one that exited 0 is done. - kube: the database pod's dump init container keeps its last lines as its termination message, and health's reason quotes it. - e2e stackHealthy: expects the catalog's services plus its one-shots, accepts Exited (0) and fails with logs on any other exit (the kube-message-apply failure at 3b89e5a). - Both upgrade tests gain: write on 17 after a rollback, refused return, move again (row on 18, replaced 18 kept), keep 18, and the dump clean-up followed by a refused rollback. The Compose test's cleanup now passes KYQ_UID, so it no longer leaks networks. - docs/guided-setup.md: the way back to 18 and the safe clean-up. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 10 +-- CHANGELOG.md | 6 +- docs/guided-setup.md | 27 ++++++-- .../files/pg-upgrade/postgres-17-to-18.sh | 32 +++++++--- internal/catalog/postgres18_test.go | 6 +- internal/dockerhost/deploy.go | 2 +- internal/dockerhost/health.go | 37 +++++++++++ internal/dockerhost/health_test.go | 51 ++++++++++++++++ internal/dockerhost/lifecycle.go | 2 +- internal/kube/health.go | 30 ++++++++- internal/kube/postgres-17-to-18.sh | 32 +++++++--- internal/kube/replicas.go | 2 + internal/kube/replicas_test.go | 44 +++++++++++++ scripts/postgres-17-to-18.sh | 32 +++++++--- scripts/test-postgres-17-to-18-pod.sh | 47 +++++++++++++- scripts/test-postgres-17-to-18.sh | 61 +++++++++++++++++-- test/e2e/message_chat_test.go | 31 ++++++++-- 17 files changed, 401 insertions(+), 51 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index f23bd6a8..105de890 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -533,7 +533,7 @@ edge compatibility: `docs/redirect.md`. a deploy is backed up first where `kyquickstart backup` can (one snapshot when the version change takes one too) and otherwise refuses `ack_required` without `--acknowledge-no-backup`. The suite's PostgreSQL 17 to 18 kit is `scripts/postgres-17-to-18.sh`, kept byte for byte (kit - v2) in kymessage's `files/pg-upgrade/` and `internal/kube/` (`TestPostgresKitIsVendoredByteForByte`). + v4) in kymessage's `files/pg-upgrade/` and `internal/kube/` (`TestPostgresKitIsVendoredByteForByte`). Uninstall keeps data and secrets, and on Kubernetes ends only once the app's pods are gone; Docker deploys, backups and lifecycle steps refuse a Compose project `kyq-` whose containers another root's directory made (another plan, or this one before its root moved), @@ -737,9 +737,11 @@ calls and kind nodes must carry their own explicit bounds. - CI's `PostgreSQL 17 to 18 upgrade` job (in `release-image.yml`'s REQUIRED list): `scripts/test-postgres-17-to-18.sh` seeds a 17 install from the previous catalog's rendered kymessage Compose file and moves it with this one (`up -d` over the running 17, a refused dump - beside a live 17, passwords over the network, rollback, rerun, a bad dump, a fresh install, a 17 - backup restored with the manifest's command); `scripts/test-postgres-17-to-18-pod.sh` runs the - previous and current database pod specs in Docker as a kubelet would (not Kubernetes itself). + beside a live 17, passwords over the network, rollback, a refused return to 18 after 17 ran and + the documented move-again and keep-18 ways out, rerun, a bad dump, a fresh install, a 17 backup + restored with the manifest's command); `scripts/test-postgres-17-to-18-pod.sh` runs the previous + and current database pod specs in Docker as a kubelet would, with the same rollback cases (not + Kubernetes itself). - `make workflow-lint`: needs Docker (CI runs it in `vulncheck`); actionlint v1.7.12 on every workflow and offline, digest-pinned zizmor (medium and up) on `release-image.yml` and `dependency-release.yml`. diff --git a/CHANGELOG.md b/CHANGELOG.md index a5bd09b7..7b9d9121 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,8 +19,10 @@ state directory, target data and target-held credentials; do not reset them as a **Upgrade impact:** a KyMessages install still on 17 is backed up first when its target has a backup destination; without one, `apply`/`upgrade` needs `--acknowledge-no-backup`. Chat or KyIdentity sign-in is down while the restore runs; the app's disk needs about twice the 17 - data free. Removing the 17 data afterwards is a manual step (`docs/guided-setup.md`). - CloudNativePG clusters stay on 17. + data free. Removing the 17 data afterwards is a manual step (`docs/guided-setup.md`). After a + rollback that ran 17, deploying 18 again refuses until you choose to move 17 again or keep 18 + (same doc). A one-shot service that fails (the 17 dump) fails `apply`, `start` and health at + once, with its logs. CloudNativePG clusters stay on 17. - Follow KyPost, KyCalendar and KyYard `0.6.1.1` with verified release image digests. KyPost includes the receiving accelerator and file-lock/fsync fixes; KyCalendar and KyYard refresh their Alpine base. **Upgrade impact:** the selected apps restart on diff --git a/docs/guided-setup.md b/docs/guided-setup.md index feff9062..7949256a 100644 --- a/docs/guided-setup.md +++ b/docs/guided-setup.md @@ -817,10 +817,16 @@ reach it, and it can reach nothing. Read this before choosing it: postgres-17-dump`). A dump refuses too while `pgdata/postmaster.pid` exists, which only a 17 that crashed leaves: start the previous release's pod once and let it stop. KyIdentity cannot sign anyone in while the move runs, about as long as a restore of its data. To go back, apply - with the previous release: its 17 pod starts on the untouched `pgdata/`. Once satisfied, you - may delete `pgdata/` and `upgrade-from-17/` from the claim (for example from a debug pod - mounting it); nothing does it for you. No pre-upgrade backup is taken: there is none of this - database (above), and the 17 data stays as the way back. + with the previous release: its 17 pod starts on the untouched `pgdata/`. Applying this + release again after 17 has run refuses: 18 lacks what 17 wrote since, so the dump stops the + pod in its init container, and the apply's health wait ends with the dump's message. Your + choice, from a debug pod mounting the claim, with the database scaled to 0: to move 17 again, + rename `18/` (and `upgrade-from-17/`, if it is there) with a suffix such as `.replaced` + (nothing is deleted); to keep 18 as it was, delete `18/moved-from-17.checkpoint`. Then apply + again. Once the move is done you may delete `upgrade-from-17/` (the dump) from the claim, for + example from a debug pod mounting it; 18 keeps starting. Deleting `pgdata/` (17) is separate, + and ends the way back. Nothing does either for you. No pre-upgrade backup is taken: there is + none of this database (above), and the 17 data stays as the way back. **The installer's, highly available (`database_instances`).** Owner amendment, 2026-11-13. `database_instances: 3` (3 to 5) replaces that one pod with a @@ -2429,8 +2435,17 @@ integrations: release once and stop it cleanly. - **Going back.** Deploy the previous release (or restore the pre-upgrade snapshot): its 17 starts on the untouched `pgdata/pgdata`. - - **Clean-up, your choice.** Once satisfied, `rm -r pgdata/pgdata pgdata/upgrade-from-17` in the - app's directory, as the target user. Nothing removes them for you. + - **Back to 18 after that.** Once 17 has run, the next deploy of this release refuses: 18 + lacks what 17 wrote since, so `postgres-17-dump` exits with that message, which apply + shows, and PostgreSQL does not start. Your choice, as the target user in the app's + directory with the stack stopped: to move 17 again, rename `pgdata/18` (and + `pgdata/upgrade-from-17`, if it is there) with a suffix such as `.replaced` (nothing is + deleted); to keep 18 as it was, delete `pgdata/18/moved-from-17.checkpoint`. Then deploy + again. + - **Clean-up, your choice**, in the app's directory as the target user. `rm -r + pgdata/upgrade-from-17` (the dump) is safe once the move is done; 18 keeps starting, and a + later return from 17 is still refused as above. `rm -r pgdata/pgdata` (17, and any + `.replaced` copies) is separate, and ends the way back. Nothing removes them for you. ### KyMessages: provenance, measurements and residuals diff --git a/internal/catalog/apps/kymessage/files/pg-upgrade/postgres-17-to-18.sh b/internal/catalog/apps/kymessage/files/pg-upgrade/postgres-17-to-18.sh index 85b7729b..263b42f8 100644 --- a/internal/catalog/apps/kymessage/files/pg-upgrade/postgres-17-to-18.sh +++ b/internal/catalog/apps/kymessage/files/pg-upgrade/postgres-17-to-18.sh @@ -10,6 +10,9 @@ 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" @@ -17,8 +20,23 @@ sock=$(mktemp -d) 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 - echo "postgres-17-to-18: already done"; exit 0 + 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 @@ -26,12 +44,7 @@ dump) 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 - # 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. - if [ -e "$old/postmaster.pid" ]; then - 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 - 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 }') @@ -52,6 +65,11 @@ dump) 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" diff --git a/internal/catalog/postgres18_test.go b/internal/catalog/postgres18_test.go index 72b924a7..f2955318 100644 --- a/internal/catalog/postgres18_test.go +++ b/internal/catalog/postgres18_test.go @@ -11,9 +11,9 @@ import ( "testing/fstest" ) -// kitSHA256 is the suite's PostgreSQL 17 to 18 kit v2 (ky-postgres-18): every copy in this +// kitSHA256 is the suite's PostgreSQL 17 to 18 kit v4 (ky-postgres-18): every copy in this // repository is that file byte for byte. -const kitSHA256 = "2992644109716cd34297fbcb76eba8907f4a5e3031a12c05aade010e5ea2b571" +const kitSHA256 = "195ae8684e34dd515158a88b1f76b918cf6e3f3c854ce83fe4fb190a5178cf06" func TestPostgresKitIsVendoredByteForByte(t *testing.T) { vendored, err := os.ReadFile("../../scripts/postgres-17-to-18.sh") @@ -21,7 +21,7 @@ func TestPostgresKitIsVendoredByteForByte(t *testing.T) { t.Fatal(err) } if sum := sha256.Sum256(vendored); hex.EncodeToString(sum[:]) != kitSHA256 { - t.Fatalf("scripts/postgres-17-to-18.sh is not kit v2: sha256 %x", sum) + t.Fatalf("scripts/postgres-17-to-18.sh is not kit v4: sha256 %x", sum) } if fi, err := os.Stat("../../scripts/postgres-17-to-18.sh"); err != nil || fi.Mode().Perm() != 0o755 { t.Fatalf("scripts/postgres-17-to-18.sh mode: %v %v", fi.Mode(), err) diff --git a/internal/dockerhost/deploy.go b/internal/dockerhost/deploy.go index e8db8290..8e40fb69 100644 --- a/internal/dockerhost/deploy.go +++ b/internal/dockerhost/deploy.go @@ -141,7 +141,7 @@ func (d deployStep) Apply(ctx context.Context) error { up += " --force-recreate" } if _, err := d.a.Runner.Run(ctx, d.a.compose(up), nil); err != nil { - return fmt.Errorf("docker compose up: %w", err) + return d.a.upFailed(ctx, "up", err) } _, err := d.a.Runner.Run(ctx, "umask 077; printf %s "+remote.Quote(d.hash)+" > "+remote.Quote(d.a.dir()+"/.input-hash"), nil) return err diff --git a/internal/dockerhost/health.go b/internal/dockerhost/health.go index 7734659f..0c39258c 100644 --- a/internal/dockerhost/health.go +++ b/internal/dockerhost/health.go @@ -6,6 +6,7 @@ import ( "encoding/json" "errors" "fmt" + "slices" "time" ) @@ -15,6 +16,7 @@ type container struct { Service string `json:"Service"` State string `json:"State"` Health string `json:"Health"` + Exit int `json:"ExitCode"` } // parsePS reads `docker compose ps --format json`: one object per line (Compose 2.21+). @@ -49,6 +51,17 @@ func notRunning(cs []container, services []string) string { return "" } +// failedOnce names the first one-shot (catalog Once) that exited non-zero, or "". One that +// exited 0 is done: it never has to be running. +func failedOnce(cs []container, once []string) string { + for _, c := range cs { + if c.State == "exited" && c.Exit != 0 && slices.Contains(once, c.Service) { + return c.Service + } + } + return "" +} + // unhealthy names the first service not running or not yet healthy, or "". // A container without a healthcheck counts as healthy once running. func unhealthy(cs []container, services []string) string { @@ -76,9 +89,33 @@ func (h healthStep) state(ctx context.Context) (string, error) { if err != nil { return "", err } + if s := failedOnce(cs, h.a.Catalog.Once); s != "" { + return "", h.a.onceFailed(ctx, s) + } return unhealthy(cs, h.a.Catalog.Services), nil } +// onceFailed is the error for one-shot service s that exited non-zero, with its last logs: +// waiting will not change it, and its output says why (and what the operator can do). +func (a App) onceFailed(ctx context.Context, s string) error { + logs, err := Logs(ctx, a, s, 40) + if err != nil { + return fmt.Errorf("service %s failed; its logs: %w", s, err) + } + return fmt.Errorf("service %s failed:\n%s", s, bytes.TrimSpace(logs)) +} + +// upFailed is the error of docker compose cmd: with the output of a one-shot that failed, +// which stops up and says why. +func (a App) upFailed(ctx context.Context, cmd string, err error) error { + if cs, perr := a.ps(ctx); perr == nil { + if s := failedOnce(cs, a.Catalog.Once); s != "" { + return fmt.Errorf("docker compose %s: %w: %w", cmd, err, a.onceFailed(ctx, s)) + } + } + return fmt.Errorf("docker compose %s: %w", cmd, err) +} + func (h healthStep) Inspect(ctx context.Context) (bool, error) { why, err := h.state(ctx) return why == "", err diff --git a/internal/dockerhost/health_test.go b/internal/dockerhost/health_test.go index 25d7b9d2..a9a9f0fb 100644 --- a/internal/dockerhost/health_test.go +++ b/internal/dockerhost/health_test.go @@ -2,6 +2,8 @@ package dockerhost import ( "context" + "errors" + "fmt" "strings" "testing" "time" @@ -60,3 +62,52 @@ func TestHealthApplyTimesOut(t *testing.T) { t.Fatalf("err = %v", err) } } + +// A one-shot (catalog Once) that exited 0 is done; one that exited non-zero fails health at +// once, with its logs, and so does the up it stopped. Lines as Compose 5.7 prints them. +func TestOnceExitCode(t *testing.T) { + pollInterval = time.Millisecond + const db = `{"ExitCode":0,"Health":"healthy","Service":"postgres","State":"running","Status":"Up 9 seconds (healthy)"}` + "\n" + dump := func(code string) string { + return `{"ExitCode":` + code + `,"Health":"","Service":"postgres-17-dump","State":"exited","Status":"Exited (` + code + `) 10 seconds ago"}` + "\n" + } + run := func(ps string, upErr error) (*fakeRunner, App) { + f := &fakeRunner{reply: func(cmd string) ([]byte, error) { + switch { + case strings.Contains(cmd, " ps "): + return []byte(ps), nil + case strings.Contains(cmd, " logs "): + return []byte("postgres-17-dump-1 | postgres-17-to-18: PostgreSQL 17 has run on /v since it was moved to 18\n"), nil + case strings.Contains(cmd, " up "): + return nil, upErr + } + return nil, nil + }} + a := fakeApp(f) + a.Catalog.Services, a.Catalog.Once = []string{"postgres"}, []string{"postgres-17-dump"} + return f, a + } + + _, a := run(db+dump("0"), nil) + if err := Steps(a)[1].Apply(context.Background()); err != nil { + t.Fatalf("an exited-0 one-shot is not healthy: %v", err) + } + if st, err := State(context.Background(), a); err != nil || st != "running" { + t.Fatalf("state = %q, %v; want running", st, err) + } + + f, a := run(db+dump("1"), nil) + err := Steps(a)[1].Apply(context.Background()) + if err == nil || !strings.Contains(err.Error(), "service postgres-17-dump failed:") || !strings.Contains(err.Error(), "has run on /v since") { + t.Fatalf("health err = %v", err) + } + if n := strings.Count(fmt.Sprint(f.calls), " ps "); n != 1 { + t.Fatalf("health polled %d times on a failed one-shot, want 1", n) + } + + _, a = run(dump("1"), errors.New("exit status 1")) + err = (lifecycleStep{a: a, op: "start"}).Apply(context.Background()) + if err == nil || !strings.Contains(err.Error(), "docker compose up -d: exit status 1: service postgres-17-dump failed:") || !strings.Contains(err.Error(), "has run on /v since") { + t.Fatalf("start err = %v", err) + } +} diff --git a/internal/dockerhost/lifecycle.go b/internal/dockerhost/lifecycle.go index 2ba131ef..a0426777 100644 --- a/internal/dockerhost/lifecycle.go +++ b/internal/dockerhost/lifecycle.go @@ -62,7 +62,7 @@ func (s lifecycleStep) Inspect(ctx context.Context) (bool, error) { func (s lifecycleStep) Apply(ctx context.Context) error { cmd := map[string]string{"stop": "stop", "start": "up -d", "restart": "restart"}[s.op] if _, err := s.a.Runner.Run(ctx, s.a.compose(cmd), nil); err != nil { - return fmt.Errorf("docker compose %s: %w", cmd, err) + return s.a.upFailed(ctx, cmd, err) } if s.op == "stop" { return nil diff --git a/internal/kube/health.go b/internal/kube/health.go index 5c423b2f..969fc96f 100644 --- a/internal/kube/health.go +++ b/internal/kube/health.go @@ -6,11 +6,13 @@ import ( "fmt" "net/http" "slices" + "strings" "time" appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) var pollInterval = 2 * time.Second @@ -50,7 +52,11 @@ func (h healthStep) state(ctx context.Context) (string, bool, error) { case failed(d): return e.Name + " rollout failed: " + reasons(d), true, nil case replicas(d) != *e.Spec.Replicas || !ready(d): - return fmt.Sprintf("%s: %d of %d replicas ready", e.Name, d.Status.ReadyReplicas, *e.Spec.Replicas), false, nil + why := fmt.Sprintf("%s: %d of %d replicas ready", e.Name, d.Status.ReadyReplicas, *e.Spec.Replicas) + if f := h.a.Client.initFailure(ctx, d); f != "" { + why += "; " + f + } + return why, false, nil } } if h.a.clustered() { @@ -126,6 +132,28 @@ func transient(err error) bool { return code == http.StatusTooManyRequests || code >= http.StatusInternalServerError } +// initFailure says why a pod of d is held by an init container that exited non-zero (the +// PostgreSQL 17 dump refusing): its exit code and termination message, or "". The kubelet +// retries it, so the wait goes on and its timeout says why. Best effort: a read error is "". +func (c *Client) initFailure(ctx context.Context, d *appsv1.Deployment) string { + pods, err := c.cs.CoreV1().Pods(d.Namespace).List(ctx, metav1.ListOptions{LabelSelector: metav1.FormatLabelSelector(d.Spec.Selector)}) + if err != nil { + return "" + } + for _, p := range pods.Items { + for _, st := range p.Status.InitContainerStatuses { + t := st.State.Terminated + if t == nil { + t = st.LastTerminationState.Terminated + } + if t != nil && t.ExitCode != 0 && owned(&p) { + return fmt.Sprintf("init container %s exited %d: %s", st.Name, t.ExitCode, strings.TrimSpace(t.Message)) + } + } + } + return "" +} + func ready(d *appsv1.Deployment) bool { want := int32(1) if d.Spec.Replicas != nil { diff --git a/internal/kube/postgres-17-to-18.sh b/internal/kube/postgres-17-to-18.sh index 85b7729b..263b42f8 100644 --- a/internal/kube/postgres-17-to-18.sh +++ b/internal/kube/postgres-17-to-18.sh @@ -10,6 +10,9 @@ 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" @@ -17,8 +20,23 @@ sock=$(mktemp -d) 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 - echo "postgres-17-to-18: already done"; exit 0 + 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 @@ -26,12 +44,7 @@ dump) 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 - # 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. - if [ -e "$old/postmaster.pid" ]; then - 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 - 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 }') @@ -52,6 +65,11 @@ dump) 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" diff --git a/internal/kube/replicas.go b/internal/kube/replicas.go index 21073d74..cf6314d9 100644 --- a/internal/kube/replicas.go +++ b/internal/kube/replicas.go @@ -235,6 +235,8 @@ func database(o *objects, a App, meta func(string) metav1.ObjectMeta) { {Name: claim, MountPath: "/v", SubPath: privateDir}, {Name: "tmp", MountPath: "/tmp"}, }, + // A refusal's last lines become its status message, which health reports. + TerminationMessagePolicy: corev1.TerminationMessageFallbackToLogsOnError, }}, Containers: []corev1.Container{{ Name: databaseName, diff --git a/internal/kube/replicas_test.go b/internal/kube/replicas_test.go index 4be867e5..ed59ad33 100644 --- a/internal/kube/replicas_test.go +++ b/internal/kube/replicas_test.go @@ -653,3 +653,47 @@ func TestReplicasCatalogValidation(t *testing.T) { t.Fatalf("cluster image = %q", image) } } + +// A database pod held by its 17 dump exiting non-zero (a refusal) is not ready, and health +// says so with the dump's message; one whose dump exited 0 is ready. +func TestHealthReportsFailedDump(t *testing.T) { + ctx := context.Background() + a, cs, _ := replicatedApp(t, 3, "") + steps := Steps(a) + for _, s := range steps[:3] { + if err := s.Apply(ctx); err != nil { + t.Fatalf("%s: %v", s.ID(), err) + } + } + markReady(t, cs) + db, _ := cs.AppsV1().Deployments("kyq-kyidentity").Get(ctx, databaseName, metav1.GetOptions{}) + if c := db.Spec.Template.Spec.InitContainers[1]; c.Name != "postgres-17-dump" || c.TerminationMessagePolicy != corev1.TerminationMessageFallbackToLogsOnError { + t.Fatalf("dump init container = %s %s", c.Name, c.TerminationMessagePolicy) + } + pod := &corev1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "database-x", Namespace: "kyq-kyidentity", Labels: db.Spec.Template.Labels}} + pod.Status.InitContainerStatuses = []corev1.ContainerStatus{ + {Name: "private-volumes", State: corev1.ContainerState{Terminated: &corev1.ContainerStateTerminated{ExitCode: 0}}}, + {Name: "postgres-17-dump", State: corev1.ContainerState{Waiting: &corev1.ContainerStateWaiting{Reason: "CrashLoopBackOff"}}, + LastTerminationState: corev1.ContainerState{Terminated: &corev1.ContainerStateTerminated{ExitCode: 1, Message: "postgres-17-to-18: PostgreSQL 17 has run on /v/pgdata since it was moved to 18\n"}}}, + } + pod, err := cs.CoreV1().Pods("kyq-kyidentity").Create(ctx, pod, metav1.CreateOptions{}) // named by the fixture + if err != nil { + t.Fatal(err) + } + if err := steps[3].Verify(ctx); err != nil { + t.Fatalf("a ready database with an old failed pod: %v", err) + } + db.Status = appsv1.DeploymentStatus{ObservedGeneration: db.Generation, Replicas: 1} + cs.AppsV1().Deployments("kyq-kyidentity").UpdateStatus(ctx, db, metav1.UpdateOptions{}) + err = steps[3].Verify(ctx) + if err == nil || !strings.Contains(err.Error(), "database: 0 of 1 replicas ready; init container postgres-17-dump exited 1: postgres-17-to-18: PostgreSQL 17 has run on") { + t.Fatalf("health = %v", err) + } + pod.Status.InitContainerStatuses[1] = corev1.ContainerStatus{Name: "postgres-17-dump", State: corev1.ContainerState{Terminated: &corev1.ContainerStateTerminated{ExitCode: 0}}} + if _, err := cs.CoreV1().Pods("kyq-kyidentity").UpdateStatus(ctx, pod, metav1.UpdateOptions{}); err != nil { + t.Fatal(err) + } + if err := steps[3].Verify(ctx); err == nil || strings.Contains(err.Error(), "init container") { + t.Fatalf("health with the dump done = %v", err) + } +} diff --git a/scripts/postgres-17-to-18.sh b/scripts/postgres-17-to-18.sh index 85b7729b..263b42f8 100755 --- a/scripts/postgres-17-to-18.sh +++ b/scripts/postgres-17-to-18.sh @@ -10,6 +10,9 @@ 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" @@ -17,8 +20,23 @@ sock=$(mktemp -d) 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 - echo "postgres-17-to-18: already done"; exit 0 + 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 @@ -26,12 +44,7 @@ dump) 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 - # 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. - if [ -e "$old/postmaster.pid" ]; then - 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 - 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 }') @@ -52,6 +65,11 @@ dump) 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" diff --git a/scripts/test-postgres-17-to-18-pod.sh b/scripts/test-postgres-17-to-18-pod.sh index 0f483210..d8623ff1 100755 --- a/scripts/test-postgres-17-to-18-pod.sh +++ b/scripts/test-postgres-17-to-18-pod.sh @@ -6,7 +6,9 @@ # Secret as a read-only volume, fsGroup as the claim's group, read-only root, uid 70). # Asserts rows, the app role's password over the network and a wrong one refused, the C # locale and checksums; a dump beside a live 17 refuses and writes nothing; 17 restarts on -# its untouched data; a rerun is a no-op; a fresh claim initialises. Not Kubernetes itself. +# its untouched data; back to 18 after 17 ran refuses, and the documented move-again and +# keep-18 ways out work, also after the dump alone is cleaned up; a rerun is a no-op; a fresh +# claim initialises. Not Kubernetes itself. # NEW_SRC renders the new side from another source tree (mutation checks). # usage: scripts/test-postgres-17-to-18-pod.sh (from the repository; needs Docker, Go, git) set -Eeuo pipefail @@ -108,6 +110,19 @@ in_claim "$id-claim" '[ "$(stat -c %u /v/private/18/docker)" = 70 ] && [ -s /v/p stop { pod "$work/old.json" "$id-claim" && ready; } || fail "17 no longer starts on its data" [ "$(client app-pw 'select count(*) from users')" = 20000 ] || fail "17 data changed" +client app-pw "insert into users(name) values ('written on 17 after the move')" >/dev/null || fail "write on 17" +stop + +# 4b. Back to 18 after 17 ran: the dump init container refuses, so 18 never starts. +out=$(pod "$work/new.json" "$id-claim" init 2>&1) && fail "18's dump accepted a 17 that ran since the move: $out" +grep -q 'has run on .* since it was moved to 18' <<<"$out" || fail "no rollback message: $out" +echo "refused as documented: $(grep -o 'postgres-17-to-18: PostgreSQL 17 has run.*' <<<"$out" | head -1)" + +# 4c. The documented move again: rename 18 and the dump; 18 has the row, the old 18 is kept. +in_claim "$id-claim" 'mv /v/private/18 /v/private/18.replaced && mv /v/private/upgrade-from-17 /v/private/upgrade-from-17.replaced' +{ pod "$work/new.json" "$id-claim" && ready; } || fail "18 not ready after the move again" +[ "$(client app-pw 'select count(*) from users')" = 20001 ] || fail "the move again lost the row written on 17" +in_claim "$id-claim" 'test -s /v/private/18.replaced/docker/PG_VERSION' || fail "the replaced 18 cluster is gone" stop # 5. Rerun: nothing dumped or restored again. @@ -117,6 +132,34 @@ ready || fail "18 not ready after a restart" ! grep -q 'postgres-17-to-18: restored' <<<"$(docker logs "$id-db" 2>&1)" || fail "rerun restored again" stop +# 5b. Keep 18 after 17 ran: delete the file the refusal names; accepted, and it sticks. +{ pod "$work/old.json" "$id-claim" && ready; } || fail "17 did not start for the keep-18 check" +stop +out=$(pod "$work/new.json" "$id-claim" init 2>&1) && fail "18's dump accepted a 17 that ran (keep-18 check): $out" +keep=$(sed -n 's|.*To keep 18 as it is: delete /v/\([^ ]*\), then start again.*|\1|p' <<<"$out" | tail -1) +[ -n "$keep" ] || fail "the refusal names no file to delete to keep 18: $out" +in_claim "$id-claim" "rm /v/private/$keep" +for _ in 1 2; do + out=$(pod "$work/new.json" "$id-claim" 2>&1) || fail "keep 18 was not accepted: $out" + grep -q 'already done' <<<"$out" || fail "keep 18 did not stick: $out" + ready || fail "18 not ready after keep 18" + [ "$(client app-pw 'select count(*) from users')" = 20001 ] || fail "rows after keep 18" + stop +done + +# 5c. The documented clean-up of the dump alone (17 kept): later starts go on, and a rollback +# that writes on 17 is still refused on the way back to 18. +in_claim "$id-claim" 'mv /v/private/upgrade-from-17 /v/upgrade-from-17.saved' +out=$(pod "$work/new.json" "$id-claim" 2>&1) || fail "18 after the dump was removed: $out" +grep -q 'already done' <<<"$out" || fail "start after the clean-up: $out" +ready || fail "18 not ready after the clean-up" +stop +{ pod "$work/old.json" "$id-claim" && ready; } || fail "17 did not start after the clean-up" +client app-pw "insert into users(name) values ('written on 17 after the clean-up')" >/dev/null || fail "write on 17" +stop +out=$(pod "$work/new.json" "$id-claim" init 2>&1) && fail "18's dump accepted a 17 that ran since the clean-up: $out" +grep -q 'has run on .* since it was moved to 18' <<<"$out" || fail "no rollback message after the clean-up: $out" + # 6. A fresh claim: nothing to move, the app's role and database from the init script. claim "$id-fresh" out=$(pod "$work/new.json" "$id-fresh" 2>&1) || fail "fresh pod: $out" @@ -124,4 +167,4 @@ grep -q 'nothing to move' <<<"$out" || fail "fresh claim did not skip the dump" ready || fail "fresh 18 not ready" [ "$(client app-pw 'show server_version_num' | cut -c1-2)" = 18 ] || fail "fresh role or password" in_claim "$id-fresh" 'test -s /v/private/18/docker/PG_VERSION && test ! -e /v/private/pgdata' || fail "fresh data directory" -echo "PASS: database pod PostgreSQL 17 to 18 (live-17 refusal, move, passwords, rollback, rerun, fresh claim); Kubernetes itself unproven" +echo "PASS: database pod PostgreSQL 17 to 18 (live-17 refusal, move, passwords, rollback, refused return after 17 ran, move again, keep 18, dump clean-up, rerun, fresh claim); Kubernetes itself unproven" diff --git a/scripts/test-postgres-17-to-18.sh b/scripts/test-postgres-17-to-18.sh index 5fcb26a0..06f181ff 100755 --- a/scripts/test-postgres-17-to-18.sh +++ b/scripts/test-postgres-17-to-18.sh @@ -3,7 +3,9 @@ # as deploy lays it out (bind directories owned by the target user, who runs Postgres): a 17 # install made with the previous catalog (PREV, a commit) moves on `up -d` over the running # stack, rows, roles and passwords intact; a dump beside a live 17 refuses and writes nothing; -# 17 still starts on its untouched data; a rerun is a no-op; a bad dump never yields a +# 17 still starts on its untouched data; back to 18 after 17 ran refuses, and the documented +# move-again and keep-18 ways out work, also after the dump alone is cleaned up; a rerun is a +# no-op; a bad dump never yields a # cluster; a fresh install initialises; a 17 backup (the manifest's commands) restores on 18. # NEW_APPS renders the new side from another apps directory (mutation checks). # usage: scripts/test-postgres-17-to-18.sh (from the repository; needs Docker, Go, git) @@ -15,7 +17,7 @@ work=$(mktemp -d "${TMPDIR:-/tmp}/kyq-pg18.XXXXXX") id=kyqpg18$$ cleanup() { for d in app fresh restored; do - [ -f "$work/$d/compose.yaml" ] && docker compose -p "$id$d" --project-directory "$work/$d" -f "$work/$d/compose.yaml" down -t 30 >/dev/null 2>&1 || true + [ -f "$work/$d/compose.yaml" ] && compose "$d" down -t 30 >/dev/null 2>&1 || true done # Postgres wrote these as this user; nothing else to clean. rm -rf "$work" @@ -101,15 +103,66 @@ compose app down -t 30 >/dev/null 2>&1 use app old { compose app up -d postgres >/dev/null 2>&1 && healthy app; } || fail "17 no longer starts on its data" [ "$(compose app exec -T postgres psql -U synapse -d synapse -XAtc 'select count(*) from events')" = 20000 ] || fail "17 data changed" +compose app exec -T postgres psql -U synapse -d synapse -XAtqc "insert into events(room) values ('written on 17 after the move')" compose app down -t 30 >/dev/null 2>&1 -# 5. Rerun: nothing dumped or restored again. +# 4b. Back to 18 after 17 ran: the dump refuses and 18 does not start without that row. use app new +compose app up -d postgres >/dev/null 2>&1 && fail "18 started after 17 ran since the move" +out=$(compose app logs postgres-17-dump 2>&1) +grep -q 'has run on .* since it was moved to 18' <<<"$out" || fail "no rollback message: $out" +[ "$(docker inspect -f '{{.State.Running}}' "$(compose app ps -aq postgres)")" = false ] || fail "18 is running" +echo "refused as documented: $(grep -o 'postgres-17-to-18: PostgreSQL 17 has run.*' <<<"$out" | head -1)" +compose app down -t 30 >/dev/null 2>&1 + +# 4c. The documented move again: rename 18 and the dump, deploy; 18 has the row, the old 18 is kept. +in_app app 'mv /v/pgdata/18 /v/pgdata/18.replaced && mv /v/pgdata/upgrade-from-17 /v/pgdata/upgrade-from-17.replaced' +{ compose app up -d postgres >/dev/null 2>&1 && healthy app; } || fail "18 did not start after the move again" +[ "$(client app synapse-pw synapse synapse 'select count(*) from events')" = 20001 ] || fail "the move again lost the row written on 17" +[ -s "$work/app/pgdata/18.replaced/docker/PG_VERSION" ] || fail "the replaced 18 cluster is gone" +compose app down -t 30 >/dev/null 2>&1 + +# 5. Rerun: nothing dumped or restored again. { compose app up -d postgres >/dev/null 2>&1 && healthy app; } || fail "18 did not restart" grep -q 'already done' <<<"$(compose app logs postgres-17-dump 2>&1)" || fail "rerun dumped again" ! grep -q 'postgres-17-to-18: restored' <<<"$(compose app logs postgres 2>&1)" || fail "rerun restored again" compose app down -t 30 >/dev/null 2>&1 +# 5b. Keep 18 after 17 ran: delete source-checkpoint as documented; accepted, and it sticks. +use app old +{ compose app up -d postgres >/dev/null 2>&1 && healthy app; } || fail "17 did not start for the keep-18 check" +compose app down -t 30 >/dev/null 2>&1 +use app new +compose app up -d postgres >/dev/null 2>&1 && fail "18 started after 17 ran (keep-18 check)" +# The file the refusal says to delete, as the dump sees it (/v is pgdata/). +keep=$(compose app logs postgres-17-dump 2>&1 | sed -n 's|.*To keep 18 as it is: delete /v/\([^ ]*\), then start again.*|\1|p' | tail -1) +[ -n "$keep" ] || fail "the refusal names no file to delete to keep 18" +compose app down -t 30 >/dev/null 2>&1 +in_app app "rm /v/pgdata/$keep" +for _ in 1 2; do + { compose app up -d postgres >/dev/null 2>&1 && healthy app; } || fail "keep 18 was not accepted" + grep -q 'already done' <<<"$(compose app logs postgres-17-dump 2>&1)" || fail "keep 18 did not stick" + compose app down -t 30 >/dev/null 2>&1 +done +[ "$(compose app run --rm --no-deps -T postgres-17-dump 2>&1 | tail -1)" = "postgres-17-to-18: already done" ] || fail "keep 18 dump" + +# 5c. The documented clean-up of the dump alone (17 kept): later starts go on, and a rollback +# that writes on 17 is still refused on the way back to 18. +in_app app 'mv /v/pgdata/upgrade-from-17 /v/upgrade-from-17.saved' +{ compose app up -d postgres >/dev/null 2>&1 && healthy app; } || fail "18 did not start after the dump was removed" +grep -q 'already done' <<<"$(compose app logs postgres-17-dump 2>&1)" || fail "start after the clean-up" +compose app down -t 30 >/dev/null 2>&1 +use app old +{ compose app up -d postgres >/dev/null 2>&1 && healthy app; } || fail "17 did not start after the clean-up" +compose app exec -T postgres psql -U synapse -d synapse -XAtqc "insert into events(room) values ('written on 17 after the clean-up')" +compose app down -t 30 >/dev/null 2>&1 +use app new +compose app up -d postgres >/dev/null 2>&1 && fail "18 started after 17 ran since the clean-up" +grep -q 'has run on .* since it was moved to 18' <<<"$(compose app logs postgres-17-dump 2>&1)" || fail "no rollback message after the clean-up" +compose app down -t 30 >/dev/null 2>&1 +# Keep 18 again, and put the dump back for step 6. +in_app app "rm /v/pgdata/$keep && mv /v/upgrade-from-17.saved /v/pgdata/upgrade-from-17" + # 6. A dump that fails to restore never yields a cluster, on any number of starts. in_app app 'mv /v/pgdata/18/docker /v/pgdata/18/docker.saved && cp /v/pgdata/upgrade-from-17/dump.sql /v/dump.good && echo "THIS IS NOT SQL;" >> /v/pgdata/upgrade-from-17/dump.sql' # Postgres restarts unless stopped: watch it fail for a while, then once more after a stop. @@ -139,4 +192,4 @@ appdir restored; use restored new { compose restored up -d postgres >/dev/null 2>&1 && healthy restored; } || fail "restore target did not start" eval "compose restored exec -T postgres $restore" < "$work/backup-17.sql" || fail "restore_command on 18" [ "$(client restored synapse-pw synapse synapse 'select count(*) from events')" = 20000 ] || fail "restored rows" -echo "PASS: kymessage PostgreSQL 17 to 18 (up over running 17, live-17 refusal, passwords, rollback, rerun, bad dump, fresh, 17 backup on 18)" +echo "PASS: kymessage PostgreSQL 17 to 18 (up over running 17, live-17 refusal, passwords, rollback, refused return after 17 ran, move again, keep 18, dump clean-up, rerun, bad dump, fresh, 17 backup on 18)" diff --git a/test/e2e/message_chat_test.go b/test/e2e/message_chat_test.go index acb312ce..b29b29e4 100644 --- a/test/e2e/message_chat_test.go +++ b/test/e2e/message_chat_test.go @@ -19,6 +19,7 @@ import ( "testing" "time" + "github.com/Busnes-app/kyquickstart/internal/catalog" "github.com/Busnes-app/kyquickstart/internal/kube" "maunium.net/go/mautrix" "maunium.net/go/mautrix/event" @@ -645,15 +646,33 @@ func (c *messageChat) connector(name string) string { return "" } -// stackHealthy waits until every KyMessages container is running and, with a healthcheck, -// healthy. +// stackHealthy waits until every KyMessages service is running and, with a healthcheck, +// healthy, and every one-shot (the catalog's Once) has exited 0. A one-shot that exited +// non-zero fails at once, with its logs. func stackHealthy(t *testing.T) { t.Helper() + cat, err := catalog.Load(catalog.Embedded()) + if err != nil { + t.Fatal(err) + } + app := cat["kymessage"] for deadline := time.Now().Add(3 * time.Minute); ; time.Sleep(2 * time.Second) { - out := docker(t, "ps", "-a", "--filter", "label=com.docker.compose.project=kyq-kymessage", "--format", "{{.Names}} {{.State}} {{.Status}}") - ready := strings.Count(out, "\n")+1 == 6 - for _, line := range strings.Split(out, "\n") { - if f := strings.Fields(line); len(f) < 2 || f[1] != "running" || strings.Contains(line, "(health: starting)") || strings.Contains(line, "(unhealthy)") { + out := docker(t, "ps", "-a", "--filter", "label=com.docker.compose.project=kyq-kymessage", "--format", `{{.Label "com.docker.compose.service"}} {{.Names}} {{.State}} {{.Status}}`) + lines := strings.Split(out, "\n") + ready := len(lines) == len(app.Services)+len(app.Once) + for _, line := range lines { + f := strings.Fields(line) + switch { + case len(f) < 3: + ready = false + case slices.Contains(app.Once, f[0]): + if f[2] != "exited" { + ready = false + } else if !strings.Contains(line, "Exited (0)") { + logs, _ := exec.Command("docker", "logs", "--tail", "40", f[1]).CombinedOutput() + t.Fatalf("KyMessages one-shot %s failed:\n%s\n%s", f[0], out, logs) + } + case f[2] != "running" || strings.Contains(line, "(health: starting)") || strings.Contains(line, "(unhealthy)"): ready = false } }