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

145 lines
4.8 KiB
Python

"""One compose operation per stack at a time.
``docker compose`` does no locking. Two ``update`` calls against the same
project — two open browser tabs, or the auto-update pass landing on a stack
somebody just clicked — both run ``pull`` and then ``up -d``, and race each
other recreating the same containers.
There *was* a busy flag in ``compose_service``, but it only ever fed the status
column: no lifecycle handler consulted it before acting. This module is the
actual guard, and it lives in the database so it holds across workers and
across a restart. ``compose_service.compute_status`` therefore reports only
what the containers say; callers overlay the lock to show "updating".
"""
from __future__ import annotations
import logging
from contextlib import contextmanager
from datetime import datetime, timedelta, timezone
from typing import Optional
from sqlalchemy.exc import IntegrityError
from sqlmodel import Session, delete, select
from models.runtime_state import StackLock
logger = logging.getLogger("stackpilot.stack_lock")
#: Long enough to outlast the slowest legitimate operation (compose commands
#: time out at 600s, a full pull of a large stack can chain several), short
#: enough that a lock orphaned by a killed worker clears itself within an hour.
DEFAULT_TTL = timedelta(minutes=30)
class StackBusy(Exception):
"""The stack is already running an operation."""
def __init__(self, stack_id: str, action: str):
self.stack_id = stack_id
self.action = action
super().__init__(f"Stack '{stack_id}' is busy: {action} in progress")
def _now() -> datetime:
return datetime.now(timezone.utc)
def _aware(value: Optional[datetime]) -> Optional[datetime]:
"""SQLite hands datetimes back naive; compare them as UTC."""
if value is not None and value.tzinfo is None:
return value.replace(tzinfo=timezone.utc)
return value
def acquire(
session: Session,
stack_id: str,
action: str,
owner: str = "",
ttl: timedelta = DEFAULT_TTL,
) -> None:
"""Take the lock for ``stack_id`` or raise :class:`StackBusy`.
An expired lock is taken over — that is the recovery path for a worker that
died mid-deploy, which would otherwise leave the stack unusable.
"""
now = _now()
existing = session.get(StackLock, stack_id)
if existing is not None:
if (_aware(existing.expires_at) or now) > now:
raise StackBusy(stack_id, existing.action)
logger.warning(
"Taking over an expired %s lock on '%s' (held by %r since %s)",
existing.action, stack_id, existing.owner, existing.acquired_at,
)
session.delete(existing)
session.commit()
session.add(
StackLock(
stack_id=stack_id,
action=action,
owner=owner,
acquired_at=now,
expires_at=now + ttl,
)
)
try:
session.commit()
except IntegrityError as exc:
# Another worker inserted between our check and our commit. The primary
# key is what actually makes this safe; the read above is only there to
# give a useful error and to clear stale rows.
session.rollback()
raise StackBusy(stack_id, action) from exc
def release(session: Session, stack_id: str) -> None:
"""Drop the lock. Safe to call when it is not held."""
existing = session.get(StackLock, stack_id)
if existing is not None:
session.delete(existing)
session.commit()
@contextmanager
def hold(session: Session, stack_id: str, action: str, owner: str = ""):
"""Hold the lock for the duration of the block.
Raises :class:`StackBusy` if somebody else has it. Always releases, so a
failed deploy does not leave the stack locked.
"""
acquire(session, stack_id, action, owner)
try:
yield
finally:
try:
release(session, stack_id)
except Exception: # noqa: BLE001 - never mask the original error
logger.exception("Failed to release the lock on '%s'", stack_id)
def active(session: Session) -> dict[str, str]:
"""``{stack_id: action}`` for every lock still in force.
One query for the whole stacks list, rather than a lookup per row.
"""
now = _now()
return {
lock.stack_id: lock.action
for lock in session.exec(select(StackLock)).all()
if (_aware(lock.expires_at) or now) > now
}
def is_busy(session: Session, stack_id: str) -> bool:
lock = session.get(StackLock, stack_id)
return lock is not None and (_aware(lock.expires_at) or _now()) > _now()
def prune_expired(session: Session) -> int:
"""Drop locks that have timed out. Called at startup and by the scheduler."""
result = session.exec(delete(StackLock).where(StackLock.expires_at < _now()))
session.commit()
return result.rowcount or 0