From b3861196420d94255b30268bd54b3b92790cda77 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Sun, 1 Nov 2026 09:19:28 +0100 Subject: [PATCH] perf(email): resolve only the requested key in lookup('email') Every lookup('email') resolved all 15 settings. On swarm workers and the nfs-server of Tor rows that took 22-26 s per call, even for tasks that only read external or timeout and then skip (CI run 41261531965, Nextcloud#7: ~600 s over both passes, the job ran out of its budget). The lookup takes key= now and stops after that entry; the four call sites and mail_recipient that need only external or timeout use it. Without key= the result is unchanged. Co-Authored-By: Claude Opus 5.5 --- plugins/lookup/email.py | 24 ++++- .../lookup_plugins/mail_recipient.py | 6 +- roles/sys-ctl-hlth-msmtp/tasks/00_core.yml | 2 +- roles/sys-svc-mail-msmtp/tasks/enable.yml | 2 +- roles/sys-svc-mail-smtp/tasks/disable.yml | 2 +- roles/sys-svc-mail/tasks/00_core.yml | 2 +- .../unit/python/plugins/lookup/test_email.py | 95 ++++++++++++++++++- .../lookup_plugins/test_mail_recipient.py | 14 ++- 8 files changed, 136 insertions(+), 11 deletions(-) diff --git a/plugins/lookup/email.py b/plugins/lookup/email.py index 53e8f2fb2a..b5942c5046 100644 --- a/plugins/lookup/email.py +++ b/plugins/lookup/email.py @@ -111,6 +111,18 @@ class LookupModule(LookupBase): variables: dict[str, Any] | None = None, **kwargs: Any, ) -> list[Any]: + """Resolve the system mail settings. + + Args: + terms: empty, or one application_id whose ``services.email`` + overrides are merged in. + variables: Ansible variables of the current host. + key: optional entry of RESOLUTION_ORDER; returns only that value, + resolving its predecessors but none of the later keys. + + Returns: + One-element list: the settings mapping, or the value of ``key``. + """ terms = terms or [] if len(terms) > 1: raise AnsibleError( @@ -118,6 +130,12 @@ class LookupModule(LookupBase): ) variables = variables or getattr(self._templar, "available_variables", {}) or {} + requested = kwargs.pop("key", None) + if requested is not None and requested not in RESOLUTION_ORDER: + raise AnsibleError( + f"email: unknown key {requested!r}, expected one of " + f"{', '.join(RESOLUTION_ORDER)}" + ) self._kwargs = kwargs templar = getattr(self, "_templar", None) @@ -133,16 +151,18 @@ class LookupModule(LookupBase): ) else: resolved[short_key] = _render(raw, templar, variables) + if short_key == requested: + break if len(terms) == 0: - return [resolved] + return [resolved if requested is None else resolved[requested]] application_id = str(terms[0]).strip() overrides = self._app_email_overrides(application_id, variables) merged = dict(resolved) for key, value in overrides.items(): merged[str(key).lower()] = _render(value, templar, variables) - return [merged] + return [merged if requested is None else merged[requested]] def _compute( self, diff --git a/roles/sys-ctl-hlth-msmtp/lookup_plugins/mail_recipient.py b/roles/sys-ctl-hlth-msmtp/lookup_plugins/mail_recipient.py index b5c09784e4..739a804f2b 100644 --- a/roles/sys-ctl-hlth-msmtp/lookup_plugins/mail_recipient.py +++ b/roles/sys-ctl-hlth-msmtp/lookup_plugins/mail_recipient.py @@ -23,10 +23,10 @@ class LookupModule(LookupBase): variables: dict[str, Any] | None = None, **kwargs: Any, ) -> list[str]: - email_cfg = _instantiate(EmailLookup, self._templar).run( - [], variables=variables + external = _instantiate(EmailLookup, self._templar).run( + [], variables=variables, key="external" )[0] - if _as_bool(email_cfg.get("external")): + if _as_bool(external): admin = _instantiate(UsersLookup, self._templar).run( ["administrator"], variables=variables )[0] diff --git a/roles/sys-ctl-hlth-msmtp/tasks/00_core.yml b/roles/sys-ctl-hlth-msmtp/tasks/00_core.yml index 96c5f28c62..43bdb0172a 100644 --- a/roles/sys-ctl-hlth-msmtp/tasks/00_core.yml +++ b/roles/sys-ctl-hlth-msmtp/tasks/00_core.yml @@ -7,7 +7,7 @@ system_service_timer_enabled: true system_service_tpl_environment: - "MAIL_RECIPIENT={{ lookup('mail_recipient') }}" - - "MAIL_TIMEOUT={{ lookup('email').timeout }}" + - "MAIL_TIMEOUT={{ lookup('email', key='timeout') }}" system_service_force_flush_instant: "{{ MODE_DEBUG | bool }}" system_service_force_flush_final: false diff --git a/roles/sys-svc-mail-msmtp/tasks/enable.yml b/roles/sys-svc-mail-msmtp/tasks/enable.yml index d332b9eed7..c05cf684fa 100644 --- a/roles/sys-svc-mail-msmtp/tasks/enable.yml +++ b/roles/sys-svc-mail-msmtp/tasks/enable.yml @@ -22,7 +22,7 @@ - name: "🔴 Disable SMTP to avoid port conflicts" include_tasks: "{{ lookup('path_absolute', 'roles/sys-svc-mail-smtp/tasks/disable.yml') }}" -- when: lookup('email').external | bool +- when: lookup('email', key='external') | bool block: - name: 📦 Install msmtp-mta when Mailu is used and package exists on distro package_install: # nocheck: package-install only inside the Mailu block and only where the distro ships msmtp-mta diff --git a/roles/sys-svc-mail-smtp/tasks/disable.yml b/roles/sys-svc-mail-smtp/tasks/disable.yml index 7a89c2cbbb..bf8c55f120 100644 --- a/roles/sys-svc-mail-smtp/tasks/disable.yml +++ b/roles/sys-svc-mail-smtp/tasks/disable.yml @@ -16,4 +16,4 @@ package_install: # nocheck: package-install removes postfix, the batch only installs id: postfix state: absent - when: lookup('email').external | bool + when: lookup('email', key='external') | bool diff --git a/roles/sys-svc-mail/tasks/00_core.yml b/roles/sys-svc-mail/tasks/00_core.yml index 63dbc0b8fe..5f97f0f77b 100644 --- a/roles/sys-svc-mail/tasks/00_core.yml +++ b/roles/sys-svc-mail/tasks/00_core.yml @@ -27,7 +27,7 @@ name: sys-svc-mail-smtp when: - run_once_sys_svc_mail_smtp is not defined - - not (lookup('email').external | bool) + - not (lookup('email', key='external') | bool) - name: 🔧 Setup msmtp client include_role: diff --git a/tests/unit/python/plugins/lookup/test_email.py b/tests/unit/python/plugins/lookup/test_email.py index 84410ed3c6..754479aaad 100644 --- a/tests/unit/python/plugins/lookup/test_email.py +++ b/tests/unit/python/plugins/lookup/test_email.py @@ -11,7 +11,7 @@ from unittest.mock import patch from ansible.errors import AnsibleError from plugins.lookup.applications import LookupModule as ApplicationsLookup -from plugins.lookup.email import LookupModule +from plugins.lookup.email import RESOLUTION_ORDER, LookupModule from utils.cache import _reset_cache_for_tests from utils.cache import applications as cache_applications from utils.cache import base as cache_base @@ -366,6 +366,77 @@ class TestEmailLookup(unittest.TestCase): result = self.lookup.run([], variables=variables)[0] self.assertEqual(result["domain"], "mail.example.org") + def test_key_returns_the_value_the_full_mapping_carries(self) -> None: + _write_role_config( + self._tmp, + "web-app-mailprov", + { + "mailprov": { + "ports": {"public": {"smtp": 25, "smtps": 465, "submission": 587}} + } + }, + ) + cases = ( + {"inventory_hostname": "host1"}, + {"inventory_hostname": "host1", "TLS_ENABLED": True}, + { + "SYSTEM_EMAIL_HOST": "smtp.example.org", + "SYSTEM_EMAIL_PORT": 465, + "SYSTEM_EMAIL_TLS": True, + "SYSTEM_EMAIL_TIMEOUT": "45", + "inventory_hostname": "host1", + }, + { + "MAIL_PROVIDER": "web-app-mailprov", + "group_names": ["web-app-mailprov"], + "groups": {"web-app-mailprov": ["host1"]}, + "SYSTEM_EMAIL_HOST": "mail.x.onion", + "TLS_ENABLED": True, + "DOMAIN_PRIMARY": "x.onion", + "inventory_hostname": "host1", + }, + ) + roles_dir = str(self._tmp / "roles") + for variables in cases: + full = self.lookup.run([], variables=variables, roles_dir=roles_dir)[0] + for short_key in RESOLUTION_ORDER: + with self.subTest(variables=variables, key=short_key): + value = self.lookup.run( + [], variables=variables, roles_dir=roles_dir, key=short_key + )[0] + self.assertEqual(value, full[short_key]) + + def test_key_applies_the_application_override(self) -> None: + _write_role_config( + self._tmp, + "web-app-x", + {"email": {"HOST": "smtp.app.org", "port": 587}}, + ) + variables = { + "SYSTEM_EMAIL_HOST": "smtp.global.org", + "SYSTEM_EMAIL_PORT": 25, + "inventory_hostname": "host1", + } + roles_dir = str(self._tmp / "roles") + full = self.lookup.run(["web-app-x"], variables=variables, roles_dir=roles_dir)[ + 0 + ] + for short_key in ("host", "port", "external", "from"): + with self.subTest(key=short_key): + value = self.lookup.run( + ["web-app-x"], + variables=variables, + roles_dir=roles_dir, + key=short_key, + )[0] + self.assertEqual(value, full[short_key]) + self.assertEqual(full["host"], "smtp.app.org") + self.assertEqual(full["port"], 587) + + def test_unknown_key_raises(self) -> None: + with self.assertRaises(AnsibleError): + self.lookup.run([], variables={}, key="externl") + class TestProviderOnionIsClusterWide(unittest.TestCase): """In swarm only the manager is in svc-net-tor, so a worker renders the @@ -490,6 +561,28 @@ class TestProviderOnionIsClusterWide(unittest.TestCase): self.assertTrue(result["auth"]) self.assertEqual(result["auth_mechanism"], "plain") + def test_worker_key_lookup_skips_the_provider_onion_probe(self) -> None: + self._seed(ports=self.STALWART_PORTS) + variables = self._worker(network_mode="tor") + roles_dir = str(self._tmp / "roles") + + with patch.object( + LookupModule, "_provider_onion_primary", return_value=True + ) as probe: + external = self.lookup.run( + [], variables=variables, roles_dir=roles_dir, key="external" + )[0] + timeout = self.lookup.run( + [], variables=variables, roles_dir=roles_dir, key="timeout" + )[0] + probe.assert_not_called() + full = self._run(variables) + probe.assert_called() + + self.assertIs(external, True) + self.assertEqual(external, full["external"]) + self.assertEqual(timeout, full["timeout"]) + def test_tor_on_another_host_keeps_tls(self) -> None: self._seed(ports=self.STALWART_PORTS) diff --git a/tests/unit/python/roles/sys-ctl-hlth-msmtp/lookup_plugins/test_mail_recipient.py b/tests/unit/python/roles/sys-ctl-hlth-msmtp/lookup_plugins/test_mail_recipient.py index 1b6a139d34..aeca2fb685 100644 --- a/tests/unit/python/roles/sys-ctl-hlth-msmtp/lookup_plugins/test_mail_recipient.py +++ b/tests/unit/python/roles/sys-ctl-hlth-msmtp/lookup_plugins/test_mail_recipient.py @@ -40,7 +40,7 @@ class MailRecipientLookupTests(unittest.TestCase): return patch.object( self.module.EmailLookup, "run", - return_value=[{"external": external, "timeout": "30"}], + return_value=[external], ) def _stub_users(self, email_value): @@ -55,6 +55,18 @@ class MailRecipientLookupTests(unittest.TestCase): with self._stub_email(True), self._stub_users("admin@example.com"): self.assertEqual(lookup.run([])[0], "admin@example.com") + def test_reads_only_the_external_key_of_the_email_lookup(self): + lookup = self._make_lookup() + with ( + self._stub_email(False) as email_run, + patch.object( + self.module.pwd, "getpwnam", side_effect=KeyError("administrator") + ), + ): + lookup.run([]) + email_run.assert_called_once() + self.assertEqual(email_run.call_args.kwargs.get("key"), "external") + def test_external_string_true_returns_admin_email(self): lookup = self._make_lookup() with self._stub_email("true"), self._stub_users("admin@example.com"):