Phase 3: env masking, image updates, port conflicts, resources, templates (0.3.0)

Backend:
- update_service: registry manifest digest check (Docker Hub/ghcr/lscr/private
  v2 token auth) vs local RepoDigests; in-memory cache + background loop
- port_service: parse compose ports, check /proc/net/tcp[6] + docker bindings
- template_service + bundled templates (jellyfin/vaultwarden/uptime-kuma/
  paperless-ngx/gitea) with {{VAR}} placeholders; custom templates in DB
- compose_edit set_resources (deploy.resources.limits/reservations)
- routers: images, ports, templates, editor/set-resources
- Template model; background update task wired into lifespan

Frontend:
- EnvEditor (table + raw, sensitive masking, quick-insert)
- Images page + UpdateBadge + dashboard 'updates available' banner
- PortConflictDialog pre-deploy check on Deploy
- ResourcePanel (CPU/RAM sliders) as editor Limits tab
- Templates page with per-variable instantiate form

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
menzelj
2026-06-07 16:49:38 +00:00
co-authored by Claude Opus 4.8
parent b553c1b861
commit 22d9864436
32 changed files with 1728 additions and 21 deletions
+54
View File
@@ -144,6 +144,60 @@ def set_privileged(yaml_str: str, service: str, value: bool) -> str:
return _dump(data)
def set_resources(
yaml_str: str,
service: str,
*,
cpus: float | None = None,
memory: str | None = None,
cpus_reserve: float | None = None,
memory_reserve: str | None = None,
) -> str:
"""Set deploy.resources limits/reservations for a service.
Pass None / empty to clear an individual value.
"""
data = _load(yaml_str)
svc = _get_service(data, service)
deploy = svc.setdefault("deploy", {})
resources = deploy.setdefault("resources", {})
limits = resources.get("limits", {})
if cpus:
limits["cpus"] = str(cpus)
else:
limits.pop("cpus", None)
if memory:
limits["memory"] = memory
else:
limits.pop("memory", None)
if limits:
resources["limits"] = limits
else:
resources.pop("limits", None)
reservations = resources.get("reservations", {})
if cpus_reserve:
reservations["cpus"] = str(cpus_reserve)
else:
reservations.pop("cpus", None)
if memory_reserve:
reservations["memory"] = memory_reserve
else:
reservations.pop("memory", None)
# Don't drop reservations entirely — it may hold GPU devices.
if reservations:
resources["reservations"] = reservations
elif "reservations" in resources and not resources["reservations"]:
resources.pop("reservations", None)
if not resources:
deploy.pop("resources", None)
if not deploy:
svc.pop("deploy", None)
return _dump(data)
def list_services(yaml_str: str) -> list[str]:
data = _load(yaml_str)
return list(data["services"].keys())
+158
View File
@@ -0,0 +1,158 @@
"""Port conflict detection before deploying a stack."""
from __future__ import annotations
import os
from typing import Optional
import yaml
from config import settings
from docker_client import DockerError, get_client, safe_call
# --------------------------------------------------------------------------- #
# Parse compose `ports:` entries
# --------------------------------------------------------------------------- #
def parse_compose_ports(yaml_str: str) -> list[dict]:
"""Return [{host_port:int, protocol:'tcp'|'udp', service:str}]."""
try:
data = yaml.safe_load(yaml_str) or {}
except yaml.YAMLError:
return []
services = data.get("services") or {}
out: list[dict] = []
for svc_name, svc in services.items():
if not isinstance(svc, dict):
continue
for entry in svc.get("ports", []) or []:
parsed = _parse_port_entry(entry)
if parsed:
parsed["service"] = svc_name
out.append(parsed)
return out
def _parse_port_entry(entry) -> Optional[dict]:
# Long form: {target, published, protocol}
if isinstance(entry, dict):
published = entry.get("published")
if published is None:
return None
try:
host_port = int(str(published).split("-")[0])
except ValueError:
return None
return {"host_port": host_port, "protocol": entry.get("protocol", "tcp")}
# Short form string: "[ip:]host:container[/proto]" or "container"
s = str(entry)
proto = "tcp"
if "/" in s:
s, proto = s.rsplit("/", 1)
parts = s.split(":")
# No host mapping (only container port) -> random host port, no conflict.
if len(parts) == 1:
return None
# host:container or ip:host:container
host = parts[-2]
try:
host_port = int(host.split("-")[0])
except ValueError:
return None
return {"host_port": host_port, "protocol": proto}
# --------------------------------------------------------------------------- #
# Host bound ports
# --------------------------------------------------------------------------- #
def _read_proc_net(name: str) -> set[int]:
ports: set[int] = set()
path = os.path.join(settings.HOST_PROC_PATH, "net", name)
if not os.path.isfile(path):
path = os.path.join("/proc/net", name)
try:
with open(path, "r", encoding="utf-8") as fh:
lines = fh.readlines()[1:]
except OSError:
return ports
for line in lines:
cols = line.split()
if len(cols) < 4:
continue
local = cols[1] # hexip:hexport
state = cols[3]
# TCP listen state is 0A; for UDP accept all.
if name.startswith("tcp") and state != "0A":
continue
try:
port = int(local.split(":")[1], 16)
ports.add(port)
except (IndexError, ValueError):
continue
return ports
def host_listening_ports() -> dict[str, set[int]]:
return {
"tcp": _read_proc_net("tcp") | _read_proc_net("tcp6"),
"udp": _read_proc_net("udp") | _read_proc_net("udp6"),
}
def docker_bound_ports() -> dict[tuple[int, str], str]:
"""Return {(host_port, proto): container_name}."""
out: dict[tuple[int, str], str] = {}
try:
client = get_client()
for c in safe_call(client.containers.list):
bindings = (c.attrs.get("NetworkSettings") or {}).get("Ports") or {}
for container_port, hosts in bindings.items():
if not hosts:
continue
proto = container_port.split("/")[-1] if "/" in container_port else "tcp"
for h in hosts:
hp = h.get("HostPort")
if hp:
out[(int(hp), proto)] = c.name
except (DockerError, ValueError):
pass
return out
# --------------------------------------------------------------------------- #
# Detect conflicts
# --------------------------------------------------------------------------- #
def detect_conflicts(yaml_str: str, ignore_stack: Optional[str] = None) -> list[dict]:
wanted = parse_compose_ports(yaml_str)
host_ports = host_listening_ports()
docker_ports = docker_bound_ports()
conflicts: list[dict] = []
for w in wanted:
port = w["host_port"]
proto = w.get("protocol", "tcp")
used_by = None
owner = docker_ports.get((port, proto))
if owner:
# A container from the same stack (re-deploy) is not a conflict.
if ignore_stack and owner.startswith(f"{ignore_stack}-"):
continue
used_by = f"container {owner}"
elif port in host_ports.get(proto, set()):
used_by = "host process"
if used_by:
conflicts.append(
{
"port": port,
"protocol": proto,
"service": w.get("service"),
"used_by": used_by,
}
)
return conflicts
+167
View File
@@ -0,0 +1,167 @@
"""Template library — bundled (on-disk) + custom (DB)."""
from __future__ import annotations
import json
import os
import re
from functools import lru_cache
from typing import Optional
from sqlmodel import Session, select
from models.template import Template
_TEMPLATES_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), "templates")
_VAR_RE = re.compile(r"\{\{\s*([A-Za-z0-9_]+)\s*\}\}")
@lru_cache(maxsize=1)
def _manifest() -> list[dict]:
path = os.path.join(_TEMPLATES_DIR, "manifest.json")
try:
with open(path, "r", encoding="utf-8") as fh:
return json.load(fh)
except (OSError, json.JSONDecodeError):
return []
def _read_template_file(filename: str) -> str:
path = os.path.join(_TEMPLATES_DIR, filename)
try:
with open(path, "r", encoding="utf-8") as fh:
return fh.read()
except OSError:
return ""
def extract_variables(yaml_str: str) -> list[str]:
seen: list[str] = []
for m in _VAR_RE.finditer(yaml_str):
if m.group(1) not in seen:
seen.append(m.group(1))
return seen
def render(yaml_str: str, values: dict[str, str]) -> str:
def repl(m: re.Match) -> str:
key = m.group(1)
return str(values.get(key, m.group(0)))
return _VAR_RE.sub(repl, yaml_str)
# --------------------------------------------------------------------------- #
# Listing
# --------------------------------------------------------------------------- #
def list_templates(session: Session) -> list[dict]:
out: list[dict] = []
for entry in _manifest():
out.append(
{
"id": entry["id"],
"name": entry["name"],
"description": entry.get("description"),
"tags": entry.get("tags", []),
"gpu": entry.get("gpu"),
"source": "bundled",
}
)
for tpl in session.exec(select(Template)).all():
out.append(
{
"id": f"custom:{tpl.slug}",
"name": tpl.name,
"description": tpl.description,
"tags": [t for t in tpl.tags.split(",") if t],
"gpu": None,
"source": "custom",
}
)
return out
def get_template(session: Session, template_id: str) -> Optional[dict]:
if template_id.startswith("custom:"):
slug = template_id.split(":", 1)[1]
tpl = session.exec(select(Template).where(Template.slug == slug)).first()
if not tpl:
return None
variables = [
{"name": v, "description": "", "default": ""}
for v in extract_variables(tpl.yaml)
]
return {
"id": template_id,
"name": tpl.name,
"description": tpl.description,
"tags": [t for t in tpl.tags.split(",") if t],
"gpu": None,
"source": "custom",
"yaml": tpl.yaml,
"variables": variables,
}
for entry in _manifest():
if entry["id"] == template_id:
yaml_str = _read_template_file(entry["file"])
declared = {v["name"]: v for v in entry.get("variables", [])}
# Merge declared metadata with any vars actually present.
variables = []
for name in extract_variables(yaml_str):
meta = declared.get(name, {})
variables.append(
{
"name": name,
"description": meta.get("description", ""),
"default": meta.get("default", ""),
}
)
return {
"id": entry["id"],
"name": entry["name"],
"description": entry.get("description"),
"tags": entry.get("tags", []),
"gpu": entry.get("gpu"),
"source": "bundled",
"yaml": yaml_str,
"variables": variables,
}
return None
def save_custom(
session: Session, name: str, yaml_str: str, description: str = "", tags: list[str] | None = None
) -> Template:
slug = re.sub(r"[^a-z0-9_-]+", "-", name.strip().lower()).strip("-") or "template"
existing = session.exec(select(Template).where(Template.slug == slug)).first()
if existing:
existing.name = name
existing.description = description
existing.tags = ",".join(tags or [])
existing.yaml = yaml_str
session.add(existing)
session.commit()
session.refresh(existing)
return existing
tpl = Template(
slug=slug,
name=name,
description=description,
tags=",".join(tags or []),
yaml=yaml_str,
)
session.add(tpl)
session.commit()
session.refresh(tpl)
return tpl
def delete_custom(session: Session, slug: str) -> bool:
tpl = session.exec(select(Template).where(Template.slug == slug)).first()
if not tpl:
return False
session.delete(tpl)
session.commit()
return True
+204
View File
@@ -0,0 +1,204 @@
"""Image update checker.
Compares the locally-pulled manifest digest (from RepoDigests) against the
current manifest digest in the registry. Supports Docker Hub, ghcr.io, lscr.io
and other token-auth v2 registries.
"""
from __future__ import annotations
import asyncio
import logging
import time
from dataclasses import asdict, dataclass
from typing import Optional
import httpx
from config import settings
from docker_client import DockerError, get_client, safe_call
logger = logging.getLogger("stackpilot.update")
_MANIFEST_ACCEPT = ", ".join(
[
"application/vnd.docker.distribution.manifest.v2+json",
"application/vnd.docker.distribution.manifest.list.v2+json",
"application/vnd.oci.image.manifest.v1+json",
"application/vnd.oci.image.index.v1+json",
]
)
@dataclass
class UpdateStatus:
image: str
update_available: bool
current_digest: Optional[str]
remote_digest: Optional[str]
checked_at: float
error: Optional[str] = None
def to_dict(self) -> dict:
return asdict(self)
# image ref -> UpdateStatus
_CACHE: dict[str, UpdateStatus] = {}
# --------------------------------------------------------------------------- #
# Image reference parsing
# --------------------------------------------------------------------------- #
def parse_ref(image: str) -> tuple[str, str, str]:
"""Return (registry_host, repository, tag/digest)."""
ref = image
tag = "latest"
# split tag (but not the registry port colon)
if "@" in ref:
ref, tag = ref.split("@", 1)
else:
# find last colon after last slash
slash = ref.rfind("/")
colon = ref.rfind(":")
if colon > slash:
tag = ref[colon + 1 :]
ref = ref[:colon]
parts = ref.split("/", 1)
if len(parts) == 2 and ("." in parts[0] or ":" in parts[0] or parts[0] == "localhost"):
registry = parts[0]
repo = parts[1]
else:
registry = "registry-1.docker.io"
repo = ref
if "/" not in repo:
repo = "library/" + repo
return registry, repo, tag
def _local_digest(image: str) -> Optional[str]:
try:
client = get_client()
img = safe_call(client.images.get, image)
except DockerError:
return None
repo_digests = img.attrs.get("RepoDigests") or []
for rd in repo_digests:
if "@" in rd:
return rd.split("@", 1)[1]
return None
# --------------------------------------------------------------------------- #
# Registry manifest digest
# --------------------------------------------------------------------------- #
async def _get_token(client: httpx.AsyncClient, www_auth: str) -> Optional[str]:
# Parse: Bearer realm="...",service="...",scope="..."
params = {}
if not www_auth.lower().startswith("bearer"):
return None
for part in www_auth[len("Bearer ") :].split(","):
if "=" in part:
k, v = part.split("=", 1)
params[k.strip()] = v.strip().strip('"')
realm = params.pop("realm", None)
if not realm:
return None
try:
resp = await client.get(realm, params=params, timeout=10)
resp.raise_for_status()
data = resp.json()
return data.get("token") or data.get("access_token")
except (httpx.HTTPError, ValueError):
return None
async def remote_digest(image: str) -> Optional[str]:
registry, repo, tag = parse_ref(image)
if tag.startswith("sha256:"):
return tag
scheme = "https"
url = f"{scheme}://{registry}/v2/{repo}/manifests/{tag}"
headers = {"Accept": _MANIFEST_ACCEPT}
async with httpx.AsyncClient(follow_redirects=True) as client:
try:
resp = await client.head(url, headers=headers, timeout=10)
if resp.status_code == 401:
token = await _get_token(client, resp.headers.get("WWW-Authenticate", ""))
if not token:
return None
headers["Authorization"] = f"Bearer {token}"
resp = await client.head(url, headers=headers, timeout=10)
if resp.status_code == 405 or "Docker-Content-Digest" not in resp.headers:
# Some registries don't support HEAD; fall back to GET.
resp = await client.get(url, headers=headers, timeout=10)
digest = resp.headers.get("Docker-Content-Digest")
return digest
except httpx.HTTPError as exc:
logger.debug("remote_digest failed for %s: %s", image, exc)
return None
# --------------------------------------------------------------------------- #
# Public API
# --------------------------------------------------------------------------- #
async def check_image(image: str) -> UpdateStatus:
local = _local_digest(image)
remote = await remote_digest(image)
error = None
if remote is None:
error = "could not reach registry"
update_available = bool(local and remote and local != remote)
status = UpdateStatus(
image=image,
update_available=update_available,
current_digest=local,
remote_digest=remote,
checked_at=time.time(),
error=error,
)
_CACHE[image] = status
return status
def _all_running_images() -> set[str]:
images: set[str] = set()
try:
client = get_client()
for c in safe_call(client.containers.list, all=True):
cfg_image = c.attrs.get("Config", {}).get("Image")
if cfg_image:
images.add(cfg_image)
except DockerError:
pass
return images
async def check_all() -> dict[str, dict]:
images = _all_running_images()
for image in images:
await check_image(image)
return {k: v.to_dict() for k, v in _CACHE.items()}
def get_cache() -> dict[str, dict]:
return {k: v.to_dict() for k, v in _CACHE.items()}
async def background_loop():
interval = max(settings.UPDATE_CHECK_INTERVAL_MINUTES, 5) * 60
# initial delay so startup isn't blocked
await asyncio.sleep(30)
while True:
try:
await check_all()
logger.info("Image update check complete (%d images)", len(_CACHE))
except Exception as exc: # noqa: BLE001
logger.warning("Image update check failed: %s", exc)
await asyncio.sleep(interval)