diff --git a/roles/test-e2e-cli/README.md b/roles/test-e2e-cli/README.md index cc32fbc641..2ad160a963 100644 --- a/roles/test-e2e-cli/README.md +++ b/roles/test-e2e-cli/README.md @@ -29,3 +29,7 @@ cli: ``` The script runs with `CLI_DEADLINE` exported, the epoch second the harness kills it. A script that retries budgets against it, so it can still print its own verdict before the harness ends it. + +## How often a test runs + +A role's test runs once per CLI node, not once per play host. Without `container_service_key` every host is its own CLI node. With it, every host resolves the node that holds the service's container, so in swarm all hosts of the role share one node and one run. The stack host (`STACK_HOST`) runs it when it is one of them, else the first of them in play order, and `test.env` renders from that host's variables. Each host claims `@`, so a host that skips a role (a manager-only placement) keeps an older claim that never matches it. A failed run counts as a failure on every host that shares its node. diff --git a/roles/test-e2e-cli/tasks/run_one.yml b/roles/test-e2e-cli/tasks/run_one.yml index b4e336dad2..e7a59b78bc 100644 --- a/roles/test-e2e-cli/tasks/run_one.yml +++ b/roles/test-e2e-cli/tasks/run_one.yml @@ -47,12 +47,29 @@ resolve_converge_delay: 2 when: _cli_service_key | length > 0 +- name: 🧭 Claim this host's CLI node for {{ application_id }} + ansible.builtin.set_fact: + _cli_node_claim: "{{ application_id }}@{{ CLI_HOST_NODE }}" + +- name: 🧭 Pick the one host per CLI node that runs the test of {{ application_id }} + ansible.builtin.set_fact: + _cli_runner: "{{ ((_cli_peers | select('equalto', STACK_HOST) | list) + _cli_peers) | first }}" + vars: + _cli_peers: >- + {{ ansible_play_hosts + | map('extract', hostvars) + | selectattr('_cli_node_claim', 'defined') + | selectattr('_cli_node_claim', 'equalto', _cli_node_claim) + | map(attribute='inventory_hostname') + | list }} + - name: 📁 Create stage directory for {{ application_id }} ansible.builtin.file: path: "{{ _cli_stage_dir }}" state: directory mode: "0700" delegate_to: "{{ CLI_HOST_NODE }}" + when: _cli_runner == inventory_hostname - name: 📦 Stage CLI test assets for {{ application_id }} ansible.builtin.copy: @@ -60,6 +77,7 @@ dest: "{{ _cli_stage_dir }}/" mode: "0755" delegate_to: "{{ CLI_HOST_NODE }}" + when: _cli_runner == inventory_hostname - name: 📦 Stage the shared CLI harness for {{ application_id }} ansible.builtin.copy: @@ -67,6 +85,7 @@ dest: "{{ _cli_stage_dir }}/shared/" mode: "0755" delegate_to: "{{ CLI_HOST_NODE }}" + when: _cli_runner == inventory_hostname - name: 🧭 Reset the per-role deployment-mode override ansible.builtin.include_vars: @@ -104,6 +123,7 @@ mode: "0600" content: "{{ lookup('template', _cli_env_template) }}" delegate_to: "{{ CLI_HOST_NODE }}" + when: _cli_runner == inventory_hostname - name: 🚀 Run CLI test script for {{ application_id }} ansible.builtin.shell: @@ -121,9 +141,10 @@ failed_when: false delegate_to: "{{ CLI_HOST_NODE }}" throttle: 1 + when: _cli_runner == inventory_hostname - name: ❌ Handle the failed CLI test run of {{ application_id }} - when: _cli_run.rc != 0 + when: hostvars[_cli_runner]._cli_run.rc != 0 block: - name: 📄 Print CLI test output on failure for {{ application_id }} ansible.builtin.debug: @@ -133,6 +154,7 @@ stderr: {{ _cli_run.stderr }} changed_when: false + when: _cli_runner == inventory_hostname - name: ❌ Record failure for {{ application_id }} ansible.builtin.set_fact: @@ -143,4 +165,6 @@ path: "{{ _cli_stage_dir }}" state: absent delegate_to: "{{ CLI_HOST_NODE }}" - when: CLI_HOST_NODE != inventory_hostname + when: + - _cli_runner == inventory_hostname + - CLI_HOST_NODE != inventory_hostname diff --git a/tests/integration/roles/test-e2e-cli/test_mcp_env_render.py b/tests/integration/roles/test-e2e-cli/test_mcp_env_render.py index 041dbc343d..ad0469327f 100644 --- a/tests/integration/roles/test-e2e-cli/test_mcp_env_render.py +++ b/tests/integration/roles/test-e2e-cli/test_mcp_env_render.py @@ -118,7 +118,7 @@ def _group_vars_all() -> dict: def _role_scoped_vars(application_id: str) -> dict: - """Mirror the ``include_vars`` chain ``run_one.yml:44-70`` runs before rendering.""" + """Mirror the ``include_vars`` chain ``run_one.yml`` runs before rendering.""" loaded: dict = {} for candidate in ( PROJECT_ROOT / "roles" / application_id / ROLE_FILE_DEFAULTS_MAIN, diff --git a/tests/unit/python/roles/test-e2e-cli/test_run_one_cli_node_once.py b/tests/unit/python/roles/test-e2e-cli/test_run_one_cli_node_once.py new file mode 100644 index 0000000000..ad00115dd2 --- /dev/null +++ b/tests/unit/python/roles/test-e2e-cli/test_run_one_cli_node_once.py @@ -0,0 +1,132 @@ +from __future__ import annotations + +import unittest + +from ansible.plugins.filter.core import FilterModule +from ansible.plugins.test.core import TestModule +from jinja2.nativetypes import NativeEnvironment + +from utils.cache.yaml import load_yaml_any + +from . import PROJECT_ROOT + +RUN_ONE = PROJECT_ROOT / "roles" / "test-e2e-cli" / "tasks" / "run_one.yml" +RUNNER_GUARD = "_cli_runner == inventory_hostname" + + +def _tasks() -> list[dict]: + """Flatten ``run_one.yml`` into its tasks. + + Returns: + Every task, the tasks inside a ``block`` included, in file order. + """ + pending = list(load_yaml_any(str(RUN_ONE))) + flat: list[dict] = [] + while pending: + task = pending.pop(0) + flat.append(task) + pending[:0] = task.get("block", []) + return flat + + +def _task(prefix: str) -> dict: + """Find a task of ``run_one.yml`` by the start of its name. + + Args: + prefix: the start of the task name. + + Returns: + The first task whose name starts with ``prefix``. + """ + for task in _tasks(): + if task.get("name", "").startswith(prefix): + return task + raise LookupError(f"{RUN_ONE}: no task named {prefix}") + + +def _native(expression: str, **variables): + """Render a task value the way Ansible does, keeping its native type. + + Args: + expression: the templated value. + **variables: the variables in scope. + + Returns: + The rendered value. + """ + env = NativeEnvironment() + env.filters.update(FilterModule().filters()) + env.tests.update(TestModule().tests()) + return env.from_string(expression).render(**variables) + + +def _runners(claims: dict[str, str], play_hosts: list[str], stack_host: str): + """Elect the runner every claiming host picks for its CLI node. + + Args: + claims: the ``_cli_node_claim`` of each host that set one. + play_hosts: ``ansible_play_hosts`` in play order. + stack_host: the ``STACK_HOST`` of the play. + + Returns: + The ``_cli_runner`` each claiming host computes, by host. + """ + pick = _task("🧭 Pick") + hostvars = {host: {"inventory_hostname": host} for host in play_hosts} + for host, claim in claims.items(): + hostvars[host]["_cli_node_claim"] = claim + runners = {} + for host, claim in claims.items(): + peers = _native( + pick["vars"]["_cli_peers"], + ansible_play_hosts=play_hosts, + hostvars=hostvars, + _cli_node_claim=claim, + ) + runners[host] = _native( + pick["ansible.builtin.set_fact"]["_cli_runner"], + _cli_peers=peers, + STACK_HOST=stack_host, + ) + return runners + + +class TestRunOneCliNodeOnce(unittest.TestCase): + def test_hosts_sharing_a_cli_node_elect_the_stack_host_once(self) -> None: + shared = dict.fromkeys(("wrk-01", "wrk-02", "mgr-01"), "app@wrk-02") + runners = _runners(shared, ["wrk-01", "wrk-02", "mgr-01"], "mgr-01") + self.assertEqual(set(runners.values()), {"mgr-01"}) + + def test_hosts_on_distinct_cli_nodes_each_run_their_own(self) -> None: + hosts = ["mgr-01", "wrk-01", "wrk-02"] + runners = _runners({host: f"app@{host}" for host in hosts}, hosts, "mgr-01") + self.assertEqual(runners, {host: host for host in hosts}) + + def test_a_host_outside_the_role_is_never_elected(self) -> None: + shared = {"wrk-01": "app@wrk-02", "wrk-02": "app@wrk-02"} + for claims in (shared, {**shared, "mgr-01": "earlier@wrk-02"}): + with self.subTest(claims=claims): + runners = _runners(claims, ["mgr-01", "wrk-01", "wrk-02"], "mgr-01") + self.assertEqual(runners["wrk-01"], "wrk-01") + self.assertEqual(runners["wrk-02"], "wrk-01") + + def test_every_task_on_the_cli_node_runs_on_the_runner_only(self) -> None: + delegated = [ + task + for task in _tasks() + if task.get("delegate_to") == "{{ CLI_HOST_NODE }}" + ] + self.assertGreaterEqual(len(delegated), 6) + for task in delegated: + with self.subTest(task=task["name"]): + self.assertIn(RUNNER_GUARD, str(task.get("when", ""))) + + def test_every_peer_records_the_failure_of_the_run_it_shares(self) -> None: + handler = _task("❌ Handle the failed CLI test run") + self.assertIn("hostvars[_cli_runner]._cli_run.rc", handler["when"]) + record = _task("❌ Record failure") + self.assertNotIn(RUNNER_GUARD, str(record.get("when", ""))) + + +if __name__ == "__main__": + unittest.main()