Files
stackpilot/backend/services/image_service.py
T
menzeljandClaude Opus 5.5 d6cebb3371
CI / check (push) Successful in 4m9s
CI / build-and-push (push) Failing after 16m10s
Fix what a review of the whole app found, end to end (0.67.1)
A pass over every feature against a real Docker daemon, then clicking
through the UI as admin and read-only user, on a desktop and a phone.

Security. /ws/deploy ran compose up for the read-only role; it is
admin-only now. A container's inspect view, a stack's compose file
(POSTGRES_PASSWORD: hunter2) and the viewer's .env tab no longer show
credentials to that role. Git branch and URL values that git would read
as options (-x, ext::) are refused. SFTP host keys are checked: pinned
on first use or entered by hand (key line or SHA256 fingerprint), a
different key is refused before the password is sent. A backup name
from the API can no longer reach outside the destination folder. The
file browser refuses to move or rename a browse root, as delete did.

Docker lifecycle. Closing the deploy console released the stack lock
while compose was still running and logged rc=None as success; deploys
and updates are now background runs that hold the lock to the end,
report the real exit code and can be re-attached to. Every closed log
view left a `compose logs -f` behind. A dozen open tabs exhausted the
default thread pool and hung the API; event and exec streams have their
own threads. Auto-update and the update endpoint ignored failed pulls.
A deleted git stack was recreated and started by the next webhook or
poll; deleting a stack now drops its git source, auto-update policy and
schedule entries. Deleting no longer walks into mounted shares, is
refused while a backup runs, and removes the containers even when the
compose file is broken. Stack folders compose has to normalise
(Nextcloud -> nextcloud) work everywhere and group correctly on the
volumes, networks and images pages.

Detection. Host port conflicts read the container's own network
namespace; /proc/1/net is read instead. Images referenced as docker.io/…
were never update-checked; local builds no longer report "needs
credentials". NVIDIA GPUs are read from the driver's procfs. The backup
dialog's "path mismatch" warning came from mountinfo's filesystem-relative
root and fired for any stacks folder on its own disk, ZFS dataset or
btrfs subvolume; the host path now comes from Docker's mounts.

Backups and destinations. The download ignored the folder/volume
selection (axios sent binds[]). Restoring under a new name kept the old
one. A report header past nginx's buffer turned a good backup into a
502. SFTP/S3 errors were bare 500s and "Test" did not try to write.
A destination used by a schedule could be deleted. Backup file names
are in the schedule's or the browser's time zone instead of UTC.

Editor and converter. `docker run` conversion produced invalid compose
for --network host, named volumes and -dit; --gpus and --mount were
dropped; a multi-line command pasted into the one-line field became
`image: ' '` (now a textarea, and flattened continuations are read).
Validation failed for env_file stacks. The editor overwrote unsaved
edits on every container event, lost them on a stray click (now asks),
threw when closing the diff, and its helper panel listed the starter
service "app" for every existing stack. Monaco is bundled instead of
loaded from jsdelivr, so the editor works offline (and monaco-editor
0.57 drops the dompurify advisory; axios and react-router updated).

UI. All times were two hours off: offset-less UTC from SQLite was read
as local time, and "next run" always said "just now". A token refresh
mid-session duplicated deploys, reset terminals and doubled logs. A
backend restart (update, self-update) signed everyone out on reload; the
page now waits for it. The editor was unusable on a phone, tables and
tabs overflowed, dialog text was black on the dark theme, and the file
browser opened on an error with the default roots. Read-only users get
"Admin only" pages instead of 403s; in-use networks offer no delete;
"Scan all" covers StackPilot's own stacks only and runs in the
background instead of timing out at 600s.

Deployment. nginx passes the port in Host (the OIDC redirect URI lost
:5009) and keeps an outer proxy's X-Forwarded-Proto. The frontend waits
for a healthy backend (healthcheck probes every 2s while starting). The
frontend image builds with npm ci. Secrets are 0644 in a 0700 folder so
non-root containers can read them; existing files are fixed at startup.
The test suite no longer starts real containers on a host with Docker.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Fx7gcuy8d6nPd95g43rGHu
2026-10-15 13:51:26 +02:00

179 lines
6.7 KiB
Python

"""Image listing and pruning for the images router."""
from __future__ import annotations
import logging
from typing import Callable, Optional
from docker_client import DockerError, get_client, get_long_client, safe_call
from services import update_service
from services.prune_job import PruneJob, PrunePlan
logger = logging.getLogger(__name__)
COMPOSE_PROJECT_LABEL = "com.docker.compose.project"
def list_images() -> list[dict]:
"""Return one row per image tag, annotated with using-stacks + update status.
Usage is matched on the image *id* the containers run, not on the name:
a compose file saying ``image: nginx`` or ``docker.io/library/nginx:1``
produces containers whose configured image never equals the tag Docker
lists (``nginx:latest``, ``nginx:1``), so those images showed up as used
by no stack — and were left out of "scan all".
"""
try:
client = get_client()
images = safe_call(client.images.list)
containers = safe_call(client.api.containers, all=True)
except DockerError:
return []
# image id -> stacks using it, and the references they were created from
# (which is what the update checker caches its results under).
stacks_by_id: dict[str, set[str]] = {}
refs_by_id: dict[str, set[str]] = {}
for c in containers:
image_id = c.get("ImageID") or ""
stack = (c.get("Labels") or {}).get(COMPOSE_PROJECT_LABEL)
stacks_by_id.setdefault(image_id, set())
if stack:
stacks_by_id[image_id].add(stack)
if (ref := c.get("Image")) and not ref.startswith("sha256:"):
refs_by_id.setdefault(image_id, set()).add(ref)
cache = update_service.get_cache()
result = []
for img in images:
tags = img.tags or []
if not tags:
continue
refs = refs_by_id.get(img.id, set())
for tag in tags:
update = cache.get(tag)
if update is None:
# Cached under the name the compose file used for it.
update = next((cache[r] for r in sorted(refs) if r in cache), None)
result.append(
{
"id": img.short_id,
"tag": tag,
"size": img.attrs.get("Size", 0),
"created": img.attrs.get("Created"),
"stacks": sorted(stacks_by_id.get(img.id, set())),
"update": update,
}
)
result.sort(key=lambda r: r["tag"])
return result
# --------------------------------------------------------------------------- #
# Prune
# --------------------------------------------------------------------------- #
_prune = PruneJob("image")
def prune_status() -> dict:
return _prune.status()
def _layers_size(client) -> Optional[int]:
"""Total size of all image layers on the host, or None if unavailable.
Taken before and after the prune, the difference is the space actually
freed. Summing the sizes of the deleted images would count base layers
they share with the images that stay. ``type=image`` keeps the daemon from
also walking every volume (API 1.42+; older daemons ignore it).
"""
try:
api = client.api
response = api._get(api._url("/system/df"), params={"type": "image"})
return api._result(response, True).get("LayersSize")
except Exception as exc: # noqa: BLE001 - the size is a nicety, not the job
logger.warning("Could not read image disk usage: %s", exc)
return None
def _candidates(client, all_unused: bool) -> list[dict]:
"""The images ``docker image prune [-a]`` would remove, largest first."""
in_use = {c.get("ImageID") for c in safe_call(client.api.containers, all=True)}
filters = None if all_unused else {"dangling": True}
images = safe_call(client.api.images, filters=filters)
unused = [img for img in images if img["Id"] not in in_use]
return sorted(unused, key=lambda img: img.get("Size", 0), reverse=True)
def _label(image: dict) -> str:
tags = [t for t in image.get("RepoTags") or [] if t != "<none>:<none>"]
if tags:
return tags[0] if len(tags) == 1 else f"{tags[0]} (+{len(tags) - 1})"
return image["Id"].removeprefix("sha256:")[:12]
def _remove(client, image: dict) -> list[dict]:
"""Delete one image the way the prune would, returning Docker's entries.
Tags are removed one by one rather than with force=True: the last one takes
the image with it, and a container created since the candidates were listed
still makes the daemon refuse instead of losing its image.
"""
tags = [t for t in image.get("RepoTags") or [] if t != "<none>:<none>"]
entries: list[dict] = []
for ref in tags or [image["Id"]]:
entries.extend(safe_call(client.api.remove_image, ref) or [])
return entries
def _plan(all_unused: bool) -> PrunePlan:
client = get_long_client()
measured: dict = {}
def prepare() -> None:
measured["before"] = _layers_size(client)
def remove(image: dict) -> tuple[list, bool]:
entries = _remove(client, image)
return entries, any("Deleted" in e for e in entries)
def finish(entries: list) -> tuple[dict, Optional[int]]:
# Let the daemon sweep up whatever the per-image pass left, such as
# untagged images referenced from several repositories.
filters = {"dangling": False} if all_unused else {"dangling": True}
sweep = safe_call(client.images.prune, filters=filters)
entries = entries + (sweep.get("ImagesDeleted") or [])
before, after = measured.get("before"), _layers_size(client)
if before is not None and after is not None:
reclaimed = max(before - after, 0)
else:
reclaimed = sweep.get("SpaceReclaimed", 0)
return {"ImagesDeleted": entries, "SpaceReclaimed": reclaimed}, reclaimed
return PrunePlan(
all=all_unused,
items=_candidates(client, all_unused),
label=_label,
remove=remove,
finish=finish,
prepare=prepare,
)
def prune_images(all_unused: bool = False) -> dict:
"""Remove unused images and wait for the result.
By default only dangling (untagged) images are removed; ``all_unused=True``
removes every image not referenced by a container (``docker image prune
-a``). Progress is visible through prune_status() while it runs.
"""
return _prune.run(lambda: _plan(all_unused))
def start_prune(
all_unused: bool = False, on_done: Optional[Callable[[dict], None]] = None
) -> dict:
"""Start a prune in the background and return its initial status; the UI
polls prune_status(). ``on_done`` gets what prune_images() would return."""
return _prune.start(lambda: _plan(all_unused), on_done)