Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .env.test
Original file line number Diff line number Diff line change
Expand Up @@ -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
8 changes: 8 additions & 0 deletions docs/clients_api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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:
4 changes: 4 additions & 0 deletions docs/defaults_api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
6 changes: 6 additions & 0 deletions docs/types_api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
65 changes: 65 additions & 0 deletions docs/user_guide.rst
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ Overview of implemented resources
* registries
* registry projects
* nodes
* node components
* master image groups
* master images
* projects
Expand Down Expand Up @@ -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="<node client id>",
client_secret="<node 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,
"<node id>",
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, "<node id>", "storage"):
run_storage()

Handling exceptions
===================

Expand Down
3 changes: 3 additions & 0 deletions flame_hub/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
"CoreClient",
"HubAPIError",
"StorageClient",
"NodeStatusReporter",
"NodeComponentStatusReporter",
"get_field_names",
"get_includable_names",
"__version__",
Expand All @@ -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__


Expand Down
115 changes: 115 additions & 0 deletions flame_hub/_core_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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
Expand Down Expand Up @@ -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)

Expand Down
7 changes: 7 additions & 0 deletions flame_hub/_defaults.py
Original file line number Diff line number Diff line change
Expand Up @@ -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``."""
Loading