From 326f09fad0da0bb92f795cf3fda8703884fa00de Mon Sep 17 00:00:00 2001 From: Ahmad Hassan Date: Thu, 22 Oct 2026 16:14:17 +0500 Subject: [PATCH 1/3] fix(pre-evacuation): restart nova-compute on nic-up --- bin/pre-evacuation-setup-service | 367 ++++++++++++++++--- tests/unit/test_pre_evacuation_setup.py | 461 ++++++++++++++++++++++++ 2 files changed, 782 insertions(+), 46 deletions(-) create mode 100644 tests/unit/test_pre_evacuation_setup.py diff --git a/bin/pre-evacuation-setup-service b/bin/pre-evacuation-setup-service index a869617..0afee76 100755 --- a/bin/pre-evacuation-setup-service +++ b/bin/pre-evacuation-setup-service @@ -5,8 +5,9 @@ import logging import os import socket import subprocess +import threading import time -from typing import Dict, List +from typing import Dict, List, Optional import psutil from pydantic import BaseModel, Field, field_validator @@ -14,12 +15,37 @@ from snaphelpers import Snap SOCKET_PATH = os.path.join(os.environ["SNAP_DATA"], "hypervisor", "shutdown.sock") +STATE_FILENAME = "pre-evacuation-state.json" +NOVA_COMPUTE = "nova-compute" +NOVA_COMPUTE_START_TIMEOUT = 60 +# nova-compute must stay active this long to count as started: a service that +# crashes on startup is briefly "active" between restarts. +NOVA_COMPUTE_STABLE_SECONDS = 15 +NOVA_COMPUTE_POLL_SECONDS = 2 +# The sender reports nic-up only once, so a failed start must be retried here: nothing +# else would restart nova-compute until the next network flap. +NOVA_COMPUTE_START_ATTEMPTS = 5 +NOVA_COMPUTE_START_RETRY_DELAY = 30 +# When Masakari cannot be asked whether the host is in maintenance, retry for a +# while and then restart nova-compute anyway: a node left down is the worse failure. +MAINTENANCE_LOOKUP_BUDGET = 120 +MAINTENANCE_LOOKUP_DELAY = 10 +# Right after an outage the control plane may accept connections and never answer, +# so every API call needs a timeout of its own. +MASAKARI_API_TIMEOUT = 10 +MASAKARI_ATTEMPT_TIMEOUT = 40 + PROTOCOL_VERSION = "1.0" VIRSH_TIMEOUT = 3 +# Only one recovery may run at a time +_recovery_lock = threading.Lock() + + class NetworkStatus(enum.Enum): """Enum for network interface status""" NIC_DOWN = "nic-down" + NIC_UP = "nic-up" class NetworkStatusMessage(BaseModel): @@ -110,6 +136,261 @@ def force_shutdown_vms(vm_names: List[str]): except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.Error) as exc: logging.error("Failed to kill qemu process for '%s': %s", vm_name, exc) +def _state_path() -> str: + """Path of the file recording what the evacuation procedure did.""" + return os.path.join(os.environ["SNAP_DATA"], STATE_FILENAME) + + +def load_state() -> Optional[Dict]: + """Return the recorded evacuation state, or None if no evacuation is recorded.""" + try: + with open(_state_path(), "r") as f: + return json.load(f) + except FileNotFoundError: + return None + except (OSError, ValueError) as e: + # An unreadable file still means an evacuation happened. Assume nova-compute was + # stopped: starting a service that is already running is harmless, while leaving + # the node down is not. + logging.error(f"Unreadable evacuation state file: {e}") + return {"nova_compute_stopped": True, "corrupt": True} + + +def save_state(state: Dict) -> None: + """Atomically record the evacuation state.""" + path = _state_path() + tmp_path = path + ".tmp" + with open(tmp_path, "w") as f: + json.dump(state, f) + f.flush() + os.fsync(f.fileno()) + os.replace(tmp_path, path) + + +def clear_state() -> None: + """Forget the recorded evacuation state.""" + try: + os.remove(_state_path()) + except FileNotFoundError: + pass + + +def nova_compute_active() -> bool: + """Return True if the nova-compute service is currently running.""" + services = Snap().services.list() + service = services.get(NOVA_COMPUTE) + return bool(service and service.active) + + +def start_nova_compute() -> bool: + """Start the nova-compute service and wait until it is active. + + Returns: + True if nova-compute is active, False if it could not be started in time. + """ + try: + services = Snap().services.list() + service = services.get(NOVA_COMPUTE) + if service is None: + logging.error("nova-compute service not found in the list of snap services") + return False + if service.active: + logging.info("nova-compute is already active. No action needed.") + return True + + logging.info("Starting nova-compute...") + service.start() + deadline = time.monotonic() + NOVA_COMPUTE_START_TIMEOUT + active_since = None + while time.monotonic() < deadline: + if nova_compute_active(): + active_since = active_since or time.monotonic() + if time.monotonic() - active_since >= NOVA_COMPUTE_STABLE_SECONDS: + logging.info("nova-compute service started successfully.") + return True + else: + active_since = None + time.sleep(NOVA_COMPUTE_POLL_SECONDS) + logging.error("nova-compute did not stay active within the timeout") + except Exception as e: + logging.error(f"Unexpected error during nova-compute start: {e}") + return False + + +def start_nova_compute_with_retries() -> bool: + """Start nova-compute, retrying a few times if it does not come up.""" + for attempt in range(1, NOVA_COMPUTE_START_ATTEMPTS + 1): + if start_nova_compute(): + return True + if attempt < NOVA_COMPUTE_START_ATTEMPTS: + logging.warning( + "nova-compute start attempt %s/%s failed, retrying in %ss", + attempt, + NOVA_COMPUTE_START_ATTEMPTS, + NOVA_COMPUTE_START_RETRY_DELAY, + ) + time.sleep(NOVA_COMPUTE_START_RETRY_DELAY) + return False + + +def masakari_host_on_maintenance(snap: Snap) -> Optional[bool]: + """Ask Masakari whether this host is marked on_maintenance. + + Returns: + True or False from Masakari. False also when the host is not registered in any + segment. None when the answer could not be obtained (API unreachable, + credentials missing, client library failure). + """ + try: + import openstack + + identity = snap.config.get_options("identity").as_dict().get("identity", {}) + fqdn = snap.config.get("node.fqdn") + ca_bundle = snap.paths.common / "etc" / "ssl" / "certs" / "receive-ca-bundle.pem" + conn = openstack.connect( + auth_url=identity["auth-url"], + username=identity["username"], + password=identity["password"], + project_name=identity.get("project-name"), + user_domain_name=identity.get("user-domain-name"), + project_domain_name=identity.get("project-domain-name"), + region_name=identity.get("keystone-region-name") or identity.get("region-name"), + interface="internal", + api_timeout=MASAKARI_API_TIMEOUT, + cacert=str(ca_bundle) if ca_bundle.exists() else None, + ) + names = {fqdn.lower(), fqdn.split(".")[0].lower()} + for segment in conn.instance_ha.segments(): + for host in conn.instance_ha.hosts(segment.uuid): + if host.name and host.name.lower() in names: + return bool(host.on_maintenance) + logging.info("Host %s is not registered in any Masakari segment", fqdn) + return False + except Exception as e: + logging.warning(f"Could not determine Masakari maintenance state: {e}") + return None + + +def _call_with_timeout(func, timeout: float): + """Run func in a helper thread and give up after timeout seconds. + + Returns func's result, or None if it timed out or raised. A stuck call is + abandoned (the daemon thread dies with the process), so one hung API request + cannot block the recovery. + """ + outcome: Dict = {} + + def runner(): + try: + outcome["value"] = func() + except Exception as e: + outcome["error"] = e + + thread = threading.Thread(target=runner, name="masakari-lookup", daemon=True) + thread.start() + thread.join(timeout) + if thread.is_alive(): + logging.warning(f"Masakari lookup timed out after {timeout}s") + return None + if "error" in outcome: + logging.warning(f"Masakari lookup failed: {outcome['error']}") + return None + return outcome.get("value") + + +def host_in_maintenance(snap: Snap) -> bool: + """Return True if the node must be left alone because it is in Masakari maintenance. + + Retries for a bounded time while Masakari cannot answer, which is expected right + after an outage. If it never answers the node is treated as not in maintenance. + """ + deadline = time.monotonic() + MAINTENANCE_LOOKUP_BUDGET + while True: + answer = _call_with_timeout( + lambda: masakari_host_on_maintenance(snap), MASAKARI_ATTEMPT_TIMEOUT + ) + if answer is not None: + return answer + if time.monotonic() + MAINTENANCE_LOOKUP_DELAY >= deadline: + break + time.sleep(MAINTENANCE_LOOKUP_DELAY) + logging.warning( + "Masakari did not answer within %ss, assuming the host is not in maintenance", + MAINTENANCE_LOOKUP_BUDGET, + ) + return False + + +def recover_node() -> None: + """Undo the evacuation procedure once the network is back. + + Restarts nova-compute if (and only if) the procedure stopped it, unless the host + is in Masakari maintenance. The recorded state is kept whenever nothing was + restarted, so a later nic-up or an operator can still see what happened. + """ + if not _recovery_lock.acquire(blocking=False): + logging.info("Recovery already in progress, ignoring") + return + try: + state = load_state() + if state is None: + logging.info("No evacuation recorded, nothing to recover") + return + + if host_in_maintenance(Snap()): + logging.info("Host is in Masakari maintenance, leaving nova-compute untouched") + return + + if state.get("nova_compute_stopped") and not start_nova_compute_with_retries(): + logging.error("Recovery failed, keeping the evacuation state for the next nic-up") + return + + clear_state() + logging.info("Evacuation procedure reversed") + except Exception: + logging.exception("Unexpected error during recovery") + finally: + _recovery_lock.release() + + +def _response(status: str, message: str) -> str: + return json.dumps({"status": status, "message": message, "timestamp": time.time()}) + + +def handle_nic_down() -> str: + """Stop nova-compute and shut down the VMs, recording what was done.""" + if load_state() is not None: + logging.info("Evacuation already recorded, ignoring repeated nic-down") + return _response("success", "Evacuation procedure already initiated") + + logging.info("Network interface down detected, initiating evacuation procedure") + # Record first: if we are interrupted half way, recovery still knows what to undo. + save_state( + { + "timestamp": time.time(), + "nova_compute_stopped": nova_compute_active(), + } + ) + + stop_nova_compute() + shutdown_vms() + + return _response("success", "Evacuation procedure initiated") + + +def handle_nic_up() -> str: + """Reverse the evacuation procedure in the background.""" + if load_state() is None: + logging.info("Network is up and no evacuation is recorded, nothing to do") + return _response("success", "No evacuation recorded, nothing to recover") + + logging.info("Network interface up detected, starting recovery") + # Recovery may wait on Masakari and on nova-compute, so do not hold the sender + # (a Consul check with a short timeout) while it runs. + threading.Thread(target=recover_node, name="recover-node", daemon=True).start() + return _response("success", "Recovery initiated") + + def handle_network_status(data: Dict) -> str: """Handle network status messages and take appropriate actions @@ -124,25 +405,45 @@ def handle_network_status(data: Dict) -> str: logging.info(f"Received network status update: {status_value}") if status == NetworkStatus.NIC_DOWN: - logging.info("Network interface down detected, initiating evacuation procedure") + return handle_nic_down() + if status == NetworkStatus.NIC_UP: + return handle_nic_up() + + logging.warning(f"Received unknown network status: {status_value}") + return _response("error", f"Unknown network status: {status_value}") + + +def _send(conn, payload: str) -> None: + """Send a response, tolerating a client that has already hung up.""" + try: + conn.sendall(payload.encode()) + except OSError as e: + logging.warning(f"Could not send response, client went away: {e}") + + +def _handle_connection(conn) -> None: + """Read one message from conn, act on it and answer.""" + data = conn.recv(1024) + if not data: + return - stop_nova_compute() - shutdown_vms() + raw_message = data.decode().strip() + logging.debug(f"Received raw message: {raw_message}") - return json.dumps({ - "status": "success", - "message": "Evacuation procedure initiated", - "timestamp": time.time() - }) + try: + json_data = json.loads(raw_message) + message = NetworkStatusMessage.model_validate(json_data) + validated_data = message.model_dump() - else: - logging.warning(f"Received unknown network status: {status_value}") + response = handle_network_status(validated_data) + _send(conn, response) - return json.dumps({ - "status": "error", - "message": f"Unknown network status: {status_value}", - "timestamp": time.time() - }) + except ValueError as e: + logging.error(f"Validation error: {e}") + _send(conn, _response("error", f"Schema validation failed: {str(e)}")) + except Exception as e: + logging.error(f"Error processing message: {e}") + _send(conn, _response("error", f"Server error: {str(e)}")) def run_listener(): @@ -162,37 +463,11 @@ def run_listener(): while True: conn, _ = server_sock.accept() with conn: - data = conn.recv(1024) - if not data: - continue - - raw_message = data.decode().strip() - logging.debug(f"Received raw message: {raw_message}") - try: - json_data = json.loads(raw_message) - message = NetworkStatusMessage.model_validate(json_data) - validated_data = message.model_dump() - - response = handle_network_status(validated_data) - conn.sendall(response.encode()) - - except ValueError as e: - logging.error(f"Validation error: {e}") - error_response = json.dumps({ - "status": "error", - "message": f"Schema validation failed: {str(e)}", - "timestamp": time.time() - }) - conn.sendall(error_response.encode()) - except Exception as e: - logging.error(f"Error processing message: {e}") - error_response = json.dumps({ - "status": "error", - "message": f"Server error: {str(e)}", - "timestamp": time.time() - }) - conn.sendall(error_response.encode()) + _handle_connection(conn) + except OSError as e: + # A client that vanishes must never take the listener down + logging.warning(f"Connection error, ignoring: {e}") if __name__ == "__main__": diff --git a/tests/unit/test_pre_evacuation_setup.py b/tests/unit/test_pre_evacuation_setup.py new file mode 100644 index 0000000..003c842 --- /dev/null +++ b/tests/unit/test_pre_evacuation_setup.py @@ -0,0 +1,461 @@ +# SPDX-FileCopyrightText: 2026 - Canonical Ltd +# SPDX-License-Identifier: Apache-2.0 + +import importlib.machinery +import importlib.util +import json +import sys +import threading +from pathlib import Path +from unittest.mock import MagicMock + +import pytest + +SCRIPT = Path(__file__).parents[2] / "bin" / "pre-evacuation-setup-service" + + +class FakeClock: + def __init__(self): + self.start = 1000.0 + self.now = self.start + + def monotonic(self): + return self.now + + def sleep(self, seconds): + self.now += seconds + + @property + def elapsed(self): + return self.now - self.start + + +@pytest.fixture +def svc(tmp_path, monkeypatch): + """Load the pre-evacuation-setup-service script as a module, with SNAP_DATA in tmp_path.""" + monkeypatch.setenv("SNAP_DATA", str(tmp_path)) + # Do not write bytecode next to the script: bin/ is packaged into the snap. + monkeypatch.setattr(sys, "dont_write_bytecode", True) + loader = importlib.machinery.SourceFileLoader("pre_evacuation_setup_service", str(SCRIPT)) + spec = importlib.util.spec_from_loader(loader.name, loader) + module = importlib.util.module_from_spec(spec) + loader.exec_module(module) + + # Virtual time: sleeping advances the clock instantly, so retry and wait loops + # run in microseconds and their durations can be asserted. + clock = FakeClock() + monkeypatch.setattr(module.time, "monotonic", clock.monotonic) + monkeypatch.setattr(module.time, "sleep", clock.sleep) + module.clock = clock + return module + + +def _message(status): + return {"version": "1.0", "timestamp": 1.0, "status": status} + + +def _service(active): + service = MagicMock() + service.active = active + return service + + +def _fake_snap(monkeypatch, svc, services): + snap = MagicMock() + snap.services.list.return_value = services + monkeypatch.setattr(svc, "Snap", lambda: snap) + return snap + + +class TestProtocol: + def test_nic_up_is_a_valid_status(self, svc): + message = svc.NetworkStatusMessage.model_validate(_message("nic-up")) + assert message.status == "nic-up" + + def test_unknown_status_is_rejected(self, svc): + with pytest.raises(ValueError): + svc.NetworkStatusMessage.model_validate(_message("nic-sideways")) + + +class TestState: + def test_load_state_missing(self, svc): + assert svc.load_state() is None + + def test_save_and_load_state(self, svc): + svc.save_state({"nova_compute_stopped": True}) + assert svc.load_state() == {"nova_compute_stopped": True} + + def test_clear_state(self, svc): + svc.save_state({"nova_compute_stopped": True}) + svc.clear_state() + svc.clear_state() # clearing twice is fine + assert svc.load_state() is None + + def test_corrupt_state_is_treated_as_nova_compute_stopped(self, svc, tmp_path): + (tmp_path / svc.STATE_FILENAME).write_text("{not json") + state = svc.load_state() + assert state["nova_compute_stopped"] is True + + +class TestNicDown: + @pytest.fixture(autouse=True) + def _actions(self, svc, monkeypatch): + self.stop = MagicMock() + self.shutdown = MagicMock() + monkeypatch.setattr(svc, "stop_nova_compute", self.stop) + monkeypatch.setattr(svc, "shutdown_vms", self.shutdown) + + def test_records_state_then_stops_and_shuts_down(self, svc, monkeypatch): + _fake_snap(monkeypatch, svc, {"nova-compute": _service(True)}) + + response = json.loads(svc.handle_network_status(_message("nic-down"))) + + assert response["status"] == "success" + self.stop.assert_called_once() + self.shutdown.assert_called_once() + assert svc.load_state()["nova_compute_stopped"] is True + + def test_state_is_saved_before_nova_compute_is_stopped(self, svc, monkeypatch): + _fake_snap(monkeypatch, svc, {"nova-compute": _service(True)}) + seen = {} + self.stop.side_effect = lambda: seen.update(state=svc.load_state()) + + svc.handle_network_status(_message("nic-down")) + + assert seen["state"] is not None + + def test_nova_compute_already_stopped_is_recorded_as_not_ours(self, svc, monkeypatch): + _fake_snap(monkeypatch, svc, {"nova-compute": _service(False)}) + + svc.handle_network_status(_message("nic-down")) + + assert svc.load_state()["nova_compute_stopped"] is False + + def test_repeated_nic_down_is_ignored_and_keeps_original_state(self, svc, monkeypatch): + snap = _fake_snap(monkeypatch, svc, {"nova-compute": _service(True)}) + svc.handle_network_status(_message("nic-down")) + # nova-compute is now down because of us: a second message must not rewrite + # the state as "nova-compute was already stopped". + snap.services.list.return_value = {"nova-compute": _service(False)} + + response = json.loads(svc.handle_network_status(_message("nic-down"))) + + assert response["status"] == "success" + assert self.stop.call_count == 1 + assert self.shutdown.call_count == 1 + assert svc.load_state()["nova_compute_stopped"] is True + + +class TestNicUp: + @pytest.fixture(autouse=True) + def _sync_thread(self, svc, monkeypatch): + """Run the recovery thread inline so tests can assert on its result.""" + + class InlineThread: + def __init__(self, target, **kwargs): + self.target = target + + def start(self): + self.target() + + monkeypatch.setattr(svc.threading, "Thread", InlineThread) + + def test_nic_up_without_evacuation_does_nothing(self, svc, monkeypatch): + start = MagicMock() + monkeypatch.setattr(svc, "start_nova_compute", start) + + response = json.loads(svc.handle_network_status(_message("nic-up"))) + + assert response["status"] == "success" + assert "nothing to recover" in response["message"] + start.assert_not_called() + + def test_nic_up_restarts_nova_compute_and_clears_state(self, svc, monkeypatch): + svc.save_state({"nova_compute_stopped": True}) + start = MagicMock(return_value=True) + monkeypatch.setattr(svc, "start_nova_compute", start) + monkeypatch.setattr(svc, "host_in_maintenance", lambda snap: False) + monkeypatch.setattr(svc, "Snap", MagicMock()) + + response = json.loads(svc.handle_network_status(_message("nic-up"))) + + assert response["message"] == "Recovery initiated" + start.assert_called_once() + assert svc.load_state() is None + + def test_nic_up_does_not_start_what_it_did_not_stop(self, svc, monkeypatch): + svc.save_state({"nova_compute_stopped": False}) + start = MagicMock() + monkeypatch.setattr(svc, "start_nova_compute", start) + monkeypatch.setattr(svc, "host_in_maintenance", lambda snap: False) + monkeypatch.setattr(svc, "Snap", MagicMock()) + + svc.handle_network_status(_message("nic-up")) + + start.assert_not_called() + assert svc.load_state() is None + + def test_nic_up_leaves_host_in_maintenance_alone(self, svc, monkeypatch): + svc.save_state({"nova_compute_stopped": True}) + start = MagicMock() + monkeypatch.setattr(svc, "start_nova_compute", start) + monkeypatch.setattr(svc, "host_in_maintenance", lambda snap: True) + monkeypatch.setattr(svc, "Snap", MagicMock()) + + svc.handle_network_status(_message("nic-up")) + + start.assert_not_called() + assert svc.load_state() is not None + + def test_failed_start_keeps_state_for_retry(self, svc, monkeypatch): + svc.save_state({"nova_compute_stopped": True}) + start = MagicMock(return_value=False) + monkeypatch.setattr(svc, "start_nova_compute", start) + monkeypatch.setattr(svc, "host_in_maintenance", lambda snap: False) + monkeypatch.setattr(svc, "Snap", MagicMock()) + + svc.handle_network_status(_message("nic-up")) + + assert start.call_count == svc.NOVA_COMPUTE_START_ATTEMPTS + assert svc.load_state() is not None + + def test_start_is_retried_until_it_succeeds(self, svc, monkeypatch): + svc.save_state({"nova_compute_stopped": True}) + start = MagicMock(side_effect=[False, False, True]) + monkeypatch.setattr(svc, "start_nova_compute", start) + monkeypatch.setattr(svc, "host_in_maintenance", lambda snap: False) + monkeypatch.setattr(svc, "Snap", MagicMock()) + + svc.handle_network_status(_message("nic-up")) + + assert start.call_count == 3 + assert svc.clock.elapsed == 2 * svc.NOVA_COMPUTE_START_RETRY_DELAY + assert svc.load_state() is None + + def test_no_delay_after_the_last_failed_attempt(self, svc, monkeypatch): + monkeypatch.setattr(svc, "start_nova_compute", MagicMock(return_value=False)) + + assert svc.start_nova_compute_with_retries() is False + + delays = svc.NOVA_COMPUTE_START_ATTEMPTS - 1 + assert svc.clock.elapsed == delays * svc.NOVA_COMPUTE_START_RETRY_DELAY + + def test_concurrent_recovery_is_ignored(self, svc, monkeypatch): + svc.save_state({"nova_compute_stopped": True}) + start = MagicMock() + monkeypatch.setattr(svc, "start_nova_compute", start) + assert svc._recovery_lock.acquire(blocking=False) + try: + svc.recover_node() + finally: + svc._recovery_lock.release() + + start.assert_not_called() + assert svc.load_state() is not None + + +class TestStartNovaCompute: + def test_already_active(self, svc, monkeypatch): + service = _service(True) + _fake_snap(monkeypatch, svc, {"nova-compute": service}) + + assert svc.start_nova_compute() is True + service.start.assert_not_called() + + def test_starts_and_waits_until_stable(self, svc, monkeypatch): + service = _service(False) + service.start.side_effect = lambda: setattr(service, "active", True) + _fake_snap(monkeypatch, svc, {"nova-compute": service}) + + assert svc.start_nova_compute() is True + + service.start.assert_called_once() + # It did not return on the first sight of "active" + assert svc.clock.elapsed >= svc.NOVA_COMPUTE_STABLE_SECONDS + + def test_crash_looping_service_is_not_counted_as_started(self, svc, monkeypatch): + """A service that is active only between crashes must not count as started.""" + service = _service(False) + snap = _fake_snap(monkeypatch, svc, {"nova-compute": service}) + polls = iter(range(10**6)) + + def flapping(): + return {"nova-compute": _service(next(polls) % 2 == 1)} + + snap.services.list.side_effect = flapping + + assert svc.start_nova_compute() is False + + def test_missing_service(self, svc, monkeypatch): + _fake_snap(monkeypatch, svc, {}) + assert svc.start_nova_compute() is False + + def test_times_out(self, svc, monkeypatch): + service = _service(False) + _fake_snap(monkeypatch, svc, {"nova-compute": service}) + monkeypatch.setattr(svc, "NOVA_COMPUTE_START_TIMEOUT", 0) + + assert svc.start_nova_compute() is False + + +class TestHostInMaintenance: + def test_returns_masakari_answer(self, svc, monkeypatch): + monkeypatch.setattr(svc, "masakari_host_on_maintenance", lambda snap: True) + assert svc.host_in_maintenance(MagicMock()) is True + + def test_retries_until_masakari_answers(self, svc, monkeypatch): + answers = iter([None, None, False]) + monkeypatch.setattr(svc, "masakari_host_on_maintenance", lambda snap: next(answers)) + + assert svc.host_in_maintenance(MagicMock()) is False + assert svc.clock.elapsed == 2 * svc.MAINTENANCE_LOOKUP_DELAY + + def test_assumes_not_in_maintenance_when_masakari_never_answers(self, svc, monkeypatch): + calls = [] + monkeypatch.setattr( + svc, "masakari_host_on_maintenance", lambda snap: calls.append(1) or None + ) + + assert svc.host_in_maintenance(MagicMock()) is False + + assert len(calls) > 1 + # bounded: never waits longer than the budget + assert svc.clock.elapsed <= svc.MAINTENANCE_LOOKUP_BUDGET + + def test_a_hung_lookup_cannot_block_recovery(self, svc, monkeypatch): + """A call that never returns is abandoned instead of hanging forever.""" + release = threading.Event() + monkeypatch.setattr(svc, "masakari_host_on_maintenance", lambda snap: release.wait()) + monkeypatch.setattr(svc, "MASAKARI_ATTEMPT_TIMEOUT", 0.05) + monkeypatch.setattr(svc, "MAINTENANCE_LOOKUP_BUDGET", 0) + + try: + assert svc.host_in_maintenance(MagicMock()) is False + finally: + release.set() + + def test_call_with_timeout_returns_value(self, svc): + assert svc._call_with_timeout(lambda: "ok", 1) == "ok" + + def test_call_with_timeout_swallows_errors(self, svc): + def boom(): + raise RuntimeError("api down") + + assert svc._call_with_timeout(boom, 1) is None + + +class TestListenerResilience: + def test_send_ignores_a_client_that_hung_up(self, svc): + conn = MagicMock() + conn.sendall.side_effect = BrokenPipeError(32, "Broken pipe") + + svc._send(conn, "reply") # must not raise + + def test_handle_connection_survives_broken_pipe_on_reply(self, svc, monkeypatch): + conn = MagicMock() + conn.recv.return_value = json.dumps(_message("nic-up")).encode() + conn.sendall.side_effect = BrokenPipeError(32, "Broken pipe") + monkeypatch.setattr(svc, "handle_network_status", lambda data: "{}") + + svc._handle_connection(conn) # must not raise + + def test_handle_connection_survives_broken_pipe_on_error_reply(self, svc): + conn = MagicMock() + conn.recv.return_value = b"not json" + conn.sendall.side_effect = BrokenPipeError(32, "Broken pipe") + + svc._handle_connection(conn) # must not raise + + def test_handle_connection_answers_a_valid_message(self, svc, monkeypatch): + conn = MagicMock() + conn.recv.return_value = json.dumps(_message("nic-up")).encode() + monkeypatch.setattr(svc, "handle_network_status", lambda data: '{"status": "success"}') + + svc._handle_connection(conn) + + conn.sendall.assert_called_once_with(b'{"status": "success"}') + + def test_handle_connection_reports_invalid_status(self, svc): + conn = MagicMock() + conn.recv.return_value = json.dumps(_message("nic-sideways")).encode() + + svc._handle_connection(conn) + + reply = json.loads(conn.sendall.call_args[0][0].decode()) + assert reply["status"] == "error" + + +class TestMasakariLookup: + @pytest.fixture + def snap(self, tmp_path): + snap = MagicMock() + snap.paths.common = tmp_path + snap.config.get.return_value = "compute-1.maas" + snap.config.get_options.return_value.as_dict.return_value = { + "identity": { + "auth-url": "http://keystone/v3", + "username": "u", + "password": "p", + "project-name": "services", + "user-domain-name": "service_domain", + "project-domain-name": "service_domain", + "region-name": "RegionOne", + } + } + return snap + + @pytest.fixture + def conn(self, monkeypatch): + conn = MagicMock() + fake_openstack = MagicMock() + fake_openstack.connect.return_value = conn + monkeypatch.setitem(sys.modules, "openstack", fake_openstack) + return conn + + @staticmethod + def _host(name, on_maintenance): + host = MagicMock() + host.name = name + host.on_maintenance = on_maintenance + return host + + def test_host_on_maintenance(self, svc, snap, conn): + conn.instance_ha.segments.return_value = [MagicMock(uuid="s1")] + conn.instance_ha.hosts.return_value = [self._host("compute-1.maas", True)] + assert svc.masakari_host_on_maintenance(snap) is True + + def test_requests_have_a_timeout(self, svc, snap, conn): + import sys + + conn.instance_ha.segments.return_value = [] + svc.masakari_host_on_maintenance(snap) + + kwargs = sys.modules["openstack"].connect.call_args.kwargs + assert kwargs["api_timeout"] == svc.MASAKARI_API_TIMEOUT + + def test_host_not_on_maintenance(self, svc, snap, conn): + conn.instance_ha.segments.return_value = [MagicMock(uuid="s1")] + conn.instance_ha.hosts.return_value = [self._host("compute-1.maas", False)] + assert svc.masakari_host_on_maintenance(snap) is False + + def test_matches_short_hostname(self, svc, snap, conn): + conn.instance_ha.segments.return_value = [MagicMock(uuid="s1")] + conn.instance_ha.hosts.return_value = [self._host("compute-1", True)] + assert svc.masakari_host_on_maintenance(snap) is True + + def test_does_not_match_a_different_host(self, svc, snap, conn): + conn.instance_ha.segments.return_value = [MagicMock(uuid="s1")] + conn.instance_ha.hosts.return_value = [self._host("compute-10.maas", True)] + assert svc.masakari_host_on_maintenance(snap) is False + + def test_host_not_registered(self, svc, snap, conn): + conn.instance_ha.segments.return_value = [] + assert svc.masakari_host_on_maintenance(snap) is False + + def test_api_failure_is_unknown(self, svc, snap, conn): + conn.instance_ha.segments.side_effect = RuntimeError("api down") + assert svc.masakari_host_on_maintenance(snap) is None + + def test_missing_credentials_is_unknown(self, svc, snap, conn): + snap.config.get_options.return_value.as_dict.return_value = {"identity": {}} + assert svc.masakari_host_on_maintenance(snap) is None From 2fbf08943017b8d90cc0d7e1194a4581d62cdc98 Mon Sep 17 00:00:00 2001 From: Ahmad Hassan Date: Fri, 20 Nov 2026 14:49:09 +0500 Subject: [PATCH 2/3] fix: cancel pending recovery on newer nic-down --- bin/pre-evacuation-setup-service | 164 ++++++++++++++++++++---- tests/unit/test_pre_evacuation_setup.py | 157 ++++++++++++++++++++--- 2 files changed, 275 insertions(+), 46 deletions(-) diff --git a/bin/pre-evacuation-setup-service b/bin/pre-evacuation-setup-service index 0afee76..4f39323 100755 --- a/bin/pre-evacuation-setup-service +++ b/bin/pre-evacuation-setup-service @@ -40,34 +40,74 @@ VIRSH_TIMEOUT = 3 # Only one recovery may run at a time _recovery_lock = threading.Lock() +# A recovery that is still running must be abandoned when a newer nic-down arrives: +# a second outage means the node must stay down, and a recovery that already +# restarted nova-compute would leave it running during the outage. Every nic-down +# bumps the generation; a recovery tagged with an older generation is cancelled. +# Reentrant: _outage_cancelled is also called while the lock is already held. +_state_lock = threading.RLock() +_outage_generation = 0 + + +def _cancel_pending_recovery() -> None: + """Invalidate any recovery in flight: a newer nic-down wins over a stale recovery.""" + global _outage_generation + with _state_lock: + _outage_generation += 1 + + +def _outage_cancelled(generation: int) -> bool: + """Return True if a newer nic-down arrived since this recovery started.""" + with _state_lock: + return _outage_generation != generation + + +def _interruptible_sleep(seconds: float, generation: int) -> bool: + """Sleep up to seconds, returning True if a newer nic-down cancelled the recovery. + + Polls instead of blocking on an event, so a single generation counter drives + both the sleep and the cancellation checks. + """ + deadline = time.monotonic() + seconds + while True: + if _outage_cancelled(generation): + return True + remaining = deadline - time.monotonic() + if remaining <= 0: + return False + time.sleep(min(1.0, remaining)) class NetworkStatus(enum.Enum): """Enum for network interface status""" + NIC_DOWN = "nic-down" NIC_UP = "nic-up" class NetworkStatusMessage(BaseModel): """Pydantic model for network status messages""" + version: str = Field(description="Protocol version") timestamp: float = Field(description="Message timestamp") status: str = Field(description="Network status") - @field_validator('version') + @field_validator("version") @classmethod def validate_version(cls, v): if v != PROTOCOL_VERSION: logging.warning(f"Incompatible protocol version: {v}, expected: {PROTOCOL_VERSION}") return v - @field_validator('status') + @field_validator("status") @classmethod def validate_status(cls, v): try: return NetworkStatus(v).value except ValueError: - raise ValueError(f"Invalid status: {v}. Must be one of: {', '.join([s.value for s in NetworkStatus])}") + raise ValueError( + f"Invalid status: {v}. Must be one of: {', '.join([s.value for s in NetworkStatus])}" + ) def stop_nova_compute(): @@ -79,8 +119,8 @@ def stop_nova_compute(): snap = Snap() services = snap.services.list() - if 'nova-compute' in services: - service = services['nova-compute'] + if "nova-compute" in services: + service = services["nova-compute"] if service.active: logging.info("nova-compute is active. Proceeding to stop the service...") @@ -105,7 +145,7 @@ def shutdown_vms(): check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, - text=True + text=True, ) vm_names = [line.strip() for line in result.stdout.strip().splitlines() if line.strip()] @@ -122,6 +162,7 @@ def shutdown_vms(): force_shutdown_vms(vm_names) break + def force_shutdown_vms(vm_names: List[str]): """ Forcefully stop VMs by killing their qemu processes. @@ -136,6 +177,7 @@ def force_shutdown_vms(vm_names: List[str]): except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.Error) as exc: logging.error("Failed to kill qemu process for '%s': %s", vm_name, exc) + def _state_path() -> str: """Path of the file recording what the evacuation procedure did.""" return os.path.join(os.environ["SNAP_DATA"], STATE_FILENAME) @@ -182,11 +224,12 @@ def nova_compute_active() -> bool: return bool(service and service.active) -def start_nova_compute() -> bool: +def start_nova_compute(generation: int) -> bool: """Start the nova-compute service and wait until it is active. Returns: - True if nova-compute is active, False if it could not be started in time. + True if nova-compute is active, False if it could not be started in time + or if a newer nic-down cancelled the recovery. """ try: services = Snap().services.list() @@ -199,10 +242,19 @@ def start_nova_compute() -> bool: return True logging.info("Starting nova-compute...") - service.start() + # Hold the generation lock across the start decision, so a nic-down that + # arrives during the start-wait cannot slip past the check below. + with _state_lock: + if _outage_cancelled(generation): + logging.info("A newer nic-down arrived, not starting nova-compute") + return False + service.start() deadline = time.monotonic() + NOVA_COMPUTE_START_TIMEOUT active_since = None while time.monotonic() < deadline: + if _outage_cancelled(generation): + logging.info("A newer nic-down arrived, abandoning nova-compute start") + return False if nova_compute_active(): active_since = active_since or time.monotonic() if time.monotonic() - active_since >= NOVA_COMPUTE_STABLE_SECONDS: @@ -217,11 +269,14 @@ def start_nova_compute() -> bool: return False -def start_nova_compute_with_retries() -> bool: +def start_nova_compute_with_retries(generation: int) -> bool: """Start nova-compute, retrying a few times if it does not come up.""" for attempt in range(1, NOVA_COMPUTE_START_ATTEMPTS + 1): - if start_nova_compute(): + if start_nova_compute(generation): return True + if _outage_cancelled(generation): + logging.info("A newer nic-down arrived, abandoning recovery") + return False if attempt < NOVA_COMPUTE_START_ATTEMPTS: logging.warning( "nova-compute start attempt %s/%s failed, retrying in %ss", @@ -229,7 +284,9 @@ def start_nova_compute_with_retries() -> bool: NOVA_COMPUTE_START_ATTEMPTS, NOVA_COMPUTE_START_RETRY_DELAY, ) - time.sleep(NOVA_COMPUTE_START_RETRY_DELAY) + if _interruptible_sleep(NOVA_COMPUTE_START_RETRY_DELAY, generation): + logging.info("A newer nic-down arrived, abandoning recovery") + return False return False @@ -298,22 +355,29 @@ def _call_with_timeout(func, timeout: float): return outcome.get("value") -def host_in_maintenance(snap: Snap) -> bool: +def host_in_maintenance(snap: Snap, generation: int) -> Optional[bool]: """Return True if the node must be left alone because it is in Masakari maintenance. Retries for a bounded time while Masakari cannot answer, which is expected right after an outage. If it never answers the node is treated as not in maintenance. + + Returns: + True or False from Masakari, or None if a newer nic-down cancelled the + recovery while the lookup was in progress. """ deadline = time.monotonic() + MAINTENANCE_LOOKUP_BUDGET while True: answer = _call_with_timeout( lambda: masakari_host_on_maintenance(snap), MASAKARI_ATTEMPT_TIMEOUT ) + if _outage_cancelled(generation): + return None if answer is not None: return answer if time.monotonic() + MAINTENANCE_LOOKUP_DELAY >= deadline: break - time.sleep(MAINTENANCE_LOOKUP_DELAY) + if _interruptible_sleep(MAINTENANCE_LOOKUP_DELAY, generation): + return None logging.warning( "Masakari did not answer within %ss, assuming the host is not in maintenance", MAINTENANCE_LOOKUP_BUDGET, @@ -321,12 +385,14 @@ def host_in_maintenance(snap: Snap) -> bool: return False -def recover_node() -> None: +def recover_node(generation: int) -> None: """Undo the evacuation procedure once the network is back. Restarts nova-compute if (and only if) the procedure stopped it, unless the host - is in Masakari maintenance. The recorded state is kept whenever nothing was - restarted, so a later nic-up or an operator can still see what happened. + is in Masakari maintenance. The recovery is abandoned when a newer nic-down + arrives (a second outage): the node must stay down, and a start that already + happened is undone. The recorded state is kept whenever nothing was restarted, + so a later nic-up or an operator can still see what happened. """ if not _recovery_lock.acquire(blocking=False): logging.info("Recovery already in progress, ignoring") @@ -336,16 +402,46 @@ def recover_node() -> None: if state is None: logging.info("No evacuation recorded, nothing to recover") return - - if host_in_maintenance(Snap()): - logging.info("Host is in Masakari maintenance, leaving nova-compute untouched") + if _outage_cancelled(generation): + logging.info("A newer nic-down arrived, abandoning recovery") return - if state.get("nova_compute_stopped") and not start_nova_compute_with_retries(): - logging.error("Recovery failed, keeping the evacuation state for the next nic-up") + maintenance = host_in_maintenance(Snap(), generation) + if maintenance is None: + logging.info("Recovery cancelled by a newer nic-down, keeping the evacuation state") + return + if maintenance: + logging.info("Host is in Masakari maintenance, leaving nova-compute untouched") return - clear_state() + if state.get("nova_compute_stopped"): + if not start_nova_compute_with_retries(generation): + if _outage_cancelled(generation): + logging.info( + "Recovery cancelled by a newer nic-down, keeping the evacuation state" + ) + else: + logging.error( + "Recovery failed, keeping the evacuation state for the next nic-up" + ) + return + if _outage_cancelled(generation): + # A newer nic-down arrived while we were starting. It may have stopped + # the service behind our back, or missed it while it was still + # activating; undo the start we completed, because nova-compute must + # not run during the outage. + stop_nova_compute() + logging.info( + "A newer nic-down arrived, stopped nova-compute again and " + "keeping the evacuation state" + ) + return + + with _state_lock: + if _outage_cancelled(generation): + logging.info("A newer nic-down arrived, keeping the evacuation state") + return + clear_state() logging.info("Evacuation procedure reversed") except Exception: logging.exception("Unexpected error during recovery") @@ -360,9 +456,20 @@ def _response(status: str, message: str) -> str: def handle_nic_down() -> str: """Stop nova-compute and shut down the VMs, recording what was done.""" if load_state() is not None: - logging.info("Evacuation already recorded, ignoring repeated nic-down") + # A repeated nic-down while an evacuation is already recorded: either a + # duplicate message or a second outage during recovery. Cancel any recovery + # in flight and stop nova-compute again in case recovery had already started + # it. The VMs were already shut down during the first outage, and re-running + # the shutdown would kill VMs an operator restarted in the meantime. + logging.info( + "Evacuation already recorded: cancelling pending recovery and " + "re-stopping nova-compute if it was restarted" + ) + _cancel_pending_recovery() + stop_nova_compute() return _response("success", "Evacuation procedure already initiated") + _cancel_pending_recovery() logging.info("Network interface down detected, initiating evacuation procedure") # Record first: if we are interrupted half way, recovery still knows what to undo. save_state( @@ -386,8 +493,13 @@ def handle_nic_up() -> str: logging.info("Network interface up detected, starting recovery") # Recovery may wait on Masakari and on nova-compute, so do not hold the sender - # (a Consul check with a short timeout) while it runs. - threading.Thread(target=recover_node, name="recover-node", daemon=True).start() + # (a Consul check with a short timeout) while it runs. The recovery is tagged + # with the current outage generation so a newer nic-down can cancel it. + with _state_lock: + generation = _outage_generation + threading.Thread( + target=recover_node, args=(generation,), name="recover-node", daemon=True + ).start() return _response("success", "Recovery initiated") diff --git a/tests/unit/test_pre_evacuation_setup.py b/tests/unit/test_pre_evacuation_setup.py index 003c842..6fb4362 100644 --- a/tests/unit/test_pre_evacuation_setup.py +++ b/tests/unit/test_pre_evacuation_setup.py @@ -54,6 +54,13 @@ def _message(status): return {"version": "1.0", "timestamp": 1.0, "status": status} +def _join_recovery_thread(svc, timeout=5): + """Wait for the recover-node thread spawned by handle_nic_up to finish.""" + for t in threading.enumerate(): + if t.name == "recover-node": + t.join(timeout) + + def _service(active): service = MagicMock() service.active = active @@ -131,7 +138,7 @@ def test_nova_compute_already_stopped_is_recorded_as_not_ours(self, svc, monkeyp assert svc.load_state()["nova_compute_stopped"] is False - def test_repeated_nic_down_is_ignored_and_keeps_original_state(self, svc, monkeypatch): + def test_repeated_nic_down_cancels_recovery_and_restops_nova_compute(self, svc, monkeypatch): snap = _fake_snap(monkeypatch, svc, {"nova-compute": _service(True)}) svc.handle_network_status(_message("nic-down")) # nova-compute is now down because of us: a second message must not rewrite @@ -141,7 +148,10 @@ def test_repeated_nic_down_is_ignored_and_keeps_original_state(self, svc, monkey response = json.loads(svc.handle_network_status(_message("nic-down"))) assert response["status"] == "success" - assert self.stop.call_count == 1 + # The recovery is cancelled and nova-compute is stopped again in case a + # recovery had already restarted it. The VMs are not shut down a second + # time: an operator may have restarted them in the meantime. + assert self.stop.call_count == 2 assert self.shutdown.call_count == 1 assert svc.load_state()["nova_compute_stopped"] is True @@ -152,11 +162,12 @@ def _sync_thread(self, svc, monkeypatch): """Run the recovery thread inline so tests can assert on its result.""" class InlineThread: - def __init__(self, target, **kwargs): + def __init__(self, target, args=(), **kwargs): self.target = target + self.args = args def start(self): - self.target() + self.target(*self.args) monkeypatch.setattr(svc.threading, "Thread", InlineThread) @@ -174,7 +185,7 @@ def test_nic_up_restarts_nova_compute_and_clears_state(self, svc, monkeypatch): svc.save_state({"nova_compute_stopped": True}) start = MagicMock(return_value=True) monkeypatch.setattr(svc, "start_nova_compute", start) - monkeypatch.setattr(svc, "host_in_maintenance", lambda snap: False) + monkeypatch.setattr(svc, "host_in_maintenance", lambda snap, gen: False) monkeypatch.setattr(svc, "Snap", MagicMock()) response = json.loads(svc.handle_network_status(_message("nic-up"))) @@ -187,7 +198,7 @@ def test_nic_up_does_not_start_what_it_did_not_stop(self, svc, monkeypatch): svc.save_state({"nova_compute_stopped": False}) start = MagicMock() monkeypatch.setattr(svc, "start_nova_compute", start) - monkeypatch.setattr(svc, "host_in_maintenance", lambda snap: False) + monkeypatch.setattr(svc, "host_in_maintenance", lambda snap, gen: False) monkeypatch.setattr(svc, "Snap", MagicMock()) svc.handle_network_status(_message("nic-up")) @@ -199,7 +210,7 @@ def test_nic_up_leaves_host_in_maintenance_alone(self, svc, monkeypatch): svc.save_state({"nova_compute_stopped": True}) start = MagicMock() monkeypatch.setattr(svc, "start_nova_compute", start) - monkeypatch.setattr(svc, "host_in_maintenance", lambda snap: True) + monkeypatch.setattr(svc, "host_in_maintenance", lambda snap, gen: True) monkeypatch.setattr(svc, "Snap", MagicMock()) svc.handle_network_status(_message("nic-up")) @@ -211,7 +222,7 @@ def test_failed_start_keeps_state_for_retry(self, svc, monkeypatch): svc.save_state({"nova_compute_stopped": True}) start = MagicMock(return_value=False) monkeypatch.setattr(svc, "start_nova_compute", start) - monkeypatch.setattr(svc, "host_in_maintenance", lambda snap: False) + monkeypatch.setattr(svc, "host_in_maintenance", lambda snap, gen: False) monkeypatch.setattr(svc, "Snap", MagicMock()) svc.handle_network_status(_message("nic-up")) @@ -223,7 +234,7 @@ def test_start_is_retried_until_it_succeeds(self, svc, monkeypatch): svc.save_state({"nova_compute_stopped": True}) start = MagicMock(side_effect=[False, False, True]) monkeypatch.setattr(svc, "start_nova_compute", start) - monkeypatch.setattr(svc, "host_in_maintenance", lambda snap: False) + monkeypatch.setattr(svc, "host_in_maintenance", lambda snap, gen: False) monkeypatch.setattr(svc, "Snap", MagicMock()) svc.handle_network_status(_message("nic-up")) @@ -235,7 +246,7 @@ def test_start_is_retried_until_it_succeeds(self, svc, monkeypatch): def test_no_delay_after_the_last_failed_attempt(self, svc, monkeypatch): monkeypatch.setattr(svc, "start_nova_compute", MagicMock(return_value=False)) - assert svc.start_nova_compute_with_retries() is False + assert svc.start_nova_compute_with_retries(svc._outage_generation) is False delays = svc.NOVA_COMPUTE_START_ATTEMPTS - 1 assert svc.clock.elapsed == delays * svc.NOVA_COMPUTE_START_RETRY_DELAY @@ -246,7 +257,7 @@ def test_concurrent_recovery_is_ignored(self, svc, monkeypatch): monkeypatch.setattr(svc, "start_nova_compute", start) assert svc._recovery_lock.acquire(blocking=False) try: - svc.recover_node() + svc.recover_node(svc._outage_generation) finally: svc._recovery_lock.release() @@ -254,12 +265,118 @@ def test_concurrent_recovery_is_ignored(self, svc, monkeypatch): assert svc.load_state() is not None +class TestRecoveryCancellation: + """A newer nic-down must cancel a recovery that has not finished. + + handle_nic_up spawns recover_node in a background thread; that thread can sit + in the Masakari lookup or in nova-compute start retries for minutes. If a + second outage hits meanwhile, the recovery must not start nova-compute while + the network is down, and a start that already happened must be undone. + """ + + @pytest.fixture + def _actions(self, svc, monkeypatch): + self.stop = MagicMock() + self.shutdown = MagicMock() + monkeypatch.setattr(svc, "stop_nova_compute", self.stop) + monkeypatch.setattr(svc, "shutdown_vms", self.shutdown) + + def test_stale_generation_aborts_before_any_action(self, svc, monkeypatch): + """A nic-down that arrived after the nic-up invalidates the recovery outright.""" + svc.save_state({"nova_compute_stopped": True}) + start = MagicMock() + lookup = MagicMock() + monkeypatch.setattr(svc, "start_nova_compute", start) + monkeypatch.setattr(svc, "host_in_maintenance", lookup) + monkeypatch.setattr(svc, "Snap", MagicMock()) + + stale = svc._outage_generation + svc._cancel_pending_recovery() # simulates the newer nic-down + svc.recover_node(stale) + + start.assert_not_called() + lookup.assert_not_called() + assert svc.load_state() is not None + + def test_nic_down_during_masakari_lookup_cancels_recovery(self, svc, monkeypatch, _actions): + """A nic-down that arrives while recovery waits on Masakari stops the start.""" + svc.save_state({"nova_compute_stopped": True}) + start = MagicMock() + monkeypatch.setattr(svc, "start_nova_compute", start) + monkeypatch.setattr(svc, "Snap", MagicMock()) + entered = threading.Event() + monkeypatch.setattr( + svc, + "masakari_host_on_maintenance", + lambda snap: entered.set() or threading.Event().wait(5), + ) + monkeypatch.setattr(svc, "MASAKARI_ATTEMPT_TIMEOUT", 0.05) + monkeypatch.setattr(svc, "MAINTENANCE_LOOKUP_DELAY", 0.01) + + def nic_down(): + entered.wait(5) + svc.handle_network_status(_message("nic-down")) + + canceller = threading.Thread(target=nic_down) + canceller.start() + svc.recover_node(0) # generation captured before the nic-down bumped it + canceller.join(5) + + start.assert_not_called() + assert svc.load_state() is not None + assert self.stop.call_count == 1 + + def test_nic_down_after_start_undoes_the_start(self, svc, monkeypatch, _actions): + """A nic-down that arrives while the start is in flight: the start is undone.""" + svc.save_state({"nova_compute_stopped": True}) + monkeypatch.setattr(svc, "host_in_maintenance", lambda snap, gen: False) + monkeypatch.setattr(svc, "Snap", MagicMock()) + entered = threading.Event() + + def slow_start(gen): + entered.set() + threading.Event().wait(0.2) + return True + + monkeypatch.setattr(svc, "start_nova_compute", slow_start) + + def nic_down(): + entered.wait(5) + threading.Event().wait(0.05) # let the start return first + svc.handle_network_status(_message("nic-down")) + + canceller = threading.Thread(target=nic_down) + canceller.start() + svc.recover_node(0) + canceller.join(5) + + # The recovery undid the start it had completed, in addition to the + # stop the nic-down itself performed. + assert self.stop.call_count == 2 + assert svc.load_state() is not None + + def test_nic_up_after_cancelled_recovery_recovers_normally(self, svc, monkeypatch): + """After a cancel, state exists; new nic-up spawns recovery with current gen → start called, state cleared.""" + svc.save_state({"nova_compute_stopped": True}) + start = MagicMock(return_value=True) + monkeypatch.setattr(svc, "start_nova_compute", start) + monkeypatch.setattr(svc, "host_in_maintenance", lambda snap, gen: False) + monkeypatch.setattr(svc, "Snap", MagicMock()) + + svc._cancel_pending_recovery() # simulates the cancelled recovery + svc.handle_network_status(_message("nic-up")) # spawns a fresh recovery + _join_recovery_thread(svc) + + start.assert_called_once() + assert svc.load_state() is None + + class TestStartNovaCompute: def test_already_active(self, svc, monkeypatch): service = _service(True) _fake_snap(monkeypatch, svc, {"nova-compute": service}) - assert svc.start_nova_compute() is True + assert svc.start_nova_compute(svc._outage_generation) is True service.start.assert_not_called() def test_starts_and_waits_until_stable(self, svc, monkeypatch): @@ -267,7 +384,7 @@ def test_starts_and_waits_until_stable(self, svc, monkeypatch): service.start.side_effect = lambda: setattr(service, "active", True) _fake_snap(monkeypatch, svc, {"nova-compute": service}) - assert svc.start_nova_compute() is True + assert svc.start_nova_compute(svc._outage_generation) is True service.start.assert_called_once() # It did not return on the first sight of "active" @@ -284,30 +401,30 @@ def flapping(): snap.services.list.side_effect = flapping - assert svc.start_nova_compute() is False + assert svc.start_nova_compute(svc._outage_generation) is False def test_missing_service(self, svc, monkeypatch): _fake_snap(monkeypatch, svc, {}) - assert svc.start_nova_compute() is False + assert svc.start_nova_compute(svc._outage_generation) is False def test_times_out(self, svc, monkeypatch): service = _service(False) _fake_snap(monkeypatch, svc, {"nova-compute": service}) monkeypatch.setattr(svc, "NOVA_COMPUTE_START_TIMEOUT", 0) - assert svc.start_nova_compute() is False + assert svc.start_nova_compute(svc._outage_generation) is False class TestHostInMaintenance: def test_returns_masakari_answer(self, svc, monkeypatch): monkeypatch.setattr(svc, "masakari_host_on_maintenance", lambda snap: True) - assert svc.host_in_maintenance(MagicMock()) is True + assert svc.host_in_maintenance(MagicMock(), svc._outage_generation) is True def test_retries_until_masakari_answers(self, svc, monkeypatch): answers = iter([None, None, False]) monkeypatch.setattr(svc, "masakari_host_on_maintenance", lambda snap: next(answers)) - assert svc.host_in_maintenance(MagicMock()) is False + assert svc.host_in_maintenance(MagicMock(), svc._outage_generation) is False assert svc.clock.elapsed == 2 * svc.MAINTENANCE_LOOKUP_DELAY def test_assumes_not_in_maintenance_when_masakari_never_answers(self, svc, monkeypatch): @@ -316,7 +433,7 @@ def test_assumes_not_in_maintenance_when_masakari_never_answers(self, svc, monke svc, "masakari_host_on_maintenance", lambda snap: calls.append(1) or None ) - assert svc.host_in_maintenance(MagicMock()) is False + assert svc.host_in_maintenance(MagicMock(), svc._outage_generation) is False assert len(calls) > 1 # bounded: never waits longer than the budget @@ -330,7 +447,7 @@ def test_a_hung_lookup_cannot_block_recovery(self, svc, monkeypatch): monkeypatch.setattr(svc, "MAINTENANCE_LOOKUP_BUDGET", 0) try: - assert svc.host_in_maintenance(MagicMock()) is False + assert svc.host_in_maintenance(MagicMock(), svc._outage_generation) is False finally: release.set() From c623eefd8abad7a1e758445f6b7539a474e36581 Mon Sep 17 00:00:00 2001 From: Ahmad Hassan Date: Tue, 24 Nov 2026 10:47:32 +0500 Subject: [PATCH 3/3] fix(pre-evacuation): durable recovery, complete fencing, fail-closed Masakari - track fencing steps per outage generation; redelivery re-fences - persist recovery request before acking nic-up; resume after restart - retry failed recovery cycles via sweeper (cap 3, then operator) - fail closed when Masakari status is unknown; use workload region - stability window on already-active nova-compute; socket 0600 --- bin/pre-evacuation-setup-service | 424 ++++++++++---- tests/unit/test_pre_evacuation_setup.py | 705 ++++++++++++++---------- 2 files changed, 717 insertions(+), 412 deletions(-) diff --git a/bin/pre-evacuation-setup-service b/bin/pre-evacuation-setup-service index 4f39323..907c643 100755 --- a/bin/pre-evacuation-setup-service +++ b/bin/pre-evacuation-setup-service @@ -7,7 +7,7 @@ import socket import subprocess import threading import time -from typing import Dict, List, Optional +from typing import Dict, List, Optional, Union import psutil from pydantic import BaseModel, Field, field_validator @@ -27,19 +27,28 @@ NOVA_COMPUTE_POLL_SECONDS = 2 NOVA_COMPUTE_START_ATTEMPTS = 5 NOVA_COMPUTE_START_RETRY_DELAY = 30 # When Masakari cannot be asked whether the host is in maintenance, retry for a -# while and then restart nova-compute anyway: a node left down is the worse failure. +# while and then keep the node down: restarting into an unknown maintenance state +# could fight an evacuation, and the sweep retries once Masakari answers. MAINTENANCE_LOOKUP_BUDGET = 120 MAINTENANCE_LOOKUP_DELAY = 10 # Right after an outage the control plane may accept connections and never answer, # so every API call needs a timeout of its own. MASAKARI_API_TIMEOUT = 10 MASAKARI_ATTEMPT_TIMEOUT = 40 +# A failed recovery cycle keeps its request pending; the sweeper re-runs it after +# this interval so a transiently broken control plane cannot strand the node. +RECOVERY_SWEEP_INTERVAL = 60 +# After this many failed recovery cycles for one outage, stop retrying and hand +# over to the operator (recovery_status='failed'). +MAX_RECOVERY_CYCLES = 3 PROTOCOL_VERSION = "1.0" VIRSH_TIMEOUT = 3 +# Never let a stalled client block the single-threaded Unix socket listener. +CLIENT_READ_TIMEOUT = 2 -# Only one recovery may run at a time -_recovery_lock = threading.Lock() +# The recovery worker runs one cycle at a time; the running flag keeps duplicates out. +_recovery_running = False # A recovery that is still running must be abandoned when a newer nic-down arrives: # a second outage means the node must stay down, and a recovery that already # restarted nova-compute would leave it running during the outage. Every nic-down @@ -238,17 +247,16 @@ def start_nova_compute(generation: int) -> bool: logging.error("nova-compute service not found in the list of snap services") return False if service.active: - logging.info("nova-compute is already active. No action needed.") - return True - - logging.info("Starting nova-compute...") - # Hold the generation lock across the start decision, so a nic-down that - # arrives during the start-wait cannot slip past the check below. - with _state_lock: - if _outage_cancelled(generation): - logging.info("A newer nic-down arrived, not starting nova-compute") - return False - service.start() + logging.info("nova-compute is already active; verifying it stays stable...") + else: + logging.info("Starting nova-compute...") + # Hold the generation lock across the start decision, so a nic-down that + # arrives during the start-wait cannot slip past the check below. + with _state_lock: + if _outage_cancelled(generation): + logging.info("A newer nic-down arrived, not starting nova-compute") + return False + service.start() deadline = time.monotonic() + NOVA_COMPUTE_START_TIMEOUT active_since = None while time.monotonic() < deadline: @@ -311,17 +319,36 @@ def masakari_host_on_maintenance(snap: Snap) -> Optional[bool]: project_name=identity.get("project-name"), user_domain_name=identity.get("user-domain-name"), project_domain_name=identity.get("project-domain-name"), - region_name=identity.get("keystone-region-name") or identity.get("region-name"), + # Masakari runs in the workload region, not the Keystone-only region. + region_name=identity.get("region-name") or identity.get("keystone-region-name"), interface="internal", api_timeout=MASAKARI_API_TIMEOUT, cacert=str(ca_bundle) if ca_bundle.exists() else None, ) names = {fqdn.lower(), fqdn.split(".")[0].lower()} + in_masakari_segment = False for segment in conn.instance_ha.segments(): for host in conn.instance_ha.hosts(segment.uuid): if host.name and host.name.lower() in names: - return bool(host.on_maintenance) - logging.info("Host %s is not registered in any Masakari segment", fqdn) + in_masakari_segment = True + if host.on_maintenance: + logging.info( + "Host %s is on_maintenance in Masakari (operator handoff required)", + fqdn, + ) + return True + if not in_masakari_segment: + logging.info("Host %s is not registered in any Masakari segment", fqdn) + + # Masakari's host-failure workflow also disables nova-compute in Nova; do not + # restart the local daemon while Nova considers the host disabled. + for svc in conn.compute.services(binary=NOVA_COMPUTE): + if svc.host and svc.host.lower() in names and svc.status == "disabled": + logging.info( + "Nova compute service on %s is disabled (operator handoff required)", + fqdn, + ) + return True return False except Exception as e: logging.warning(f"Could not determine Masakari maintenance state: {e}") @@ -355,15 +382,17 @@ def _call_with_timeout(func, timeout: float): return outcome.get("value") -def host_in_maintenance(snap: Snap, generation: int) -> Optional[bool]: - """Return True if the node must be left alone because it is in Masakari maintenance. +def host_in_maintenance(snap: Snap, generation: int) -> Optional[Union[bool, str]]: + """Return whether the node must be left alone because of Masakari maintenance. Retries for a bounded time while Masakari cannot answer, which is expected right - after an outage. If it never answers the node is treated as not in maintenance. + after an outage. If it never answers the status stays unknown: the caller keeps + the node down (fail-safe) instead of guessing. Returns: - True or False from Masakari, or None if a newer nic-down cancelled the - recovery while the lookup was in progress. + True (maintenance or Nova-disabled operator handoff), False (safe to restart), + "unknown" (Masakari never answered - caller must not restart), or None if a + newer nic-down cancelled the recovery while the lookup was in progress. """ deadline = time.monotonic() + MAINTENANCE_LOOKUP_BUDGET while True: @@ -379,74 +408,188 @@ def host_in_maintenance(snap: Snap, generation: int) -> Optional[bool]: if _interruptible_sleep(MAINTENANCE_LOOKUP_DELAY, generation): return None logging.warning( - "Masakari did not answer within %ss, assuming the host is not in maintenance", + "Masakari maintenance status unavailable after %ss; failing closed " + "(keeping the node down until the status is known)", MAINTENANCE_LOOKUP_BUDGET, ) - return False + return "unknown" -def recover_node(generation: int) -> None: - """Undo the evacuation procedure once the network is back. +def _recover_once(generation: int, state: Dict) -> bool: + """Run one recovery attempt for the given outage generation. - Restarts nova-compute if (and only if) the procedure stopped it, unless the host - is in Masakari maintenance. The recovery is abandoned when a newer nic-down - arrives (a second outage): the node must stay down, and a start that already - happened is undone. The recorded state is kept whenever nothing was restarted, - so a later nic-up or an operator can still see what happened. + Returns: + True when this recovery attempt finished the job (state cleared, nothing + left to do). False when the attempt ended without restarting nova-compute + (cancelled, maintenance handoff, unknown maintenance status, or failed + start) and a later cycle must pick the pending request up. """ - if not _recovery_lock.acquire(blocking=False): - logging.info("Recovery already in progress, ignoring") - return - try: - state = load_state() - if state is None: - logging.info("No evacuation recorded, nothing to recover") - return - if _outage_cancelled(generation): - logging.info("A newer nic-down arrived, abandoning recovery") - return + if _outage_cancelled(generation): + logging.info("A newer nic-down arrived, abandoning recovery") + return False - maintenance = host_in_maintenance(Snap(), generation) - if maintenance is None: - logging.info("Recovery cancelled by a newer nic-down, keeping the evacuation state") - return - if maintenance: - logging.info("Host is in Masakari maintenance, leaving nova-compute untouched") - return + maintenance = host_in_maintenance(Snap(), generation) + if maintenance is None: + logging.info("Recovery cancelled by a newer nic-down, keeping the evacuation state") + return False + if maintenance is True: + with _state_lock: + if _outage_cancelled(generation): + logging.info("A newer nic-down arrived, keeping the evacuation state") + return False + current = load_state() + if current is not None and current.get("recovery_requested"): + current["recovery_requested"] = False + current["recovery_status"] = "deferred_maintenance" + try: + save_state(current) + except Exception as e: + logging.error(f"Failed to update state after maintenance check: {e}") + logging.info( + "Host requires operator handoff (Masakari maintenance or disabled Nova " + "compute service); leaving nova-compute untouched" + ) + return False + if maintenance == "unknown": + logging.warning( + "Masakari maintenance status unknown; keeping nova-compute down " + "(fail-safe). The pending recovery is retried until Masakari answers." + ) + with _state_lock: + current = load_state() + if current is not None: + current["recovery_status"] = "waiting_maintenance_status" + try: + save_state(current) + except Exception as e: + logging.error(f"Failed to update state after unknown status: {e}") + return False - if state.get("nova_compute_stopped"): - if not start_nova_compute_with_retries(generation): - if _outage_cancelled(generation): - logging.info( - "Recovery cancelled by a newer nic-down, keeping the evacuation state" - ) - else: - logging.error( - "Recovery failed, keeping the evacuation state for the next nic-up" - ) - return + if state.get("nova_compute_stopped"): + if not start_nova_compute_with_retries(generation): if _outage_cancelled(generation): - # A newer nic-down arrived while we were starting. It may have stopped - # the service behind our back, or missed it while it was still - # activating; undo the start we completed, because nova-compute must - # not run during the outage. - stop_nova_compute() logging.info( - "A newer nic-down arrived, stopped nova-compute again and " - "keeping the evacuation state" + "Recovery cancelled by a newer nic-down, keeping the evacuation state" ) - return + else: + with _state_lock: + if not _outage_cancelled(generation): + current = load_state() + if current is not None: + cycles = int(current.get("recovery_cycles", 0)) + 1 + current["recovery_cycles"] = cycles + if cycles >= MAX_RECOVERY_CYCLES: + current["recovery_requested"] = False + current["recovery_status"] = "failed" + current["failed_at"] = time.time() + logging.error( + "Recovery failed after %s cycles of %s nova-compute " + "start attempts; operator intervention required " + "(evacuation state kept with recovery_status='failed')", + cycles, + NOVA_COMPUTE_START_ATTEMPTS, + ) + else: + current["recovery_status"] = "retry_scheduled" + logging.error( + "Recovery cycle %s/%s failed; the recovery sweeper " + "will retry while the request stays pending", + cycles, + MAX_RECOVERY_CYCLES, + ) + try: + save_state(current) + except Exception as e: + logging.error(f"Failed to update state after failed start: {e}") + return False + if _outage_cancelled(generation): + # A newer nic-down arrived while we were starting. It may have stopped + # the service behind our back, or missed it while it was still + # activating; undo the start we completed, because nova-compute must + # not run during the outage. + stop_nova_compute() + logging.info( + "A newer nic-down arrived, stopped nova-compute again and " + "keeping the evacuation state" + ) + return False - with _state_lock: - if _outage_cancelled(generation): - logging.info("A newer nic-down arrived, keeping the evacuation state") + with _state_lock: + if _outage_cancelled(generation): + if state.get("nova_compute_stopped"): + stop_nova_compute() + logging.info("A newer nic-down arrived, keeping the evacuation state") + return False + clear_state() + logging.info("Evacuation procedure reversed") + return True + + +def _recovery_worker() -> None: + """Run recovery cycles until the pending request is completed or deferred.""" + global _recovery_running + try: + while True: + with _state_lock: + state = load_state() + if state is None or not state.get("recovery_requested"): + _recovery_running = False + return + generation = _outage_generation + if not _recover_once(generation, state): + # This cycle ended without completing the recovery: cancelled by a + # newer nic-down, deferred to the operator, maintenance status + # unknown, or the start attempts failed. The request stays pending + # on disk; the sweeper re-launches a worker for the next cycle. + _recovery_running = False return - clear_state() - logging.info("Evacuation procedure reversed") except Exception: logging.exception("Unexpected error during recovery") - finally: - _recovery_lock.release() + with _state_lock: + _recovery_running = False + + +def _recovery_sweeper() -> None: + """Periodically relaunch the recovery worker while a request stays pending. + + Covers the cases the sender cannot: a recovery cycle that failed and scheduled + a retry, Masakari that only answers later, or any exit path that left the + request pending without a live worker. + """ + while True: + time.sleep(RECOVERY_SWEEP_INTERVAL) + try: + with _state_lock: + state = load_state() + if state is None or not state.get("recovery_requested"): + continue + if _recovery_running: + continue + logging.info("Recovery sweeper: pending request found, running recovery") + _start_recovery_worker() + except Exception: + logging.exception("Unexpected error in the recovery sweeper") + + +def _start_recovery_worker() -> None: + """Ensure a background recovery worker is running to drain pending requests.""" + global _recovery_running + with _state_lock: + if _recovery_running: + logging.info("Recovery worker already active; it will pick up the pending request") + return + _recovery_running = True + threading.Thread(target=_recovery_worker, name="recover-node", daemon=True).start() + + +def resume_pending_recovery() -> None: + """Resume a durably recorded recovery request after a receiver restart.""" + with _state_lock: + state = load_state() + if state is None or not state.get("recovery_requested"): + return + logging.info("Found pending recovery request on startup, resuming recovery") + _start_recovery_worker() def _response(status: str, message: str) -> str: @@ -455,51 +598,86 @@ def _response(status: str, message: str) -> str: def handle_nic_down() -> str: """Stop nova-compute and shut down the VMs, recording what was done.""" - if load_state() is not None: - # A repeated nic-down while an evacuation is already recorded: either a - # duplicate message or a second outage during recovery. Cancel any recovery - # in flight and stop nova-compute again in case recovery had already started - # it. The VMs were already shut down during the first outage, and re-running - # the shutdown would kill VMs an operator restarted in the meantime. - logging.info( - "Evacuation already recorded: cancelling pending recovery and " - "re-stopping nova-compute if it was restarted" - ) + with _state_lock: _cancel_pending_recovery() - stop_nova_compute() - return _response("success", "Evacuation procedure already initiated") - - _cancel_pending_recovery() - logging.info("Network interface down detected, initiating evacuation procedure") - # Record first: if we are interrupted half way, recovery still knows what to undo. - save_state( - { - "timestamp": time.time(), - "nova_compute_stopped": nova_compute_active(), - } - ) + generation = _outage_generation + existing = load_state() + nova_was_active = nova_compute_active() + if existing is not None: + # A redelivery for this outage, or a new outage while the old record + # still exists (recovery was deferred, failed, or cancelled). Keep the + # record, re-tag it with the current outage generation, and re-fence: + # virsh only touches running domains, so re-running the shutdown + # completes an interrupted evacuation and stops anything an operator + # or a cancelled recovery restarted in the meantime. + state = dict(existing) + state["outage_generation"] = generation + state["recovery_requested"] = False + state.pop("recovery_status", None) + state["recovery_cycles"] = 0 + if nova_was_active: + state["nova_compute_stopped"] = True + state["fencing_completed"] = False + try: + save_state(state) + except Exception as e: + logging.error(f"Failed to update evacuation state on nic-down: {e}") + logging.info( + "Evacuation already recorded: re-fencing (stopping nova-compute " + "and shutting down running VMs)" + ) + else: + state = { + "timestamp": time.time(), + "outage_generation": generation, + "nova_compute_stopped": nova_was_active, + "recovery_requested": False, + "recovery_cycles": 0, + "fencing_completed": False, + } + # Record first: if we are interrupted half way, recovery still knows what to undo. + try: + save_state(state) + except Exception as e: + logging.error(f"Failed to save evacuation state on nic-down: {e}") + logging.info("Network interface down detected, initiating evacuation procedure") stop_nova_compute() shutdown_vms() + with _state_lock: + current = load_state() + if current is not None and current.get("outage_generation") == generation: + current["fencing_completed"] = True + try: + save_state(current) + except Exception as e: + logging.error(f"Failed to mark fencing completed: {e}") + return _response("success", "Evacuation procedure initiated") def handle_nic_up() -> str: - """Reverse the evacuation procedure in the background.""" - if load_state() is None: - logging.info("Network is up and no evacuation is recorded, nothing to do") - return _response("success", "No evacuation recorded, nothing to recover") + """Durably record a recovery request and ensure the background worker runs it.""" + with _state_lock: + state = load_state() + if state is None: + logging.info("Network is up and no evacuation is recorded, nothing to do") + return _response("success", "No evacuation recorded, nothing to recover") + state["recovery_requested"] = True + state["recovery_status"] = "pending" + state["recovery_cycles"] = 0 + try: + save_state(state) + except Exception as e: + logging.error(f"Failed to persist recovery request: {e}") + return _response("error", f"Failed to persist recovery request: {e}") logging.info("Network interface up detected, starting recovery") # Recovery may wait on Masakari and on nova-compute, so do not hold the sender - # (a Consul check with a short timeout) while it runs. The recovery is tagged - # with the current outage generation so a newer nic-down can cancel it. - with _state_lock: - generation = _outage_generation - threading.Thread( - target=recover_node, args=(generation,), name="recover-node", daemon=True - ).start() + # (a Consul check with a short timeout) while it runs. Because recovery_requested + # is already persisted, an active worker will pick it up instead of dropping it. + _start_recovery_worker() return _response("success", "Recovery initiated") @@ -535,6 +713,7 @@ def _send(conn, payload: str) -> None: def _handle_connection(conn) -> None: """Read one message from conn, act on it and answer.""" + conn.settimeout(CLIENT_READ_TIMEOUT) data = conn.recv(1024) if not data: return @@ -558,19 +737,34 @@ def _handle_connection(conn) -> None: _send(conn, _response("error", f"Server error: {str(e)}")) -def run_listener(): - logging.basicConfig(level=logging.INFO) +def create_listener_socket() -> socket.socket: + """Create, bind and restrict the listener socket. + The socket is owner-only (root) so unprivileged local users cannot trigger + evacuation or recovery; the consul-client health check runs as root. + """ os.makedirs(os.path.dirname(SOCKET_PATH), exist_ok=True) if os.path.exists(SOCKET_PATH): os.remove(SOCKET_PATH) - - with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as server_sock: + server_sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + old_umask = os.umask(0o177) + try: server_sock.bind(SOCKET_PATH) - os.chmod(SOCKET_PATH, 0o666) - server_sock.listen() + finally: + os.umask(old_umask) + os.chmod(SOCKET_PATH, 0o600) + server_sock.listen() + return server_sock + + +def run_listener(): + logging.basicConfig(level=logging.INFO) + + with create_listener_socket() as server_sock: logging.info(f"Listening on Unix socket: {SOCKET_PATH}") logging.info(f"Using protocol version: {PROTOCOL_VERSION}") + resume_pending_recovery() + threading.Thread(target=_recovery_sweeper, name="recovery-sweeper", daemon=True).start() while True: conn, _ = server_sock.accept() diff --git a/tests/unit/test_pre_evacuation_setup.py b/tests/unit/test_pre_evacuation_setup.py index 6fb4362..b323314 100644 --- a/tests/unit/test_pre_evacuation_setup.py +++ b/tests/unit/test_pre_evacuation_setup.py @@ -4,6 +4,8 @@ import importlib.machinery import importlib.util import json +import os +import stat import sys import threading from pathlib import Path @@ -54,13 +56,6 @@ def _message(status): return {"version": "1.0", "timestamp": 1.0, "status": status} -def _join_recovery_thread(svc, timeout=5): - """Wait for the recover-node thread spawned by handle_nic_up to finish.""" - for t in threading.enumerate(): - if t.name == "recover-node": - t.join(timeout) - - def _service(active): service = MagicMock() service.active = active @@ -74,6 +69,32 @@ def _fake_snap(monkeypatch, svc, services): return snap +def _plant(svc, **fields): + svc.save_state(fields) + + +def _state(svc): + return svc.load_state() + + +def _join_recovery_thread(svc, timeout=5): + """Wait for the recover-node thread spawned by handle_nic_up to finish.""" + for t in threading.enumerate(): + if t.name == "recover-node": + t.join(timeout) + + +class InlineThread: + """Run the thread target synchronously so tests can assert on its result.""" + + def __init__(self, target, args=(), **kwargs): + self.target = target + self.args = args + + def start(self): + self.target(*self.args) + + class TestProtocol: def test_nic_up_is_a_valid_status(self, svc): message = svc.NetworkStatusMessage.model_validate(_message("nic-up")) @@ -85,26 +106,20 @@ def test_unknown_status_is_rejected(self, svc): class TestState: - def test_load_state_missing(self, svc): - assert svc.load_state() is None - - def test_save_and_load_state(self, svc): - svc.save_state({"nova_compute_stopped": True}) - assert svc.load_state() == {"nova_compute_stopped": True} - - def test_clear_state(self, svc): - svc.save_state({"nova_compute_stopped": True}) - svc.clear_state() - svc.clear_state() # clearing twice is fine - assert svc.load_state() is None - def test_corrupt_state_is_treated_as_nova_compute_stopped(self, svc, tmp_path): (tmp_path / svc.STATE_FILENAME).write_text("{not json") state = svc.load_state() assert state["nova_compute_stopped"] is True + def test_corrupt_state_has_no_outage_generation(self, svc, tmp_path): + """A corrupt record cannot be tied to an outage: it must re-fence as a new one.""" + (tmp_path / svc.STATE_FILENAME).write_text("{not json") + assert "outage_generation" not in svc.load_state() + class TestNicDown: + """Contract 1: the record tracks fencing steps; redelivery completes missing ones.""" + @pytest.fixture(autouse=True) def _actions(self, svc, monkeypatch): self.stop = MagicMock() @@ -112,7 +127,7 @@ def _actions(self, svc, monkeypatch): monkeypatch.setattr(svc, "stop_nova_compute", self.stop) monkeypatch.setattr(svc, "shutdown_vms", self.shutdown) - def test_records_state_then_stops_and_shuts_down(self, svc, monkeypatch): + def test_fresh_outage_records_generation_then_fences(self, svc, monkeypatch): _fake_snap(monkeypatch, svc, {"nova-compute": _service(True)}) response = json.loads(svc.handle_network_status(_message("nic-down"))) @@ -120,264 +135,293 @@ def test_records_state_then_stops_and_shuts_down(self, svc, monkeypatch): assert response["status"] == "success" self.stop.assert_called_once() self.shutdown.assert_called_once() - assert svc.load_state()["nova_compute_stopped"] is True + state = _state(svc) + assert state["nova_compute_stopped"] is True + assert state["outage_generation"] == 1 + assert state["fencing_completed"] is True def test_state_is_saved_before_nova_compute_is_stopped(self, svc, monkeypatch): _fake_snap(monkeypatch, svc, {"nova-compute": _service(True)}) seen = {} - self.stop.side_effect = lambda: seen.update(state=svc.load_state()) + self.stop.side_effect = lambda: seen.update(state=_state(svc)) svc.handle_network_status(_message("nic-down")) assert seen["state"] is not None - def test_nova_compute_already_stopped_is_recorded_as_not_ours(self, svc, monkeypatch): + def test_nova_already_stopped_is_recorded_as_not_ours(self, svc, monkeypatch): _fake_snap(monkeypatch, svc, {"nova-compute": _service(False)}) svc.handle_network_status(_message("nic-down")) - assert svc.load_state()["nova_compute_stopped"] is False + assert _state(svc)["nova_compute_stopped"] is False - def test_repeated_nic_down_cancels_recovery_and_restops_nova_compute(self, svc, monkeypatch): + def test_redelivery_refences_and_retags_generation(self, svc, monkeypatch): snap = _fake_snap(monkeypatch, svc, {"nova-compute": _service(True)}) svc.handle_network_status(_message("nic-down")) - # nova-compute is now down because of us: a second message must not rewrite - # the state as "nova-compute was already stopped". - snap.services.list.return_value = {"nova-compute": _service(False)} + first = _state(svc) + # nova-compute came back (recovery or operator): the redelivery must fence again. + snap.services.list.return_value = {"nova-compute": _service(True)} response = json.loads(svc.handle_network_status(_message("nic-down"))) assert response["status"] == "success" - # The recovery is cancelled and nova-compute is stopped again in case a - # recovery had already restarted it. The VMs are not shut down a second - # time: an operator may have restarted them in the meantime. assert self.stop.call_count == 2 + assert self.shutdown.call_count == 2 + state = _state(svc) + assert state["outage_generation"] == first["outage_generation"] + 1 + assert state["nova_compute_stopped"] is True + assert state["fencing_completed"] is True + + def test_redelivery_preserves_owed_restart_when_nova_stays_down(self, svc, monkeypatch): + _fake_snap(monkeypatch, svc, {"nova-compute": _service(True)}) + svc.handle_network_status(_message("nic-down")) + _fake_snap(monkeypatch, svc, {"nova-compute": _service(False)}) + + svc.handle_network_status(_message("nic-down")) + + # nova-compute never came back: recovery still owes the restart. + assert _state(svc)["nova_compute_stopped"] is True + + def test_redelivery_cancels_a_pending_recovery(self, svc, monkeypatch): + _fake_snap(monkeypatch, svc, {"nova-compute": _service(True)}) + svc.handle_network_status(_message("nic-down")) + _plant(svc, recovery_requested=True, recovery_status="pending", recovery_cycles=1) + _fake_snap(monkeypatch, svc, {"nova-compute": _service(False)}) + + svc.handle_network_status(_message("nic-down")) + + state = _state(svc) + assert state["recovery_requested"] is False + assert "recovery_status" not in state + assert state["recovery_cycles"] == 0 + + def test_stale_record_from_an_older_outage_is_refenced(self, svc, monkeypatch): + """A record without a generation tag (planted or pre-upgrade) must not suppress fencing.""" + _fake_snap(monkeypatch, svc, {"nova-compute": _service(True)}) + _plant(svc, timestamp=1.0, nova_compute_stopped=False, fencing_completed=True) + + svc.handle_network_status(_message("nic-down")) + + self.shutdown.assert_called_once() + state = _state(svc) + assert state["outage_generation"] == 1 + assert state["fencing_completed"] is True + + def test_failed_state_write_does_not_block_fencing(self, svc, monkeypatch): + _fake_snap(monkeypatch, svc, {"nova-compute": _service(True)}) + saved = [] + + def failing_save(state): + saved.append(dict(state)) + raise OSError("disk full") + + monkeypatch.setattr(svc, "save_state", failing_save) + + response = json.loads(svc.handle_network_status(_message("nic-down"))) + + assert response["status"] == "success" + # Fencing ran although the bookkeeping write failed: the record never + # landed, so the completion mark finds no record (a later nic-down will + # re-fence from scratch). + assert self.stop.call_count == 1 assert self.shutdown.call_count == 1 - assert svc.load_state()["nova_compute_stopped"] is True + assert len(saved) == 1 + def test_each_nic_down_bumps_the_generation(self, svc, monkeypatch): + _fake_snap(monkeypatch, svc, {"nova-compute": _service(False)}) -class TestNicUp: - @pytest.fixture(autouse=True) - def _sync_thread(self, svc, monkeypatch): - """Run the recovery thread inline so tests can assert on its result.""" + svc.handle_network_status(_message("nic-down")) + assert svc._outage_generation == 1 + svc.handle_network_status(_message("nic-down")) + assert svc._outage_generation == 2 - class InlineThread: - def __init__(self, target, args=(), **kwargs): - self.target = target - self.args = args - def start(self): - self.target(*self.args) +class TestNicUp: + """Contract 2: the nic-up ack means the recovery request is durably accepted.""" + @pytest.fixture(autouse=True) + def _sync_thread(self, svc, monkeypatch): monkeypatch.setattr(svc.threading, "Thread", InlineThread) def test_nic_up_without_evacuation_does_nothing(self, svc, monkeypatch): - start = MagicMock() - monkeypatch.setattr(svc, "start_nova_compute", start) + worker = MagicMock() + monkeypatch.setattr(svc, "_start_recovery_worker", worker) response = json.loads(svc.handle_network_status(_message("nic-up"))) assert response["status"] == "success" assert "nothing to recover" in response["message"] - start.assert_not_called() + worker.assert_not_called() - def test_nic_up_restarts_nova_compute_and_clears_state(self, svc, monkeypatch): - svc.save_state({"nova_compute_stopped": True}) - start = MagicMock(return_value=True) - monkeypatch.setattr(svc, "start_nova_compute", start) - monkeypatch.setattr(svc, "host_in_maintenance", lambda snap, gen: False) - monkeypatch.setattr(svc, "Snap", MagicMock()) + def test_nic_up_persists_the_request_before_acking(self, svc, monkeypatch): + svc.save_state({"outage_generation": 1, "nova_compute_stopped": True}) + worker = MagicMock() + monkeypatch.setattr(svc, "_start_recovery_worker", worker) response = json.loads(svc.handle_network_status(_message("nic-up"))) assert response["message"] == "Recovery initiated" - start.assert_called_once() - assert svc.load_state() is None + state = _state(svc) + assert state["recovery_requested"] is True + assert state["recovery_status"] == "pending" + assert state["recovery_cycles"] == 0 + worker.assert_called_once() + + def test_failed_persist_returns_error_and_starts_no_worker(self, svc, monkeypatch): + """A request that cannot be made durable must not be acknowledged.""" + svc.save_state({"outage_generation": 1, "nova_compute_stopped": True}) + worker = MagicMock() + monkeypatch.setattr(svc, "_start_recovery_worker", worker) + monkeypatch.setattr(svc, "save_state", MagicMock(side_effect=OSError("disk full"))) - def test_nic_up_does_not_start_what_it_did_not_stop(self, svc, monkeypatch): - svc.save_state({"nova_compute_stopped": False}) - start = MagicMock() - monkeypatch.setattr(svc, "start_nova_compute", start) - monkeypatch.setattr(svc, "host_in_maintenance", lambda snap, gen: False) - monkeypatch.setattr(svc, "Snap", MagicMock()) - - svc.handle_network_status(_message("nic-up")) + response = json.loads(svc.handle_network_status(_message("nic-up"))) - start.assert_not_called() - assert svc.load_state() is None + assert response["status"] == "error" + worker.assert_not_called() - def test_nic_up_leaves_host_in_maintenance_alone(self, svc, monkeypatch): - svc.save_state({"nova_compute_stopped": True}) - start = MagicMock() - monkeypatch.setattr(svc, "start_nova_compute", start) - monkeypatch.setattr(svc, "host_in_maintenance", lambda snap, gen: True) - monkeypatch.setattr(svc, "Snap", MagicMock()) + def test_worker_drains_the_pending_request(self, svc, monkeypatch): + """A nic-up arriving while a worker is busy is picked up, never dropped.""" + svc.save_state({"outage_generation": 1, "nova_compute_stopped": True}) + once = MagicMock(side_effect=lambda gen, state: svc.clear_state() or True) + monkeypatch.setattr(svc, "_recover_once", once) svc.handle_network_status(_message("nic-up")) + _join_recovery_thread(svc) - start.assert_not_called() - assert svc.load_state() is not None - - def test_failed_start_keeps_state_for_retry(self, svc, monkeypatch): - svc.save_state({"nova_compute_stopped": True}) - start = MagicMock(return_value=False) - monkeypatch.setattr(svc, "start_nova_compute", start) - monkeypatch.setattr(svc, "host_in_maintenance", lambda snap, gen: False) - monkeypatch.setattr(svc, "Snap", MagicMock()) - - svc.handle_network_status(_message("nic-up")) + once.assert_called_once() + assert svc._recovery_running is False - assert start.call_count == svc.NOVA_COMPUTE_START_ATTEMPTS - assert svc.load_state() is not None - def test_start_is_retried_until_it_succeeds(self, svc, monkeypatch): - svc.save_state({"nova_compute_stopped": True}) - start = MagicMock(side_effect=[False, False, True]) - monkeypatch.setattr(svc, "start_nova_compute", start) - monkeypatch.setattr(svc, "host_in_maintenance", lambda snap, gen: False) +class TestRecoveryOnce: + def _run(self, svc, monkeypatch, state, maintenance, start=None): + monkeypatch.setattr(svc, "host_in_maintenance", lambda snap, gen: maintenance) monkeypatch.setattr(svc, "Snap", MagicMock()) - - svc.handle_network_status(_message("nic-up")) - - assert start.call_count == 3 - assert svc.clock.elapsed == 2 * svc.NOVA_COMPUTE_START_RETRY_DELAY - assert svc.load_state() is None - - def test_no_delay_after_the_last_failed_attempt(self, svc, monkeypatch): - monkeypatch.setattr(svc, "start_nova_compute", MagicMock(return_value=False)) - - assert svc.start_nova_compute_with_retries(svc._outage_generation) is False - - delays = svc.NOVA_COMPUTE_START_ATTEMPTS - 1 - assert svc.clock.elapsed == delays * svc.NOVA_COMPUTE_START_RETRY_DELAY - - def test_concurrent_recovery_is_ignored(self, svc, monkeypatch): - svc.save_state({"nova_compute_stopped": True}) + if start is not None: + monkeypatch.setattr(svc, "start_nova_compute_with_retries", start) + return svc._recover_once(svc._outage_generation, state) + + def test_maintenance_defers_to_the_operator(self, svc, monkeypatch): + _plant(svc, nova_compute_stopped=True, recovery_requested=True) + result = self._run(svc, monkeypatch, _state(svc), True) + + assert result is False + state = _state(svc) + assert state["recovery_requested"] is False + assert state["recovery_status"] == "deferred_maintenance" + + def test_unknown_maintenance_keeps_the_node_down(self, svc, monkeypatch): + """Masakari unreachable after the budget: never restart, keep the request pending.""" + _plant(svc, nova_compute_stopped=True, recovery_requested=True) start = MagicMock() - monkeypatch.setattr(svc, "start_nova_compute", start) - assert svc._recovery_lock.acquire(blocking=False) - try: - svc.recover_node(svc._outage_generation) - finally: - svc._recovery_lock.release() + result = self._run(svc, monkeypatch, _state(svc), "unknown", start=start) + assert result is False start.assert_not_called() - assert svc.load_state() is not None + state = _state(svc) + assert state["recovery_requested"] is True + assert state["recovery_status"] == "waiting_maintenance_status" + + def test_successful_start_clears_the_state(self, svc, monkeypatch): + _plant(svc, nova_compute_stopped=True, recovery_requested=True) + result = self._run( + svc, monkeypatch, _state(svc), False, start=MagicMock(return_value=True) + ) + assert result is True + assert _state(svc) is None -class TestRecoveryCancellation: - """A newer nic-down must cancel a recovery that has not finished. + def test_failed_cycle_schedules_a_retry(self, svc, monkeypatch): + _plant(svc, nova_compute_stopped=True, recovery_requested=True, recovery_cycles=0) + result = self._run( + svc, monkeypatch, _state(svc), False, start=MagicMock(return_value=False) + ) - handle_nic_up spawns recover_node in a background thread; that thread can sit - in the Masakari lookup or in nova-compute start retries for minutes. If a - second outage hits meanwhile, the recovery must not start nova-compute while - the network is down, and a start that already happened must be undone. - """ + assert result is False + state = _state(svc) + assert state["recovery_requested"] is True + assert state["recovery_status"] == "retry_scheduled" + assert state["recovery_cycles"] == 1 - @pytest.fixture - def _actions(self, svc, monkeypatch): - self.stop = MagicMock() - self.shutdown = MagicMock() - monkeypatch.setattr(svc, "stop_nova_compute", self.stop) - monkeypatch.setattr(svc, "shutdown_vms", self.shutdown) + def test_cycle_cap_hands_over_to_the_operator(self, svc, monkeypatch): + _plant( + svc, + nova_compute_stopped=True, + recovery_requested=True, + recovery_cycles=svc.MAX_RECOVERY_CYCLES - 1, + ) + result = self._run( + svc, monkeypatch, _state(svc), False, start=MagicMock(return_value=False) + ) - def test_stale_generation_aborts_before_any_action(self, svc, monkeypatch): - """A nic-down that arrived after the nic-up invalidates the recovery outright.""" - svc.save_state({"nova_compute_stopped": True}) - start = MagicMock() - lookup = MagicMock() - monkeypatch.setattr(svc, "start_nova_compute", start) - monkeypatch.setattr(svc, "host_in_maintenance", lookup) - monkeypatch.setattr(svc, "Snap", MagicMock()) + assert result is False + state = _state(svc) + assert state["recovery_requested"] is False + assert state["recovery_status"] == "failed" - stale = svc._outage_generation - svc._cancel_pending_recovery() # simulates the newer nic-down - svc.recover_node(stale) + def test_cancellation_after_a_completed_start_undoes_it(self, svc, monkeypatch): + stop = MagicMock() + monkeypatch.setattr(svc, "stop_nova_compute", stop) + _plant(svc, nova_compute_stopped=True, recovery_requested=True) - start.assert_not_called() - lookup.assert_not_called() - assert svc.load_state() is not None + def start_then_new_outage(gen): + svc._cancel_pending_recovery() # a newer nic-down arrives during the start + return True - def test_nic_down_during_masakari_lookup_cancels_recovery(self, svc, monkeypatch, _actions): - """A nic-down that arrives while recovery waits on Masakari stops the start.""" - svc.save_state({"nova_compute_stopped": True}) - start = MagicMock() - monkeypatch.setattr(svc, "start_nova_compute", start) - monkeypatch.setattr(svc, "Snap", MagicMock()) - entered = threading.Event() - monkeypatch.setattr( - svc, - "masakari_host_on_maintenance", - lambda snap: entered.set() or threading.Event().wait(5), - ) - monkeypatch.setattr(svc, "MASAKARI_ATTEMPT_TIMEOUT", 0.05) - monkeypatch.setattr(svc, "MAINTENANCE_LOOKUP_DELAY", 0.01) + result = self._run(svc, monkeypatch, _state(svc), False, start=start_then_new_outage) - def nic_down(): - entered.wait(5) - svc.handle_network_status(_message("nic-down")) + assert result is False + stop.assert_called_once() + assert _state(svc) is not None - canceller = threading.Thread(target=nic_down) - canceller.start() - svc.recover_node(0) # generation captured before the nic-down bumped it - canceller.join(5) - start.assert_not_called() - assert svc.load_state() is not None - assert self.stop.call_count == 1 +class TestRecoveryWorkerAndSweeper: + def test_worker_drains_until_the_state_is_gone(self, svc, monkeypatch): + _plant(svc, nova_compute_stopped=True, recovery_requested=True) + once = MagicMock(side_effect=lambda gen, state: svc.clear_state() or True) + monkeypatch.setattr(svc, "_recover_once", once) - def test_nic_down_after_start_undoes_the_start(self, svc, monkeypatch, _actions): - """A nic-down that arrives while the start is in flight: the start is undone.""" - svc.save_state({"nova_compute_stopped": True}) - monkeypatch.setattr(svc, "host_in_maintenance", lambda snap, gen: False) - monkeypatch.setattr(svc, "Snap", MagicMock()) - entered = threading.Event() + svc._recovery_worker() - def slow_start(gen): - entered.set() - threading.Event().wait(0.2) - return True + assert once.call_count == 1 + assert svc._recovery_running is False - monkeypatch.setattr(svc, "start_nova_compute", slow_start) + def test_sweeper_relaunches_the_worker_for_a_pending_request(self, svc, monkeypatch): + _plant(svc, nova_compute_stopped=True, recovery_requested=True) + starter = MagicMock() + monkeypatch.setattr(svc, "_start_recovery_worker", starter) + sleeps = [] - def nic_down(): - entered.wait(5) - threading.Event().wait(0.05) # let the start return first - svc.handle_network_status(_message("nic-down")) + def fake_sleep(seconds): + sleeps.append(seconds) + if len(sleeps) > 1: + raise KeyboardInterrupt # stop the infinite sweeper after one pass - canceller = threading.Thread(target=nic_down) - canceller.start() - svc.recover_node(0) - canceller.join(5) + monkeypatch.setattr(svc.time, "sleep", fake_sleep) + with pytest.raises(KeyboardInterrupt): + svc._recovery_sweeper() - # The recovery undid the start it had completed, in addition to the - # stop the nic-down itself performed. - assert self.stop.call_count == 2 - assert svc.load_state() is not None + starter.assert_called_once() - def test_nic_up_after_cancelled_recovery_recovers_normally(self, svc, monkeypatch): - """After a cancel, state exists; new nic-up spawns recovery with current gen → start called, state cleared.""" - svc.save_state({"nova_compute_stopped": True}) - start = MagicMock(return_value=True) - monkeypatch.setattr(svc, "start_nova_compute", start) - monkeypatch.setattr(svc, "host_in_maintenance", lambda snap, gen: False) - monkeypatch.setattr(svc, "Snap", MagicMock()) + def test_resume_on_startup_picks_up_a_pending_request(self, svc, monkeypatch): + _plant(svc, nova_compute_stopped=True, recovery_requested=True) + starter = MagicMock() + monkeypatch.setattr(svc, "_start_recovery_worker", starter) - svc._cancel_pending_recovery() # simulates the cancelled recovery - svc.handle_network_status(_message("nic-up")) # spawns a fresh recovery - _join_recovery_thread(svc) + svc.resume_pending_recovery() - start.assert_called_once() - assert svc.load_state() is None + starter.assert_called_once() class TestStartNovaCompute: - def test_already_active(self, svc, monkeypatch): + def test_already_active_must_still_prove_stability(self, svc, monkeypatch): + """A crash-looping service is briefly active between restarts: one sample is not enough.""" service = _service(True) _fake_snap(monkeypatch, svc, {"nova-compute": service}) assert svc.start_nova_compute(svc._outage_generation) is True service.start.assert_not_called() + assert svc.clock.elapsed >= svc.NOVA_COMPUTE_STABLE_SECONDS def test_starts_and_waits_until_stable(self, svc, monkeypatch): service = _service(False) @@ -387,11 +431,9 @@ def test_starts_and_waits_until_stable(self, svc, monkeypatch): assert svc.start_nova_compute(svc._outage_generation) is True service.start.assert_called_once() - # It did not return on the first sight of "active" assert svc.clock.elapsed >= svc.NOVA_COMPUTE_STABLE_SECONDS def test_crash_looping_service_is_not_counted_as_started(self, svc, monkeypatch): - """A service that is active only between crashes must not count as started.""" service = _service(False) snap = _fake_snap(monkeypatch, svc, {"nova-compute": service}) polls = iter(range(10**6)) @@ -403,103 +445,44 @@ def flapping(): assert svc.start_nova_compute(svc._outage_generation) is False - def test_missing_service(self, svc, monkeypatch): - _fake_snap(monkeypatch, svc, {}) - assert svc.start_nova_compute(svc._outage_generation) is False - def test_times_out(self, svc, monkeypatch): - service = _service(False) - _fake_snap(monkeypatch, svc, {"nova-compute": service}) - monkeypatch.setattr(svc, "NOVA_COMPUTE_START_TIMEOUT", 0) +class TestStartNovaComputeWithRetries: + def test_retries_until_it_succeeds(self, svc, monkeypatch): + start = MagicMock(side_effect=[False, False, True]) + monkeypatch.setattr(svc, "start_nova_compute", start) - assert svc.start_nova_compute(svc._outage_generation) is False + assert svc.start_nova_compute_with_retries(svc._outage_generation) is True + assert start.call_count == 3 + assert svc.clock.elapsed == 2 * svc.NOVA_COMPUTE_START_RETRY_DELAY class TestHostInMaintenance: - def test_returns_masakari_answer(self, svc, monkeypatch): - monkeypatch.setattr(svc, "masakari_host_on_maintenance", lambda snap: True) - assert svc.host_in_maintenance(MagicMock(), svc._outage_generation) is True - - def test_retries_until_masakari_answers(self, svc, monkeypatch): - answers = iter([None, None, False]) - monkeypatch.setattr(svc, "masakari_host_on_maintenance", lambda snap: next(answers)) - - assert svc.host_in_maintenance(MagicMock(), svc._outage_generation) is False - assert svc.clock.elapsed == 2 * svc.MAINTENANCE_LOOKUP_DELAY + def test_budget_exhaustion_fails_closed(self, svc, monkeypatch): + """Masakari unreachable after the budget: 'unknown', never 'not in maintenance'.""" + monkeypatch.setattr(svc, "masakari_host_on_maintenance", lambda snap: None) - def test_assumes_not_in_maintenance_when_masakari_never_answers(self, svc, monkeypatch): - calls = [] - monkeypatch.setattr( - svc, "masakari_host_on_maintenance", lambda snap: calls.append(1) or None - ) - - assert svc.host_in_maintenance(MagicMock(), svc._outage_generation) is False - - assert len(calls) > 1 - # bounded: never waits longer than the budget + assert svc.host_in_maintenance(MagicMock(), svc._outage_generation) == "unknown" assert svc.clock.elapsed <= svc.MAINTENANCE_LOOKUP_BUDGET def test_a_hung_lookup_cannot_block_recovery(self, svc, monkeypatch): - """A call that never returns is abandoned instead of hanging forever.""" release = threading.Event() monkeypatch.setattr(svc, "masakari_host_on_maintenance", lambda snap: release.wait()) monkeypatch.setattr(svc, "MASAKARI_ATTEMPT_TIMEOUT", 0.05) monkeypatch.setattr(svc, "MAINTENANCE_LOOKUP_BUDGET", 0) try: - assert svc.host_in_maintenance(MagicMock(), svc._outage_generation) is False + assert svc.host_in_maintenance(MagicMock(), svc._outage_generation) == "unknown" finally: release.set() - def test_call_with_timeout_returns_value(self, svc): - assert svc._call_with_timeout(lambda: "ok", 1) == "ok" - - def test_call_with_timeout_swallows_errors(self, svc): - def boom(): - raise RuntimeError("api down") - - assert svc._call_with_timeout(boom, 1) is None - - -class TestListenerResilience: - def test_send_ignores_a_client_that_hung_up(self, svc): - conn = MagicMock() - conn.sendall.side_effect = BrokenPipeError(32, "Broken pipe") - - svc._send(conn, "reply") # must not raise - - def test_handle_connection_survives_broken_pipe_on_reply(self, svc, monkeypatch): - conn = MagicMock() - conn.recv.return_value = json.dumps(_message("nic-up")).encode() - conn.sendall.side_effect = BrokenPipeError(32, "Broken pipe") - monkeypatch.setattr(svc, "handle_network_status", lambda data: "{}") - - svc._handle_connection(conn) # must not raise - - def test_handle_connection_survives_broken_pipe_on_error_reply(self, svc): - conn = MagicMock() - conn.recv.return_value = b"not json" - conn.sendall.side_effect = BrokenPipeError(32, "Broken pipe") - - svc._handle_connection(conn) # must not raise + def test_cancellation_during_the_lookup(self, svc, monkeypatch): + def bump_and_fail(snap): + svc._cancel_pending_recovery() + return None - def test_handle_connection_answers_a_valid_message(self, svc, monkeypatch): - conn = MagicMock() - conn.recv.return_value = json.dumps(_message("nic-up")).encode() - monkeypatch.setattr(svc, "handle_network_status", lambda data: '{"status": "success"}') + monkeypatch.setattr(svc, "masakari_host_on_maintenance", bump_and_fail) - svc._handle_connection(conn) - - conn.sendall.assert_called_once_with(b'{"status": "success"}') - - def test_handle_connection_reports_invalid_status(self, svc): - conn = MagicMock() - conn.recv.return_value = json.dumps(_message("nic-sideways")).encode() - - svc._handle_connection(conn) - - reply = json.loads(conn.sendall.call_args[0][0].decode()) - assert reply["status"] == "error" + assert svc.host_in_maintenance(MagicMock(), svc._outage_generation) is None class TestMasakariLookup: @@ -513,10 +496,8 @@ def snap(self, tmp_path): "auth-url": "http://keystone/v3", "username": "u", "password": "p", - "project-name": "services", - "user-domain-name": "service_domain", - "project-domain-name": "service_domain", - "region-name": "RegionOne", + "region-name": "workload-region", + "keystone-region-name": "keystone-region", } } return snap @@ -541,38 +522,168 @@ def test_host_on_maintenance(self, svc, snap, conn): conn.instance_ha.hosts.return_value = [self._host("compute-1.maas", True)] assert svc.masakari_host_on_maintenance(snap) is True - def test_requests_have_a_timeout(self, svc, snap, conn): + def test_uses_the_workload_region_not_the_keystone_region(self, svc, snap, conn): import sys conn.instance_ha.segments.return_value = [] svc.masakari_host_on_maintenance(snap) kwargs = sys.modules["openstack"].connect.call_args.kwargs - assert kwargs["api_timeout"] == svc.MASAKARI_API_TIMEOUT + assert kwargs["region_name"] == "workload-region" - def test_host_not_on_maintenance(self, svc, snap, conn): + def test_disabled_nova_service_requires_operator_handoff(self, svc, snap, conn): + """Masakari's host-failure workflow disables the Nova service: leave it alone.""" + nova_svc = MagicMock() + nova_svc.host = "compute-1.maas" + nova_svc.status = "disabled" conn.instance_ha.segments.return_value = [MagicMock(uuid="s1")] conn.instance_ha.hosts.return_value = [self._host("compute-1.maas", False)] - assert svc.masakari_host_on_maintenance(snap) is False + conn.compute.services.return_value = [nova_svc] - def test_matches_short_hostname(self, svc, snap, conn): - conn.instance_ha.segments.return_value = [MagicMock(uuid="s1")] - conn.instance_ha.hosts.return_value = [self._host("compute-1", True)] assert svc.masakari_host_on_maintenance(snap) is True - def test_does_not_match_a_different_host(self, svc, snap, conn): + def test_enabled_nova_service_is_not_maintenance(self, svc, snap, conn): + nova_svc = MagicMock() + nova_svc.host = "compute-1.maas" + nova_svc.status = "enabled" conn.instance_ha.segments.return_value = [MagicMock(uuid="s1")] - conn.instance_ha.hosts.return_value = [self._host("compute-10.maas", True)] - assert svc.masakari_host_on_maintenance(snap) is False + conn.instance_ha.hosts.return_value = [self._host("compute-1.maas", False)] + conn.compute.services.return_value = [nova_svc] - def test_host_not_registered(self, svc, snap, conn): - conn.instance_ha.segments.return_value = [] assert svc.masakari_host_on_maintenance(snap) is False def test_api_failure_is_unknown(self, svc, snap, conn): conn.instance_ha.segments.side_effect = RuntimeError("api down") assert svc.masakari_host_on_maintenance(snap) is None - def test_missing_credentials_is_unknown(self, svc, snap, conn): - snap.config.get_options.return_value.as_dict.return_value = {"identity": {}} - assert svc.masakari_host_on_maintenance(snap) is None + +class TestListenerResilience: + def test_send_ignores_a_client_that_hung_up(self, svc): + conn = MagicMock() + conn.sendall.side_effect = BrokenPipeError(32, "Broken pipe") + + svc._send(conn, "reply") # must not raise + + def test_handle_connection_survives_broken_pipe_on_error_reply(self, svc): + conn = MagicMock() + conn.recv.return_value = b"not json" + conn.sendall.side_effect = BrokenPipeError(32, "Broken pipe") + + svc._handle_connection(conn) # must not raise + + def test_handle_connection_answers_a_valid_message(self, svc, monkeypatch): + conn = MagicMock() + conn.recv.return_value = json.dumps(_message("nic-up")).encode() + monkeypatch.setattr(svc, "handle_network_status", lambda data: '{"status": "success"}') + + svc._handle_connection(conn) + + conn.sendall.assert_called_once_with(b'{"status": "success"}') + + +class TestSocketPermissions: + def test_listener_socket_is_owner_only(self, svc, tmp_path): + sock = svc.create_listener_socket() + try: + mode = stat.S_IMODE(os.stat(svc.SOCKET_PATH).st_mode) + assert mode == 0o600 + finally: + sock.close() + + +class TestRecoveryCancellation: + """A newer nic-down must cancel a recovery that has not finished.""" + + @pytest.fixture + def _actions(self, svc, monkeypatch): + self.stop = MagicMock() + self.shutdown = MagicMock() + monkeypatch.setattr(svc, "stop_nova_compute", self.stop) + monkeypatch.setattr(svc, "shutdown_vms", self.shutdown) + + def test_stale_generation_aborts_before_any_action(self, svc, monkeypatch): + """A nic-down that arrived after the nic-up invalidates the recovery outright.""" + svc.save_state({"nova_compute_stopped": True, "recovery_requested": True}) + start = MagicMock() + lookup = MagicMock() + monkeypatch.setattr(svc, "start_nova_compute_with_retries", start) + monkeypatch.setattr(svc, "host_in_maintenance", lookup) + monkeypatch.setattr(svc, "Snap", MagicMock()) + + stale = svc._outage_generation + svc._cancel_pending_recovery() # simulates the newer nic-down + svc._recover_once(stale, svc.load_state()) + + start.assert_not_called() + lookup.assert_not_called() + assert svc.load_state() is not None + + def test_nic_down_during_masakari_lookup_cancels_recovery(self, svc, monkeypatch, _actions): + svc.save_state({"nova_compute_stopped": True, "recovery_requested": True}) + start = MagicMock() + monkeypatch.setattr(svc, "start_nova_compute_with_retries", start) + monkeypatch.setattr(svc, "Snap", MagicMock()) + entered = threading.Event() + monkeypatch.setattr( + svc, + "masakari_host_on_maintenance", + lambda snap: entered.set() or threading.Event().wait(5), + ) + monkeypatch.setattr(svc, "MASAKARI_ATTEMPT_TIMEOUT", 0.05) + monkeypatch.setattr(svc, "MAINTENANCE_LOOKUP_DELAY", 0.01) + + def nic_down(): + entered.wait(5) + svc.handle_network_status(_message("nic-down")) + + canceller = threading.Thread(target=nic_down) + canceller.start() + svc._recover_once(0, svc.load_state()) + canceller.join(5) + + start.assert_not_called() + assert svc.load_state() is not None + assert self.stop.call_count == 1 + + def test_nic_down_after_start_undoes_the_start(self, svc, monkeypatch, _actions): + svc.save_state({"nova_compute_stopped": True, "recovery_requested": True}) + monkeypatch.setattr(svc, "host_in_maintenance", lambda snap, gen: False) + monkeypatch.setattr(svc, "Snap", MagicMock()) + entered = threading.Event() + + def slow_start(gen): + entered.set() + threading.Event().wait(0.2) + return True + + monkeypatch.setattr(svc, "start_nova_compute_with_retries", slow_start) + + def nic_down(): + entered.wait(5) + threading.Event().wait(0.05) # let the start return first + svc.handle_network_status(_message("nic-down")) + + canceller = threading.Thread(target=nic_down) + canceller.start() + svc._recover_once(0, svc.load_state()) + canceller.join(5) + + # The recovery undid the start it had completed, in addition to the + # stop the nic-down itself performed. + assert self.stop.call_count == 2 + assert svc.load_state() is not None + + def test_nic_up_after_cancelled_recovery_recovers_normally(self, svc, monkeypatch): + svc.save_state({"nova_compute_stopped": True, "recovery_requested": True}) + start = MagicMock(return_value=True) + monkeypatch.setattr(svc, "start_nova_compute_with_retries", start) + monkeypatch.setattr(svc, "host_in_maintenance", lambda snap, gen: False) + monkeypatch.setattr(svc, "Snap", MagicMock()) + monkeypatch.setattr(svc.threading, "Thread", InlineThread) + + svc._cancel_pending_recovery() # simulates the cancelled recovery + svc.handle_network_status(_message("nic-up")) # spawns a fresh worker + _join_recovery_thread(svc) + + start.assert_called_once() + assert svc.load_state() is None