diff --git a/.env.test b/.env.test index a6cffcd..c03eb44 100644 --- a/.env.test +++ b/.env.test @@ -7,5 +7,5 @@ PYTEST_ADMIN_PASSWORD=start123 PYTEST_DEFAULT_MASTER_IMAGE=python/base PYTEST_ASYNC_MAX_RETRIES=5 PYTEST_ASYNC_RETRY_DELAY_MILLIS=500 -PYTEST_HUB_VERSION=0.20.0 +PYTEST_HUB_VERSION=0.21.0 PYTEST_RESPONSE_TIMEOUT=5 diff --git a/docs/clients_api.rst b/docs/clients_api.rst index 323ca0e..7548095 100644 --- a/docs/clients_api.rst +++ b/docs/clients_api.rst @@ -18,3 +18,11 @@ Clients .. autoclass:: flame_hub.StorageClient :members: :undoc-members: + +.. autoclass:: flame_hub.NodeStatusReporter + :members: + :inherited-members: + +.. autoclass:: flame_hub.NodeComponentStatusReporter + :members: + :inherited-members: diff --git a/docs/defaults_api.rst b/docs/defaults_api.rst index 44fa053..496b5c8 100644 --- a/docs/defaults_api.rst +++ b/docs/defaults_api.rst @@ -8,3 +8,7 @@ Defaults .. autodata:: flame_hub._defaults.DEFAULT_CORE_BASE_URL .. autodata:: flame_hub._defaults.DEFAULT_STORAGE_BASE_URL + +.. autodata:: flame_hub._defaults.DEFAULT_NODE_STATUS_INTERVAL + +.. autodata:: flame_hub._defaults.DEFAULT_NODE_STATUS_PROBE_TIMEOUT diff --git a/docs/types_api.rst b/docs/types_api.rst index 519ce88..58b2fa3 100644 --- a/docs/types_api.rst +++ b/docs/types_api.rst @@ -17,6 +17,12 @@ Types .. autoclass:: flame_hub.types.NodeType +.. autoclass:: flame_hub.types.NodeComponentStatus + +.. autoclass:: flame_hub.types.NodeComponentName + +.. autodata:: flame_hub.types.NodeComponentProbe + .. autoclass:: flame_hub.types.RegistryProjectType .. autoclass:: flame_hub.types.ProjectNodeApprovalStatus diff --git a/docs/user_guide.rst b/docs/user_guide.rst index c018c55..8152f24 100644 --- a/docs/user_guide.rst +++ b/docs/user_guide.rst @@ -107,6 +107,7 @@ Overview of implemented resources * registries * registry projects * nodes + * node components * master image groups * master images * projects @@ -366,6 +367,70 @@ token as a string. If :py:obj:`None` is passed to ``auth``, then the request is sent without any authentication. +Reporting node status +===================== + +A node reports the health of its components to the Hub. Only the node's own client may report, so authenticate with the +node's client credentials. The Hub marks a node offline after five minutes without a report. + +:py:meth:`.CoreClient.report_node_status` sends a snapshot of all components and replaces the node's component set, +while :py:meth:`.CoreClient.report_node_component_status` updates a single component and leaves the others untouched. +Read the reported state with :py:meth:`.CoreClient.find_node_components`. + +To report in the background every :py:const:`~flame_hub._defaults.DEFAULT_NODE_STATUS_INTERVAL` seconds, use +:py:class:`.NodeStatusReporter` for snapshots or :py:class:`.NodeComponentStatusReporter` for a component reporting +itself. Both report once on start and log a failed report instead of raising it. + +The status itself comes from probes that your service provides, one per component, e.g. a request to a service's +health endpoint. The SDK runs them in parallel and measures their latency. A probe that returns :any:`None` reports +``ok``; one that raises or takes longer than +:py:const:`~flame_hub._defaults.DEFAULT_NODE_STATUS_PROBE_TIMEOUT` seconds reports ``error`` with the reason, so one +unreachable service does not stop the others from being reported. Return a +:py:class:`~flame_hub.models.NodeComponentProbeResult` to report a version, a message or other details. + +.. code-block:: python + + import httpx + + import flame_hub + from flame_hub.models import NodeComponentProbeResult + + core_client = flame_hub.CoreClient( + base_url="http://localhost:3000/core/", + auth=flame_hub.auth.ClientAuth( + client_id="", + client_secret="", + base_url="http://localhost:3000/auth/", + ), + ) + + + def probe_storage(): + httpx.get("http://storage:8000/healthz", timeout=5).raise_for_status() + + + def probe_pod_orchestrator(): + info = httpx.get("http://po:8000/po/healthz", timeout=5).raise_for_status().json() + return NodeComponentProbeResult(version=info["version"]) + + + # The node adapter reports every component at once. + with flame_hub.NodeStatusReporter( + core_client, + "", + probes={ + "api": lambda: None, # the adapter itself is up while it reports + "storage": probe_storage, + "podOrchestrator": probe_pod_orchestrator, + }, + version="1.2.3", + ): + run_node() + + # A component reports only itself. + with flame_hub.NodeComponentStatusReporter(core_client, "", "storage"): + run_storage() + Handling exceptions =================== diff --git a/flame_hub/__init__.py b/flame_hub/__init__.py index c089e98..7f48653 100644 --- a/flame_hub/__init__.py +++ b/flame_hub/__init__.py @@ -6,6 +6,8 @@ "CoreClient", "HubAPIError", "StorageClient", + "NodeStatusReporter", + "NodeComponentStatusReporter", "get_field_names", "get_includable_names", "__version__", @@ -21,6 +23,7 @@ from ._exceptions import HubAPIError from ._core_client import CoreClient from ._storage_client import StorageClient +from ._node_status_reporter import NodeStatusReporter, NodeComponentStatusReporter from ._version import __version__, __version_info__ diff --git a/flame_hub/_core_client.py b/flame_hub/_core_client.py index 4792397..ef2104e 100644 --- a/flame_hub/_core_client.py +++ b/flame_hub/_core_client.py @@ -113,6 +113,7 @@ class Node(CreateNode): registry_project_id: uuid.UUID | None registry_project: t.Annotated[RegistryProject | None, IsIncludable] = None client_id: uuid.UUID | None + version: str | None created_at: datetime updated_at: datetime @@ -133,6 +134,48 @@ class NodeRegistryCredentials(CoreBaseModel): account_secret: str | None +NodeComponentStatus = t.Literal["ok", "error", "disabled"] +NodeComponentName = t.Literal["api", "ui", "podOrchestrator", "storage", "messenger", "kong", "idp", "victoriaLogs"] + + +class NodeComponentReport(CoreBaseModel): + """Status report of a single node component. Omitted (:any:`None`) counters and ``version`` keep the value stored + on the Hub, an omitted ``message`` clears it.""" + + name: NodeComponentName + status: NodeComponentStatus + version: str | None = None + message: str | None = None + latency: float | None = None + uptime: int | None = None + checks_total: int | None = None + checks_successful: int | None = None + + +class NodeComponentsReport(CoreBaseModel): + """Status snapshot of all components of a node. ``version`` is the node's deployed version.""" + + version: str | None = None + components: list[NodeComponentReport] + + +class NodeComponent(CoreBaseModel): + id: uuid.UUID + node_id: uuid.UUID + node: t.Annotated[Node | None, IsIncludable] = None + name: str + version: str | None + status: NodeComponentStatus + message: str | None + latency: float | None + uptime: int | None + checks_total: int | None + checks_successful: int | None + reported_at: datetime + created_at: datetime + updated_at: datetime + + class ClientCredentials(CoreBaseModel): id: uuid.UUID secret: str | None @@ -589,6 +632,78 @@ def update_node_client_credentials( **params, ) + def report_node_status( + self, + node_id: Node | uuid.UUID | str, + components: list[NodeComponentReport], + version: str | None = None, + **params: te.Unpack[BaseKwargs], + ) -> list[NodeComponent]: + """Report a status snapshot of all components of a node. The snapshot replaces the node's component set, so + components missing from ``components`` are removed. ``version`` sets the node's deployed version. Only the + node's own client is allowed to report.""" + + r = self._request( + "PUT", + "nodes", + node_id, + "status", + expected_code=httpx.codes.OK.value, + json=NodeComponentsReport(version=version, components=components).model_dump( + mode="json", exclude_none=True + ), + **params, + ) + + return [NodeComponent(**component) for component in r.json()["data"]] + + def report_node_component_status( + self, + node_id: Node | uuid.UUID | str, + name: NodeComponentName, + status: NodeComponentStatus, + version: str | None = None, + message: str | None = None, + latency: float | None = None, + uptime: int | None = None, + checks_total: int | None = None, + checks_successful: int | None = None, + **params: te.Unpack[BaseKwargs], + ) -> NodeComponent: + """Report the status of a single node component without touching the node's other components. Only the + node's own client is allowed to report.""" + + report = NodeComponentReport( + name=name, + status=status, + version=version, + message=message, + latency=latency, + uptime=uptime, + checks_total=checks_total, + checks_successful=checks_successful, + ) + r = self._request( + "PUT", + "nodes", + node_id, + "components", + name, + "status", + expected_code=httpx.codes.OK.value, + # The component name is taken from the path. + json=report.model_dump(mode="json", exclude_none=True, exclude={"name"}), + **params, + ) + + return NodeComponent(**r.json()["data"]) + + def get_node_components(self, **params: te.Unpack[GetKwargs]) -> ResourceListResult[NodeComponent]: + return self._get_all_resources(NodeComponent, "node-components", **params) + + def find_node_components(self, **params: te.Unpack[FindAllKwargs]) -> ResourceListResult[NodeComponent]: + return self._find_all_resources(NodeComponent, "node-components", **params) + def get_master_image_groups(self, **params: te.Unpack[GetKwargs]) -> ResourceListResult[MasterImageGroup]: return self._get_all_resources(MasterImageGroup, "master-image-groups", **params) diff --git a/flame_hub/_defaults.py b/flame_hub/_defaults.py index 3a0aff7..14a7651 100644 --- a/flame_hub/_defaults.py +++ b/flame_hub/_defaults.py @@ -6,3 +6,10 @@ DEFAULT_STORAGE_BASE_URL = "https://storage.privateaim.dev" """URL of the storage endpoints of the publicly available Hub instance.""" + +DEFAULT_NODE_STATUS_INTERVAL = 60 +"""Seconds between two status reports of a reporter. The Hub marks a node offline after five minutes without a +report, so the default tolerates a few failed reports.""" + +DEFAULT_NODE_STATUS_PROBE_TIMEOUT = 10 +"""Seconds a probe of a reporter may take before its component is reported as ``error``.""" diff --git a/flame_hub/_node_status_reporter.py b/flame_hub/_node_status_reporter.py new file mode 100644 index 0000000..60df731 --- /dev/null +++ b/flame_hub/_node_status_reporter.py @@ -0,0 +1,307 @@ +import logging +import threading +import time +import typing as t +import uuid +from collections.abc import Callable, Mapping + +import typing_extensions as te + +from flame_hub._base_client import BaseKwargs +from flame_hub._core_client import ( + CoreBaseModel, + CoreClient, + Node, + NodeComponent, + NodeComponentName, + NodeComponentReport, + NodeComponentStatus, +) +from flame_hub._defaults import DEFAULT_NODE_STATUS_INTERVAL, DEFAULT_NODE_STATUS_PROBE_TIMEOUT + +logger = logging.getLogger(__name__) + +# The Hub rejects longer messages. +_MESSAGE_MAX_LENGTH = 1024 + + +class NodeComponentProbeResult(CoreBaseModel): + """What a probe found out about a component. ``latency`` defaults to the time the probe took, in milliseconds.""" + + status: NodeComponentStatus = "ok" + version: str | None = None + message: str | None = None + latency: float | None = None + uptime: int | None = None + checks_total: int | None = None + checks_successful: int | None = None + + +NodeComponentProbe: t.TypeAlias = Callable[[], NodeComponentProbeResult | None] +"""Checks one component, e.g. by requesting its health endpoint. Returning :any:`None` means the component is ``ok``; +raising an exception means it is in ``error``, with the exception as message.""" + + +def _truncate(message: str) -> str: + return message if len(message) <= _MESSAGE_MAX_LENGTH else message[: _MESSAGE_MAX_LENGTH - 3] + "..." + + +class _ProbeCall(object): + """One probe call on its own daemon thread. A probe cannot be cancelled, and a daemon thread is not joined at + interpreter exit, so a probe that never returns does not keep the host process alive.""" + + def __init__(self, name: NodeComponentName, probe: NodeComponentProbe): + self.result: NodeComponentProbeResult | None = None + self.error: Exception | None = None + self.latency = 0.0 + self.done = threading.Event() + + threading.Thread(target=self._run, args=(probe,), name=f"node-status-probe-{name}", daemon=True).start() + + def _run(self, probe: NodeComponentProbe): + started = time.perf_counter() + + try: + self.result = probe() + except Exception as e: + self.error = e + finally: + self.latency = (time.perf_counter() - started) * 1000 + self.done.set() + + +class _ProbeRunner(object): + """Runs probes in parallel, together bounded by ``timeout`` seconds. A probe still running from an earlier call is + not started again, so a hanging probe occupies at most one thread.""" + + def __init__(self, probes: Mapping[NodeComponentName, NodeComponentProbe], timeout: float): + if not probes: + raise ValueError("'probes' must name at least one component.") + if timeout <= 0: + raise ValueError("'probe_timeout' must be greater than 0.") + + self.probes = dict(probes) + self.timeout = timeout + self._in_flight: dict[NodeComponentName, _ProbeCall] = {} + + def run(self) -> list[NodeComponentReport]: + calls: dict[NodeComponentName, _ProbeCall] = {} + busy: list[NodeComponentName] = [] + + for name, probe in self.probes.items(): + previous = self._in_flight.get(name) + + if previous is not None and not previous.done.is_set(): + busy.append(name) + continue + + calls[name] = self._in_flight[name] = _ProbeCall(name, probe) + + deadline = time.monotonic() + self.timeout + for call in calls.values(): + call.done.wait(max(0.0, deadline - time.monotonic())) + + reports = [] + + for name in self.probes: + if name in busy: + reports.append(self._error(name, "The previous probe is still running.")) + continue + + call = calls[name] + + if not call.done.is_set(): + reports.append(self._error(name, f"The probe timed out after {self.timeout} seconds.")) + continue + + if call.error is not None: + reports.append(self._error(name, f"{type(call.error).__name__}: {call.error}")) + continue + + fields = (call.result or NodeComponentProbeResult()).model_dump(by_alias=False) + if fields["latency"] is None: + fields["latency"] = call.latency + if fields["message"] is not None: + fields["message"] = _truncate(fields["message"]) + + reports.append(NodeComponentReport(name=name, **fields)) + + return reports + + @staticmethod + def _error(name: NodeComponentName, message: str) -> NodeComponentReport: + return NodeComponentReport(name=name, status="error", message=_truncate(message)) + + +ReportT = t.TypeVar("ReportT") + + +class _IntervalReporter(t.Generic[ReportT]): + """Calls :py:meth:`report` once on :py:meth:`start` and then every ``interval`` seconds on a daemon thread until + :py:meth:`stop` is called. A failed report is logged and retried on the next tick; it never raises into the host + application.""" + + def __init__(self, probes: Mapping[NodeComponentName, NodeComponentProbe], interval: float, probe_timeout: float): + if interval <= 0: + raise ValueError("'interval' must be greater than 0.") + + self.interval = interval + self._probes = _ProbeRunner(probes, probe_timeout) + # Every run owns its stop event, so a worker that outlives a timed-out stop() still ends after its report. + self._stopped = threading.Event() + self._thread: threading.Thread | None = None + + def report(self) -> ReportT: + """Run the probes and send one report. Raises if the Hub request fails.""" + raise NotImplementedError + + def report_once(self) -> ReportT | None: + """Send one report. Returns :any:`None` and logs the error if the report failed.""" + try: + return self.report() + except Exception: + logger.exception("Reporting the node status failed, retrying in %s seconds.", self.interval) + return None + + @property + def running(self) -> bool: + return self._thread is not None and self._thread.is_alive() + + def start(self): + """Start reporting in the background. Does nothing if the reporter is already running.""" + if self.running: + return + + self._stopped = threading.Event() + self._thread = threading.Thread(target=self._run, args=(self._stopped,), name=type(self).__name__, daemon=True) + self._thread.start() + + def stop(self, timeout: float | None = None): + """Stop reporting and wait up to ``timeout`` seconds for a report in flight to finish.""" + self._stopped.set() + + if self._thread is not None: + self._thread.join(timeout) + self._thread = None + + def close(self): + """Stop reporting. A probe still running is abandoned; its daemon thread does not delay process exit.""" + self.stop() + + def _run(self, stopped: threading.Event): + while not stopped.is_set(): + self.report_once() + stopped.wait(self.interval) + + def __enter__(self) -> te.Self: + self.start() + return self + + def __exit__(self, *args): + self.close() + + +class NodeStatusReporter(_IntervalReporter[list[NodeComponent]]): + """Periodically probes the components of a node and reports them together as a snapshot with + :py:meth:`.CoreClient.report_node_status`. + + The probes are written by the application, e.g. as requests to the health endpoints of the node's services. They + run in parallel; a probe that raises or exceeds ``probe_timeout`` reports its component as ``error``, so the other + components are still reported. A snapshot replaces the node's component set, so name every component the node + runs. A component reporting only itself uses :py:class:`.NodeComponentStatusReporter`. + + Parameters + ---------- + core_client : :py:class:`.CoreClient` + The client to report with. It must authenticate as the node's own client, either on its own or through + ``auth``. + node_id : :py:class:`.Node` | :py:class:`~uuid.UUID` | :py:class:`str` + The node to report for. + probes : :py:class:`~collections.abc.Mapping`\\[:py:type:`~flame_hub.types.NodeComponentName`, :py:type:`~flame_hub.types.NodeComponentProbe`] + One probe per component. + version : :py:class:`str`, optional + The node's deployed version. + interval : :py:class:`float` + Seconds between two reports, defaults to :py:const:`~flame_hub._defaults.DEFAULT_NODE_STATUS_INTERVAL`. + probe_timeout : :py:class:`float` + Seconds a probe may take, defaults to :py:const:`~flame_hub._defaults.DEFAULT_NODE_STATUS_PROBE_TIMEOUT`. + **params : :py:obj:`~typing.Unpack` [:py:class:`.BaseKwargs`] + Passed to every report request, e.g. ``auth``. + """ + + def __init__( + self, + core_client: CoreClient, + node_id: Node | uuid.UUID | str, + probes: Mapping[NodeComponentName, NodeComponentProbe], + version: str | None = None, + interval: float = DEFAULT_NODE_STATUS_INTERVAL, + probe_timeout: float = DEFAULT_NODE_STATUS_PROBE_TIMEOUT, + **params: te.Unpack[BaseKwargs], + ): + super().__init__(probes, interval, probe_timeout) + self.core_client = core_client + self.node_id = node_id + self.version = version + self.params = params + + def report(self) -> list[NodeComponent]: + return self.core_client.report_node_status( + self.node_id, self._probes.run(), version=self.version, **self.params + ) + + +class NodeComponentStatusReporter(_IntervalReporter[NodeComponent]): + """Periodically reports the status of a single node component with + :py:meth:`.CoreClient.report_node_component_status`, leaving the node's other components untouched. + + Parameters + ---------- + core_client : :py:class:`.CoreClient` + The client to report with. It must authenticate as the node's own client, either on its own or through + ``auth``. + node_id : :py:class:`.Node` | :py:class:`~uuid.UUID` | :py:class:`str` + The node the component belongs to. + name : :py:type:`~flame_hub.types.NodeComponentName` + The component to report. + probe : :py:type:`~flame_hub.types.NodeComponentProbe`, optional + Checks the component. Without a probe the component reports ``ok`` while the reporter runs. + interval : :py:class:`float` + Seconds between two reports, defaults to :py:const:`~flame_hub._defaults.DEFAULT_NODE_STATUS_INTERVAL`. + probe_timeout : :py:class:`float` + Seconds the probe may take, defaults to :py:const:`~flame_hub._defaults.DEFAULT_NODE_STATUS_PROBE_TIMEOUT`. + **params : :py:obj:`~typing.Unpack` [:py:class:`.BaseKwargs`] + Passed to every report request, e.g. ``auth``. + """ + + def __init__( + self, + core_client: CoreClient, + node_id: Node | uuid.UUID | str, + name: NodeComponentName, + probe: NodeComponentProbe | None = None, + interval: float = DEFAULT_NODE_STATUS_INTERVAL, + probe_timeout: float = DEFAULT_NODE_STATUS_PROBE_TIMEOUT, + **params: te.Unpack[BaseKwargs], + ): + super().__init__({name: probe or (lambda: None)}, interval, probe_timeout) + self.core_client = core_client + self.node_id = node_id + self.name = name + self.params = params + + def report(self) -> NodeComponent: + (component,) = self._probes.run() + + return self.core_client.report_node_component_status( + self.node_id, + component.name, + component.status, + version=component.version, + message=component.message, + latency=component.latency, + uptime=component.uptime, + checks_total=component.checks_total, + checks_successful=component.checks_successful, + **self.params, + ) diff --git a/flame_hub/models.py b/flame_hub/models.py index 480225b..9f9fcce 100644 --- a/flame_hub/models.py +++ b/flame_hub/models.py @@ -75,6 +75,10 @@ "StorageCapability", "StorageCapabilityToken", "StorageCapabilityTokenRequest", + "NodeComponent", + "NodeComponentReport", + "NodeComponentsReport", + "NodeComponentProbeResult", ] from ._core_client import ( @@ -118,7 +122,11 @@ StorageCapability, StorageCapabilityToken, StorageCapabilityTokenRequest, + NodeComponent, + NodeComponentReport, + NodeComponentsReport, ) +from ._node_status_reporter import NodeComponentProbeResult from ._storage_client import CreateBucket, Bucket, BucketFile, StorageBaseModel from ._base_client import ( UNSET, diff --git a/flame_hub/types.py b/flame_hub/types.py index 80715a0..114d476 100644 --- a/flame_hub/types.py +++ b/flame_hub/types.py @@ -6,6 +6,9 @@ "FindAllKwargs", "GetKwargs", "NodeType", + "NodeComponentStatus", + "NodeComponentName", + "NodeComponentProbe", "RegistryCommand", "IncludeParams", "FieldParams", @@ -48,6 +51,8 @@ ) from ._core_client import ( NodeType, + NodeComponentStatus, + NodeComponentName, RegistryCommand, RegistryProjectType, MasterImageCommandArgument, @@ -59,4 +64,5 @@ ProcessStatus, LogChannel, ) +from ._node_status_reporter import NodeComponentProbe from ._storage_client import ReadableBinary, UploadFile diff --git a/tests/test_core.py b/tests/test_core.py index f7e7bef..fa93e00 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -22,6 +22,8 @@ AnalysisBucketFile, StorageCapabilityTokenRequest, StorageCapability, + NodeComponent, + NodeComponentReport, ) from tests.helpers import next_random_string, next_uuid, assert_eventually, next_random_number @@ -88,6 +90,16 @@ def node_includables(): return get_includable_names(Node) +@pytest.fixture() +def node_component(core_client, node, node_client_auth): + return core_client.report_node_component_status(node, "storage", "ok", auth=node_client_auth) + + +@pytest.fixture(scope="session") +def node_component_includables(): + return get_includable_names(NodeComponent) + + @pytest.fixture() def project(core_client, master_image): new_project = core_client.create_project(next_random_string()) @@ -364,6 +376,74 @@ def test_update_node_client_credentials(core_client, node): assert new_credentials.secret == new_secret +def test_report_node_status(core_client, node, node_client_auth): + version = "1.2.3" + components = core_client.report_node_status( + node, + [ + NodeComponentReport(name="storage", status="ok", latency=1.5, checks_total=4, checks_successful=3), + NodeComponentReport(name="messenger", status="error", message="connection refused"), + ], + version=version, + auth=node_client_auth, + ) + + assert {c.name: c.status for c in components} == {"storage": "ok", "messenger": "error"} + assert all(c.node_id == node.id for c in components) + + node_get = core_client.get_node(node.id) + assert node_get.version == version + assert node_get.online is True + + # A snapshot replaces the component set. + components = core_client.report_node_status( + node, [NodeComponentReport(name="storage", status="disabled")], auth=node_client_auth + ) + + assert [(c.name, c.status) for c in components] == [("storage", "disabled")] + assert [c.name for c in core_client.find_node_components(filter={"node_id": node.id})] == ["storage"] + + +def test_report_node_component_status(core_client, node, node_client_auth, node_component): + component = core_client.report_node_component_status( + node, + node_component.name, + "error", + message="disk full", + uptime=60, + auth=node_client_auth, + ) + + assert component.id == node_component.id + assert component.status == "error" + assert component.message == "disk full" + assert component.uptime == 60 + assert component.reported_at >= node_component.reported_at + + +def test_report_node_status_requires_node_client(core_client, node): + with pytest.raises(HubAPIError) as e: + core_client.report_node_component_status(node, "storage", "ok") + + assert e.value.error_response.status_code == 403 + + +def test_get_node_components(core_client, node_component, node_component_includables): + components_get = core_client.get_node_components(include=node_component_includables) + + assert len(components_get) > 0 + assert all(includable in c.model_fields_set for c in components_get for includable in node_component_includables) + + +def test_find_node_components(core_client, node_component, node_component_includables): + components_find = core_client.find_node_components( + filter={"node_id": node_component.node_id}, include=node_component_includables + ) + + assert [c.id for c in components_find] == [node_component.id] + assert all(includable in c.model_fields_set for c in components_find for includable in node_component_includables) + + def test_get_master_image(core_client, master_image): assert master_image == core_client.get_master_image(master_image.id) diff --git a/tests/test_node_status_reporter.py b/tests/test_node_status_reporter.py new file mode 100644 index 0000000..ebf8e7c --- /dev/null +++ b/tests/test_node_status_reporter.py @@ -0,0 +1,275 @@ +import json +import subprocess +import sys +import threading +import uuid +from datetime import datetime, timezone + +import httpx2 as httpx +import pytest + +from flame_hub import CoreClient, NodeStatusReporter, NodeComponentStatusReporter +from flame_hub.models import NodeComponentProbeResult + +NODE_ID = str(uuid.uuid4()) + + +def component_json(name: str, status: str) -> dict: + now = datetime.now(timezone.utc).isoformat() + return { + "id": str(uuid.uuid4()), + "nodeId": NODE_ID, + "name": name, + "version": None, + "status": status, + "message": None, + "latency": None, + "uptime": None, + "checksTotal": None, + "checksSuccessful": None, + "reportedAt": now, + "createdAt": now, + "updatedAt": now, + } + + +class FakeHub: + """Records every status request and answers like the Hub, or with 503 while ``failing`` is set.""" + + def __init__(self): + self.requests: list[httpx.Request] = [] + self.failing = False + self.reported = threading.Event() + + def handle(self, request: httpx.Request) -> httpx.Response: + self.requests.append(request) + self.reported.set() + + if self.failing: + return httpx.Response( + 503, json={"message": "unavailable", "statusCode": 503, "code": "service_unavailable"} + ) + + body = json.loads(request.content) + + if request.url.path.endswith(f"/nodes/{NODE_ID}/status"): + data = [component_json(c["name"], c["status"]) for c in body["components"]] + return httpx.Response(200, json={"data": data, "meta": {"total": len(data)}}) + + name = request.url.path.split("/")[-2] + return httpx.Response(200, json={"data": component_json(name, body["status"]), "meta": {}}) + + def client(self) -> CoreClient: + return CoreClient(client=httpx.Client(base_url="http://hub/core/", transport=httpx.MockTransport(self.handle))) + + +@pytest.fixture() +def hub(): + return FakeHub() + + +def test_snapshot_reporter_sends_version_and_probed_components(hub): + reporter = NodeStatusReporter( + hub.client(), + NODE_ID, + probes={ + "storage": lambda: NodeComponentProbeResult(latency=1.5, version="0.5.1"), + "messenger": lambda: None, + }, + version="1.2.3", + ) + + components = reporter.report() + + request = hub.requests[-1] + body = json.loads(request.content) + assert request.method == "PUT" + assert request.url.path == f"/core/nodes/{NODE_ID}/status" + assert body["version"] == "1.2.3" + assert body["components"][0] == {"name": "storage", "status": "ok", "latency": 1.5, "version": "0.5.1"} + # Without an own latency, the probe's duration is reported. + assert body["components"][1]["name"] == "messenger" + assert body["components"][1]["status"] == "ok" + assert body["components"][1]["latency"] >= 0 + assert [(c.name, c.status) for c in components] == [("storage", "ok"), ("messenger", "ok")] + reporter.close() + + +def test_raising_probe_reports_error_and_others_still_report(hub): + def probe_storage(): + raise ConnectionError("connection refused") + + reporter = NodeStatusReporter(hub.client(), NODE_ID, probes={"storage": probe_storage, "messenger": lambda: None}) + + reporter.report() + + storage, messenger = json.loads(hub.requests[-1].content)["components"] + assert storage == {"name": "storage", "status": "error", "message": "ConnectionError: connection refused"} + assert messenger["status"] == "ok" + reporter.close() + + +def test_slow_probe_times_out_and_is_not_started_twice(hub): + release = threading.Event() + starts = [] + + def probe_storage(): + starts.append(1) + release.wait(2) + + reporter = NodeStatusReporter( + hub.client(), NODE_ID, probes={"storage": probe_storage, "messenger": lambda: None}, probe_timeout=0.05 + ) + + reporter.report() + storage, messenger = json.loads(hub.requests[-1].content)["components"] + assert storage["status"] == "error" + assert "timed out" in storage["message"] + assert messenger["status"] == "ok" + + reporter.report() + storage, _ = json.loads(hub.requests[-1].content)["components"] + assert storage["status"] == "error" + assert "still running" in storage["message"] + assert len(starts) == 1 + + release.set() + reporter.close() + + +def test_long_message_is_truncated(hub): + def probe_storage(): + raise RuntimeError("x" * 5000) + + reporter = NodeStatusReporter(hub.client(), NODE_ID, probes={"storage": probe_storage}) + + reporter.report() + + (storage,) = json.loads(hub.requests[-1].content)["components"] + assert len(storage["message"]) == 1024 + reporter.close() + + +def test_component_reporter_sends_name_in_path_only(hub): + reporter = NodeComponentStatusReporter( + hub.client(), + NODE_ID, + "storage", + probe=lambda: NodeComponentProbeResult(status="error", message="disk full", latency=2.0), + ) + + component = reporter.report() + + request = hub.requests[-1] + assert request.method == "PUT" + assert request.url.path == f"/core/nodes/{NODE_ID}/components/storage/status" + assert json.loads(request.content) == {"status": "error", "message": "disk full", "latency": 2.0} + assert component.name == "storage" + assert component.status == "error" + reporter.close() + + +def test_component_reporter_without_probe_reports_ok(hub): + reporter = NodeComponentStatusReporter(hub.client(), NODE_ID, "storage") + + reporter.report() + + assert json.loads(hub.requests[-1].content)["status"] == "ok" + reporter.close() + + +def test_failed_report_is_logged_not_raised(hub, caplog): + hub.failing = True + reporter = NodeStatusReporter(hub.client(), NODE_ID, probes={"storage": lambda: None}) + + assert reporter.report_once() is None + assert "Reporting the node status failed" in caplog.text + reporter.close() + + +def test_reporter_reports_on_start_and_repeats_until_stopped(hub): + hub.failing = True # a failure must not end the loop + reporter = NodeComponentStatusReporter(hub.client(), NODE_ID, "storage", interval=0.01) + + with reporter: + assert reporter.running + assert hub.reported.wait(1) + for _ in range(100): + if len(hub.requests) >= 3: + break + hub.reported.clear() + hub.reported.wait(1) + + assert not reporter.running + assert len(hub.requests) >= 3 + + count = len(hub.requests) + hub.reported.clear() + assert not hub.reported.wait(0.05) + assert len(hub.requests) == count + + +def test_start_is_idempotent(hub): + reporter = NodeStatusReporter(hub.client(), NODE_ID, probes={"storage": lambda: None}, interval=60) + reporter.start() + thread = reporter._thread + reporter.start() + + assert reporter._thread is thread + reporter.close() + + +def test_restart_after_timed_out_stop_runs_one_loop(hub): + release = threading.Event() + calls = [] + + def probe(): + calls.append(threading.current_thread()) + release.wait(1) + + reporter = NodeComponentStatusReporter(hub.client(), NODE_ID, "storage", probe=probe, interval=0.01) + reporter.start() + while not calls: + threading.Event().wait(0.001) + loop = reporter._thread + + reporter.stop(timeout=0) # the old report is still in flight + reporter.start() + release.set() + loop.join(2) + + assert not loop.is_alive() + reporter.close() + + +@pytest.mark.parametrize( + "kwargs", + [{"interval": 0}, {"interval": -1}, {"probe_timeout": 0}, {"probes": {}}], +) +def test_invalid_arguments(hub, kwargs): + with pytest.raises(ValueError): + NodeStatusReporter(hub.client(), NODE_ID, **({"probes": {"storage": lambda: None}} | kwargs)) + + +HUNG_PROBE_SCRIPT = """ +import threading +import httpx2 as httpx +from flame_hub import CoreClient, NodeStatusReporter + +def handle(request): + return httpx.Response(503, json={"message": "unavailable", "statusCode": 503, "code": "service_unavailable"}) + +client = CoreClient(client=httpx.Client(base_url="http://hub/core/", transport=httpx.MockTransport(handle))) +reporter = NodeStatusReporter(client, "n1", probes={"storage": threading.Event().wait}, probe_timeout=0.05) +reporter.report_once() +reporter.close() +print("closed") +""" + + +def test_hung_probe_does_not_block_process_exit(): + # A probe that never returns must not keep the interpreter alive at exit. + result = subprocess.run([sys.executable, "-c", HUNG_PROBE_SCRIPT], capture_output=True, text=True, timeout=30) + + assert result.returncode == 0, result.stderr + assert result.stdout.strip() == "closed"