diff --git a/plugins/lookup/email.py b/plugins/lookup/email.py index 28d2ab90a0..4e2e6fc444 100644 --- a/plugins/lookup/email.py +++ b/plugins/lookup/email.py @@ -1,9 +1,8 @@ # nocheck: comments-valid explanatory WHY-comments in this SPOT lookup predate the stricter lint from __future__ import annotations -from collections.abc import Mapping from pathlib import Path -from typing import Any +from typing import TYPE_CHECKING, Any from ansible.errors import AnsibleError from ansible.plugins.loader import lookup_loader @@ -12,18 +11,16 @@ from ansible.plugins.lookup import LookupBase from plugins.lookup.applications import LookupModule as ApplicationsLookup from plugins.lookup.domain import LookupModule as DomainLookup from plugins.lookup.users import LookupModule as UsersLookup -from utils.cache.carrier import ( - APPLICATIONS_RENDERED_FACT, - PROVIDER_VIEW_RENDERED_FACT, - _carried_applications, - _carried_provider_view, - merged_applications_cache_key, -) +from utils.cache.carrier import APPLICATIONS_RENDERED_FACT from utils.domains.primary_domain import get_domain from utils.mail.provider import deployed_roles, resolve_active_provider +from utils.mail.provider_view import provider_view, view_carrier, view_id from utils.networks.reachability import network, network_of from utils.roles.entity.name import entity_name +if TYPE_CHECKING: + from collections.abc import Mapping + SYSTEM_EMAIL_PREFIX = "SYSTEM_EMAIL_" # Default mail provider role; overridable per inventory via the MAIL_PROVIDER var. @@ -97,21 +94,6 @@ def _render( return value -def _provider_carrier( - variables: Mapping[str, Any], host: str -) -> Mapping[str, Any] | None: - hostvars = variables.get("hostvars") - raw_get = getattr(hostvars, "raw_get", None) - try: - host_vars = raw_get(host) if callable(raw_get) else hostvars[host] - except (KeyError, TypeError): - return None - if not isinstance(host_vars, Mapping): - return None - carrier = host_vars.get(APPLICATIONS_RENDERED_FACT) - return carrier if isinstance(carrier, Mapping) else None - - def active_mail_provider(variables: Mapping[str, Any]) -> str: """The mail provider role this deploy relays through. @@ -127,66 +109,6 @@ def active_mail_provider(variables: Mapping[str, Any]) -> str: ) -def provider_view( - variables: Mapping[str, Any], provider: str -) -> tuple[str, dict[str, Any]] | None: - """This host's variables as the onion-serving provider host sees its groups. - - Args: - variables: Ansible variables of the current host. - provider: the active mail provider role. - - Returns: - ``(provider host, view)``, or ``None`` when no host of *provider* - is in ``svc-net-tor``. - """ - groups = variables.get("groups") or {} - tor_hosts = set(groups.get("svc-net-tor") or []) - provider_hosts = [h for h in groups.get(provider) or [] if h in tor_hosts] - if not provider_hosts: - return None - own_groups = list(variables.get("group_names") or []) - fallback = own_groups + [ - g for g in ("svc-net-tor", provider) if g not in own_groups - ] - try: - provider_vars = variables["hostvars"][provider_hosts[0]] - provider_groups = provider_vars["group_names"] - except (KeyError, TypeError): - provider_vars = {} - provider_groups = fallback - view = dict(variables) - view["group_names"] = list(provider_groups or fallback) - if provider_vars.get("NETWORK_MODE"): - view["NETWORK_MODE"] = provider_vars["NETWORK_MODE"] - return provider_hosts[0], view - - -def _view_id(host: str, view: Mapping[str, Any]) -> list[str]: - return [str(host), str(view.get("NETWORK_MODE") or "")] - - -def _view_carrier( - variables: Mapping[str, Any], - host: str, - view: Mapping[str, Any], - roles_dir: str | None, -) -> Mapping[str, Any] | None: - key = merged_applications_cache_key(view, roles_dir=roles_dir) - if _carried_provider_view(variables, key) is not None and list( - variables[PROVIDER_VIEW_RENDERED_FACT].get("view") or [] - ) == _view_id(host, view): - return variables[PROVIDER_VIEW_RENDERED_FACT] - provider = _provider_carrier(variables, host) - if ( - provider is not None - and _carried_applications({APPLICATIONS_RENDERED_FACT: provider}, key) - is not None - ): - return provider - return None - - def provider_view_carrier( variables: Mapping[str, Any], *, @@ -216,7 +138,7 @@ def provider_view_carrier( if host == variables.get("inventory_hostname"): return None view.pop("application_id", None) - if _view_carrier(variables, host, view, roles_dir) is not None: + if view_carrier(variables, host, view, roles_dir) is not None: return None applications = ApplicationsLookup() applications._templar = templar @@ -228,7 +150,7 @@ def provider_view_carrier( )[0] finally: templar.available_variables = previous - return {**carrier, "view": _view_id(host, view)} + return {**carrier, "view": view_id(host, view)} class LookupModule(LookupBase): @@ -464,7 +386,7 @@ class LookupModule(LookupBase): forwarded = { k: v for k, v in getattr(self, "_kwargs", {}).items() if k == "roles_dir" } - carrier = _view_carrier(variables, host, view, forwarded.get("roles_dir")) + carrier = view_carrier(variables, host, view, forwarded.get("roles_dir")) if carrier is not None: view[APPLICATIONS_RENDERED_FACT] = carrier try: diff --git a/roles/sys-dns-cloudflare-records/defaults/main.yml b/roles/sys-dns-cloudflare-records/defaults/main.yml index 2617d00ba6..4226f6f8ec 100644 --- a/roles/sys-dns-cloudflare-records/defaults/main.yml +++ b/roles/sys-dns-cloudflare-records/defaults/main.yml @@ -7,7 +7,7 @@ cloudflare_request_timeout: 20 # Seconds one Cloudflare HTTP socket operation ma cloudflare_attempt_timeout: 60 # Seconds one record job may run before async_wrapper kills it as hung cloudflare_attempts: 3 # Attempts per record; only hangs, timeouts, connection errors, 429 and 5xx earn another cloudflare_retry_delay: 10 # Seconds between two attempts -cloudflare_collect_retries: "{{ ((cloudflare_attempt_timeout | int) / 5) | round(0, 'ceil') | int + 2 }}" # Cap on 5 s polls per job; the attempt's collect deadline ends them sooner +cloudflare_collect_retries: "{{ ((lookup('timeout', cloudflare_attempt_timeout | int) | int) / 5) | round(0, 'ceil') | int + 2 }}" # Cap on 5 s polls per job; the attempt's collect deadline ends them sooner cloudflare_tolerate: # Substrings of an answer that mean the record already stands as wanted - "An identical record already exists" - "code: 81058" diff --git a/roles/sys-dns-cloudflare-records/tasks/apply.yml b/roles/sys-dns-cloudflare-records/tasks/apply.yml index 2a27374098..4ed994cd8f 100644 --- a/roles/sys-dns-cloudflare-records/tasks/apply.yml +++ b/roles/sys-dns-cloudflare-records/tasks/apply.yml @@ -1,7 +1,7 @@ --- - name: ⏸️ Wait before applying the hung or transiently failed records again ansible.builtin.wait_for: - timeout: "{{ cloudflare_retry_delay | int }}" + timeout: "{{ lookup('timeout', cloudflare_retry_delay | int) | int }}" when: cloudflare_attempt | int > 1 - name: πŸ“Œ Apply A/AAAA @@ -15,12 +15,12 @@ ttl: "{{ item.ttl | default(1) }}" state: "{{ item.state | default('present') }}" solo: "{{ item.solo | default(false) }}" - timeout: "{{ cloudflare_request_timeout | int }}" + timeout: "{{ lookup('timeout', cloudflare_request_timeout | int) | int }}" loop: "{{ _cf_pending | selectattr('type','in',['A','AAAA']) | list }}" loop_control: { label: "{{ item.type }} {{ item.name }} -> {{ item.content }}" } ignore_errors: true # rationale: async; judge.yml reaps and judges every job of this attempt before the next attempt or the rest of the play - async: "{{ cloudflare_attempt_timeout | int }}" + async: "{{ lookup('timeout', cloudflare_attempt_timeout | int) | int }}" poll: "{{ ASYNC_ENABLED | bool | ternary(0, 1) }}" no_log: "{{ cloudflare_no_log | bool }}" register: _cf_a @@ -37,12 +37,12 @@ priority: "{{ (item.type == 'MX') | ternary(item.priority | default(10), omit) }}" state: "{{ item.state | default('present') }}" solo: "{{ item.solo | default(false) }}" - timeout: "{{ cloudflare_request_timeout | int }}" + timeout: "{{ lookup('timeout', cloudflare_request_timeout | int) | int }}" loop: "{{ _cf_pending | selectattr('type','in',['CNAME','MX','TXT']) | list }}" loop_control: { label: "{{ item.type }} {{ item.name }} -> {{ item.value }}" } ignore_errors: true # rationale: async; judge.yml reaps and judges every job of this attempt before the next attempt or the rest of the play - async: "{{ cloudflare_attempt_timeout | int }}" + async: "{{ lookup('timeout', cloudflare_attempt_timeout | int) | int }}" poll: "{{ ASYNC_ENABLED | bool | ternary(0, 1) }}" no_log: "{{ cloudflare_no_log | bool }}" register: _cf_cname @@ -63,17 +63,17 @@ ttl: "{{ item.ttl | default(1) }}" state: "{{ item.state | default('present') }}" solo: "{{ item.solo | default(false) }}" - timeout: "{{ cloudflare_request_timeout | int }}" + timeout: "{{ lookup('timeout', cloudflare_request_timeout | int) | int }}" loop: "{{ _cf_pending | selectattr('type','equalto','SRV') | list }}" loop_control: { label: "SRV {{ item.service }}.{{ item.proto }} {{ item.name }} -> {{ item.value }}:{{ item.port }}" } ignore_errors: true # rationale: async; judge.yml reaps and judges the jobs of every SRV record that opted out of best effort - async: "{{ cloudflare_attempt_timeout | int }}" + async: "{{ lookup('timeout', cloudflare_attempt_timeout | int) | int }}" poll: "{{ ASYNC_ENABLED | bool | ternary(0, 1) }}" no_log: "{{ cloudflare_no_log | bool }}" register: _cf_srv changed_when: false -- name: πŸ•’ Stamp the deadline by which every job of this attempt has finished or been killed +- name: πŸ•’ Stamp the deadline for every job of this attempt ansible.builtin.set_fact: - _cf_collect_deadline: "{{ now(utc=true).timestamp() + (cloudflare_attempt_timeout | int) + 10 }}" + _cf_collect_deadline: "{{ now(utc=true).timestamp() + (lookup('timeout', cloudflare_attempt_timeout | int) | int) + 10 }}" diff --git a/roles/sys-dns-cloudflare-records/tasks/main.yml b/roles/sys-dns-cloudflare-records/tasks/main.yml index adbb622520..be298f65bf 100644 --- a/roles/sys-dns-cloudflare-records/tasks/main.yml +++ b/roles/sys-dns-cloudflare-records/tasks/main.yml @@ -26,6 +26,6 @@ ansible.builtin.fail: msg: >- Cloudflare records: {{ _cf_retry | length }} record(s) still failed after - {{ cloudflare_attempts }} attempt(s) of at most {{ cloudflare_attempt_timeout }} s each: + {{ cloudflare_attempts }} attempt(s) of at most {{ lookup('timeout', cloudflare_attempt_timeout | int) | int }} s each: {% for r in _cf_retry %}{{ r.item.type }} {{ r.item.name }} ({{ r.item.zone }}): {{ r.error }}{{ ' || ' if not loop.last }}{% endfor %} when: _cf_retry | length > 0 diff --git a/tests/unit/python/plugins/filter/test_async_retry_split.py b/tests/unit/python/plugins/filter/test_async_retry_split.py index 5e8803a52a..fb35b025ed 100644 --- a/tests/unit/python/plugins/filter/test_async_retry_split.py +++ b/tests/unit/python/plugins/filter/test_async_retry_split.py @@ -1,18 +1,15 @@ import unittest -from pathlib import Path - -import yaml from plugins.filter.async_failures import async_retry_split +from utils.cache.yaml import load_yaml +from utils.roles.mapping import ROLE_FILE_DEFAULTS_MAIN + +from . import PROJECT_ROOT _DEFAULTS = ( - Path(__file__).resolve().parents[5] - / "roles" - / "sys-dns-cloudflare-records" - / "defaults" - / "main.yml" + PROJECT_ROOT / "roles" / "sys-dns-cloudflare-records" / ROLE_FILE_DEFAULTS_MAIN ) -_ROLE = yaml.safe_load(_DEFAULTS.read_text(encoding="utf-8")) +_ROLE = load_yaml(str(_DEFAULTS)) _TOLERATE = _ROLE["cloudflare_tolerate"] _TRANSIENT = _ROLE["cloudflare_transient"] diff --git a/utils/mail/provider_view.py b/utils/mail/provider_view.py new file mode 100644 index 0000000000..280ccd4c36 --- /dev/null +++ b/utils/mail/provider_view.py @@ -0,0 +1,111 @@ +"""The applications view of the onion-serving mail provider host, and its carriers.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +from utils.cache.carrier import ( + APPLICATIONS_RENDERED_FACT, + PROVIDER_VIEW_RENDERED_FACT, + _carried_applications, + _carried_provider_view, + merged_applications_cache_key, +) + + +def _provider_carrier( + variables: Mapping[str, Any], host: str +) -> Mapping[str, Any] | None: + hostvars = variables.get("hostvars") + raw_get = getattr(hostvars, "raw_get", None) + try: + host_vars = raw_get(host) if callable(raw_get) else hostvars[host] + except (KeyError, TypeError): + return None + if not isinstance(host_vars, Mapping): + return None + carrier = host_vars.get(APPLICATIONS_RENDERED_FACT) + return carrier if isinstance(carrier, Mapping) else None + + +def provider_view( + variables: Mapping[str, Any], provider: str +) -> tuple[str, dict[str, Any]] | None: + """This host's variables as the onion-serving provider host sees its groups. + + Args: + variables: Ansible variables of the current host. + provider: the active mail provider role. + + Returns: + ``(provider host, view)``, or ``None`` when no host of *provider* + is in ``svc-net-tor``. + """ + groups = variables.get("groups") or {} + tor_hosts = set(groups.get("svc-net-tor") or []) + provider_hosts = [h for h in groups.get(provider) or [] if h in tor_hosts] + if not provider_hosts: + return None + own_groups = list(variables.get("group_names") or []) + fallback = own_groups + [ + g for g in ("svc-net-tor", provider) if g not in own_groups + ] + try: + provider_vars = variables["hostvars"][provider_hosts[0]] + provider_groups = provider_vars["group_names"] + except (KeyError, TypeError): + provider_vars = {} + provider_groups = fallback + view = dict(variables) + view["group_names"] = list(provider_groups or fallback) + if provider_vars.get("NETWORK_MODE"): + view["NETWORK_MODE"] = provider_vars["NETWORK_MODE"] + return provider_hosts[0], view + + +def view_id(host: str, view: Mapping[str, Any]) -> list[str]: + """Identify a provider view. + + Args: + host: the provider host the view was built for. + view: the view from `provider_view`. + + Returns: + ``[host, NETWORK_MODE]``. + """ + return [str(host), str(view.get("NETWORK_MODE") or "")] + + +def view_carrier( + variables: Mapping[str, Any], + host: str, + view: Mapping[str, Any], + roles_dir: str | None, +) -> Mapping[str, Any] | None: + """Return a carrier that still matches *view*, or ``None``. + + Args: + variables: Ansible variables of the current host. + host: the provider host *view* was built for. + view: the view from `provider_view`. + roles_dir: roles tree the key is computed over; the repository's when ``None``. + + Returns: + This host's parked provider view when its key and `view_id` match, + else the provider host's own applications carrier when its key + matches, else ``None``. + """ + key = merged_applications_cache_key(view, roles_dir=roles_dir) + if _carried_provider_view(variables, key) is not None and list( + variables[PROVIDER_VIEW_RENDERED_FACT].get("view") or [] + ) == view_id(host, view): + return variables[PROVIDER_VIEW_RENDERED_FACT] + provider = _provider_carrier(variables, host) + if ( + provider is not None + and _carried_applications({APPLICATIONS_RENDERED_FACT: provider}, key) + is not None + ): + return provider + return None