|
| 1 | +""" |
| 2 | +Actuator endpoints for operations and Kubernetes deployment. |
| 3 | +
|
| 4 | +The same operational surface as the engines (the Java ``ActuatorServices`` |
| 5 | +and its Rust port), so a polyglot installation monitors every app one way: |
| 6 | +
|
| 7 | +- ``GET /info`` - application identity (name, version, description), runtime, |
| 8 | + origin id, start/current time and uptime. |
| 9 | +- ``GET /info/routes`` - the local routing table split by visibility |
| 10 | + (``routing.public`` / ``routing.private``, route -> instance count). |
| 11 | +- ``GET /env`` - selected environment variables (``show.env.variables``) and |
| 12 | + selected configuration parameters (``show.application.properties``) - |
| 13 | + opt-in lists, so secrets are never dumped wholesale (engine parity). |
| 14 | +- ``GET /health`` - runs the health-check functions listed in |
| 15 | + ``mandatory.health.dependencies`` / ``optional.health.dependencies``. |
| 16 | + All mandatory up -> ``UP`` (HTTP 200); any mandatory down -> ``DOWN`` |
| 17 | + (HTTP 400, engine parity). The outcome feeds the liveness state. |
| 18 | +- ``GET /livenessprobe`` - ``OK`` (text) while the last health outcome is |
| 19 | + good, else HTTP 400 ``Unhealthy. Please check '/health' endpoint.`` |
| 20 | +
|
| 21 | +A health-check function is a normal registered function (usually private) |
| 22 | +speaking the engines' interface contract - called through the same event bus |
| 23 | +that serves PostOffice, first with header ``type=info`` (an advisory identity |
| 24 | +map merged into its dependency entry), then with ``type=health`` (a status |
| 25 | +text or map; a non-200 reply marks the dependency down):: |
| 26 | +
|
| 27 | + @preload("demo.health", private=True) |
| 28 | + async def health(headers: dict[str, str], _body: Body) -> Body: |
| 29 | + if headers.get("type") == "info": |
| 30 | + return {"service": "demo.service", "href": "http://127.0.0.1"} |
| 31 | + return "demo.service is running fine" |
| 32 | +
|
| 33 | +Engine deltas (deliberate, wrapper-scale): no ``/info/lib`` (a wrapper app |
| 34 | +has no runtime dependency manifest - deferred on the Rust port too), no XML |
| 35 | +responses, and no 5-second info cache (dependencies are in-process |
| 36 | +functions, so the ``type=info`` lookup costs nothing). |
| 37 | +""" |
| 38 | + |
| 39 | +from __future__ import annotations |
| 40 | + |
| 41 | +import contextlib |
| 42 | +import os |
| 43 | +import platform as runtime_platform |
| 44 | +import re |
| 45 | +import time |
| 46 | +import uuid |
| 47 | +from datetime import datetime, timezone |
| 48 | +from typing import Any |
| 49 | + |
| 50 | +from aiohttp import web |
| 51 | + |
| 52 | +from .bus import DeliveryTimeout |
| 53 | +from .config import app_config |
| 54 | +from .envelope import iso_utc |
| 55 | +from .log import get_logger |
| 56 | +from .registry import FunctionRegistry |
| 57 | +from .version import __version__ |
| 58 | + |
| 59 | +log = get_logger("mercury.actuator") |
| 60 | + |
| 61 | +INFO_TIMEOUT_MS = 3000 # engine value for the advisory type=info lookup |
| 62 | +HEALTH_TIMEOUT_MS = 10000 # engine value for the type=health probe |
| 63 | +UNHEALTHY = "Unhealthy. Please check '/health' endpoint." |
| 64 | + |
| 65 | +_SPLIT = re.compile(r"[,\s]+") |
| 66 | + |
| 67 | +_origin: str | None = None |
| 68 | + |
| 69 | + |
| 70 | +def app_origin() -> str: |
| 71 | + """Unique instance id, minted once per process (the Java reference |
| 72 | + engine's format: UTC yyyyMMdd date prefix + 32-hex uuid).""" |
| 73 | + global _origin |
| 74 | + if _origin is None: |
| 75 | + _origin = time.strftime("%Y%m%d", time.gmtime()) + uuid.uuid4().hex |
| 76 | + return _origin |
| 77 | + |
| 78 | + |
| 79 | +def elapsed_time(milliseconds: float) -> str: |
| 80 | + """Human-readable duration matching the engines' rendering |
| 81 | + (including their strict boundary behavior, kept verbatim for parity).""" |
| 82 | + one_second = 1000 |
| 83 | + one_minute = 60 * one_second |
| 84 | + one_hour = 60 * one_minute |
| 85 | + one_day = 24 * one_hour |
| 86 | + remaining = int(milliseconds) |
| 87 | + parts: list[str] = [] |
| 88 | + if remaining > one_day: |
| 89 | + days = remaining // one_day |
| 90 | + parts.append(f"{days} day" if days == 1 else f"{days} days") |
| 91 | + remaining -= days * one_day |
| 92 | + if remaining > one_hour: |
| 93 | + hours = remaining // one_hour |
| 94 | + parts.append(f"{hours} hour" if hours == 1 else f"{hours} hours") |
| 95 | + remaining -= hours * one_hour |
| 96 | + if remaining > one_minute: |
| 97 | + minutes = remaining // one_minute |
| 98 | + parts.append(f"{minutes} minute" if minutes == 1 else f"{minutes} minutes") |
| 99 | + remaining -= minutes * one_minute |
| 100 | + if remaining >= one_second: |
| 101 | + seconds = remaining // one_second |
| 102 | + parts.append(f"{seconds} second" if seconds == 1 else f"{seconds} seconds") |
| 103 | + return " ".join(parts) if parts else f"{remaining} ms" |
| 104 | + |
| 105 | + |
| 106 | +def _as_list(value: Any) -> list[str]: |
| 107 | + """A comma/space-separated string (engine syntax) or a YAML list.""" |
| 108 | + if isinstance(value, list): |
| 109 | + items = [str(item).strip() for item in value] |
| 110 | + else: |
| 111 | + items = _SPLIT.split(str(value or "")) |
| 112 | + return [item for item in items if item] |
| 113 | + |
| 114 | + |
| 115 | +class Actuator: |
| 116 | + """HTTP handlers for the actuator endpoints (wired by EventApiServer).""" |
| 117 | + |
| 118 | + def __init__(self, registry: FunctionRegistry): |
| 119 | + config = app_config() |
| 120 | + self.registry = registry |
| 121 | + self.start = datetime.now(timezone.utc) |
| 122 | + self.healthy = True # liveness follows the most recent /health outcome |
| 123 | + self.app_name = config.get_property("application.name", "application") or "application" |
| 124 | + self.app_version = config.get_property("info.app.version", __version__) or __version__ |
| 125 | + self.description = (config.get_property("info.app.description", self.app_name) |
| 126 | + or self.app_name) |
| 127 | + self.required = _as_list(config.get("mandatory.health.dependencies")) |
| 128 | + self.optional = _as_list(config.get("optional.health.dependencies")) |
| 129 | + if self.required: |
| 130 | + log.info("Mandatory service dependencies - %s", self.required) |
| 131 | + if self.optional: |
| 132 | + log.info("Optional services dependencies - %s", self.optional) |
| 133 | + |
| 134 | + def _app_block(self) -> dict[str, Any]: |
| 135 | + return {"name": self.app_name, "version": self.app_version, |
| 136 | + "description": self.description} |
| 137 | + |
| 138 | + # aiohttp handlers must be coroutines - async is the framework contract |
| 139 | + # even when a handler has nothing to await |
| 140 | + async def handle_info(self, _request: web.Request) -> web.Response: |
| 141 | + now = datetime.now(timezone.utc) |
| 142 | + return web.json_response({ |
| 143 | + "app": self._app_block(), |
| 144 | + "runtime": { |
| 145 | + "language": "python", |
| 146 | + "python": runtime_platform.python_version(), |
| 147 | + "mercury_composable": __version__, |
| 148 | + }, |
| 149 | + "origin": app_origin(), |
| 150 | + "time": {"start": iso_utc(self.start), "current": iso_utc(now)}, |
| 151 | + "up_time": elapsed_time((now - self.start).total_seconds() * 1000), |
| 152 | + }) |
| 153 | + |
| 154 | + async def handle_routes(self, _request: web.Request) -> web.Response: |
| 155 | + public: dict[str, int] = {} |
| 156 | + private: dict[str, int] = {} |
| 157 | + for route, service in sorted(self.registry.routes().items()): |
| 158 | + target = private if service.private else public |
| 159 | + target[route] = service.instances |
| 160 | + return web.json_response({ |
| 161 | + "app": self._app_block(), |
| 162 | + "routing": {"public": public, "private": private}, |
| 163 | + }) |
| 164 | + |
| 165 | + async def handle_env(self, _request: web.Request) -> web.Response: |
| 166 | + config = app_config() |
| 167 | + environment = {name: os.environ.get(name, "") |
| 168 | + for name in _as_list(config.get("show.env.variables"))} |
| 169 | + properties = {name: config.get_property(name) or "" |
| 170 | + for name in _as_list(config.get("show.application.properties"))} |
| 171 | + return web.json_response({ |
| 172 | + "app": self._app_block(), |
| 173 | + "env": {"environment": environment, "properties": properties}, |
| 174 | + }) |
| 175 | + |
| 176 | + async def handle_health(self, _request: web.Request) -> web.Response: |
| 177 | + dependency: list[dict[str, Any]] = [] |
| 178 | + # optional services never affect the overall status (engine semantics) |
| 179 | + await self._check_services(self.optional, required=False, dependency=dependency) |
| 180 | + up = await self._check_services(self.required, required=True, dependency=dependency) |
| 181 | + self.healthy = up |
| 182 | + result: dict[str, Any] = {} |
| 183 | + if not dependency: |
| 184 | + result["message"] = ("Did you forget to define mandatory.health.dependencies " |
| 185 | + "or optional.health.dependencies") |
| 186 | + result["dependency"] = dependency |
| 187 | + result["status"] = "UP" if up else "DOWN" |
| 188 | + result["origin"] = app_origin() |
| 189 | + result["name"] = self.app_name |
| 190 | + return web.json_response(result, status=200 if up else 400) |
| 191 | + |
| 192 | + async def handle_livenessprobe(self, _request: web.Request) -> web.Response: |
| 193 | + if self.healthy: |
| 194 | + return web.Response(text="OK") |
| 195 | + return web.Response(status=400, text=UNHEALTHY) |
| 196 | + |
| 197 | + async def _check_services(self, services: list[str], *, required: bool, |
| 198 | + dependency: list[dict[str, Any]]) -> bool: |
| 199 | + all_up = True |
| 200 | + for route in services: |
| 201 | + entry: dict[str, Any] = {"route": route, "required": required} |
| 202 | + dependency.append(entry) |
| 203 | + service = self.registry.get(route) |
| 204 | + if service is None: |
| 205 | + all_up = False |
| 206 | + entry["status_code"] = 404 |
| 207 | + entry["message"] = f"Please check - Route {route} not found" |
| 208 | + continue |
| 209 | + bus = self.registry.bus |
| 210 | + # info is advisory - merge whatever the service reports about |
| 211 | + # itself; the health probe below decides the status |
| 212 | + with contextlib.suppress(DeliveryTimeout): |
| 213 | + info = await bus.deliver(service, {"type": "info"}, None, INFO_TIMEOUT_MS) |
| 214 | + if isinstance(info.body, dict): |
| 215 | + entry.update(info.body) |
| 216 | + try: |
| 217 | + reply = await bus.deliver(service, {"type": "health"}, None, HEALTH_TIMEOUT_MS) |
| 218 | + entry["status_code"] = reply.get_status() |
| 219 | + if isinstance(reply.body, (str, dict)): |
| 220 | + entry["message"] = reply.body |
| 221 | + if reply.has_error(): |
| 222 | + all_up = False |
| 223 | + except DeliveryTimeout as e: |
| 224 | + all_up = False |
| 225 | + entry["status_code"] = 408 |
| 226 | + entry["message"] = f"Please check - {e}" |
| 227 | + return all_up |
0 commit comments