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
204 lines
6.9 KiB
Python
204 lines
6.9 KiB
Python
"""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
|
|
from services.compose_service import project_name
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# 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 []
|
|
if not isinstance(data, dict):
|
|
return []
|
|
services = data.get("services") or {}
|
|
if not isinstance(services, dict):
|
|
return []
|
|
out: list[dict] = []
|
|
for svc_name, svc in services.items():
|
|
if not isinstance(svc, dict):
|
|
continue
|
|
for entry in svc.get("ports", []) or []:
|
|
for parsed in _parse_port_entry(entry):
|
|
parsed["service"] = svc_name
|
|
out.append(parsed)
|
|
return out
|
|
|
|
|
|
#: A published range is checked port by port, up to this many.
|
|
_MAX_RANGE = 1024
|
|
|
|
|
|
def _host_ports(spec: str) -> list[int]:
|
|
""""8080" -> [8080]; "8080-8082" -> [8080, 8081, 8082]; junk -> []."""
|
|
try:
|
|
if "-" in spec:
|
|
low, high = (int(p) for p in spec.split("-", 1))
|
|
if low > high or high - low >= _MAX_RANGE:
|
|
return [low]
|
|
return list(range(low, high + 1))
|
|
return [int(spec)]
|
|
except ValueError:
|
|
return []
|
|
|
|
|
|
def _parse_port_entry(entry) -> list[dict]:
|
|
# Long form: {target, published, protocol}
|
|
if isinstance(entry, dict):
|
|
published = entry.get("published")
|
|
if published is None:
|
|
return []
|
|
proto = str(entry.get("protocol") or "tcp")
|
|
return [{"host_port": p, "protocol": proto} for p in _host_ports(str(published))]
|
|
|
|
# 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 []
|
|
# host:container or ip:host:container (an IPv6 address has more colons;
|
|
# the host port is always the second to last part)
|
|
return [{"host_port": p, "protocol": proto} for p in _host_ports(parts[-2])]
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# Host bound ports
|
|
# --------------------------------------------------------------------------- #
|
|
|
|
|
|
def _proc_net_path(name: str) -> str:
|
|
"""The host's socket table, not this container's.
|
|
|
|
``/proc/net`` is a link to ``self/net`` — the network namespace of whoever
|
|
reads it — so ``${HOST_PROC_PATH}/net/tcp`` read from inside the StackPilot
|
|
container lists the container's own sockets (just its API port), and every
|
|
port a host process listens on went unnoticed. PID 1 of the host's /proc
|
|
lives in the host's namespace.
|
|
"""
|
|
for candidate in (
|
|
os.path.join(settings.HOST_PROC_PATH, "1", "net", name),
|
|
os.path.join(settings.HOST_PROC_PATH, "net", name),
|
|
):
|
|
if os.path.isfile(candidate):
|
|
return candidate
|
|
return os.path.join("/proc/net", name)
|
|
|
|
|
|
def _read_proc_net(name: str) -> set[int]:
|
|
ports: set[int] = set()
|
|
path = _proc_net_path(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"),
|
|
}
|
|
|
|
|
|
COMPOSE_PROJECT_LABEL = "com.docker.compose.project"
|
|
|
|
|
|
def docker_bound_ports() -> dict[tuple[int, str], tuple[str, Optional[str]]]:
|
|
"""Return {(host_port, proto): (container_name, compose_project)}.
|
|
|
|
The compose project is taken from the container's compose label so a
|
|
stack's own running containers can be reliably recognised on re-deploy,
|
|
regardless of explicit container_name or name separator differences.
|
|
"""
|
|
out: dict[tuple[int, str], tuple[str, Optional[str]]] = {}
|
|
try:
|
|
client = get_client()
|
|
for c in safe_call(client.containers.list):
|
|
project = (c.labels or {}).get(COMPOSE_PROJECT_LABEL)
|
|
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, project)
|
|
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:
|
|
owner_name, owner_project = owner
|
|
# A container from the same stack (re-deploy) is not a conflict.
|
|
# Match on the compose project label, falling back to the legacy
|
|
# name-prefix check for containers without the label.
|
|
if ignore_stack and (
|
|
owner_project in (ignore_stack, project_name(ignore_stack))
|
|
or owner_name.startswith(f"{ignore_stack}-")
|
|
):
|
|
continue
|
|
used_by = f"container {owner_name}"
|
|
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
|