diff --git a/changelog.d/579-kibana-version-change.md b/changelog.d/579-kibana-version-change.md new file mode 100644 index 00000000..f331375f --- /dev/null +++ b/changelog.d/579-kibana-version-change.md @@ -0,0 +1,3 @@ +### Added + +- Kibana follows a change of its cluster's version (S-024-9): changing the Elasticsearch service's `version` to a later patch or minor moves Kibana in the same converge, after every node. Before Kibana's held package changes, the `cloudfall_kibana` role reads every node's version (`GET /_nodes`, `no_log`) and, while one is older than the declared version, leaves Kibana as it is and stops the converge, which answers `PRECONDITION` with the code `service_kibana_node_older` and the nodes still behind. Kibana then restarts on the new version and the converge waits until it reports itself available, its saved objects migrated. A converge that finds Kibana at the declared version reads nothing more; a newer Kibana, or one of another major, is still refused before anything changes (#579) diff --git a/engine/ansible/playbooks/services.yml b/engine/ansible/playbooks/services.yml index 5f01cbc9..a5909484 100644 --- a/engine/ansible/playbooks/services.yml +++ b/engine/ansible/playbooks/services.yml @@ -394,6 +394,12 @@ (cloudfall_services_elasticsearch_files | default({})) [cloudfall_service_item.kibana.elasticsearch] | default({}) }} + # Where a converge refused while a node of the cluster is older + # than the declared version is reported, the directory the + # MariaDB role reports to: the services converge answers it with + # PRECONDITION (S-024-9). + cloudfall_kibana_report_directory: >- + {{ cloudfall_services_mariadb_report_directory | default('') }} loop: "{{ cloudfall_kibana_here }}" loop_control: loop_var: cloudfall_service_item diff --git a/engine/ansible/roles/cloudfall_kibana/defaults/main.yml b/engine/ansible/roles/cloudfall_kibana/defaults/main.yml index f3abc757..9f50b001 100644 --- a/engine/ansible/roles/cloudfall_kibana/defaults/main.yml +++ b/engine/ansible/roles/cloudfall_kibana/defaults/main.yml @@ -89,3 +89,33 @@ cloudfall_kibana_elasticsearch_url: >- # How long Kibana may take to report itself available (10 s apart): a first # start, or a new version, migrates its saved objects first. cloudfall_kibana_available_retries: 60 +# The Kibana dpkg has installed, read by "Read the installed Kibana version"; +# '' when none is. +cloudfall_kibana_installed_version: >- + {{ + cloudfall_kibana_installed.stdout.split(' ', 1) | last + if cloudfall_kibana_installed.rc == 0 + and cloudfall_kibana_installed.stdout is match('installed ') + else '' + }} +# Where a converge refused while a node of the cluster is older than the +# declared version is reported, the directory the MariaDB and RabbitMQ roles +# report to: the services converge answers it with PRECONDITION (S-024-9). +cloudfall_kibana_report_directory: "" +cloudfall_kibana_node_older_code: service_kibana_node_older +# "name version" of each node GET /_nodes answered older than the declared +# version, read before Kibana's package changes. +cloudfall_kibana_older: >- + {{ + cloudfall_kibana_nodes.json + | cloudfall_kibana_older_nodes( + cloudfall_kibana_elasticsearch_service.elasticsearch.version) + }} +cloudfall_kibana_node_older_message: >- + Kibana service {{ cloudfall_kibana_service.id }} on {{ cloudfall_server_id }} + is left at {{ cloudfall_kibana_installed_version or 'no version' }}: these + nodes of Elasticsearch service {{ cloudfall_kibana_elasticsearch_service.id }} + run older than the declared + {{ cloudfall_kibana_elasticsearch_service.elasticsearch.version }}: + {{ cloudfall_kibana_older | join(', ') }}. Kibana never runs ahead of a + node; converge every node to that version, then run the command again diff --git a/engine/ansible/roles/cloudfall_kibana/filter_plugins/kibana_nodes.py b/engine/ansible/roles/cloudfall_kibana/filter_plugins/kibana_nodes.py new file mode 100644 index 00000000..a8fe9229 --- /dev/null +++ b/engine/ansible/roles/cloudfall_kibana/filter_plugins/kibana_nodes.py @@ -0,0 +1,60 @@ +"""Read the nodes of Kibana's cluster before its package changes (S-024-9). + +Elastic supports no Kibana newer than a node of its cluster, so the role +reads every node's version (``GET /_nodes``) and keeps Kibana as it is while +one is older than the declared version. Ansible loads this file itself; it +imports nothing from the SDK. +""" + +from __future__ import annotations + +import re +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from collections.abc import Callable + +_VERSION = re.compile(r"^(\d+)\.(\d+)\.(\d+)$") + + +def _parsed(version: object) -> tuple[int, int, int]: + """Return a node or service version as three numbers; refuse anything else.""" + found = _VERSION.match(version) if isinstance(version, str) else None + if found is None: + message = f"{version!r} is not a version of the form 9.2.4" + raise ValueError(message) + major, minor, patch = (int(part) for part in found.groups()) + return major, minor, patch + + +def older_nodes(answer: object, version: str) -> list[str]: + """Return ``name version`` of each node older than ``version``, by name. + + ``answer`` is the JSON of ``GET /_nodes?filter_path=nodes.*.name, + nodes.*.version``: ``{"nodes": {"": {"name": ..., "version": ...}}}``. + An answer without a node, or a node without a name or version, is + refused: the role never decides on a cluster it could not read. + """ + wanted = _parsed(version) + nodes = answer.get("nodes") if isinstance(answer, dict) else None + if not isinstance(nodes, dict) or not nodes: + message = "the cluster answered GET /_nodes with no node" + raise ValueError(message) + found: list[str] = [] + for node in nodes.values(): + name = node.get("name") if isinstance(node, dict) else None + if not isinstance(name, str) or not name: + message = "the cluster answered GET /_nodes with a node without a name" + raise ValueError(message) + running = node.get("version") + if _parsed(running) < wanted: + found.append(f"{name} {running}") + return sorted(found) + + +class FilterModule: + """The role's filters.""" + + def filters(self) -> dict[str, Callable[..., object]]: + """Name the filters for Ansible.""" + return {"cloudfall_kibana_older_nodes": older_nodes} diff --git a/engine/ansible/roles/cloudfall_kibana/meta/argument_specs.yml b/engine/ansible/roles/cloudfall_kibana/meta/argument_specs.yml index b140cc73..48441cf6 100644 --- a/engine/ansible/roles/cloudfall_kibana/meta/argument_specs.yml +++ b/engine/ansible/roles/cloudfall_kibana/meta/argument_specs.yml @@ -70,3 +70,9 @@ argument_specs: description: >- Controller paths of the Elasticsearch service's staged account files; the role reads 'cloudfallPassword' + cloudfall_kibana_report_directory: + type: str + description: >- + Controller directory where a converge refused while a node of the + cluster is older than the declared version is reported, for the + services converge to answer PRECONDITION; empty reports nothing diff --git a/engine/ansible/roles/cloudfall_kibana/tasks/main.yml b/engine/ansible/roles/cloudfall_kibana/tasks/main.yml index 3fd3058c..23dbca89 100644 --- a/engine/ansible/roles/cloudfall_kibana/tasks/main.yml +++ b/engine/ansible/roles/cloudfall_kibana/tasks/main.yml @@ -104,30 +104,27 @@ # A read: a dry run (--check) must refuse a drifted host too check_mode: false -# Kibana runs at the version of its cluster. Moving it after the nodes when -# the service's version changes comes with a later release (#579), so a -# Kibana of another version is refused before anything changes. -- name: Refuse a Kibana of another version than the Elasticsearch service's +# Kibana runs at the version of its cluster and follows a change of it +# (S-024-9) as the node does (S-012): to a later patch or minor of the same +# major. APT does not downgrade it, and a new major needs Elastic's upgrade +# checks, so both are refused before anything changes. +- name: Refuse a Kibana version the converge can't move to the service's ansible.builtin.assert: that: - >- cloudfall_kibana_installed_version == '' - or cloudfall_kibana_installed_version - == cloudfall_kibana_elasticsearch_service.elasticsearch.version + or ( + cloudfall_kibana_installed_version.split('.')[0] + == cloudfall_kibana_elasticsearch_service.elasticsearch.version.split('.')[0] + and cloudfall_kibana_installed_version + is version(cloudfall_kibana_elasticsearch_service.elasticsearch.version, '<=') + ) fail_msg: >- kibana {{ cloudfall_kibana_installed_version }} is installed on {{ cloudfall_server_id }}; Elasticsearch service {{ cloudfall_kibana_elasticsearch_service.id }} declares - {{ cloudfall_kibana_elasticsearch_service.elasticsearch.version }}, and - this release does not move Kibana to another version - vars: - cloudfall_kibana_installed_version: >- - {{ - cloudfall_kibana_installed.stdout.split(' ', 1) | last - if cloudfall_kibana_installed.rc == 0 - and cloudfall_kibana_installed.stdout is match('installed ') - else '' - }} + {{ cloudfall_kibana_elasticsearch_service.elasticsearch.version }}, another + major or older, which this converge does not install # Kibana comes from the repository of the service's major, which the # Elasticsearch role configured on this node earlier in the run. @@ -146,7 +143,22 @@ {{ cloudfall_kibana_service.kibana.elasticsearch }} first, which configures it -# Every refusal above only reads; the host changes from here on. +# Whenever the package would change (a first install, or a new declared +# version), every node of the cluster is read first, and Kibana stays as it is +# while one is older (S-024-9). A converge that finds Kibana at the declared +# version reads nothing more. A dry run converges no node, so it reads none. +- name: Stop before Kibana's package changes while a node of its cluster is older + ansible.builtin.include_tasks: version.yml + when: + - not ansible_check_mode + - >- + cloudfall_kibana_installed_version + != cloudfall_kibana_elasticsearch_service.elasticsearch.version + +# Every refusal above only reads; the host changes from here on. The package +# is held, so the pinned install moves it to a new declared version, and the +# restart it notifies starts the new version, which migrates the saved objects +# before Kibana reports itself available below. - name: Install the Elasticsearch service's version of Kibana ansible.builtin.apt: name: "kibana={{ cloudfall_kibana_elasticsearch_service.elasticsearch.version }}" diff --git a/engine/ansible/roles/cloudfall_kibana/tasks/version.yml b/engine/ansible/roles/cloudfall_kibana/tasks/version.yml new file mode 100644 index 00000000..827bd448 --- /dev/null +++ b/engine/ansible/roles/cloudfall_kibana/tasks/version.yml @@ -0,0 +1,51 @@ +--- +# Kibana moves to the Elasticsearch service's version after every node of its +# cluster (S-024-9): Elastic supports no Kibana newer than a node. services.yml +# runs Kibana after the nodes this run converges; a node the run did not +# converge (another server's --limit, a node left behind) is still read here, +# from the cluster itself, before the package changes. While one is older +# than the declared version, Kibana is left as it is and the services converge +# answers PRECONDITION. Only reads come before the stop. +- name: Read the version of every node of the cluster + ansible.builtin.uri: + url: >- + {{ cloudfall_kibana_elasticsearch_url + }}/_nodes?filter_path=nodes.*.name,nodes.*.version + ca_path: >- + {{ + cloudfall_kibana_elasticsearch_ca_path + if cloudfall_kibana_elasticsearch_service.elasticsearch.remoteAccess is defined + else omit + }} + url_username: cloudfall + url_password: >- + {{ lookup('ansible.builtin.file', + cloudfall_kibana_elasticsearch_files.cloudfallPassword) }} + force_basic_auth: true + status_code: 200 + register: cloudfall_kibana_nodes + no_log: true + +- name: Report the converge refused while a node is older than the service's version + ansible.builtin.copy: + content: >- + {{ {'service': cloudfall_kibana_service.id, + 'server': cloudfall_server_id, + 'outcome': 'refused', + 'code': cloudfall_kibana_node_older_code, + 'message': cloudfall_kibana_node_older_message} | to_json }} + dest: >- + {{ cloudfall_kibana_report_directory }}/{{ cloudfall_kibana_service.id }}.json + mode: "0600" + delegate_to: localhost + become: false + when: + - cloudfall_kibana_older | length > 0 + - cloudfall_kibana_report_directory | length > 0 + +- name: Stop before Kibana's package changes while a node is older than the service's version + ansible.builtin.fail: + msg: >- + PRECONDITION {{ cloudfall_kibana_node_older_code }}: + {{ cloudfall_kibana_node_older_message }} + when: cloudfall_kibana_older | length > 0 diff --git a/engine/tests/test_s024_9_kibana_version_change.py b/engine/tests/test_s024_9_kibana_version_change.py new file mode 100644 index 00000000..7fb6fb9b --- /dev/null +++ b/engine/tests/test_s024_9_kibana_version_change.py @@ -0,0 +1,464 @@ +"""Kibana follows a change of its cluster's version, after every node (S-024-9, #579). + +The Kibana role's ``version.yml`` runs for real with ansible-playbook on +localhost against a stand-in node that answers ``GET /_nodes`` for a cluster of +two; the order of the role's tasks and of ``services.yml``'s plays is read from +the files, and the role's conditions are evaluated with Ansible's own +templating. Upgrading the package on a Debian 13 host, Kibana's saved-object +migration and the dashboard opening afterwards need a live host and are listed +in the pull request as unverified. +""" + +from __future__ import annotations + +import base64 +import importlib.util +import json +import os +import re +import shutil +import subprocess +import sys +import threading +from dataclasses import dataclass, field +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from typing import TYPE_CHECKING, Any, cast + +import pytest +import yaml +from ansible.parsing.dataloader import DataLoader +from ansible.template import Templar, trust_as_template + +if TYPE_CHECKING: + from collections.abc import Iterator + from types import ModuleType + +ROOT = Path(__file__).parents[2] +ROLES = ROOT / "engine" / "ansible" / "roles" +ROLE = ROLES / "cloudfall_kibana" +SERVICES = ROOT / "engine" / "ansible" / "playbooks" / "services.yml" +CLOUDFALL_PASSWORD = "synthetic-cloudfall-value" # noqa: S105 - grepped for +RECAP = re.compile(r"localhost\s+:\s+ok=\d+\s+changed=(\d+)") +DECLARED = "9.2.5" +CHECK = "Stop before Kibana's package changes while a node of its cluster is older" +INSTALL = "Install the Elasticsearch service's version of Kibana" + + +def _filters() -> ModuleType: + path = ROLE / "filter_plugins" / "kibana_nodes.py" + spec = importlib.util.spec_from_file_location("kibana_nodes", path) + assert spec is not None + assert spec.loader is not None + module = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return module + + +FILTERS = _filters() + + +def _answer(**versions: str) -> dict[str, object]: + """Return GET /_nodes as a cluster answers it, filtered to name and version.""" + return { + "nodes": { + f"id-{name}": {"name": name, "version": version} + for name, version in versions.items() + } + } + + +def _search_main(port: int = 9200, version: str = DECLARED) -> dict[str, object]: + return { + "id": "search-main", + "serviceKind": "elasticsearch", + "environment": "production", + "server": "h1", + "bind": {"address": "127.0.0.1", "port": port}, + "elasticsearch": { + "version": version, + "heapMb": 2048, + "nodes": ["h1", "h2"], + "clusterName": "search-main", + "users": [], + }, + "backup": { + "directory": "/var/backups/cloudfall/search-main", + "onCalendar": "*-*-* 03:20:00 UTC", + "retentionDays": 14, + }, + } + + +def _kibana() -> dict[str, object]: + return { + "id": "search-kibana", + "serviceKind": "kibana", + "environment": "production", + "server": "h1", + "bind": {"address": "127.0.0.1", "port": 5601}, + "kibana": {"elasticsearch": "search-main", "heapMb": 1024, "users": []}, + } + + +def _tasks(name: str) -> list[dict[str, Any]]: + tasks = DataLoader().load_from_file(str(ROLE / "tasks" / name)) + assert isinstance(tasks, list) + return cast("list[dict[str, Any]]", tasks) + + +def _task(name: str, tasks: list[dict[str, Any]]) -> dict[str, Any]: + return next(task for task in tasks if task["name"] == name) + + +def _defaults() -> dict[str, object]: + defaults = yaml.safe_load((ROLE / "defaults" / "main.yml").read_text("utf-8")) + assert isinstance(defaults, dict) + return cast("dict[str, object]", defaults) + + +def _conditions(task: dict[str, Any], **variables: object) -> bool: + """Evaluate a task's ``when`` with the role's defaults, as Ansible does.""" + defaults = { + key: trust_as_template(value) if isinstance(value, str) else value + for key, value in _defaults().items() + } + templar = Templar(loader=DataLoader(), variables={**defaults, **variables}) + return all( + templar.evaluate_conditional(trust_as_template(str(condition))) + for condition in task["when"] + ) + + +# proves: S-024-9 +@pytest.mark.parametrize( + ("versions", "older"), + [ + pytest.param({"h1": "9.2.5", "h2": "9.2.5"}, [], id="every node moved"), + pytest.param({"h1": "9.2.5", "h2": "9.2.4"}, ["h2 9.2.4"], id="one old"), + pytest.param( + {"h1": "9.2.4", "h2": "9.1.9"}, ["h1 9.2.4", "h2 9.1.9"], id="both old" + ), + # A node ahead of the declared version does not hold Kibana back + pytest.param({"h1": "9.2.10", "h2": "9.3.0"}, [], id="newer"), + ], +) +def test_s024_9_the_nodes_older_than_the_declared_version_are_named( + versions: dict[str, str], older: list[str] +) -> None: + assert FILTERS.older_nodes(_answer(**versions), DECLARED) == older + + +@pytest.mark.parametrize( + "answer", + [ + pytest.param({"nodes": {}}, id="no node"), + pytest.param({}, id="no nodes key"), + pytest.param(_answer(h1="9.2"), id="short version"), + pytest.param(_answer(h1="9.2.5-SNAPSHOT"), id="suffixed version"), + pytest.param({"nodes": {"a": {"version": "9.2.5"}}}, id="no name"), + pytest.param({"nodes": {"a": {"name": "h1"}}}, id="no version"), + ], +) +def test_a_cluster_answer_the_role_cannot_read_is_refused(answer: object) -> None: + with pytest.raises(ValueError, match=r"GET /_nodes|not a version"): + FILTERS.older_nodes(answer, DECLARED) + + +# proves: S-024-9 +def test_s024_9_every_node_is_read_before_the_package_changes() -> None: + main = _tasks("main.yml") + names = [task["name"] for task in main] + check = _task(CHECK, main) + + assert check["ansible.builtin.include_tasks"] == "version.yml" + assert names.index(CHECK) < names.index(INSTALL) + # Every task before the check only reads or refuses + assert names.index(CHECK) + 1 == names.index(INSTALL) + cluster = _search_main() + + def reads(installed: dict[str, object], *, check_mode: bool = False) -> bool: + return _conditions( + check, + ansible_check_mode=check_mode, + cloudfall_kibana_installed=installed, + cloudfall_kibana_elasticsearch_service=cluster, + ) + + # A new declared version, and a first install, read the nodes first + assert reads({"rc": 0, "stdout": "installed 9.2.4"}) + assert reads({"rc": 1, "stdout": ""}) + # Kibana at the declared version: nothing more is read (S-024-4) + assert not reads({"rc": 0, "stdout": f"installed {DECLARED}"}) + # A dry run converges no node, so it reads none + assert not reads({"rc": 0, "stdout": "installed 9.2.4"}, check_mode=True) + + +# proves: S-024-9 +def test_s024_9_the_held_package_moves_and_kibana_waits_for_its_migration() -> None: + main = _tasks("main.yml") + names = [task["name"] for task in main] + install = _task(INSTALL, main)["ansible.builtin.apt"] + + # Held at the old version, the pinned install still moves it, and the + # hold comes back at the new one + assert install["allow_change_held_packages"] is True + assert _task(INSTALL, main)["notify"] == "Restart Kibana" + hold = _task("Hold the Kibana package at the service's version", main) + assert hold["ansible.builtin.dpkg_selections"]["selection"] == "hold" + # The restart is flushed before the wait, and the version is checked + # once Kibana, its saved objects migrated, reports itself available + order = [ + INSTALL, + "Hold the Kibana package at the service's version", + "Apply the managed Kibana configuration", + "Wait until Kibana reports itself available", + "Refuse a Kibana that reports another version than the service's", + ] + assert [names.index(name) for name in order] == sorted( + names.index(name) for name in order + ) + + +# proves: S-024-9 +def test_s024_9_kibana_converges_after_every_node_and_reports_its_refusal() -> None: + nodes, kibana = yaml.safe_load(SERVICES.read_text(encoding="utf-8")) + + # The nodes' play, every server's, comes first; Kibana's play after it + assert any( + task.get("ansible.builtin.include_role", {}).get("name") + == "cloudfall_elasticsearch" + for task in nodes["tasks"] + ) + (block,) = kibana["tasks"] + _, deploy = block["block"] + assert deploy["ansible.builtin.include_role"]["name"] == "cloudfall_kibana" + # The refusal reaches the directory the services converge reads + report = deploy["vars"]["cloudfall_kibana_report_directory"] + templar = Templar( + loader=DataLoader(), + variables={"cloudfall_services_mariadb_report_directory": "/tmp/reports"}, # noqa: S108 + ) + assert templar.template(trust_as_template(report)) == "/tmp/reports" # noqa: S108 + assert ( + Templar(loader=DataLoader(), variables={}).template(trust_as_template(report)) + == "" + ) + + +def test_a_newer_or_another_major_kibana_is_refused_before_anything_changes() -> None: + refuse = _task( + "Refuse a Kibana version the converge can't move to the service's", + _tasks("main.yml"), + ) + + def holds(installed: str) -> bool: + defaults = { + key: trust_as_template(value) if isinstance(value, str) else value + for key, value in _defaults().items() + } + templar = Templar( + loader=DataLoader(), + variables={ + **defaults, + "cloudfall_kibana_installed": { + "rc": 0, + "stdout": f"installed {installed}", + }, + "cloudfall_kibana_elasticsearch_service": _search_main(), + }, + ) + return all( + templar.evaluate_conditional(trust_as_template(str(condition))) + for condition in refuse["ansible.builtin.assert"]["that"] + ) + + assert holds("9.2.4") + assert holds("9.1.0") + assert holds(DECLARED) + assert not holds("9.2.6") + assert not holds("8.19.4") + + +@dataclass +class FakeCluster: + """A node that answers GET /_nodes for its cluster, and records each request.""" + + versions: dict[str, str] + port: int = 0 + requests: list[tuple[str, str]] = field(default_factory=list) + + +def _handler(cluster: FakeCluster) -> type[BaseHTTPRequestHandler]: + expected = "Basic " + base64.b64encode( + f"cloudfall:{CLOUDFALL_PASSWORD}".encode() + ).decode("ascii") + + class Handler(BaseHTTPRequestHandler): + def do_GET(self) -> None: + cluster.requests.append(("GET", self.path)) + if self.headers.get("Authorization") != expected: + self._send(401, {"error": "unauthenticated"}) + return + if self.path != "/_nodes?filter_path=nodes.*.name,nodes.*.version": + self._send(404, {"error": self.path}) + return + self._send(200, _answer(**cluster.versions)) + + def _send(self, status: int, answer: object) -> None: + content = json.dumps(answer).encode() + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(content))) + self.end_headers() + self.wfile.write(content) + + def log_message(self, format: str, *args: object) -> None: # noqa: A002 + del format, args + + return Handler + + +@pytest.fixture +def cluster() -> Iterator[FakeCluster]: + """Serve a stand-in node of a cluster of two.""" + fake = FakeCluster(versions={"h1": DECLARED, "h2": DECLARED}) + server = ThreadingHTTPServer(("127.0.0.1", 0), _handler(fake)) + fake.port = server.server_address[1] + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + yield fake + finally: + server.shutdown() + server.server_close() + + +@dataclass(frozen=True) +class Converged: + """How one run of the version check ended.""" + + returncode: int + output: str + + @property + def changed(self) -> int: + """Return the play recap's changed count.""" + found = RECAP.search(self.output) + assert found is not None, self.output + return int(found.group(1)) + + +def _check(tmp_path: Path, cluster: FakeCluster, reports: Path) -> Converged: + """Run the role's version check as the Kibana play does, Kibana at 9.2.4.""" + password = tmp_path / "cloudfall.password" + password.write_text(CLOUDFALL_PASSWORD, encoding="utf-8") + play = [ + { + "name": "Read the nodes before Kibana's package changes", + "hosts": "localhost", + "connection": "local", + "gather_facts": False, + "vars": { + "cloudfall_server_id": "h1", + "ansible_python_interpreter": sys.executable, + }, + "tasks": [ + { + "name": "Run the version check of the Kibana role", + "ansible.builtin.include_role": { + "name": "cloudfall_kibana", + "tasks_from": "version", + }, + "vars": { + "cloudfall_kibana_service": _kibana(), + "cloudfall_kibana_elasticsearch_service": _search_main( + cluster.port + ), + "cloudfall_kibana_elasticsearch_files": { + "cloudfallPassword": str(password) + }, + "cloudfall_kibana_installed": { + "rc": 0, + "stdout": "installed 9.2.4", + }, + "cloudfall_kibana_report_directory": str(reports), + }, + }, + ], + } + ] + playbook = tmp_path / "version.yml" + playbook.write_text(yaml.safe_dump(play), encoding="utf-8") + binary = shutil.which("ansible-playbook") + assert binary is not None + done = subprocess.run( # noqa: S603 - fixed binary and arguments. + [binary, "--inventory", "localhost,", "-vvv", "--diff", str(playbook)], + check=False, + capture_output=True, + text=True, + timeout=300, + env={**os.environ, "ANSIBLE_ROLES_PATH": str(ROLES)}, + ) + return Converged(done.returncode, done.stdout + done.stderr) + + +requires_ansible = pytest.mark.skipif( + shutil.which("ansible-playbook") is None, reason="ansible-playbook is not on PATH" +) + + +# proves: S-024-9 +@requires_ansible +def test_s024_9_a_node_still_on_the_old_version_stops_with_precondition( + tmp_path: Path, cluster: FakeCluster +) -> None: + cluster.versions["h2"] = "9.2.4" + reports = tmp_path / "reports" + reports.mkdir() + + done = _check(tmp_path, cluster, reports) + + assert done.returncode != 0, done.output + assert "PRECONDITION service_kibana_node_older" in done.output + report = json.loads((reports / "search-kibana.json").read_text(encoding="utf-8")) + assert report["outcome"] == "refused" + assert report["code"] == "service_kibana_node_older" + assert (report["service"], report["server"]) == ("search-kibana", "h1") + assert "h2 9.2.4" in report["message"] + assert "left at 9.2.4" in report["message"] + assert report["message"].endswith( + "9.2.5: h2 9.2.4. Kibana never runs ahead of a node; converge every node " + "to that version, then run the command again" + ) + # The cluster was only read, once, as the cloudfall account + assert cluster.requests == [ + ("GET", "/_nodes?filter_path=nodes.*.name,nodes.*.version") + ] + assert CLOUDFALL_PASSWORD not in done.output + + +# proves: S-024-9 +@requires_ansible +def test_s024_9_every_node_on_the_new_version_lets_kibana_move( + tmp_path: Path, cluster: FakeCluster +) -> None: + reports = tmp_path / "reports" + reports.mkdir() + + done = _check(tmp_path, cluster, reports) + + assert done.returncode == 0, done.output + # Only a read: the check itself changes nothing + assert done.changed == 0 + assert list(reports.iterdir()) == [] + assert CLOUDFALL_PASSWORD not in done.output + + +# proves: S-024-5 +def test_s024_5_the_node_read_is_no_log() -> None: + (read,) = (task for task in _tasks("version.yml") if "ansible.builtin.uri" in task) + + assert read["no_log"] is True + assert read["ansible.builtin.uri"].get("method", "GET") == "GET" diff --git a/engine/tests/test_s024_kibana_role.py b/engine/tests/test_s024_kibana_role.py index f052d9ef..d04b4653 100644 --- a/engine/tests/test_s024_kibana_role.py +++ b/engine/tests/test_s024_kibana_role.py @@ -60,9 +60,10 @@ "Refuse a Domain this server does not hold for Kibana", "Require the staged encryption keys and the cloudfall password", "Read the installed Kibana version", - "Refuse a Kibana of another version than the Elasticsearch service's", + "Refuse a Kibana version the converge can't move to the service's", "Read the Elastic repository of the node", "Require the Elastic repository of the node", + "Stop before Kibana's package changes while a node of its cluster is older", ) @@ -232,15 +233,16 @@ def test_s024_3_kibana_is_the_clusters_version_and_held() -> None: "/etc/apt/sources.list.d/elasticsearch.sources" ) refuse = _task( - "Refuse a Kibana of another version than the Elasticsearch service's", main + "Refuse a Kibana version the converge can't move to the service's", main ) installed = {"rc": 0, "stdout": "installed 9.2.4"} assert _holds(refuse, _variables(cloudfall_kibana_installed=installed)) assert _holds( refuse, _variables(cloudfall_kibana_installed={"rc": 1, "stdout": ""}) ) - older = {"rc": 0, "stdout": "installed 9.2.3"} - assert not _holds(refuse, _variables(cloudfall_kibana_installed=older)) + # A newer Kibana is never moved back (S-024-9 moves an older one forward) + newer = {"rc": 0, "stdout": "installed 9.2.5"} + assert not _holds(refuse, _variables(cloudfall_kibana_installed=newer)) # proves: S-024-3 diff --git a/sdk/src/cloudfall/lifecycle.py b/sdk/src/cloudfall/lifecycle.py index 109161cf..a6620cea 100644 --- a/sdk/src/cloudfall/lifecycle.py +++ b/sdk/src/cloudfall/lifecycle.py @@ -1279,7 +1279,9 @@ def run_services_playbook( replica that can't attach or diverged) stops the run as that refusal, which the command answers with ``PRECONDITION``, rather than as a failed playbook. The RabbitMQ role reports the same way a converge it refused - while its cluster has no majority (S-023). The outcomes are returned. + while its cluster has no majority (S-023), and the Kibana role one it + refused while a node of its cluster is older than the declared version + (S-024-9). The outcomes are returned. """ state = validate_config(context.project_directory, context.schema_directory) inventory = PlatformInventory.from_state(state) @@ -1312,11 +1314,14 @@ def run(name: str, extra_vars: Mapping[str, object]) -> None: tempfile.TemporaryDirectory(prefix="cloudfall-replication-") as reports, ): extra_vars: dict[str, object] = {**extra, **provided} - # A project without MariaDB or a RabbitMQ cluster runs as it did; the - # RabbitMQ role reports there a converge it refused while its cluster - # has no majority (S-023) + # A project without MariaDB, a RabbitMQ cluster or Kibana runs as it + # did; the RabbitMQ role reports there a converge it refused while its + # cluster has no majority (S-023), the Kibana role one it refused while + # a node of its cluster is older than the declared version (S-024-9) if any( - service.mariadb is not None or is_rabbitmq_cluster(service) + service.mariadb is not None + or is_rabbitmq_cluster(service) + or service.kibana is not None for service in inventory.services ): extra_vars[REPORT_DIRECTORY_VARIABLE] = reports diff --git a/sdk/tests/test_s024_9_kibana_version_precondition.py b/sdk/tests/test_s024_9_kibana_version_precondition.py new file mode 100644 index 00000000..8d80de74 --- /dev/null +++ b/sdk/tests/test_s024_9_kibana_version_precondition.py @@ -0,0 +1,137 @@ +"""The services converge answers a Kibana held back by an older node (S-024-9, #579). + +``services.yml`` needs Debian 13 hosts, so the converge runs with a recording +step runner that reports, as the Kibana role does, the refusal of a cluster +whose node is older than the declared version. The role's own check is tested +in ``engine/tests/test_s024_9_kibana_version_change.py``. +""" + +from __future__ import annotations + +import json +from dataclasses import dataclass, field +from pathlib import Path + +import pytest +from cloudfall.lifecycle import ( + EngineContext, + ExecutionStep, + LifecycleError, + converge_services, +) +from cloudfall.mariadb_replication import REPORT_DIRECTORY_VARIABLE +from cloudfall.secrets import SopsSecretProvider +from elasticsearch_hosts import FakeNodes +from kibana_project import SCHEMAS, kibana_service, search_main, write_project + +ROOT = Path(__file__).parents[2] +SEARCH_SECRETS = ( + "CLOUDFALL_PASSWORD=synthetic-cloudfall-value\n" + "ELASTIC_PASSWORD=synthetic-elastic-value\n" + "ANALYST_PASSWORD=synthetic-analyst-value\n" +) +KIBANA_SECRETS = ( + "SECURITY_ENCRYPTION_KEY=synthetic-security-key-0123456789abcdef\n" + "SAVED_OBJECTS_ENCRYPTION_KEY=synthetic-saved-objects-key-0123456789\n" + "REPORTING_ENCRYPTION_KEY=synthetic-reporting-key-0123456789abcd\n" +) +MESSAGE = ( + "Kibana service search-kibana on h1 is left at 9.2.4: these nodes of " + "Elasticsearch service search-main run older than the declared 9.2.5: " + "h2 9.2.4. Kibana never runs ahead of a node; converge every node to that " + "version, then run the command again" +) + + +@dataclass(frozen=True) +class Finished: + """A step's exit and output.""" + + returncode: int = 0 + stdout: str = "" + stderr: str = "" + + +@dataclass +class Recorder: + """Answer the provider playbooks; report ``refusal`` from services.yml.""" + + refusal: dict[str, str] | None = None + nodes: FakeNodes = field(default_factory=FakeNodes) + services: dict[str, object] = field(default_factory=dict) + + def __call__(self, step: ExecutionStep) -> Finished: + """Answer a provider playbook, or fail services.yml with the refusal.""" + if "--extra-vars" not in step.argv: + return Finished() + extra = json.loads(step.argv[step.argv.index("--extra-vars") + 1]) + self.nodes.answer(Path(step.argv[-1]).name, extra) + if not step.argv[-1].endswith("services.yml"): + return Finished() + self.services = extra + if self.refusal is None: + return Finished() + reports = Path(extra[REPORT_DIRECTORY_VARIABLE]) + (reports / f"{self.refusal['service']}.json").write_text( + json.dumps(self.refusal), encoding="utf-8" + ) + return Finished(returncode=2) + + +def _converge(tmp_path: Path, recorder: Recorder) -> None: + project = write_project( + tmp_path / "project", search_main(version="9.2.5"), kibana_service() + ) + services = project / "secrets" / "production" / "services" + services.mkdir(parents=True) + (services / "search-main.env").write_text(SEARCH_SECRETS, encoding="utf-8") + (services / "search-kibana.env").write_text(KIBANA_SECRETS, encoding="utf-8") + converge_services( + EngineContext( + project_directory=project, + schema_directory=SCHEMAS, + engine_directory=ROOT / "engine", + inventory_file=project / "tmp" / "ansible-inventory.json", + run=recorder, + ), + SopsSecretProvider( + secrets_directory=project / "secrets", + decrypt=lambda path: path.read_text(encoding="utf-8"), + ), + ) + + +# proves: S-024-9 +def test_s024_9_a_node_older_than_the_declared_version_answers_precondition( + tmp_path: Path, +) -> None: + recorder = Recorder( + refusal={ + "service": "search-kibana", + "server": "h1", + "outcome": "refused", + "code": "service_kibana_node_older", + "message": MESSAGE, + } + ) + + with pytest.raises(LifecycleError) as error: + _converge(tmp_path, recorder) + + # Not the failed playbook: the role's refusal, which the converge command + # answers with PRECONDITION + assert error.value.code == "service_kibana_node_older" + assert error.value.detail == MESSAGE + assert error.value.context["service"] == "search-kibana" + assert error.value.context["server"] == "h1" + + +# proves: S-024-9 +def test_s024_9_a_project_with_kibana_hands_the_role_its_report_directory( + tmp_path: Path, +) -> None: + recorder = Recorder() + + _converge(tmp_path, recorder) + + assert REPORT_DIRECTORY_VARIABLE in recorder.services