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
88 changes: 88 additions & 0 deletions app/readiness.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
"""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.



@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. Imported lazily so unit tests run without the
docker SDK initializing its ``from_env()`` client at import (mirrors
status_collect / the monitor)."""
try:
from apps.utils.docker.base import client

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.
logger.warning("readiness: docker ping failed", exc_info=True)
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
33 changes: 32 additions & 1 deletion app/routers/health.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
from __future__ import annotations

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

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

router = APIRouter()

Expand All @@ -21,3 +25,30 @@ 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).
"""
r = evaluate_readiness(request.app)
return JSONResponse(
{
"id": request.app.state.settings.greffer_id,
"status": r.status,
"reasons": r.reasons,
},
status_code=503 if r.fatal else 200,
)
21 changes: 21 additions & 0 deletions app/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,27 @@ 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

# 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.


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
72 changes: 72 additions & 0 deletions app/workers/watchdog.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
"""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

from fastapi import FastAPI

from app.readiness import 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)
readiness = evaluate_readiness(app)
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
23 changes: 23 additions & 0 deletions apps/utils/docker/compose.py
Original file line number Diff line number Diff line change
Expand Up @@ -518,6 +518,28 @@ 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 = os.getenv('GREFFER_INSTANCE_LOG_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 +553,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
36 changes: 36 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -1,9 +1,22 @@
version: "3.8"

# Log rotation for the greffer's OWN containers (greffer-observability epic,
# Feature #3). Docker's json-file driver does not rotate by default; without a
# cap, uvicorn/nginx/rathole logs grow unbounded on the operator's box. The
# greffon INSTANCE containers the greffer renders get the same treatment via
# create_compose's _inject_instance_log_rotation (the larger disk risk).
x-logging: &default-logging
driver: json-file
options:
max-size: "10m"
max-file: "3"

services:
greffer:
build: .
image: &app app
restart: unless-stopped
logging: *default-logging
networks:
- internal
# Run pending ops migrations BEFORE uvicorn binds so they can't race
Expand Down Expand Up @@ -46,9 +59,31 @@ services:
# picks up changes. Always mounted so proxy-mode deployments
# don't need a separate compose layer.
- rathole-client-config:/config
# Self-health visibility (Feature #3). Targets /readyz so `docker compose
# ps` shows when the greffer is wedged. This is NOT the restart trigger:
# plain compose does not restart on `unhealthy`; the in-process watchdog
# exits the process on a sustained FATAL readyz, and `restart:
# unless-stopped` recovers it. A greffer pending acceptance is DEGRADED ->
# 200 -> healthy, so it is not flapped. start_period covers ops-migrations +
# uvicorn bind + token resolve before failures count.
healthcheck:

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 Mirror compose additions in the CLI template

When greffers are installed via greffer up, the compose file is rendered from cli/greffer_cli/templates/compose.yml; I checked that template and it still lacks both the new /readyz healthcheck and the new x-logging/logging blocks added here. As a result, published-image/operator deployments keep running without the compose health visibility and own-service log caps promised by this change, while only source-tree compose users get them.

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 the x-logging anchor + per-service logging and the /readyz healthcheck to cli/greffer_cli/templates/compose.yml so greffer up (published-image) deployments get the same health visibility and own-service log caps as the source-tree compose. Both files validate.

test:
- CMD-SHELL
- >-
python -c "import urllib.request,os;
t=open(os.path.join(os.getenv('GREFFON_PATH','/data'),
'.greffer-token')).read().strip();

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 Honor explicit tokens in the healthcheck

In deployments that set GREFFER_TOKEN (or when token persistence falls back to the in-memory token), create_app uses that token and does not write it to .greffer-token, but this healthcheck always authenticates with the file contents. Those otherwise-supported deployments will report the greffer as unhealthy forever because /readyz rejects the stale/missing file token; the command should prefer GREFFER_TOKEN before reading the persisted token.

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. The healthcheck now resolves the token the way create_app does (resolve_token = settings.greffer_token i.e. GREFFER_TOKEN env, else the persisted file) rather than always reading .greffer-token. So a GREFFER_TOKEN-set (or in-memory-token) deployment authenticates correctly instead of being reported unhealthy forever. Applied to both docker-compose.yml and the CLI template; a missing token (no env + no file) still exits 0.

urllib.request.urlopen(urllib.request.Request(
'http://localhost:8000/readyz',
headers={'X-GREFFON-TOKEN': t}), timeout=4)"
interval: 30s
timeout: 5s
retries: 3
start_period: 60s
nginx:
build: ./nginx
restart: unless-stopped
logging: *default-logging
networks:
- internal
volumes:
Expand Down Expand Up @@ -76,6 +111,7 @@ services:
profiles: ["tunnel"]
network_mode: host
restart: unless-stopped
logging: *default-logging
depends_on:
- greffer
# rathole-client forwards inbound tunnel traffic to whatever host the
Expand Down
Loading