Skip to content
Merged
Show file tree
Hide file tree
Changes from 8 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
25 changes: 12 additions & 13 deletions Dockerfile.updater
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,18 @@
# a manager-triggered remote update (self-update v2). It holds the v2 updater
# engine (greffer_cli.updater) plus everything that engine shells out to:
# - docker-cli : talk to the host daemon over the mounted socket
# (pull by digest, inspect the OCI version label,
# recreate via compose)
# (pull by digest, inspect, create/start/stop/rm,
# tag, image prune for the per-container recreate)
# - docker-cli-buildx : `docker buildx imagetools inspect` to resolve a
# tag -> digest at the registry without a pull
# - docker-cli-compose : `docker compose` recreate of the greffer stack
# - cosign : verify image signatures + the signed version
# manifest, offline, against the baked public key
# - cosign : verify image signatures, offline, against the
# baked public key
#
# It runs detached with the docker socket + the greffer's /work (compose dir) and
# /data (ratchet/lock) mounted. The greffer invokes it as
# `python -m greffer_cli.updater <target_tag>` (the spawn supplies the full
# command), so this image sets NO entrypoint that would duplicate it.
# It runs detached with ONLY the docker socket + the greffer's /data volume
# (the update lock) mounted; NO compose file (socket-only per-container
# recreate). The greffer invokes it as `python -m greffer_cli.updater` with the
# target version in GREFFER_UPDATER_TARGET_TAG, so this image sets NO entrypoint
# that would duplicate the command.

# --- build the greffer_cli wheel + its deps into a venv ---------------------
FROM python:3.11-alpine AS builder
Expand All @@ -35,10 +35,9 @@ RUN python -m venv /opt/venv \
FROM python:3.11-alpine
ENV LANG=C.UTF-8 LC_ALL=C.UTF-8

# docker-cli (host daemon via socket) + buildx (imagetools inspect) + compose.
RUN apk add --no-cache docker-cli docker-cli-buildx docker-cli-compose \
&& ln -sf /usr/libexec/docker/cli-plugins/docker-compose /usr/local/bin/docker-compose \
&& docker-compose version \
# docker-cli (host daemon via socket) + buildx (imagetools inspect). No compose:
# the socket-only model recreates each container directly via the Docker API.
RUN apk add --no-cache docker-cli docker-cli-buildx \
&& docker buildx version

# cosign from the official, multi-arch ko image (pinned), so no checksum dance
Expand Down
29 changes: 23 additions & 6 deletions app/routers/controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

import logging
import time
from pathlib import Path
from typing import Literal
from uuid import UUID

Expand Down Expand Up @@ -71,6 +72,18 @@ def _settings(request: Request):
return request.app.state.settings


def _refuse_if_updating(settings) -> None:
"""409 if a self-update is recreating the stack (HLD section 10): a manager
start/stop/update must not race the updater, which during a recreate stops/
rms/recreates containers and is about to certify the stack on the gate. A
non-blocking probe of the ``/data`` update lock; held -> fail fast so the
manager retries. No-op where there is no lock to probe (the probe returns
False if fcntl or the lock file is unavailable)."""
lock_path = Path(settings.greffon_path) / ".update.lock"
if updater_spawn.update_in_progress(lock_path):
raise HTTPException(status_code=409, detail="update_in_progress")


@router.post("/start/")
def start_greffon(
payload: GreffonStartRequest, request: Request
Expand All @@ -86,6 +99,7 @@ def start_greffon(
# ``model_dump()`` also includes ``tunnel_client_toml`` — but the
# downstream compose / repository code only reads keys it knows
# about, so the extra field is harmless to pass through.
_refuse_if_updating(_settings(request))
greffon = payload.model_dump()
compose_file = repository.get_compose_file_from_repository(greffon)
# L4 (Tier-C) ports are published directly on their service. The bind
Expand Down Expand Up @@ -208,6 +222,7 @@ def start_greffon(
def stop_greffon(
payload: GreffonStopRequest, request: Request
) -> GreffonStopResponse:
_refuse_if_updating(_settings(request))
greffon = payload.model_dump()
instance_id_var.set(greffon.get("id")) # tag logs (Feature #4)
_t0 = time.monotonic()
Expand Down Expand Up @@ -310,10 +325,10 @@ def remote_update(
recreates the greffer.

The handler does NOT verify provenance or recreate anything itself: it spawns
the signed updater, which takes the ``/work`` lock and runs the full verify
-> pin -> recreate -> health-gate -> rollback flow, then returns 202 with the
spawned container id. The target tag is already validated by the model and is
passed to the updater as a list arg (no shell)."""
the signed updater, which takes the ``/data`` lock and runs the full
verify-then-pull -> recreate -> health-gate -> rollback flow, then returns 202
with the spawned container id. The target tag is validated by the model and
passed to the updater via ``GREFFER_UPDATER_TARGET_TAG`` (no shell)."""
settings = _settings(request)
if not settings.greffer_remote_update_enabled:
raise HTTPException(
Expand Down Expand Up @@ -341,14 +356,16 @@ def remote_update(
detail="updater_image_not_digest_pinned",
)

# Refuse if an update is already recreating the stack (HLD section 10): avoid
# spawning a second updater that would only fail to take the /data lock.
_refuse_if_updating(settings)

instance_id_var.set(None) # node-level op, not tied to a greffon instance
try:
updater_id = updater_spawn.spawn_updater(
image=settings.greffer_updater_image,
target_tag=payload.target_tag,
manifest_url=settings.greffer_version_manifest_url,
greffer_id=settings.greffer_id,
mode=settings.greffer_mode or "proxy",
data_dest=str(settings.greffon_path),
)
except updater_spawn.UpdaterSpawnError as exc:
Expand Down
117 changes: 66 additions & 51 deletions apps/utils/docker/updater.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,22 @@

A manager-triggered remote update cannot run in the greffer process: the
updater recreates the greffer's OWN container, so it has to outlive the process
it replaces. The controller therefore spawns a SEPARATE, short-lived container
from the signed, digest-pinned updater image, mounting the docker socket plus
the same host paths the greffer itself uses, and returns 202 right away. The
updater then takes the ``/work`` lock, verifies provenance, and recreates the
stack (see ``greffer_cli.updater``).

Host-path discovery: inside a container the bind sources visible on ``/proc``
are CONTAINER paths; to mount the same host directories into a SIBLING
container we need the HOST sources. We read them off the greffer's own
container record (looked up by ``hostname`` == container id), not from env, so
``/work`` (the compose dir) and ``/data`` always track however the operator
actually mounted the greffer. Reusing the recorded mount ``Type``/``Source``
also preserves a named-volume ``/data`` as a volume mount rather than guessing a
host path.

Fail-closed: any missing mount, unknown self-container, or docker error raises
``UpdaterSpawnError`` and the route surfaces it; nothing is spawned half-wired.
it replaces. The controller spawns a SEPARATE, short-lived container from the
signed, digest-pinned updater image, mounting ONLY the docker socket and the
greffer's ``/data`` volume (socket-only model: no compose file, no compose-dir
mount), and returns 202 right away. The updater then takes the
``/data/.update.lock``, verify-then-pulls each image at the target version, and
recreates the stack per container (see ``greffer_cli.updater``).

``/data`` host-source discovery: inside a container the bind sources on
``/proc`` are CONTAINER paths; to mount the same host ``/data`` into a SIBLING
container we read the source off the greffer's own container record (looked up
by ``hostname`` == container id), preserving a named-volume ``/data`` as a
volume mount rather than guessing a host path.

Fail-closed: any missing ``/data`` mount, unknown self-container, or docker
error raises ``UpdaterSpawnError`` and the route surfaces it; nothing is spawned
half-wired.
"""

from __future__ import annotations
Expand All @@ -34,25 +33,46 @@

# The updater image MUST be digest-pinned: it is the one root-equivalent,
# socket-mounted container that recreates the greffer, and it is NOT itself run
# through the cosign/floor verification it performs on the target. A mutable tag
# through the cosign verification it performs on the target. A mutable tag
# (``:latest``) could be repointed registry-side to swap it. Require an explicit
# ``@sha256:<64 hex>`` so a tag move can never change what runs. Anchored with
# fullmatch (repo segment, then exactly one ``@sha256:<64 hex>``, nothing
# trailing) so a pathological ref like ``a@sha256:<64hex>@sha256:<64hex>`` or
# trailing junk cannot slip past.
# fullmatch so a pathological ref with a second ``@sha256:`` or trailing junk
# cannot slip past.
_DIGEST_PINNED_RE = re.compile(r"[^@\s]+@sha256:[0-9a-f]{64}")

DOCKER_SOCK = "/var/run/docker.sock"


def is_digest_pinned(ref: object) -> bool:
"""True iff ``ref`` is an image reference pinned by a sha256 digest."""
return isinstance(ref, str) and _DIGEST_PINNED_RE.fullmatch(ref) is not None

# The greffer mounts its compose dir at /app (``./:/app``) and uses
# ``$GREFFON_PATH`` (default /data) for persistent state. The updater image
# expects the compose dir at /work and the shared state at /data.
SELF_COMPOSE_DEST = "/app"
UPDATER_COMPOSE_DEST = "/work"
DOCKER_SOCK = "/var/run/docker.sock"

def update_in_progress(lock_path) -> bool:
"""True iff a self-update currently holds the ``/data`` update lock.

The controller probes this (non-blocking ``flock``) on start/stop/update so a
manager action cannot mutate instance/compose state in the window the updater
is recreating the stack (HLD section 10). The probe acquires-then-releases, so
it never holds the lock the updater needs; a held lock (the updater is
mid-update) makes the acquire fail -> True. On a platform without fcntl, or if
the lock file cannot be opened, returns False (cannot tell -> do not block)."""
try:
import fcntl
except ImportError:
return False
try:
fh = open(lock_path, "a", encoding="utf-8") # "a": create, never truncate
except OSError:
return False
try:
fcntl.flock(fh.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
fcntl.flock(fh.fileno(), fcntl.LOCK_UN)
return False
except OSError:
return True
finally:
fh.close()


class UpdaterSpawnError(Exception):
Expand Down Expand Up @@ -87,23 +107,23 @@ def _mount_for(self_attrs: dict, destination: str, *, target: str) -> Mount:
if not source:
raise UpdaterSpawnError(
f"mount at {destination} has no reusable source")
return Mount(target=target, source=source, type=mtype,
read_only=False)
return Mount(target=target, source=source, type=mtype, read_only=False)
raise UpdaterSpawnError(
f"greffer has no mount at {destination}; cannot wire the updater")


def spawn_updater(
*, image: str, target_tag: str, manifest_url: str, greffer_id: str | None,
mode: str, data_dest: str = "/data", client=None,
*, image: str, target_tag: str | None, greffer_id: str | None,
data_dest: str = "/data", client=None,
) -> str:
"""Spawn the detached updater container and return its id.

``image`` MUST be a digest-pinned ref (caller's responsibility / settings
contract). Mounts: the greffer's compose dir -> /work, its ``data_dest``
(default /data) -> /data, and the docker socket. The target tag is passed as
a list arg (no shell), and the updater re-validates it; provenance/floor
verification all happen inside the container before any recreate."""
``image`` MUST be a digest-pinned ref (the route and this both enforce it).
Mounts: the greffer's ``data_dest`` (default ``/data``) -> ``/data`` and the
docker socket; NOTHING else (socket-only, no compose dir). ``target_tag`` (the
server-resolved version; latest when None) is passed as
``GREFFER_UPDATER_TARGET_TAG``, which the updater re-validates before running
the in-container verify -> recreate -> health-gate -> rollback flow."""
if not image:
raise UpdaterSpawnError("no updater image configured")
if not is_digest_pinned(image):
Expand All @@ -115,33 +135,28 @@ def spawn_updater(
self_attrs = _self_container(client).attrs

mounts = [
_mount_for(self_attrs, SELF_COMPOSE_DEST, target=UPDATER_COMPOSE_DEST),
_mount_for(self_attrs, data_dest, target="/data"),
Mount(target=DOCKER_SOCK, source=DOCKER_SOCK, type="bind"),
]
environment = {
"GREFFER_VERSION_MANIFEST_URL": manifest_url,
"GREFFER_ID": greffer_id or "",
"GREFFER_MODE": mode,
}
environment = {"GREFFER_ID": greffer_id or ""}
if target_tag:
environment["GREFFER_UPDATER_TARGET_TAG"] = target_tag
try:
container = client.containers.run(
image,
["python", "-m", "greffer_cli.updater", target_tag],
["python", "-m", "greffer_cli.updater"],
detach=True,
# The updater is one-shot; drop the container when it exits so a
# series of updates doesn't litter the host. Logs are captured by
# the manager-visible exit, not the container record.
# One-shot; drop the container when it exits so a series of updates
# doesn't litter the host.
remove=True,
environment=environment,
mounts=mounts,
# Default bridge: the updater needs egress to fetch the signed
# version manifest (HTTPS) and to resolve image digests at the
# registry (``buildx imagetools inspect`` / cosign run in-container).
# It exposes no inbound port.
# Default bridge: the updater needs egress to resolve image digests
# and pull (buildx imagetools inspect / cosign / docker pull run
# in-container). It exposes no inbound port.
)
except docker.errors.APIError as exc:
raise UpdaterSpawnError(f"failed to spawn updater: {exc}") from exc
logger.info("remote_update_spawned image=%s target=%s container=%s",
image, target_tag, container.id[:12])
image, target_tag or "latest", container.id[:12])
return container.id
Loading
Loading