Files
stackpilot/backend/services/exec_service.py
T
menzeljandClaude Opus 5 51d1998307
CI / check (push) Successful in 7m17s
CI / build-and-push (push) Successful in 1m45s
Remove the remote-host (agent) integration (0.48.0)
StackPilot now manages exactly one Docker host: the one it runs on. The
stackpilot-agent sidecar and everything that proxied to it are gone — 4721
lines deleted against 657 added.

Deleted outright: agent/ (image, compose, env), agent_app.py, models/agent.py,
routers/agents.py (1200 lines), services/agent_service.py, the agent API client,
RemoteStackDetail, the host components and AgentStacksSection. That removes 57
API routes and the three /ws/agent-* proxies.

Threaded out everywhere else, which was the bulk of the work. Every API module
carried an optional agentId that switched the base path; every page that listed
Docker objects rendered one section per host behind a HostHeader; Files had a
host switcher; the New Stack editor and the template dialog had host selectors;
schedules, auto-update policies and stack summaries carried agent_id. All of it
is gone, and the typechecker drove the sweep — 85 files touched, tsc and the
build clean.

Two things the removal exposed as dead weight rather than merely unused:

compose_service kept an in-process busy set purely because the agent needed a
lock and has no database. With the agent gone that was a second source of truth
next to the real DB lock, so it is deleted; compute_status now reports only what
the containers say and the two callers that want "updating" overlay the lock.
StacksTable's linkBase prop only ever existed to point at /hosts/{id}/stacks.

The dashboard's "Hosts 1/1 online" KPI can no longer say anything else, so the
tile and the KPIs behind it are gone and the row is five wide.

Upgrading matters here. An existing install still has an agent table holding
each remote host's URL and bearer token — full Docker control of that host,
sitting in the database with nothing left to use it. _drop_removed_schema drops
it on first start, and drops the agent_id columns where the SQLite build
supports DROP COLUMN. Each statement runs in its own transaction on purpose: a
failed DDL poisons the transaction it is in, so sharing one would let an
unsupported column drop take the table drop down with it. test_agent_removal
covers both branches plus the fresh-install and idempotent cases, and an
end-to-end run against a seeded pre-0.48 database confirms the table is gone and
every /api/agents route answers 404.

Docstrings that justified a design by "shared with the agent, which has no
database" were rewritten rather than left lying: update_service's persistence
callback and image_status_store are still the right split (registry logic stays
testable without a database), but for that reason now, not the old one. The
README's multi-host sections are removed and an upgrade note explains what to do
with running agent containers; ROADMAP keeps its history behind a note saying
the feature it describes no longer exists.

CI no longer builds or pushes stackpilot-agent.

735 tests pass, ruff and tsc clean.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Dk43rmEeRfYi5wsLDbmfyG
2026-08-31 14:11:54 +02:00

136 lines
4.7 KiB
Python

"""Interactive exec (web terminal) into compose-managed containers.
Reuses ``container_service._get_managed`` so a terminal can only be opened on a
container that belongs to a compose-managed stack — never an arbitrary host
container. The raw exec socket is bidirectional (stdin + a TTY-merged
stdout/stderr stream), suitable for piping straight to xterm.js.
"""
from __future__ import annotations
import asyncio
import contextlib
import json
import socket as _socket
from starlette.websockets import WebSocketDisconnect
from docker_client import get_client, safe_call
from services.container_service import _get_managed
DEFAULT_SHELL = "/bin/sh"
def create_exec(container_id: str, cmd: list[str] | None = None, tty: bool = True) -> str:
"""Create an exec instance on a managed container and return its id."""
container = _get_managed(container_id)
client = get_client()
created = safe_call(
client.api.exec_create,
container.id,
cmd or [DEFAULT_SHELL],
stdin=True,
tty=tty,
stdout=True,
stderr=True,
)
return created["Id"]
def start_exec(exec_id: str, tty: bool = True):
"""Start the exec and return ``(holder, raw_socket)``.
docker-py 7.x returns a ``socket.SocketIO`` wrapper whose real, recv/sendall
-capable fd lives at ``._sock``; older versions hand back the socket
directly. We keep both: ``holder`` is what we close, ``raw`` is what we
recv/sendall on.
"""
client = get_client()
holder = safe_call(client.api.exec_start, exec_id, socket=True, tty=tty, demux=False)
raw = getattr(holder, "_sock", None) or holder
return holder, raw
def resize_exec(exec_id: str, height: int, width: int) -> None:
"""Resize the exec's TTY (rows x cols) so the shell wraps correctly."""
client = get_client()
safe_call(client.api.exec_resize, exec_id, height=height, width=width)
def exec_exit_code(exec_id: str):
"""Return the exec's ExitCode once it has finished (None while running)."""
client = get_client()
info = safe_call(client.api.exec_inspect, exec_id)
return info.get("ExitCode")
async def pump_exec(websocket, exec_id: str, holder, raw) -> None:
"""Bidirectionally pump an exec socket <-> a WebSocket.
Browser -> container: JSON ``{"type":"data","data":...}`` keystrokes and
``{"type":"resize","rows","cols"}`` control frames (raw text is also
accepted as keystrokes). Container -> browser: ``{"type":"data","data":...}``
then a final ``{"type":"exit","code":...}``.
The blocking ``recv`` runs in the default executor; on teardown we shut the
socket down so that orphaned recv thread unblocks and exits.
"""
raw.setblocking(True)
loop = asyncio.get_event_loop()
closed = asyncio.Event()
async def to_browser() -> None:
try:
while True:
data = await loop.run_in_executor(None, raw.recv, 4096)
if not data:
break
await websocket.send_text(
json.dumps({"type": "data", "data": data.decode("utf-8", "replace")})
)
except Exception: # noqa: BLE001
pass
finally:
closed.set()
async def from_browser() -> None:
try:
while True:
msg = await websocket.receive_text()
obj = None
try:
obj = json.loads(msg)
except (json.JSONDecodeError, TypeError):
obj = None
if isinstance(obj, dict) and obj.get("type") == "resize":
with contextlib.suppress(Exception):
resize_exec(exec_id, int(obj.get("rows", 24)), int(obj.get("cols", 80)))
elif isinstance(obj, dict) and "data" in obj:
await loop.run_in_executor(None, raw.sendall, str(obj["data"]).encode())
else:
await loop.run_in_executor(None, raw.sendall, msg.encode())
except WebSocketDisconnect:
pass
except Exception: # noqa: BLE001
pass
finally:
closed.set()
out_task = asyncio.create_task(to_browser())
in_task = asyncio.create_task(from_browser())
await closed.wait()
with contextlib.suppress(Exception):
raw.shutdown(_socket.SHUT_RDWR)
with contextlib.suppress(Exception):
holder.close()
for task in (out_task, in_task):
task.cancel()
with contextlib.suppress(Exception):
await asyncio.gather(out_task, in_task, return_exceptions=True)
code = None
with contextlib.suppress(Exception):
code = exec_exit_code(exec_id)
with contextlib.suppress(Exception):
await websocket.send_text(json.dumps({"type": "exit", "code": code}))