Repository navigation
feat(observability): greffer self-health — /readyz + watchdog + log rotation #72
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 6 commits
aa83840
476b25e
8d910fe
18346fc
540e3ae
1aaaf8a
70b1b0c
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,105 @@ | ||
| """Greffer self-readiness evaluation (greffer-observability epic, Feature #3). | ||
|
|
||
| Shared by the ``/readyz`` endpoint (operator / manager visibility) and the | ||
| in-process watchdog (self-heal). The fatal-vs-degraded split is deliberate: | ||
|
|
||
| - **fatal**: the greffer is wedged and a process restart is the right fix. The | ||
| watchdog acts on a SUSTAINED fatal condition; the compose healthcheck surfaces | ||
| it for ``docker compose ps``. | ||
| - **degraded**: something is off but a restart would not help (and could | ||
| restart-loop). A greffer pending acceptance is the canonical case: it is | ||
| healthy and MUST stay up until an admin accepts it. | ||
|
|
||
| Reasons are machine-readable tokens carried by both the endpoint body and the | ||
| watchdog's logs. | ||
| """ | ||
| from __future__ import annotations | ||
|
|
||
| import logging | ||
| from dataclasses import dataclass, field | ||
|
|
||
| from fastapi import FastAPI | ||
|
|
||
| logger = logging.getLogger("greffer") | ||
|
|
||
| # Long-lived worker tasks whose death means the greffer is wedged (the loop is | ||
| # gone until a restart). ``greffer-register`` is one-shot (it exits normally | ||
| # after success) and ``greffer-reregister`` is an idle supervisor (its death | ||
| # only delays a 403-driven re-register, which is recoverable), so neither is | ||
| # fatal here. | ||
| FATAL_WORKERS = ("greffer-monitor", "greffer-crl-sync", "greffer-heartbeat") | ||
|
|
||
| # A short-timeout client dedicated to the readiness ping. The shared | ||
| # apps.utils.docker client uses the SDK default (~60s), so a HUNG (not down) | ||
| # daemon would leave the ping blocked. anyio's abandon_on_cancel stops WAITING | ||
| # on that thread but does not stop the ping, and the AnyIO worker threads are | ||
| # non-daemon, so a stuck ping keeps the process alive past the watchdog's | ||
| # graceful SIGTERM and `restart: unless-stopped` never sees a clean exit (codex | ||
| # P2 on greffon/greffer#72). A bounded client makes the ping itself fail fast. | ||
| _DOCKER_PING_TIMEOUT_SECONDS = 4 | ||
| _ping_client = None | ||
|
|
||
|
|
||
| @dataclass | ||
| class Readiness: | ||
| fatal: bool = False | ||
| reasons: list[str] = field(default_factory=list) | ||
|
|
||
| @property | ||
| def status(self) -> str: | ||
| if self.fatal: | ||
| return "fatal" | ||
| return "degraded" if self.reasons else "ready" | ||
|
|
||
|
|
||
| def _docker_ok() -> bool: | ||
| """Ping the docker daemon with a short-timeout client so a hung daemon fails | ||
| fast (see ``_DOCKER_PING_TIMEOUT_SECONDS`` above). Imported lazily so unit | ||
| tests run without the docker SDK initializing a client at import (mirrors | ||
| status_collect / the monitor).""" | ||
| global _ping_client | ||
| try: | ||
| import docker | ||
|
|
||
| if _ping_client is None: | ||
| _ping_client = docker.from_env( | ||
| timeout=_DOCKER_PING_TIMEOUT_SECONDS) | ||
| _ping_client.ping() | ||
| return True | ||
| except Exception: | ||
| # A readiness probe must treat ANY ping failure as "daemon unreachable" | ||
| # (the docker SDK raises APIError / connection / socket errors of | ||
| # several types); logging keeps it from being a silent swallow. Drop a | ||
| # possibly-broken client so the next probe rebuilds it. | ||
| logger.warning("readiness: docker ping failed", exc_info=True) | ||
| _ping_client = None | ||
| return False | ||
|
|
||
|
|
||
| def evaluate_readiness(app: FastAPI) -> Readiness: | ||
| """Compute the greffer's readiness. Pure-ish (only reads ``app.state`` and | ||
| pings docker), so the endpoint and the watchdog share one definition.""" | ||
| r = Readiness() | ||
|
|
||
| # fatal: docker daemon unreachable. Every compose op depends on it; a | ||
| # restart re-establishes the client. | ||
| if not _docker_ok(): | ||
| r.fatal = True | ||
| r.reasons.append("docker_unreachable") | ||
|
|
||
| # fatal: a long-lived worker crashed. ``task.done()`` on a forever-loop | ||
| # worker means it returned or raised; only a restart brings the loop back. | ||
| tasks = getattr(app.state, "worker_tasks", None) or {} | ||
| for name in FATAL_WORKERS: | ||
| task = tasks.get(name) | ||
| if task is not None and task.done(): | ||
| r.fatal = True | ||
| r.reasons.append(f"worker_dead:{name}") | ||
|
|
||
| # degraded: registration not yet accepted. The greffer is healthy and must | ||
| # NOT be restarted while it waits for an admin to accept it. | ||
| registered = getattr(app.state, "registered", None) | ||
| if registered is not None and not registered.is_set(): | ||
| r.reasons.append("registration_pending") | ||
|
|
||
| return r | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -139,6 +139,45 @@ def _heartbeat_interval_in_range(cls, v): | |
| # bug Codex caught before merge (greffon/greffer#17 review). | ||
| greffer_workers_enabled: bool = False | ||
|
|
||
| # Self-health watchdog (greffer-observability epic, Feature #3). The | ||
| # watchdog evaluates /readyz's FATAL conditions and, when one is sustained | ||
| # past the grace window, exits the uvicorn process so ``restart: | ||
| # unless-stopped`` recovers it (plain ``docker compose`` does NOT restart a | ||
| # container on an unhealthy healthcheck). On by default. Degraded states | ||
| # (e.g. registration pending acceptance) are NEVER fatal, so a greffer | ||
| # awaiting acceptance does not restart-loop. ``grace`` rides out transient | ||
| # docker blips. Field names carry the ``greffer_`` prefix to bind the | ||
| # documented GREFFER_WATCHDOG_* env vars (see prefix pitfall above). | ||
| greffer_watchdog_enabled: bool = True | ||
| greffer_watchdog_interval: int = 10 | ||
| greffer_watchdog_grace: int = 30 | ||
| # Upper bound on a single readiness probe so a HUNG (not just down) docker | ||
| # daemon can't block the watchdog inside the ping forever — otherwise it | ||
| # would never advance the grace clock or reach the restart for exactly the | ||
| # docker failure it exists to heal. A probe that exceeds this is itself | ||
| # treated as fatal. Keep < interval and < grace. | ||
| greffer_watchdog_probe_timeout: int = 5 | ||
|
|
||
| # Compose log rotation for the greffon INSTANCE containers the greffer | ||
| # renders (the real disk risk: an instance can log unbounded under the | ||
| # docker json-file driver's default of no rotation). Injected per service | ||
| # in ``create_compose`` unless the catalog author already set ``logging``. | ||
| # The greffer's OWN services carry static logging in docker-compose.yml. | ||
| greffer_instance_log_max_size: str = "10m" | ||
| greffer_instance_log_max_file: int = 3 | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
When an operator mistypes Useful? React with 👍 / 👎.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fixed. Added a |
||
|
|
||
| @field_validator("greffer_instance_log_max_file", mode="before") | ||
| @classmethod | ||
| def _coerce_log_max_file(cls, v): | ||
| # An operator typo (e.g. GREFFER_INSTANCE_LOG_MAX_FILE=2x) must NOT crash | ||
| # the app at pydantic parse and take down ALL instance operations over an | ||
| # optional logging knob; fall back to the default (codex P2 on | ||
| # greffon/greffer#72). Mirrors _inject_instance_log_rotation's fallback. | ||
| try: | ||
| return int(v) | ||
| except (TypeError, ValueError): | ||
| return 3 | ||
|
|
||
| logger_name: str = "greffer" | ||
|
|
||
|
|
||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,90 @@ | ||
| """Self-heal watchdog (greffer-observability epic, Feature #3). | ||
|
|
||
| Plain ``docker compose`` (non-Swarm) does NOT restart a container on an | ||
| unhealthy healthcheck; ``restart: unless-stopped`` fires only on process exit. | ||
| So the greffer watches its OWN readiness in-process and, when a FATAL condition | ||
| (see ``app/readiness.py``) is sustained past the grace window, exits the uvicorn | ||
| process so the restart policy recovers it. | ||
|
|
||
| Safety (the watchdog is on by default, so the safety lives in the logic, not a | ||
| flag): only FATAL conditions ever trigger an exit; degraded states (e.g. | ||
| registration pending acceptance) never do, so a greffer awaiting acceptance is | ||
| never restart-looped. The grace window rides out transient docker blips, and a | ||
| condition that clears before grace expires resets the timer. | ||
| """ | ||
| from __future__ import annotations | ||
|
|
||
| import asyncio | ||
| import logging | ||
| import os | ||
| import signal | ||
| import time | ||
|
|
||
| import anyio | ||
| from fastapi import FastAPI | ||
|
|
||
| from app.readiness import Readiness, evaluate_readiness | ||
| from app.settings import Settings | ||
|
|
||
| logger = logging.getLogger("greffer") | ||
|
|
||
|
|
||
| def _terminate() -> None: | ||
| """Ask uvicorn to shut down gracefully so the container's restart policy | ||
| brings up a fresh process. SIGTERM (not ``os._exit``) so lifespan teardown | ||
| and worker cancellation run rather than leaving in-flight compose ops or | ||
| file writes half-done. Isolated in a function so tests can patch it.""" | ||
| logger.critical("watchdog: sending SIGTERM to self (pid=%s) for restart", | ||
| os.getpid()) | ||
| os.kill(os.getpid(), signal.SIGTERM) | ||
|
|
||
|
|
||
| async def watchdog_worker(app: FastAPI) -> None: | ||
| settings: Settings = app.state.settings | ||
| fatal_since: float | None = None | ||
| try: | ||
| while True: | ||
| await asyncio.sleep(settings.greffer_watchdog_interval) | ||
| # Offload the docker-pinging evaluation (so a hung daemon cannot | ||
| # block the shared event loop) AND bound it: a probe that runs past | ||
| # the timeout is itself the FATAL docker-hang the watchdog exists to | ||
| # heal, so synthesize that rather than blocking here forever. | ||
| # ``abandon_on_cancel`` lets the timeout (and shutdown cancellation) | ||
| # return promptly instead of waiting on the stuck ping thread. | ||
| try: | ||
| readiness = await asyncio.wait_for( | ||
| anyio.to_thread.run_sync( | ||
| evaluate_readiness, app, abandon_on_cancel=True), | ||
| timeout=settings.greffer_watchdog_probe_timeout) | ||
|
Comment on lines
+56
to
+58
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
In the hung-Docker case this path times out by cancelling Useful? React with 👍 / 👎.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Good catch — abandon_on_cancel stops waiting on the thread but not |
||
| except asyncio.TimeoutError: | ||
| logger.warning( | ||
| "watchdog: readiness probe exceeded %ss (docker likely " | ||
| "hung); treating as FATAL", | ||
| settings.greffer_watchdog_probe_timeout) | ||
| readiness = Readiness( | ||
| fatal=True, reasons=["readiness_probe_timeout"]) | ||
| if not readiness.fatal: | ||
| if fatal_since is not None: | ||
| logger.info( | ||
| "watchdog: fatal condition cleared before grace " | ||
| "expired; not restarting") | ||
| fatal_since = None | ||
| continue | ||
| now = time.monotonic() | ||
| if fatal_since is None: | ||
| # First fatal observation: start the grace clock, do not act | ||
| # yet (rides out a transient blip). | ||
| fatal_since = now | ||
| logger.error( | ||
| "watchdog: FATAL readiness %s; will restart if sustained " | ||
| "%ss", readiness.reasons, settings.greffer_watchdog_grace) | ||
| elif now - fatal_since >= settings.greffer_watchdog_grace: | ||
| logger.critical( | ||
| "watchdog: FATAL readiness sustained >= %ss (%s); exiting " | ||
| "uvicorn for restart", settings.greffer_watchdog_grace, | ||
| readiness.reasons) | ||
| _terminate() | ||
| return | ||
| except asyncio.CancelledError: | ||
| logger.info("watchdog cancelled") | ||
| raise | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If the
greffer-reregistertask ever exits, the greffer can still become permanently stuck: on a later heartbeat 403,heartbeat_workerclearsregisteredand setsreregister_requested, but with no live supervisor consuming that event, heartbeats stay parked until the process restarts. Because this fatal-worker list excludesgreffer-reregister,/readyzremains non-fatal and the watchdog never performs the restart that would recover the supervisor.Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Agreed, and it overrides my earlier call. Added
greffer-reregisterto FATAL_WORKERS: since it is the only consumer ofreregister_requested, its death permanently wedges 403-recovery (heartbeats park withregisteredcleared and nobody to re-register), so /readyz now reports fatal and the watchdog restarts it. Added a test.