Files
stackpilot/backend/routers/ws.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

470 lines
17 KiB
Python

"""WebSocket endpoints for real-time log streaming and Docker events."""
from __future__ import annotations
import asyncio
import contextlib
import json
import logging
import threading
from collections.abc import Awaitable, Callable
from fastapi import APIRouter, Query, WebSocket, WebSocketDisconnect
from jose import JWTError
from sqlmodel import Session
from auth import decode_token, resolve_token_user
from database import engine
from models.setting import EVENT_PULL_FAILED, EVENT_STACK_ERROR, EVENT_STACK_START
from models.stack import Stack
from services import (
audit_service,
compose_run_service,
compose_service,
exec_service,
notify_service,
update_service,
)
logger = logging.getLogger("stackpilot.ws")
router = APIRouter(tags=["ws"])
def _user_for(token: str | None):
"""The live user behind a socket's token, or None.
Resolves against the database rather than reading the role straight off the
JWT: a socket can outlive a demotion, a disabled account or a password
reset, and the exec endpoint below is root-equivalent on the host. Same
check the HTTP routes make.
"""
if not token:
return None
try:
payload = decode_token(token, "access")
except (JWTError, Exception): # noqa: BLE001
return None
with Session(engine) as session:
user = resolve_token_user(session, payload)
if user:
session.expunge(user)
return user
async def _authorize(websocket: WebSocket, token: str | None):
"""The user behind the token, or None after closing the socket with 4401."""
user = _user_for(token)
if user is None:
await websocket.close(code=4401)
return user
async def _authorize_admin(websocket: WebSocket, token: str | None):
"""Like _authorize but also requires the admin role.
Anything that changes what runs on the host is admin-only over HTTP, so it
has to be over a socket too — the deploy console runs the same
``compose up`` the REST ``/start`` does. Closes 4401 on a missing/invalid
token, 4403 on a valid non-admin one."""
user = _user_for(token)
if user is None:
await websocket.close(code=4401)
return None
if user.role != "admin":
await websocket.close(code=4403)
return None
return user
async def _wait_disconnect(websocket: WebSocket) -> None:
"""Return once the client has gone. Whatever it sends is ignored.
A stream that only ever *sends* notices a closed socket on its next send —
which for a quiet log or an idle Docker host can be hours away, and until
then everything behind the socket (a ``compose logs -f``, an event reader
thread) stays alive for nobody.
"""
try:
while True:
message = await websocket.receive()
if message.get("type") == "websocket.disconnect":
return
except Exception: # noqa: BLE001 - a broken socket is a gone client
return
async def _until_gone(websocket: WebSocket, work: Awaitable[None]) -> None:
"""Run ``work`` until it finishes or the client disconnects, whichever is first.
Cancelling ``work`` is what stops whatever it was reading from; see
:func:`compose_service.stream_compose`.
"""
task = asyncio.ensure_future(work)
gone = asyncio.create_task(_wait_disconnect(websocket))
try:
await asyncio.wait({task, gone}, return_when=asyncio.FIRST_COMPLETED)
finally:
for pending in (task, gone):
pending.cancel()
await asyncio.gather(task, gone, return_exceptions=True)
if task.done() and not task.cancelled() and task.exception() is not None:
exc = task.exception()
if not isinstance(exc, WebSocketDisconnect):
with contextlib.suppress(Exception):
await websocket.send_text(json.dumps({"type": "error", "detail": str(exc)}))
async def _stream_logs(websocket: WebSocket, stack_id: str, service: str | None):
"""Stream `docker compose logs -f` output to the client."""
args = ["logs", "--no-color", "--tail", "200", "--timestamps", "-f"]
if service:
# "--" so a service name can never be read as a compose option.
args += ["--", service]
async def pump() -> None:
# aclosing: cancelled while *sending*, the loop is left by an exception
# outside the generator, which would then only be closed — and its
# `compose logs -f` killed — whenever garbage collection got to it.
async with contextlib.aclosing(
compose_service.stream_compose(stack_id, args)
) as lines:
async for line in lines:
await _send_log(line)
async def _send_log(line: str) -> None:
await websocket.send_text(
json.dumps({"type": "log", "stack_id": stack_id, "service": service, "line": line})
)
await _until_gone(websocket, pump())
@router.websocket("/ws/logs/{stack_id}")
async def ws_stack_logs(
websocket: WebSocket,
stack_id: str,
token: str | None = Query(default=None),
):
await websocket.accept()
if not await _authorize(websocket, token):
return
await _stream_logs(websocket, stack_id, None)
@router.websocket("/ws/logs/{stack_id}/{service}")
async def ws_service_logs(
websocket: WebSocket,
stack_id: str,
service: str,
token: str | None = Query(default=None),
):
await websocket.accept()
if not await _authorize(websocket, token):
return
await _stream_logs(websocket, stack_id, service)
# --------------------------------------------------------------------------- #
# Deploy / update: a compose run the socket only watches
# --------------------------------------------------------------------------- #
def _stack_known(stack_id: str) -> bool:
with Session(engine) as session:
return session.get(Stack, stack_id) is not None
async def _watch_run(
websocket: WebSocket,
stack_id: str,
action: str,
username: str,
stream: Callable,
on_finish: Callable[[int | None], Awaitable[None]],
) -> None:
"""Start (or attach to) the compose run and relay it until it ends.
The run belongs to :mod:`services.compose_run_service`, not to this socket:
closing the deploy console no longer releases the stack lock under a
running compose, and the audit entry carries the real exit code.
"""
if not _stack_known(stack_id):
with contextlib.suppress(Exception):
await websocket.send_text(
json.dumps({"type": "error", "detail": f"Stack '{stack_id}' not found"})
)
await websocket.close(code=4404)
return
try:
run, queue, _attached = compose_run_service.start(
stack_id, action, username, stream, on_finish
)
except compose_run_service.RunBusy as exc:
with contextlib.suppress(Exception):
await websocket.send_text(json.dumps({"type": "error", "detail": str(exc)}))
await websocket.close(code=4409)
return
async def relay() -> None:
while True:
item = await queue.get()
if item is None:
return
kind, payload = item
if kind == "log":
await websocket.send_text(json.dumps({"type": "log", "line": payload}))
else:
await websocket.send_text(json.dumps({"type": "done", "returncode": payload}))
try:
await _until_gone(websocket, relay())
finally:
run.unsubscribe(queue)
with contextlib.suppress(Exception):
await websocket.close()
@router.websocket("/ws/deploy/{stack_id}")
async def ws_deploy(
websocket: WebSocket,
stack_id: str,
token: str | None = Query(default=None),
):
"""Run `docker compose up -d` and stream its output (image pulls, container
creation) to the browser so the user sees deploy progress live. Records the
same audit entry and notification as the REST `/start` endpoint. Admin-only,
like that endpoint."""
await websocket.accept()
user = await _authorize_admin(websocket, token)
if not user:
return
username = user.username
async def finish(rc: int | None) -> None:
with Session(engine) as session:
audit_service.record(
session, user=username, action="stack.start", target=stack_id,
detail=f"rc={rc} (deploy console)", ip="ws",
)
if rc == 0:
await notify_service.notify(
EVENT_STACK_START, f"Stack '{stack_id}' started",
"compose up completed successfully.", session,
)
else:
await notify_service.notify(
EVENT_STACK_ERROR, f"Stack '{stack_id}' start failed",
"compose up returned a non-zero exit code.", session,
)
await _watch_run(
websocket, stack_id, "start", username,
lambda: compose_service.stream_up(stack_id), finish,
)
@router.websocket("/ws/update/{stack_id}")
async def ws_update(
websocket: WebSocket,
stack_id: str,
token: str | None = Query(default=None),
):
"""Run `docker compose pull && up -d` and stream its output, so the stacks
list can render real update progress. Same audit/notify contract as the
REST `/update` endpoint, which stays for non-interactive callers."""
await websocket.accept()
user = await _authorize_admin(websocket, token)
if not user:
return
username = user.username
async def finish(rc: int | None) -> None:
with Session(engine) as session:
audit_service.record(
session, user=username, action="stack.update", target=stack_id,
detail=f"rc={rc} (update stream)", ip="ws",
)
if rc == 0:
await notify_service.notify(
EVENT_STACK_START, f"Stack '{stack_id}' updated",
"compose pull + up completed successfully.", session,
)
else:
await notify_service.notify(
EVENT_PULL_FAILED, f"Stack '{stack_id}' update failed",
"compose pull/up returned a non-zero exit code.", session,
)
if rc == 0:
await asyncio.to_thread(update_service.refresh_stack_local, stack_id)
await _watch_run(
websocket, stack_id, "update", username,
lambda: compose_service.stream_update(stack_id), finish,
)
# --------------------------------------------------------------------------- #
# Docker events
# --------------------------------------------------------------------------- #
#: Docker event types worth telling the UI about. Filtered daemon-side, so the
#: bulk of the firehose never crosses the socket.
_EVENT_TYPES = ["container", "image", "network", "volume"]
#: Container actions that say nothing about state a page renders. exec_* alone
#: is three events per web-terminal keystroke session, and `top`/`attach` fire
#: whenever something inspects a container — invalidating queries on those would
#: make the stream noisier than the polling it replaces.
_IGNORED_ACTIONS = {
"exec_create", "exec_start", "exec_die", "exec_detach",
"attach", "top", "resize", "archive-path", "extract-to-dir",
}
@router.websocket("/ws/events")
async def ws_events(
websocket: WebSocket,
token: str | None = Query(default=None),
):
"""Stream Docker events so the UI can refresh on change instead of polling.
Every page used to poll its own endpoint every few seconds. Almost all of
that state only changes when Docker does something, which is exactly what
this reports — so the client refreshes on an event and keeps a slow poll as
a safety net.
Payload per event::
{"type": "event", "resource": "container", "action": "start",
"container": "jellyfin", "stack": "jellyfin"}
``resource`` is what the client needs to decide which queries to drop.
The blocking read runs on a thread of its own, not on the event loop's
shared executor: every open tab holds one reader for as long as it is open,
and on the executor a handful of tabs used up every worker — after which
each ``asyncio.to_thread`` (backups, the dashboard, NFS destinations) waited
forever.
"""
await websocket.accept()
if not await _authorize(websocket, token):
return
from docker_client import get_client
loop = asyncio.get_running_loop()
queue: asyncio.Queue = asyncio.Queue()
guard = threading.Lock()
state: dict = {"stream": None, "stop": False}
def post(item) -> None:
try:
loop.call_soon_threadsafe(queue.put_nowait, item)
except RuntimeError: # the loop is gone (shutdown)
pass
def reader() -> None:
"""Blocking read of the event stream, handed to the loop thread-safely."""
try:
stream = get_client().events(decode=True, filters={"type": _EVENT_TYPES})
with guard:
if state["stop"]:
# The client left while we were connecting.
with contextlib.suppress(Exception):
stream.close()
return
state["stream"] = stream
for event in stream:
post(event)
except Exception: # noqa: BLE001 - a closed stream lands here on teardown
pass
finally:
post(None)
threading.Thread(target=reader, name="docker-events", daemon=True).start()
gone = asyncio.create_task(_wait_disconnect(websocket))
try:
await websocket.send_text(json.dumps({"type": "ready"}))
while True:
getter = asyncio.ensure_future(queue.get())
done, _ = await asyncio.wait({getter, gone}, return_when=asyncio.FIRST_COMPLETED)
if getter not in done:
getter.cancel()
break # the client disconnected
event = getter.result()
if event is None: # reader finished — daemon gone or stream closed
await websocket.send_text(
json.dumps({"type": "error", "detail": "Docker event stream ended"})
)
break
action = (event.get("Action") or "").split(":")[0]
if action in _IGNORED_ACTIONS:
continue
actor = event.get("Actor", {}) or {}
attrs = actor.get("Attributes", {}) or {}
await websocket.send_text(
json.dumps(
{
"type": "event",
"resource": event.get("Type"),
"action": event.get("Action"),
"container": attrs.get("name"),
"stack": attrs.get("com.docker.compose.project"),
}
)
)
except WebSocketDisconnect:
pass
except Exception as exc: # noqa: BLE001
with contextlib.suppress(Exception):
await websocket.send_text(json.dumps({"type": "error", "detail": str(exc)}))
finally:
gone.cancel()
# Closing the stream is what actually unblocks the reader thread.
with guard:
state["stop"] = True
stream = state["stream"]
if stream is not None:
with contextlib.suppress(Exception):
stream.close()
@router.websocket("/ws/exec/{container_id}")
async def ws_exec(
websocket: WebSocket,
container_id: str,
token: str | None = Query(default=None),
cmd: str | None = Query(default=None),
):
"""Interactive shell into a compose-managed container (admin only)."""
await websocket.accept()
user = await _authorize_admin(websocket, token)
if not user:
return
username = user.username
shell = cmd or exec_service.DEFAULT_SHELL
try:
exec_id = exec_service.create_exec(container_id, [shell])
holder, raw = exec_service.start_exec(exec_id)
except Exception as exc: # noqa: BLE001
with contextlib.suppress(Exception):
await websocket.send_text(json.dumps({"type": "error", "detail": str(exc)}))
with contextlib.suppress(Exception):
await websocket.close()
return
with contextlib.suppress(Exception):
with Session(engine) as session:
audit_service.record(
session, user=username, action="container.exec",
target=container_id[:12], detail=shell, ip="ws",
)
try:
await exec_service.pump_exec(websocket, exec_id, holder, raw)
except WebSocketDisconnect:
pass
finally:
with contextlib.suppress(Exception):
await websocket.close()