diff --git a/roles/web-app-stalwart/README.md b/roles/web-app-stalwart/README.md index fec5619a68..1be06116af 100644 --- a/roles/web-app-stalwart/README.md +++ b/roles/web-app-stalwart/README.md @@ -281,7 +281,7 @@ The provider cutover is an inventory change; mailbox data moves with it when the - keeps folders, flags, Dovecot keywords and internal dates; Mailu's `Sent`, `Trash`, `Junk`/`Spam` and `Drafts` land in the folders Stalwart marks with the matching special use, - imports the active Sieve script and activates it. - A host without Mailu's maildir volume gets a note that there is nothing to import. Otherwise the deploy starts the import as the transient unit `stalwart-mailu-import` and moves on; a deploy that finds the unit still running leaves it alone. Follow it with `journalctl -fu stalwart-mailu-import`: it logs `[PROGRESS]` every 1000 messages of a folder, one `[MAILBOX] -> : found= imported= skipped= failed= sieve=` line per mailbox, one line per folder below it, `[SKIP]` for every mailbox outside the served domains, a closing `[SUMMARY]` and `[DONE] rc=`. When the unit stops, it removes the staged credentials. A re-run imports nothing twice: a message is skipped when its Message-ID, or without one its Date/From/To/Subject, is already in the target folder, and a Sieve script with unchanged content is left alone. The switch may therefore stay on across deploys; turn it off once Mailu is retired. + A host without Mailu's maildir volume gets a note that there is nothing to import. Otherwise the deploy starts the import as the transient unit `stalwart-mailu-import` and moves on; a deploy that finds the unit still running leaves it alone. Follow it with `journalctl -fu stalwart-mailu-import`: it logs `[PROGRESS]` every 1000 messages of a folder, one `[MAILBOX] -> : found= imported= skipped= failed= sieve=` line per mailbox, one line per folder below it, `[SKIP]` for every mailbox outside the served domains, a closing `[SUMMARY]` and `[DONE] rc=`. When the unit stops, it removes the staged credentials. An import that ends with `[DONE] rc=0` leaves the marker `.mailu-import.done` in the Stalwart instance directory, and no later deploy starts the import again while it exists; delete the marker to import again. A failed import leaves no marker, so the next deploy repeats it, and the repeat imports nothing twice: a message is skipped when its Message-ID, or without one its Date/From/To/Subject, is already in the target folder, and a Sieve script with unchanged content is left alone. Turn the switch off once Mailu is retired. 5. Non-Cloudflare DNS: publish the new DKIM TXT record reported by the deploy; MX and A records keep their hostname. A `mailbox_map` entry merges a Mailu mailbox into another account instead of creating its own: diff --git a/roles/web-app-stalwart/files/python/imap_layout.py b/roles/web-app-stalwart/files/python/imap_layout.py new file mode 100644 index 0000000000..80ce1ea6b8 --- /dev/null +++ b/roles/web-app-stalwart/files/python/imap_layout.py @@ -0,0 +1,97 @@ +"""Map Mailu maildir folders onto Stalwart's IMAP folders and read what is there.""" + +from __future__ import annotations + +import re +from dataclasses import dataclass +from typing import TYPE_CHECKING + +from mailu_maildir import dedup_key, maildir_folder_to_imap + +if TYPE_CHECKING: + import imaplib + +_SPECIAL_USE = { + "sent": "\\Sent", + "trash": "\\Trash", + "junk": "\\Junk", + "spam": "\\Junk", + "drafts": "\\Drafts", +} +_LIST_LINE = re.compile( + r'^\((?P[^)]*)\) (?:"(?P[^"]*)"|NIL) (?P.+)$' +) +_KEY_FETCH = "(BODY.PEEK[HEADER.FIELDS (MESSAGE-ID DATE FROM TO SUBJECT)])" +_FETCH_CHUNK = 500 + + +class MigrationError(RuntimeError): + pass + + +@dataclass(frozen=True) +class ServerLayout: + separator: str + special_use: dict[str, str] + + +def imap_quote(value: str) -> str: + return '"' + value.replace("\\", "\\\\").replace('"', '\\"') + '"' + + +def _imap_unquote(name: str) -> str: + if len(name) >= 2 and name[0] == name[-1] == '"': + return name[1:-1].replace('\\"', '"').replace("\\\\", "\\") + return name + + +def server_layout(imap: imaplib.IMAP4) -> ServerLayout: + typ, lines = imap.list() + if typ != "OK": + raise MigrationError(f"LIST failed: {lines}") + separators: set[str] = set() + special_use: dict[str, str] = {} + for line in lines or []: + if not isinstance(line, bytes): + continue + match = _LIST_LINE.match(line.decode("utf-8", "replace")) + if not match: + continue + if match.group("separator"): + separators.add(match.group("separator")) + for attribute in match.group("attributes").split(): + if attribute in _SPECIAL_USE.values(): + special_use.setdefault(attribute, _imap_unquote(match.group("name"))) + if len(separators) != 1: + raise MigrationError(f"cannot tell the hierarchy separator from LIST: {lines}") + return ServerLayout(separators.pop(), special_use) + + +def destination_mailbox(maildir_name: str, layout: ServerLayout) -> str: + mailbox = maildir_folder_to_imap(maildir_name, layout.separator) + attribute = _SPECIAL_USE.get(mailbox.lower()) + return layout.special_use.get(attribute, mailbox) if attribute else mailbox + + +def existing_keys(imap: imaplib.IMAP4) -> set[str]: + """Dedup keys of the SELECTed folder, fetched client-side. + + ``SEARCH HEADER`` is not used: Stalwart indexes headers asynchronously, so a + search right after APPEND misses fresh messages. + """ + typ, nums = imap.search(None, "ALL") + if typ != "OK": + raise MigrationError(f"SEARCH failed: {nums}") + sequence = [n.decode() for n in (nums[0] or b"").split()] if nums else [] + keys: set[str] = set() + for start in range(0, len(sequence), _FETCH_CHUNK): + chunk = ",".join(sequence[start : start + _FETCH_CHUNK]) + typ, data = imap.fetch(chunk, _KEY_FETCH) + if typ != "OK": + raise MigrationError(f"FETCH of the dedup headers failed: {data}") + keys.update( + key + for part in data or [] + if isinstance(part, tuple) and (key := dedup_key(part[1])) + ) + return keys diff --git a/roles/web-app-stalwart/files/python/migrate_from_mailu.py b/roles/web-app-stalwart/files/python/migrate_from_mailu.py index b155fcb9c8..1bb4ad0318 100755 --- a/roles/web-app-stalwart/files/python/migrate_from_mailu.py +++ b/roles/web-app-stalwart/files/python/migrate_from_mailu.py @@ -10,6 +10,7 @@ Args: --admin-file: JSON ``{"user": ..., "password": ...}`` of Stalwart's recovery administrator. --mailbox-map: JSON list ``[{"source": ..., "target": ...}]`` merging a mailbox into another account. --workers: IMAP sessions appending in parallel per mailbox. + --done-file: marker written once an import ends without a failure. """ from __future__ import annotations @@ -18,7 +19,6 @@ import argparse import base64 import imaplib import json -import re import ssl import sys import threading @@ -29,6 +29,13 @@ from contextlib import suppress from dataclasses import dataclass, field from pathlib import Path +from imap_layout import ( + MigrationError, + destination_mailbox, + existing_keys, + imap_quote, + server_layout, +) from mailu_maildir import ( Mailbox, SieveScript, @@ -38,7 +45,6 @@ from mailu_maildir import ( iter_maildir_folders, iter_messages, maildir_flags_to_imap, - maildir_folder_to_imap, parse_mailbox_map, plan_imports, read_active_sieve, @@ -46,18 +52,6 @@ from mailu_maildir import ( sieve_script_name, ) -_SPECIAL_USE = { - "sent": "\\Sent", - "trash": "\\Trash", - "junk": "\\Junk", - "spam": "\\Junk", - "drafts": "\\Drafts", -} -_LIST_LINE = re.compile( - r'^\((?P[^)]*)\) (?:"(?P[^"]*)"|NIL) (?P.+)$' -) -_KEY_FETCH = "(BODY.PEEK[HEADER.FIELDS (MESSAGE-ID DATE FROM TO SUBJECT)])" -_FETCH_CHUNK = 500 _ADMIN_USING = ["urn:ietf:params:jmap:core", "urn:stalwart:jmap"] _SIEVE_CAPABILITY = "urn:ietf:params:jmap:sieve" _SIEVE_USING = ["urn:ietf:params:jmap:core", _SIEVE_CAPABILITY] @@ -68,10 +62,6 @@ _PROGRESS_EVERY = 1000 _LOOPBACK_OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({})) -class MigrationError(RuntimeError): - pass - - @dataclass class FolderStats: found: int = 0 @@ -91,74 +81,6 @@ class AccountStats: return sum(getattr(f, attribute) for f in self.folders.values()) -@dataclass(frozen=True) -class ServerLayout: - separator: str - special_use: dict[str, str] - - -def imap_quote(value: str) -> str: - return '"' + value.replace("\\", "\\\\").replace('"', '\\"') + '"' - - -def _imap_unquote(name: str) -> str: - if len(name) >= 2 and name[0] == name[-1] == '"': - return name[1:-1].replace('\\"', '"').replace("\\\\", "\\") - return name - - -def server_layout(imap: imaplib.IMAP4) -> ServerLayout: - typ, lines = imap.list() - if typ != "OK": - raise MigrationError(f"LIST failed: {lines}") - separators: set[str] = set() - special_use: dict[str, str] = {} - for line in lines or []: - if not isinstance(line, bytes): - continue - match = _LIST_LINE.match(line.decode("utf-8", "replace")) - if not match: - continue - if match.group("separator"): - separators.add(match.group("separator")) - for attribute in match.group("attributes").split(): - if attribute in _SPECIAL_USE.values(): - special_use.setdefault(attribute, _imap_unquote(match.group("name"))) - if len(separators) != 1: - raise MigrationError(f"cannot tell the hierarchy separator from LIST: {lines}") - return ServerLayout(separators.pop(), special_use) - - -def destination_mailbox(maildir_name: str, layout: ServerLayout) -> str: - mailbox = maildir_folder_to_imap(maildir_name, layout.separator) - attribute = _SPECIAL_USE.get(mailbox.lower()) - return layout.special_use.get(attribute, mailbox) if attribute else mailbox - - -def existing_keys(imap: imaplib.IMAP4) -> set[str]: - """Dedup keys of the SELECTed folder, fetched client-side. - - ``SEARCH HEADER`` is not used: Stalwart indexes headers asynchronously, so a - search right after APPEND misses fresh messages. - """ - typ, nums = imap.search(None, "ALL") - if typ != "OK": - raise MigrationError(f"SEARCH failed: {nums}") - sequence = [n.decode() for n in (nums[0] or b"").split()] if nums else [] - keys: set[str] = set() - for start in range(0, len(sequence), _FETCH_CHUNK): - chunk = ",".join(sequence[start : start + _FETCH_CHUNK]) - typ, data = imap.fetch(chunk, _KEY_FETCH) - if typ != "OK": - raise MigrationError(f"FETCH of the dedup headers failed: {data}") - keys.update( - key - for part in data or [] - if isinstance(part, tuple) and (key := dedup_key(part[1])) - ) - return keys - - def append_messages( imaps: list[imaplib.IMAP4], mailbox: str, @@ -488,11 +410,19 @@ def parse_args(argv: list[str] | None = None) -> argparse.Namespace: parser.add_argument("--admin-file", required=True) parser.add_argument("--mailbox-map", required=True) parser.add_argument("--workers", type=int, required=True) + parser.add_argument("--done-file", required=True) return parser.parse_args(argv) +def mark_done(done_file: Path, started: float) -> None: + done_file.write_text(f"{started:.0f}\n", encoding="utf-8") + + if __name__ == "__main__": start = time.time() - rc = run(parse_args()) + arguments = parse_args() + rc = run(arguments) + if rc == 0: + mark_done(Path(arguments.done_file), start) print(f"[DONE] rc={rc} in {time.time() - start:.1f}s") raise SystemExit(rc) diff --git a/roles/web-app-stalwart/files/test/verify/migration.sh b/roles/web-app-stalwart/files/test/verify/migration.sh index a8b76e9081..d98d19d16a 100644 --- a/roles/web-app-stalwart/files/test/verify/migration.sh +++ b/roles/web-app-stalwart/files/test/verify/migration.sh @@ -144,7 +144,8 @@ run_migration() { --jmap-url "${STALWART_JMAP_URL}" \ --admin-file "${WORKDIR}/admin.json" \ --mailbox-map "${STALWART_MAILBOX_MAP}" \ - --workers "${STALWART_IMPORT_WORKERS}" | tee "${log}" + --workers "${STALWART_IMPORT_WORKERS}" \ + --done-file "${WORKDIR}/import.done" | tee "${log}" rm -f "${WORKDIR}/admin.json" } diff --git a/roles/web-app-stalwart/tasks/12_import_mailu.yml b/roles/web-app-stalwart/tasks/12_import_mailu.yml index 4d23698444..4ceba050c6 100644 --- a/roles/web-app-stalwart/tasks/12_import_mailu.yml +++ b/roles/web-app-stalwart/tasks/12_import_mailu.yml @@ -12,6 +12,19 @@ msg: "Mailu's maildir volume {{ STALWART_MAILU_MAILDIR_VOLUME }} does not exist on this host yet; there is nothing to import." when: STALWART_MAILU_MAILDIR_VOLUME not in stalwart_volume_names.stdout_lines +- name: "๐Ÿ” Check whether a finished import left its marker" + ansible.builtin.stat: + path: "{{ STALWART_IMPORT_DONE_FILE }}" + register: stalwart_import_done + when: STALWART_MAILU_MAILDIR_VOLUME in stalwart_volume_names.stdout_lines + +- name: "โ„น๏ธ Report that the Mailu import is complete" + ansible.builtin.debug: + msg: "The Mailu import finished earlier; delete {{ STALWART_IMPORT_DONE_FILE }} to import again." + when: + - STALWART_MAILU_MAILDIR_VOLUME in stalwart_volume_names.stdout_lines + - stalwart_import_done.stat.exists + - name: "๐Ÿ” Read the state of the import unit" ansible.builtin.command: argv: @@ -23,18 +36,22 @@ - "{{ STALWART_IMPORT_UNIT }}" register: stalwart_import_unit_state changed_when: false - when: STALWART_MAILU_MAILDIR_VOLUME in stalwart_volume_names.stdout_lines + when: + - STALWART_MAILU_MAILDIR_VOLUME in stalwart_volume_names.stdout_lines + - not stalwart_import_done.stat.exists - name: "โ„น๏ธ Report that the import of an earlier deploy still runs" ansible.builtin.debug: msg: "{{ STALWART_IMPORT_UNIT }} is {{ stalwart_import_unit_state.stdout }}; follow it with: journalctl -fu {{ STALWART_IMPORT_UNIT }}" when: - STALWART_MAILU_MAILDIR_VOLUME in stalwart_volume_names.stdout_lines + - not stalwart_import_done.stat.exists - stalwart_import_unit_state.stdout not in ['inactive', 'failed'] - name: "๐Ÿ“ฅ Import every Mailu mailbox into Stalwart" when: - STALWART_MAILU_MAILDIR_VOLUME in stalwart_volume_names.stdout_lines + - not stalwart_import_done.stat.exists - stalwart_import_unit_state.stdout in ['inactive', 'failed'] block: - name: "๐Ÿ” Resolve the legacy Mailu maildir volume mountpoint" diff --git a/roles/web-app-stalwart/tasks/12_import_mailu/run.yml b/roles/web-app-stalwart/tasks/12_import_mailu/run.yml index a96bb47af7..fa3292d1ef 100644 --- a/roles/web-app-stalwart/tasks/12_import_mailu/run.yml +++ b/roles/web-app-stalwart/tasks/12_import_mailu/run.yml @@ -53,6 +53,8 @@ - "{{ STALWART_MAILBOX_MAP | to_json }}" - --workers - "{{ STALWART_IMPORT_WORKERS }}" + - --done-file + - "{{ STALWART_IMPORT_DONE_FILE }}" changed_when: true rescue: - name: "๐Ÿงน Remove the import working directory and its credentials" # nocheck: rescue-credentials the staged recovery administrator password would otherwise outlive a unit that never started, since only the unit's ExecStopPost removes it diff --git a/roles/web-app-stalwart/vars/main.yml b/roles/web-app-stalwart/vars/main.yml index c1d8fc1966..04c8384eee 100644 --- a/roles/web-app-stalwart/vars/main.yml +++ b/roles/web-app-stalwart/vars/main.yml @@ -100,8 +100,10 @@ STALWART_IMPORT_DIR: "{{ [ lookup('container', application_id, 'directories.inst STALWART_IMPORT_SCRIPTS: - migrate_from_mailu.py - mailu_maildir.py + - imap_layout.py STALWART_IMPORT_ADMIN_FILE: "{{ [ STALWART_IMPORT_DIR, 'admin.json' ] | path_join }}" STALWART_IMPORT_UNIT: "stalwart-mailu-import" +STALWART_IMPORT_DONE_FILE: "{{ [ lookup('container', application_id, 'directories.instance'), '.mailu-import.done' ] | path_join }}" STALWART_IMPORT_WORKERS: "{{ lookup('config', application_id, 'services.stalwart.migration.workers') or ([[RESOURCE_HOST_CPUS | int - 1, 1] | max, 8] | min) }}" STALWART_ALIASES: "{{ lookup('config', application_id, 'services.stalwart.aliases') | stalwart_aliases }}" diff --git a/tests/unit/python/roles/web-app-stalwart/files/test_imap_layout.py b/tests/unit/python/roles/web-app-stalwart/files/test_imap_layout.py new file mode 100644 index 0000000000..9d85b57eca --- /dev/null +++ b/tests/unit/python/roles/web-app-stalwart/files/test_imap_layout.py @@ -0,0 +1,94 @@ +import importlib.util +import sys +import unittest + +from . import PROJECT_ROOT + +SCRIPTS = PROJECT_ROOT / "roles/web-app-stalwart/files/python" +LIST_LINES = [ + b'(\\HasNoChildren) "/" "INBOX"', + b'(\\HasNoChildren \\Sent) "/" "Sent Items"', + b'(\\HasNoChildren \\Junk) "/" "Junk Mail"', + b'(\\HasNoChildren) "/" Archive', +] + + +def _load(name: str): + spec = importlib.util.spec_from_file_location(name, str(SCRIPTS / f"{name}.py")) + mod = importlib.util.module_from_spec(spec) + assert spec and spec.loader + sys.modules[name] = mod + spec.loader.exec_module(mod) + return mod + + +def _load_module(): + _load("mailu_maildir") + return _load("imap_layout") + + +class _FakeImap: + def __init__(self, existing_headers: list[bytes] | None = None, list_lines=None): + self._existing_headers = existing_headers or [] + self._list_lines = LIST_LINES if list_lines is None else list_lines + + def list(self): + return "OK", list(self._list_lines) + + def search(self, charset, *criteria): + nums = b" ".join( + str(i + 1).encode() for i in range(len(self._existing_headers)) + ) + return "OK", [nums] + + def fetch(self, message_set, message_parts): + data = [ + ((f"{i + 1} ()").encode(), header) + for i, header in enumerate(self._existing_headers) + ] + return "OK", data + + +class TestServerLayout(unittest.TestCase): + def setUp(self): + self.m = _load_module() + self.layout = self.m.server_layout(_FakeImap()) + + def test_reads_separator_and_special_use(self): + self.assertEqual(self.layout.separator, "/") + self.assertEqual( + self.layout.special_use, {"\\Sent": "Sent Items", "\\Junk": "Junk Mail"} + ) + + def test_nested_folder_uses_the_server_separator(self): + self.assertEqual( + self.m.destination_mailbox(".Archive.2024", self.layout), "Archive/2024" + ) + + def test_special_folder_lands_in_the_special_use_folder(self): + self.assertEqual(self.m.destination_mailbox(".Sent", self.layout), "Sent Items") + self.assertEqual(self.m.destination_mailbox(".Spam", self.layout), "Junk Mail") + + def test_special_name_without_server_counterpart_keeps_its_name(self): + self.assertEqual(self.m.destination_mailbox(".Drafts", self.layout), "Drafts") + + def test_ambiguous_separator_fails(self): + imap = _FakeImap(list_lines=[b'(\\X) "/" A', b'(\\X) "." B']) + with self.assertRaises(self.m.MigrationError): + self.m.server_layout(imap) + + def test_imap_quote_escapes(self): + self.assertEqual(self.m.imap_quote('My "x"\\y'), '"My \\"x\\"\\\\y"') + + +class TestExistingKeys(unittest.TestCase): + def test_collects_the_server_side_keys(self): + m = _load_module() + imap = _FakeImap( + existing_headers=[b"Message-ID: \r\n\r\n", b"X: 1\r\n\r\n"] + ) + self.assertEqual(m.existing_keys(imap), {""}) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/web-app-stalwart/files/test_migrate_from_mailu.py b/tests/unit/python/roles/web-app-stalwart/files/test_migrate_from_mailu.py index a8c039e85a..2e7888e70e 100644 --- a/tests/unit/python/roles/web-app-stalwart/files/test_migrate_from_mailu.py +++ b/tests/unit/python/roles/web-app-stalwart/files/test_migrate_from_mailu.py @@ -28,6 +28,7 @@ def _load(name: str): def _load_module(): _load("mailu_maildir") + _load("imap_layout") return _load("migrate_from_mailu") @@ -78,38 +79,6 @@ class _SlowImap(_FakeImap): return super().append(mailbox, flags, date_time, message) -class TestServerLayout(unittest.TestCase): - def setUp(self): - self.m = _load_module() - self.layout = self.m.server_layout(_FakeImap()) - - def test_reads_separator_and_special_use(self): - self.assertEqual(self.layout.separator, "/") - self.assertEqual( - self.layout.special_use, {"\\Sent": "Sent Items", "\\Junk": "Junk Mail"} - ) - - def test_nested_folder_uses_the_server_separator(self): - self.assertEqual( - self.m.destination_mailbox(".Archive.2024", self.layout), "Archive/2024" - ) - - def test_special_folder_lands_in_the_special_use_folder(self): - self.assertEqual(self.m.destination_mailbox(".Sent", self.layout), "Sent Items") - self.assertEqual(self.m.destination_mailbox(".Spam", self.layout), "Junk Mail") - - def test_special_name_without_server_counterpart_keeps_its_name(self): - self.assertEqual(self.m.destination_mailbox(".Drafts", self.layout), "Drafts") - - def test_ambiguous_separator_fails(self): - imap = _FakeImap(list_lines=[b'(\\X) "/" A', b'(\\X) "." B']) - with self.assertRaises(self.m.MigrationError): - self.m.server_layout(imap) - - def test_imap_quote_escapes(self): - self.assertEqual(self.m.imap_quote('My "x"\\y'), '"My \\"x\\"\\\\y"') - - class TestMigrateAccount(unittest.TestCase): def setUp(self): self.m = _load_module() @@ -164,12 +133,6 @@ class TestMigrateAccount(unittest.TestCase): self.assertEqual(stats.folder("Archive").skipped, 1) self.assertEqual(stats.total("found"), 4) - def test_existing_keys_collects_the_server_side_keys(self): - imap = _FakeImap( - existing_headers=[b"Message-ID: \r\n\r\n", b"X: 1\r\n\r\n"] - ) - self.assertEqual(self.m.existing_keys(imap), {""}) - def test_parallel_sessions_append_every_message_once(self): for index in range(5, 45): (self.account / "cur" / f"{index}.host:2,").write_bytes( @@ -205,9 +168,17 @@ class TestOpenSessions(unittest.TestCase): "--admin-file=/x/admin.json", "--mailbox-map=[]", f"--workers={workers}", + "--done-file=/x/import.done", ] ) + def test_done_marker_records_the_start_of_the_run(self): + with tempfile.TemporaryDirectory() as base: + marker = Path(base) / "import.done" + self.m.mark_done(marker, 1700000000.4) + self.assertTrue(marker.is_file()) + self.assertEqual(marker.stat().st_size, len("1700000000\n")) + def test_opens_one_session_per_worker(self): self.m.open_session = lambda args, stalwart, target: "s" self.assertEqual(self.m.open_sessions(self._args(3), None, "a@x"), ["s"] * 3)