Skip to content
4 changes: 4 additions & 0 deletions app/lifespan.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,10 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
yield
return
tasks = start_workers(app)
# Expose the task handles by name so /readyz and the watchdog can tell a
# live long-lived worker from a crashed one (Feature #3). Set synchronously
# before the first ``yield``, so it is populated before any task runs.
app.state.worker_tasks = {t.get_name(): t for t in tasks}
logger.info("started %d background workers", len(tasks))
try:
yield
Expand Down
105 changes: 105 additions & 0 deletions app/readiness.py
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")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Treat reregister supervisor death as fatal

If the greffer-reregister task ever exits, the greffer can still become permanently stuck: on a later heartbeat 403, heartbeat_worker clears registered and sets reregister_requested, but with no live supervisor consuming that event, heartbeats stay parked until the process restarts. Because this fatal-worker list excludes greffer-reregister, /readyz remains non-fatal and the watchdog never performs the restart that would recover the supervisor.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

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-reregister to FATAL_WORKERS: since it is the only consumer of reregister_requested, its death permanently wedges 403-recovery (heartbeats park with registered cleared and nobody to re-register), so /readyz now reports fatal and the watchdog restarts it. Added a test.


# 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
47 changes: 46 additions & 1 deletion app/routers/health.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
from __future__ import annotations

from fastapi import APIRouter, Request
import asyncio

import anyio
from fastapi import APIRouter, Depends, Request
from fastapi.responses import JSONResponse

from app.auth import require_token
from app.readiness import Readiness, evaluate_readiness

router = APIRouter()

Expand All @@ -21,3 +28,41 @@ async def healthz(request: Request) -> dict[str, str]:
"id": request.app.state.settings.greffer_id,
"status": "ok",
}


@router.get("/readyz", dependencies=[Depends(require_token)])
async def readyz(request: Request) -> JSONResponse:
"""Readiness with a fatal-vs-degraded split (greffer-observability epic,
Feature #3).

Returns **503** on a FATAL condition (docker daemon unreachable, a
long-lived worker dead) so the compose healthcheck can surface it; **200**
otherwise, including when ``degraded`` (a greffer pending acceptance is
healthy and must not be flapped). The ``reasons`` list is machine-readable.

Auth is ``X-GREFFON-TOKEN`` (same as the controller routes) because this
endpoint is publicly routed like ``/healthz`` and would otherwise leak the
greffer's internal state. The in-process watchdog shares
``evaluate_readiness`` so the endpoint and the self-heal decision can never
drift. ``/healthz`` stays liveness-only (a greffer-cli contract).
"""
# ``evaluate_readiness`` pings docker (a blocking SDK call). Offload it so a
# hung daemon can't stall the uvicorn event loop (mirrors the heartbeat
# worker's anyio.to_thread offload), and bound it so a HUNG daemon reports
# fatal promptly instead of holding the request open.
timeout = request.app.state.settings.greffer_watchdog_probe_timeout
try:
r = await asyncio.wait_for(
anyio.to_thread.run_sync(
evaluate_readiness, request.app, abandon_on_cancel=True),
timeout=timeout)
except asyncio.TimeoutError:
r = Readiness(fatal=True, reasons=["readiness_probe_timeout"])
return JSONResponse(
{
"id": request.app.state.settings.greffer_id,
"status": r.status,
"reasons": r.reasons,
},
status_code=503 if r.fatal else 200,
)
39 changes: 39 additions & 0 deletions app/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Keep malformed log-rotation count from aborting startup

When an operator mistypes GREFFER_INSTANCE_LOG_MAX_FILE (for example 2x), pydantic parses this new Settings field before the app boots and raises a validation error. That bypasses the fallback in _inject_instance_log_rotation() that was meant to default malformed values to 3, so an optional logging knob can crash the greffer and prevent all instance operations. Make this field tolerant/string or add a validator with the same fallback.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed. Added a field_validator(mode="before") on greffer_instance_log_max_file that coerces a malformed value (e.g. 2x) to the default 3, so pydantic no longer raises at startup and an optional logging knob cannot crash the greffer / block instance operations. Mirrors the inject-side fallback; added tests.


@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"


Expand Down
9 changes: 8 additions & 1 deletion app/workers/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,19 +29,26 @@
from app.workers.heartbeat import heartbeat_worker
from app.workers.monitor import monitor_worker
from app.workers.register import register_worker, reregister_worker
from app.workers.watchdog import watchdog_worker

logger = logging.getLogger("greffer")


def start_workers(app: FastAPI) -> list[asyncio.Task]:
return [
tasks = [
asyncio.create_task(register_worker(app), name="greffer-register"),
asyncio.create_task(monitor_worker(app), name="greffer-monitor"),
asyncio.create_task(crl_sync_worker(app), name="greffer-crl-sync"),
asyncio.create_task(heartbeat_worker(app), name="greffer-heartbeat"),
asyncio.create_task(
reregister_worker(app), name="greffer-reregister"),
]
# Self-heal watchdog (Feature #3), on by default. Appended after the others
# so their tasks exist by the time it first evaluates readiness.
if app.state.settings.greffer_watchdog_enabled:
tasks.append(asyncio.create_task(
watchdog_worker(app), name="greffer-watchdog"))
return tasks


async def stop_workers(tasks: list[asyncio.Task]) -> None:
Expand Down
90 changes: 90 additions & 0 deletions app/workers/watchdog.py
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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Bound the Docker ping instead of abandoning it

In the hung-Docker case this path times out by cancelling run_sync, but abandon_on_cancel=True does not stop client.ping(); it leaves the AnyIO worker thread blocked. Because _terminate() later sends a graceful SIGTERM rather than killing the process, those stuck non-daemon threads can keep the PID alive, so Docker's restart: unless-stopped never gets a clean process exit for the exact failure this watchdog is meant to heal. Put a real timeout on the Docker ping or run the probe in something killable before treating the timeout as self-healed.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch — abandon_on_cancel stops waiting on the thread but not client.ping(), and AnyIO worker threads are non-daemon, so a stuck ping would keep the PID alive past the graceful SIGTERM. Fixed at the source: the readiness ping now uses its own short-timeout client (docker.from_env(timeout=4)) so the ping itself fails fast and the thread completes, letting graceful SIGTERM produce a clean exit for restart:unless-stopped. The wait_for bound stays as a secondary net.

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
33 changes: 33 additions & 0 deletions apps/utils/docker/compose.py
Original file line number Diff line number Diff line change
Expand Up @@ -518,6 +518,38 @@ def _compute_instance_context(greffon_info):
return greffon_info


def _inject_instance_log_rotation(compose):
"""Cap per-container log disk on the greffon INSTANCE containers
(greffer-observability epic, Feature #3). Docker's json-file driver does
NOT rotate by default, so a chatty instance can fill the operator's disk.
Set ``max-size``/``max-file`` on every service that has not already declared
its own ``logging`` (a catalog author's explicit choice wins). Values come
from GREFFER_INSTANCE_LOG_MAX_SIZE / _MAX_FILE (read via os.getenv here,
matching this module's env style; the same vars bind Settings fields)."""
services = (compose or {}).get('services')
if not isinstance(services, dict):
return
max_size = os.getenv('GREFFER_INSTANCE_LOG_MAX_SIZE', '10m')
# ``max-file`` must be an integer string; coerce with a fallback so a
# malformed GREFFER_INSTANCE_LOG_MAX_FILE does not write an invalid value
# into EVERY rendered instance compose and break every greffon start.
raw_max_file = os.getenv('GREFFER_INSTANCE_LOG_MAX_FILE', '3')
try:
max_file = str(int(raw_max_file))
except (TypeError, ValueError):
logger.warning(
'invalid GREFFER_INSTANCE_LOG_MAX_FILE=%r; using default 3',
raw_max_file)
max_file = '3'
for service in services.values():
if not isinstance(service, dict) or 'logging' in service:
continue
service['logging'] = {
'driver': 'json-file',
'options': {'max-size': max_size, 'max-file': str(max_file)},
}


def create_compose(compose, greffon_info):
greffon_path = os.path.join(os.getenv('GREFFON_PATH', '/data'), greffon_info['id'])
if not os.path.exists(greffon_path):
Expand All @@ -531,6 +563,7 @@ def create_compose(compose, greffon_info):
# values would otherwise be templated `{{ smtp.host }}` strings.
greffon_info = _compute_integrations_context(greffon_info)
_delete_unset_integration_env_keys(compose, greffon_info)
_inject_instance_log_rotation(compose)
t = Template(yaml.dump(compose))
compose_file = t.render(**greffon_info)
with open(os.path.join(greffon_path, 'docker-compose.yml'), 'w') as temp_file:
Expand Down
Loading
Loading