Files
stackpilot/backend/services/convert_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

358 lines
13 KiB
Python

"""Convert a `docker run ...` command string into a Compose YAML fragment.
The result has to be a compose file that ``docker compose config`` accepts and
that means what the command meant. Three things got that wrong before:
* every flag the converter did not know was assumed to take a value, so a
boolean like ``--read-only`` or ``-P`` swallowed the image name, and
``-dit ubuntu bash`` came out as a service running the image ``bash``;
* ``--network host`` became ``networks: [host]`` and ``-v data:/data`` a
reference to a volume nobody declared — both of which compose rejects;
* flags with real effect (``--gpus``, ``--mount``, ``--entrypoint``,
``--cap-drop``, ``--shm-size`` …) were dropped without a word.
``docker run``'s boolean flags are a short, closed list; everything else takes a
value. That is what the parser goes by now.
"""
from __future__ import annotations
import re
import shlex
import yaml
#: docker run flags that take no value.
_BOOL_LONG = {
"--detach", "--interactive", "--tty", "--rm", "--init", "--privileged",
"--read-only", "--publish-all", "--oom-kill-disable", "--no-healthcheck",
"--disable-content-trust", "--quiet", "--sig-proxy", "--use-api-socket",
}
#: Single-letter booleans, which may be bundled ("-dit").
_BOOL_SHORT = set("ditPq")
#: Single-letter flags that take a value ("-p 80:80", "-p80:80").
_VALUE_SHORT = {
"p": "--publish", "v": "--volume", "e": "--env", "l": "--label",
"u": "--user", "w": "--workdir", "h": "--hostname", "m": "--memory",
"a": "--attach", "c": "--cpu-shares",
}
_SHORT_TO_LONG = {"d": "--detach", "i": "--interactive", "t": "--tty",
"P": "--publish-all", "q": "--quiet"}
#: network_mode values, as opposed to networks a service joins.
_NETWORK_MODES = {"host", "none", "bridge"}
_SERVICE_NAME_RE = re.compile(r"[^a-zA-Z0-9._-]+")
def _service_name_from_image(image: str) -> str:
name = image.split("@", 1)[0].split("/")[-1].split(":")[0]
return _SERVICE_NAME_RE.sub("-", name).strip("-.") or "app"
#: A line continuation whose newline is already gone. Pasted into a one-line
#: field, backslash-newline arrives as a backslash followed by the next line's
#: indentation, which shlex read as an escaped space: a lone " " token that
#: became the image. A backslash followed by an option, or by more than one
#: blank, is such a continuation; a single escaped space inside a word
#: (``My\ Files``) is left alone.
_FLATTENED_CONTINUATION = re.compile(r"\\[ \t]+(?=-)|\\[ \t]{2,}")
def _tokens(command: str) -> list[str]:
# Shell line continuations, as pasted from a README.
command = command.replace("\\\r\n", " ").replace("\\\n", " ")
tokens = shlex.split(_FLATTENED_CONTINUATION.sub(" ", command))
# Drop leading "sudo docker run" / "docker container run".
while tokens and tokens[0] in ("docker", "run", "container", "sudo", "podman"):
tokens.pop(0)
return tokens
def _parse(tokens: list[str]) -> tuple[list[tuple[str, str | None]], str | None, list[str]]:
"""Split into ([(long_flag, value)], image, command)."""
flags: list[tuple[str, str | None]] = []
i, n = 0, len(tokens)
while i < n:
tok = tokens[i]
if tok == "--":
i += 1
break
if not tok.startswith("-") or tok == "-":
break # the image
if tok.startswith("--"):
name, eq, value = tok.partition("=")
if eq:
flags.append((name, value))
i += 1
elif name in _BOOL_LONG:
flags.append((name, None))
i += 1
else:
flags.append((name, tokens[i + 1] if i + 1 < n else ""))
i += 2
continue
# Short form: bundled booleans ("-dit"), or one value flag with its
# value attached ("-p8080:80") or following ("-p 8080:80").
body = tok[1:]
j = 0
while j < len(body) and body[j] in _BOOL_SHORT:
flags.append((_SHORT_TO_LONG[body[j]], None))
j += 1
if j == len(body):
i += 1
continue
letter = body[j]
long_name = _VALUE_SHORT.get(letter, f"-{letter}")
attached = body[j + 1 :]
if attached.startswith("="):
attached = attached[1:]
if attached:
flags.append((long_name, attached))
i += 1
else:
flags.append((long_name, tokens[i + 1] if i + 1 < n else ""))
i += 2
image = tokens[i] if i < n else None
command = tokens[i + 1 :] if image is not None else []
return flags, image, command
def _is_named_volume(source: str) -> bool:
return bool(source) and not source.startswith(("/", ".", "~", "$"))
def _mount(value: str) -> dict:
"""``--mount type=bind,source=/a,target=/b,readonly`` as compose long syntax."""
spec: dict = {}
for part in value.split(","):
key, eq, val = part.partition("=")
key = key.strip()
if key in ("source", "src"):
spec["source"] = val
elif key in ("target", "destination", "dst"):
spec["target"] = val
elif key == "type":
spec["type"] = val
elif key in ("readonly", "ro"):
spec["read_only"] = (not eq) or val.lower() in ("1", "true")
elif key == "bind-propagation":
spec.setdefault("bind", {})["propagation"] = val
elif key == "volume-nocopy":
spec.setdefault("volume", {})["nocopy"] = (not eq) or val.lower() in ("1", "true")
elif key == "tmpfs-size":
spec.setdefault("tmpfs", {})["size"] = val
spec.setdefault("type", "volume")
return spec
def _gpus(value: str) -> dict:
"""``--gpus all`` / ``--gpus 2`` / ``--gpus device=0,1`` as a device reservation."""
reservation: dict = {"driver": "nvidia", "capabilities": ["gpu"]}
value = value.strip().strip('"').strip("'")
if value.startswith("device="):
reservation["device_ids"] = [d for d in value[len("device="):].split(",") if d]
elif value.isdigit():
reservation["count"] = int(value)
else:
reservation["count"] = "all"
return reservation
def _ulimit(value: str, ulimits: dict) -> None:
name, _, limits = value.partition("=")
soft, _, hard = limits.partition(":")
try:
ulimits[name] = (
{"soft": int(soft), "hard": int(hard)} if hard else int(soft)
)
except ValueError:
pass
def convert_docker_run(command: str) -> str:
tokens = _tokens(command)
flags, image, command_args = _parse(tokens)
if not image:
raise ValueError("Could not find an image in the docker run command")
service: dict = {"image": image}
top_volumes: dict = {}
top_networks: dict = {}
name = None
lists: dict[str, list] = {}
healthcheck: dict = {}
logging: dict = {}
ulimits: dict = {}
gpus: list[dict] = []
def add(key: str, value) -> None:
lists.setdefault(key, []).append(value)
for flag, value in flags:
value = value if value is not None else ""
if flag == "--name":
name = value
elif flag == "--publish":
add("ports", value)
elif flag == "--volume":
add("volumes", value)
source = value.split(":", 1)[0] if ":" in value else ""
if _is_named_volume(source):
top_volumes[source] = None
elif flag == "--mount":
spec = _mount(value)
add("volumes", spec)
if spec.get("type") == "volume" and _is_named_volume(spec.get("source", "")):
top_volumes[spec["source"]] = None
elif flag == "--tmpfs":
add("tmpfs", value)
elif flag == "--env":
add("environment", value)
elif flag == "--env-file":
add("env_file", value)
elif flag == "--device":
add("devices", value)
elif flag == "--cap-add":
add("cap_add", value)
elif flag == "--cap-drop":
add("cap_drop", value)
elif flag == "--label":
add("labels", value)
elif flag in ("--network", "--net"):
if value in _NETWORK_MODES or value.startswith(("container:", "service:")):
service["network_mode"] = value
elif value:
add("networks", value)
# `docker run --network x` needs x to exist already.
top_networks[value] = {"external": True}
elif flag == "--network-alias":
add("_aliases", value)
elif flag == "--add-host":
add("extra_hosts", value)
elif flag == "--dns":
add("dns", value)
elif flag == "--dns-search":
add("dns_search", value)
elif flag == "--security-opt":
add("security_opt", value)
elif flag == "--sysctl":
add("sysctls", value)
elif flag == "--group-add":
add("group_add", value)
elif flag == "--expose":
add("expose", value)
elif flag == "--gpus":
gpus.append(_gpus(value))
elif flag == "--ulimit":
_ulimit(value, ulimits)
elif flag == "--restart":
service["restart"] = value
elif flag == "--privileged":
service["privileged"] = True
elif flag == "--read-only":
service["read_only"] = True
elif flag == "--init":
service["init"] = True
elif flag == "--interactive":
service["stdin_open"] = True
elif flag == "--tty":
service["tty"] = True
elif flag == "--hostname":
service["hostname"] = value
elif flag == "--user":
service["user"] = value
elif flag == "--workdir":
service["working_dir"] = value
elif flag == "--entrypoint":
service["entrypoint"] = value
elif flag == "--shm-size":
service["shm_size"] = value
elif flag == "--memory":
service["mem_limit"] = value
elif flag == "--memory-reservation":
service["mem_reservation"] = value
elif flag == "--cpus":
try:
service["cpus"] = float(value)
except ValueError:
pass
elif flag == "--cpu-shares":
try:
service["cpu_shares"] = int(value)
except ValueError:
pass
elif flag == "--pids-limit":
try:
service["pids_limit"] = int(value)
except ValueError:
pass
elif flag == "--pid":
service["pid"] = value
elif flag == "--ipc":
service["ipc"] = value
elif flag == "--stop-signal":
service["stop_signal"] = value
elif flag in ("--stop-timeout", "--time"):
service["stop_grace_period"] = f"{value}s" if value.isdigit() else value
elif flag == "--platform":
service["platform"] = value
elif flag == "--pull":
service["pull_policy"] = value
elif flag == "--log-driver":
logging["driver"] = value
elif flag == "--log-opt":
key, _, val = value.partition("=")
logging.setdefault("options", {})[key] = val
elif flag == "--health-cmd":
healthcheck["test"] = ["CMD-SHELL", value]
elif flag == "--health-interval":
healthcheck["interval"] = value
elif flag == "--health-timeout":
healthcheck["timeout"] = value
elif flag == "--health-start-period":
healthcheck["start_period"] = value
elif flag == "--health-retries":
try:
healthcheck["retries"] = int(value)
except ValueError:
pass
elif flag == "--no-healthcheck":
healthcheck = {"disable": True}
# Everything else (--detach, --rm, --publish-all, --cidfile, …) has no
# compose equivalent worth writing down.
aliases = lists.pop("_aliases", [])
if aliases:
nets = lists.get("networks") or []
if nets:
# Aliases apply to the networks given on the command line.
lists["networks"] = {net: {"aliases": aliases} for net in nets}
service.setdefault("restart", "unless-stopped")
for key in (
"ports", "expose", "volumes", "tmpfs", "environment", "env_file", "devices",
"cap_add", "cap_drop", "security_opt", "sysctls", "group_add", "extra_hosts",
"dns", "dns_search", "labels", "networks",
):
if key in lists:
service[key] = lists[key]
if ulimits:
service["ulimits"] = ulimits
if logging:
service["logging"] = logging
if healthcheck:
service["healthcheck"] = healthcheck
if gpus:
service["deploy"] = {"resources": {"reservations": {"devices": gpus}}}
if command_args:
service["command"] = command_args
if name:
service["container_name"] = name
svc_name = _SERVICE_NAME_RE.sub("-", name).strip("-.") if name else ""
doc: dict = {"services": {svc_name or _service_name_from_image(image): service}}
if top_volumes:
doc["volumes"] = top_volumes
if top_networks:
doc["networks"] = top_networks
return yaml.safe_dump(doc, sort_keys=False, default_flow_style=False)