From bd233bdb96bb18b489923d3cfa8b9cf7a305d7de Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Sun, 1 Nov 2026 09:26:59 +0100 Subject: [PATCH] fix(web-app-stalwart): migrate 0.16 stores with stalwart-migrate 1.0.4 and verify every account stalwart-migrate 1.0.0 failed the final verify on echoserver (6 rows) and galaxyserver (2 rows), all x:BlockedIp entries that expire when the tool starts 1.x, so a final run could never pass; 1.0.0 to 1.0.3 also skip accounts without a change counter. The pin moves to 1.0.4, final runs with --verify-full instead of a sample of 16 accounts, and a failed final restarts 0.16 and prints the error and verify rows of the new report phase, since final-report.txt is only written by a passing run. The README describes how to read the rows and when to start over. Co-Authored-By: Claude Opus 5.5 --- roles/web-app-stalwart/README.md | 15 +- .../files/shell/migrate_v016.sh | 18 ++- roles/web-app-stalwart/meta/services.yml | 2 +- .../files/test_migrate_v016.py | 136 ++++++++++++++++++ 4 files changed, 162 insertions(+), 9 deletions(-) create mode 100644 tests/unit/python/roles/web-app-stalwart/files/test_migrate_v016.py diff --git a/roles/web-app-stalwart/README.md b/roles/web-app-stalwart/README.md index 62f7b6c21e..6f1585b871 100644 --- a/roles/web-app-stalwart/README.md +++ b/roles/web-app-stalwart/README.md @@ -301,8 +301,9 @@ A deploy whose store guard finds a 0.16 store migrates it on its own ([`tasks/st | `target` | 3 | | `prepare` | 5, interactive on a terminal; without one it accepts the recommended answer of every question `stalwart-migrate` marks as not answered in `migrate-v016/state/answers.toml` | | `sync` | 5, repeatable while 0.16 serves | -| `final` | 6 and 7 | +| `final` | 6 and 7, with `--verify-full`, so every account is verified before the swap | | `status` | the progress `stalwart-migrate status` reports | +| `report` | the `error` and `verify` rows of `stalwart-migrate report`; `final` prints them itself when it fails | | `all` | `upgrade` to `final` in order | Then deploy again (step 8). The steps by hand: @@ -323,13 +324,13 @@ Then deploy again (step 8). The steps by hand: -v /etc:/etc/stalwart:ro \ -v :/etc/stalwart-v1 \ -v :/var/lib/stalwart-migrate \ - stalwartlabs/stalwart-migrate:1.0.0 prepare \ + stalwartlabs/stalwart-migrate:1.0.4 prepare \ --source /etc/stalwart/config.json \ --state /var/lib/stalwart-migrate ``` Then run the same container with `run --source /etc/stalwart/config.json --target /etc/stalwart-v1/config.json --state /var/lib/stalwart-migrate`. `run` copies only what changed since the previous run and may be repeated. -6. Stop the Stalwart server (`docker stop stalwart` in compose, `docker service scale _stalwart=0` in swarm) and run the same container with `run --final` and the same options. It verifies the copy and writes `final-report.txt` into the state directory. +6. Stop the Stalwart server (`docker stop stalwart` in compose, `docker service scale _stalwart=0` in swarm) and run the same container with `run --final` and the same options. It verifies the copy and, only when the verification passes, writes `final-report.txt` into the state directory. A failed verification writes no such file and leaves the run unmarked: list its rows with `report --state /var/lib/stalwart-migrate --severity verify` (or `migrate.sh report`), start Stalwart 0.16 again and see [A failed final run](#a-failed-final-run). 7. Swap the databases, as a PostgreSQL superuser connected to the `postgres` database: ```sql @@ -340,6 +341,14 @@ Then deploy again (step 8). The steps by hand: 8. Deploy this role. The store guard finds the migrated 1.x store under the role's database name and lets Stalwart 1.x start on it. 9. Keep `stalwart_v016`, the dump and the state directory until 1.x is verified. `stalwart-migrate rollback` reads the state directory to copy the 1.x store back into a new 0.16 store. +### A failed final run + +A failed `final` swaps nothing: Stalwart 0.16 serves the database `stalwart` again, and `stalwart_v1` and `migrate-v016/state` hold the unfinished copy. `stalwart-migrate rollback` does not apply, it copies a 1.x store back into a new 0.16 store. Every deploy of this role runs `all` again while the store is 0.16, so keep the role out of deploys until the rows are understood. + +1. Read the rows that `final` printed above its error in the deploy log, or run `migrate.sh report`. Each row names the run, the account id, the object type and id, and the kind of difference. +2. `stalwart-migrate` 1.0.0 to 1.0.3 report differences where none exist: email `keywords` holding a `\` system flag, contact card `vcard` with extra vCard 3.0 `N` or `ADR` components, and certificate or IP ban settings that the 1.x start inside the tool refreshes or expires. These releases also skip accounts that have no change counter. When the rows are only of these kinds and the state was written by such a release, start over with the pinned release: as a PostgreSQL superuser run `DROP DATABASE stalwart_v1;`, move `migrate-v016/state` aside and deploy again. +3. Any other row, such as an object missing in the target, `blob`, `script`, a quota, changelog or counter row, or `account is not up to date`, is a real difference. Keep 0.16 serving, fix its cause, then run `final` again with the same state. + ### Restore and redeploy The marker lives outside the stack and its volumes, so it survives `docker stack rm`, `docker compose down`, a crashed database and the stop and start cycle of `backup.project_hard_restart`. diff --git a/roles/web-app-stalwart/files/shell/migrate_v016.sh b/roles/web-app-stalwart/files/shell/migrate_v016.sh index be7a632494..a29ef135a6 100644 --- a/roles/web-app-stalwart/files/shell/migrate_v016.sh +++ b/roles/web-app-stalwart/files/shell/migrate_v016.sh @@ -1,5 +1,5 @@ #!/usr/bin/env bash -# Param $1: upgrade | check | backup | target | prepare | sync | final | status | all, the steps of "Upgrading from 0.16" in roles/web-app-stalwart/README.md. +# Param $1: upgrade | check | backup | target | prepare | sync | final | status | report | all, the steps of "Upgrading from 0.16" in roles/web-app-stalwart/README.md. # Param migrate.env: the values the deploy rendered next to this script. set -euo pipefail umask 077 @@ -193,9 +193,12 @@ phase_sync() { phase_final() { phase_check stop_stalwart - if ! migrate run --final --yes --source "${SOURCE_MOUNT}/config.json" --target "${TARGET_MOUNT}/config.json" --state "$STATE_MOUNT"; then + if ! migrate run --final --yes --verify-full --source "${SOURCE_MOUNT}/config.json" --target "${TARGET_MOUNT}/config.json" --state "$STATE_MOUNT"; then start_stalwart - die "the final run failed and nothing was swapped; Stalwart 0.16 serves again, see ${STATE_DIR}/final-report.txt" + if ! phase_report >&2; then + echo "migrate: stalwart-migrate report could not list the rows of ${STATE_DIR}" >&2 + fi + die "the final run failed and nothing was swapped; Stalwart 0.16 serves again; the error and verify rows above come from '$0 report', and ${STATE_DIR}/final-report.txt is only written by a final run that passes" fi psql_admin postgres "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname IN ('${DB}', '${DB_V1}') AND pid <> pg_backend_pid()" > /dev/null psql_admin postgres "ALTER DATABASE \"${DB}\" RENAME TO \"${DB_V016}\"" @@ -212,6 +215,11 @@ phase_status() { migrate status --state "$STATE_MOUNT" } +phase_report() { + migrate report --state "$STATE_MOUNT" --severity error + migrate report --state "$STATE_MOUNT" --severity verify +} + phase_all() { phase_upgrade phase_check @@ -223,11 +231,11 @@ phase_all() { } case "${1:-}" in - upgrade | check | backup | target | prepare | sync | final | status | all) + upgrade | check | backup | target | prepare | sync | final | status | report | all) "phase_$1" ;; *) - echo "usage: $0 upgrade|check|backup|target|prepare|sync|final|status|all" >&2 + echo "usage: $0 upgrade|check|backup|target|prepare|sync|final|status|report|all" >&2 exit 2 ;; esac diff --git a/roles/web-app-stalwart/meta/services.yml b/roles/web-app-stalwart/meta/services.yml index 6447fd11a5..65e7cc307e 100644 --- a/roles/web-app-stalwart/meta/services.yml +++ b/roles/web-app-stalwart/meta/services.yml @@ -149,7 +149,7 @@ stalwart_migrate: enabled: false shared: false image: stalwartlabs/stalwart-migrate - version: "1.0.0" + version: "1.0.4" design: bond: 1 enabled: "{{ 'web-svc-design' in group_names }}" diff --git a/tests/unit/python/roles/web-app-stalwart/files/test_migrate_v016.py b/tests/unit/python/roles/web-app-stalwart/files/test_migrate_v016.py new file mode 100644 index 0000000000..30855bd331 --- /dev/null +++ b/tests/unit/python/roles/web-app-stalwart/files/test_migrate_v016.py @@ -0,0 +1,136 @@ +from __future__ import annotations + +import os +import shlex +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + +from . import PROJECT_ROOT + +SCRIPT = PROJECT_ROOT / "roles" / "web-app-stalwart" / "files" / "shell" / "migrate_v016.sh" +CONTAINER_STUB = r"""#!/bin/sh +printf '%s\n' "$*" >>"$STUB_LOG" +case "$*" in + *" --help") echo "stalwart-migrate migrates a Stalwart v0.16 deployment to v1.0" ;; + *"{{.Config.Image}}"*) echo "stalwartlabs/stalwart:v0.16.27" ;; + *"{{.Image}}"*) echo "sha256:last" ;; + "image inspect "*) echo "sha256:last" ;; + *"{{range "*) echo "stalwart_net " ;; + *"FROM pg_database"*) echo 0 ;; + *'RENAME TO "stalwart"'*) : >"$STUB_SWAPPED" ;; + *"SELECT layout"*) if [ -e "$STUB_SWAPPED" ]; then echo bytea; else echo bigint; fi ;; + *" run --final "*) exit "$STUB_FINAL_RC" ;; + *" report "*) if [ "$STUB_REPORT_RC" != 0 ]; then exit "$STUB_REPORT_RC"; fi; echo "row of $*" ;; +esac +""" + + +def run_final(final_rc: int, report_rc: int) -> tuple[subprocess.CompletedProcess[str], list[str]]: + """Run the final phase against a stubbed container CLI. + + Args: + final_rc: exit code of `stalwart-migrate run --final`. + report_rc: exit code of `stalwart-migrate report`. + + Returns: + The finished script and the container CLI calls it made, in order. + """ + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + bin_dir = root / "bin" + bin_dir.mkdir() + stub = bin_dir / "container" + stub.write_text(CONTAINER_STUB) + stub.chmod(0o755) + stage = root / "migrate-v016" + stage.mkdir() + script = stage / "migrate.sh" + shutil.copy(SCRIPT, script) + values = { + "IMAGE": "stalwartlabs/stalwart-migrate:1.0.4", + "TARGET_VERSION": "v1.0.1", + "NETWORK": "stalwart_net", + "PG_ADMIN": "postgres", + "PG_ADDRESS": "postgres", + "DB": "stalwart", + "DB_OWNER": "stalwart", + "DB_V1": "stalwart_v1", + "DB_V016": "stalwart_v016", + "LAYOUT_SQL": "SELECT layout", + "SOURCE_DIR": str(root / "etc"), + "TARGET_DIR": str(stage / "target"), + "STATE_DIR": str(stage / "state"), + "BACKUP_FILE": str(stage / "backup" / "stalwart-v016.dump"), + "MARKER": str(root / "store.layout"), + "DEPLOYMENT_MODE": "compose", + "STALWART_CONTAINER": "stalwart", + "STACK_DIR": str(root), + "COMPOSE_SERVICE": "stalwart", + "STALWART_ADDRESS": "stalwart", + } + (stage / "migrate.env").write_text( + "".join(f"{key}={shlex.quote(value)}\n" for key, value in values.items()) + ) + log = root / "container.log" + log.touch() + done = subprocess.run( + ["bash", str(script), "final"], + env={ + "PATH": f"{bin_dir}{os.pathsep}{os.environ['PATH']}", + "STUB_LOG": str(log), + "STUB_SWAPPED": str(root / "swapped"), + "STUB_FINAL_RC": str(final_rc), + "STUB_REPORT_RC": str(report_rc), + }, + stdin=subprocess.DEVNULL, + capture_output=True, + text=True, + check=False, + ) + calls = log.read_text().splitlines() # nocheck: cache-read stub call log + return done, calls + + +def position(calls: list[str], fragment: str) -> int: + return next(index for index, call in enumerate(calls) if fragment in call) + + +class TestAFailedFinalRunShowsWhyAndSwapsNothing(unittest.TestCase): + def test_the_report_rows_follow_the_restart_of_0_16(self) -> None: + done, calls = run_final(final_rc=1, report_rc=0) + self.assertEqual(done.returncode, 1, done.stdout + done.stderr) + stop = calls.index("stop stalwart") + final = position(calls, " run --final ") + start = calls.index("start stalwart") + errors = position(calls, "report --state /migrate/state --severity error") + verify = position(calls, "report --state /migrate/state --severity verify") + self.assertLess(stop, final) + self.assertLess(final, start) + self.assertLess(start, errors) + self.assertLess(errors, verify) + self.assertIn(" --verify-full ", calls[final]) + self.assertFalse([call for call in calls if "RENAME" in call], calls) + self.assertIn("--severity verify", done.stderr) + self.assertIn("the final run failed and nothing was swapped", done.stderr) + + def test_a_failing_report_still_ends_in_the_final_error(self) -> None: + done, calls = run_final(final_rc=1, report_rc=3) + self.assertEqual(done.returncode, 1, done.stdout + done.stderr) + self.assertIn("start stalwart", calls) + self.assertIn("could not list the rows", done.stderr) + self.assertIn("the final run failed and nothing was swapped", done.stderr) + + def test_a_passing_final_run_swaps_without_a_report(self) -> None: + done, calls = run_final(final_rc=0, report_rc=0) + self.assertEqual(done.returncode, 0, done.stdout + done.stderr) + self.assertFalse([call for call in calls if " report " in call], calls) + self.assertNotIn("start stalwart", calls) + self.assertEqual(len([call for call in calls if "RENAME" in call]), 2, calls) + self.assertIn("final: stalwart holds the 1.x store", done.stdout) + + +if __name__ == "__main__": + unittest.main()