diff --git a/.gitignore b/.gitignore index 6c81a04..4b82bec 100644 --- a/.gitignore +++ b/.gitignore @@ -500,3 +500,7 @@ App_Data/ /backups/ *.dump *.sql.gz + +# An update that stopped halfway (scripts/update.sh) +/.update-in-progress +/.update-in-progress.tmp diff --git a/CHANGELOG.md b/CHANGELOG.md index fc544e9..f761fd1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,16 @@ version may change things that need attention when updating, and these notes say ### For people running an archive and for maintainers +- **PostgreSQL 19.** The database image moves from 18 to 19. A new PostgreSQL version cannot open the data of the old + one, so `scripts/update.sh` now moves the archive with the backup: it stops the app, backs up, starts the new database + beside the old data and restores into it. The old database stays in the `db-data` volume, renamed and otherwise untouched, so going back stays + possible; once the archive has run well, remove it with the command the update prints (see "A new PostgreSQL version" + in `docs/operations.md`). The update takes longer than usual and checks first that the volume has room for a second copy of + the database. An update that is interrupted midway leaves `.update-in-progress` and refuses to go on until + `sh scripts/update.sh --recover` has put the old database back. `scripts/restore.sh` has a new `--database-only`. Future + major versions work the same way. `scripts/backup.sh` no longer recreates the database container, and + `scripts/test-update.sh` tests the move. + - **The 1.0 checklist** is written down in `docs/release-1.0.md`: each condition, how it is checked, and where it stands. Some are not met yet and it says so (a group that has run it for a season, a second person who can approve a release). `SUPPORT.md` says which versions get security fixes and what is not supported: the newest minor only, as diff --git a/compose.yaml b/compose.yaml index a964602..24c6b7c 100644 --- a/compose.yaml +++ b/compose.yaml @@ -2,7 +2,7 @@ services: db: # Pinned by digest; Dependabot updates it. - image: postgres:18-alpine@sha256:123b17998ccaf47e53b502e8c6a1e79afd8f579c6f3eec83c563da026f957395 + image: postgres:19-alpine@sha256:8b0ff4cdf221f0c53d7fcda681d3b461be725c492cd881c5ec9c0ad25023f188 environment: POSTGRES_DB: commonage POSTGRES_USER: commonage diff --git a/docs/deployment.md b/docs/deployment.md index dc40922..6e7671c 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -136,6 +136,10 @@ upgrades the database when it starts. If the new version does not come up, the s and restores the backup, so the archive is as it was. Anything added during those minutes would be lost, so update when nobody is working on the archive. The archive is down for a short time either way. +If the new release uses a newer PostgreSQL, the script moves the database with the backup and keeps the old one in the volume +until you remove it; the release notes say so, and [Backup and restore](operations.md#a-new-postgresql-version) has the +details. + The script is part of Commonage from version 0.3. To get from 0.2 to it once, by hand: ```sh diff --git a/docs/development.md b/docs/development.md index 460ac5b..13149dc 100644 --- a/docs/development.md +++ b/docs/development.md @@ -261,6 +261,25 @@ unchanged tag, merge by themselves once every required check has passed. Each ch rebase the next waiting update (`.github/workflows/dependabot-auto-merge.yml`), since `main` only accepts pull requests that are up to date. An update whose checks fail stays open for a maintainer. +**A new major version of `postgres` is not ignored.** `scripts/update.sh` compares the major version of the running +database with the one the new release's `compose.yaml` starts (read from the `image: postgres:` line), and when they +differ it stops the app, backs up, renames the old data in the `db-data` volume (`/docker` to `/kept`: the new +image refuses to start while a folder `/var/lib/postgresql/*/docker` of another major exists, which is why a plain bump +breaks existing archives), starts an empty new database and restores the backup's database into it +(`restore.sh --database-only`); a failed start renames the old data back. A file `.update-in-progress` marks the time in +between, and `update.sh --recover` clears it. `scripts/backup.sh` uses `--no-recreate` so that the backup still reads the +old database. So the Dependabot change to `compose.yaml` is the only change to the scripts and compose files a bump needs, as long as the image keeps this +layout (PostgreSQL 18 and later) and the volume stays mounted at `/var/lib/postgresql`. Besides the pull request itself, +change `postgres:-alpine` in `tests/Commonage.Tests/CommonageAppFactory.cs` and +`tests/Commonage.BrowserTests/BrowserFixture.cs`, which Dependabot does not see. CI job `update` starts the previous +release (PostgreSQL 18 now) and updates to the pull request. It covers: the move to the new major with the data still there; +a failed update going back to the original database (the same cluster comes back); an update killed after the old data +was set aside, the refusal that follows and `--recover`; the old data still being in the volume, and its removal with the +printed command. The `update-from-*` jobs cover the move from each earlier minor. Not covered: a disk too full for the +second copy (the check is only read by hand), a lost connection that is not a kill of the script, and the first major bump +after 19 (20 is untested until it comes; the script reads all numbers from the compose file). Release notes for the release that carries +the bump should say it (see the entry for 19 in `CHANGELOG.md`). + Major updates are never merged automatically. Read the release notes, check in the CI log that all tests ran (a test runner that finds no tests still succeeds), then merge. diff --git a/docs/operations.md b/docs/operations.md index 46dcbe9..558d0b0 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -340,6 +340,56 @@ up, deletes all containers and volumes, restores and compares, and checks that n without `COMMONAGE_LOGIN_KEY`. It runs in CI on every pull request, as its own Compose project on ports 18080 and 15432, so it can also run next to your own archive. +### A new PostgreSQL version + +Now and then a release moves to a new major version of PostgreSQL (18 to 19, for example), which cannot open the data of +the old one. `scripts/update.sh` notices this and handles it, without you doing anything extra. It stops the app, makes +the backup, checks its checksums again, sets the old data aside, starts an empty new database and restores the backup's +database into it; the uploaded files stay as they are. The old database is not deleted: the script only renames its folder +in the `db-data` volume (`/var/lib/postgresql/18/docker` becomes `/var/lib/postgresql/18/kept`), because the new PostgreSQL +image refuses to start next to it. If the new version does not come up, the script renames it back and starts the +previous release on it, so the archive is as it was. The archive is down while this happens, longer than for an ordinary +update, in proportion to the size of the database. + +**If the update is interrupted** (the connection drops, the power goes) after the old database was set aside, the file +`.update-in-progress` stays in the folder, and `scripts/update.sh` refuses to do anything else until it is cleared up. It prints +where the old database is and what to do; the short way is: + +```sh +sh scripts/update.sh --recover +``` + +It puts the archive back on the release it was on, with its old database. Nothing is lost: the database is in the volume +and the backup is in the backup folder. The recovery can be run again if it is interrupted too. + +**Disk space.** Until you remove the old database, the volume holds the database twice, and the backup is a third copy. +The update checks the free space for the backup, and also the free space of the database volume for the second copy (about +one and a half times the size of the database), and stops before changing anything when it is short. + +**The old database holds the archive's data, personal data of contributors included.** Free the space, and the data, +when the archive has run well for a while (a week, say). The update prints this command, with the right version number: + +```sh +docker compose run --rm --no-deps --entrypoint rm db -rf /var/lib/postgresql/18 +``` + +This is final. Until then, going back to the previous release later is possible. Stop the archive +(`docker compose stop web db`), check out the previous release (and set `COMMONAGE_VERSION` in `.env` as before), then, +with your two version numbers: + +```sh +docker compose run --rm --no-deps --entrypoint sh db -c 'ls /var/lib/postgresql/18; rm -rf /var/lib/postgresql/19/docker' +``` + +If the listing shows `kept` and no `docker`, run `mv /var/lib/postgresql/18/kept /var/lib/postgresql/18/docker` the same way. +If it shows `docker` as well, a database of the old version was started in between: do not move anything, and restore the +newest backup with `scripts/restore.sh` instead, which also brings the data back, although only as of that backup. Then +`docker compose up -d`. Whatever was added to the archive since the update is not in the old database: restore the newest +backup afterwards (`scripts/restore.sh`) to have it. + +An archive that is moved by hand (`git checkout` and `docker compose up`, without the script) does not start: the new +database refuses a volume that holds the old one. Use `scripts/update.sh`. + ## Demo archive `COMMONAGE_DEMO=en` or `COMMONAGE_DEMO=de` in `.env` fills a new, empty archive with made-up content when the app diff --git a/docs/security.md b/docs/security.md index 1917a67..59f64b4 100644 --- a/docs/security.md +++ b/docs/security.md @@ -52,6 +52,7 @@ vulnerability, see [SECURITY.md](../SECURITY.md). | Secret | Where it is, and how it is protected | |---|---| | Passwords | Only as hashes in the database (ASP.NET Core Identity, PBKDF2 with a salt per password). | +| Old database after a PostgreSQL major upgrade | `scripts/update.sh` keeps the old database in the database volume as `/var/lib/postgresql//kept`, so that going back is possible. It holds everything in the archive, contributors' personal data included, until a curator removes it with the command the update prints (also in `docs/operations.md`). It is in the volume only, owned by the database, not reachable from the web; the backup made for the move is written owner-only (`umask 077`) like every backup, and holds the same data. `.update-in-progress` holds only paths and version numbers. Accepted: until removed, deleted items and anything erased since stay in that copy. `scripts/test-update.sh`. | | Login keys | The keys that sign login cookies, setup links and form tokens are in the database (`DataProtectionKeys`), so that logins survive a restore. Each is encrypted with AES-256-GCM with `COMMONAGE_LOGIN_KEY` (`Security/LoginKeys.cs`), which is in `.env` only, not in the database or the backups. Tested in `LoginKeyTests` and in the backup-and-restore test, which also checks that no key in the database can be read. | | Authenticator secrets and recovery codes | In the database, encrypted with the login keys (`ProtectedUserStore`), so they need `COMMONAGE_LOGIN_KEY` as well. Recovery codes are shown once and kept nowhere else. | | Setup links | Not stored. They are signed with the login keys, work once and for seven days, and a new one makes older ones invalid. | diff --git a/scripts/backup.sh b/scripts/backup.sh index 4c9dd05..da87e65 100755 --- a/scripts/backup.sh +++ b/scripts/backup.sh @@ -23,7 +23,9 @@ sha256() { if command -v sha256sum >/dev/null 2>&1; then sha256sum "$@"; else shasum -a 256 "$@"; fi } -docker compose up -d --wait db >/dev/null +# Never recreates the database container: during an update that moves to a new PostgreSQL major, the new compose files +# would start an empty database instead of the one that has to be backed up. +docker compose up -d --wait --no-recreate db >/dev/null # The database first, then the files: an upload in between leaves an extra file, which does no harm. echo "Backing up the database..." diff --git a/scripts/restore.sh b/scripts/restore.sh index 204d086..5c902e3 100755 --- a/scripts/restore.sh +++ b/scripts/restore.sh @@ -1,7 +1,10 @@ #!/bin/sh # Restores a backup made with scripts/backup.sh. Everything currently in the archive is replaced. # -# scripts/restore.sh [--yes] +# scripts/restore.sh [--yes] [--database-only] +# +# --database-only leaves the uploaded files as they are. scripts/update.sh uses it when it moves the archive to a new +# PostgreSQL version, which changes nothing in the files. # # Restore into the same or a newer version of Commonage; the app upgrades the database when it starts. # See docs/operations.md. @@ -10,12 +13,18 @@ set -eu export MSYS_NO_PATHCONV=1 confirmed=no -if [ "${1:-}" = "--yes" ]; then - confirmed=yes +database_only=no +while [ $# -gt 0 ]; do + case "$1" in + --yes) confirmed=yes ;; + --database-only) database_only=yes ;; + -*) echo "Usage: scripts/restore.sh [--yes] [--database-only] " >&2; exit 2 ;; + *) break ;; + esac shift -fi +done if [ $# -ne 1 ]; then - echo "Usage: scripts/restore.sh [--yes] " >&2 + echo "Usage: scripts/restore.sh [--yes] [--database-only] " >&2 exit 2 fi @@ -34,7 +43,9 @@ else fi if [ "$confirmed" != yes ]; then - printf 'This replaces the whole archive (database and files) with the backup in %s.\nType "restore" to continue: ' "$folder" + scope="database and files" + [ "$database_only" != yes ] || scope="database" + printf 'This replaces the whole archive (%s) with the backup in %s.\nType "restore" to continue: ' "$scope" "$folder" read -r answer [ "$answer" = restore ] || { echo "Nothing was changed."; exit 1; } fi @@ -48,9 +59,13 @@ docker compose exec -T db dropdb --username=commonage --if-exists --force common docker compose exec -T db createdb --username=commonage commonage docker compose exec -T db pg_restore --username=commonage --dbname=commonage --no-owner --exit-on-error < "$folder/database.dump" -echo "Restoring the uploaded files..." -docker compose run --rm --no-deps -T --entrypoint sh web -c \ - 'find /app/App_Data/media -mindepth 1 -delete && tar -C /app/App_Data -xf -' < "$folder/media.tar" +if [ "$database_only" = yes ]; then + echo "Leaving the uploaded files as they are." +else + echo "Restoring the uploaded files..." + docker compose run --rm --no-deps -T --entrypoint sh web -c \ + 'find /app/App_Data/media -mindepth 1 -delete && tar -C /app/App_Data -xf -' < "$folder/media.tar" +fi echo "Starting the app..." docker compose up -d web >/dev/null diff --git a/scripts/test-update.sh b/scripts/test-update.sh index 8250e59..9125a7b 100755 --- a/scripts/test-update.sh +++ b/scripts/test-update.sh @@ -1,7 +1,8 @@ #!/bin/sh # Tests updating a real archive: starts an earlier published release in the production setup, makes a backup with that # release's own scripts, tries an update that fails after upgrading the database, checks that everything went back, -# updates to the current code, and finally restores the old release's backup into the new version. +# updates to the current code (which moves the archive to a new PostgreSQL major version when the code uses another one +# than the release, and keeps the old database in the volume), and finally restores the old release's backup into the new version. # # scripts/test-update.sh from the newest earlier release that has a published image # scripts/test-update.sh 0.3 from the newest 0.3.x release that has a published image @@ -95,6 +96,25 @@ running_image() { docker inspect --format '{{.Config.Image}}' "$(docker compose ps --quiet web)" } +database_major() { + version=$(docker compose exec -T db psql --username=commonage --dbname=commonage -Atc 'show server_version_num' | tr -d '\r') + echo $(( version / 10000 )) +} + +item_count() { + docker compose exec -T db psql --username=commonage --dbname=commonage -Atc 'select count(*) from "ArchiveItems"' | tr -d '\r' +} + +# The PostgreSQL major that the current code starts. When the previous release runs another one, the update moves the +# archive to it, and that is the path this test is about. +expected_major=$(git show "$head:compose.yaml" | sed -n 's/^ *image: *postgres:\([0-9][0-9]*\).*/\1/p' | head -n 1) +[ -n "$expected_major" ] || fail "could not read the PostgreSQL version from compose.yaml" + +# Different for every database cluster: it only stays the same when the original data directory is the one that runs. +cluster_identity() { + docker compose exec -T db psql --username=commonage --dbname=commonage -Atc 'select system_identifier from pg_control_system()' | tr -d '\r' +} + migrations() { docker compose exec -T db psql --username=commonage --dbname=commonage -Atc 'select count(*) from "__EFMigrationsHistory"' | tr -d '\r' } @@ -112,6 +132,11 @@ echo "Starting $previous with the demo content..." docker compose up -d --no-build >/dev/null 2>&1 wait_for_page migrations_before=$(migrations) +major_before=$(database_major) +items_before=$(item_count) +identity_before=$(cluster_identity) +[ "$items_before" -gt 0 ] || fail "the demo content is not in the database" +echo "$previous runs PostgreSQL $major_before; the current code runs PostgreSQL $expected_major." # The backup that release itself makes, with its own scripts. It is restored into the new version at the end. echo "Making a backup with $previous..." @@ -129,8 +154,31 @@ wait_for_page grep -q '^COMMONAGE_VERSION=8.0.0' .env || fail ".env did not go back" grep -q '^POSTGRES_PASSWORD=update-test' .env || fail ".env lost its other lines" [ "$(migrations)" = "$migrations_before" ] || fail "the database was not restored ($(migrations) migrations, was $migrations_before)" +[ "$(database_major)" = "$major_before" ] || fail "the database is on PostgreSQL $(database_major) after going back, was $major_before" +[ "$(cluster_identity)" = "$identity_before" ] || fail "going back did not bring back the original database (another cluster runs)" +[ "$(item_count)" = "$items_before" ] || fail "the items were not restored after going back" [ ! -e .env.updating ] || fail "a temporary file stayed behind" +if [ "$major_before" != "$expected_major" ]; then + echo "Interrupting an update right after the old database was set aside..." + if COMMONAGE_UPDATE_TEST_CRASH=after-rename sh scripts/update.sh 9.0.0 "$work/backups" >/dev/null 2>&1; then + fail "the interrupted update reported success" + fi + [ -f .update-in-progress ] || fail "the interrupted update left no marker" + if again=$(sh scripts/update.sh 9.0.0 "$work/backups" 2>&1); then fail "an update was accepted over an unfinished one"; fi + echo "$again" | grep -q "/var/lib/postgresql/$major_before/kept" || fail "the refusal does not say where the old database is: $again" + echo "$again" | grep -q -- "--recover" || fail "the refusal does not say how to recover: $again" + sh scripts/update.sh --recover >/dev/null || fail "the recovery failed" + wait_for_page + [ ! -e .update-in-progress ] || fail "the marker stayed after the recovery" + [ "$(running_image)" = "$image:8.0.0" ] || fail "the old image does not run after the recovery, but $(running_image)" + [ "$(git describe --tags --exact-match HEAD)" = v8.0.0 ] || fail "the checkout did not go back in the recovery" + grep -q '^COMMONAGE_VERSION=8.0.0' .env || fail ".env did not go back in the recovery" + [ "$(database_major)" = "$major_before" ] || fail "the database is not on PostgreSQL $major_before after the recovery" + [ "$(cluster_identity)" = "$identity_before" ] || fail "the recovery did not bring back the original database" + [ "$(item_count)" = "$items_before" ] || fail "the items are not as before after the recovery" +fi + echo "Refusing what cannot work..." if sh scripts/update.sh 7.0.0 "$work/backups" 2>/dev/null; then fail "an unknown release was accepted"; fi if sh scripts/update.sh nonsense "$work/backups" 2>/dev/null; then fail "a wrong version was accepted"; fi @@ -149,6 +197,17 @@ readable=$(docker compose exec -T db psql --username=commonage --dbname=commonag "select count(*) from \"DataProtectionKeys\" where \"Xml\" like '%requiresEncryption=\"true\"%'" | tr -d '\r') [ "$readable" = 0 ] || fail "$readable login keys in the database are still readable without the key" curl -kfsS https://localhost/search | grep -q "Flood in Mill Street" || fail "the content did not survive the update" +[ "$(database_major)" = "$expected_major" ] || fail "the database is on PostgreSQL $(database_major), not $expected_major" +[ "$(item_count)" = "$items_before" ] || fail "the items did not survive the update ($(item_count), were $items_before)" +if [ "$major_before" != "$expected_major" ]; then + # The old database stays in the volume, set aside, until the curator removes it with the command the update prints. + kept=$(docker compose run --rm --no-deps -T --entrypoint ls db "/var/lib/postgresql/$major_before" | tr -d '\r') + [ "$kept" = kept ] || fail "the old database was not kept in the volume ('$kept')" + docker compose run --rm --no-deps -T --entrypoint rm db -rf "/var/lib/postgresql/$major_before" >/dev/null + old_folders=$(docker compose run --rm --no-deps -T --entrypoint ls db /var/lib/postgresql | tr -d '\r') + [ "$old_folders" = "$expected_major" ] || fail "removing the old database left '$old_folders'" + [ "$(database_major)" = "$expected_major" ] || fail "the database does not answer after removing the old one" +fi migrations_current=$(migrations) [ "$(ls -d "$work"/backups/commonage-* | wc -l)" -ge 2 ] || fail "no backup was made" diff --git a/scripts/update.sh b/scripts/update.sh index 67d31b9..c006777 100755 --- a/scripts/update.sh +++ b/scripts/update.sh @@ -48,7 +48,82 @@ add_login_key() { } pull() { - [ "${COMMONAGE_UPDATE_SKIP_PULL:-}" = 1 ] || docker compose pull --quiet web + [ "${COMMONAGE_UPDATE_SKIP_PULL:-}" = 1 ] || docker compose pull --quiet web "$@" +} + +# The PostgreSQL major version of the database that is running now (18, 19, ...). +running_database_major() { + version=$(docker compose exec -T db psql --username=commonage --dbname=commonage -Atc 'show server_version_num' 2>/dev/null | tr -d '\r') || return 0 + case "$version" in + [0-9][0-9][0-9][0-9][0-9]*) echo $(( version / 10000 )) ;; + esac +} + +# The PostgreSQL major version that the checked-out compose files start (18 for "postgres:18-alpine@sha256:..."). +configured_database_major() { + docker compose config 2>/dev/null | sed -n 's/^ *image: *postgres:\([0-9][0-9]*\).*/\1/p' | head -n 1 +} + +is_number() { + case "$1" in + "" | *[!0-9]*) return 1 ;; + esac +} + +# The old and the new major are only ever used in commands when both are plain numbers and the new one is higher. +valid_majors() { + is_number "$1" && is_number "$2" && [ "$2" -gt "$1" ] +} + +# Runs a script in the database volume, with the database stopped. $1 is the script, $2 the old major, $3 the new one; +# the script sees them as $OLD and $NEW. The image of the database refuses to start while the volume holds the data of +# another major version in /var/lib/postgresql//docker, so the old data is renamed to +# /var/lib/postgresql//kept: nothing is deleted, the new version no longer sees it, and the previous release +# gets it back by renaming it again. +in_database_volume() { + valid_majors "$2" "$3" || return 1 + docker compose stop db >/dev/null 2>&1 || true + docker compose run --rm --no-deps -T -e OLD="$2" -e NEW="$3" --entrypoint sh db -c "$1" >/dev/null +} + +# Renames the old data. Refuses when a "kept" is there already: it is the data of an earlier, unfinished move. +set_old_database_aside() { + in_database_volume ' + old=/var/lib/postgresql/$OLD + if [ -e "$old/kept" ]; then echo "$old/kept exists already, from an earlier update. Nothing was moved." >&2; exit 2; fi + [ -s "$old/docker/PG_VERSION" ] || { echo "There is no database in $old/docker. Nothing was moved." >&2; exit 3; } + mv "$old/docker" "$old/kept" + ' "$1" "$2" +} + +# Undoes the above after a failed or interrupted update, and can be run again. The database of the new major in the +# volume is only a copy of the backup. An empty or new "docker" folder of the old major is moved aside, never over +# "kept", and a "docker" folder that holds a database is never replaced. +bring_old_database_back() { + in_database_volume ' + old=/var/lib/postgresql/$OLD + rm -rf "/var/lib/postgresql/$NEW/docker" + if [ -d "$old/kept" ]; then + if [ -e "$old/docker" ]; then + [ ! -s "$old/docker/PG_VERSION" ] || { echo "$old/docker holds a database and $old/kept does too. Nothing was changed." >&2; exit 4; } + mv "$old/docker" "$old/docker.unused.$(date +%s)" + fi + mv "$old/kept" "$old/docker" + elif [ ! -s "$old/docker/PG_VERSION" ]; then + echo "The old database is neither in $old/kept nor in $old/docker." >&2 + exit 5 + fi + ' "$1" "$2" +} + +# Checks the backup again right before the database is replaced. +backup_is_intact() { + [ -s "$1/database.dump" ] && [ -f "$1/media.tar" ] || return 1 + if command -v sha256sum >/dev/null 2>&1; then + (cd "$1" && sha256sum -c --quiet SHA256SUMS) + else + (cd "$1" && shasum -a 256 -c --quiet SHA256SUMS) + fi } # Asks from inside the Compose network, because in production the app has no open port. The app answers only after it @@ -67,48 +142,232 @@ wait_until_healthy() { return 1 } +# While the old database is set aside, this file says so. An update that stopped halfway (the connection dropped, the +# power went) would otherwise look like a finished one, and the app could start on an empty database. Nothing else +# runs while it exists. +marker=.update-in-progress + +write_marker() { + printf 'backup=%s\nold_major=%s\nnew_major=%s\nprevious_ref=%s\nnew_ref=%s\n' "$1" "$2" "$3" "$4" "$5" > "$marker.tmp" + mv "$marker.tmp" "$marker" +} + +marker_value() { + sed -n "s/^$1=//p" "$marker" | head -n 1 | tr -d '\r' +} + +print_recovery() { + m_backup=$(marker_value backup) + m_old=$(marker_value old_major) + m_new=$(marker_value new_major) + m_previous=$(marker_value previous_ref) + cat >&2 </dev/null 2>&1 || true + git checkout -q "$r_previous" + set_version "${r_previous#v}" + bring_old_database_back "$r_old" "$r_new" || die "the old database could not be put back. $marker stays; the old database is untouched." + docker compose up -d --remove-orphans >/dev/null + wait_until_healthy || die "the app does not answer. $marker stays. Look at: docker compose logs web" + rm -f "$marker" + echo "The archive runs on $r_previous again, on its old database." + exit 0 +fi + +if [ "${1:-}" != --after-checkout ] && [ -f "$marker" ]; then + print_recovery + die "an earlier update did not finish." +fi + # Stage 2 runs from the new release's copy of this script, because the checkout may have replaced the running one. if [ "${1:-}" = --after-checkout ]; then new_ref=$2 setting=$3 previous_ref=$4 backups=$5 + # A dropped connection must not stop the update halfway; other signals and failures go back (see below). + trap '' HUP + + backup= + old_major= + new_major= + major_change=0 + # While 1, an unexpected end of the script puts the archive back on the previous release. + guard=0 go_back_without_restoring() { git checkout -q "$previous_ref" set_version "${previous_ref#v}" } + # Nothing was changed on disk yet, besides the version, and the app only has to be started again. + go_back_without_restoring_and_restart() { + go_back_without_restoring + docker compose up -d web >/dev/null 2>&1 || true + rm -f "$marker" + } + + stop_update() { + guard=0 + die "$@" + } + + on_unexpected_end() { + code=$? + trap - EXIT INT TERM + if [ "$guard" = 1 ] && [ "$code" -ne 0 ]; then + guard=0 + echo "The update stopped unexpectedly. Going back to $previous_ref..." >&2 + git checkout -q "$previous_ref" 2>/dev/null || true + set_version "${previous_ref#v}" 2>/dev/null || true + if [ "$major_change" = 1 ]; then + if bring_old_database_back "$old_major" "$new_major" && docker compose up -d --remove-orphans >/dev/null 2>&1; then + rm -f "$marker" + echo "The archive is back on $previous_ref with its old database." >&2 + else + print_recovery + fi + else + docker compose up -d --remove-orphans >/dev/null 2>&1 || true + fi + fi + exit "$code" + } + trap on_unexpected_end EXIT + trap 'exit 130' INT TERM + + # A new PostgreSQL major version cannot open the data of the old one. The database that is running still belongs to + # the previous release, which is what the backup has to read, so this is asked before anything is changed. + old_major=$(running_database_major) + new_major=$(configured_database_major) + if ! is_number "$old_major" || ! is_number "$new_major"; then + go_back_without_restoring + stop_update "could not tell which PostgreSQL version the database runs ('$old_major') and which $new_ref needs ('$new_major'). Nothing was changed." + fi + if [ "$new_major" -lt "$old_major" ]; then + go_back_without_restoring + stop_update "$new_ref needs PostgreSQL $new_major, older than the $old_major that the archive runs. To go back to an older version, restore a backup (docs/operations.md). Nothing was changed." + fi + [ "$old_major" = "$new_major" ] || major_change=1 + + if [ "$major_change" = 1 ]; then + # The login key goes into .env while the app still runs, so that no step later in the move can fail on it. + add_login_key || { go_back_without_restoring; stop_update "could not write .env. Nothing was changed."; } + # The app stops before the backup, so that nothing is added between the backup and the move to the new database. + echo "$new_ref uses PostgreSQL $new_major, the archive is on PostgreSQL $old_major. The archive is moved with the backup." + write_marker "" "$old_major" "$new_major" "$previous_ref" "$new_ref" + guard=1 + docker compose stop web >/dev/null 2>&1 || true + else + guard=1 + fi + echo "Backing up..." if ! sh scripts/backup.sh "$backups"; then - go_back_without_restoring - die "the backup failed. Nothing was changed." + guard=0 + go_back_without_restoring_and_restart + stop_update "the backup failed. Nothing was changed." fi backup=$(ls -dt "$backups"/commonage-* | head -n 1) + [ "$major_change" != 1 ] || write_marker "$backup" "$old_major" "$new_major" "$previous_ref" "$new_ref" echo "Getting $new_ref..." set_version "$setting" - if ! pull; then + if [ "$major_change" = 1 ]; then + # Nothing is replaced unless the backup is whole and the new database image is here. + backup_is_intact "$backup" || { go_back_without_restoring_and_restart; stop_update "the backup did not pass its checksums. Nothing was changed."; } + pull db || { go_back_without_restoring_and_restart; stop_update "could not download $new_ref. Nothing was changed."; } + elif ! pull; then go_back_without_restoring - die "could not download $new_ref. Nothing was changed." + stop_update "could not download $new_ref. Nothing was changed." fi # After the backup, which keeps the archive as it was in case the update has to be undone. add_login_key + # From here on, a same-major update has started the new app, and only the backup can undo that. + [ "$major_change" = 1 ] || guard=0 echo "Starting $new_ref. The app upgrades the database when it starts, which can take a while." - if docker compose up -d --remove-orphans web && wait_until_healthy; then + # With a new PostgreSQL major, the old data is set aside in the volume (not deleted), the new database starts empty + # and the backup's database is restored into it; the uploaded files stay as they are. The app starts at the end. + moved=1 + if [ "$major_change" = 1 ]; then + echo "Moving the archive to PostgreSQL $new_major..." + if set_old_database_aside "$old_major" "$new_major"; then + # Only scripts/test-update.sh sets this: it stops the update right here, as a power cut would. + [ "${COMMONAGE_UPDATE_TEST_CRASH:-}" != after-rename ] || kill -9 $$ + sh scripts/restore.sh --yes --database-only "$backup" || moved=0 + else + moved=0 + fi + fi + if [ "$moved" = 1 ] && docker compose up -d --remove-orphans web && wait_until_healthy; then docker compose up -d --remove-orphans >/dev/null + guard=0 + rm -f "$marker" echo "Updated to $new_ref. The backup from just before is in $backup" + if [ "$major_change" = 1 ]; then + echo "The archive now runs on PostgreSQL $new_major. The old database is still in the volume, set aside, so that going back stays possible." + echo "It holds the archive's data, including personal data, until it is removed. Once the archive has run well for a while, free its disk space with:" + echo " docker compose run --rm --no-deps --entrypoint rm db -rf /var/lib/postgresql/$old_major" + fi exit 0 fi + guard=0 echo "$new_ref did not come up. Its log:" >&2 docker compose logs --tail 40 web >&2 || true - echo "Going back to $previous_ref and restoring the backup..." >&2 + echo "Going back to $previous_ref..." >&2 # The exact version, because a version such as 0.3 may now point to the release that just failed. git checkout -q "$previous_ref" set_version "${previous_ref#v}" - if pull && sh scripts/restore.sh --yes "$backup" && wait_until_healthy; then - docker compose up -d --remove-orphans >/dev/null - die "the archive is back on $previous_ref as it was before. Nothing was lost, unless something changed during the update attempt. Please report the problem." + if [ "$major_change" = 1 ]; then + docker compose stop web >/dev/null 2>&1 || true + if bring_old_database_back "$old_major" "$new_major"; then + # The old database is back as it was, and nothing wrote to it: the backup is not needed. + if pull && docker compose up -d --remove-orphans web && wait_until_healthy; then + docker compose up -d --remove-orphans >/dev/null + rm -f "$marker" + die "the archive is back on $previous_ref, on its old database, as it was before. Nothing was lost, unless something changed during the update attempt. Please report the problem." + fi + fi + else + echo "Restoring the backup..." >&2 + if pull && sh scripts/restore.sh --yes "$backup" && wait_until_healthy; then + docker compose up -d --remove-orphans >/dev/null + die "the archive is back on $previous_ref as it was before. Nothing was lost, unless something changed during the update attempt. Please report the problem." + fi + fi + if [ "$major_change" = 1 ]; then + print_recovery + die "going back failed too. The archive may be down. The old database is untouched in /var/lib/postgresql/$old_major/kept or /var/lib/postgresql/$old_major/docker of the database volume, and $marker stays until it is cleared up: follow the steps above. The backup is $backup." fi die "going back failed too. The archive may be down. Your data is safe in $backup: follow \"Restore\" in docs/operations.md, with COMMONAGE_VERSION=${previous_ref#v} in .env." fi @@ -164,5 +423,22 @@ needed_kilobytes=$(( database_bytes / 1024 + ${media_kilobytes:-0} + 1048576 )) [ "$free_kilobytes" -ge "$needed_kilobytes" ] || die "the backup needs about $(( needed_kilobytes / 1024 )) MB in $backups, and only $(( free_kilobytes / 1024 )) MB are free. Make room, or name another folder: scripts/update.sh ${target:-} /other/folder" +# A new PostgreSQL major version needs room for a second copy of the database in the database volume (the old one is kept). +running_major=$(running_database_major) +next_major=$(git show "$new_ref:compose.yaml" 2>/dev/null | sed -n 's/^ *image: *postgres:\([0-9][0-9]*\).*/\1/p' | head -n 1) +if is_number "$running_major" && is_number "$next_major" && [ "$next_major" != "$running_major" ]; then + [ "$next_major" -gt "$running_major" ] || + die "$new_ref needs PostgreSQL $next_major, older than the $running_major that the archive runs. To go back to an older version, restore a backup (docs/operations.md)." + volume_free_kilobytes=$(docker compose run --rm --no-deps -T --entrypoint df db -Pk /var/lib/postgresql 2>/dev/null | awk 'NR == 2 { print $4 }' | tr -d '\r') + # The restored database, with its indexes, plus a little for the new server to work in. + volume_needed_kilobytes=$(( database_bytes / 1024 + database_bytes / 2048 + 262144 )) + if is_number "$volume_free_kilobytes"; then + [ "$volume_free_kilobytes" -ge "$volume_needed_kilobytes" ] || + die "$new_ref moves the archive to PostgreSQL $next_major, which keeps the old database and needs about $(( volume_needed_kilobytes / 1024 )) MB more in the database volume, and only $(( volume_free_kilobytes / 1024 )) MB are free. Make room first (docs/operations.md, \"A new PostgreSQL version\")." + else + echo "Warning: could not see how much room the database volume has. $new_ref moves the archive to PostgreSQL $next_major, which needs about $(( volume_needed_kilobytes / 1024 )) MB more there." >&2 + fi +fi + git checkout -q "$new_ref" exec sh scripts/update.sh --after-checkout "$new_ref" "$setting" "$previous_ref" "$backups" diff --git a/tests/Commonage.BrowserTests/BrowserFixture.cs b/tests/Commonage.BrowserTests/BrowserFixture.cs index f58f8a2..e4dfd29 100644 --- a/tests/Commonage.BrowserTests/BrowserFixture.cs +++ b/tests/Commonage.BrowserTests/BrowserFixture.cs @@ -15,7 +15,7 @@ public sealed class BrowserFixture : WebApplicationFactory, IAsyncLifet public const string AdminEmail = "admin@example.org"; public const string AdminPassword = "Browser-test-password-1"; - private readonly PostgreSqlContainer _db = new PostgreSqlBuilder("postgres:18-alpine").Build(); + private readonly PostgreSqlContainer _db = new PostgreSqlBuilder("postgres:19-alpine").Build(); private readonly string _storageRoot = Path.Combine(Path.GetTempPath(), "commonage-browser-tests", Guid.NewGuid().ToString("N")); private IPlaywright? _playwright; private IBrowserContext? _lastContext; diff --git a/tests/Commonage.Tests/CommonageAppFactory.cs b/tests/Commonage.Tests/CommonageAppFactory.cs index a783de0..e5a8546 100644 --- a/tests/Commonage.Tests/CommonageAppFactory.cs +++ b/tests/Commonage.Tests/CommonageAppFactory.cs @@ -11,7 +11,7 @@ public class CommonageAppFactory : WebApplicationFactory, IAsyncLifetim public const string AdminEmail = "admin@example.org"; public const string AdminPassword = "Test-only-password-1"; - private readonly PostgreSqlContainer _db = new PostgreSqlBuilder("postgres:18-alpine").Build(); + private readonly PostgreSqlContainer _db = new PostgreSqlBuilder("postgres:19-alpine").Build(); private readonly string _storageRoot = Path.Combine(Path.GetTempPath(), "commonage-tests", Guid.NewGuid().ToString("N")); /// Connects as the container's superuser, for tests that set up databases of their own.