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
This commit is contained in:
+3
-16
@@ -5,10 +5,9 @@
|
||||
# suite never reaches the registry (and never reaches the self-update
|
||||
# checker, which would happily offer a broken release).
|
||||
#
|
||||
# Builds and pushes the three images to this instance's container registry
|
||||
# on every push to main: backend, frontend, and agent (which is built FROM
|
||||
# the backend image - see agent/Dockerfile - so it has to come after). Each
|
||||
# image gets both a ":latest" tag and a ":{APP_VERSION}" tag, the latter read
|
||||
# Builds and pushes both images to this instance's container registry on every
|
||||
# push to main: backend and frontend. Each image gets both a ":latest" tag and
|
||||
# a ":{APP_VERSION}" tag, the latter read
|
||||
# from backend/version.py (the single source of truth for the release
|
||||
# version) - self_update_service compares registry version *tags* against the
|
||||
# running APP_VERSION to decide whether an update is available, so without a
|
||||
@@ -105,15 +104,3 @@ jobs:
|
||||
./frontend
|
||||
docker push "$REGISTRY/stackpilot-frontend:latest"
|
||||
docker push "$REGISTRY/stackpilot-frontend:${{ steps.version.outputs.version }}"
|
||||
|
||||
# Uses the backend image just pushed above as its base (already in the
|
||||
# local Docker cache from that step, so this doesn't need to pull it).
|
||||
- name: Build and push agent
|
||||
run: |
|
||||
docker build \
|
||||
--build-arg "BACKEND_IMAGE=$REGISTRY/stackpilot-backend:latest" \
|
||||
-t "$REGISTRY/stackpilot-agent:latest" \
|
||||
-t "$REGISTRY/stackpilot-agent:${{ steps.version.outputs.version }}" \
|
||||
./agent
|
||||
docker push "$REGISTRY/stackpilot-agent:latest"
|
||||
docker push "$REGISTRY/stackpilot-agent:${{ steps.version.outputs.version }}"
|
||||
|
||||
@@ -4,17 +4,43 @@ A self-hosted Docker Compose manager for power users and homelab enthusiasts —
|
||||
as intuitive as Dockge, as capable as Portainer for Compose workflows.
|
||||
|
||||
> **Status:** Phase 1 (Core) + Phase 2 (Volumes & GPU) + Phase 3 (Quality of
|
||||
> Life) + Phase 4 (Operations) + Phase 5 (Multi-host) + Phase 6 (Backup
|
||||
> destinations) + Phase 7 (Scheduled backups) + Phase 8 (Remote-stack backups)
|
||||
> + Phase 9 (Networks) + Phase 10 (iGPU passthrough) + Phase 11 (Remote UX &
|
||||
> network attach) + Phase 12 (File browser) + Phase 13 (Multi-host networks &
|
||||
> images) + Phase 14 (Multi-host file browser) + Phase 15 (Dashboard stack
|
||||
> resource usage) + Phase 16 (Volumes page, multi-host) + Phase 17 (Multi-host
|
||||
> dashboard) + Phase 18 (Image prune) + Phase 19 (Compose validate & diff) +
|
||||
> Life) + Phase 4 (Operations) + Phase 6 (Backup destinations) + Phase 7
|
||||
> (Scheduled backups) + Phase 9 (Networks) + Phase 10 (iGPU passthrough) +
|
||||
> Phase 11 (Network attach) + Phase 12 (File browser) + Phase 13 (Network &
|
||||
> image management) + Phase 15 (Dashboard stack resource usage) +
|
||||
> Phase 16 (Volumes page) + Phase 18 (Image prune) + Phase 19 (Compose validate & diff) +
|
||||
> Phase 20 (Container management) + Phase 21 (Container terminal) + Phase 22
|
||||
> (Auto-update) + Phase 23 (Secrets & configs) + Phase 24 (Design System v2)
|
||||
> complete.
|
||||
|
||||
## Upgrading to 0.48.0 — remote hosts are gone
|
||||
|
||||
The multi-host feature (the `stackpilot-agent` sidecar and everything that
|
||||
proxied to it) has been removed. StackPilot now manages exactly one Docker
|
||||
host: the one it runs on.
|
||||
|
||||
**If you never registered a remote host, nothing changes for you.** Otherwise:
|
||||
|
||||
- **Stop and remove your `stackpilot-agent` containers.** They will simply sit
|
||||
there unused; nothing talks to them any more. The `stackpilot-agent` image is
|
||||
no longer built or published.
|
||||
- **Registered hosts are deleted from the database on first start**, together
|
||||
with the bearer tokens they held. That is deliberate: leaving credentials for
|
||||
a feature that no longer exists is worse than dropping them.
|
||||
- **Backup schedules that targeted a remote stack will fail** with "stack not
|
||||
found" until you delete them under Settings → Scheduled backups. Their
|
||||
`agent_id` column is dropped where SQLite supports it.
|
||||
- **Stacks that lived on a remote host are untouched on that host** — StackPilot
|
||||
just no longer sees them. Their compose files are still in that host's stacks
|
||||
directory and `docker compose` still works there, which is the point of the
|
||||
file-is-the-truth model.
|
||||
|
||||
Gone with it: the host switcher on the Files page, the per-host sections on
|
||||
Stacks / Networks / Images / Volumes / Dashboard, the host selector in the New
|
||||
Stack editor and the template dialog, Settings → Remote hosts, and the
|
||||
`/api/agents/*` and `/ws/agent-*` endpoints (57 API routes and 3 WebSocket
|
||||
routes in total).
|
||||
|
||||
## Upgrading to 0.47.0 — nothing to do
|
||||
|
||||
Three pieces of state moved out of process memory and into the database, and
|
||||
@@ -112,7 +138,6 @@ it is what your saved destination credentials are encrypted with.
|
||||
- **Live deploy console** — deploying from the editor streams `compose up`
|
||||
output (image pulls, container creation) over a WebSocket in real time instead
|
||||
of a blind spinner; the deploy keeps running server-side if the modal is closed.
|
||||
Works for **remote** stacks too — the central app proxies the agent's deploy
|
||||
stream through to the browser. Compose runs with `--progress json`, so the
|
||||
console shows a **real progress bar** (download bytes per layer, weighted by
|
||||
layer size, then container create/start) plus a per-image bar; the raw output
|
||||
@@ -205,17 +230,6 @@ it is what your saved destination credentials are encrypted with.
|
||||
- **Audit log page** (admin): searchable, paginated view of all recorded actions.
|
||||
- **Mobile-responsive layout**: off-canvas sidebar + adaptive spacing.
|
||||
|
||||
### Phase 5 — Multi-host
|
||||
|
||||
- **Remote agents**: deploy `stackpilot-agent` (same image, different CMD) on any
|
||||
host — it needs only the Docker socket and a shared `AGENT_TOKEN`, and exposes a
|
||||
slim, token-guarded stack/system API (no UI, no DB).
|
||||
- **Central management**: add hosts under **Settings → Remote hosts** (name, agent
|
||||
URL, token) with a live connectivity dot. The Stacks page groups stacks by host
|
||||
("This host" + one section per agent); remote stacks have their own detail view
|
||||
with full lifecycle (start/stop/restart/pull/update/down), live logs, and
|
||||
compose/.env editing — all proxied to the agent.
|
||||
|
||||
### Phase 6 — Backup destinations
|
||||
|
||||
- **Off-box backups**: define **SFTP**, **S3-compatible** (MinIO, Backblaze B2,
|
||||
@@ -226,7 +240,7 @@ it is what your saved destination credentials are encrypted with.
|
||||
config changes) and file I/O runs through throwaway helper containers.
|
||||
- **Push & restore**: the stack Backup dialog can push straight to a destination
|
||||
instead of downloading; the Restore dialog can browse a destination's backups
|
||||
and restore (volumes included) directly from it. Remote backups can also be
|
||||
and restore (volumes included) directly from it. Backups can also be
|
||||
deleted from the UI.
|
||||
|
||||
### Phase 7 — Scheduled backups
|
||||
@@ -239,16 +253,6 @@ it is what your saved destination credentials are encrypted with.
|
||||
- **Run now** for an on-demand run, plus a `backup_failed` notification event
|
||||
wired into the webhook system.
|
||||
|
||||
### Phase 8 — Remote-stack backups
|
||||
|
||||
- **Back up agent stacks**: the agent exposes its own backup/restore endpoints,
|
||||
and the main app streams a remote stack's backup through to a destination
|
||||
(credentials stay central — agents never see them). Remote stack detail has a
|
||||
**Backup** button; each host section on the Stacks page has a **Restore** button.
|
||||
- **Schedule remote stacks**: a backup schedule can target a remote host; backups
|
||||
are namespaced per host (`backup-<host>-<stack>-…`) so retention never prunes
|
||||
across hosts sharing a destination.
|
||||
|
||||
### Phase 9 — Networks
|
||||
|
||||
- **Network management**: the Networks page lists Docker networks (driver, scope,
|
||||
@@ -268,14 +272,8 @@ it is what your saved destination credentials are encrypted with.
|
||||
resolve inside images, so the numeric GID is what actually grants access. The
|
||||
GPU selector shows the detected GIDs; removal cleans them (and `LIBVA_DRIVER_NAME`).
|
||||
|
||||
### Phase 11 — Remote UX & network attach
|
||||
### Phase 11 — Network attach
|
||||
|
||||
- **Live remote logs**: remote-stack logs now stream over a WebSocket proxied
|
||||
through the central app to the agent (`/ws/agent-logs/{agent}/{stack}`), instead
|
||||
of polling — same live viewer as local stacks.
|
||||
- **Deploy to a remote host from the UI**: the New Stack editor and the template
|
||||
dialog gained a *host* selector. Pick an online agent and the stack is created
|
||||
(and optionally started) on that host; you land on its remote detail page.
|
||||
- **Network attach/detach**: each network row on the Networks page expands to an
|
||||
inspect view listing connected containers, with admin controls to disconnect a
|
||||
container or connect any container on the host (`POST /api/networks/{id}/connect`
|
||||
@@ -285,7 +283,7 @@ it is what your saved destination credentials are encrypted with.
|
||||
|
||||
- **New shell**: the sidebar is gone — a fixed 60px top bar carries a pill
|
||||
navigation (active route = dark pill), the logo mark, a version badge, a
|
||||
remote-host online indicator, theme toggle and an avatar menu. Narrow
|
||||
theme toggle and an avatar menu. Narrow
|
||||
screens get an off-canvas drawer.
|
||||
- **Design tokens** (`frontend/src/styles/tokens.css`): one CSS-variable set
|
||||
for surfaces, borders, text tiers, brand colours, radii and type scales,
|
||||
@@ -299,7 +297,7 @@ it is what your saved destination credentials are encrypted with.
|
||||
auto-update policy). SVG waterfall with alternating gradient /
|
||||
diagonal-hatch bars, value chips and hover conversion/drop-off tooltips.
|
||||
- **Summary widgets** from `GET /api/dashboard/summary`: compose-containers
|
||||
card with per-host breakdown (agents report a compose-only count) and an
|
||||
card and an
|
||||
"Insights" chip (healthy-rate %), a 30-day uptime line chart (sampled every
|
||||
5 min into `DATA_DIR/uptime.jsonl`, charted as daily averages), and an ops
|
||||
contribution grid from audit-log activity with the peak weekday.
|
||||
@@ -323,9 +321,7 @@ it is what your saved destination credentials are encrypted with.
|
||||
compose file is rewritten in place (top-level `secrets:`/`configs:` defs are
|
||||
pruned when no service still uses them); **redeploy the stack to apply**.
|
||||
- **Admin-only** (secrets are sensitive); every write/delete/attach/detach is
|
||||
audited (`secret.*`). Works for **remote stacks** too — the agent stores the
|
||||
files on its own host (`/agent/stacks/{id}/secrets/*`, proxied via
|
||||
`/api/agents/{id}/stacks/{id}/secrets/*`). Names are validated against path
|
||||
audited (`secret.*`). Names are validated against path
|
||||
traversal (single component, no `..`, no leading dot); content capped at 1 MiB.
|
||||
|
||||
### Phase 22 — Auto-update (Watchtower-style)
|
||||
@@ -337,10 +333,8 @@ it is what your saved destination credentials are encrypted with.
|
||||
- Runs inside the existing image-update-check cycle (reuses the freshly-computed
|
||||
digest cache, no extra registry calls). Only **running** stacks are
|
||||
auto-redeployed — a stopped stack is never silently started ("skipped").
|
||||
- New `stack_auto_updated` notification event. Works for **remote stacks** too
|
||||
(policy stored centrally; the agent answers `/agent/stacks/{id}/updates` and
|
||||
performs the redeploy). Last run + status (updated / up-to-date /
|
||||
update-available / skipped / error) are shown inline.
|
||||
- New `stack_auto_updated` notification event. Last run + status (updated /
|
||||
up-to-date / update-available / skipped / error) are shown inline.
|
||||
|
||||
### Phase 21 — Container terminal (web exec)
|
||||
|
||||
@@ -351,9 +345,6 @@ it is what your saved destination credentials are encrypted with.
|
||||
- **Admin-only** (exec is root-equivalent): a non-admin token is rejected at the
|
||||
WebSocket handshake (`4403`). Only containers with the
|
||||
`com.docker.compose.project` label can be reached.
|
||||
- Works for **remote stacks** too: the same terminal proxies through
|
||||
`/ws/agent-exec/{agent_id}/{container_id}` to the agent's new
|
||||
`/agent/ws/exec/{container_id}` (bidirectional — keystrokes in, output out).
|
||||
|
||||
### Phase 20 — Container management
|
||||
|
||||
@@ -365,9 +356,6 @@ it is what your saved destination credentials are encrypted with.
|
||||
- Admins get **per-container start / stop / restart** buttons directly on the
|
||||
card (`POST /api/containers/{id}/{action}`), so a single misbehaving service
|
||||
can be bounced without touching the rest of the stack.
|
||||
- Works for **remote stacks** too — the same card is used on the remote stack
|
||||
detail page, proxied through `/api/agents/{id}/containers/*` to the agent's
|
||||
new `/agent/containers/*` endpoints.
|
||||
- Only containers carrying the `com.docker.compose.project` label are exposed,
|
||||
so this never becomes a generic "control any container on the host" backdoor.
|
||||
|
||||
@@ -380,33 +368,17 @@ it is what your saved destination credentials are encrypted with.
|
||||
### Phase 18 — Image prune
|
||||
|
||||
- **Prune images** (dangling, or all unused) from the Images page, on the local
|
||||
host and on each agent.
|
||||
host.
|
||||
|
||||
### Phase 17 — Multi-host dashboard
|
||||
### Phase 16 — Volumes page
|
||||
|
||||
- The dashboard now shows, **per host** (local + each registered agent, online
|
||||
dot / offline notice), a **resource overview bar** (CPU cores, memory
|
||||
used/total, disk used/total, Docker volumes total, containers, Docker version)
|
||||
and a **stacks-with-usage table** with CPU/memory meters and inline
|
||||
start/stop/restart. The volumes total reuses the cached `/volumes/sizes`
|
||||
lookup (`docker system df`), polled gently (~60s).
|
||||
- New agent endpoint `/agent/stacks/stats` (proxied at
|
||||
`/api/agents/{id}/stacks/stats`); `/agent/system` now also reports `cpu_cores`,
|
||||
`mem_total`, `mem_used`, and `disk_total`/`disk_used` (disk of the host volume
|
||||
backing the stacks dir) so the remote resource bar and meters have a host
|
||||
reference.
|
||||
|
||||
### Phase 16 — Volumes page (multi-host)
|
||||
|
||||
- **New Volumes page** (sidebar) with per-host sections (local + each online
|
||||
agent, like Networks/Images). Lists Docker volumes with driver, owning stack,
|
||||
- **New Volumes page** (sidebar). Lists Docker volumes with driver, owning stack,
|
||||
in-use containers and mountpoint.
|
||||
- Admin actions: delete a volume (with an in-use warning + force option) and
|
||||
**Prune unused**; an *Only unused* filter. New agent endpoints
|
||||
`/agent/volumes` (list/delete/prune), proxied at `/api/agents/{id}/volumes/*`.
|
||||
**Prune unused**; an *Only unused* filter.
|
||||
- **Volume sizes** are loaded on demand via a *Compute sizes* button (runs
|
||||
`docker system df`, which walks volume contents and can take a few seconds);
|
||||
results are cached ~60s. Endpoint `GET /api/volumes/sizes` (+ per-agent).
|
||||
results are cached ~60s. Endpoint `GET /api/volumes/sizes`.
|
||||
- The Volume **Wizard** in the stack editor (bind/named/NFS/SMB/tmpfs YAML
|
||||
generation) is unchanged — the new page is for managing/cleaning up volumes.
|
||||
|
||||
@@ -420,29 +392,14 @@ it is what your saved destination credentials are encrypted with.
|
||||
otherwise it shows absolute usage against the host total. Inline start/stop/
|
||||
restart actions per row for admins. New endpoint `GET /api/stacks/stats`.
|
||||
|
||||
### Phase 14 — Multi-host file browser
|
||||
### Phase 13 — Network & image management
|
||||
|
||||
- **The Files page now has a host switcher.** When agents are registered, a
|
||||
*Host* dropdown at the top switches the whole browser between the local host
|
||||
and any online agent; switching resets the path and clipboard.
|
||||
- All file operations (browse, view/edit, create, rename, copy/move, delete,
|
||||
upload files & folders, download) work against the selected agent, sandboxed
|
||||
by *that agent's* `ALLOWED_BROWSE_ROOTS`/`HOST_ROOT_PREFIX`.
|
||||
- New agent endpoints `/agent/files/*`, proxied at `/api/agents/{id}/files/*`.
|
||||
|
||||
### Phase 13 — Multi-host networks & images
|
||||
|
||||
- **Networks and Images are now per-host.** Both pages render a section for the
|
||||
local host plus one for every registered agent (online dot included), exactly
|
||||
like the Stacks page. Each agent section talks to that host's Docker daemon.
|
||||
- **Remote network management**: list, inspect, create, delete, prune, and
|
||||
connect/disconnect containers on an agent host — including a *Prune unused*
|
||||
button, which resolves the common "all predefined address pools have been
|
||||
fully subnetted" deploy error without SSH.
|
||||
- **Remote images**: list image tags (with using-stacks) and run on-demand update
|
||||
checks per host.
|
||||
- New agent endpoints `/agent/networks/*` and `/agent/images/*`, proxied through
|
||||
the central app at `/api/agents/{id}/networks/*` and `/api/agents/{id}/images/*`.
|
||||
- **Network management**: list, inspect, create, delete, prune, and
|
||||
connect/disconnect containers — including a *Prune unused* button, which
|
||||
resolves the common "all predefined address pools have been fully subnetted"
|
||||
deploy error without SSH.
|
||||
- **Images**: list image tags (with using-stacks) and run on-demand update
|
||||
checks.
|
||||
|
||||
### Phase 12 — File browser
|
||||
|
||||
@@ -465,7 +422,7 @@ it is what your saved destination credentials are encrypted with.
|
||||
- **Sandboxed**: all access is confined to `ALLOWED_BROWSE_ROOTS`; path
|
||||
traversal and deleting a browse root are refused. StackPilot's own `DATA_DIR`
|
||||
is refused regardless of the setting — it holds `stackpilot.db` with password
|
||||
hashes, agent tokens and backup-destination credentials, none of which the API
|
||||
hashes and backup-destination credentials, none of which the API
|
||||
itself ever hands out. Note that a single `/` entry in `ALLOWED_BROWSE_ROOTS`
|
||||
switches the sandbox off entirely; it is no longer part of the default. To reach the real host
|
||||
filesystem, mount it into the backend and set `HOST_ROOT_PREFIX` (see the
|
||||
@@ -474,17 +431,6 @@ it is what your saved destination credentials are encrypted with.
|
||||
`move`, `upload` — with optional `rel_path` for folder uploads —, `download`,
|
||||
`DELETE`).
|
||||
|
||||
## Deploying an agent on another host
|
||||
|
||||
```bash
|
||||
cd agent
|
||||
cp .env.example .env # set a strong AGENT_TOKEN
|
||||
docker compose up -d # exposes the agent on :5010
|
||||
```
|
||||
|
||||
Then in the central UI: **Settings → Remote hosts → Add host** with
|
||||
`http://<that-host>:5010` and the same `AGENT_TOKEN`.
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
@@ -563,7 +509,7 @@ Same three commands the CI runs — `build-and-push` only starts once they pass.
|
||||
```bash
|
||||
cd backend
|
||||
pip install -r requirements-dev.txt
|
||||
pytest # 729 tests, no Docker daemon needed
|
||||
pytest # 735 tests, no Docker daemon needed
|
||||
ruff check .
|
||||
cd ../frontend && npx tsc --noEmit -p tsconfig.json
|
||||
```
|
||||
@@ -573,14 +519,12 @@ never opens a Docker socket and never starts the background loops; `conftest.py`
|
||||
points `DATA_DIR`/`STACKS_DIR` at a temp directory before anything is imported.
|
||||
|
||||
The load-bearing one is `tests/test_route_authorization.py`. Authorization lives
|
||||
in the routers — each of 171 routes independently picks `require_admin` or
|
||||
in the routers — each route independently picks `require_admin` or
|
||||
`get_current_user`, and nothing checked that the choice was right, which is how
|
||||
0.43.0 shipped a read-only role that could download the auth database. That file
|
||||
states the policy once — *every route requires admin unless it is listed* — and
|
||||
fails on any route that disagrees. Adding a route the `user` role may reach means
|
||||
adding it to `USER_READABLE` with a note on why it cannot return a credential.
|
||||
`tests/test_agent_authorization.py` does the same for the agent, where a single
|
||||
forgotten `Depends(verify_token)` would expose a whole host.
|
||||
|
||||
`tests/test_token_revocation.py` covers the revoke switch — that each of the
|
||||
three authority changes kills the account's tokens, that a cosmetic re-save does
|
||||
@@ -594,8 +538,8 @@ that moved into the database: that a busy stack answers 409 without ever
|
||||
reaching Docker, that an expired lock is taken over rather than stranding the
|
||||
stack, that the stats cache serves repeat callers from one sweep, and that the
|
||||
update cache and rate limiter survive a restart. One of them asserts that
|
||||
`update_service` never imports the database — it is shared with the agent,
|
||||
which has none, so persistence has to stay opt-in.
|
||||
`update_service` never imports the database — it is pure registry logic, and
|
||||
persistence stays opt-in so the module remains testable without one.
|
||||
|
||||
`tests/test_bundled_templates.py` covers the 83 shipped templates: each must
|
||||
parse, name an image per service, keep `.env.example` in sync with the variables
|
||||
@@ -648,22 +592,6 @@ GET /api/auth/users POST /api/auth/users
|
||||
PATCH /api/auth/users/{id} DELETE /api/auth/users/{id}
|
||||
```
|
||||
|
||||
### Phase 5 endpoints
|
||||
|
||||
```
|
||||
GET /api/agents POST /api/agents
|
||||
PUT /api/agents/{id} DELETE /api/agents/{id}
|
||||
POST /api/agents/{id}/ping GET /api/agents/{id}/system
|
||||
GET /api/agents/{id}/stacks | /{sid} GET /api/agents/{id}/stacks/{sid}/logs
|
||||
POST /api/agents/{id}/stacks PUT /api/agents/{id}/stacks/{sid}
|
||||
DELETE /api/agents/{id}/stacks/{sid} POST /api/agents/{id}/stacks/{sid}/{action}
|
||||
|
||||
agent (on the remote host, Bearer AGENT_TOKEN):
|
||||
GET /agent/ping | /system | /stacks | /stacks/{id} | /stacks/{id}/logs
|
||||
GET /agent/stacks/{id}/backup POST /agent/stacks/restore
|
||||
POST /agent/stacks | /stacks/{id}/{action} PUT/DELETE /agent/stacks/{id}
|
||||
```
|
||||
|
||||
### Phase 6 endpoints
|
||||
|
||||
```
|
||||
@@ -682,14 +610,6 @@ PUT /api/backups/schedules/{id} DELETE /api/backups/schedules
|
||||
POST /api/backups/schedules/{id}/run
|
||||
```
|
||||
|
||||
### Phase 8 endpoints (remote-stack backups)
|
||||
|
||||
```
|
||||
GET /api/agents/{id}/stacks/{sid}/backup POST /api/agents/{id}/stacks/{sid}/backup/push
|
||||
POST /api/agents/{id}/stacks/restore POST /api/agents/{id}/stacks/restore-from
|
||||
backup schedules accept an optional agent_id to target a remote host.
|
||||
```
|
||||
|
||||
### Phase 9 endpoints
|
||||
|
||||
```
|
||||
@@ -701,10 +621,8 @@ DELETE /api/stacks/{id}?delete_files= (stack delete, now surfaced in
|
||||
### Phase 11 endpoints
|
||||
|
||||
```
|
||||
WS /ws/agent-logs/{agent_id}/{stack_id} (live remote logs, proxied to the agent)
|
||||
GET /api/networks/{id}/containers POST /api/networks/{id}/connect | /disconnect
|
||||
POST /api/agents/{id}/stacks (create a stack on a remote host — now in the UI)
|
||||
POST /api/templates/{id}/instantiate {agent_id} (instantiate a template onto a remote host)
|
||||
POST /api/templates/{id}/instantiate (create a stack from a template)
|
||||
```
|
||||
|
||||
### Phase 24 endpoints
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
# StackPilot Roadmap — Phases 21–23
|
||||
|
||||
> **Historical record.** Phases below describe work as it shipped at the time.
|
||||
> The multi-host / agent integration they refer to was removed in 0.48.0 —
|
||||
> StackPilot manages a single Docker host. Anything here mentioning
|
||||
> `agent_app.py`, `AGENT_TOKEN`, `/api/agents/*` or `/ws/agent-*` no longer
|
||||
> exists; the entries are kept because they record what was actually done, not
|
||||
> what is currently true.
|
||||
|
||||
Planned 2026-06-09. Status keys: ☐ not started · ◐ in progress · ☑ done.
|
||||
Each phase ships independently following the standing release checklist
|
||||
(bump `backend/main.py` + `backend/agent_app.py` AGENT_VERSION +
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
# Shared secret the central StackPilot must present to manage this host.
|
||||
# Generate with: openssl rand -base64 32
|
||||
# Enter the SAME value when adding this host under Settings → Remote hosts.
|
||||
AGENT_TOKEN=change-me-to-a-long-random-shared-secret
|
||||
|
||||
# Host directory where this host's stack folders live.
|
||||
STACKS_HOST_DIR=./data/stacks
|
||||
@@ -1,17 +0,0 @@
|
||||
# The agent reuses the backend image (same compose/Docker code + deps) and
|
||||
# just runs a different ASGI app. Build the backend image first.
|
||||
ARG BACKEND_IMAGE=git.menzel.center/menzeljonas/stackpilot-backend:latest
|
||||
FROM ${BACKEND_IMAGE}
|
||||
|
||||
ENV STACKS_DIR=/opt/stacks \
|
||||
PORT=5010
|
||||
|
||||
EXPOSE 5010
|
||||
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s \
|
||||
CMD curl -fsS http://localhost:5010/agent/health || exit 1
|
||||
|
||||
# Wie beim Backend: falls jemand einen TLS-Proxy vor den Agent setzt, soll die
|
||||
# echte Client-IP in den Logs stehen.
|
||||
CMD ["uvicorn", "agent_app:app", "--host", "0.0.0.0", "--port", "5010", \
|
||||
"--proxy-headers", "--forwarded-allow-ips", "*"]
|
||||
@@ -1,26 +0,0 @@
|
||||
# StackPilot agent — deploy this on each remote host you want to manage.
|
||||
# It needs only the Docker socket and a shared AGENT_TOKEN (must match the
|
||||
# token you enter when adding this host in the central StackPilot UI).
|
||||
services:
|
||||
agent:
|
||||
image: git.menzel.center/menzeljonas/stackpilot-agent:latest
|
||||
build:
|
||||
context: .
|
||||
args:
|
||||
BACKEND_IMAGE: git.menzel.center/menzeljonas/stackpilot-backend:latest
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
- AGENT_TOKEN=${AGENT_TOKEN:?set AGENT_TOKEN in .env}
|
||||
- STACKS_DIR=/opt/stacks
|
||||
- HOST_PROC_PATH=/host_proc
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
# Same rule as the central app: this must resolve to the same path as
|
||||
# STACKS_DIR, or the stacks' relative bind mounts (./config) end up at the
|
||||
# container path on the host, where the agent cannot see them.
|
||||
- ${STACKS_HOST_DIR:-/opt/stacks}:/opt/stacks
|
||||
- /proc:/host_proc:ro
|
||||
# Read-only host devices for status/detection parity with the main host.
|
||||
- /dev:/dev:ro
|
||||
ports:
|
||||
- "5010:5010"
|
||||
@@ -1,857 +0,0 @@
|
||||
"""StackPilot agent — a slim, token-guarded Docker Compose API for one host.
|
||||
|
||||
The agent runs on each remote host (same image as the backend, different CMD).
|
||||
It has no users, no database and no UI: it exposes just enough of the stack /
|
||||
system surface for a central StackPilot to manage this host's compose stacks,
|
||||
authenticated by a single shared bearer token (``AGENT_TOKEN``).
|
||||
|
||||
All compose/Docker logic is reused from the backend's ``compose_service`` and
|
||||
``docker_client`` so behaviour matches the local host exactly.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
from dataclasses import asdict
|
||||
|
||||
import tempfile
|
||||
|
||||
import json
|
||||
|
||||
from fastapi import (
|
||||
Depends,
|
||||
FastAPI,
|
||||
File,
|
||||
Form,
|
||||
Header,
|
||||
HTTPException,
|
||||
Query,
|
||||
Request,
|
||||
UploadFile,
|
||||
WebSocket,
|
||||
WebSocketDisconnect,
|
||||
)
|
||||
from fastapi.responses import FileResponse, JSONResponse, StreamingResponse
|
||||
from pydantic import BaseModel
|
||||
|
||||
from config import settings
|
||||
from version import APP_VERSION
|
||||
from docker_client import DockerError, get_client, safe_call
|
||||
from services import (
|
||||
backup_service,
|
||||
compose_edit_service,
|
||||
compose_service,
|
||||
container_service,
|
||||
device_service,
|
||||
exec_service,
|
||||
file_service,
|
||||
image_service,
|
||||
network_service,
|
||||
secret_service,
|
||||
stats_service,
|
||||
update_service,
|
||||
volume_service,
|
||||
)
|
||||
|
||||
logger = logging.getLogger("stackpilot.agent")
|
||||
|
||||
# Map network_service's DockerError codes to HTTP status. forbidden is mapped to
|
||||
# 400 (not 403) so the central proxy doesn't misread it as a token failure.
|
||||
_DOCKER_STATUS = {"invalid_request": 400, "forbidden": 400, "not_found": 404}
|
||||
|
||||
|
||||
def _map_docker(exc: DockerError):
|
||||
code = _DOCKER_STATUS.get(exc.error)
|
||||
if code:
|
||||
raise HTTPException(status_code=code, detail=exc.detail or exc.error)
|
||||
raise exc # falls through to the global 502 DockerError handler
|
||||
|
||||
AGENT_VERSION = APP_VERSION
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Auth
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
def verify_token(authorization: str = Header(default="")) -> None:
|
||||
expected = settings.AGENT_TOKEN
|
||||
if not expected:
|
||||
raise HTTPException(status_code=503, detail="Agent token not configured")
|
||||
if authorization != f"Bearer {expected}":
|
||||
raise HTTPException(status_code=401, detail="Invalid agent token")
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Schemas
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
class StackBody(BaseModel):
|
||||
name: str | None = None
|
||||
yaml: str | None = None
|
||||
env: str | None = None
|
||||
|
||||
|
||||
class NetworkCreateBody(BaseModel):
|
||||
name: str
|
||||
driver: str = "bridge"
|
||||
subnet: str | None = None
|
||||
gateway: str | None = None
|
||||
internal: bool = False
|
||||
attachable: bool = True
|
||||
|
||||
|
||||
class ContainerRefBody(BaseModel):
|
||||
container: str
|
||||
aliases: list[str] | None = None
|
||||
force: bool = False
|
||||
|
||||
|
||||
class FileWriteBody(BaseModel):
|
||||
path: str
|
||||
content: str
|
||||
|
||||
|
||||
class FileNameBody(BaseModel):
|
||||
path: str
|
||||
name: str
|
||||
|
||||
|
||||
class FileRenameBody(BaseModel):
|
||||
path: str
|
||||
new_name: str
|
||||
|
||||
|
||||
class FileTransferBody(BaseModel):
|
||||
src: str
|
||||
dest_dir: str
|
||||
overwrite: bool = False
|
||||
|
||||
|
||||
def _file_guard(fn, *args, **kwargs):
|
||||
try:
|
||||
return fn(*args, **kwargs)
|
||||
except file_service.BrowseError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Helpers
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
def _summary(stack_id: str, summaries: dict | None = None) -> dict:
|
||||
if summaries is None:
|
||||
try:
|
||||
containers = compose_service.containers_for_stack(stack_id)
|
||||
total = len(containers)
|
||||
running = sum(1 for c in containers if c.state == "running")
|
||||
status = compose_service.compute_status(stack_id, containers)
|
||||
except DockerError:
|
||||
total = running = 0
|
||||
status = "unknown"
|
||||
else:
|
||||
info = summaries.get(stack_id)
|
||||
total = info["total"] if info else 0
|
||||
running = info["running"] if info else 0
|
||||
if compose_service.is_busy(stack_id):
|
||||
status = "updating"
|
||||
else:
|
||||
status = info["status"] if info else "stopped"
|
||||
return {
|
||||
"id": stack_id,
|
||||
"name": stack_id,
|
||||
"description": None,
|
||||
"status": status,
|
||||
"service_count": total,
|
||||
"running_count": running,
|
||||
"created_at": None,
|
||||
"updated_at": None,
|
||||
}
|
||||
|
||||
|
||||
def _hostname() -> str:
|
||||
return os.uname().nodename
|
||||
|
||||
|
||||
def _mem_info() -> tuple[int, int]:
|
||||
"""Return (total_bytes, used_bytes) from meminfo (used = total - available)."""
|
||||
for base in (settings.HOST_PROC_PATH, "/proc"):
|
||||
try:
|
||||
vals: dict[str, int] = {}
|
||||
with open(os.path.join(base, "meminfo"), "r", encoding="utf-8") as fh:
|
||||
for line in fh:
|
||||
parts = line.split(":")
|
||||
if len(parts) == 2 and parts[0] in ("MemTotal", "MemAvailable", "MemFree"):
|
||||
try:
|
||||
vals[parts[0]] = int(parts[1].split()[0]) * 1024 # kB -> bytes
|
||||
except ValueError:
|
||||
pass
|
||||
total = vals.get("MemTotal", 0)
|
||||
available = vals.get("MemAvailable", vals.get("MemFree", 0))
|
||||
return total, max(total - available, 0)
|
||||
except OSError:
|
||||
continue
|
||||
return 0, 0
|
||||
|
||||
|
||||
def _disk_info() -> tuple[int, int]:
|
||||
"""Return (total_bytes, used_bytes) for the host disk backing the stacks dir."""
|
||||
for path in (settings.STACKS_DIR, "/"):
|
||||
try:
|
||||
usage = shutil.disk_usage(path)
|
||||
return usage.total, usage.used
|
||||
except OSError:
|
||||
continue
|
||||
return 0, 0
|
||||
|
||||
|
||||
def _system_info() -> dict:
|
||||
docker_version = ""
|
||||
host_os = ""
|
||||
running = total = compose_running = 0
|
||||
try:
|
||||
client = get_client()
|
||||
docker_version = safe_call(client.version).get("Version", "")
|
||||
info = safe_call(client.info)
|
||||
host_os = info.get("OperatingSystem", "")
|
||||
running = info.get("ContainersRunning", 0)
|
||||
total = info.get("Containers", 0)
|
||||
# Running compose-managed containers — the dashboard's container card
|
||||
# compares this across hosts; counting everything would include this
|
||||
# agent itself and skew the bars.
|
||||
compose_running = len(
|
||||
safe_call(client.api.containers, filters={"label": compose_service.COMPOSE_LABEL})
|
||||
)
|
||||
except DockerError as exc:
|
||||
docker_version = f"unavailable ({exc.error})"
|
||||
mem_total, mem_used = _mem_info()
|
||||
disk_total, disk_used = _disk_info()
|
||||
return {
|
||||
"hostname": _hostname(),
|
||||
"docker_version": docker_version,
|
||||
"host_os": host_os,
|
||||
"cpu_cores": os.cpu_count() or 0,
|
||||
"mem_total": mem_total,
|
||||
"mem_used": mem_used,
|
||||
"disk_total": disk_total,
|
||||
"disk_used": disk_used,
|
||||
"containers_running": running,
|
||||
"containers_total": total,
|
||||
"compose_running": compose_running,
|
||||
}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# App
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
app = FastAPI(title="StackPilot Agent", version=AGENT_VERSION)
|
||||
|
||||
|
||||
@app.exception_handler(DockerError)
|
||||
async def _docker_error(_request: Request, exc: DockerError):
|
||||
return JSONResponse(status_code=502, content={"error": exc.error, "detail": exc.detail})
|
||||
|
||||
|
||||
@app.get("/agent/ping", dependencies=[Depends(verify_token)])
|
||||
def ping() -> dict:
|
||||
return {"ok": True, "hostname": _hostname(), "version": AGENT_VERSION}
|
||||
|
||||
|
||||
@app.get("/agent/system", dependencies=[Depends(verify_token)])
|
||||
def system() -> dict:
|
||||
return _system_info()
|
||||
|
||||
|
||||
@app.get("/agent/stacks", dependencies=[Depends(verify_token)])
|
||||
def list_stacks() -> list[dict]:
|
||||
try:
|
||||
summaries = compose_service.stack_status_summaries()
|
||||
except DockerError:
|
||||
summaries = {}
|
||||
return [_summary(sid, summaries) for sid in compose_service.discover_stacks()]
|
||||
|
||||
|
||||
@app.get("/agent/stacks/stats", dependencies=[Depends(verify_token)])
|
||||
def stacks_stats() -> dict:
|
||||
return stats_service.stack_stats()
|
||||
|
||||
|
||||
@app.get("/agent/stacks/updates", dependencies=[Depends(verify_token)])
|
||||
def stacks_updates() -> dict:
|
||||
"""Per-stack image-update availability from the cached digests."""
|
||||
return update_service.stacks_update_summary()
|
||||
|
||||
|
||||
@app.get("/agent/stacks/{stack_id}", dependencies=[Depends(verify_token)])
|
||||
def get_stack(stack_id: str) -> dict:
|
||||
directory = compose_service.stack_dir(stack_id)
|
||||
if not os.path.isdir(directory):
|
||||
raise HTTPException(status_code=404, detail=f"Stack '{stack_id}' not found")
|
||||
try:
|
||||
raw = compose_service.containers_for_stack(stack_id)
|
||||
containers = [asdict(c) for c in raw]
|
||||
status = compose_service.compute_status(stack_id, raw)
|
||||
except DockerError:
|
||||
containers = []
|
||||
status = "unknown"
|
||||
return {
|
||||
"id": stack_id,
|
||||
"name": stack_id,
|
||||
"description": None,
|
||||
"status": status,
|
||||
"yaml": compose_service.read_compose(stack_id),
|
||||
"env": compose_service.read_env(stack_id),
|
||||
"containers": containers,
|
||||
"created_at": None,
|
||||
"updated_at": None,
|
||||
}
|
||||
|
||||
|
||||
@app.post("/agent/stacks", dependencies=[Depends(verify_token)], status_code=201)
|
||||
def create_stack(body: StackBody) -> dict:
|
||||
if not body.name:
|
||||
raise HTTPException(status_code=400, detail="name is required")
|
||||
stack_id = compose_service.slugify(body.name)
|
||||
if os.path.isdir(compose_service.stack_dir(stack_id)):
|
||||
raise HTTPException(status_code=409, detail=f"Stack '{stack_id}' already exists")
|
||||
compose_service.write_compose(stack_id, body.yaml or "services:\n")
|
||||
if body.env:
|
||||
compose_service.write_env(stack_id, body.env)
|
||||
return _summary(stack_id)
|
||||
|
||||
|
||||
@app.put("/agent/stacks/{stack_id}", dependencies=[Depends(verify_token)])
|
||||
def update_stack(stack_id: str, body: StackBody) -> dict:
|
||||
if not os.path.isdir(compose_service.stack_dir(stack_id)):
|
||||
raise HTTPException(status_code=404, detail=f"Stack '{stack_id}' not found")
|
||||
if body.yaml is not None:
|
||||
compose_service.write_compose(stack_id, body.yaml)
|
||||
if body.env is not None:
|
||||
compose_service.write_env(stack_id, body.env)
|
||||
return _summary(stack_id)
|
||||
|
||||
|
||||
@app.delete("/agent/stacks/{stack_id}", dependencies=[Depends(verify_token)])
|
||||
async def delete_stack(stack_id: str, delete_files: bool = Query(True)) -> dict:
|
||||
if not os.path.isdir(compose_service.stack_dir(stack_id)):
|
||||
raise HTTPException(status_code=404, detail=f"Stack '{stack_id}' not found")
|
||||
try:
|
||||
await compose_service.down(stack_id)
|
||||
except Exception: # noqa: BLE001 - best-effort teardown
|
||||
pass
|
||||
if delete_files:
|
||||
compose_service.delete_stack_files(stack_id)
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
_ACTIONS = {
|
||||
"start": compose_service.up,
|
||||
"stop": compose_service.stop,
|
||||
"restart": compose_service.restart,
|
||||
"pull": compose_service.pull,
|
||||
"update": compose_service.update,
|
||||
"down": compose_service.down,
|
||||
}
|
||||
|
||||
|
||||
@app.post("/agent/stacks/{stack_id}/{action}", dependencies=[Depends(verify_token)])
|
||||
async def lifecycle(stack_id: str, action: str) -> dict:
|
||||
fn = _ACTIONS.get(action)
|
||||
if not fn:
|
||||
raise HTTPException(status_code=400, detail=f"Unknown action '{action}'")
|
||||
if not os.path.isdir(compose_service.stack_dir(stack_id)):
|
||||
raise HTTPException(status_code=404, detail=f"Stack '{stack_id}' not found")
|
||||
result = await fn(stack_id)
|
||||
if result.get("returncode") not in (0, None):
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail={
|
||||
"error": f"compose {action} failed",
|
||||
"detail": result.get("stderr", "").strip()[-2000:],
|
||||
},
|
||||
)
|
||||
if action in ("pull", "update"):
|
||||
update_service.refresh_stack_local(stack_id)
|
||||
return result
|
||||
|
||||
|
||||
@app.get("/agent/stacks/{stack_id}/logs", dependencies=[Depends(verify_token)])
|
||||
async def stack_logs(stack_id: str, tail: int = Query(200, le=2000)) -> dict:
|
||||
if not os.path.isdir(compose_service.stack_dir(stack_id)):
|
||||
raise HTTPException(status_code=404, detail=f"Stack '{stack_id}' not found")
|
||||
result = await compose_service.logs(stack_id, tail=tail)
|
||||
return {"logs": result.get("stdout", "") + result.get("stderr", "")}
|
||||
|
||||
|
||||
@app.get("/agent/stacks/{stack_id}/updates", dependencies=[Depends(verify_token)])
|
||||
async def stack_updates(stack_id: str, refresh: bool = Query(True)) -> dict:
|
||||
"""Update status for this stack's images (used by central auto-update)."""
|
||||
return await update_service.stack_updates(stack_id, refresh=refresh)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Secrets & configs (per-stack, file-based)
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
class SecretWriteBody(BaseModel):
|
||||
kind: str = "secret"
|
||||
name: str
|
||||
content: str
|
||||
|
||||
|
||||
class SecretAttachBody(BaseModel):
|
||||
kind: str = "secret"
|
||||
name: str
|
||||
service: str
|
||||
target: str | None = None
|
||||
|
||||
|
||||
class SecretDetachBody(BaseModel):
|
||||
kind: str = "secret"
|
||||
name: str
|
||||
service: str
|
||||
|
||||
|
||||
def _ensure_stack(stack_id: str) -> None:
|
||||
if not os.path.isdir(compose_service.stack_dir(stack_id)):
|
||||
raise HTTPException(status_code=404, detail=f"Stack '{stack_id}' not found")
|
||||
|
||||
|
||||
def _secret_guard(fn, *args, **kwargs):
|
||||
try:
|
||||
return fn(*args, **kwargs)
|
||||
except (secret_service.SecretError, compose_edit_service.EditError) as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@app.get("/agent/stacks/{stack_id}/secrets", dependencies=[Depends(verify_token)])
|
||||
def agent_list_secrets(stack_id: str) -> list:
|
||||
_ensure_stack(stack_id)
|
||||
return secret_service.list_all(stack_id)
|
||||
|
||||
|
||||
@app.put("/agent/stacks/{stack_id}/secrets", dependencies=[Depends(verify_token)])
|
||||
def agent_write_secret(stack_id: str, body: SecretWriteBody) -> dict:
|
||||
_ensure_stack(stack_id)
|
||||
return _secret_guard(secret_service.write_secret, stack_id, body.kind, body.name, body.content)
|
||||
|
||||
|
||||
@app.delete("/agent/stacks/{stack_id}/secrets/{kind}/{name}", dependencies=[Depends(verify_token)])
|
||||
def agent_delete_secret(stack_id: str, kind: str, name: str) -> dict:
|
||||
_ensure_stack(stack_id)
|
||||
_secret_guard(secret_service.delete_secret, stack_id, kind, name)
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@app.post("/agent/stacks/{stack_id}/secrets/attach", dependencies=[Depends(verify_token)])
|
||||
def agent_attach_secret(stack_id: str, body: SecretAttachBody) -> dict:
|
||||
_ensure_stack(stack_id)
|
||||
if not secret_service.exists(stack_id, body.kind, body.name):
|
||||
raise HTTPException(status_code=404, detail="secret not found")
|
||||
new_yaml = _secret_guard(secret_service.attach, stack_id, body.kind, body.name, body.service, body.target)
|
||||
return {"ok": True, "yaml": new_yaml}
|
||||
|
||||
|
||||
@app.post("/agent/stacks/{stack_id}/secrets/detach", dependencies=[Depends(verify_token)])
|
||||
def agent_detach_secret(stack_id: str, body: SecretDetachBody) -> dict:
|
||||
_ensure_stack(stack_id)
|
||||
new_yaml = _secret_guard(secret_service.detach, stack_id, body.kind, body.name, body.service)
|
||||
return {"ok": True, "yaml": new_yaml}
|
||||
|
||||
|
||||
@app.get("/agent/stacks/{stack_id}/backup/inventory", dependencies=[Depends(verify_token)])
|
||||
async def backup_inventory(stack_id: str) -> dict:
|
||||
"""What a backup of this stack would capture (see routers/backups.py)."""
|
||||
_ensure_stack(stack_id)
|
||||
return await asyncio.to_thread(backup_service.plan, stack_id)
|
||||
|
||||
|
||||
@app.get("/agent/stacks/{stack_id}/backup", dependencies=[Depends(verify_token)])
|
||||
async def backup_stack(
|
||||
stack_id: str,
|
||||
include_volumes: bool = Query(True),
|
||||
include_binds: bool = Query(True),
|
||||
stop_first: bool = Query(True),
|
||||
binds: list[str] | None = Query(None),
|
||||
volumes: list[str] | None = Query(None),
|
||||
):
|
||||
if not os.path.isdir(compose_service.stack_dir(stack_id)):
|
||||
raise HTTPException(status_code=404, detail=f"Stack '{stack_id}' not found")
|
||||
try:
|
||||
path, report = await backup_service.create_backup_ex(
|
||||
stack_id, stack_id, include_volumes=include_volumes, stop_first=stop_first,
|
||||
include_binds=include_binds, binds=binds, volumes=volumes,
|
||||
)
|
||||
except backup_service.BackupError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
return FileResponse(
|
||||
path,
|
||||
media_type="application/gzip",
|
||||
filename=backup_service.backup_filename(stack_id, include_volumes),
|
||||
headers={"X-Stackpilot-Backup": json.dumps({
|
||||
"size": report.get("size"),
|
||||
"binds": report.get("binds", []),
|
||||
"volumes": report.get("volumes", []),
|
||||
"skipped": report.get("skipped", []),
|
||||
"path_mismatch": report.get("path_mismatch"),
|
||||
})},
|
||||
)
|
||||
|
||||
|
||||
@app.post("/agent/stacks/restore", dependencies=[Depends(verify_token)])
|
||||
async def restore_stack(
|
||||
file: UploadFile = File(...),
|
||||
target_id: str | None = Form(None),
|
||||
overwrite: bool = Form(False),
|
||||
restore_volumes: bool = Form(True),
|
||||
restore_binds: bool = Form(True),
|
||||
) -> dict:
|
||||
tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".tar.gz")
|
||||
try:
|
||||
while chunk := await file.read(1024 * 1024):
|
||||
tmp.write(chunk)
|
||||
tmp.close()
|
||||
target = compose_service.slugify(target_id) if target_id else None
|
||||
try:
|
||||
return backup_service.restore_backup(
|
||||
tmp.name, target_id=target, overwrite=overwrite,
|
||||
restore_volumes=restore_volumes, restore_binds=restore_binds,
|
||||
)
|
||||
except backup_service.BackupError as exc:
|
||||
code = 409 if "already exists" in str(exc) else 400
|
||||
raise HTTPException(status_code=code, detail=str(exc)) from exc
|
||||
finally:
|
||||
if os.path.exists(tmp.name):
|
||||
os.unlink(tmp.name)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Networks
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
@app.get("/agent/networks", dependencies=[Depends(verify_token)])
|
||||
def list_networks() -> list[dict]:
|
||||
return network_service.list_networks()
|
||||
|
||||
|
||||
@app.get("/agent/networks/{network_id}", dependencies=[Depends(verify_token)])
|
||||
def inspect_network(network_id: str) -> dict:
|
||||
try:
|
||||
return network_service.inspect_network(network_id)
|
||||
except DockerError as exc:
|
||||
_map_docker(exc)
|
||||
|
||||
|
||||
@app.get("/agent/networks/{network_id}/containers", dependencies=[Depends(verify_token)])
|
||||
def network_containers(network_id: str) -> list[dict]:
|
||||
try:
|
||||
return network_service.connectable_containers(network_id)
|
||||
except DockerError as exc:
|
||||
_map_docker(exc)
|
||||
|
||||
|
||||
@app.post("/agent/networks/{network_id}/connect", dependencies=[Depends(verify_token)])
|
||||
def connect_container(network_id: str, body: ContainerRefBody) -> dict:
|
||||
try:
|
||||
network_service.connect_container(network_id, body.container, body.aliases)
|
||||
except DockerError as exc:
|
||||
_map_docker(exc)
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@app.post("/agent/networks/{network_id}/disconnect", dependencies=[Depends(verify_token)])
|
||||
def disconnect_container(network_id: str, body: ContainerRefBody) -> dict:
|
||||
try:
|
||||
network_service.disconnect_container(network_id, body.container, body.force)
|
||||
except DockerError as exc:
|
||||
_map_docker(exc)
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@app.post("/agent/networks", dependencies=[Depends(verify_token)], status_code=201)
|
||||
def create_network(body: NetworkCreateBody) -> dict:
|
||||
try:
|
||||
return network_service.create_network(body.model_dump())
|
||||
except DockerError as exc:
|
||||
_map_docker(exc)
|
||||
|
||||
|
||||
@app.delete("/agent/networks/{network_id}", dependencies=[Depends(verify_token)])
|
||||
def delete_network(network_id: str) -> dict:
|
||||
try:
|
||||
network_service.delete_network(network_id)
|
||||
except DockerError as exc:
|
||||
_map_docker(exc)
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@app.post("/agent/networks/prune", dependencies=[Depends(verify_token)])
|
||||
def prune_networks() -> dict:
|
||||
return network_service.prune_networks()
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Images
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
@app.get("/agent/images", dependencies=[Depends(verify_token)])
|
||||
def list_images() -> list[dict]:
|
||||
return image_service.list_images()
|
||||
|
||||
|
||||
@app.get("/agent/images/updates", dependencies=[Depends(verify_token)])
|
||||
def image_updates() -> dict:
|
||||
return update_service.get_cache()
|
||||
|
||||
|
||||
@app.post("/agent/images/check", dependencies=[Depends(verify_token)])
|
||||
async def image_check() -> dict:
|
||||
return await update_service.check_all()
|
||||
|
||||
|
||||
@app.post("/agent/images/prune", dependencies=[Depends(verify_token)])
|
||||
def image_prune(all_unused: bool = Query(False, alias="all")) -> dict:
|
||||
return image_service.prune_images(all_unused)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Containers (single-container inspect + lifecycle)
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
@app.get("/agent/containers/{container_id}", dependencies=[Depends(verify_token)])
|
||||
def inspect_container(container_id: str) -> dict:
|
||||
return container_service.inspect_container(container_id)
|
||||
|
||||
|
||||
@app.post("/agent/containers/{container_id}/{action}", dependencies=[Depends(verify_token)])
|
||||
def container_action(container_id: str, action: str) -> dict:
|
||||
return container_service.container_action(container_id, action)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Volumes
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
@app.get("/agent/volumes", dependencies=[Depends(verify_token)])
|
||||
def list_volumes() -> list[dict]:
|
||||
return volume_service.list_volumes()
|
||||
|
||||
|
||||
@app.get("/agent/volumes/sizes", dependencies=[Depends(verify_token)])
|
||||
def volume_sizes(force: bool = Query(False)) -> dict:
|
||||
return volume_service.volume_sizes(force=force)
|
||||
|
||||
|
||||
@app.delete("/agent/volumes/{name}", dependencies=[Depends(verify_token)])
|
||||
def delete_volume(name: str, force: bool = Query(False)) -> dict:
|
||||
vols = {v["name"]: v for v in volume_service.list_volumes()}
|
||||
if name in vols and vols[name]["in_use"] and not force:
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail={
|
||||
"error": "volume_in_use",
|
||||
"detail": f"Volume '{name}' is used by: {', '.join(vols[name]['used_by'])}",
|
||||
},
|
||||
)
|
||||
volume_service.remove_volume(name, force=force)
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@app.post("/agent/volumes/prune", dependencies=[Depends(verify_token)])
|
||||
def prune_volumes() -> dict:
|
||||
return volume_service.prune_volumes()
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# File browser (sandboxed by this agent's ALLOWED_BROWSE_ROOTS/HOST_ROOT_PREFIX)
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
@app.get("/agent/files/list", dependencies=[Depends(verify_token)])
|
||||
def files_list(path: str = Query("/"), show_hidden: bool = Query(False)) -> dict:
|
||||
return _file_guard(device_service.browse, path, show_hidden)
|
||||
|
||||
|
||||
@app.get("/agent/files/read", dependencies=[Depends(verify_token)])
|
||||
def files_read(path: str = Query(...)) -> dict:
|
||||
return _file_guard(file_service.read_file, path)
|
||||
|
||||
|
||||
@app.get("/agent/files/download", dependencies=[Depends(verify_token)])
|
||||
def files_download(path: str = Query(...)):
|
||||
if _file_guard(file_service.is_dir, path):
|
||||
filename, chunks = _file_guard(file_service.open_archive, path)
|
||||
# Stream the zip as it's built (no temp file, starts immediately).
|
||||
return StreamingResponse(
|
||||
chunks, media_type="application/zip",
|
||||
headers={"Content-Disposition": f'attachment; filename="{filename}"'},
|
||||
)
|
||||
real, filename = _file_guard(file_service.resolve_download, path)
|
||||
return FileResponse(real, filename=filename, media_type="application/octet-stream")
|
||||
|
||||
|
||||
@app.put("/agent/files/write", dependencies=[Depends(verify_token)])
|
||||
def files_write(body: FileWriteBody) -> dict:
|
||||
return _file_guard(file_service.write_file, body.path, body.content)
|
||||
|
||||
|
||||
@app.post("/agent/files/mkdir", dependencies=[Depends(verify_token)])
|
||||
def files_mkdir(body: FileNameBody) -> dict:
|
||||
return _file_guard(file_service.create_dir, body.path, body.name)
|
||||
|
||||
|
||||
@app.post("/agent/files/touch", dependencies=[Depends(verify_token)])
|
||||
def files_touch(body: FileNameBody) -> dict:
|
||||
return _file_guard(file_service.create_file, body.path, body.name)
|
||||
|
||||
|
||||
@app.post("/agent/files/rename", dependencies=[Depends(verify_token)])
|
||||
def files_rename(body: FileRenameBody) -> dict:
|
||||
return _file_guard(file_service.rename, body.path, body.new_name)
|
||||
|
||||
|
||||
@app.post("/agent/files/copy", dependencies=[Depends(verify_token)])
|
||||
def files_copy(body: FileTransferBody) -> dict:
|
||||
return _file_guard(file_service.copy, body.src, body.dest_dir, body.overwrite)
|
||||
|
||||
|
||||
@app.post("/agent/files/move", dependencies=[Depends(verify_token)])
|
||||
def files_move(body: FileTransferBody) -> dict:
|
||||
return _file_guard(file_service.move, body.src, body.dest_dir, body.overwrite)
|
||||
|
||||
|
||||
@app.delete("/agent/files", dependencies=[Depends(verify_token)])
|
||||
def files_delete(path: str = Query(...), recursive: bool = Query(False)) -> dict:
|
||||
return _file_guard(file_service.delete, path, recursive)
|
||||
|
||||
|
||||
@app.post("/agent/files/upload", dependencies=[Depends(verify_token)])
|
||||
async def files_upload(
|
||||
path: str = Form(...),
|
||||
overwrite: bool = Form(False),
|
||||
rel_path: str = Form(""),
|
||||
file: UploadFile = File(...),
|
||||
) -> dict:
|
||||
real = _file_guard(
|
||||
file_service.upload_target, path, file.filename or "", overwrite, rel_path or None
|
||||
)
|
||||
tmp = tempfile.NamedTemporaryFile(delete=False, dir=os.path.dirname(real))
|
||||
try:
|
||||
while chunk := await file.read(1024 * 1024):
|
||||
tmp.write(chunk)
|
||||
tmp.close()
|
||||
os.replace(tmp.name, real)
|
||||
except OSError as exc:
|
||||
if os.path.exists(tmp.name):
|
||||
os.unlink(tmp.name)
|
||||
raise HTTPException(status_code=400, detail=f"Upload failed: {exc}") from exc
|
||||
return {"ok": True, "name": rel_path or file.filename}
|
||||
|
||||
|
||||
@app.websocket("/agent/ws/logs/{stack_id}")
|
||||
async def ws_logs(websocket: WebSocket, stack_id: str, token: str | None = Query(default=None)):
|
||||
"""Stream `docker compose logs -f` to the central app (token via query param)."""
|
||||
await websocket.accept()
|
||||
expected = settings.AGENT_TOKEN
|
||||
if not expected or token != expected:
|
||||
await websocket.close(code=4401)
|
||||
return
|
||||
if not os.path.isdir(compose_service.stack_dir(stack_id)):
|
||||
await websocket.send_text(json.dumps({"type": "error", "detail": "stack not found"}))
|
||||
await websocket.close()
|
||||
return
|
||||
args = ["logs", "--no-color", "--tail", "200", "--timestamps", "-f"]
|
||||
try:
|
||||
async for line in compose_service.stream_compose(stack_id, args):
|
||||
await websocket.send_text(
|
||||
json.dumps({"type": "log", "stack_id": stack_id, "service": None, "line": line})
|
||||
)
|
||||
except WebSocketDisconnect:
|
||||
pass
|
||||
except Exception as exc: # noqa: BLE001
|
||||
try:
|
||||
await websocket.send_text(json.dumps({"type": "error", "detail": str(exc)}))
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
|
||||
@app.websocket("/agent/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 to the central app so the
|
||||
browser sees deploy progress live (token via query param)."""
|
||||
await websocket.accept()
|
||||
expected = settings.AGENT_TOKEN
|
||||
if not expected or token != expected:
|
||||
await websocket.close(code=4401)
|
||||
return
|
||||
if not os.path.isdir(compose_service.stack_dir(stack_id)):
|
||||
await websocket.send_text(json.dumps({"type": "error", "detail": "stack not found"}))
|
||||
await websocket.close()
|
||||
return
|
||||
compose_service.mark_busy(stack_id)
|
||||
try:
|
||||
async for kind, payload in compose_service.stream_up(stack_id):
|
||||
if kind == "log":
|
||||
await websocket.send_text(json.dumps({"type": "log", "line": payload}))
|
||||
else:
|
||||
await websocket.send_text(json.dumps({"type": "done", "returncode": payload}))
|
||||
except WebSocketDisconnect:
|
||||
# Browser navigated away; the compose subprocess keeps running.
|
||||
pass
|
||||
except Exception as exc: # noqa: BLE001
|
||||
try:
|
||||
await websocket.send_text(json.dumps({"type": "error", "detail": str(exc)}))
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
finally:
|
||||
compose_service.clear_busy(stack_id)
|
||||
|
||||
|
||||
@app.websocket("/agent/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 (token via query)."""
|
||||
await websocket.accept()
|
||||
expected = settings.AGENT_TOKEN
|
||||
if not expected or token != expected:
|
||||
await websocket.close(code=4401)
|
||||
return
|
||||
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
|
||||
try:
|
||||
await websocket.send_text(json.dumps({"type": "error", "detail": str(exc)}))
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
await websocket.close()
|
||||
return
|
||||
try:
|
||||
await exec_service.pump_exec(websocket, exec_id, holder, raw)
|
||||
except WebSocketDisconnect:
|
||||
pass
|
||||
finally:
|
||||
try:
|
||||
await websocket.close()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
|
||||
@app.get("/agent/health")
|
||||
def health() -> dict:
|
||||
return {"status": "ok"}
|
||||
@@ -38,10 +38,6 @@ class Settings(BaseSettings):
|
||||
# Throwaway image used to read/write named-volume contents during backup.
|
||||
BACKUP_HELPER_IMAGE: str = "alpine:latest"
|
||||
|
||||
# Multi-host agent: shared bearer token the agent requires on every request.
|
||||
# Only used when running the agent app (agent_app:app).
|
||||
AGENT_TOKEN: str = ""
|
||||
|
||||
# Host browser sandbox roots. Deliberately does NOT contain "/": that entry
|
||||
# makes _is_allowed() wave through every path, i.e. it switches the sandbox
|
||||
# off. Add it back explicitly if you really want the whole filesystem.
|
||||
|
||||
@@ -7,6 +7,7 @@ from collections.abc import Generator
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import inspect, text
|
||||
from sqlalchemy.exc import OperationalError
|
||||
from sqlmodel import Session, SQLModel, create_engine
|
||||
|
||||
from config import settings
|
||||
@@ -93,12 +94,60 @@ def _ensure_model_columns() -> None:
|
||||
logger.info("Schema migration: added column %s.%s", table_name, col.name)
|
||||
|
||||
|
||||
#: Tables and columns left behind when the remote-host (agent) integration was
|
||||
#: removed in 0.48.0. SQLite before 3.35 cannot DROP COLUMN, and the rows are
|
||||
#: harmless dead weight either way — so the table goes and the columns are only
|
||||
#: dropped where the SQLite build supports it.
|
||||
_REMOVED_TABLES = ("agent",)
|
||||
_REMOVED_COLUMNS = (("autoupdate", "agent_id"), ("backupschedule", "agent_id"))
|
||||
|
||||
|
||||
def _drop_removed_schema() -> None:
|
||||
"""Clean up schema left over from features that no longer exist.
|
||||
|
||||
Without this an upgraded install keeps an ``agent`` table full of host URLs
|
||||
and bearer tokens for a feature that is gone — credentials sitting in the
|
||||
database with nothing to use them.
|
||||
|
||||
Each statement runs in its own transaction on purpose: a failed DDL poisons
|
||||
the transaction it is in, so sharing one would mean a single unsupported
|
||||
DROP COLUMN takes the table drop down with it.
|
||||
"""
|
||||
insp = inspect(engine)
|
||||
live = set(insp.get_table_names())
|
||||
|
||||
for table in _REMOVED_TABLES:
|
||||
if table not in live:
|
||||
continue
|
||||
with engine.begin() as conn:
|
||||
conn.execute(text(f'DROP TABLE "{table}"'))
|
||||
logger.info("Schema migration: dropped obsolete table %s", table)
|
||||
|
||||
for table, column in _REMOVED_COLUMNS:
|
||||
if table not in live:
|
||||
continue
|
||||
if column not in {c["name"] for c in insp.get_columns(table)}:
|
||||
continue
|
||||
try:
|
||||
with engine.begin() as conn:
|
||||
conn.execute(text(f'ALTER TABLE "{table}" DROP COLUMN "{column}"'))
|
||||
logger.info("Schema migration: dropped obsolete column %s.%s", table, column)
|
||||
except OperationalError:
|
||||
# SQLite < 3.35 has no DROP COLUMN. The column is nullable and
|
||||
# nothing reads it any more, so leaving it is harmless.
|
||||
logger.info(
|
||||
"Leaving obsolete column %s.%s in place (this SQLite cannot "
|
||||
"drop columns); it is unused", table, column
|
||||
)
|
||||
|
||||
|
||||
def init_db() -> None:
|
||||
# Import models so they are registered on SQLModel.metadata.
|
||||
import models # noqa: F401
|
||||
|
||||
SQLModel.metadata.create_all(engine)
|
||||
_ensure_model_columns()
|
||||
_drop_removed_schema()
|
||||
|
||||
|
||||
def get_session() -> Generator[Session, None, None]:
|
||||
|
||||
@@ -15,7 +15,6 @@ from version import APP_VERSION
|
||||
from database import engine, init_db
|
||||
from docker_client import DockerError
|
||||
from routers import (
|
||||
agents,
|
||||
audit,
|
||||
auth,
|
||||
backups,
|
||||
@@ -132,7 +131,6 @@ app.include_router(backups.router)
|
||||
app.include_router(destinations.router)
|
||||
app.include_router(schedules.router)
|
||||
app.include_router(networks.router)
|
||||
app.include_router(agents.router)
|
||||
app.include_router(ws.router)
|
||||
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
"""SQLModel table models. Importing this package registers all tables."""
|
||||
from models.agent import Agent
|
||||
from models.audit import AuditLog
|
||||
from models.auto_update import AutoUpdate
|
||||
from models.backup_destination import BackupDestination
|
||||
@@ -10,7 +9,7 @@ from models.stack import Stack
|
||||
from models.user import User
|
||||
|
||||
__all__ = [
|
||||
"User", "Stack", "AuditLog", "Setting", "Webhook", "Agent",
|
||||
"User", "Stack", "AuditLog", "Setting", "Webhook",
|
||||
"BackupDestination", "BackupSchedule", "AutoUpdate",
|
||||
"StackLock", "ImageStatus", "LoginAttempt",
|
||||
]
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
|
||||
from sqlmodel import Field, SQLModel
|
||||
|
||||
|
||||
def _now() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
class Agent(SQLModel, table=True):
|
||||
"""A remote host running stackpilot-agent."""
|
||||
|
||||
id: Optional[int] = Field(default=None, primary_key=True)
|
||||
name: str
|
||||
url: str # e.g. http://10.0.0.5:5010
|
||||
token: str # shared AGENT_TOKEN of that host
|
||||
status: str = "unknown" # online | offline | unauthorized | unknown
|
||||
hostname: Optional[str] = None # reported by the agent on ping
|
||||
last_seen: Optional[datetime] = None
|
||||
created_at: datetime = Field(default_factory=_now)
|
||||
|
||||
|
||||
# --- API schemas ---
|
||||
|
||||
|
||||
class AgentCreate(SQLModel):
|
||||
name: str
|
||||
url: str
|
||||
token: str
|
||||
|
||||
|
||||
class AgentUpdate(SQLModel):
|
||||
name: Optional[str] = None
|
||||
url: Optional[str] = None
|
||||
token: Optional[str] = None
|
||||
|
||||
|
||||
class AgentRead(SQLModel):
|
||||
id: int
|
||||
name: str
|
||||
url: str
|
||||
status: str
|
||||
hostname: Optional[str]
|
||||
last_seen: Optional[datetime]
|
||||
created_at: datetime
|
||||
token_set: bool
|
||||
@@ -16,12 +16,10 @@ class AutoUpdate(SQLModel, table=True):
|
||||
When the background image-update check finds a newer registry digest for one
|
||||
of the stack's images, the stack is either pulled + redeployed
|
||||
(``redeploy=True``) or merely notified about (``redeploy=False``).
|
||||
``agent_id`` None = local host, otherwise a remote agent's stack.
|
||||
"""
|
||||
|
||||
id: Optional[int] = Field(default=None, primary_key=True)
|
||||
stack_id: str
|
||||
agent_id: Optional[int] = None
|
||||
enabled: bool = True
|
||||
redeploy: bool = True # True = pull + up -d; False = notify only
|
||||
last_run: Optional[datetime] = None
|
||||
@@ -41,8 +39,6 @@ class AutoUpdateWrite(SQLModel):
|
||||
class AutoUpdateRead(SQLModel):
|
||||
id: Optional[int]
|
||||
stack_id: str
|
||||
agent_id: Optional[int]
|
||||
agent_name: Optional[str] = None
|
||||
enabled: bool
|
||||
redeploy: bool
|
||||
last_run: Optional[datetime]
|
||||
|
||||
@@ -19,7 +19,6 @@ class BackupSchedule(SQLModel, table=True):
|
||||
id: Optional[int] = Field(default=None, primary_key=True)
|
||||
stack_id: str
|
||||
destination_id: int
|
||||
agent_id: Optional[int] = None # None = local host; otherwise a remote agent
|
||||
frequency: str = "daily" # one of FREQUENCIES
|
||||
hour: int = 3 # UTC, used for daily/weekly
|
||||
minute: int = 0
|
||||
@@ -40,7 +39,6 @@ class BackupSchedule(SQLModel, table=True):
|
||||
class ScheduleCreate(SQLModel):
|
||||
stack_id: str
|
||||
destination_id: int
|
||||
agent_id: Optional[int] = None
|
||||
frequency: str = "daily"
|
||||
hour: int = 3
|
||||
minute: int = 0
|
||||
@@ -68,8 +66,6 @@ class ScheduleRead(SQLModel):
|
||||
stack_id: str
|
||||
destination_id: int
|
||||
destination_name: Optional[str]
|
||||
agent_id: Optional[int]
|
||||
agent_name: Optional[str]
|
||||
frequency: str
|
||||
hour: int
|
||||
minute: int
|
||||
|
||||
@@ -8,9 +8,6 @@ and all three were lost on restart.
|
||||
|
||||
They are tables now. SQLite is already here; this needs no new dependency.
|
||||
|
||||
Note that ``services/compose_service.py`` and ``services/update_service.py``
|
||||
are shared with the agent, which has no database at all — so these tables are
|
||||
only ever touched from the central app's own routers and background loops.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
@@ -40,4 +40,3 @@ class TemplateFromStackRequest(SQLModel):
|
||||
|
||||
class TemplateInstantiateRequest(SQLModel):
|
||||
name: str # new stack name
|
||||
agent_id: int | None = None # None = local host; otherwise deploy to a remote agent
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -24,7 +24,7 @@ async def fleet(
|
||||
_user: User = Depends(get_current_user),
|
||||
) -> dict:
|
||||
"""Fleet-wide 'needs attention' list, KPIs and per-host rollup across the
|
||||
local host and every agent — the data behind the operator cockpit."""
|
||||
the host — the data behind the operator cockpit."""
|
||||
try:
|
||||
return await dashboard_service.compute_fleet(session, refresh=refresh)
|
||||
except Exception as exc: # noqa: BLE001 — surface the real cause for diagnosis
|
||||
|
||||
@@ -6,7 +6,6 @@ from sqlmodel import Session, select
|
||||
|
||||
from auth import require_admin
|
||||
from database import get_session
|
||||
from models.agent import Agent
|
||||
from models.backup_destination import BackupDestination
|
||||
from models.backup_schedule import (
|
||||
FREQUENCIES,
|
||||
@@ -28,14 +27,11 @@ def _ip(request: Request) -> str:
|
||||
|
||||
def _to_read(session: Session, s: BackupSchedule) -> ScheduleRead:
|
||||
dest = session.get(BackupDestination, s.destination_id)
|
||||
agent = session.get(Agent, s.agent_id) if s.agent_id is not None else None
|
||||
return ScheduleRead(
|
||||
id=s.id,
|
||||
stack_id=s.stack_id,
|
||||
destination_id=s.destination_id,
|
||||
destination_name=dest.name if dest else None,
|
||||
agent_id=s.agent_id,
|
||||
agent_name=agent.name if agent else None,
|
||||
frequency=s.frequency,
|
||||
hour=s.hour,
|
||||
minute=s.minute,
|
||||
@@ -63,11 +59,7 @@ def _validate(session: Session, schedule: BackupSchedule) -> None:
|
||||
raise HTTPException(status_code=400, detail=f"Unknown frequency '{schedule.frequency}'")
|
||||
if not session.get(BackupDestination, schedule.destination_id):
|
||||
raise HTTPException(status_code=404, detail=f"Destination {schedule.destination_id} not found")
|
||||
if schedule.agent_id is not None:
|
||||
# Remote stack: validate the agent exists; the stack is checked at run time.
|
||||
if not session.get(Agent, schedule.agent_id):
|
||||
raise HTTPException(status_code=404, detail=f"Agent {schedule.agent_id} not found")
|
||||
elif not session.get(Stack, schedule.stack_id):
|
||||
if not session.get(Stack, schedule.stack_id):
|
||||
raise HTTPException(status_code=404, detail=f"Stack '{schedule.stack_id}' not found")
|
||||
|
||||
|
||||
|
||||
@@ -51,7 +51,6 @@ def _guard(fn, *args, **kwargs):
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
|
||||
|
||||
# --- These functions are shared verbatim by the agent (see agent_app.py). ---
|
||||
|
||||
|
||||
def list_secrets(stack_id: str) -> list[dict]:
|
||||
|
||||
@@ -178,6 +178,9 @@ def get_stack(
|
||||
except DockerError:
|
||||
containers = []
|
||||
status = "unknown"
|
||||
# An operation in flight outranks whatever the containers currently say.
|
||||
if stack_lock_service.is_busy(session, stack_id):
|
||||
status = "updating"
|
||||
return {
|
||||
"id": stack.id,
|
||||
"name": stack.name,
|
||||
@@ -451,7 +454,7 @@ def get_auto_update(
|
||||
_user: User = Depends(get_current_user),
|
||||
) -> dict:
|
||||
policy = auto_update_service.get_policy(session, stack_id)
|
||||
return auto_update_service.to_read(session, policy, stack_id)
|
||||
return auto_update_service.to_read(policy, stack_id)
|
||||
|
||||
|
||||
@router.put("/{stack_id}/auto-update", response_model=AutoUpdateRead)
|
||||
@@ -468,7 +471,7 @@ def set_auto_update(
|
||||
target=stack_id, detail=f"enabled={body.enabled} redeploy={body.redeploy}",
|
||||
ip=_client_ip(request),
|
||||
)
|
||||
return auto_update_service.to_read(session, policy, stack_id)
|
||||
return auto_update_service.to_read(policy, stack_id)
|
||||
|
||||
|
||||
@router.post("/{stack_id}/auto-update/run", response_model=AutoUpdateRead)
|
||||
@@ -482,4 +485,4 @@ async def run_auto_update(
|
||||
raise HTTPException(status_code=404, detail="No auto-update policy for this stack")
|
||||
await auto_update_service.run_policy(session, policy)
|
||||
session.refresh(policy)
|
||||
return auto_update_service.to_read(session, policy, stack_id)
|
||||
return auto_update_service.to_read(policy, stack_id)
|
||||
|
||||
@@ -12,7 +12,6 @@ from sqlmodel import Session
|
||||
|
||||
from auth import get_current_user, require_admin
|
||||
from database import get_session
|
||||
from models.agent import Agent
|
||||
from models.stack import Stack
|
||||
from models.template import (
|
||||
TemplateFromStackRequest,
|
||||
@@ -20,8 +19,7 @@ from models.template import (
|
||||
TemplateSaveRequest,
|
||||
)
|
||||
from models.user import User
|
||||
from services import agent_service, audit_service, compose_service, template_service
|
||||
from services.agent_service import AgentError
|
||||
from services import audit_service, compose_service, template_service
|
||||
|
||||
router = APIRouter(prefix="/api/templates", tags=["templates"])
|
||||
|
||||
@@ -103,7 +101,7 @@ def delete_template(
|
||||
|
||||
|
||||
@router.post("/{template_id}/instantiate", status_code=201)
|
||||
async def instantiate(
|
||||
def instantiate(
|
||||
template_id: str,
|
||||
body: TemplateInstantiateRequest,
|
||||
request: Request,
|
||||
@@ -114,28 +112,7 @@ async def instantiate(
|
||||
if not tpl:
|
||||
raise HTTPException(status_code=404, detail="Template not found")
|
||||
|
||||
# Remote host: agents don't share our filesystem, so ship compose + env.
|
||||
if body.agent_id is not None:
|
||||
agent = session.get(Agent, body.agent_id)
|
||||
if not agent:
|
||||
raise HTTPException(status_code=404, detail=f"Agent {body.agent_id} not found")
|
||||
try:
|
||||
result = await agent_service.call(
|
||||
session, agent, "POST", "/agent/stacks",
|
||||
json={"name": body.name, "yaml": tpl["compose"], "env": tpl["env"] or None},
|
||||
)
|
||||
except AgentError as exc:
|
||||
raise HTTPException(
|
||||
status_code=exc.status if exc.status >= 400 else 502,
|
||||
detail={"error": exc.error, "detail": exc.detail},
|
||||
) from exc
|
||||
audit_service.record(
|
||||
session, user=user.username, action="template.instantiate",
|
||||
target=f"{agent.name}/{result.get('id')}", detail=template_id, ip=_ip(request),
|
||||
)
|
||||
return {"id": result.get("id"), "name": body.name, "agent_id": agent.id}
|
||||
|
||||
# Local host: copy the whole template folder into a new stack.
|
||||
# Copy the whole template folder into a new stack.
|
||||
stack_id = compose_service.slugify(body.name)
|
||||
if session.get(Stack, stack_id) or os.path.isdir(compose_service.stack_dir(stack_id)):
|
||||
raise HTTPException(status_code=409, detail=f"Stack '{stack_id}' already exists")
|
||||
@@ -156,4 +133,4 @@ async def instantiate(
|
||||
session, user=user.username, action="template.instantiate",
|
||||
target=stack_id, detail=template_id, ip=_ip(request),
|
||||
)
|
||||
return {"id": stack_id, "name": body.name, "agent_id": None}
|
||||
return {"id": stack_id, "name": body.name}
|
||||
|
||||
@@ -4,18 +4,15 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import urllib.parse
|
||||
|
||||
import contextlib
|
||||
|
||||
import websockets
|
||||
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.agent import Agent
|
||||
from models.setting import EVENT_PULL_FAILED, EVENT_STACK_ERROR, EVENT_STACK_START
|
||||
from services import (
|
||||
audit_service,
|
||||
@@ -158,7 +155,6 @@ async def ws_deploy(
|
||||
await websocket.send_text(json.dumps({"type": "error", "detail": str(exc)}))
|
||||
await websocket.close(code=4409)
|
||||
return
|
||||
compose_service.mark_busy(stack_id)
|
||||
try:
|
||||
async for kind, payload in compose_service.stream_up(stack_id):
|
||||
if kind == "log":
|
||||
@@ -174,7 +170,6 @@ async def ws_deploy(
|
||||
with contextlib.suppress(Exception):
|
||||
await websocket.send_text(json.dumps({"type": "error", "detail": str(exc)}))
|
||||
finally:
|
||||
compose_service.clear_busy(stack_id)
|
||||
with contextlib.suppress(Exception):
|
||||
stack_lock_service.release(lock_session, stack_id)
|
||||
lock_session.close()
|
||||
@@ -203,78 +198,6 @@ async def ws_deploy(
|
||||
await websocket.close()
|
||||
|
||||
|
||||
@router.websocket("/ws/agent-logs/{agent_id}/{stack_id}")
|
||||
async def ws_agent_logs(
|
||||
websocket: WebSocket,
|
||||
agent_id: int,
|
||||
stack_id: str,
|
||||
token: str | None = Query(default=None),
|
||||
):
|
||||
"""Proxy live compose logs from a remote agent through to the browser."""
|
||||
await websocket.accept()
|
||||
if not await _authorize(websocket, token):
|
||||
return
|
||||
|
||||
with Session(engine) as session:
|
||||
agent = session.get(Agent, agent_id)
|
||||
if not agent:
|
||||
await websocket.send_text(json.dumps({"type": "error", "detail": "agent not found"}))
|
||||
await websocket.close()
|
||||
return
|
||||
|
||||
base = agent.url.rstrip("/")
|
||||
ws_url = ("wss://" + base[8:] if base.startswith("https://")
|
||||
else "ws://" + base[7:] if base.startswith("http://")
|
||||
else "ws://" + base)
|
||||
# URL-encode the token: agent tokens may contain base64 chars (+ / =) that
|
||||
# would otherwise be mangled in the query string and rejected as 4401.
|
||||
ws_url += f"/agent/ws/logs/{stack_id}?token={urllib.parse.quote(agent.token, safe='')}"
|
||||
|
||||
async def _err(detail: str) -> None:
|
||||
with contextlib.suppress(Exception):
|
||||
await websocket.send_text(json.dumps({"type": "error", "detail": detail}))
|
||||
|
||||
# Connect to the agent. Surface connection problems (agent down, wrong URL,
|
||||
# an outdated agent that lacks /agent/ws/logs, TLS issues) instead of
|
||||
# silently dropping the socket.
|
||||
try:
|
||||
upstream = await websockets.connect(ws_url, open_timeout=10, ping_interval=20)
|
||||
except websockets.InvalidStatus as exc:
|
||||
code = getattr(getattr(exc, "response", None), "status_code", None)
|
||||
hint = " — the agent may be running an old version without live-log support; update it." if code == 404 else ""
|
||||
logger.warning("Agent log proxy: handshake to %s failed (%s)", agent.name, code)
|
||||
await _err(f"Agent '{agent.name}' rejected the log stream (HTTP {code}){hint}")
|
||||
with contextlib.suppress(Exception):
|
||||
await websocket.close()
|
||||
return
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("Agent log proxy: cannot reach %s at %s: %s", agent.name, agent.url, exc)
|
||||
await _err(f"Could not connect to agent '{agent.name}' at {agent.url}: {exc}")
|
||||
with contextlib.suppress(Exception):
|
||||
await websocket.close()
|
||||
return
|
||||
|
||||
try:
|
||||
async for message in upstream:
|
||||
await websocket.send_text(
|
||||
message if isinstance(message, str) else message.decode("utf-8", "replace")
|
||||
)
|
||||
except WebSocketDisconnect:
|
||||
pass
|
||||
except websockets.ConnectionClosed as exc:
|
||||
# Abnormal upstream close (e.g. 4401 bad token, or agent-side error).
|
||||
if exc.code not in (1000, 1001):
|
||||
await _err(f"Agent log stream closed unexpectedly (code {exc.code}).")
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("Agent log proxy: stream error from %s: %s", agent.name, exc)
|
||||
await _err(str(exc))
|
||||
finally:
|
||||
with contextlib.suppress(Exception):
|
||||
await upstream.close()
|
||||
with contextlib.suppress(Exception):
|
||||
await websocket.close()
|
||||
|
||||
|
||||
@router.websocket("/ws/update/{stack_id}")
|
||||
async def ws_update(
|
||||
websocket: WebSocket,
|
||||
@@ -300,7 +223,6 @@ async def ws_update(
|
||||
await websocket.send_text(json.dumps({"type": "error", "detail": str(exc)}))
|
||||
await websocket.close(code=4409)
|
||||
return
|
||||
compose_service.mark_busy(stack_id)
|
||||
try:
|
||||
async for kind, payload in compose_service.stream_update(stack_id):
|
||||
if kind == "log":
|
||||
@@ -315,7 +237,6 @@ async def ws_update(
|
||||
with contextlib.suppress(Exception):
|
||||
await websocket.send_text(json.dumps({"type": "error", "detail": str(exc)}))
|
||||
finally:
|
||||
compose_service.clear_busy(stack_id)
|
||||
with contextlib.suppress(Exception):
|
||||
stack_lock_service.release(lock_session, stack_id)
|
||||
lock_session.close()
|
||||
@@ -347,85 +268,6 @@ async def ws_update(
|
||||
update_service.refresh_stack_local(stack_id)
|
||||
|
||||
|
||||
@router.websocket("/ws/agent-deploy/{agent_id}/{stack_id}")
|
||||
async def ws_agent_deploy(
|
||||
websocket: WebSocket,
|
||||
agent_id: int,
|
||||
stack_id: str,
|
||||
token: str | None = Query(default=None),
|
||||
):
|
||||
"""Proxy a remote agent's `compose up` deploy stream through to the browser,
|
||||
then record the same audit entry as the REST agent lifecycle endpoint."""
|
||||
await websocket.accept()
|
||||
if not await _authorize(websocket, token):
|
||||
return
|
||||
username = decode_token(token, "access").get("sub", "unknown") if token else "unknown"
|
||||
|
||||
with Session(engine) as session:
|
||||
agent = session.get(Agent, agent_id)
|
||||
if not agent:
|
||||
await websocket.send_text(json.dumps({"type": "error", "detail": "agent not found"}))
|
||||
await websocket.close()
|
||||
return
|
||||
|
||||
base = agent.url.rstrip("/")
|
||||
ws_url = ("wss://" + base[8:] if base.startswith("https://")
|
||||
else "ws://" + base[7:] if base.startswith("http://")
|
||||
else "ws://" + base)
|
||||
ws_url += f"/agent/ws/deploy/{stack_id}?token={urllib.parse.quote(agent.token, safe='')}"
|
||||
|
||||
async def _err(detail: str) -> None:
|
||||
with contextlib.suppress(Exception):
|
||||
await websocket.send_text(json.dumps({"type": "error", "detail": detail}))
|
||||
|
||||
try:
|
||||
upstream = await websockets.connect(ws_url, open_timeout=10, ping_interval=20)
|
||||
except websockets.InvalidStatus as exc:
|
||||
code = getattr(getattr(exc, "response", None), "status_code", None)
|
||||
hint = " — the agent may be running an old version without deploy-console support; update it." if code == 404 else ""
|
||||
logger.warning("Agent deploy proxy: handshake to %s failed (%s)", agent.name, code)
|
||||
await _err(f"Agent '{agent.name}' rejected the deploy stream (HTTP {code}){hint}")
|
||||
with contextlib.suppress(Exception):
|
||||
await websocket.close()
|
||||
return
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("Agent deploy proxy: cannot reach %s at %s: %s", agent.name, agent.url, exc)
|
||||
await _err(f"Could not connect to agent '{agent.name}' at {agent.url}: {exc}")
|
||||
with contextlib.suppress(Exception):
|
||||
await websocket.close()
|
||||
return
|
||||
|
||||
rc: int | None = None
|
||||
try:
|
||||
async for message in upstream:
|
||||
text = message if isinstance(message, str) else message.decode("utf-8", "replace")
|
||||
with contextlib.suppress(Exception):
|
||||
msg = json.loads(text)
|
||||
if msg.get("type") == "done":
|
||||
rc = msg.get("returncode")
|
||||
await websocket.send_text(text)
|
||||
except WebSocketDisconnect:
|
||||
pass
|
||||
except websockets.ConnectionClosed as exc:
|
||||
if exc.code not in (1000, 1001):
|
||||
await _err(f"Agent deploy stream closed unexpectedly (code {exc.code}).")
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("Agent deploy proxy: stream error from %s: %s", agent.name, exc)
|
||||
await _err(str(exc))
|
||||
finally:
|
||||
with contextlib.suppress(Exception):
|
||||
await upstream.close()
|
||||
with contextlib.suppress(Exception):
|
||||
await websocket.close()
|
||||
|
||||
with contextlib.suppress(Exception):
|
||||
with Session(engine) as session:
|
||||
audit_service.record(
|
||||
session, user=username, action="agent.stack.start",
|
||||
target=f"{agent.name}/{stack_id}", detail=f"rc={rc} (deploy console)", ip="ws",
|
||||
)
|
||||
|
||||
|
||||
@router.websocket("/ws/events")
|
||||
async def ws_events(
|
||||
websocket: WebSocket,
|
||||
@@ -514,91 +356,3 @@ async def ws_exec(
|
||||
await websocket.close()
|
||||
|
||||
|
||||
@router.websocket("/ws/agent-exec/{agent_id}/{container_id}")
|
||||
async def ws_agent_exec(
|
||||
websocket: WebSocket,
|
||||
agent_id: int,
|
||||
container_id: str,
|
||||
token: str | None = Query(default=None),
|
||||
cmd: str | None = Query(default=None),
|
||||
):
|
||||
"""Proxy an interactive exec session to a remote agent (admin only).
|
||||
|
||||
Unlike the log/deploy proxies this forwards in BOTH directions so keystrokes
|
||||
reach the container and its output streams back."""
|
||||
await websocket.accept()
|
||||
if not await _authorize_admin(websocket, token):
|
||||
return
|
||||
|
||||
with Session(engine) as session:
|
||||
agent = session.get(Agent, agent_id)
|
||||
if not agent:
|
||||
await websocket.send_text(json.dumps({"type": "error", "detail": "agent not found"}))
|
||||
await websocket.close()
|
||||
return
|
||||
|
||||
base = agent.url.rstrip("/")
|
||||
ws_url = ("wss://" + base[8:] if base.startswith("https://")
|
||||
else "ws://" + base[7:] if base.startswith("http://")
|
||||
else "ws://" + base)
|
||||
ws_url += f"/agent/ws/exec/{container_id}?token={urllib.parse.quote(agent.token, safe='')}"
|
||||
if cmd:
|
||||
ws_url += f"&cmd={urllib.parse.quote(cmd, safe='')}"
|
||||
|
||||
async def _err(detail: str) -> None:
|
||||
with contextlib.suppress(Exception):
|
||||
await websocket.send_text(json.dumps({"type": "error", "detail": detail}))
|
||||
|
||||
try:
|
||||
upstream = await websockets.connect(ws_url, open_timeout=10, ping_interval=20)
|
||||
except websockets.InvalidStatus as exc:
|
||||
code = getattr(getattr(exc, "response", None), "status_code", None)
|
||||
hint = " — the agent may be running an old version without terminal support; update it." if code == 404 else ""
|
||||
logger.warning("Agent exec proxy: handshake to %s failed (%s)", agent.name, code)
|
||||
await _err(f"Agent '{agent.name}' rejected the terminal (HTTP {code}){hint}")
|
||||
with contextlib.suppress(Exception):
|
||||
await websocket.close()
|
||||
return
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("Agent exec proxy: cannot reach %s at %s: %s", agent.name, agent.url, exc)
|
||||
await _err(f"Could not connect to agent '{agent.name}' at {agent.url}: {exc}")
|
||||
with contextlib.suppress(Exception):
|
||||
await websocket.close()
|
||||
return
|
||||
|
||||
with contextlib.suppress(Exception):
|
||||
with Session(engine) as session:
|
||||
username = decode_token(token, "access").get("sub", "unknown") if token else "unknown"
|
||||
audit_service.record(
|
||||
session, user=username, action="agent.container.exec",
|
||||
target=f"{agent.name}/{container_id[:12]}", ip="ws",
|
||||
)
|
||||
|
||||
async def browser_to_agent() -> None:
|
||||
try:
|
||||
while True:
|
||||
msg = await websocket.receive_text()
|
||||
await upstream.send(msg)
|
||||
except (WebSocketDisconnect, websockets.ConnectionClosed):
|
||||
pass
|
||||
|
||||
async def agent_to_browser() -> None:
|
||||
try:
|
||||
async for message in upstream:
|
||||
await websocket.send_text(
|
||||
message if isinstance(message, str) else message.decode("utf-8", "replace")
|
||||
)
|
||||
except (WebSocketDisconnect, websockets.ConnectionClosed):
|
||||
pass
|
||||
|
||||
b2a = asyncio.create_task(browser_to_agent())
|
||||
a2b = asyncio.create_task(agent_to_browser())
|
||||
done, pending = await asyncio.wait({b2a, a2b}, return_when=asyncio.FIRST_COMPLETED)
|
||||
for task in pending:
|
||||
task.cancel()
|
||||
with contextlib.suppress(Exception):
|
||||
await asyncio.gather(*pending, return_exceptions=True)
|
||||
with contextlib.suppress(Exception):
|
||||
await upstream.close()
|
||||
with contextlib.suppress(Exception):
|
||||
await websocket.close()
|
||||
|
||||
@@ -1,211 +0,0 @@
|
||||
"""Talk to remote stackpilot-agent hosts over HTTP.
|
||||
|
||||
The central app stores an ``Agent`` row per remote host and proxies stack /
|
||||
system calls to it using the agent's shared token. Connectivity state
|
||||
(``status``, ``hostname``, ``last_seen``) is refreshed on every successful or
|
||||
failed call so the UI can show a live dot per host.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Optional
|
||||
|
||||
import httpx
|
||||
from sqlmodel import Session
|
||||
|
||||
from models.agent import Agent
|
||||
|
||||
logger = logging.getLogger("stackpilot.agent_proxy")
|
||||
|
||||
_TIMEOUT = 30.0
|
||||
|
||||
|
||||
class AgentError(Exception):
|
||||
def __init__(self, status: int, error: str, detail: str = ""):
|
||||
self.status = status
|
||||
self.error = error
|
||||
self.detail = detail
|
||||
super().__init__(f"{error}: {detail}" if detail else error)
|
||||
|
||||
|
||||
def _now() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def _mark(session: Session, agent: Agent, status: str, hostname: Optional[str] = None) -> None:
|
||||
agent.status = status
|
||||
if status == "online":
|
||||
agent.last_seen = _now()
|
||||
if hostname:
|
||||
agent.hostname = hostname
|
||||
session.add(agent)
|
||||
session.commit()
|
||||
session.refresh(agent)
|
||||
|
||||
|
||||
async def _request(
|
||||
agent: Agent,
|
||||
method: str,
|
||||
path: str,
|
||||
*,
|
||||
params: Optional[dict] = None,
|
||||
json: Any = None,
|
||||
) -> httpx.Response:
|
||||
url = agent.url.rstrip("/") + path
|
||||
headers = {"Authorization": f"Bearer {agent.token}"}
|
||||
async with httpx.AsyncClient(follow_redirects=True) as client:
|
||||
return await client.request(
|
||||
method, url, headers=headers, params=params, json=json, timeout=_TIMEOUT
|
||||
)
|
||||
|
||||
|
||||
async def call(
|
||||
session: Session,
|
||||
agent: Agent,
|
||||
method: str,
|
||||
path: str,
|
||||
*,
|
||||
params: Optional[dict] = None,
|
||||
json: Any = None,
|
||||
) -> Any:
|
||||
"""Proxy a request to the agent, updating its status, returning parsed JSON."""
|
||||
try:
|
||||
resp = await _request(agent, method, path, params=params, json=json)
|
||||
except httpx.HTTPError as exc:
|
||||
_mark(session, agent, "offline")
|
||||
raise AgentError(502, "agent_unreachable", str(exc)) from exc
|
||||
|
||||
if resp.status_code in (401, 403):
|
||||
_mark(session, agent, "unauthorized")
|
||||
raise AgentError(resp.status_code, "agent_unauthorized", "Invalid agent token")
|
||||
|
||||
_mark(session, agent, "online")
|
||||
|
||||
if resp.status_code >= 400:
|
||||
detail = ""
|
||||
try:
|
||||
body = resp.json()
|
||||
detail = body.get("detail") if isinstance(body, dict) else str(body)
|
||||
if isinstance(detail, dict):
|
||||
detail = detail.get("detail") or detail.get("error") or str(detail)
|
||||
except ValueError:
|
||||
detail = resp.text[:500]
|
||||
raise AgentError(resp.status_code, "agent_error", str(detail))
|
||||
|
||||
if resp.content:
|
||||
try:
|
||||
return resp.json()
|
||||
except ValueError:
|
||||
return resp.text
|
||||
return None
|
||||
|
||||
|
||||
def _handle_status(session: Session, agent: Agent, status_code: int, body_text: str = "") -> None:
|
||||
"""Update agent status from a response code; raise AgentError on failure."""
|
||||
if status_code in (401, 403):
|
||||
_mark(session, agent, "unauthorized")
|
||||
raise AgentError(status_code, "agent_unauthorized", "Invalid agent token")
|
||||
_mark(session, agent, "online")
|
||||
if status_code >= 400:
|
||||
raise AgentError(status_code, "agent_error", body_text[:500])
|
||||
|
||||
|
||||
async def download_to_file(
|
||||
session: Session,
|
||||
agent: Agent,
|
||||
path: str,
|
||||
dest_path: str,
|
||||
*,
|
||||
params: Optional[dict] = None,
|
||||
) -> None:
|
||||
"""Stream a GET from the agent into ``dest_path``."""
|
||||
url = agent.url.rstrip("/") + path
|
||||
headers = {"Authorization": f"Bearer {agent.token}"}
|
||||
try:
|
||||
async with httpx.AsyncClient(follow_redirects=True) as client:
|
||||
async with client.stream("GET", url, headers=headers, params=params, timeout=None) as resp:
|
||||
if resp.status_code >= 400:
|
||||
text = (await resp.aread()).decode("utf-8", "replace")
|
||||
_handle_status(session, agent, resp.status_code, text)
|
||||
_handle_status(session, agent, resp.status_code)
|
||||
with open(dest_path, "wb") as fh:
|
||||
async for chunk in resp.aiter_bytes(1024 * 256):
|
||||
fh.write(chunk)
|
||||
except httpx.HTTPError as exc:
|
||||
_mark(session, agent, "offline")
|
||||
raise AgentError(502, "agent_unreachable", str(exc)) from exc
|
||||
|
||||
|
||||
async def stream_download(
|
||||
session: Session,
|
||||
agent: Agent,
|
||||
path: str,
|
||||
*,
|
||||
params: Optional[dict] = None,
|
||||
):
|
||||
"""Stream a GET from the agent straight through, yielding chunks.
|
||||
|
||||
Unlike :func:`download_to_file` this never buffers to disk, so a large
|
||||
response (e.g. a folder zip the agent builds on the fly) starts flowing to
|
||||
the browser immediately instead of being staged first.
|
||||
"""
|
||||
url = agent.url.rstrip("/") + path
|
||||
headers = {"Authorization": f"Bearer {agent.token}"}
|
||||
try:
|
||||
async with httpx.AsyncClient(follow_redirects=True) as client:
|
||||
async with client.stream("GET", url, headers=headers, params=params, timeout=None) as resp:
|
||||
if resp.status_code >= 400:
|
||||
text = (await resp.aread()).decode("utf-8", "replace")
|
||||
_handle_status(session, agent, resp.status_code, text)
|
||||
_handle_status(session, agent, resp.status_code)
|
||||
async for chunk in resp.aiter_bytes(1024 * 256):
|
||||
yield chunk
|
||||
except httpx.HTTPError as exc:
|
||||
_mark(session, agent, "offline")
|
||||
raise AgentError(502, "agent_unreachable", str(exc)) from exc
|
||||
|
||||
|
||||
async def upload_file(
|
||||
session: Session,
|
||||
agent: Agent,
|
||||
path: str,
|
||||
file_path: str,
|
||||
filename: str,
|
||||
data: dict,
|
||||
) -> Any:
|
||||
"""Stream a multipart POST (file + form fields) to the agent, returning JSON."""
|
||||
url = agent.url.rstrip("/") + path
|
||||
headers = {"Authorization": f"Bearer {agent.token}"}
|
||||
try:
|
||||
async with httpx.AsyncClient(follow_redirects=True) as client:
|
||||
with open(file_path, "rb") as fh:
|
||||
files = {"file": (filename, fh, "application/gzip")}
|
||||
resp = await client.post(url, headers=headers, files=files, data=data, timeout=None)
|
||||
except httpx.HTTPError as exc:
|
||||
_mark(session, agent, "offline")
|
||||
raise AgentError(502, "agent_unreachable", str(exc)) from exc
|
||||
|
||||
detail = ""
|
||||
if resp.status_code >= 400:
|
||||
try:
|
||||
body = resp.json()
|
||||
detail = body.get("detail") if isinstance(body, dict) else str(body)
|
||||
except ValueError:
|
||||
detail = resp.text[:500]
|
||||
_handle_status(session, agent, resp.status_code, str(detail))
|
||||
return resp.json() if resp.content else None
|
||||
|
||||
|
||||
async def ping(session: Session, agent: Agent) -> dict:
|
||||
"""Health-check an agent and refresh its status + hostname. Never raises."""
|
||||
try:
|
||||
data = await call(session, agent, "GET", "/agent/ping")
|
||||
if isinstance(data, dict) and data.get("hostname"):
|
||||
agent.hostname = data["hostname"]
|
||||
session.add(agent)
|
||||
session.commit()
|
||||
session.refresh(agent)
|
||||
return {"status": agent.status, "hostname": agent.hostname, "data": data}
|
||||
except AgentError:
|
||||
return {"status": agent.status, "hostname": agent.hostname, "data": None}
|
||||
@@ -5,9 +5,8 @@ Runs once per image-update-check cycle (called from
|
||||
cache). For each enabled policy whose stack has a newer image available, either
|
||||
pulls + redeploys the stack or just notifies, recording the outcome.
|
||||
|
||||
Central-only / DB-aware. Image resolution + digest comparison live in the
|
||||
DB-free ``update_service`` so the agent can answer ``/agent/stacks/{id}/updates``
|
||||
with the same logic.
|
||||
Image resolution and digest comparison live in ``update_service``; this module
|
||||
adds the policy layer on top.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -17,11 +16,9 @@ from datetime import datetime, timezone
|
||||
from sqlmodel import Session, select
|
||||
|
||||
from database import engine
|
||||
from models.agent import Agent
|
||||
from models.auto_update import AutoUpdate
|
||||
from models.setting import EVENT_PULL_FAILED, EVENT_STACK_AUTO_UPDATED
|
||||
from services import (
|
||||
agent_service,
|
||||
compose_service,
|
||||
notify_service,
|
||||
stack_lock_service,
|
||||
@@ -39,23 +36,18 @@ def _now() -> datetime:
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Policy CRUD helpers (shared by the stacks + agents routers)
|
||||
# Policy CRUD helpers
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
def get_policy(session: Session, stack_id: str, agent_id: int | None = None) -> AutoUpdate | None:
|
||||
stmt = select(AutoUpdate).where(AutoUpdate.stack_id == stack_id)
|
||||
stmt = stmt.where(AutoUpdate.agent_id == agent_id) if agent_id is not None \
|
||||
else stmt.where(AutoUpdate.agent_id.is_(None))
|
||||
return session.exec(stmt).first()
|
||||
def get_policy(session: Session, stack_id: str) -> AutoUpdate | None:
|
||||
return session.exec(select(AutoUpdate).where(AutoUpdate.stack_id == stack_id)).first()
|
||||
|
||||
|
||||
def upsert_policy(
|
||||
session: Session, stack_id: str, enabled: bool, redeploy: bool, agent_id: int | None = None
|
||||
) -> AutoUpdate:
|
||||
policy = get_policy(session, stack_id, agent_id)
|
||||
def upsert_policy(session: Session, stack_id: str, enabled: bool, redeploy: bool) -> AutoUpdate:
|
||||
policy = get_policy(session, stack_id)
|
||||
if policy is None:
|
||||
policy = AutoUpdate(stack_id=stack_id, agent_id=agent_id)
|
||||
policy = AutoUpdate(stack_id=stack_id)
|
||||
policy.enabled = enabled
|
||||
policy.redeploy = redeploy
|
||||
session.add(policy)
|
||||
@@ -64,22 +56,19 @@ def upsert_policy(
|
||||
return policy
|
||||
|
||||
|
||||
def to_read(session: Session, policy: AutoUpdate | None, stack_id: str, agent_id: int | None = None) -> dict:
|
||||
def to_read(policy: AutoUpdate | None, stack_id: str) -> dict:
|
||||
"""Build an AutoUpdateRead-shaped dict, defaulting to disabled when absent."""
|
||||
agent_name = None
|
||||
if agent_id is not None:
|
||||
agent = session.get(Agent, agent_id)
|
||||
agent_name = agent.name if agent else None
|
||||
if policy is None:
|
||||
return {
|
||||
"id": None, "stack_id": stack_id, "agent_id": agent_id, "agent_name": agent_name,
|
||||
"id": None, "stack_id": stack_id,
|
||||
"enabled": False, "redeploy": True,
|
||||
"last_run": None, "last_status": None, "last_result": None,
|
||||
}
|
||||
return {
|
||||
"id": policy.id, "stack_id": policy.stack_id, "agent_id": policy.agent_id,
|
||||
"agent_name": agent_name, "enabled": policy.enabled, "redeploy": policy.redeploy,
|
||||
"last_run": policy.last_run, "last_status": policy.last_status, "last_result": policy.last_result,
|
||||
"id": policy.id, "stack_id": policy.stack_id,
|
||||
"enabled": policy.enabled, "redeploy": policy.redeploy,
|
||||
"last_run": policy.last_run, "last_status": policy.last_status,
|
||||
"last_result": policy.last_result,
|
||||
}
|
||||
|
||||
|
||||
@@ -138,48 +127,6 @@ async def _run_local(session: Session, policy: AutoUpdate) -> None:
|
||||
)
|
||||
|
||||
|
||||
async def _run_remote(session: Session, policy: AutoUpdate) -> None:
|
||||
agent = session.get(Agent, policy.agent_id)
|
||||
if not agent:
|
||||
_record(session, policy, "error", "agent not found")
|
||||
return
|
||||
stack_id = policy.stack_id
|
||||
try:
|
||||
summary = await agent_service.call(
|
||||
session, agent, "GET", f"/agent/stacks/{stack_id}/updates",
|
||||
params={"refresh": "true"},
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
_record(session, policy, "error", f"agent check failed: {exc}")
|
||||
return
|
||||
if not summary or not summary.get("update_available"):
|
||||
_record(session, policy, "up-to-date")
|
||||
return
|
||||
|
||||
stale = ", ".join(summary.get("stale_images", []))
|
||||
label = f"{agent.name}/{stack_id}"
|
||||
prev = policy.last_status
|
||||
if policy.redeploy:
|
||||
try:
|
||||
await agent_service.call(session, agent, "POST", f"/agent/stacks/{stack_id}/update")
|
||||
except Exception as exc: # noqa: BLE001
|
||||
_record(session, policy, "error", str(exc))
|
||||
await _safe_notify(EVENT_PULL_FAILED, f"Auto-update of '{label}' failed", str(exc), session)
|
||||
return
|
||||
_record(session, policy, "updated", stale)
|
||||
await _safe_notify(
|
||||
EVENT_STACK_AUTO_UPDATED, f"Stack '{label}' auto-updated",
|
||||
f"Pulled and redeployed: {stale}.", session,
|
||||
)
|
||||
else:
|
||||
_record(session, policy, "update-available", stale)
|
||||
if prev != "update-available":
|
||||
await _safe_notify(
|
||||
EVENT_STACK_AUTO_UPDATED, f"Update available for '{label}'",
|
||||
f"Newer images: {stale} (auto-redeploy is off).", session,
|
||||
)
|
||||
|
||||
|
||||
async def _safe_notify(event: str, title: str, message: str, session: Session) -> None:
|
||||
try:
|
||||
await notify_service.notify(event, title, message, session)
|
||||
@@ -188,10 +135,7 @@ async def _safe_notify(event: str, title: str, message: str, session: Session) -
|
||||
|
||||
|
||||
async def run_policy(session: Session, policy: AutoUpdate) -> None:
|
||||
if policy.agent_id is None:
|
||||
await _run_local(session, policy)
|
||||
else:
|
||||
await _run_remote(session, policy)
|
||||
await _run_local(session, policy)
|
||||
|
||||
|
||||
async def run_due() -> None:
|
||||
|
||||
@@ -199,22 +199,6 @@ def containers_for_stack(stack_id: str) -> list[ContainerInfo]:
|
||||
return result
|
||||
|
||||
|
||||
# in-memory set of stacks currently performing a pull/up
|
||||
_BUSY: set[str] = set()
|
||||
|
||||
|
||||
def mark_busy(stack_id: str) -> None:
|
||||
_BUSY.add(stack_id)
|
||||
|
||||
|
||||
def clear_busy(stack_id: str) -> None:
|
||||
_BUSY.discard(stack_id)
|
||||
|
||||
|
||||
def is_busy(stack_id: str) -> bool:
|
||||
return stack_id in _BUSY
|
||||
|
||||
|
||||
def _status_from_states(states: list[str]) -> str:
|
||||
if not states:
|
||||
return "stopped"
|
||||
@@ -229,10 +213,13 @@ def _status_from_states(states: list[str]) -> str:
|
||||
|
||||
|
||||
def compute_status(stack_id: str, containers: Optional[list[ContainerInfo]] = None) -> str:
|
||||
"""Status for one stack. Pass already-fetched ``containers`` to avoid a
|
||||
redundant Docker round-trip (the detail view already has them)."""
|
||||
if stack_id in _BUSY:
|
||||
return "updating"
|
||||
"""Status for one stack, from its containers alone.
|
||||
|
||||
"updating" is not derived here: whether an operation is in flight lives in
|
||||
``stack_lock_service``, and callers that want to show it overlay the lock on
|
||||
top of this. Pass already-fetched ``containers`` to avoid a redundant Docker
|
||||
round-trip (the detail view already has them).
|
||||
"""
|
||||
try:
|
||||
if containers is None:
|
||||
containers = containers_for_stack(stack_id)
|
||||
@@ -447,11 +434,7 @@ async def stream_update(stack_id: str, override: Optional[str] = None):
|
||||
|
||||
|
||||
async def up(stack_id: str, override: Optional[str] = None) -> dict:
|
||||
mark_busy(stack_id)
|
||||
try:
|
||||
return await run_compose(stack_id, ["up", "-d", "--remove-orphans"], override)
|
||||
finally:
|
||||
clear_busy(stack_id)
|
||||
return await run_compose(stack_id, ["up", "-d", "--remove-orphans"], override)
|
||||
|
||||
|
||||
async def down(stack_id: str, override: Optional[str] = None) -> dict:
|
||||
@@ -471,27 +454,19 @@ async def restart(stack_id: str, override: Optional[str] = None) -> dict:
|
||||
|
||||
|
||||
async def pull(stack_id: str, override: Optional[str] = None) -> dict:
|
||||
mark_busy(stack_id)
|
||||
try:
|
||||
return await run_compose(stack_id, ["pull"], override)
|
||||
finally:
|
||||
clear_busy(stack_id)
|
||||
return await run_compose(stack_id, ["pull"], override)
|
||||
|
||||
|
||||
async def update(stack_id: str, override: Optional[str] = None) -> dict:
|
||||
"""Pull then up -d."""
|
||||
mark_busy(stack_id)
|
||||
try:
|
||||
pull_res = await run_compose(stack_id, ["pull"], override)
|
||||
up_res = await run_compose(stack_id, ["up", "-d", "--remove-orphans"], override)
|
||||
return {
|
||||
"returncode": up_res["returncode"],
|
||||
"stdout": pull_res["stdout"] + "\n" + up_res["stdout"],
|
||||
"stderr": pull_res["stderr"] + "\n" + up_res["stderr"],
|
||||
"command": "pull + up -d",
|
||||
}
|
||||
finally:
|
||||
clear_busy(stack_id)
|
||||
pull_res = await run_compose(stack_id, ["pull"], override)
|
||||
up_res = await run_compose(stack_id, ["up", "-d", "--remove-orphans"], override)
|
||||
return {
|
||||
"returncode": up_res["returncode"],
|
||||
"stdout": pull_res["stdout"] + "\n" + up_res["stdout"],
|
||||
"stderr": pull_res["stderr"] + "\n" + up_res["stderr"],
|
||||
"command": "pull + up -d",
|
||||
}
|
||||
|
||||
|
||||
async def logs(
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Single-container inspect + lifecycle — shared by the central app and agent.
|
||||
"""Single-container inspect + lifecycle.
|
||||
|
||||
Only containers that belong to a compose-managed stack (i.e. carry the
|
||||
``com.docker.compose.project`` label) are exposed, so this never becomes a
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
|
||||
Most of StackPilot's secrets are files on disk (``.env``, ``.secrets/*``) where
|
||||
filesystem permissions are the right control. A few can't be: backup
|
||||
destination credentials and agent tokens are needed by background jobs, so they
|
||||
sit in ``stackpilot.db``. This module encrypts those at rest.
|
||||
destination credentials are needed by background jobs, so they sit in
|
||||
``stackpilot.db``. This module encrypts those at rest.
|
||||
|
||||
The key is derived from ``SECRET_KEY`` rather than being a second thing to
|
||||
configure — which is exactly why ``SECRET_KEY`` is now persisted (see
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
"""Fleet aggregate for the dashboard cockpit.
|
||||
"""Host aggregate for the dashboard cockpit.
|
||||
|
||||
One read-only call rolls up every host (local + agents) into a "needs
|
||||
attention" list, headline KPIs and a per-host resource view. It is cheap by
|
||||
construction: a single container *summary* list (no per-container inspect)
|
||||
drives the local figures, image freshness comes from the cache the
|
||||
update-service background loop already maintains, and per agent it makes a
|
||||
small bounded set of HTTP fetches that degrade gracefully on failure.
|
||||
One read-only call rolls the host up into a "needs attention" list, headline
|
||||
KPIs and a resource view. It is cheap by construction: a single container
|
||||
*summary* list (no per-container inspect) drives the figures, and image
|
||||
freshness comes from the cache the update-service background loop already
|
||||
maintains.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -15,15 +14,13 @@ from datetime import datetime, timedelta, timezone
|
||||
|
||||
from sqlmodel import Session, select
|
||||
|
||||
from database import engine
|
||||
from docker_client import DockerError, get_client, safe_call
|
||||
from models.agent import Agent
|
||||
from models.backup_schedule import BackupSchedule
|
||||
from services import agent_service, compose_service, update_service
|
||||
from services import compose_service, update_service
|
||||
|
||||
COMPOSE_LABEL = compose_service.COMPOSE_LABEL
|
||||
|
||||
# Fleet aggregate: cached briefly because each call may fan out to every agent.
|
||||
# Cached briefly: the dashboard polls this and the rollup is not free.
|
||||
FLEET_TTL = 25.0
|
||||
DISK_PRESSURE = 0.85 # disk used fraction above which a host needs attention
|
||||
MEM_PRESSURE = 0.90 # memory used fraction above which a host needs attention
|
||||
@@ -73,14 +70,12 @@ def _is_updated(containers: list[dict], cache: dict[str, dict]) -> bool:
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Fleet aggregate (one call → "needs attention" + KPIs across every host)
|
||||
# Host aggregate (one call → "needs attention" + KPIs)
|
||||
#
|
||||
# The dashboard used to poll each agent individually and recombine the numbers
|
||||
# client-side. ``compute_fleet`` does the fan-out server-side instead: one local
|
||||
# Docker pass plus, per online agent, a small set of system/stacks/updates
|
||||
# fetches — all wrapped so a slow or broken agent degrades to "offline" rather
|
||||
# than stalling the whole view. Cached for FLEET_TTL because the fan-out is not
|
||||
# free.
|
||||
# The dashboard used to fetch these numbers per stack and recombine them
|
||||
# client-side. ``compute_fleet`` rolls them up server-side instead, off one
|
||||
# Docker pass plus the update cache, and holds the result for FLEET_TTL because
|
||||
# the dashboard polls it.
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
# Stack-status buckets the status bar / KPIs are built from. Anything reporting
|
||||
@@ -189,98 +184,12 @@ def _local_host() -> tuple[dict, list[dict]]:
|
||||
return host, attention
|
||||
|
||||
|
||||
def _offline_host(agent_id: int, name: str, status: str) -> dict:
|
||||
return {"id": agent_id, "name": name, "online": False, "status": status,
|
||||
"cpu_cores": 0, "mem_used": 0, "mem_total": 0, "disk_used": 0, "disk_total": 0,
|
||||
"stacks": _bucket_statuses([]), "containers_running": 0, "containers_total": 0,
|
||||
"unhealthy": 0, "updates_available": 0}
|
||||
|
||||
|
||||
async def _agent_host(agent_id: int) -> tuple[dict, list[dict]]:
|
||||
"""One agent's host card + attention items, tolerant of partial failure.
|
||||
|
||||
Opens its own Session so the fan-out across agents stays concurrency-safe
|
||||
(a shared SQLModel session is not), and fetches sequentially within the
|
||||
agent because :func:`agent_service.call` commits a status update each time.
|
||||
"""
|
||||
with Session(engine) as session:
|
||||
agent = session.get(Agent, agent_id)
|
||||
if agent is None:
|
||||
return _offline_host(agent_id, str(agent_id), "unknown"), []
|
||||
name = agent.name
|
||||
# Agent stacks live in the host section of the dashboard, not a route
|
||||
# of their own, so aggregate agent items deep-link back to it.
|
||||
link = "/"
|
||||
|
||||
if agent.status != "online":
|
||||
return _offline_host(agent_id, name, agent.status), [
|
||||
_attn("error", "agent_offline", name,
|
||||
f"{name} is {agent.status}", "Check it under Settings → Remote hosts.",
|
||||
"/settings")]
|
||||
|
||||
async def _fetch(path: str):
|
||||
try:
|
||||
return await agent_service.call(session, agent, "GET", path)
|
||||
except Exception: # AgentError or transport — degrade gracefully
|
||||
return None
|
||||
|
||||
sys_data = await _fetch("/agent/system")
|
||||
stacks = await _fetch("/agent/stacks")
|
||||
updates = await _fetch("/agent/stacks/updates")
|
||||
|
||||
if sys_data is None and stacks is None:
|
||||
# Couldn't reach it at all — agent_service.call already marked it offline.
|
||||
return _offline_host(agent_id, name, "offline"), [
|
||||
_attn("error", "agent_offline", name,
|
||||
f"{name} is unreachable", "Check it under Settings → Remote hosts.",
|
||||
"/settings")]
|
||||
|
||||
sys_data = sys_data or {}
|
||||
statuses = [s.get("status", "") for s in (stacks or [])]
|
||||
buckets = _bucket_statuses(statuses)
|
||||
update_count = sum(1 for v in (updates or {}).values()
|
||||
if isinstance(v, dict) and v.get("update_available"))
|
||||
|
||||
host = {
|
||||
"id": agent_id,
|
||||
"name": name,
|
||||
"online": True,
|
||||
"status": "online",
|
||||
"cpu_cores": sys_data.get("cpu_cores", 0),
|
||||
"mem_used": sys_data.get("mem_used", 0), "mem_total": sys_data.get("mem_total", 0),
|
||||
"disk_used": sys_data.get("disk_used", 0), "disk_total": sys_data.get("disk_total", 0),
|
||||
"stacks": buckets,
|
||||
"containers_running": sys_data.get("compose_running", sys_data.get("containers_running", 0)),
|
||||
"containers_total": sys_data.get("containers_total", 0),
|
||||
"unhealthy": buckets["error"], # agents expose no healthcheck rollup; error is the proxy
|
||||
"updates_available": update_count,
|
||||
}
|
||||
|
||||
attention: list[dict] = []
|
||||
if buckets["error"]:
|
||||
attention.append(_attn("error", "stack_error", name,
|
||||
f"{name}: {buckets['error']} stack(s) in error",
|
||||
"Containers are dead.", link))
|
||||
if buckets["partial"]:
|
||||
attention.append(_attn("warn", "stack_partial", name,
|
||||
f"{name}: {buckets['partial']} stack(s) partially running",
|
||||
"Some services are down.", link))
|
||||
if update_count:
|
||||
attention.append(_attn("warn", "updates", name,
|
||||
f"{name}: {update_count} stack(s) have image updates",
|
||||
"Pull the newer images.", link))
|
||||
attention += _resource_attention(name, link,
|
||||
host["mem_used"], host["mem_total"],
|
||||
host["disk_used"], host["disk_total"])
|
||||
return host, attention
|
||||
|
||||
|
||||
def _backup_attention(session: Session, agent_names: dict[int, str]) -> list[dict]:
|
||||
def _backup_attention(session: Session) -> list[dict]:
|
||||
"""Flag enabled backup schedules whose last run failed or is overdue."""
|
||||
now = datetime.now(timezone.utc)
|
||||
items: list[dict] = []
|
||||
for sch in session.exec(select(BackupSchedule).where(BackupSchedule.enabled == True)).all(): # noqa: E712
|
||||
host = agent_names.get(sch.agent_id, "local") if sch.agent_id else "local"
|
||||
host = "local"
|
||||
status = (sch.last_status or "").lower()
|
||||
if status and not status.startswith("ok"):
|
||||
items.append(_attn("error", "backup_failed", host,
|
||||
@@ -307,23 +216,12 @@ async def compute_fleet(session: Session, refresh: bool = False) -> dict:
|
||||
return _fleet_cache["data"]
|
||||
|
||||
local_host, attention = await asyncio.to_thread(_local_host)
|
||||
|
||||
agents = session.exec(select(Agent)).all()
|
||||
agent_names = {a.id: a.name for a in agents}
|
||||
agent_ids = [a.id for a in agents]
|
||||
agent_results = await asyncio.gather(*[_agent_host(aid) for aid in agent_ids])
|
||||
|
||||
hosts = [local_host]
|
||||
for host, items in agent_results:
|
||||
hosts.append(host)
|
||||
attention += items
|
||||
attention += _backup_attention(session, agent_names)
|
||||
attention += _backup_attention(session)
|
||||
|
||||
attention.sort(key=lambda a: _SEVERITY_ORDER.get(a["severity"], 9))
|
||||
|
||||
kpis = {
|
||||
"hosts_online": sum(1 for h in hosts if h["online"]),
|
||||
"hosts_total": len(hosts),
|
||||
"stacks_running": sum(h["stacks"]["running"] for h in hosts),
|
||||
"stacks_partial": sum(h["stacks"]["partial"] for h in hosts),
|
||||
"stacks_total": sum(h["stacks"]["total"] for h in hosts),
|
||||
|
||||
@@ -94,11 +94,10 @@ def _real_root(path: str) -> str:
|
||||
"""Map a logical host path into the container view (HOST_ROOT_PREFIX).
|
||||
|
||||
Refuses anything that resolves inside StackPilot's own ``DATA_DIR``. That
|
||||
directory holds ``stackpilot.db`` — users, password hashes, agent tokens and
|
||||
directory holds ``stackpilot.db`` — users, password hashes and
|
||||
backup-destination credentials — and the API deliberately never hands those
|
||||
out (``AgentRead.token_set`` is a bool, destination secrets come back
|
||||
masked). Without this the file browser would be a way around that, for
|
||||
admins too. Note this only bites when ``HOST_ROOT_PREFIX`` is empty: with a
|
||||
out (destination secrets come back masked). Without this the file browser
|
||||
would be a way around that, for admins too. Note this only bites when ``HOST_ROOT_PREFIX`` is empty: with a
|
||||
prefix set, no logical path can reach the container's own ``/data`` at all.
|
||||
"""
|
||||
prefix = settings.HOST_ROOT_PREFIX.rstrip("/")
|
||||
|
||||
@@ -66,7 +66,6 @@ def exec_exit_code(exec_id: str):
|
||||
async def pump_exec(websocket, exec_id: str, holder, raw) -> None:
|
||||
"""Bidirectionally pump an exec socket <-> a WebSocket.
|
||||
|
||||
Shared by the central app and the agent (both pass a Starlette 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":...}``
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Image listing — shared by the central images router and the agent."""
|
||||
"""Image listing for the images router."""
|
||||
from __future__ import annotations
|
||||
|
||||
from docker_client import DockerError, get_client, safe_call
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""Persistence for the image update cache.
|
||||
|
||||
``update_service`` holds the registry-digest results in a module dict because
|
||||
it is shared with the agent, which has no database. This module is the central
|
||||
app's half: it seeds that dict at startup and mirrors every write back into
|
||||
SQLite, wired up in ``main.lifespan``.
|
||||
``update_service`` holds the registry-digest results in a module dict and knows
|
||||
nothing about storage — it is pure registry logic and stays unit-testable
|
||||
without a database. This module is its persistence half: it seeds that dict at
|
||||
startup and mirrors every write back into SQLite, wired up in ``main.lifespan``.
|
||||
|
||||
What it buys: after a restart the update badges are there immediately instead
|
||||
of blank until the next background sweep (up to an hour), and the "already
|
||||
|
||||
@@ -11,22 +11,18 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
import tempfile
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from sqlmodel import Session, select
|
||||
|
||||
from database import engine
|
||||
from models.agent import Agent
|
||||
from models.backup_destination import BackupDestination
|
||||
from models.backup_schedule import BackupSchedule
|
||||
from models.setting import EVENT_BACKUP_FAILED
|
||||
from models.stack import Stack
|
||||
from services import (
|
||||
agent_service,
|
||||
backup_destination_service as dest_service,
|
||||
backup_service,
|
||||
compose_service,
|
||||
notify_service,
|
||||
)
|
||||
|
||||
@@ -87,31 +83,16 @@ async def run_schedule(session: Session, schedule: BackupSchedule) -> dict:
|
||||
if not dest:
|
||||
raise RuntimeError(f"destination {schedule.destination_id} not found")
|
||||
|
||||
# Produce the backup archive — locally or by streaming it from an agent.
|
||||
if schedule.agent_id is not None:
|
||||
agent = session.get(Agent, schedule.agent_id)
|
||||
if not agent:
|
||||
raise RuntimeError(f"agent {schedule.agent_id} not found")
|
||||
prefix = compose_service.slugify(agent.name)
|
||||
tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".tar.gz")
|
||||
tmp.close()
|
||||
path = tmp.name
|
||||
await agent_service.download_to_file(
|
||||
session, agent, f"/agent/stacks/{schedule.stack_id}/backup", path,
|
||||
params={"include_volumes": schedule.include_volumes, "stop_first": schedule.stop_first},
|
||||
)
|
||||
else:
|
||||
stack = session.get(Stack, schedule.stack_id)
|
||||
if not stack:
|
||||
raise RuntimeError(f"stack '{schedule.stack_id}' not found")
|
||||
prefix = None
|
||||
path = await backup_service.create_backup(
|
||||
schedule.stack_id, stack.name,
|
||||
include_volumes=schedule.include_volumes, stop_first=schedule.stop_first,
|
||||
)
|
||||
stack = session.get(Stack, schedule.stack_id)
|
||||
if not stack:
|
||||
raise RuntimeError(f"stack '{schedule.stack_id}' not found")
|
||||
path = await backup_service.create_backup(
|
||||
schedule.stack_id, stack.name,
|
||||
include_volumes=schedule.include_volumes, stop_first=schedule.stop_first,
|
||||
)
|
||||
|
||||
filename = backup_service.backup_filename(schedule.stack_id, schedule.include_volumes, prefix=prefix)
|
||||
basename = backup_service.backup_basename(schedule.stack_id, prefix)
|
||||
filename = backup_service.backup_filename(schedule.stack_id, schedule.include_volumes)
|
||||
basename = backup_service.backup_basename(schedule.stack_id)
|
||||
await asyncio.to_thread(dest_service.upload, dest, path, filename)
|
||||
pruned = await asyncio.to_thread(_prune, dest, basename, schedule.keep)
|
||||
schedule.last_status = "ok"
|
||||
|
||||
@@ -5,15 +5,11 @@ 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 (``compose_service._BUSY``), 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`` keeps its in-process set because it is shared with the
|
||||
agent, which has no database. The agent is a single process managing one host,
|
||||
and the central app holds this lock before calling it, so the two do not
|
||||
conflict.
|
||||
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
|
||||
|
||||
|
||||
@@ -53,13 +53,13 @@ _NOTIFIED: set[str] = set()
|
||||
|
||||
#: Optional sink for cache writes.
|
||||
#:
|
||||
#: This module is shared with the agent, which has no database, so persistence
|
||||
#: cannot live here. The central app registers a callback that mirrors each
|
||||
#: entry into SQLite (see ``services/image_status_store.py``) and seeds the
|
||||
#: cache from it at startup; the agent registers nothing and behaves exactly as
|
||||
#: before. Without it a restart blanked every update badge until the next
|
||||
#: background sweep — up to an hour — and re-announced updates it had already
|
||||
#: notified about.
|
||||
#: This module is pure registry logic and knows nothing about storage, which
|
||||
#: keeps it unit-testable without a database. ``main.lifespan`` registers a
|
||||
#: callback that mirrors each entry into SQLite (see
|
||||
#: ``services/image_status_store.py``) and seeds the cache from it at startup.
|
||||
#: Without it a restart blanked every update badge until the next background
|
||||
#: sweep — up to an hour — and re-announced updates it had already notified
|
||||
#: about.
|
||||
_persist_cb: Optional[Callable[[UpdateStatus, bool], None]] = None
|
||||
|
||||
|
||||
@@ -299,7 +299,7 @@ async def stack_updates(stack_id: str, refresh: bool = True) -> dict:
|
||||
|
||||
``refresh=True`` queries the registry now; ``False`` reads the cache the
|
||||
background loop already populated (so the auto-update pass adds no extra
|
||||
registry round-trips). DB-free, so the agent can reuse it verbatim.
|
||||
registry round-trips).
|
||||
"""
|
||||
images = stack_images(stack_id)
|
||||
result: dict[str, dict] = {}
|
||||
|
||||
@@ -1,97 +0,0 @@
|
||||
"""The agent's token guard.
|
||||
|
||||
The agent has no users and no roles: one shared ``AGENT_TOKEN`` is the whole
|
||||
access-control model, declared per route as
|
||||
``dependencies=[Depends(verify_token)]``. That makes a forgotten decorator
|
||||
argument the entire failure mode — one route without it hands anonymous full
|
||||
Docker control of that host, and nothing in review would show it.
|
||||
|
||||
So the invariant is asserted here rather than assumed across 50 decorators.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
#: The only agent routes that may answer without a token — the liveness probe
|
||||
#: the container's HEALTHCHECK calls, which returns nothing but a version.
|
||||
UNAUTHENTICATED = {"GET /agent/health"}
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def agent_app():
|
||||
import agent_app as module
|
||||
|
||||
return module.app
|
||||
|
||||
|
||||
def _routes(app):
|
||||
from fastapi.routing import APIRoute
|
||||
|
||||
out = []
|
||||
for route in app.routes:
|
||||
if not isinstance(route, APIRoute):
|
||||
continue
|
||||
for method in sorted(route.methods - {"HEAD", "OPTIONS"}):
|
||||
out.append((f"{method} {route.path}", route))
|
||||
return sorted(out, key=lambda r: r[0])
|
||||
|
||||
|
||||
def _has_token_guard(route) -> bool:
|
||||
from agent_app import verify_token
|
||||
|
||||
found = [False]
|
||||
|
||||
def walk(dependant):
|
||||
for sub in dependant.dependencies:
|
||||
if sub.call is verify_token:
|
||||
found[0] = True
|
||||
walk(sub)
|
||||
|
||||
walk(route.dependant)
|
||||
return found[0]
|
||||
|
||||
|
||||
def test_every_agent_route_requires_the_token(agent_app):
|
||||
unguarded = {
|
||||
key
|
||||
for key, route in _routes(agent_app)
|
||||
if not _has_token_guard(route) and not key.startswith("GET /agent/health")
|
||||
}
|
||||
assert not unguarded, (
|
||||
"These agent routes answer without AGENT_TOKEN, which is full Docker "
|
||||
f"access to the host: {sorted(unguarded)}"
|
||||
)
|
||||
|
||||
|
||||
def test_only_the_health_probe_is_unauthenticated(agent_app):
|
||||
open_routes = {key for key, route in _routes(agent_app) if not _has_token_guard(route)}
|
||||
assert open_routes == UNAUTHENTICATED
|
||||
|
||||
|
||||
def test_a_wrong_token_is_rejected(agent_app, monkeypatch):
|
||||
from starlette.testclient import TestClient
|
||||
|
||||
from config import settings
|
||||
|
||||
monkeypatch.setattr(settings, "AGENT_TOKEN", "the-real-token", raising=False)
|
||||
client = TestClient(agent_app, raise_server_exceptions=False)
|
||||
|
||||
assert client.get("/agent/ping").status_code == 401
|
||||
assert client.get(
|
||||
"/agent/ping", headers={"Authorization": "Bearer wrong"}
|
||||
).status_code == 401
|
||||
# The health probe stays open so the container's HEALTHCHECK works.
|
||||
assert client.get("/agent/health").status_code == 200
|
||||
|
||||
|
||||
def test_an_unset_token_refuses_everything(agent_app, monkeypatch):
|
||||
"""An agent started without AGENT_TOKEN must not be wide open."""
|
||||
from starlette.testclient import TestClient
|
||||
|
||||
from config import settings
|
||||
|
||||
monkeypatch.setattr(settings, "AGENT_TOKEN", "", raising=False)
|
||||
client = TestClient(agent_app, raise_server_exceptions=False)
|
||||
|
||||
response = client.get("/agent/ping", headers={"Authorization": "Bearer anything"})
|
||||
assert response.status_code == 503
|
||||
@@ -0,0 +1,201 @@
|
||||
"""Cleaning up after the removed multi-host integration.
|
||||
|
||||
The agent sidecar and everything that proxied to it were removed in 0.48.0.
|
||||
Upgrading installs still carry the schema it left behind, and one part of that
|
||||
is not merely dead weight: the ``agent`` table held each remote host's URL and
|
||||
its bearer token, which is full Docker control of that host. Leaving those in
|
||||
the database for a feature that no longer exists would be worse than dropping
|
||||
them, so ``_drop_removed_schema`` drops the table outright.
|
||||
|
||||
The ``agent_id`` columns are only dropped where the SQLite build supports it
|
||||
(DROP COLUMN needs 3.35+); they are nullable and unread, so leaving them is
|
||||
harmless.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import create_engine, inspect, text
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def pre_048_db(tmp_path, monkeypatch):
|
||||
"""A database as an install running 0.47.0 would have it."""
|
||||
import database
|
||||
import models # noqa: F401 — populates SQLModel.metadata
|
||||
|
||||
engine = create_engine(f"sqlite:///{tmp_path / 'legacy.db'}")
|
||||
with engine.begin() as conn:
|
||||
conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE TABLE agent (
|
||||
id INTEGER NOT NULL PRIMARY KEY,
|
||||
name VARCHAR NOT NULL,
|
||||
url VARCHAR NOT NULL,
|
||||
token VARCHAR NOT NULL,
|
||||
status VARCHAR NOT NULL,
|
||||
hostname VARCHAR,
|
||||
last_seen DATETIME,
|
||||
created_at DATETIME NOT NULL
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
conn.execute(
|
||||
text(
|
||||
"INSERT INTO agent (id, name, url, token, status, created_at) VALUES"
|
||||
" (1, 'nas', 'http://10.0.0.5:5010', 'super-secret-agent-token',"
|
||||
" 'online', '2026-01-01')"
|
||||
)
|
||||
)
|
||||
conn.execute(
|
||||
text(
|
||||
"""
|
||||
CREATE TABLE autoupdate (
|
||||
id INTEGER NOT NULL PRIMARY KEY,
|
||||
stack_id VARCHAR NOT NULL,
|
||||
agent_id INTEGER,
|
||||
enabled BOOLEAN NOT NULL,
|
||||
redeploy BOOLEAN NOT NULL,
|
||||
last_run DATETIME,
|
||||
last_status VARCHAR,
|
||||
last_result VARCHAR,
|
||||
created_at DATETIME NOT NULL
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
conn.execute(
|
||||
text(
|
||||
"INSERT INTO autoupdate (id, stack_id, agent_id, enabled, redeploy,"
|
||||
" created_at) VALUES (1, 'jellyfin', NULL, 1, 1, '2026-01-01')"
|
||||
)
|
||||
)
|
||||
monkeypatch.setattr(database, "engine", engine)
|
||||
return engine
|
||||
|
||||
|
||||
def test_the_agent_table_and_its_tokens_are_dropped(pre_048_db):
|
||||
import database
|
||||
|
||||
assert "agent" in inspect(pre_048_db).get_table_names()
|
||||
|
||||
database._drop_removed_schema()
|
||||
|
||||
assert "agent" not in inspect(pre_048_db).get_table_names(), (
|
||||
"the agent table holds host URLs and bearer tokens for a feature that no "
|
||||
"longer exists — it must not survive the upgrade"
|
||||
)
|
||||
|
||||
|
||||
def test_surviving_rows_are_untouched(pre_048_db):
|
||||
"""Dropping the agent schema must not disturb the policies that remain."""
|
||||
import database
|
||||
|
||||
database._drop_removed_schema()
|
||||
|
||||
with pre_048_db.begin() as conn:
|
||||
row = conn.execute(
|
||||
text("SELECT stack_id, enabled FROM autoupdate WHERE id = 1")
|
||||
).one()
|
||||
assert row.stack_id == "jellyfin"
|
||||
assert row.enabled
|
||||
|
||||
|
||||
def test_the_agent_id_column_is_dropped_where_sqlite_allows_it(pre_048_db):
|
||||
import sqlite3
|
||||
|
||||
import database
|
||||
|
||||
database._drop_removed_schema()
|
||||
columns = {c["name"] for c in inspect(pre_048_db).get_columns("autoupdate")}
|
||||
supports_drop = tuple(int(p) for p in sqlite3.sqlite_version.split(".")) >= (3, 35, 0)
|
||||
if supports_drop:
|
||||
assert "agent_id" not in columns
|
||||
else: # pragma: no cover - depends on the host's SQLite
|
||||
assert "agent_id" in columns, "the fallback must leave the column alone"
|
||||
|
||||
|
||||
def test_an_unsupported_drop_column_does_not_block_the_table_drop(
|
||||
pre_048_db, monkeypatch
|
||||
):
|
||||
"""A failed DDL poisons its transaction.
|
||||
|
||||
If the table drop and the column drops shared one, a SQLite too old for
|
||||
DROP COLUMN would take the agent table — tokens and all — down with it.
|
||||
"""
|
||||
import database
|
||||
from sqlalchemy.exc import OperationalError
|
||||
|
||||
real_execute = database.text
|
||||
|
||||
def exploding_text(sql):
|
||||
if "DROP COLUMN" in sql:
|
||||
raise OperationalError("DROP COLUMN", {}, Exception("near \"DROP\""))
|
||||
return real_execute(sql)
|
||||
|
||||
monkeypatch.setattr(database, "text", exploding_text)
|
||||
database._drop_removed_schema()
|
||||
|
||||
assert "agent" not in inspect(pre_048_db).get_table_names(), (
|
||||
"the table drop must not be collateral damage of an unsupported column drop"
|
||||
)
|
||||
|
||||
|
||||
def test_running_it_twice_is_harmless(pre_048_db):
|
||||
"""It runs on every start, not just the first one after the upgrade."""
|
||||
import database
|
||||
|
||||
database._drop_removed_schema()
|
||||
database._drop_removed_schema()
|
||||
assert "agent" not in inspect(pre_048_db).get_table_names()
|
||||
|
||||
|
||||
def test_a_fresh_install_is_unaffected(db):
|
||||
"""Nothing to drop, and no error for trying."""
|
||||
import database
|
||||
|
||||
database._drop_removed_schema()
|
||||
assert "agent" not in inspect(database.engine).get_table_names()
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Nothing agent-shaped is left in the running application
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
def test_no_route_mentions_agents(app):
|
||||
from fastapi.routing import APIRoute
|
||||
|
||||
leftovers = [
|
||||
r.path
|
||||
for r in app.routes
|
||||
if "agent" in getattr(r, "path", "").lower()
|
||||
]
|
||||
assert not leftovers, f"remote-host routes still registered: {leftovers}"
|
||||
assert not any(
|
||||
isinstance(r, APIRoute) and "/api/agents" in r.path for r in app.routes
|
||||
)
|
||||
|
||||
|
||||
def test_no_agent_model_is_registered():
|
||||
from sqlmodel import SQLModel
|
||||
|
||||
import models # noqa: F401
|
||||
|
||||
assert "agent" not in SQLModel.metadata.tables
|
||||
|
||||
|
||||
def test_the_agent_modules_are_gone():
|
||||
"""Import guards, so a stray file cannot quietly come back."""
|
||||
import importlib
|
||||
|
||||
for name in ("agent_app", "models.agent", "routers.agents", "services.agent_service"):
|
||||
with pytest.raises(ModuleNotFoundError):
|
||||
importlib.import_module(name)
|
||||
|
||||
|
||||
def test_no_agent_token_setting():
|
||||
from config import settings
|
||||
|
||||
assert not hasattr(settings, "AGENT_TOKEN")
|
||||
@@ -7,7 +7,7 @@ Two independent gates, both in :mod:`services.device_service`:
|
||||
anything landing inside StackPilot's own ``DATA_DIR``.
|
||||
|
||||
The second gate exists because the API deliberately never hands out what lives
|
||||
there (agent tokens come back as a bool, destination secrets come back masked),
|
||||
there (destination secrets come back masked),
|
||||
so the file browser must not be the way around that — for admins either.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -78,15 +78,10 @@ def test_status_from_states(svc, states, expected):
|
||||
assert svc._status_from_states(states) == expected
|
||||
|
||||
|
||||
def test_busy_stacks_report_as_updating(svc):
|
||||
"""The busy flag has to win over the container states, or a stack shows
|
||||
'stopped' for the moment between `down` and `up` during an update."""
|
||||
svc.mark_busy("busy-stack")
|
||||
try:
|
||||
assert svc.compute_status("busy-stack", containers=[]) == "updating"
|
||||
finally:
|
||||
svc.clear_busy("busy-stack")
|
||||
assert svc.compute_status("busy-stack", containers=[]) == "stopped"
|
||||
def test_status_comes_from_the_containers_alone(svc):
|
||||
""""updating" is not derived here — that lives in ``stack_lock_service``,
|
||||
and callers overlay it. Keeping both would be two sources of truth."""
|
||||
assert svc.compute_status("no-such-stack", containers=[]) == "stopped"
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
@@ -44,10 +44,9 @@ PUBLIC = {
|
||||
#: Reachable by the read-only ``user`` role. Everything here has been checked
|
||||
#: for whether it can return a credential:
|
||||
#:
|
||||
#: * ``GET /api/agents`` returns ``AgentRead``, whose ``token_set`` is a bool.
|
||||
#: * ``GET /api/settings`` returns the interval and counts — webhook URLs (which
|
||||
#: carry tokens) come from the admin-only ``/api/settings/webhooks``.
|
||||
#: * ``GET /api/stacks/{id}`` and its agent twin blank out ``env`` for non-admins.
|
||||
#: * ``GET /api/stacks/{id}`` blanks out ``env`` for non-admins.
|
||||
#: * ``GET /api/templates`` is metadata only; the detail route, which returns a
|
||||
#: template's env, is admin-only.
|
||||
#: * The ``/api/editor/*`` routes are pure YAML transformations — they take YAML
|
||||
@@ -94,24 +93,6 @@ USER_READABLE = {
|
||||
"GET /api/system/devices",
|
||||
"GET /api/system/update",
|
||||
"GET /api/templates",
|
||||
# Remote hosts: the same read-only surface, proxied.
|
||||
"GET /api/agents",
|
||||
"POST /api/agents/{agent_id}/ping",
|
||||
"GET /api/agents/{agent_id}/system",
|
||||
"GET /api/agents/{agent_id}/stacks",
|
||||
"GET /api/agents/{agent_id}/stacks/stats",
|
||||
"GET /api/agents/{agent_id}/stacks/updates",
|
||||
"GET /api/agents/{agent_id}/stacks/{stack_id}",
|
||||
"GET /api/agents/{agent_id}/stacks/{stack_id}/auto-update",
|
||||
"GET /api/agents/{agent_id}/stacks/{stack_id}/logs",
|
||||
"GET /api/agents/{agent_id}/containers/{container_id}",
|
||||
"GET /api/agents/{agent_id}/images",
|
||||
"GET /api/agents/{agent_id}/images/updates",
|
||||
"GET /api/agents/{agent_id}/networks",
|
||||
"GET /api/agents/{agent_id}/networks/{network_id}",
|
||||
"GET /api/agents/{agent_id}/networks/{network_id}/containers",
|
||||
"GET /api/agents/{agent_id}/volumes",
|
||||
"GET /api/agents/{agent_id}/volumes/sizes",
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -184,11 +184,12 @@ def test_pruning_drops_images_no_stack_uses_any_more(clean_image_status):
|
||||
assert [r.image for r in session.exec(select(ImageStatus)).all()] == ["kept:1"]
|
||||
|
||||
|
||||
def test_the_agent_has_no_persistence_wired_up(clean_image_status):
|
||||
"""``update_service`` is shared with the agent, which has no database.
|
||||
def test_the_registry_layer_stays_free_of_storage(clean_image_status):
|
||||
"""``update_service`` is pure registry logic.
|
||||
|
||||
Persistence therefore has to be opt-in, registered by the central app —
|
||||
if this module ever imports the database directly, the agent breaks.
|
||||
Persistence is opt-in, registered by ``main.lifespan``, which keeps the
|
||||
module unit-testable without a database and keeps the storage decision in
|
||||
one place. This is the kind of boundary a later change erases silently.
|
||||
"""
|
||||
import inspect
|
||||
|
||||
|
||||
+1
-1
@@ -1,3 +1,3 @@
|
||||
"""Single source of truth for the StackPilot release version."""
|
||||
|
||||
APP_VERSION = "0.47.0"
|
||||
APP_VERSION = "0.48.0"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "stackpilot-frontend",
|
||||
"private": true,
|
||||
"version": "0.47.0",
|
||||
"version": "0.48.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
|
||||
@@ -6,7 +6,6 @@ import { Dashboard } from "@/pages/Dashboard";
|
||||
import { Stacks } from "@/pages/Stacks";
|
||||
import { StackDetail } from "@/pages/StackDetail";
|
||||
import { StackEditor } from "@/pages/StackEditor";
|
||||
import { RemoteStackDetail } from "@/pages/RemoteStackDetail";
|
||||
import { Images } from "@/pages/Images";
|
||||
import { Files } from "@/pages/Files";
|
||||
import { Volumes } from "@/pages/Volumes";
|
||||
@@ -63,7 +62,6 @@ export default function App() {
|
||||
<Route path="/stacks/new" element={<StackEditor />} />
|
||||
<Route path="/stacks/:id" element={<StackDetail />} />
|
||||
<Route path="/stacks/:id/edit" element={<StackEditor />} />
|
||||
<Route path="/hosts/:agentId/stacks/:id" element={<RemoteStackDetail />} />
|
||||
<Route path="/networks" element={<Networks />} />
|
||||
<Route path="/images" element={<Images />} />
|
||||
<Route path="/volumes" element={<Volumes />} />
|
||||
|
||||
@@ -1,132 +0,0 @@
|
||||
import api from "./client";
|
||||
import { backupParams, readReport } from "./backups";
|
||||
import type { BackupInventory, BackupOptions, RestoreResult } from "./backups";
|
||||
import type { Agent, StackDetail, StackStats, StackSummary, StackUpdateInfo } from "@/types";
|
||||
|
||||
export type RemoteStackSummary = StackSummary & { agent_id: number; agent_name: string };
|
||||
export type RemoteStackDetail = StackDetail & { agent_id: number; agent_name: string };
|
||||
|
||||
export interface AgentSystem {
|
||||
hostname: string;
|
||||
docker_version: string;
|
||||
host_os: string;
|
||||
cpu_cores: number;
|
||||
mem_total: number;
|
||||
mem_used: number;
|
||||
disk_total: number;
|
||||
disk_used: number;
|
||||
containers_running: number;
|
||||
containers_total: number;
|
||||
compose_running?: number; // agents < 0.31.1 don't report it
|
||||
}
|
||||
|
||||
export const agentsApi = {
|
||||
list: (refresh = true) =>
|
||||
api.get<Agent[]>(`/api/agents?refresh=${refresh}`).then((r) => r.data),
|
||||
create: (body: { name: string; url: string; token: string }) =>
|
||||
api.post<Agent>("/api/agents", body).then((r) => r.data),
|
||||
update: (id: number, body: { name?: string; url?: string; token?: string }) =>
|
||||
api.put<Agent>(`/api/agents/${id}`, body).then((r) => r.data),
|
||||
remove: (id: number) => api.delete(`/api/agents/${id}`).then((r) => r.data),
|
||||
ping: (id: number) =>
|
||||
api.post<{ status: string; hostname?: string }>(`/api/agents/${id}/ping`).then((r) => r.data),
|
||||
|
||||
system: (id: number) =>
|
||||
api.get<AgentSystem>(`/api/agents/${id}/system`).then((r) => r.data),
|
||||
stacks: (id: number) =>
|
||||
api.get<RemoteStackSummary[]>(`/api/agents/${id}/stacks`).then((r) => r.data),
|
||||
stackStats: (id: number) =>
|
||||
api.get<Record<string, StackStats>>(`/api/agents/${id}/stacks/stats`).then((r) => r.data),
|
||||
stackUpdates: (id: number) =>
|
||||
api
|
||||
.get<Record<string, StackUpdateInfo>>(`/api/agents/${id}/stacks/updates`)
|
||||
.then((r) => r.data),
|
||||
createStack: (id: number, body: { name: string; yaml: string; env?: string }) =>
|
||||
api
|
||||
.post<{ id: string; name: string }>(`/api/agents/${id}/stacks`, body)
|
||||
.then((r) => r.data),
|
||||
stack: (id: number, stackId: string) =>
|
||||
api.get<RemoteStackDetail>(`/api/agents/${id}/stacks/${stackId}`).then((r) => r.data),
|
||||
logs: (id: number, stackId: string, tail = 200) =>
|
||||
api
|
||||
.get<{ logs: string }>(`/api/agents/${id}/stacks/${stackId}/logs?tail=${tail}`)
|
||||
.then((r) => r.data),
|
||||
update_stack: (id: number, stackId: string, body: { yaml?: string; env?: string }) =>
|
||||
api.put(`/api/agents/${id}/stacks/${stackId}`, body).then((r) => r.data),
|
||||
action: (id: number, stackId: string, action: string) =>
|
||||
api.post(`/api/agents/${id}/stacks/${stackId}/${action}`).then((r) => r.data),
|
||||
|
||||
backupInventory: (id: number, stackId: string) =>
|
||||
api
|
||||
.get<BackupInventory>(`/api/agents/${id}/stacks/${stackId}/backup/inventory`)
|
||||
.then((r) => r.data),
|
||||
backupDownload: async (id: number, stackId: string, opts: BackupOptions) => {
|
||||
const res = await api.get(`/api/agents/${id}/stacks/${stackId}/backup`, {
|
||||
params: backupParams(opts),
|
||||
responseType: "blob",
|
||||
});
|
||||
const cd = res.headers["content-disposition"] as string | undefined;
|
||||
const name = cd?.match(/filename="?([^"]+)"?/)?.[1] ?? `backup-${stackId}.tar.gz`;
|
||||
const url = URL.createObjectURL(res.data as Blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = name;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
URL.revokeObjectURL(url);
|
||||
return readReport(res.headers);
|
||||
},
|
||||
backupPush: (
|
||||
id: number,
|
||||
stackId: string,
|
||||
body: {
|
||||
destination_id: number;
|
||||
include_volumes: boolean;
|
||||
include_binds?: boolean;
|
||||
stop_first: boolean;
|
||||
binds?: string[];
|
||||
volumes?: string[];
|
||||
}
|
||||
) =>
|
||||
api
|
||||
.post<{ ok: boolean; destination: string; name: string }>(
|
||||
`/api/agents/${id}/stacks/${stackId}/backup/push`,
|
||||
body
|
||||
)
|
||||
.then((r) => r.data),
|
||||
restoreUpload: (
|
||||
id: number,
|
||||
file: File,
|
||||
opts: {
|
||||
targetId?: string;
|
||||
overwrite: boolean;
|
||||
restoreVolumes: boolean;
|
||||
restoreBinds?: boolean;
|
||||
}
|
||||
) => {
|
||||
const form = new FormData();
|
||||
form.append("file", file);
|
||||
if (opts.targetId) form.append("target_id", opts.targetId);
|
||||
form.append("overwrite", String(opts.overwrite));
|
||||
form.append("restore_volumes", String(opts.restoreVolumes));
|
||||
form.append("restore_binds", String(opts.restoreBinds ?? true));
|
||||
return api
|
||||
.post<RestoreResult>(`/api/agents/${id}/stacks/restore`, form)
|
||||
.then((r) => r.data);
|
||||
},
|
||||
restoreFrom: (
|
||||
id: number,
|
||||
body: {
|
||||
destination_id: number;
|
||||
name: string;
|
||||
target_id?: string;
|
||||
overwrite: boolean;
|
||||
restore_volumes: boolean;
|
||||
restore_binds?: boolean;
|
||||
}
|
||||
) =>
|
||||
api
|
||||
.post<RestoreResult>(`/api/agents/${id}/stacks/restore-from`, body)
|
||||
.then((r) => r.data),
|
||||
};
|
||||
@@ -3,8 +3,6 @@ import api from "./client";
|
||||
export interface AutoUpdatePolicy {
|
||||
id: number | null;
|
||||
stack_id: string;
|
||||
agent_id: number | null;
|
||||
agent_name: string | null;
|
||||
enabled: boolean;
|
||||
redeploy: boolean;
|
||||
last_run: string | null;
|
||||
@@ -12,17 +10,12 @@ export interface AutoUpdatePolicy {
|
||||
last_result: string | null;
|
||||
}
|
||||
|
||||
// Local host, or a remote agent's stack when agentId is given.
|
||||
const base = (stackId: string, agentId?: number) =>
|
||||
agentId != null
|
||||
? `/api/agents/${agentId}/stacks/${stackId}/auto-update`
|
||||
: `/api/stacks/${stackId}/auto-update`;
|
||||
const base = (stackId: string) => `/api/stacks/${stackId}/auto-update`;
|
||||
|
||||
export const autoUpdateApi = {
|
||||
get: (stackId: string, agentId?: number) =>
|
||||
api.get<AutoUpdatePolicy>(base(stackId, agentId)).then((r) => r.data),
|
||||
set: (stackId: string, body: { enabled: boolean; redeploy: boolean }, agentId?: number) =>
|
||||
api.put<AutoUpdatePolicy>(base(stackId, agentId), body).then((r) => r.data),
|
||||
run: (stackId: string, agentId?: number) =>
|
||||
api.post<AutoUpdatePolicy>(`${base(stackId, agentId)}/run`).then((r) => r.data),
|
||||
get: (stackId: string) => api.get<AutoUpdatePolicy>(base(stackId)).then((r) => r.data),
|
||||
set: (stackId: string, body: { enabled: boolean; redeploy: boolean }) =>
|
||||
api.put<AutoUpdatePolicy>(base(stackId), body).then((r) => r.data),
|
||||
run: (stackId: string) =>
|
||||
api.post<AutoUpdatePolicy>(`${base(stackId)}/run`).then((r) => r.data),
|
||||
};
|
||||
|
||||
@@ -67,7 +67,7 @@ export interface BackupOptions {
|
||||
volumes?: string[];
|
||||
}
|
||||
|
||||
/** Query params shared by the local and the agent-proxied backup endpoints. */
|
||||
/** Query params for the backup endpoints. */
|
||||
export function backupParams(opts: BackupOptions) {
|
||||
return {
|
||||
include_volumes: opts.includeVolumes,
|
||||
|
||||
@@ -31,13 +31,10 @@ export interface ContainerDetail {
|
||||
|
||||
export type ContainerAction = "start" | "stop" | "restart";
|
||||
|
||||
// Base path for the local host or, when agentId is given, a remote agent.
|
||||
const base = (agentId?: number) =>
|
||||
agentId != null ? `/api/agents/${agentId}/containers` : "/api/containers";
|
||||
const base = "/api/containers";
|
||||
|
||||
export const containersApi = {
|
||||
inspect: (id: string, agentId?: number) =>
|
||||
api.get<ContainerDetail>(`${base(agentId)}/${id}`).then((r) => r.data),
|
||||
action: (id: string, action: ContainerAction, agentId?: number) =>
|
||||
api.post(`${base(agentId)}/${id}/${action}`).then((r) => r.data),
|
||||
inspect: (id: string) => api.get<ContainerDetail>(`${base}/${id}`).then((r) => r.data),
|
||||
action: (id: string, action: ContainerAction) =>
|
||||
api.post(`${base}/${id}/${action}`).then((r) => r.data),
|
||||
};
|
||||
|
||||
@@ -9,7 +9,7 @@ export interface StackBuckets {
|
||||
}
|
||||
|
||||
export interface FleetHost {
|
||||
id: string | number; // "local" or an agent id
|
||||
id: string | number;
|
||||
name: string;
|
||||
online: boolean;
|
||||
status: string;
|
||||
@@ -26,8 +26,6 @@ export interface FleetHost {
|
||||
}
|
||||
|
||||
export interface FleetKpis {
|
||||
hosts_online: number;
|
||||
hosts_total: number;
|
||||
stacks_running: number;
|
||||
stacks_partial: number;
|
||||
stacks_total: number;
|
||||
|
||||
+21
-25
@@ -20,51 +20,48 @@ function triggerDownload(blob: Blob, filename: string) {
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
|
||||
// Base path for the local host or, when agentId is given, a remote agent.
|
||||
const base = (agentId?: number) =>
|
||||
agentId != null ? `/api/agents/${agentId}/files` : "/api/files";
|
||||
const base = "/api/files";
|
||||
|
||||
export const filesApi = {
|
||||
list: (path: string, showHidden = false, agentId?: number) =>
|
||||
list: (path: string, showHidden = false) =>
|
||||
api
|
||||
.get<HostPathResult>(`${base(agentId)}/list`, { params: { path, show_hidden: showHidden } })
|
||||
.get<HostPathResult>(`${base}/list`, { params: { path, show_hidden: showHidden } })
|
||||
.then((r) => r.data),
|
||||
|
||||
read: (path: string, agentId?: number) =>
|
||||
api.get<FileContent>(`${base(agentId)}/read`, { params: { path } }).then((r) => r.data),
|
||||
read: (path: string) =>
|
||||
api.get<FileContent>(`${base}/read`, { params: { path } }).then((r) => r.data),
|
||||
|
||||
write: (path: string, content: string, agentId?: number) =>
|
||||
api.put<{ path: string; size: number }>(`${base(agentId)}/write`, { path, content }).then((r) => r.data),
|
||||
write: (path: string, content: string) =>
|
||||
api.put<{ path: string; size: number }>(`${base}/write`, { path, content }).then((r) => r.data),
|
||||
|
||||
mkdir: (path: string, name: string, agentId?: number) =>
|
||||
api.post<{ path: string }>(`${base(agentId)}/mkdir`, { path, name }).then((r) => r.data),
|
||||
mkdir: (path: string, name: string) =>
|
||||
api.post<{ path: string }>(`${base}/mkdir`, { path, name }).then((r) => r.data),
|
||||
|
||||
touch: (path: string, name: string, agentId?: number) =>
|
||||
api.post<{ path: string }>(`${base(agentId)}/touch`, { path, name }).then((r) => r.data),
|
||||
touch: (path: string, name: string) =>
|
||||
api.post<{ path: string }>(`${base}/touch`, { path, name }).then((r) => r.data),
|
||||
|
||||
rename: (path: string, newName: string, agentId?: number) =>
|
||||
api.post<{ path: string }>(`${base(agentId)}/rename`, { path, new_name: newName }).then((r) => r.data),
|
||||
rename: (path: string, newName: string) =>
|
||||
api.post<{ path: string }>(`${base}/rename`, { path, new_name: newName }).then((r) => r.data),
|
||||
|
||||
remove: (path: string, recursive = false, agentId?: number) =>
|
||||
api.delete(base(agentId), { params: { path, recursive } }).then((r) => r.data),
|
||||
remove: (path: string, recursive = false) =>
|
||||
api.delete(base, { params: { path, recursive } }).then((r) => r.data),
|
||||
|
||||
copy: (src: string, destDir: string, overwrite = false, agentId?: number) =>
|
||||
copy: (src: string, destDir: string, overwrite = false) =>
|
||||
api
|
||||
.post<{ path: string }>(`${base(agentId)}/copy`, { src, dest_dir: destDir, overwrite })
|
||||
.post<{ path: string }>(`${base}/copy`, { src, dest_dir: destDir, overwrite })
|
||||
.then((r) => r.data),
|
||||
|
||||
move: (src: string, destDir: string, overwrite = false, agentId?: number) =>
|
||||
move: (src: string, destDir: string, overwrite = false) =>
|
||||
api
|
||||
.post<{ path: string }>(`${base(agentId)}/move`, { src, dest_dir: destDir, overwrite })
|
||||
.post<{ path: string }>(`${base}/move`, { src, dest_dir: destDir, overwrite })
|
||||
.then((r) => r.data),
|
||||
|
||||
download: async (
|
||||
path: string,
|
||||
filename: string,
|
||||
agentId?: number,
|
||||
onProgress?: (loaded: number, total: number | undefined) => void,
|
||||
) => {
|
||||
const res = await api.get(`${base(agentId)}/download`, {
|
||||
const res = await api.get(`${base}/download`, {
|
||||
params: { path },
|
||||
responseType: "blob",
|
||||
onDownloadProgress: onProgress
|
||||
@@ -79,7 +76,6 @@ export const filesApi = {
|
||||
file: File,
|
||||
overwrite = false,
|
||||
relPath = "",
|
||||
agentId?: number,
|
||||
onProgress?: (pct: number) => void,
|
||||
) => {
|
||||
const form = new FormData();
|
||||
@@ -87,7 +83,7 @@ export const filesApi = {
|
||||
form.append("overwrite", String(overwrite));
|
||||
if (relPath) form.append("rel_path", relPath);
|
||||
form.append("file", file);
|
||||
const res = await api.post<{ ok: boolean; name: string }>(`${base(agentId)}/upload`, form, {
|
||||
const res = await api.post<{ ok: boolean; name: string }>(`${base}/upload`, form, {
|
||||
onUploadProgress: onProgress
|
||||
? (e) => {
|
||||
const pct = e.total ? (e.loaded / e.total) * 100 : (e.progress ?? 0) * 100;
|
||||
|
||||
@@ -18,22 +18,16 @@ export interface ImageRow {
|
||||
update: UpdateStatus | null;
|
||||
}
|
||||
|
||||
// Base path for the local host or, when agentId is given, a remote agent.
|
||||
const base = (agentId?: number) =>
|
||||
agentId != null ? `/api/agents/${agentId}/images` : "/api/images";
|
||||
const base = "/api/images";
|
||||
|
||||
export const imagesApi = {
|
||||
list: (agentId?: number) => api.get<ImageRow[]>(base(agentId)).then((r) => r.data),
|
||||
updates: (agentId?: number) =>
|
||||
api.get<Record<string, UpdateStatus>>(`${base(agentId)}/updates`).then((r) => r.data),
|
||||
check: (agentId?: number) =>
|
||||
api.post<Record<string, UpdateStatus>>(`${base(agentId)}/check`).then((r) => r.data),
|
||||
prune: (allUnused: boolean, agentId?: number) =>
|
||||
list: () => api.get<ImageRow[]>(base).then((r) => r.data),
|
||||
updates: () => api.get<Record<string, UpdateStatus>>(`${base}/updates`).then((r) => r.data),
|
||||
check: () => api.post<Record<string, UpdateStatus>>(`${base}/check`).then((r) => r.data),
|
||||
prune: (allUnused: boolean) =>
|
||||
api
|
||||
.post<{ ImagesDeleted: unknown[]; SpaceReclaimed: number }>(
|
||||
`${base(agentId)}/prune`,
|
||||
null,
|
||||
{ params: { all: allUnused } }
|
||||
)
|
||||
.post<{ ImagesDeleted: unknown[]; SpaceReclaimed: number }>(`${base}/prune`, null, {
|
||||
params: { all: allUnused },
|
||||
})
|
||||
.then((r) => r.data),
|
||||
};
|
||||
|
||||
@@ -34,25 +34,19 @@ export interface NetworkContainer {
|
||||
connected: boolean;
|
||||
}
|
||||
|
||||
// Base path for the local host or, when agentId is given, a remote agent.
|
||||
const base = (agentId?: number) =>
|
||||
agentId != null ? `/api/agents/${agentId}/networks` : "/api/networks";
|
||||
const base = "/api/networks";
|
||||
|
||||
export const networksApi = {
|
||||
list: (agentId?: number) =>
|
||||
api.get<NetworkInfo[]>(base(agentId)).then((r) => r.data),
|
||||
inspect: (id: string, agentId?: number) =>
|
||||
api.get<NetworkInfo>(`${base(agentId)}/${id}`).then((r) => r.data),
|
||||
containers: (id: string, agentId?: number) =>
|
||||
api.get<NetworkContainer[]>(`${base(agentId)}/${id}/containers`).then((r) => r.data),
|
||||
create: (body: NetworkCreate, agentId?: number) =>
|
||||
api.post<NetworkInfo>(base(agentId), body).then((r) => r.data),
|
||||
connect: (id: string, container: string, aliases?: string[], agentId?: number) =>
|
||||
api.post(`${base(agentId)}/${id}/connect`, { container, aliases }).then((r) => r.data),
|
||||
disconnect: (id: string, container: string, force = false, agentId?: number) =>
|
||||
api.post(`${base(agentId)}/${id}/disconnect`, { container, force }).then((r) => r.data),
|
||||
remove: (id: string, agentId?: number) =>
|
||||
api.delete(`${base(agentId)}/${id}`).then((r) => r.data),
|
||||
prune: (agentId?: number) =>
|
||||
api.post<{ NetworksDeleted: string[] | null }>(`${base(agentId)}/prune`).then((r) => r.data),
|
||||
list: () => api.get<NetworkInfo[]>(base).then((r) => r.data),
|
||||
inspect: (id: string) => api.get<NetworkInfo>(`${base}/${id}`).then((r) => r.data),
|
||||
containers: (id: string) =>
|
||||
api.get<NetworkContainer[]>(`${base}/${id}/containers`).then((r) => r.data),
|
||||
create: (body: NetworkCreate) => api.post<NetworkInfo>(base, body).then((r) => r.data),
|
||||
connect: (id: string, container: string, aliases?: string[]) =>
|
||||
api.post(`${base}/${id}/connect`, { container, aliases }).then((r) => r.data),
|
||||
disconnect: (id: string, container: string, force = false) =>
|
||||
api.post(`${base}/${id}/disconnect`, { container, force }).then((r) => r.data),
|
||||
remove: (id: string) => api.delete(`${base}/${id}`).then((r) => r.data),
|
||||
prune: () =>
|
||||
api.post<{ NetworksDeleted: string[] | null }>(`${base}/prune`).then((r) => r.data),
|
||||
};
|
||||
|
||||
@@ -5,8 +5,6 @@ export interface BackupSchedule {
|
||||
stack_id: string;
|
||||
destination_id: number;
|
||||
destination_name: string | null;
|
||||
agent_id: number | null;
|
||||
agent_name: string | null;
|
||||
frequency: "hourly" | "daily" | "weekly";
|
||||
hour: number;
|
||||
minute: number;
|
||||
@@ -24,7 +22,6 @@ export interface BackupSchedule {
|
||||
export interface ScheduleInput {
|
||||
stack_id: string;
|
||||
destination_id: number;
|
||||
agent_id?: number | null;
|
||||
frequency: string;
|
||||
hour: number;
|
||||
minute: number;
|
||||
|
||||
@@ -9,30 +9,18 @@ export interface SecretEntry {
|
||||
modified: number;
|
||||
}
|
||||
|
||||
// Local host, or a remote agent's stack when agentId is given.
|
||||
const base = (stackId: string, agentId?: number) =>
|
||||
agentId != null
|
||||
? `/api/agents/${agentId}/stacks/${stackId}/secrets`
|
||||
: `/api/stacks/${stackId}/secrets`;
|
||||
const base = (stackId: string) => `/api/stacks/${stackId}/secrets`;
|
||||
|
||||
export const secretsApi = {
|
||||
list: (stackId: string, agentId?: number) =>
|
||||
api.get<SecretEntry[]>(base(stackId, agentId)).then((r) => r.data),
|
||||
write: (
|
||||
stackId: string,
|
||||
body: { kind: SecretKind; name: string; content: string },
|
||||
agentId?: number,
|
||||
) => api.put(base(stackId, agentId), body).then((r) => r.data),
|
||||
remove: (stackId: string, kind: SecretKind, name: string, agentId?: number) =>
|
||||
api.delete(`${base(stackId, agentId)}/${kind}/${name}`).then((r) => r.data),
|
||||
list: (stackId: string) => api.get<SecretEntry[]>(base(stackId)).then((r) => r.data),
|
||||
write: (stackId: string, body: { kind: SecretKind; name: string; content: string }) =>
|
||||
api.put(base(stackId), body).then((r) => r.data),
|
||||
remove: (stackId: string, kind: SecretKind, name: string) =>
|
||||
api.delete(`${base(stackId)}/${kind}/${name}`).then((r) => r.data),
|
||||
attach: (
|
||||
stackId: string,
|
||||
body: { kind: SecretKind; name: string; service: string; target?: string },
|
||||
agentId?: number,
|
||||
) => api.post(`${base(stackId, agentId)}/attach`, body).then((r) => r.data),
|
||||
detach: (
|
||||
stackId: string,
|
||||
body: { kind: SecretKind; name: string; service: string },
|
||||
agentId?: number,
|
||||
) => api.post(`${base(stackId, agentId)}/detach`, body).then((r) => r.data),
|
||||
) => api.post(`${base(stackId)}/attach`, body).then((r) => r.data),
|
||||
detach: (stackId: string, body: { kind: SecretKind; name: string; service: string }) =>
|
||||
api.post(`${base(stackId)}/detach`, body).then((r) => r.data),
|
||||
};
|
||||
|
||||
@@ -19,12 +19,9 @@ export const templatesApi = {
|
||||
list: () => api.get<TemplateSummary[]>("/api/templates").then((r) => r.data),
|
||||
get: (id: string) =>
|
||||
api.get<TemplateDetail>(`/api/templates/${id}`).then((r) => r.data),
|
||||
instantiate: (id: string, name: string, agentId?: number | null) =>
|
||||
instantiate: (id: string, name: string) =>
|
||||
api
|
||||
.post<{ id: string; name: string; agent_id: number | null }>(
|
||||
`/api/templates/${id}/instantiate`,
|
||||
{ name, agent_id: agentId ?? null }
|
||||
)
|
||||
.post<{ id: string; name: string }>(`/api/templates/${id}/instantiate`, { name })
|
||||
.then((r) => r.data),
|
||||
save: (body: {
|
||||
name: string;
|
||||
|
||||
@@ -1,21 +1,18 @@
|
||||
import api from "./client";
|
||||
import type { HostPathResult, VolumeInfo } from "@/types";
|
||||
|
||||
// Base path for the local host or, when agentId is given, a remote agent.
|
||||
const base = (agentId?: number) =>
|
||||
agentId != null ? `/api/agents/${agentId}/volumes` : "/api/volumes";
|
||||
const base = "/api/volumes";
|
||||
|
||||
export const volumesApi = {
|
||||
list: (agentId?: number) =>
|
||||
api.get<VolumeInfo[]>(base(agentId)).then((r) => r.data),
|
||||
sizes: (force = false, agentId?: number) =>
|
||||
list: () => api.get<VolumeInfo[]>(base).then((r) => r.data),
|
||||
sizes: (force = false) =>
|
||||
api
|
||||
.get<Record<string, number | null>>(`${base(agentId)}/sizes`, { params: { force } })
|
||||
.get<Record<string, number | null>>(`${base}/sizes`, { params: { force } })
|
||||
.then((r) => r.data),
|
||||
remove: (name: string, force = false, agentId?: number) =>
|
||||
api.delete(`${base(agentId)}/${name}?force=${force}`).then((r) => r.data),
|
||||
prune: (agentId?: number) =>
|
||||
api.post<{ VolumesDeleted: string[] | null }>(`${base(agentId)}/prune`).then((r) => r.data),
|
||||
remove: (name: string, force = false) =>
|
||||
api.delete(`${base}/${name}?force=${force}`).then((r) => r.data),
|
||||
prune: () =>
|
||||
api.post<{ VolumesDeleted: string[] | null }>(`${base}/prune`).then((r) => r.data),
|
||||
generateYaml: (spec: Record<string, unknown>) =>
|
||||
api
|
||||
.post<{ yaml: string }>("/api/volumes/generate-yaml", spec)
|
||||
|
||||
@@ -3,7 +3,6 @@ import {
|
||||
AlertTriangle,
|
||||
AlertCircle,
|
||||
CheckCircle2,
|
||||
ServerOff,
|
||||
HeartPulse,
|
||||
ArrowUpCircle,
|
||||
HardDrive,
|
||||
@@ -15,7 +14,6 @@ import type { AttentionItem } from "@/api/dashboard";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const KIND_ICON: Record<string, React.ComponentType<{ className?: string }>> = {
|
||||
agent_offline: ServerOff,
|
||||
unhealthy: HeartPulse,
|
||||
stack_error: AlertTriangle,
|
||||
stack_partial: AlertCircle,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Link } from "react-router-dom";
|
||||
import { Server, Boxes, Container, HeartPulse, ArrowUpCircle, Archive } from "lucide-react";
|
||||
import { Boxes, Container, HeartPulse, ArrowUpCircle, Archive } from "lucide-react";
|
||||
import type { FleetKpis } from "@/api/dashboard";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
@@ -47,14 +47,7 @@ function Kpi({
|
||||
|
||||
export function FleetKpiRow({ kpis }: { kpis: FleetKpis }) {
|
||||
return (
|
||||
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-6">
|
||||
<Kpi
|
||||
icon={<Server />}
|
||||
label="Hosts"
|
||||
value={`${kpis.hosts_online}/${kpis.hosts_total}`}
|
||||
sub="online"
|
||||
tone={kpis.hosts_online < kpis.hosts_total ? "error" : "default"}
|
||||
/>
|
||||
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-5">
|
||||
<Kpi
|
||||
icon={<Boxes />}
|
||||
label="Stacks"
|
||||
|
||||
@@ -32,7 +32,7 @@ export function HostResourceTable({ hosts }: { hosts: FleetHost[] }) {
|
||||
return (
|
||||
<div className="sp-card overflow-hidden p-0">
|
||||
<div className="border-b border-sp-border px-4 py-2.5">
|
||||
<h2 className="sp-label">Hosts</h2>
|
||||
<h2 className="sp-label">Host resources</h2>
|
||||
</div>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const color: Record<string, string> = {
|
||||
online: "bg-green-500",
|
||||
offline: "bg-red-500",
|
||||
unauthorized: "bg-amber-500",
|
||||
unknown: "bg-slate-400",
|
||||
};
|
||||
|
||||
export function HostDot({ status }: { status: string }) {
|
||||
return (
|
||||
<span
|
||||
className={cn("inline-block h-2.5 w-2.5 rounded-full", color[status] ?? color.unknown)}
|
||||
title={status}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { HardDrive, Server } from "lucide-react";
|
||||
import { HostDot } from "@/components/hosts/HostDot";
|
||||
import type { Agent } from "@/types";
|
||||
|
||||
/**
|
||||
* Section header for a host (local or a remote agent). `children` is rendered
|
||||
* on the right for per-host action buttons.
|
||||
*/
|
||||
export function HostHeader({
|
||||
agent,
|
||||
children,
|
||||
}: {
|
||||
agent?: Agent;
|
||||
children?: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div className="mb-3 flex flex-wrap items-center justify-between gap-2">
|
||||
<h2 className="flex items-center gap-2 text-sm font-semibold uppercase tracking-wide text-slate-500">
|
||||
{agent ? <Server className="h-4 w-4" /> : <HardDrive className="h-4 w-4" />}
|
||||
{agent ? agent.name : "This host"}
|
||||
{agent && <HostDot status={agent.status} />}
|
||||
{agent?.hostname && (
|
||||
<span className="font-mono text-xs normal-case text-slate-400">{agent.hostname}</span>
|
||||
)}
|
||||
</h2>
|
||||
<div className="flex flex-wrap gap-2">{children}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { NavLink, useNavigate } from "react-router-dom";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import {
|
||||
LayoutDashboard,
|
||||
Boxes,
|
||||
@@ -21,7 +20,6 @@ import {
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useAuthStore } from "@/store/auth";
|
||||
import { useThemeStore } from "@/store/theme";
|
||||
import { agentsApi } from "@/api/agents";
|
||||
import { VersionBadge } from "./VersionBadge";
|
||||
|
||||
type NavItem = {
|
||||
@@ -91,14 +89,6 @@ export function TopNav() {
|
||||
const signOutEverywhere = useAuthStore((s) => s.signOutEverywhere);
|
||||
const { theme, toggle } = useThemeStore();
|
||||
|
||||
const agents = useQuery({
|
||||
queryKey: ["agents"],
|
||||
queryFn: () => agentsApi.list(),
|
||||
refetchInterval: 30000,
|
||||
});
|
||||
const agentCount = agents.data?.length ?? 0;
|
||||
const agentsOnline = agents.data?.filter((a) => a.status === "online").length ?? 0;
|
||||
|
||||
// Close avatar menu on outside click.
|
||||
useEffect(() => {
|
||||
if (!menuOpen) return;
|
||||
@@ -159,21 +149,6 @@ export function TopNav() {
|
||||
{/* Right cluster */}
|
||||
<div className="ml-auto flex shrink-0 items-center gap-2 lg:ml-0">
|
||||
<VersionBadge />
|
||||
{agentCount > 0 && (
|
||||
<button
|
||||
onClick={() => navigate("/settings")}
|
||||
className="hidden items-center gap-1.5 rounded-pill border border-sp-border bg-sp-surface px-2.5 py-1 text-xs font-medium text-sp-text-2 hover:text-sp-text-1 sm:flex"
|
||||
title={`${agentsOnline}/${agentCount} remote hosts online`}
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
"h-2 w-2 rounded-full",
|
||||
agentsOnline === agentCount ? "bg-sp-green" : "bg-sp-amber"
|
||||
)}
|
||||
/>
|
||||
{agentsOnline}/{agentCount}
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
onClick={toggle}
|
||||
className="rounded-pill border border-sp-border bg-sp-surface p-2 text-sp-text-2 hover:text-sp-text-1"
|
||||
|
||||
@@ -1,98 +0,0 @@
|
||||
import { useState } from "react";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { Server } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import { Card } from "@/components/ui";
|
||||
import { StacksTable } from "@/components/stacks/StacksTable";
|
||||
import { RestoreButton } from "@/components/stacks/BackupRestore";
|
||||
import { HostDot } from "@/components/hosts/HostDot";
|
||||
import { agentsApi } from "@/api/agents";
|
||||
import { apiErrorMessage } from "@/api/client";
|
||||
import type { Agent } from "@/types";
|
||||
|
||||
export function AgentStacksSection({ agent, isAdmin }: { agent: Agent; isAdmin: boolean }) {
|
||||
const qc = useQueryClient();
|
||||
const [busyId, setBusyId] = useState<string | null>(null);
|
||||
const online = agent.status === "online";
|
||||
|
||||
const stacks = useQuery({
|
||||
queryKey: ["agent-stacks", agent.id],
|
||||
queryFn: () => agentsApi.stacks(agent.id),
|
||||
enabled: online,
|
||||
refetchInterval: 8000,
|
||||
});
|
||||
const stats = useQuery({
|
||||
queryKey: ["agent-stack-stats", agent.id],
|
||||
queryFn: () => agentsApi.stackStats(agent.id),
|
||||
enabled: online,
|
||||
refetchInterval: 5000,
|
||||
});
|
||||
const sys = useQuery({
|
||||
queryKey: ["agent-system", agent.id],
|
||||
queryFn: () => agentsApi.system(agent.id),
|
||||
enabled: online,
|
||||
refetchInterval: 30000,
|
||||
});
|
||||
const updates = useQuery({
|
||||
queryKey: ["agent-stack-updates", agent.id],
|
||||
queryFn: () => agentsApi.stackUpdates(agent.id),
|
||||
enabled: online,
|
||||
refetchInterval: 60000,
|
||||
});
|
||||
|
||||
const run = async (action: string, label: string, id: string) => {
|
||||
setBusyId(id);
|
||||
const t = toast.loading(`${label} ${id} on ${agent.name}…`);
|
||||
try {
|
||||
await agentsApi.action(agent.id, id, action);
|
||||
toast.success(`${label} ${id} ✓`, { id: t });
|
||||
qc.invalidateQueries({ queryKey: ["agent-stacks", agent.id] });
|
||||
qc.invalidateQueries({ queryKey: ["agent-stack-updates", agent.id] });
|
||||
} catch (e) {
|
||||
toast.error(apiErrorMessage(e), { id: t });
|
||||
} finally {
|
||||
setBusyId(null);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<section>
|
||||
<div className="mb-3 flex items-center justify-between gap-2">
|
||||
<h2 className="flex items-center gap-2 text-sm font-semibold uppercase tracking-wide text-slate-500">
|
||||
<Server className="h-4 w-4" />
|
||||
{agent.name}
|
||||
<HostDot status={agent.status} />
|
||||
{agent.hostname && (
|
||||
<span className="font-mono text-xs normal-case text-slate-400">{agent.hostname}</span>
|
||||
)}
|
||||
</h2>
|
||||
{isAdmin && online && <RestoreButton agentId={agent.id} />}
|
||||
</div>
|
||||
|
||||
{!online ? (
|
||||
<Card>
|
||||
<p className="text-sm text-slate-500">
|
||||
Host is {agent.status}. Check it under Settings → Remote hosts.
|
||||
</p>
|
||||
</Card>
|
||||
) : (
|
||||
<StacksTable
|
||||
stacks={stacks.data}
|
||||
stats={stats.data}
|
||||
updates={updates.data}
|
||||
hostCpus={sys.data?.cpu_cores ?? 0}
|
||||
hostMem={sys.data?.mem_total ?? 0}
|
||||
isAdmin={isAdmin}
|
||||
isBusy={(id) => busyId === id}
|
||||
loading={stacks.isLoading}
|
||||
linkBase={`/hosts/${agent.id}/stacks`}
|
||||
onStart={(id) => run("start", "Starting", id)}
|
||||
onStop={(id) => run("stop", "Stopping", id)}
|
||||
onRestart={(id) => run("restart", "Restarting", id)}
|
||||
onUpdate={isAdmin ? (id) => run("update", "Updating", id) : undefined}
|
||||
emptyText="No stacks on this host."
|
||||
/>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -14,36 +14,34 @@ const STATUS_TONE: Record<string, string> = {
|
||||
};
|
||||
|
||||
/**
|
||||
* Watchtower-style auto-update control for one stack (local or, with agentId,
|
||||
* a remote agent's stack). When a newer image digest is found by the background
|
||||
* Watchtower-style auto-update control for one stack. When a newer image
|
||||
* digest is found by the background
|
||||
* check, the stack is pulled + redeployed or merely flagged, per the policy.
|
||||
*/
|
||||
export function AutoUpdatePanel({
|
||||
stackId,
|
||||
agentId,
|
||||
isAdmin,
|
||||
}: {
|
||||
stackId: string;
|
||||
agentId?: number;
|
||||
isAdmin: boolean;
|
||||
}) {
|
||||
const qc = useQueryClient();
|
||||
const key = ["auto-update", agentId ?? "local", stackId];
|
||||
const key = ["auto-update", stackId];
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey: key,
|
||||
queryFn: () => autoUpdateApi.get(stackId, agentId),
|
||||
queryFn: () => autoUpdateApi.get(stackId),
|
||||
});
|
||||
|
||||
const save = useMutation({
|
||||
mutationFn: (body: { enabled: boolean; redeploy: boolean }) =>
|
||||
autoUpdateApi.set(stackId, body, agentId),
|
||||
autoUpdateApi.set(stackId, body),
|
||||
onSuccess: (p) => qc.setQueryData(key, p),
|
||||
onError: (e) => toast.error(apiErrorMessage(e)),
|
||||
});
|
||||
|
||||
const runNow = useMutation({
|
||||
mutationFn: () => autoUpdateApi.run(stackId, agentId),
|
||||
mutationFn: () => autoUpdateApi.run(stackId),
|
||||
onSuccess: (p) => {
|
||||
qc.setQueryData(key, p);
|
||||
toast.success(`Auto-update: ${p.last_status ?? "done"}`);
|
||||
@@ -84,7 +82,7 @@ export function AutoUpdatePanel({
|
||||
<label className="flex cursor-pointer items-center gap-2">
|
||||
<input
|
||||
type="radio"
|
||||
name={`mode-${agentId ?? "l"}-${stackId}`}
|
||||
name={`mode-${stackId}`}
|
||||
checked={p.redeploy}
|
||||
onChange={() => save.mutate({ enabled: true, redeploy: true })}
|
||||
/>
|
||||
@@ -93,7 +91,7 @@ export function AutoUpdatePanel({
|
||||
<label className="flex cursor-pointer items-center gap-2">
|
||||
<input
|
||||
type="radio"
|
||||
name={`mode-${agentId ?? "l"}-${stackId}`}
|
||||
name={`mode-${stackId}`}
|
||||
checked={!p.redeploy}
|
||||
onChange={() => save.mutate({ enabled: true, redeploy: false })}
|
||||
/>
|
||||
|
||||
@@ -5,7 +5,6 @@ import { toast } from "sonner";
|
||||
import { Button } from "@/components/ui";
|
||||
import { backupsApi, destinationsApi } from "@/api/backups";
|
||||
import type { BackupReport } from "@/api/backups";
|
||||
import { agentsApi } from "@/api/agents";
|
||||
import { apiErrorMessage } from "@/api/client";
|
||||
import { formatBytes } from "@/lib/utils";
|
||||
|
||||
@@ -117,13 +116,7 @@ function AssetRow({
|
||||
);
|
||||
}
|
||||
|
||||
export function BackupButton({
|
||||
stackId,
|
||||
agentId,
|
||||
}: {
|
||||
stackId: string;
|
||||
agentId?: number;
|
||||
}) {
|
||||
export function BackupButton({ stackId }: { stackId: string }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [stopFirst, setStopFirst] = useState(true);
|
||||
const [target, setTarget] = useState("download"); // "download" | destination id
|
||||
@@ -138,11 +131,8 @@ export function BackupButton({
|
||||
enabled: open,
|
||||
});
|
||||
const inventory = useQuery({
|
||||
queryKey: ["backup-inventory", agentId ?? "local", stackId],
|
||||
queryFn: () =>
|
||||
agentId != null
|
||||
? agentsApi.backupInventory(agentId, stackId)
|
||||
: backupsApi.inventory(stackId),
|
||||
queryKey: ["backup-inventory", stackId],
|
||||
queryFn: () => backupsApi.inventory(stackId),
|
||||
enabled: open,
|
||||
});
|
||||
|
||||
@@ -175,10 +165,7 @@ export function BackupButton({
|
||||
volumes: volSel.length ? volSel : undefined,
|
||||
};
|
||||
if (target === "download") {
|
||||
const report =
|
||||
agentId != null
|
||||
? await agentsApi.backupDownload(agentId, stackId, opts)
|
||||
: await backupsApi.download(stackId, opts);
|
||||
const report = await backupsApi.download(stackId, opts);
|
||||
toast.success(describe(report), { id: tid });
|
||||
} else {
|
||||
const body = {
|
||||
@@ -189,10 +176,7 @@ export function BackupButton({
|
||||
binds: opts.binds,
|
||||
volumes: opts.volumes,
|
||||
};
|
||||
const res =
|
||||
agentId != null
|
||||
? await agentsApi.backupPush(agentId, stackId, body)
|
||||
: await backupsApi.push(stackId, body);
|
||||
const res = await backupsApi.push(stackId, body);
|
||||
toast.success(`Pushed to ${res.destination}`, { id: tid });
|
||||
}
|
||||
setOpen(false);
|
||||
@@ -310,7 +294,7 @@ export function BackupButton({
|
||||
);
|
||||
}
|
||||
|
||||
export function RestoreButton({ agentId }: { agentId?: number }) {
|
||||
export function RestoreButton() {
|
||||
const qc = useQueryClient();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [mode, setMode] = useState<"upload" | "destination">("upload");
|
||||
@@ -351,10 +335,7 @@ export function RestoreButton({ agentId }: { agentId?: number }) {
|
||||
restoreVolumes,
|
||||
restoreBinds,
|
||||
};
|
||||
res =
|
||||
agentId != null
|
||||
? await agentsApi.restoreUpload(agentId, file, opts)
|
||||
: await backupsApi.restore(file, opts);
|
||||
res = await backupsApi.restore(file, opts);
|
||||
} else {
|
||||
if (!destId || !remoteName) {
|
||||
toast.error("Pick a destination and a backup", { id: tid });
|
||||
@@ -369,15 +350,12 @@ export function RestoreButton({ agentId }: { agentId?: number }) {
|
||||
restore_volumes: restoreVolumes,
|
||||
restore_binds: restoreBinds,
|
||||
};
|
||||
res =
|
||||
agentId != null
|
||||
? await agentsApi.restoreFrom(agentId, body)
|
||||
: await backupsApi.restoreFrom(body);
|
||||
res = await backupsApi.restoreFrom(body);
|
||||
}
|
||||
const bits = [`${res.volumes_restored} volume(s)`];
|
||||
if (res.binds_restored) bits.push(`${res.binds_restored} folder(s)`);
|
||||
toast.success(`Restored '${res.stack_id}' — ${bits.join(", ")}`, { id: tid });
|
||||
qc.invalidateQueries({ queryKey: agentId != null ? ["agent-stacks", agentId] : ["stacks"] });
|
||||
qc.invalidateQueries({ queryKey: ["stacks"] });
|
||||
setOpen(false);
|
||||
setFile(null);
|
||||
setTargetId("");
|
||||
|
||||
@@ -11,13 +11,11 @@ import type { ContainerInfo } from "@/types";
|
||||
|
||||
export function ContainerCard({
|
||||
container,
|
||||
agentId,
|
||||
host,
|
||||
isAdmin,
|
||||
onChanged,
|
||||
}: {
|
||||
container: ContainerInfo;
|
||||
agentId?: number;
|
||||
host?: string;
|
||||
isAdmin: boolean;
|
||||
onChanged?: () => void;
|
||||
@@ -28,8 +26,8 @@ export function ContainerCard({
|
||||
const running = container.state === "running";
|
||||
|
||||
const detail = useQuery({
|
||||
queryKey: ["container", agentId ?? "local", container.id],
|
||||
queryFn: () => containersApi.inspect(container.id, agentId),
|
||||
queryKey: ["container", container.id],
|
||||
queryFn: () => containersApi.inspect(container.id),
|
||||
enabled: open,
|
||||
});
|
||||
|
||||
@@ -37,7 +35,7 @@ export function ContainerCard({
|
||||
setBusy(true);
|
||||
const t = toast.loading(`${action} ${container.service}…`);
|
||||
try {
|
||||
await containersApi.action(container.id, action, agentId);
|
||||
await containersApi.action(container.id, action);
|
||||
toast.success(`${container.service}: ${action} ok`, { id: t });
|
||||
onChanged?.();
|
||||
if (open) detail.refetch();
|
||||
@@ -153,7 +151,6 @@ export function ContainerCard({
|
||||
<ContainerTerminal
|
||||
containerId={container.id}
|
||||
service={container.service}
|
||||
agentId={agentId}
|
||||
onClose={() => setTermOpen(false)}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -8,7 +8,7 @@ export type ContainerPort = {
|
||||
|
||||
const WILDCARD_IPS = new Set(["", "0.0.0.0", "::"]);
|
||||
|
||||
/** Pick the host to link to: an explicit override (remote agent), the bound
|
||||
/** Pick the host to link to: an explicit override, the bound
|
||||
* host IP if it's a concrete address, otherwise the host we're viewing from. */
|
||||
function linkHost(hostIp: string | undefined, override?: string): string {
|
||||
if (override) return override;
|
||||
@@ -25,7 +25,7 @@ function scheme(hostPort: string, container: string): "http" | "https" {
|
||||
}
|
||||
|
||||
/** Clickable chips for a container's published ports. `host` overrides the
|
||||
* link target (used for remote agent stacks). Renders nothing if unpublished. */
|
||||
* link target. Renders nothing if unpublished. */
|
||||
export function ContainerPorts({
|
||||
ports,
|
||||
host,
|
||||
|
||||
@@ -12,19 +12,17 @@ const SHELLS = ["/bin/sh", "/bin/bash", "/bin/ash"];
|
||||
|
||||
/**
|
||||
* Interactive terminal modal: opens an exec session into a compose-managed
|
||||
* container over `/ws/exec/{id}` (or `/ws/agent-exec/{aid}/{id}` for a remote
|
||||
* agent) and wires it to an xterm.js terminal. Admin-only on the backend; a
|
||||
* container over `/ws/exec/{id}` and wires it to an xterm.js terminal.
|
||||
* Admin-only on the backend; a
|
||||
* 4403 close surfaces as an "admin only" error.
|
||||
*/
|
||||
export function ContainerTerminal({
|
||||
containerId,
|
||||
service,
|
||||
agentId,
|
||||
onClose,
|
||||
}: {
|
||||
containerId: string;
|
||||
service: string;
|
||||
agentId?: number;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const token = useAuthStore((s) => s.accessToken);
|
||||
@@ -50,12 +48,8 @@ export function ContainerTerminal({
|
||||
fit.fit();
|
||||
|
||||
const proto = window.location.protocol === "https:" ? "wss" : "ws";
|
||||
const path =
|
||||
agentId != null
|
||||
? `/ws/agent-exec/${agentId}/${containerId}`
|
||||
: `/ws/exec/${containerId}`;
|
||||
const url =
|
||||
`${proto}://${window.location.host}${path}` +
|
||||
`${proto}://${window.location.host}/ws/exec/${containerId}` +
|
||||
`?token=${encodeURIComponent(token)}&cmd=${encodeURIComponent(shell)}`;
|
||||
const ws = new WebSocket(url);
|
||||
|
||||
@@ -120,7 +114,7 @@ export function ContainerTerminal({
|
||||
ws.close();
|
||||
term.dispose();
|
||||
};
|
||||
}, [containerId, agentId, shell, token]);
|
||||
}, [containerId, shell, token]);
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
|
||||
|
||||
@@ -29,11 +29,9 @@ const EMPTY_STATS: DeployStats = {
|
||||
*/
|
||||
export function DeployConsole({
|
||||
stackId,
|
||||
agentId,
|
||||
onClose,
|
||||
}: {
|
||||
stackId: string;
|
||||
agentId?: number;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const [lines, setLines] = useState<LogLine[]>([]);
|
||||
@@ -89,11 +87,7 @@ export function DeployConsole({
|
||||
};
|
||||
|
||||
const proto = window.location.protocol === "https:" ? "wss" : "ws";
|
||||
const path =
|
||||
agentId != null
|
||||
? `/ws/agent-deploy/${agentId}/${stackId}`
|
||||
: `/ws/deploy/${stackId}`;
|
||||
const url = `${proto}://${window.location.host}${path}?token=${token}`;
|
||||
const url = `${proto}://${window.location.host}/ws/deploy/${stackId}?token=${token}`;
|
||||
const ws = new WebSocket(url);
|
||||
ws.onmessage = (ev) => {
|
||||
try {
|
||||
@@ -136,7 +130,7 @@ export function DeployConsole({
|
||||
window.clearInterval(timer);
|
||||
ws.close();
|
||||
};
|
||||
}, [stackId, agentId, token, tracker]);
|
||||
}, [stackId, token, tracker]);
|
||||
|
||||
useEffect(() => {
|
||||
if (boxRef.current) boxRef.current.scrollTop = boxRef.current.scrollHeight;
|
||||
|
||||
@@ -87,7 +87,7 @@ type LogLine = {
|
||||
level: Level;
|
||||
};
|
||||
|
||||
export function LogViewer({ stackId, agentId }: { stackId: string; agentId?: number }) {
|
||||
export function LogViewer({ stackId }: { stackId: string }) {
|
||||
const [lines, setLines] = useState<LogLine[]>([]);
|
||||
const [autoScroll, setAutoScroll] = useState(true);
|
||||
const [connected, setConnected] = useState(false);
|
||||
@@ -102,18 +102,14 @@ export function LogViewer({ stackId, agentId }: { stackId: string; agentId?: num
|
||||
setError(null);
|
||||
let gotError = false;
|
||||
const proto = window.location.protocol === "https:" ? "wss" : "ws";
|
||||
const path =
|
||||
agentId != null
|
||||
? `/ws/agent-logs/${agentId}/${stackId}`
|
||||
: `/ws/logs/${stackId}`;
|
||||
const url = `${proto}://${window.location.host}${path}?token=${token}`;
|
||||
const url = `${proto}://${window.location.host}/ws/logs/${stackId}?token=${token}`;
|
||||
const ws = new WebSocket(url);
|
||||
ws.onopen = () => setConnected(true);
|
||||
ws.onclose = (ev) => {
|
||||
setConnected(false);
|
||||
// Auth rejection from the proxy/agent (JWT or agent token) closes 4401.
|
||||
// An expired or revoked session closes 4401.
|
||||
if (!gotError && ev.code === 4401) {
|
||||
setError("Not authorized to stream logs (session or agent token).");
|
||||
setError("Not authorized to stream logs — sign in again.");
|
||||
}
|
||||
};
|
||||
ws.onmessage = (ev) => {
|
||||
@@ -137,7 +133,7 @@ export function LogViewer({ stackId, agentId }: { stackId: string; agentId?: num
|
||||
}
|
||||
};
|
||||
return () => ws.close();
|
||||
}, [stackId, agentId, token]);
|
||||
}, [stackId, token]);
|
||||
|
||||
// Unique services seen so far, for the container filter.
|
||||
const services = useMemo(() => {
|
||||
|
||||
@@ -15,26 +15,24 @@ import { apiErrorMessage } from "@/api/client";
|
||||
export function SecretsPanel({
|
||||
stackId,
|
||||
yaml,
|
||||
agentId,
|
||||
isAdmin,
|
||||
onChanged,
|
||||
}: {
|
||||
stackId: string;
|
||||
yaml: string;
|
||||
agentId?: number;
|
||||
isAdmin: boolean;
|
||||
onChanged?: () => void;
|
||||
}) {
|
||||
const qc = useQueryClient();
|
||||
const key = ["secrets", agentId ?? "local", stackId];
|
||||
const key = ["secrets", stackId];
|
||||
|
||||
const list = useQuery({
|
||||
queryKey: key,
|
||||
queryFn: () => secretsApi.list(stackId, agentId),
|
||||
queryFn: () => secretsApi.list(stackId),
|
||||
enabled: isAdmin,
|
||||
});
|
||||
const services = useQuery({
|
||||
queryKey: ["editor-services", stackId, agentId, yaml.length],
|
||||
queryKey: ["editor-services", stackId, yaml.length],
|
||||
queryFn: () => editorApi.services(yaml),
|
||||
enabled: isAdmin,
|
||||
});
|
||||
@@ -46,7 +44,7 @@ export function SecretsPanel({
|
||||
const invalidate = () => qc.invalidateQueries({ queryKey: key });
|
||||
|
||||
const create = useMutation({
|
||||
mutationFn: () => secretsApi.write(stackId, { kind, name: name.trim(), content }, agentId),
|
||||
mutationFn: () => secretsApi.write(stackId, { kind, name: name.trim(), content }),
|
||||
onSuccess: () => {
|
||||
toast.success(`${kind} "${name}" saved`);
|
||||
setName(""); setContent("");
|
||||
@@ -56,21 +54,21 @@ export function SecretsPanel({
|
||||
});
|
||||
|
||||
const remove = useMutation({
|
||||
mutationFn: (s: SecretEntry) => secretsApi.remove(stackId, s.kind, s.name, agentId),
|
||||
mutationFn: (s: SecretEntry) => secretsApi.remove(stackId, s.kind, s.name),
|
||||
onSuccess: () => { toast.success("Deleted"); invalidate(); },
|
||||
onError: (e) => toast.error(apiErrorMessage(e)),
|
||||
});
|
||||
|
||||
const attach = useMutation({
|
||||
mutationFn: (v: { s: SecretEntry; service: string; target?: string }) =>
|
||||
secretsApi.attach(stackId, { kind: v.s.kind, name: v.s.name, service: v.service, target: v.target }, agentId),
|
||||
secretsApi.attach(stackId, { kind: v.s.kind, name: v.s.name, service: v.service, target: v.target }),
|
||||
onSuccess: () => { toast.success("Attached — redeploy the stack to apply"); onChanged?.(); },
|
||||
onError: (e) => toast.error(apiErrorMessage(e)),
|
||||
});
|
||||
|
||||
const detach = useMutation({
|
||||
mutationFn: (v: { s: SecretEntry; service: string }) =>
|
||||
secretsApi.detach(stackId, { kind: v.s.kind, name: v.s.name, service: v.service }, agentId),
|
||||
secretsApi.detach(stackId, { kind: v.s.kind, name: v.s.name, service: v.service }),
|
||||
onSuccess: () => { toast.success("Detached — redeploy the stack to apply"); onChanged?.(); },
|
||||
onError: (e) => toast.error(apiErrorMessage(e)),
|
||||
});
|
||||
|
||||
@@ -25,7 +25,6 @@ export function StacksTable({
|
||||
statusFor,
|
||||
onDismissStatus,
|
||||
loading,
|
||||
linkBase = "/stacks",
|
||||
showEdit = false,
|
||||
showDelete = false,
|
||||
onStart,
|
||||
@@ -45,7 +44,6 @@ export function StacksTable({
|
||||
statusFor?: (id: string) => StackActionStatus | undefined;
|
||||
onDismissStatus?: (id: string) => void;
|
||||
loading: boolean;
|
||||
linkBase?: string;
|
||||
showEdit?: boolean;
|
||||
showDelete?: boolean;
|
||||
onStart: (id: string) => void;
|
||||
@@ -86,7 +84,6 @@ export function StacksTable({
|
||||
busy={isBusy(s.id)}
|
||||
status={statusFor?.(s.id)}
|
||||
onDismissStatus={onDismissStatus}
|
||||
linkBase={linkBase}
|
||||
showEdit={showEdit}
|
||||
showDelete={showDelete}
|
||||
onStart={onStart}
|
||||
@@ -111,7 +108,6 @@ function StackRow({
|
||||
busy,
|
||||
status,
|
||||
onDismissStatus,
|
||||
linkBase,
|
||||
showEdit,
|
||||
showDelete,
|
||||
onStart,
|
||||
@@ -128,7 +124,6 @@ function StackRow({
|
||||
busy: boolean;
|
||||
status?: StackActionStatus;
|
||||
onDismissStatus?: (id: string) => void;
|
||||
linkBase: string;
|
||||
showEdit: boolean;
|
||||
showDelete: boolean;
|
||||
onStart: (id: string) => void;
|
||||
@@ -139,7 +134,7 @@ function StackRow({
|
||||
const qc = useQueryClient();
|
||||
const running = stack.running_count > 0;
|
||||
const updateAvailable = update?.update_available ?? false;
|
||||
const canDelete = showDelete && !stack.agent_id;
|
||||
const canDelete = showDelete;
|
||||
const [confirming, setConfirming] = useState(false);
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
|
||||
@@ -165,7 +160,7 @@ function StackRow({
|
||||
to the CPU column, so the row never changes height. */}
|
||||
<div className="flex items-center gap-2">
|
||||
<Link
|
||||
to={`${linkBase}/${stack.id}`}
|
||||
to={`/stacks/${stack.id}`}
|
||||
className="flex shrink-0 items-center gap-2"
|
||||
>
|
||||
<StatusDot status={stack.status} />
|
||||
@@ -259,7 +254,7 @@ function StackRow({
|
||||
)}
|
||||
{showEdit && (
|
||||
<Link
|
||||
to={`${linkBase}/${stack.id}/edit`}
|
||||
to={`/stacks/${stack.id}/edit`}
|
||||
title="Edit"
|
||||
className="rounded-lg p-1.5 text-slate-500 hover:bg-slate-100 dark:hover:bg-slate-700"
|
||||
>
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
*
|
||||
* Compose is run with `--progress json` (compose ≥ 2.36), which emits one JSON
|
||||
* object per status change — including per-layer `current`/`total` bytes, so a
|
||||
* real percentage can be computed. Older compose (and older StackPilot agents)
|
||||
* real percentage can be computed. Older compose releases
|
||||
* emit the plain text form ` <id> <Status> <details>`; that is parsed too, but
|
||||
* without byte totals the bar falls back to layer/container counts.
|
||||
*/
|
||||
@@ -192,7 +192,7 @@ export type ImageRow = {
|
||||
pct: number;
|
||||
done: boolean;
|
||||
/** False when the stream carries no per-layer bytes for this image (old
|
||||
* compose / old agent): show the state instead of a misleading bar. */
|
||||
* compose): show the state instead of a misleading bar. */
|
||||
measured: boolean;
|
||||
error?: string;
|
||||
detail: string;
|
||||
|
||||
@@ -3,7 +3,6 @@ import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { AlertTriangle, Clock, RefreshCw } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import { Card } from "@/components/ui";
|
||||
import { HostHeader } from "@/components/hosts/HostHeader";
|
||||
import { StacksTable } from "@/components/stacks/StacksTable";
|
||||
import { AttentionStrip } from "@/components/dashboard/AttentionStrip";
|
||||
import { FleetKpiRow } from "@/components/dashboard/FleetKpiRow";
|
||||
@@ -11,13 +10,11 @@ import { StackStatusBar } from "@/components/dashboard/StackStatusBar";
|
||||
import { HostResourceTable } from "@/components/dashboard/HostResourceTable";
|
||||
import { stacksApi } from "@/api/stacks";
|
||||
import { systemApi } from "@/api/system";
|
||||
import { agentsApi } from "@/api/agents";
|
||||
import { dashboardApi } from "@/api/dashboard";
|
||||
import { apiErrorMessage } from "@/api/client";
|
||||
import { cn, relativeTime } from "@/lib/utils";
|
||||
import { useAuthStore } from "@/store/auth";
|
||||
import { useStackActions } from "@/hooks/useStackActions";
|
||||
import type { Agent } from "@/types";
|
||||
|
||||
export function Dashboard() {
|
||||
const isAdmin = useAuthStore((s) => s.user?.role === "admin");
|
||||
@@ -41,9 +38,7 @@ export function Dashboard() {
|
||||
refetchInterval: 10000,
|
||||
enabled: isAdmin,
|
||||
});
|
||||
const agents = useQuery({ queryKey: ["agents"], queryFn: () => agentsApi.list(), refetchInterval: 15000 });
|
||||
|
||||
const hasAgents = (agents.data?.length ?? 0) > 0;
|
||||
|
||||
const refreshFleet = async () => {
|
||||
setRefreshing(true);
|
||||
@@ -118,9 +113,9 @@ export function Dashboard() {
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* ---- Local host stacks ---- */}
|
||||
{/* ---- Stacks ---- */}
|
||||
<section>
|
||||
{hasAgents ? <HostHeader /> : <h2 className="sp-label mb-3">This host</h2>}
|
||||
<h2 className="sp-label mb-3">Stacks</h2>
|
||||
<StacksTable
|
||||
stacks={stacks.data}
|
||||
stats={stats.data}
|
||||
@@ -138,11 +133,6 @@ export function Dashboard() {
|
||||
/>
|
||||
</section>
|
||||
|
||||
{/* ---- Remote host stacks ---- */}
|
||||
{agents.data?.map((agent) => (
|
||||
<AgentDashboardSection key={agent.id} agent={agent} isAdmin={isAdmin} />
|
||||
))}
|
||||
|
||||
{/* ---- Recent activity (admin only, like the audit log itself) ---- */}
|
||||
{isAdmin && (
|
||||
<section>
|
||||
@@ -172,75 +162,3 @@ export function Dashboard() {
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------------- */
|
||||
/* Remote host stacks section */
|
||||
/* ---------------------------------------------------------------------- */
|
||||
|
||||
function AgentDashboardSection({ agent, isAdmin }: { agent: Agent; isAdmin: boolean }) {
|
||||
const qc = useQueryClient();
|
||||
const online = agent.status === "online";
|
||||
const [busyId, setBusyId] = useState<string | null>(null);
|
||||
|
||||
const stacks = useQuery({
|
||||
queryKey: ["agent-stacks", agent.id],
|
||||
queryFn: () => agentsApi.stacks(agent.id),
|
||||
enabled: online,
|
||||
refetchInterval: 8000,
|
||||
});
|
||||
const stats = useQuery({
|
||||
queryKey: ["agent-stack-stats", agent.id],
|
||||
queryFn: () => agentsApi.stackStats(agent.id),
|
||||
enabled: online,
|
||||
refetchInterval: 5000,
|
||||
});
|
||||
const sys = useQuery({
|
||||
queryKey: ["agent-system", agent.id],
|
||||
queryFn: () => agentsApi.system(agent.id),
|
||||
enabled: online,
|
||||
refetchInterval: 30000,
|
||||
});
|
||||
|
||||
const run = async (action: string, label: string, id: string) => {
|
||||
setBusyId(id);
|
||||
const t = toast.loading(`${label} ${id} on ${agent.name}…`);
|
||||
try {
|
||||
await agentsApi.action(agent.id, id, action);
|
||||
toast.success(`${label} ${id} ✓`, { id: t });
|
||||
qc.invalidateQueries({ queryKey: ["agent-stacks", agent.id] });
|
||||
qc.invalidateQueries({ queryKey: ["agent-stack-stats", agent.id] });
|
||||
} catch (e) {
|
||||
toast.error(apiErrorMessage(e), { id: t });
|
||||
} finally {
|
||||
setBusyId(null);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<section>
|
||||
<HostHeader agent={agent} />
|
||||
{!online ? (
|
||||
<Card>
|
||||
<p className="text-sm text-slate-500">
|
||||
Host is {agent.status}. Check it under Settings → Remote hosts.
|
||||
</p>
|
||||
</Card>
|
||||
) : (
|
||||
<StacksTable
|
||||
stacks={stacks.data}
|
||||
stats={stats.data}
|
||||
hostCpus={sys.data?.cpu_cores ?? 0}
|
||||
hostMem={sys.data?.mem_total ?? 0}
|
||||
isAdmin={isAdmin}
|
||||
isBusy={(id) => busyId === id}
|
||||
loading={stacks.isLoading}
|
||||
linkBase={`/hosts/${agent.id}/stacks`}
|
||||
onStart={(id) => run("start", "Starting", id)}
|
||||
onStop={(id) => run("stop", "Stopping", id)}
|
||||
onRestart={(id) => run("restart", "Restarting", id)}
|
||||
emptyText="No stacks on this host."
|
||||
/>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -21,14 +21,12 @@ import {
|
||||
Copy,
|
||||
Scissors,
|
||||
ClipboardPaste,
|
||||
Server,
|
||||
} from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import Editor from "@monaco-editor/react";
|
||||
import { Button, Card, Input, Spinner } from "@/components/ui";
|
||||
import { ConfirmDialog } from "@/components/ui/ConfirmDialog";
|
||||
import { filesApi } from "@/api/files";
|
||||
import { agentsApi } from "@/api/agents";
|
||||
import { apiErrorMessage } from "@/api/client";
|
||||
import { useAuthStore } from "@/store/auth";
|
||||
import { useThemeStore } from "@/store/theme";
|
||||
@@ -74,7 +72,6 @@ function crumbs(path: string): { label: string; path: string }[] {
|
||||
export function Files() {
|
||||
const isAdmin = useAuthStore((s) => s.user?.role === "admin");
|
||||
const qc = useQueryClient();
|
||||
const [host, setHost] = useState<number | undefined>(undefined); // undefined = local
|
||||
const [path, setPath] = useState("/");
|
||||
// Persist "Show hidden" across reloads — otherwise an uploaded dotfile (.env)
|
||||
// becomes invisible again after a refresh and looks like it was lost.
|
||||
@@ -117,24 +114,9 @@ export function Files() {
|
||||
}
|
||||
}, []);
|
||||
|
||||
const agents = useQuery({
|
||||
queryKey: ["agents"],
|
||||
queryFn: () => agentsApi.list(),
|
||||
refetchInterval: 15000,
|
||||
});
|
||||
const onlineAgents = (agents.data ?? []).filter((a) => a.status === "online");
|
||||
|
||||
// Switch host: reset workspace state so we never mix paths/clipboards across hosts.
|
||||
const switchHost = (h: number | undefined) => {
|
||||
setHost(h);
|
||||
setPath("/");
|
||||
setEditing(null);
|
||||
setClip(null);
|
||||
};
|
||||
|
||||
const { data, isLoading, isFetching, error } = useQuery({
|
||||
queryKey: ["files", host ?? "local", path, showHidden],
|
||||
queryFn: () => filesApi.list(path, showHidden, host),
|
||||
queryKey: ["files", path, showHidden],
|
||||
queryFn: () => filesApi.list(path, showHidden),
|
||||
});
|
||||
|
||||
const refresh = () => qc.invalidateQueries({ queryKey: ["files"] });
|
||||
@@ -150,7 +132,7 @@ export function Files() {
|
||||
const upload = useMutation({
|
||||
mutationFn: ({ file, overwrite }: { file: File; overwrite: boolean }) => {
|
||||
setProgress({ label: file.name, pct: 0, kind: "upload" });
|
||||
return filesApi.upload(path, file, overwrite, "", host, (pct) =>
|
||||
return filesApi.upload(path, file, overwrite, "", (pct) =>
|
||||
setProgress({
|
||||
label: file.name,
|
||||
pct,
|
||||
@@ -202,7 +184,7 @@ export function Files() {
|
||||
const f = files[i];
|
||||
const rel = (f as File & { webkitRelativePath?: string }).webkitRelativePath || f.name;
|
||||
try {
|
||||
await filesApi.upload(path, f, true, rel, host, (filePct) => {
|
||||
await filesApi.upload(path, f, true, rel, (filePct) => {
|
||||
const sent = doneBytes + (filePct / 100) * f.size;
|
||||
setProgress({
|
||||
label: f.name,
|
||||
@@ -240,7 +222,7 @@ export function Files() {
|
||||
const paste = useMutation({
|
||||
mutationFn: (overwrite: boolean) => {
|
||||
const op = clip!.mode === "copy" ? filesApi.copy : filesApi.move;
|
||||
return op(clip!.src, path, overwrite, host);
|
||||
return op(clip!.src, path, overwrite);
|
||||
},
|
||||
onSuccess: () => {
|
||||
toast.success(clip!.mode === "copy" ? "Copied" : "Moved");
|
||||
@@ -258,7 +240,7 @@ export function Files() {
|
||||
});
|
||||
|
||||
const remove = useMutation({
|
||||
mutationFn: (e: HostPathEntry) => filesApi.remove(join(path, e.name), e.type === "dir", host),
|
||||
mutationFn: (e: HostPathEntry) => filesApi.remove(join(path, e.name), e.type === "dir"),
|
||||
onSuccess: () => {
|
||||
toast.success("Deleted");
|
||||
setDeleting(null);
|
||||
@@ -276,7 +258,6 @@ export function Files() {
|
||||
.download(
|
||||
join(path, e.name),
|
||||
isDir ? `${e.name}.zip` : e.name,
|
||||
host,
|
||||
(loaded, total) =>
|
||||
setProgress({
|
||||
label: e.name,
|
||||
@@ -292,29 +273,6 @@ export function Files() {
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Host switcher (only when remote hosts are registered) */}
|
||||
{(agents.data?.length ?? 0) > 0 && (
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
<Server className="h-4 w-4 text-slate-400" />
|
||||
<span className="text-slate-500">Host</span>
|
||||
<select
|
||||
value={host ?? "local"}
|
||||
onChange={(e) => switchHost(e.target.value === "local" ? undefined : Number(e.target.value))}
|
||||
className="rounded-lg border border-slate-300 bg-white px-3 py-1.5 text-sm dark:border-slate-600 dark:bg-slate-800"
|
||||
>
|
||||
<option value="local">This host</option>
|
||||
{onlineAgents.map((a) => (
|
||||
<option key={a.id} value={a.id}>
|
||||
{a.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{host != null && !onlineAgents.some((a) => a.id === host) && (
|
||||
<span className="text-xs text-amber-500">selected host is offline</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Roots + actions */}
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{data?.roots.map((r) => (
|
||||
@@ -584,7 +542,6 @@ export function Files() {
|
||||
path={join(path, editing.name)}
|
||||
name={editing.name}
|
||||
isAdmin={isAdmin}
|
||||
agentId={host}
|
||||
onClose={() => setEditing(null)}
|
||||
onSaved={refresh}
|
||||
/>
|
||||
@@ -593,7 +550,6 @@ export function Files() {
|
||||
<NewEntryDialog
|
||||
kind={newKind}
|
||||
dir={path}
|
||||
agentId={host}
|
||||
onCancel={() => setNewKind(null)}
|
||||
onDone={() => {
|
||||
setNewKind(null);
|
||||
@@ -605,7 +561,6 @@ export function Files() {
|
||||
<RenameDialog
|
||||
entry={renaming}
|
||||
dir={path}
|
||||
agentId={host}
|
||||
onCancel={() => setRenaming(null)}
|
||||
onDone={() => {
|
||||
setRenaming(null);
|
||||
@@ -661,14 +616,12 @@ function FileEditor({
|
||||
path,
|
||||
name,
|
||||
isAdmin,
|
||||
agentId,
|
||||
onClose,
|
||||
onSaved,
|
||||
}: {
|
||||
path: string;
|
||||
name: string;
|
||||
isAdmin: boolean;
|
||||
agentId?: number;
|
||||
onClose: () => void;
|
||||
onSaved: () => void;
|
||||
}) {
|
||||
@@ -676,8 +629,8 @@ function FileEditor({
|
||||
const [content, setContent] = useState("");
|
||||
const [dirty, setDirty] = useState(false);
|
||||
const { data, isLoading, error } = useQuery({
|
||||
queryKey: ["file-content", agentId ?? "local", path],
|
||||
queryFn: () => filesApi.read(path, agentId),
|
||||
queryKey: ["file-content", path],
|
||||
queryFn: () => filesApi.read(path),
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
@@ -685,7 +638,7 @@ function FileEditor({
|
||||
}, [data]);
|
||||
|
||||
const save = useMutation({
|
||||
mutationFn: () => filesApi.write(path, content, agentId),
|
||||
mutationFn: () => filesApi.write(path, content),
|
||||
onSuccess: () => {
|
||||
toast.success("Saved");
|
||||
setDirty(false);
|
||||
@@ -735,7 +688,7 @@ function FileEditor({
|
||||
? "This looks like a binary file and can't be edited here."
|
||||
: `File is too large to edit (${formatBytes(data?.size ?? 0)}).`}
|
||||
</p>
|
||||
<Button variant="outline" onClick={() => filesApi.download(path, name, agentId)}>
|
||||
<Button variant="outline" onClick={() => filesApi.download(path, name)}>
|
||||
<Download className="h-4 w-4" /> Download instead
|
||||
</Button>
|
||||
</div>
|
||||
@@ -767,13 +720,11 @@ function FileEditor({
|
||||
function NewEntryDialog({
|
||||
kind,
|
||||
dir,
|
||||
agentId,
|
||||
onCancel,
|
||||
onDone,
|
||||
}: {
|
||||
kind: "dir" | "file";
|
||||
dir: string;
|
||||
agentId?: number;
|
||||
onCancel: () => void;
|
||||
onDone: () => void;
|
||||
}) {
|
||||
@@ -781,8 +732,8 @@ function NewEntryDialog({
|
||||
const create = useMutation({
|
||||
mutationFn: () =>
|
||||
kind === "dir"
|
||||
? filesApi.mkdir(dir, name.trim(), agentId)
|
||||
: filesApi.touch(dir, name.trim(), agentId),
|
||||
? filesApi.mkdir(dir, name.trim())
|
||||
: filesApi.touch(dir, name.trim()),
|
||||
onSuccess: () => {
|
||||
toast.success(kind === "dir" ? "Folder created" : "File created");
|
||||
onDone();
|
||||
@@ -812,19 +763,17 @@ function NewEntryDialog({
|
||||
function RenameDialog({
|
||||
entry,
|
||||
dir,
|
||||
agentId,
|
||||
onCancel,
|
||||
onDone,
|
||||
}: {
|
||||
entry: HostPathEntry;
|
||||
dir: string;
|
||||
agentId?: number;
|
||||
onCancel: () => void;
|
||||
onDone: () => void;
|
||||
}) {
|
||||
const [name, setName] = useState(entry.name);
|
||||
const rename = useMutation({
|
||||
mutationFn: () => filesApi.rename(join(dir, entry.name), name.trim(), agentId),
|
||||
mutationFn: () => filesApi.rename(join(dir, entry.name), name.trim()),
|
||||
onSuccess: () => {
|
||||
toast.success("Renamed");
|
||||
onDone();
|
||||
|
||||
@@ -4,13 +4,10 @@ import { RefreshCw, ArrowUpCircle, CheckCircle2, HelpCircle, Eraser } from "luci
|
||||
import { toast } from "sonner";
|
||||
import { Button, Card, Spinner } from "@/components/ui";
|
||||
import { ConfirmDialog } from "@/components/ui/ConfirmDialog";
|
||||
import { HostHeader } from "@/components/hosts/HostHeader";
|
||||
import { imagesApi, type ImageRow } from "@/api/images";
|
||||
import { agentsApi } from "@/api/agents";
|
||||
import { apiErrorMessage } from "@/api/client";
|
||||
import { formatBytes, relativeTime } from "@/lib/utils";
|
||||
import { useAuthStore } from "@/store/auth";
|
||||
import type { Agent } from "@/types";
|
||||
|
||||
function UpdateBadge({ row }: { row: ImageRow }) {
|
||||
const u = row.update;
|
||||
@@ -31,50 +28,25 @@ function UpdateBadge({ row }: { row: ImageRow }) {
|
||||
|
||||
export function Images() {
|
||||
const isAdmin = useAuthStore((s) => s.user?.role === "admin");
|
||||
const agents = useQuery({
|
||||
queryKey: ["agents"],
|
||||
queryFn: () => agentsApi.list(),
|
||||
refetchInterval: 15000,
|
||||
});
|
||||
const hasAgents = (agents.data?.length ?? 0) > 0;
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<ImagesSection isAdmin={isAdmin} showHostLabel={hasAgents} />
|
||||
{agents.data?.map((agent) => (
|
||||
<ImagesSection key={agent.id} agent={agent} isAdmin={isAdmin} showHostLabel />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
return <ImagesSection isAdmin={isAdmin} />;
|
||||
}
|
||||
|
||||
function ImagesSection({
|
||||
agent,
|
||||
isAdmin,
|
||||
showHostLabel,
|
||||
}: {
|
||||
agent?: Agent;
|
||||
isAdmin: boolean;
|
||||
showHostLabel: boolean;
|
||||
}) {
|
||||
const agentId = agent?.id;
|
||||
const online = !agent || agent.status === "online";
|
||||
function ImagesSection({ isAdmin }: { isAdmin: boolean }) {
|
||||
const qc = useQueryClient();
|
||||
const [checking, setChecking] = useState(false);
|
||||
const [pruneOpen, setPruneOpen] = useState(false);
|
||||
const [pruneAll, setPruneAll] = useState(false);
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey: ["images", agentId ?? "local"],
|
||||
queryFn: () => imagesApi.list(agentId),
|
||||
enabled: online,
|
||||
queryKey: ["images"],
|
||||
queryFn: () => imagesApi.list(),
|
||||
});
|
||||
|
||||
const check = async () => {
|
||||
setChecking(true);
|
||||
const t = toast.loading("Checking for updates…");
|
||||
try {
|
||||
await imagesApi.check(agentId);
|
||||
await qc.invalidateQueries({ queryKey: ["images", agentId ?? "local"] });
|
||||
await imagesApi.check();
|
||||
await qc.invalidateQueries({ queryKey: ["images"] });
|
||||
toast.success("Update check complete", { id: t });
|
||||
} catch (e) {
|
||||
toast.error(apiErrorMessage(e), { id: t });
|
||||
@@ -84,7 +56,7 @@ function ImagesSection({
|
||||
};
|
||||
|
||||
const prune = useMutation({
|
||||
mutationFn: () => imagesApi.prune(pruneAll, agentId),
|
||||
mutationFn: () => imagesApi.prune(pruneAll),
|
||||
onSuccess: (r) => {
|
||||
const n = r.ImagesDeleted?.length ?? 0;
|
||||
toast.success(
|
||||
@@ -94,35 +66,25 @@ function ImagesSection({
|
||||
);
|
||||
setPruneOpen(false);
|
||||
setPruneAll(false);
|
||||
qc.invalidateQueries({ queryKey: ["images", agentId ?? "local"] });
|
||||
qc.invalidateQueries({ queryKey: ["images"] });
|
||||
},
|
||||
onError: (e) => toast.error(apiErrorMessage(e)),
|
||||
});
|
||||
|
||||
return (
|
||||
<section>
|
||||
{(showHostLabel || (isAdmin && online)) && (
|
||||
<HostHeader agent={agent}>
|
||||
{isAdmin && online && (
|
||||
<>
|
||||
<Button variant="outline" onClick={() => setPruneOpen(true)}>
|
||||
<Eraser className="h-4 w-4" /> Prune
|
||||
</Button>
|
||||
<Button onClick={check} loading={checking}>
|
||||
<RefreshCw className="h-4 w-4" /> Check updates
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</HostHeader>
|
||||
{isAdmin && (
|
||||
<div className="mb-3 flex flex-wrap items-center justify-end gap-2">
|
||||
<Button variant="outline" onClick={() => setPruneOpen(true)}>
|
||||
<Eraser className="h-4 w-4" /> Prune
|
||||
</Button>
|
||||
<Button onClick={check} loading={checking}>
|
||||
<RefreshCw className="h-4 w-4" /> Check updates
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!online ? (
|
||||
<Card>
|
||||
<p className="text-sm text-slate-500">
|
||||
Host is {agent?.status}. Check it under Settings → Remote hosts.
|
||||
</p>
|
||||
</Card>
|
||||
) : isLoading ? (
|
||||
{isLoading ? (
|
||||
<Spinner />
|
||||
) : (
|
||||
<Card className="overflow-x-auto p-0">
|
||||
|
||||
@@ -13,61 +13,33 @@ import {
|
||||
import { toast } from "sonner";
|
||||
import { Badge, Button, Card, Input, Spinner } from "@/components/ui";
|
||||
import { ConfirmDialog } from "@/components/ui/ConfirmDialog";
|
||||
import { HostHeader } from "@/components/hosts/HostHeader";
|
||||
import { networksApi, type NetworkInfo } from "@/api/networks";
|
||||
import { agentsApi } from "@/api/agents";
|
||||
import { apiErrorMessage } from "@/api/client";
|
||||
import { useAuthStore } from "@/store/auth";
|
||||
import type { Agent } from "@/types";
|
||||
|
||||
const selectClass =
|
||||
"w-full rounded-lg border border-slate-300 bg-white px-3 py-2 text-sm dark:border-slate-600 dark:bg-slate-800";
|
||||
|
||||
export function Networks() {
|
||||
const isAdmin = useAuthStore((s) => s.user?.role === "admin");
|
||||
const agents = useQuery({
|
||||
queryKey: ["agents"],
|
||||
queryFn: () => agentsApi.list(),
|
||||
refetchInterval: 15000,
|
||||
});
|
||||
const hasAgents = (agents.data?.length ?? 0) > 0;
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<NetworksSection isAdmin={isAdmin} showHostLabel={hasAgents} />
|
||||
{agents.data?.map((agent) => (
|
||||
<NetworksSection key={agent.id} agent={agent} isAdmin={isAdmin} showHostLabel />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
return <NetworksSection isAdmin={isAdmin} />;
|
||||
}
|
||||
|
||||
function NetworksSection({
|
||||
agent,
|
||||
isAdmin,
|
||||
showHostLabel,
|
||||
}: {
|
||||
agent?: Agent;
|
||||
isAdmin: boolean;
|
||||
showHostLabel: boolean;
|
||||
}) {
|
||||
const agentId = agent?.id;
|
||||
const online = !agent || agent.status === "online";
|
||||
function NetworksSection({ isAdmin }: { isAdmin: boolean }) {
|
||||
const qc = useQueryClient();
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey: ["networks", agentId ?? "local"],
|
||||
queryFn: () => networksApi.list(agentId),
|
||||
queryKey: ["networks"],
|
||||
queryFn: () => networksApi.list(),
|
||||
refetchInterval: 10000,
|
||||
enabled: online,
|
||||
});
|
||||
const [creating, setCreating] = useState(false);
|
||||
const [toDelete, setToDelete] = useState<NetworkInfo | null>(null);
|
||||
const [expanded, setExpanded] = useState<string | null>(null);
|
||||
const invalidate = () => qc.invalidateQueries({ queryKey: ["networks", agentId ?? "local"] });
|
||||
const invalidate = () => qc.invalidateQueries({ queryKey: ["networks"] });
|
||||
const colSpan = isAdmin ? 6 : 5;
|
||||
|
||||
const prune = useMutation({
|
||||
mutationFn: () => networksApi.prune(agentId),
|
||||
mutationFn: () => networksApi.prune(),
|
||||
onSuccess: (r) => {
|
||||
const n = r.NetworksDeleted?.length ?? 0;
|
||||
toast.success(n ? `Pruned ${n} network(s)` : "No unused networks");
|
||||
@@ -76,7 +48,7 @@ function NetworksSection({
|
||||
onError: (e) => toast.error(apiErrorMessage(e)),
|
||||
});
|
||||
const remove = useMutation({
|
||||
mutationFn: (id: string) => networksApi.remove(id, agentId),
|
||||
mutationFn: (id: string) => networksApi.remove(id),
|
||||
onSuccess: () => {
|
||||
toast.success("Network deleted");
|
||||
setToDelete(null);
|
||||
@@ -85,32 +57,20 @@ function NetworksSection({
|
||||
onError: (e) => toast.error(apiErrorMessage(e)),
|
||||
});
|
||||
|
||||
const header = (
|
||||
<HostHeader agent={agent}>
|
||||
{isAdmin && online && (
|
||||
<>
|
||||
return (
|
||||
<section>
|
||||
{isAdmin && (
|
||||
<div className="mb-3 flex flex-wrap items-center justify-end gap-2">
|
||||
<Button variant="outline" onClick={() => prune.mutate()} loading={prune.isPending}>
|
||||
<Eraser className="h-4 w-4" /> Prune unused
|
||||
</Button>
|
||||
<Button onClick={() => setCreating(true)}>
|
||||
<Plus className="h-4 w-4" /> Create network
|
||||
</Button>
|
||||
</>
|
||||
</div>
|
||||
)}
|
||||
</HostHeader>
|
||||
);
|
||||
|
||||
return (
|
||||
<section>
|
||||
{(showHostLabel || (isAdmin && online)) && header}
|
||||
|
||||
{!online ? (
|
||||
<Card>
|
||||
<p className="text-sm text-slate-500">
|
||||
Host is {agent?.status}. Check it under Settings → Remote hosts.
|
||||
</p>
|
||||
</Card>
|
||||
) : isLoading ? (
|
||||
{isLoading ? (
|
||||
<Spinner />
|
||||
) : (
|
||||
<Card className="overflow-x-auto p-0">
|
||||
@@ -175,7 +135,7 @@ function NetworksSection({
|
||||
{expanded === n.id && (
|
||||
<tr>
|
||||
<td colSpan={colSpan} className="bg-slate-50 px-4 py-3 dark:bg-slate-800/40">
|
||||
<NetworkDetail network={n} isAdmin={isAdmin} agentId={agentId} />
|
||||
<NetworkDetail network={n} isAdmin={isAdmin} />
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
@@ -195,7 +155,6 @@ function NetworksSection({
|
||||
|
||||
{creating && (
|
||||
<CreateNetworkDialog
|
||||
agentId={agentId}
|
||||
onDone={() => { setCreating(false); invalidate(); }}
|
||||
onCancel={() => setCreating(false)}
|
||||
/>
|
||||
@@ -222,31 +181,29 @@ function NetworksSection({
|
||||
function NetworkDetail({
|
||||
network,
|
||||
isAdmin,
|
||||
agentId,
|
||||
}: {
|
||||
network: NetworkInfo;
|
||||
isAdmin: boolean;
|
||||
agentId?: number;
|
||||
}) {
|
||||
const qc = useQueryClient();
|
||||
const [pick, setPick] = useState("");
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey: ["network-containers", agentId ?? "local", network.id],
|
||||
queryFn: () => networksApi.containers(network.id, agentId),
|
||||
queryKey: ["network-containers", network.id],
|
||||
queryFn: () => networksApi.containers(network.id),
|
||||
refetchInterval: 10000,
|
||||
});
|
||||
const refresh = () => {
|
||||
qc.invalidateQueries({ queryKey: ["network-containers", agentId ?? "local", network.id] });
|
||||
qc.invalidateQueries({ queryKey: ["networks", agentId ?? "local"] });
|
||||
qc.invalidateQueries({ queryKey: ["network-containers", network.id] });
|
||||
qc.invalidateQueries({ queryKey: ["networks"] });
|
||||
};
|
||||
|
||||
const connect = useMutation({
|
||||
mutationFn: (container: string) => networksApi.connect(network.id, container, undefined, agentId),
|
||||
mutationFn: (container: string) => networksApi.connect(network.id, container),
|
||||
onSuccess: () => { toast.success("Container connected"); setPick(""); refresh(); },
|
||||
onError: (e) => toast.error(apiErrorMessage(e)),
|
||||
});
|
||||
const disconnect = useMutation({
|
||||
mutationFn: (container: string) => networksApi.disconnect(network.id, container, false, agentId),
|
||||
mutationFn: (container: string) => networksApi.disconnect(network.id, container, false),
|
||||
onSuccess: () => { toast.success("Container disconnected"); refresh(); },
|
||||
onError: (e) => toast.error(apiErrorMessage(e)),
|
||||
});
|
||||
@@ -336,11 +293,9 @@ function Meta({ label, value, mono }: { label: string; value: string; mono?: boo
|
||||
}
|
||||
|
||||
function CreateNetworkDialog({
|
||||
agentId,
|
||||
onDone,
|
||||
onCancel,
|
||||
}: {
|
||||
agentId?: number;
|
||||
onDone: () => void;
|
||||
onCancel: () => void;
|
||||
}) {
|
||||
@@ -356,17 +311,14 @@ function CreateNetworkDialog({
|
||||
|
||||
const create = useMutation({
|
||||
mutationFn: () =>
|
||||
networksApi.create(
|
||||
{
|
||||
name: form.name,
|
||||
driver: form.driver,
|
||||
subnet: form.subnet.trim() || null,
|
||||
gateway: form.gateway.trim() || null,
|
||||
internal: form.internal,
|
||||
attachable: form.attachable,
|
||||
},
|
||||
agentId
|
||||
),
|
||||
networksApi.create({
|
||||
name: form.name,
|
||||
driver: form.driver,
|
||||
subnet: form.subnet.trim() || null,
|
||||
gateway: form.gateway.trim() || null,
|
||||
internal: form.internal,
|
||||
attachable: form.attachable,
|
||||
}),
|
||||
onSuccess: () => { toast.success("Network created"); onDone(); },
|
||||
onError: (e) => toast.error(apiErrorMessage(e)),
|
||||
});
|
||||
|
||||
@@ -1,299 +0,0 @@
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { Link, useParams } from "react-router-dom";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import {
|
||||
Play,
|
||||
Square,
|
||||
RotateCw,
|
||||
DownloadCloud,
|
||||
ArrowUpCircle,
|
||||
Power,
|
||||
ArrowLeft,
|
||||
Save,
|
||||
} from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import { Badge, Button, Card, Spinner, StatusDot } from "@/components/ui";
|
||||
import { HostDot } from "@/components/hosts/HostDot";
|
||||
import { LogViewer } from "@/components/stacks/LogViewer";
|
||||
import { ContainerCard } from "@/components/stacks/ContainerCard";
|
||||
import { AutoUpdatePanel } from "@/components/stacks/AutoUpdatePanel";
|
||||
import { SecretsPanel } from "@/components/stacks/SecretsPanel";
|
||||
import { BackupButton } from "@/components/stacks/BackupRestore";
|
||||
import { agentsApi } from "@/api/agents";
|
||||
import { apiErrorMessage } from "@/api/client";
|
||||
import { useAuthStore } from "@/store/auth";
|
||||
import type { ContainerInfo } from "@/types";
|
||||
|
||||
const TABS = ["Overview", "Logs", "Environment", "Compose", "Secrets"] as const;
|
||||
type Tab = (typeof TABS)[number];
|
||||
|
||||
export function RemoteStackDetail() {
|
||||
const { agentId = "", id = "" } = useParams();
|
||||
const aid = Number(agentId);
|
||||
const qc = useQueryClient();
|
||||
const isAdmin = useAuthStore((s) => s.user?.role === "admin");
|
||||
const [tab, setTab] = useState<Tab>("Overview");
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey: ["agent-stack", aid, id],
|
||||
queryFn: () => agentsApi.stack(aid, id),
|
||||
refetchInterval: 5000,
|
||||
});
|
||||
|
||||
// Port links on a remote stack must target the agent host, not this host.
|
||||
const agents = useQuery({ queryKey: ["agents"], queryFn: () => agentsApi.list(false) });
|
||||
const agentHost = useMemo(() => {
|
||||
const a = agents.data?.find((x) => x.id === aid);
|
||||
if (!a) return undefined;
|
||||
try {
|
||||
return new URL(a.url).hostname;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}, [agents.data, aid]);
|
||||
|
||||
const run = async (action: string, label: string) => {
|
||||
setBusy(true);
|
||||
const t = toast.loading(`${label} ${id}…`);
|
||||
try {
|
||||
await agentsApi.action(aid, id, action);
|
||||
toast.success(`${label} ${id} ✓`, { id: t });
|
||||
qc.invalidateQueries({ queryKey: ["agent-stack", aid, id] });
|
||||
} catch (e) {
|
||||
toast.error(apiErrorMessage(e), { id: t });
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (isLoading || !data) return <Spinner />;
|
||||
|
||||
return (
|
||||
<div className="flex h-full flex-col space-y-4">
|
||||
<Link
|
||||
to="/stacks"
|
||||
className="inline-flex items-center gap-1 text-sm text-slate-500 hover:text-slate-700 dark:hover:text-slate-300"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4" /> All stacks
|
||||
</Link>
|
||||
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div>
|
||||
<div className="flex items-center gap-2">
|
||||
<StatusDot status={data.status} />
|
||||
<h1 className="sp-heading text-xl">{data.name}</h1>
|
||||
<Badge status={data.status}>{data.status}</Badge>
|
||||
</div>
|
||||
<p className="mt-1 flex items-center gap-1 text-sm text-slate-500">
|
||||
on <span className="font-medium">{data.agent_name}</span>
|
||||
<HostDot status="online" />
|
||||
</p>
|
||||
</div>
|
||||
{isAdmin && (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button variant="outline" onClick={() => run("start", "Starting")} loading={busy}>
|
||||
<Play className="h-4 w-4 text-green-500" /> Start
|
||||
</Button>
|
||||
<Button variant="outline" onClick={() => run("stop", "Stopping")} loading={busy}>
|
||||
<Square className="h-4 w-4 text-red-500" /> Stop
|
||||
</Button>
|
||||
<Button variant="outline" onClick={() => run("restart", "Restarting")} loading={busy}>
|
||||
<RotateCw className="h-4 w-4 text-sky-500" /> Restart
|
||||
</Button>
|
||||
<Button variant="outline" onClick={() => run("pull", "Pulling")} loading={busy}>
|
||||
<DownloadCloud className="h-4 w-4" /> Pull
|
||||
</Button>
|
||||
<Button variant="outline" onClick={() => run("update", "Updating")} loading={busy}>
|
||||
<ArrowUpCircle className="h-4 w-4" /> Update
|
||||
</Button>
|
||||
<Button variant="outline" onClick={() => run("down", "Tearing down")} loading={busy}>
|
||||
<Power className="h-4 w-4" /> Down
|
||||
</Button>
|
||||
<BackupButton stackId={id} agentId={aid} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex gap-1 border-b border-slate-200 dark:border-slate-700">
|
||||
{TABS.map((t) => (
|
||||
<button
|
||||
key={t}
|
||||
onClick={() => setTab(t)}
|
||||
className={
|
||||
tab === t
|
||||
? "border-b-2 border-accent px-4 py-2 text-sm font-medium text-accent dark:border-accent-dark dark:text-accent-dark"
|
||||
: "px-4 py-2 text-sm text-slate-500 hover:text-slate-700 dark:hover:text-slate-300"
|
||||
}
|
||||
>
|
||||
{t}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="flex-1 overflow-hidden">
|
||||
{tab === "Overview" && (
|
||||
<Overview
|
||||
stackId={id}
|
||||
containers={data.containers}
|
||||
host={agentHost}
|
||||
agentId={aid}
|
||||
isAdmin={isAdmin}
|
||||
onChanged={() => qc.invalidateQueries({ queryKey: ["agent-stack", aid, id] })}
|
||||
/>
|
||||
)}
|
||||
{tab === "Logs" && (
|
||||
<Card className="h-full overflow-hidden">
|
||||
<LogViewer stackId={id} agentId={aid} />
|
||||
</Card>
|
||||
)}
|
||||
{tab === "Environment" && (
|
||||
<RemoteEditor
|
||||
agentId={aid}
|
||||
stackId={id}
|
||||
field="env"
|
||||
value={data.env}
|
||||
canEdit={isAdmin}
|
||||
queryKey={["agent-stack", aid, id]}
|
||||
/>
|
||||
)}
|
||||
{tab === "Compose" && (
|
||||
<RemoteEditor
|
||||
agentId={aid}
|
||||
stackId={id}
|
||||
field="yaml"
|
||||
value={data.yaml}
|
||||
canEdit={isAdmin}
|
||||
queryKey={["agent-stack", aid, id]}
|
||||
/>
|
||||
)}
|
||||
{tab === "Secrets" && (
|
||||
<SecretsPanel
|
||||
stackId={id}
|
||||
yaml={data.yaml}
|
||||
agentId={aid}
|
||||
isAdmin={isAdmin}
|
||||
onChanged={() => qc.invalidateQueries({ queryKey: ["agent-stack", aid, id] })}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Overview({
|
||||
stackId,
|
||||
containers,
|
||||
host,
|
||||
agentId,
|
||||
isAdmin,
|
||||
onChanged,
|
||||
}: {
|
||||
stackId: string;
|
||||
containers: ContainerInfo[];
|
||||
host?: string;
|
||||
agentId: number;
|
||||
isAdmin: boolean;
|
||||
onChanged: () => void;
|
||||
}) {
|
||||
return (
|
||||
<div className="space-y-2 overflow-auto">
|
||||
<AutoUpdatePanel stackId={stackId} agentId={agentId} isAdmin={isAdmin} />
|
||||
{containers.length === 0 && (
|
||||
<Card>
|
||||
<p className="text-sm text-slate-500">No containers running.</p>
|
||||
</Card>
|
||||
)}
|
||||
{containers.map((c) => (
|
||||
<ContainerCard
|
||||
key={c.id}
|
||||
container={c}
|
||||
agentId={agentId}
|
||||
host={host}
|
||||
isAdmin={isAdmin}
|
||||
onChanged={onChanged}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function RemoteEditor({
|
||||
agentId,
|
||||
stackId,
|
||||
field,
|
||||
value,
|
||||
canEdit,
|
||||
queryKey,
|
||||
}: {
|
||||
agentId: number;
|
||||
stackId: string;
|
||||
field: "yaml" | "env";
|
||||
value: string;
|
||||
canEdit: boolean;
|
||||
queryKey: unknown[];
|
||||
}) {
|
||||
const qc = useQueryClient();
|
||||
const [text, setText] = useState(value);
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!editing) setText(value);
|
||||
}, [value, editing]);
|
||||
|
||||
const save = async () => {
|
||||
setSaving(true);
|
||||
try {
|
||||
const body = field === "yaml" ? { yaml: text } : { env: text };
|
||||
await agentsApi.update_stack(agentId, stackId, body);
|
||||
toast.success("Saved. Restart or update the stack to apply.");
|
||||
setEditing(false);
|
||||
qc.invalidateQueries({ queryKey });
|
||||
} catch (e) {
|
||||
toast.error(apiErrorMessage(e));
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (!editing) {
|
||||
return (
|
||||
<Card className="flex h-full flex-col overflow-hidden">
|
||||
{canEdit && (
|
||||
<div className="mb-2 flex justify-end">
|
||||
<Button variant="outline" onClick={() => setEditing(true)}>
|
||||
Edit
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{value ? (
|
||||
<pre className="flex-1 overflow-auto whitespace-pre-wrap font-mono text-xs">{value}</pre>
|
||||
) : (
|
||||
<p className="text-sm text-slate-500">
|
||||
{field === "env" ? "No .env file for this stack." : "Empty compose file."}
|
||||
</p>
|
||||
)}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Card className="flex h-full flex-col gap-2 overflow-hidden">
|
||||
<textarea
|
||||
value={text}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
spellCheck={false}
|
||||
className="flex-1 resize-none rounded-lg border border-slate-300 bg-white p-3 font-mono text-xs outline-none focus:border-accent dark:border-slate-600 dark:bg-slate-900"
|
||||
/>
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button variant="outline" onClick={() => setEditing(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={save} loading={saving}>
|
||||
<Save className="h-4 w-4" /> Save
|
||||
</Button>
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -9,7 +9,6 @@ import {
|
||||
Users as UsersIcon,
|
||||
ShieldCheck,
|
||||
Power,
|
||||
Server,
|
||||
RefreshCw,
|
||||
HardDrive,
|
||||
CalendarClock,
|
||||
@@ -26,12 +25,10 @@ import {
|
||||
import { destinationsApi, type BackupDestination } from "@/api/backups";
|
||||
import { schedulesApi, type BackupSchedule } from "@/api/schedules";
|
||||
import { stacksApi } from "@/api/stacks";
|
||||
import { agentsApi } from "@/api/agents";
|
||||
import { HostDot } from "@/components/hosts/HostDot";
|
||||
import { apiErrorMessage } from "@/api/client";
|
||||
import { relativeTime } from "@/lib/utils";
|
||||
import { useAuthStore } from "@/store/auth";
|
||||
import type { Agent, User } from "@/types";
|
||||
import type { User } from "@/types";
|
||||
|
||||
export function Settings() {
|
||||
const isAdmin = useAuthStore((s) => s.user?.role === "admin");
|
||||
@@ -51,7 +48,6 @@ export function Settings() {
|
||||
return (
|
||||
<div className="mx-auto max-w-3xl space-y-6">
|
||||
<GeneralSection />
|
||||
<HostsSection />
|
||||
<DestinationsSection />
|
||||
<SchedulesSection />
|
||||
<NotificationsSection />
|
||||
@@ -78,7 +74,6 @@ function SchedulesSection() {
|
||||
const { data, isLoading } = useQuery({ queryKey: ["schedules"], queryFn: schedulesApi.list });
|
||||
const destinations = useQuery({ queryKey: ["destinations"], queryFn: destinationsApi.list });
|
||||
const stacks = useQuery({ queryKey: ["stacks"], queryFn: stacksApi.list });
|
||||
const agents = useQuery({ queryKey: ["agents"], queryFn: () => agentsApi.list() });
|
||||
const [adding, setAdding] = useState(false);
|
||||
const invalidate = () => qc.invalidateQueries({ queryKey: ["schedules"] });
|
||||
const noDest = (destinations.data?.length ?? 0) === 0;
|
||||
@@ -104,7 +99,6 @@ function SchedulesSection() {
|
||||
<ScheduleForm
|
||||
stacks={stacks.data ?? []}
|
||||
destinations={destinations.data ?? []}
|
||||
agents={agents.data ?? []}
|
||||
onDone={() => { setAdding(false); invalidate(); }}
|
||||
onCancel={() => setAdding(false)}
|
||||
/>
|
||||
@@ -145,7 +139,6 @@ function ScheduleRow({ schedule, onChange }: { schedule: BackupSchedule; onChang
|
||||
<Card className="space-y-2">
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<div className="flex items-center gap-2">
|
||||
{schedule.agent_name && <Badge>{schedule.agent_name}</Badge>}
|
||||
<span className="font-mono text-sm font-medium">{schedule.stack_id}</span>
|
||||
<span className="text-slate-400">→</span>
|
||||
<Badge>{schedule.destination_name ?? `dest ${schedule.destination_id}`}</Badge>
|
||||
@@ -181,17 +174,14 @@ function ScheduleRow({ schedule, onChange }: { schedule: BackupSchedule; onChang
|
||||
function ScheduleForm({
|
||||
stacks,
|
||||
destinations,
|
||||
agents,
|
||||
onDone,
|
||||
onCancel,
|
||||
}: {
|
||||
stacks: { id: string; name: string }[];
|
||||
destinations: BackupDestination[];
|
||||
agents: Agent[];
|
||||
onDone: () => void;
|
||||
onCancel: () => void;
|
||||
}) {
|
||||
const [host, setHost] = useState("local"); // "local" | agent id (string)
|
||||
const [form, setForm] = useState({
|
||||
stack_id: stacks[0]?.id ?? "",
|
||||
destination_id: destinations[0]?.id ?? 0,
|
||||
@@ -206,30 +196,17 @@ function ScheduleForm({
|
||||
});
|
||||
const set = (k: string, v: unknown) => setForm((f) => ({ ...f, [k]: v }));
|
||||
|
||||
const isRemote = host !== "local";
|
||||
const agentId = isRemote ? Number(host) : undefined;
|
||||
const stackOptions = stacks;
|
||||
|
||||
// When a remote host is selected, pull its stacks for the picker.
|
||||
const remoteStacks = useQuery({
|
||||
queryKey: ["agent-stacks", agentId],
|
||||
queryFn: () => agentsApi.stacks(agentId!),
|
||||
enabled: isRemote,
|
||||
});
|
||||
const stackOptions = isRemote
|
||||
? (remoteStacks.data ?? []).map((s) => ({ id: s.id, name: s.name }))
|
||||
: stacks;
|
||||
|
||||
// Keep stack_id valid as host/options change.
|
||||
// Keep stack_id valid as the options change.
|
||||
useEffect(() => {
|
||||
if (stackOptions.length && !stackOptions.some((s) => s.id === form.stack_id)) {
|
||||
set("stack_id", stackOptions[0].id);
|
||||
}
|
||||
}, [stackOptions]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
const onlineAgents = agents.filter((a) => a.status === "online");
|
||||
|
||||
const create = useMutation({
|
||||
mutationFn: () => schedulesApi.create({ ...form, agent_id: agentId ?? null }),
|
||||
mutationFn: () => schedulesApi.create(form),
|
||||
onSuccess: () => { toast.success("Schedule added"); onDone(); },
|
||||
onError: (e) => toast.error(apiErrorMessage(e)),
|
||||
});
|
||||
@@ -237,19 +214,10 @@ function ScheduleForm({
|
||||
return (
|
||||
<Card className="space-y-3">
|
||||
<div className="grid gap-3 sm:grid-cols-3">
|
||||
<label className="space-y-1">
|
||||
<span className="text-xs font-medium text-slate-500">Host</span>
|
||||
<select className={selectClass} value={host} onChange={(e) => setHost(e.target.value)}>
|
||||
<option value="local">This host</option>
|
||||
{onlineAgents.map((a) => (
|
||||
<option key={a.id} value={String(a.id)}>{a.name}</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="space-y-1">
|
||||
<span className="text-xs font-medium text-slate-500">Stack</span>
|
||||
<select className={selectClass} value={form.stack_id} onChange={(e) => set("stack_id", e.target.value)}>
|
||||
{stackOptions.length === 0 && <option value="">{isRemote ? "no stacks" : "—"}</option>}
|
||||
{stackOptions.length === 0 && <option value="">—</option>}
|
||||
{stackOptions.map((s) => (
|
||||
<option key={s.id} value={s.id}>{s.name}</option>
|
||||
))}
|
||||
@@ -485,135 +453,6 @@ function DestinationForm({ onDone, onCancel }: { onDone: () => void; onCancel: (
|
||||
);
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* Remote hosts (agents) */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
function HostsSection() {
|
||||
const qc = useQueryClient();
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey: ["agents"],
|
||||
queryFn: () => agentsApi.list(),
|
||||
refetchInterval: 15000,
|
||||
});
|
||||
const [adding, setAdding] = useState(false);
|
||||
const invalidate = () => qc.invalidateQueries({ queryKey: ["agents"] });
|
||||
|
||||
return (
|
||||
<section>
|
||||
<SectionTitle icon={<Server className="h-4 w-4" />}>Remote hosts</SectionTitle>
|
||||
<div className="space-y-3">
|
||||
{isLoading ? (
|
||||
<Spinner />
|
||||
) : (
|
||||
data?.map((a) => <HostRow key={a.id} agent={a} onChange={invalidate} />)
|
||||
)}
|
||||
{data?.length === 0 && !adding && (
|
||||
<Card>
|
||||
<p className="text-sm text-slate-500">
|
||||
No remote hosts. Deploy <code>stackpilot-agent</code> on another host and
|
||||
add it here to manage its stacks from this dashboard.
|
||||
</p>
|
||||
</Card>
|
||||
)}
|
||||
{adding ? (
|
||||
<AddHostForm onDone={() => { setAdding(false); invalidate(); }} onCancel={() => setAdding(false)} />
|
||||
) : (
|
||||
<Button variant="outline" onClick={() => setAdding(true)}>
|
||||
<Plus className="h-4 w-4" /> Add host
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function HostRow({ agent, onChange }: { agent: Agent; onChange: () => void }) {
|
||||
const ping = useMutation({
|
||||
mutationFn: () => agentsApi.ping(agent.id),
|
||||
onSuccess: (r) => {
|
||||
toast[r.status === "online" ? "success" : "error"](`Host is ${r.status}`);
|
||||
onChange();
|
||||
},
|
||||
onError: (e) => toast.error(apiErrorMessage(e)),
|
||||
});
|
||||
const remove = useMutation({
|
||||
mutationFn: () => agentsApi.remove(agent.id),
|
||||
onSuccess: () => { toast.success("Host removed"); onChange(); },
|
||||
onError: (e) => toast.error(apiErrorMessage(e)),
|
||||
});
|
||||
|
||||
return (
|
||||
<Card className="flex flex-wrap items-center justify-between gap-2">
|
||||
<div className="min-w-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<HostDot status={agent.status} />
|
||||
<span className="font-medium">{agent.name}</span>
|
||||
<span className="text-xs text-slate-400">{agent.status}</span>
|
||||
{agent.hostname && (
|
||||
<span className="font-mono text-xs text-slate-400">({agent.hostname})</span>
|
||||
)}
|
||||
</div>
|
||||
<p className="break-all font-mono text-xs text-slate-500">{agent.url}</p>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button variant="ghost" onClick={() => ping.mutate()} loading={ping.isPending}>
|
||||
<RefreshCw className="h-4 w-4" /> Check
|
||||
</Button>
|
||||
<Button variant="ghost" onClick={() => remove.mutate()} loading={remove.isPending}>
|
||||
<Trash2 className="h-4 w-4 text-red-500" />
|
||||
</Button>
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function AddHostForm({ onDone, onCancel }: { onDone: () => void; onCancel: () => void }) {
|
||||
const [name, setName] = useState("");
|
||||
const [url, setUrl] = useState("");
|
||||
const [token, setToken] = useState("");
|
||||
|
||||
const create = useMutation({
|
||||
mutationFn: () => agentsApi.create({ name, url, token }),
|
||||
onSuccess: (a) => {
|
||||
toast[a.status === "online" ? "success" : "error"](
|
||||
a.status === "online" ? "Host added and reachable" : `Host added but ${a.status}`
|
||||
);
|
||||
onDone();
|
||||
},
|
||||
onError: (e) => toast.error(apiErrorMessage(e)),
|
||||
});
|
||||
|
||||
return (
|
||||
<Card className="space-y-3">
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<label className="space-y-1">
|
||||
<span className="text-xs font-medium text-slate-500">Name</span>
|
||||
<Input value={name} onChange={(e) => setName(e.target.value)} placeholder="nas" />
|
||||
</label>
|
||||
<label className="space-y-1">
|
||||
<span className="text-xs font-medium text-slate-500">Agent URL</span>
|
||||
<Input value={url} onChange={(e) => setUrl(e.target.value)} placeholder="http://10.0.0.5:5010" />
|
||||
</label>
|
||||
</div>
|
||||
<label className="block space-y-1">
|
||||
<span className="text-xs font-medium text-slate-500">Shared token (AGENT_TOKEN)</span>
|
||||
<Input type="password" value={token} onChange={(e) => setToken(e.target.value)} />
|
||||
</label>
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button variant="outline" onClick={onCancel}>Cancel</Button>
|
||||
<Button
|
||||
onClick={() => create.mutate()}
|
||||
loading={create.isPending}
|
||||
disabled={!name.trim() || !url.trim() || !token}
|
||||
>
|
||||
Add host
|
||||
</Button>
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* General */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
@@ -9,7 +9,6 @@ import { EnvEditor } from "@/components/env/EnvEditor";
|
||||
import { PortConflictDialog } from "@/components/stacks/PortConflictDialog";
|
||||
import { DeployConsole } from "@/components/stacks/DeployConsole";
|
||||
import { stacksApi } from "@/api/stacks";
|
||||
import { agentsApi } from "@/api/agents";
|
||||
import { editorApi } from "@/api/editor";
|
||||
import { portsApi, type PortConflict } from "@/api/ports";
|
||||
import { apiErrorMessage } from "@/api/client";
|
||||
@@ -41,9 +40,7 @@ export function StackEditor() {
|
||||
const [runCmd, setRunCmd] = useState("");
|
||||
const [conflicts, setConflicts] = useState<PortConflict[] | null>(null);
|
||||
const [checking, setChecking] = useState(false);
|
||||
const [host, setHost] = useState("local");
|
||||
const [deployId, setDeployId] = useState<string | null>(null);
|
||||
const [deployAgentId, setDeployAgentId] = useState<number | undefined>(undefined);
|
||||
const [validating, setValidating] = useState(false);
|
||||
const [validation, setValidation] = useState<{ ok: boolean; errors: string } | null>(null);
|
||||
const [showDiff, setShowDiff] = useState(false);
|
||||
@@ -54,13 +51,6 @@ export function StackEditor() {
|
||||
enabled: !isNew,
|
||||
});
|
||||
|
||||
const agents = useQuery({
|
||||
queryKey: ["agents"],
|
||||
queryFn: () => agentsApi.list(),
|
||||
enabled: isNew,
|
||||
});
|
||||
const onlineAgents = (agents.data ?? []).filter((a) => a.status === "online");
|
||||
const remote = isNew && host !== "local";
|
||||
|
||||
useEffect(() => {
|
||||
if (existing.data) {
|
||||
@@ -78,22 +68,6 @@ export function StackEditor() {
|
||||
}
|
||||
setSaving(true);
|
||||
try {
|
||||
// Remote host: create the stack on the agent, then optionally start it.
|
||||
if (remote) {
|
||||
const aid = Number(host);
|
||||
const created = await agentsApi.createStack(aid, { name, yaml, env });
|
||||
qc.invalidateQueries({ queryKey: ["agent-stacks", aid] });
|
||||
toast.success("Saved");
|
||||
if (deploy) {
|
||||
// Stream the remote deploy live through the agent-deploy WS proxy.
|
||||
setDeployAgentId(aid);
|
||||
setDeployId(created.id);
|
||||
return;
|
||||
}
|
||||
navigate(`/hosts/${aid}/stacks/${created.id}`);
|
||||
return;
|
||||
}
|
||||
|
||||
let stackId = id;
|
||||
if (isNew) {
|
||||
const created = await stacksApi.create({ name, description, yaml, env });
|
||||
@@ -119,11 +93,6 @@ export function StackEditor() {
|
||||
};
|
||||
|
||||
const onDeploy = async () => {
|
||||
// The local port-conflict check doesn't apply to remote hosts.
|
||||
if (remote) {
|
||||
save(true);
|
||||
return;
|
||||
}
|
||||
setChecking(true);
|
||||
try {
|
||||
const found = await portsApi.conflicts(yaml, id);
|
||||
@@ -188,21 +157,6 @@ export function StackEditor() {
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
/>
|
||||
{isNew && onlineAgents.length > 0 && (
|
||||
<select
|
||||
value={host}
|
||||
onChange={(e) => setHost(e.target.value)}
|
||||
className="rounded-lg border border-slate-300 bg-white px-3 py-2 text-sm dark:border-slate-600 dark:bg-slate-800"
|
||||
title="Target host"
|
||||
>
|
||||
<option value="local">This host</option>
|
||||
{onlineAgents.map((a) => (
|
||||
<option key={a.id} value={String(a.id)}>
|
||||
{a.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
<Button variant="outline" onClick={() => setConvertOpen((v) => !v)}>
|
||||
<Wand2 className="h-4 w-4" /> Convert docker run
|
||||
</Button>
|
||||
@@ -312,20 +266,12 @@ export function StackEditor() {
|
||||
{deployId && (
|
||||
<DeployConsole
|
||||
stackId={deployId}
|
||||
agentId={deployAgentId}
|
||||
onClose={() => {
|
||||
const sid = deployId;
|
||||
const aid = deployAgentId;
|
||||
setDeployId(null);
|
||||
setDeployAgentId(undefined);
|
||||
if (aid != null) {
|
||||
qc.invalidateQueries({ queryKey: ["agent-stacks", aid] });
|
||||
navigate(`/hosts/${aid}/stacks/${sid}`);
|
||||
} else {
|
||||
qc.invalidateQueries({ queryKey: ["stacks"] });
|
||||
qc.invalidateQueries({ queryKey: ["stack", sid] });
|
||||
navigate(`/stacks/${sid}`);
|
||||
}
|
||||
qc.invalidateQueries({ queryKey: ["stacks"] });
|
||||
qc.invalidateQueries({ queryKey: ["stack", sid] });
|
||||
navigate(`/stacks/${sid}`);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -1,14 +1,12 @@
|
||||
import { useMemo, useState } from "react";
|
||||
import { Link, useSearchParams } from "react-router-dom";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { Plus, Search, HardDrive } from "lucide-react";
|
||||
import { Plus, Search } from "lucide-react";
|
||||
import { Button, Input } from "@/components/ui";
|
||||
import { StacksTable } from "@/components/stacks/StacksTable";
|
||||
import { RestoreButton } from "@/components/stacks/BackupRestore";
|
||||
import { AgentStacksSection } from "@/components/stacks/AgentStacksSection";
|
||||
import { stacksApi } from "@/api/stacks";
|
||||
import { systemApi } from "@/api/system";
|
||||
import { agentsApi } from "@/api/agents";
|
||||
import { useAuthStore } from "@/store/auth";
|
||||
import { useStackActions } from "@/hooks/useStackActions";
|
||||
|
||||
@@ -55,12 +53,6 @@ export function Stacks() {
|
||||
refetchInterval: 5000,
|
||||
});
|
||||
|
||||
const agents = useQuery({
|
||||
queryKey: ["agents"],
|
||||
queryFn: () => agentsApi.list(),
|
||||
refetchInterval: 15000,
|
||||
});
|
||||
const hasAgents = (agents.data?.length ?? 0) > 0;
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
let list = (data ?? []).filter(
|
||||
@@ -125,11 +117,6 @@ export function Stacks() {
|
||||
</div>
|
||||
|
||||
<section>
|
||||
{hasAgents && (
|
||||
<h2 className="mb-3 flex items-center gap-2 text-sm font-semibold uppercase tracking-wide text-slate-500">
|
||||
<HardDrive className="h-4 w-4" /> This host
|
||||
</h2>
|
||||
)}
|
||||
<StacksTable
|
||||
stacks={filtered}
|
||||
stats={stats.data}
|
||||
@@ -150,10 +137,6 @@ export function Stacks() {
|
||||
emptyText={q ? "No stacks match your search." : "No stacks yet. Create one with “New Stack”."}
|
||||
/>
|
||||
</section>
|
||||
|
||||
{agents.data?.map((agent) => (
|
||||
<AgentStacksSection key={agent.id} agent={agent} isAdmin={isAdmin} />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -5,14 +5,10 @@ import { LayoutTemplate, Cpu, Package, Trash2, FileCode, Search } from "lucide-r
|
||||
import { Badge, Button, Card, Input, Spinner } from "@/components/ui";
|
||||
import { ConfirmDialog } from "@/components/ui/ConfirmDialog";
|
||||
import { templatesApi, type TemplateDetail, type TemplateSummary } from "@/api/templates";
|
||||
import { agentsApi } from "@/api/agents";
|
||||
import { apiErrorMessage } from "@/api/client";
|
||||
import { useAuthStore } from "@/store/auth";
|
||||
import { toast } from "sonner";
|
||||
|
||||
const selectClass =
|
||||
"w-full rounded-lg border border-slate-300 bg-white px-3 py-2 text-sm dark:border-slate-600 dark:bg-slate-800";
|
||||
|
||||
export function Templates() {
|
||||
const isAdmin = useAuthStore((s) => s.user?.role === "admin");
|
||||
const queryClient = useQueryClient();
|
||||
@@ -198,12 +194,8 @@ function UseTemplateDialog({
|
||||
}) {
|
||||
const navigate = useNavigate();
|
||||
const [name, setName] = useState(template.name);
|
||||
const [host, setHost] = useState("local");
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const agents = useQuery({ queryKey: ["agents"], queryFn: () => agentsApi.list() });
|
||||
const onlineAgents = (agents.data ?? []).filter((a) => a.status === "online");
|
||||
|
||||
const create = async () => {
|
||||
if (!name.trim()) {
|
||||
toast.error("Stack name required");
|
||||
@@ -211,11 +203,9 @@ function UseTemplateDialog({
|
||||
}
|
||||
setBusy(true);
|
||||
try {
|
||||
const agentId = host === "local" ? null : Number(host);
|
||||
const res = await templatesApi.instantiate(template.id, name, agentId);
|
||||
const res = await templatesApi.instantiate(template.id, name);
|
||||
toast.success(`Stack '${res.name}' created`);
|
||||
if (res.agent_id != null) navigate(`/hosts/${res.agent_id}/stacks/${res.id}`);
|
||||
else navigate(`/stacks/${res.id}/edit`);
|
||||
navigate(`/stacks/${res.id}/edit`);
|
||||
} catch (e) {
|
||||
toast.error(apiErrorMessage(e));
|
||||
} finally {
|
||||
@@ -232,20 +222,6 @@ function UseTemplateDialog({
|
||||
<span className="text-xs font-medium text-slate-500">Stack name</span>
|
||||
<Input value={name} onChange={(e) => setName(e.target.value)} />
|
||||
</label>
|
||||
{onlineAgents.length > 0 && (
|
||||
<label className="block space-y-1">
|
||||
<span className="text-xs font-medium text-slate-500">Deploy to host</span>
|
||||
<select className={selectClass} value={host} onChange={(e) => setHost(e.target.value)}>
|
||||
<option value="local">This host</option>
|
||||
{onlineAgents.map((a) => (
|
||||
<option key={a.id} value={String(a.id)}>
|
||||
{a.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
|
||||
{template.files.length > 0 && (
|
||||
<div className="space-y-1">
|
||||
<span className="text-xs font-medium text-slate-500">Files</span>
|
||||
|
||||
@@ -4,66 +4,39 @@ import { Database, Trash2, Eraser, HardDrive } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import { Badge, Button, Card, Spinner } from "@/components/ui";
|
||||
import { ConfirmDialog } from "@/components/ui/ConfirmDialog";
|
||||
import { HostHeader } from "@/components/hosts/HostHeader";
|
||||
import { volumesApi } from "@/api/volumes";
|
||||
import { agentsApi } from "@/api/agents";
|
||||
import { apiErrorMessage } from "@/api/client";
|
||||
import { useAuthStore } from "@/store/auth";
|
||||
import { formatBytes } from "@/lib/utils";
|
||||
import type { Agent, VolumeInfo } from "@/types";
|
||||
import type { VolumeInfo } from "@/types";
|
||||
|
||||
export function Volumes() {
|
||||
const isAdmin = useAuthStore((s) => s.user?.role === "admin");
|
||||
const agents = useQuery({
|
||||
queryKey: ["agents"],
|
||||
queryFn: () => agentsApi.list(),
|
||||
refetchInterval: 15000,
|
||||
});
|
||||
const hasAgents = (agents.data?.length ?? 0) > 0;
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<VolumesSection isAdmin={isAdmin} showHostLabel={hasAgents} />
|
||||
{agents.data?.map((agent) => (
|
||||
<VolumesSection key={agent.id} agent={agent} isAdmin={isAdmin} showHostLabel />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
return <VolumesSection isAdmin={isAdmin} />;
|
||||
}
|
||||
|
||||
function VolumesSection({
|
||||
agent,
|
||||
isAdmin,
|
||||
showHostLabel,
|
||||
}: {
|
||||
agent?: Agent;
|
||||
isAdmin: boolean;
|
||||
showHostLabel: boolean;
|
||||
}) {
|
||||
const agentId = agent?.id;
|
||||
const online = !agent || agent.status === "online";
|
||||
function VolumesSection({ isAdmin }: { isAdmin: boolean }) {
|
||||
const qc = useQueryClient();
|
||||
const [onlyUnused, setOnlyUnused] = useState(false);
|
||||
const [toDelete, setToDelete] = useState<VolumeInfo | null>(null);
|
||||
const [force, setForce] = useState(false);
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey: ["volumes", agentId ?? "local"],
|
||||
queryFn: () => volumesApi.list(agentId),
|
||||
queryKey: ["volumes"],
|
||||
queryFn: () => volumesApi.list(),
|
||||
refetchInterval: 10000,
|
||||
enabled: online,
|
||||
});
|
||||
// Sizes are expensive (docker system df walks volume contents), so they are
|
||||
// loaded on demand via the "Compute sizes" button rather than polled.
|
||||
const sizes = useQuery({
|
||||
queryKey: ["volume-sizes", agentId ?? "local"],
|
||||
queryFn: () => volumesApi.sizes(false, agentId),
|
||||
queryKey: ["volume-sizes"],
|
||||
queryFn: () => volumesApi.sizes(false),
|
||||
enabled: false,
|
||||
});
|
||||
const invalidate = () => qc.invalidateQueries({ queryKey: ["volumes", agentId ?? "local"] });
|
||||
const invalidate = () => qc.invalidateQueries({ queryKey: ["volumes"] });
|
||||
|
||||
const prune = useMutation({
|
||||
mutationFn: () => volumesApi.prune(agentId),
|
||||
mutationFn: () => volumesApi.prune(),
|
||||
onSuccess: (r) => {
|
||||
const n = r.VolumesDeleted?.length ?? 0;
|
||||
toast.success(n ? `Pruned ${n} volume(s)` : "No unused volumes");
|
||||
@@ -72,7 +45,7 @@ function VolumesSection({
|
||||
onError: (e) => toast.error(apiErrorMessage(e)),
|
||||
});
|
||||
const remove = useMutation({
|
||||
mutationFn: (v: VolumeInfo) => volumesApi.remove(v.name, force, agentId),
|
||||
mutationFn: (v: VolumeInfo) => volumesApi.remove(v.name, force),
|
||||
onSuccess: () => {
|
||||
toast.success("Volume deleted");
|
||||
setToDelete(null);
|
||||
@@ -87,42 +60,32 @@ function VolumesSection({
|
||||
|
||||
return (
|
||||
<section>
|
||||
{(showHostLabel || (isAdmin && online)) && (
|
||||
<HostHeader agent={agent}>
|
||||
<label className="flex items-center gap-1.5 text-xs text-slate-500">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={onlyUnused}
|
||||
onChange={(e) => setOnlyUnused(e.target.checked)}
|
||||
className="h-3.5 w-3.5"
|
||||
/>
|
||||
Only unused
|
||||
</label>
|
||||
{online && (
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => sizes.refetch()}
|
||||
loading={sizes.isFetching}
|
||||
title="Runs docker system df — can take a few seconds"
|
||||
>
|
||||
<HardDrive className="h-4 w-4" /> Compute sizes
|
||||
</Button>
|
||||
)}
|
||||
{isAdmin && online && (
|
||||
<Button variant="outline" onClick={() => prune.mutate()} loading={prune.isPending}>
|
||||
<Eraser className="h-4 w-4" /> Prune unused
|
||||
</Button>
|
||||
)}
|
||||
</HostHeader>
|
||||
)}
|
||||
<div className="mb-3 flex flex-wrap items-center justify-end gap-2">
|
||||
<label className="flex items-center gap-1.5 text-xs text-slate-500">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={onlyUnused}
|
||||
onChange={(e) => setOnlyUnused(e.target.checked)}
|
||||
className="h-3.5 w-3.5"
|
||||
/>
|
||||
Only unused
|
||||
</label>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => sizes.refetch()}
|
||||
loading={sizes.isFetching}
|
||||
title="Runs docker system df — can take a few seconds"
|
||||
>
|
||||
<HardDrive className="h-4 w-4" /> Compute sizes
|
||||
</Button>
|
||||
{isAdmin && (
|
||||
<Button variant="outline" onClick={() => prune.mutate()} loading={prune.isPending}>
|
||||
<Eraser className="h-4 w-4" /> Prune unused
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{!online ? (
|
||||
<Card>
|
||||
<p className="text-sm text-slate-500">
|
||||
Host is {agent?.status}. Check it under Settings → Remote hosts.
|
||||
</p>
|
||||
</Card>
|
||||
) : isLoading ? (
|
||||
{isLoading ? (
|
||||
<Spinner />
|
||||
) : (
|
||||
<Card className="overflow-x-auto p-0">
|
||||
|
||||
@@ -15,9 +15,6 @@ export interface StackSummary {
|
||||
running_count: number;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
// present on stacks proxied from a remote host
|
||||
agent_id?: number;
|
||||
agent_name?: string;
|
||||
}
|
||||
|
||||
export interface StackUpdateInfo {
|
||||
@@ -33,17 +30,6 @@ export interface StackStats {
|
||||
containers: number;
|
||||
}
|
||||
|
||||
export interface Agent {
|
||||
id: number;
|
||||
name: string;
|
||||
url: string;
|
||||
status: "online" | "offline" | "unauthorized" | "unknown";
|
||||
hostname?: string | null;
|
||||
last_seen?: string | null;
|
||||
created_at: string;
|
||||
token_set: boolean;
|
||||
}
|
||||
|
||||
export interface ContainerInfo {
|
||||
id: string;
|
||||
name: string;
|
||||
|
||||
Reference in New Issue
Block a user