platypus-server 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- dashboard/__init__.py +11 -0
- dashboard/__main__.py +6 -0
- dashboard/app.py +498 -0
- dashboard/auth.py +35 -0
- dashboard/compose.py +102 -0
- dashboard/dockerctl.py +152 -0
- dashboard/firewall.py +57 -0
- dashboard/metrics.py +132 -0
- dashboard/services.py +18 -0
- dashboard/static/index.html +620 -0
- dashboard/static/login.html +136 -0
- dashboard/systemd.py +72 -0
- doctor.py +354 -0
- platypus_cli/__init__.py +1 -0
- platypus_cli/cli.py +60 -0
- platypus_server-0.2.0.dist-info/METADATA +497 -0
- platypus_server-0.2.0.dist-info/RECORD +63 -0
- platypus_server-0.2.0.dist-info/WHEEL +5 -0
- platypus_server-0.2.0.dist-info/entry_points.txt +7 -0
- platypus_server-0.2.0.dist-info/licenses/LICENSE +21 -0
- platypus_server-0.2.0.dist-info/top_level.txt +6 -0
- recipe/__init__.py +2 -0
- recipe/caddy.py +145 -0
- recipe/cli.py +216 -0
- recipe/model.py +143 -0
- recipe/renderer.py +86 -0
- recipe/roles/assetto-corsa/questions.yml +58 -0
- recipe/roles/assetto-corsa/template.yml +51 -0
- recipe/roles/jellyfin/questions.yml +28 -0
- recipe/roles/jellyfin/template.yml +38 -0
- recipe/roles/minecraft-server/questions.yml +42 -0
- recipe/roles/minecraft-server/template.yml +62 -0
- recipe/roles/pihole/questions.yml +33 -0
- recipe/roles/pihole/template.yml +45 -0
- recipe/roles/storage-nextcloud/questions.yml +34 -0
- recipe/roles/storage-nextcloud/template.yml +73 -0
- recipe/roles/storage-samba/questions.yml +24 -0
- recipe/roles/storage-samba/template.yml +36 -0
- recipe/roles/syncthing/questions.yml +23 -0
- recipe/roles/syncthing/template.yml +39 -0
- recipe/shutdown.py +168 -0
- recipe/state.py +119 -0
- recipe/transition.py +338 -0
- tui/__init__.py +11 -0
- tui/__main__.py +6 -0
- tui/app.py +823 -0
- tui/settings.py +110 -0
- tui/tasks/__init__.py +101 -0
- tui/tasks/backup.py +84 -0
- tui/tasks/base.py +23 -0
- tui/tasks/caddy.py +37 -0
- tui/tasks/docker.py +35 -0
- tui/tasks/firewall.py +30 -0
- tui/tasks/packages.py +138 -0
- tui/tasks/ssh.py +35 -0
- tui/tasks/sysupdate.py +44 -0
- tui/tasks/vpn.py +63 -0
- zero2server/__init__.py +11 -0
- zero2server/__main__.py +6 -0
- zero2server/catalog.py +95 -0
- zero2server/cli.py +157 -0
- zero2server/generator.py +110 -0
- zero2server/runner.py +101 -0
dashboard/__init__.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""Web-based mini dashboard package."""
|
|
2
|
+
|
|
3
|
+
try:
|
|
4
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
5
|
+
|
|
6
|
+
try:
|
|
7
|
+
__version__ = version("platypus-server")
|
|
8
|
+
except PackageNotFoundError:
|
|
9
|
+
__version__ = "unknown"
|
|
10
|
+
except ImportError: # pragma: no cover
|
|
11
|
+
__version__ = "unknown"
|
dashboard/__main__.py
ADDED
dashboard/app.py
ADDED
|
@@ -0,0 +1,498 @@
|
|
|
1
|
+
"""Flask app serving the Platypus dashboard and its REST API."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import os
|
|
5
|
+
import socket
|
|
6
|
+
import threading
|
|
7
|
+
import time
|
|
8
|
+
import urllib.request
|
|
9
|
+
from datetime import datetime, timezone
|
|
10
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
11
|
+
|
|
12
|
+
from flask import Flask, jsonify, redirect, request, send_from_directory, session, url_for
|
|
13
|
+
|
|
14
|
+
from . import compose, dockerctl, firewall, metrics, systemd
|
|
15
|
+
from . import __version__ as _DASHBOARD_VERSION
|
|
16
|
+
from .auth import (
|
|
17
|
+
USING_DEFAULT_CREDENTIALS,
|
|
18
|
+
check_credentials,
|
|
19
|
+
is_authenticated,
|
|
20
|
+
login_required,
|
|
21
|
+
)
|
|
22
|
+
from .services import get_services
|
|
23
|
+
|
|
24
|
+
# ---------------------------------------------------------------------------
|
|
25
|
+
# App setup
|
|
26
|
+
# ---------------------------------------------------------------------------
|
|
27
|
+
|
|
28
|
+
app = Flask(__name__, static_folder="static", static_url_path="/static")
|
|
29
|
+
app.secret_key = os.environ.get(
|
|
30
|
+
"DASHBOARD_SECRET_KEY", "platypus-dashboard-secret-change-me"
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
# Record the start time for the /health uptime field.
|
|
34
|
+
_APP_START: float = time.monotonic()
|
|
35
|
+
_APP_START_UTC: datetime = datetime.now(timezone.utc)
|
|
36
|
+
|
|
37
|
+
CHECK_TIMEOUT = 1.5
|
|
38
|
+
|
|
39
|
+
# ---------------------------------------------------------------------------
|
|
40
|
+
# Background metrics recorder
|
|
41
|
+
# ---------------------------------------------------------------------------
|
|
42
|
+
|
|
43
|
+
def _start_metrics_recorder() -> None:
|
|
44
|
+
"""Record CPU + memory into the history ringbuffer every 3 seconds."""
|
|
45
|
+
def _loop() -> None:
|
|
46
|
+
while True:
|
|
47
|
+
try:
|
|
48
|
+
m = metrics.get_metrics()
|
|
49
|
+
metrics.history.record(
|
|
50
|
+
m["cpu_percent"],
|
|
51
|
+
m["memory"]["percent"],
|
|
52
|
+
)
|
|
53
|
+
except Exception: # noqa: BLE001
|
|
54
|
+
pass
|
|
55
|
+
time.sleep(3)
|
|
56
|
+
|
|
57
|
+
t = threading.Thread(target=_loop, daemon=True, name="metrics-recorder")
|
|
58
|
+
t.start()
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
_start_metrics_recorder()
|
|
62
|
+
|
|
63
|
+
# ---------------------------------------------------------------------------
|
|
64
|
+
# Service health helpers
|
|
65
|
+
# ---------------------------------------------------------------------------
|
|
66
|
+
|
|
67
|
+
def _http_check(url: str) -> int | None:
|
|
68
|
+
try:
|
|
69
|
+
with urllib.request.urlopen(url, timeout=CHECK_TIMEOUT) as resp:
|
|
70
|
+
return resp.status
|
|
71
|
+
except Exception: # noqa: BLE001
|
|
72
|
+
return None
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _tcp_check(host: str, port: int) -> bool:
|
|
76
|
+
try:
|
|
77
|
+
with socket.create_connection((host, port), timeout=CHECK_TIMEOUT):
|
|
78
|
+
return True
|
|
79
|
+
except OSError:
|
|
80
|
+
return False
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _check_service(svc: dict) -> dict:
|
|
84
|
+
if "url" in svc:
|
|
85
|
+
code = _http_check(svc["url"])
|
|
86
|
+
return {
|
|
87
|
+
"name": svc["name"],
|
|
88
|
+
"url": svc["url"],
|
|
89
|
+
"status": "up" if code is not None else "down",
|
|
90
|
+
"http_code": code,
|
|
91
|
+
}
|
|
92
|
+
host = svc.get("host", "localhost")
|
|
93
|
+
port = svc.get("port")
|
|
94
|
+
up = port is not None and _tcp_check(host, port)
|
|
95
|
+
return {
|
|
96
|
+
"name": svc["name"],
|
|
97
|
+
"url": f"{host}:{port}" if port is not None else host,
|
|
98
|
+
"status": "up" if up else ("down" if port is not None else "unknown"),
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _snapshot() -> dict:
|
|
103
|
+
items = get_services()
|
|
104
|
+
with ThreadPoolExecutor(max_workers=len(items) or 1) as pool:
|
|
105
|
+
services = list(pool.map(_check_service, items))
|
|
106
|
+
return {"metrics": metrics.get_metrics(), "services": services}
|
|
107
|
+
|
|
108
|
+
# ---------------------------------------------------------------------------
|
|
109
|
+
# Public health endpoint — no auth required (for monitoring tools)
|
|
110
|
+
# ---------------------------------------------------------------------------
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
@app.get("/health")
|
|
114
|
+
def health():
|
|
115
|
+
"""Lightweight health check used by Uptime Kuma, Prometheus, etc.
|
|
116
|
+
|
|
117
|
+
Always returns HTTP 200. The ``status`` field signals application health:
|
|
118
|
+
- ``"ok"`` — everything is within normal thresholds
|
|
119
|
+
- ``"degraded"`` — CPU > 95 % or disk > 90 %
|
|
120
|
+
"""
|
|
121
|
+
try:
|
|
122
|
+
m = metrics.get_metrics()
|
|
123
|
+
cpu: float = m.get("cpu_percent", 0.0)
|
|
124
|
+
mem: float = m.get("memory", {}).get("percent", 0.0)
|
|
125
|
+
disk: float = m.get("disk", {}).get("percent", 0.0)
|
|
126
|
+
except Exception: # noqa: BLE001
|
|
127
|
+
cpu = mem = disk = 0.0
|
|
128
|
+
|
|
129
|
+
degraded = cpu > 95.0 or disk > 90.0
|
|
130
|
+
uptime_seconds = round(time.monotonic() - _APP_START)
|
|
131
|
+
|
|
132
|
+
return jsonify(
|
|
133
|
+
{
|
|
134
|
+
"status": "degraded" if degraded else "ok",
|
|
135
|
+
"version": _DASHBOARD_VERSION,
|
|
136
|
+
"uptime_seconds": uptime_seconds,
|
|
137
|
+
"started_at": _APP_START_UTC.isoformat(),
|
|
138
|
+
"checks": {
|
|
139
|
+
"cpu_percent": round(cpu, 1),
|
|
140
|
+
"memory_percent": round(mem, 1),
|
|
141
|
+
"disk_percent": round(disk, 1),
|
|
142
|
+
},
|
|
143
|
+
"timestamp": datetime.now(timezone.utc).isoformat(),
|
|
144
|
+
}
|
|
145
|
+
)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
# ---------------------------------------------------------------------------
|
|
149
|
+
# Auth routes (public)
|
|
150
|
+
# ---------------------------------------------------------------------------
|
|
151
|
+
|
|
152
|
+
@app.get("/login")
|
|
153
|
+
def login_page():
|
|
154
|
+
if is_authenticated():
|
|
155
|
+
return redirect(url_for("index"))
|
|
156
|
+
return send_from_directory(app.static_folder, "login.html")
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
@app.post("/api/login")
|
|
160
|
+
def api_login():
|
|
161
|
+
data = request.get_json(silent=True) or {}
|
|
162
|
+
if check_credentials(
|
|
163
|
+
(data.get("username") or "").strip(),
|
|
164
|
+
(data.get("password") or ""),
|
|
165
|
+
):
|
|
166
|
+
session["authenticated"] = True
|
|
167
|
+
return jsonify({"ok": True})
|
|
168
|
+
return jsonify({"error": "Invalid credentials"}), 401
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
@app.get("/api/logout")
|
|
172
|
+
@app.post("/api/logout")
|
|
173
|
+
def api_logout():
|
|
174
|
+
session.clear()
|
|
175
|
+
return redirect(url_for("login_page"))
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
@app.get("/api/auth/info")
|
|
179
|
+
def api_auth_info():
|
|
180
|
+
"""Public endpoint — returns whether default credentials are active."""
|
|
181
|
+
return jsonify({"default_credentials": USING_DEFAULT_CREDENTIALS})
|
|
182
|
+
|
|
183
|
+
# ---------------------------------------------------------------------------
|
|
184
|
+
# Main page
|
|
185
|
+
# ---------------------------------------------------------------------------
|
|
186
|
+
|
|
187
|
+
@app.get("/")
|
|
188
|
+
@login_required
|
|
189
|
+
def index():
|
|
190
|
+
return send_from_directory(app.static_folder, "index.html")
|
|
191
|
+
|
|
192
|
+
# ---------------------------------------------------------------------------
|
|
193
|
+
# System metrics
|
|
194
|
+
# ---------------------------------------------------------------------------
|
|
195
|
+
|
|
196
|
+
@app.get("/api/status")
|
|
197
|
+
@login_required
|
|
198
|
+
def status():
|
|
199
|
+
return jsonify(_snapshot())
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
@app.get("/api/metrics/history")
|
|
203
|
+
@login_required
|
|
204
|
+
def api_metrics_history():
|
|
205
|
+
points = request.args.get("points", 200, type=int)
|
|
206
|
+
return jsonify(metrics.history.snapshot(points=points))
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
@app.get("/api/processes")
|
|
210
|
+
@login_required
|
|
211
|
+
def api_processes():
|
|
212
|
+
limit = request.args.get("limit", 20, type=int)
|
|
213
|
+
return jsonify({"processes": metrics.get_processes(limit=limit)})
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
@app.get("/api/firewall")
|
|
217
|
+
@login_required
|
|
218
|
+
def api_firewall():
|
|
219
|
+
return jsonify(firewall.get_firewall_rules())
|
|
220
|
+
|
|
221
|
+
# ---------------------------------------------------------------------------
|
|
222
|
+
# Container management
|
|
223
|
+
# ---------------------------------------------------------------------------
|
|
224
|
+
|
|
225
|
+
@app.get("/api/containers")
|
|
226
|
+
@login_required
|
|
227
|
+
def api_containers():
|
|
228
|
+
try:
|
|
229
|
+
return jsonify({"containers": dockerctl.list_containers()})
|
|
230
|
+
except dockerctl.DockerError as exc:
|
|
231
|
+
return jsonify({"error": str(exc)}), 500
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
@app.get("/api/images")
|
|
235
|
+
@login_required
|
|
236
|
+
def api_images():
|
|
237
|
+
try:
|
|
238
|
+
return jsonify({"images": dockerctl.list_images()})
|
|
239
|
+
except dockerctl.DockerError as exc:
|
|
240
|
+
return jsonify({"error": str(exc)}), 500
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
@app.post("/api/containers")
|
|
244
|
+
@login_required
|
|
245
|
+
def api_run_container():
|
|
246
|
+
payload = request.get_json(silent=True) or {}
|
|
247
|
+
image = (payload.get("image") or "").strip()
|
|
248
|
+
if not image:
|
|
249
|
+
return jsonify({"error": "image is required"}), 400
|
|
250
|
+
try:
|
|
251
|
+
cid = dockerctl.run_container(
|
|
252
|
+
image,
|
|
253
|
+
name=(payload.get("name") or "").strip() or None,
|
|
254
|
+
ports=(payload.get("ports") or "").strip() or None,
|
|
255
|
+
)
|
|
256
|
+
return jsonify({"ok": True, "id": cid})
|
|
257
|
+
except dockerctl.DockerError as exc:
|
|
258
|
+
return jsonify({"error": str(exc)}), 500
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
@app.post("/api/containers/<cid>/<action>")
|
|
262
|
+
@login_required
|
|
263
|
+
def api_container_action(cid: str, action: str):
|
|
264
|
+
actions = {
|
|
265
|
+
"start": dockerctl.start_container,
|
|
266
|
+
"stop": dockerctl.stop_container,
|
|
267
|
+
"restart": dockerctl.restart_container,
|
|
268
|
+
}
|
|
269
|
+
if action not in actions:
|
|
270
|
+
return jsonify({"error": "unknown action"}), 400
|
|
271
|
+
try:
|
|
272
|
+
actions[action](cid)
|
|
273
|
+
return jsonify({"ok": True})
|
|
274
|
+
except dockerctl.DockerError as exc:
|
|
275
|
+
return jsonify({"error": str(exc)}), 500
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
@app.delete("/api/containers/<cid>")
|
|
279
|
+
@login_required
|
|
280
|
+
def api_remove_container(cid: str):
|
|
281
|
+
try:
|
|
282
|
+
dockerctl.remove_container(cid)
|
|
283
|
+
return jsonify({"ok": True})
|
|
284
|
+
except dockerctl.DockerError as exc:
|
|
285
|
+
return jsonify({"error": str(exc)}), 500
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
@app.get("/api/containers/<cid>/logs")
|
|
289
|
+
@login_required
|
|
290
|
+
def api_container_logs(cid: str):
|
|
291
|
+
tail = request.args.get("tail", 200, type=int)
|
|
292
|
+
try:
|
|
293
|
+
return jsonify({"lines": dockerctl.get_container_logs(cid, tail=tail)})
|
|
294
|
+
except dockerctl.DockerError as exc:
|
|
295
|
+
return jsonify({"error": str(exc)}), 500
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
@app.get("/api/containers/<cid>/stats")
|
|
299
|
+
@login_required
|
|
300
|
+
def api_container_stats(cid: str):
|
|
301
|
+
try:
|
|
302
|
+
return jsonify(dockerctl.get_container_stats(cid))
|
|
303
|
+
except dockerctl.DockerError as exc:
|
|
304
|
+
return jsonify({"error": str(exc)}), 500
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
@app.post("/api/images/pull")
|
|
308
|
+
@login_required
|
|
309
|
+
def api_pull_image():
|
|
310
|
+
payload = request.get_json(silent=True) or {}
|
|
311
|
+
name = (payload.get("image") or "").strip()
|
|
312
|
+
if not name:
|
|
313
|
+
return jsonify({"error": "image is required"}), 400
|
|
314
|
+
try:
|
|
315
|
+
msg = dockerctl.pull_image(name)
|
|
316
|
+
return jsonify({"ok": True, "message": msg})
|
|
317
|
+
except dockerctl.DockerError as exc:
|
|
318
|
+
return jsonify({"error": str(exc)}), 500
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
@app.delete("/api/images/<image_id>")
|
|
322
|
+
@login_required
|
|
323
|
+
def api_remove_image(image_id: str):
|
|
324
|
+
force = request.args.get("force", "false").lower() == "true"
|
|
325
|
+
try:
|
|
326
|
+
dockerctl.remove_image(image_id, force=force)
|
|
327
|
+
return jsonify({"ok": True})
|
|
328
|
+
except dockerctl.DockerError as exc:
|
|
329
|
+
return jsonify({"error": str(exc)}), 500
|
|
330
|
+
|
|
331
|
+
# ---------------------------------------------------------------------------
|
|
332
|
+
# Docker Compose stacks
|
|
333
|
+
# ---------------------------------------------------------------------------
|
|
334
|
+
|
|
335
|
+
@app.get("/api/compose")
|
|
336
|
+
@login_required
|
|
337
|
+
def api_compose_list():
|
|
338
|
+
try:
|
|
339
|
+
return jsonify({"stacks": compose.list_stacks()})
|
|
340
|
+
except compose.ComposeError as exc:
|
|
341
|
+
return jsonify({"error": str(exc)}), 500
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
@app.post("/api/compose/<stack>/<action>")
|
|
345
|
+
@login_required
|
|
346
|
+
def api_compose_action(stack: str, action: str):
|
|
347
|
+
try:
|
|
348
|
+
msg = compose.stack_action(stack, action)
|
|
349
|
+
return jsonify({"ok": True, "message": msg})
|
|
350
|
+
except compose.ComposeError as exc:
|
|
351
|
+
return jsonify({"error": str(exc)}), 500
|
|
352
|
+
|
|
353
|
+
# ---------------------------------------------------------------------------
|
|
354
|
+
# Systemd service management
|
|
355
|
+
# ---------------------------------------------------------------------------
|
|
356
|
+
|
|
357
|
+
@app.get("/api/systemd")
|
|
358
|
+
@login_required
|
|
359
|
+
def api_systemd_list():
|
|
360
|
+
units = [
|
|
361
|
+
svc.get("systemd")
|
|
362
|
+
for svc in get_services()
|
|
363
|
+
if svc.get("systemd")
|
|
364
|
+
]
|
|
365
|
+
# Also include well-known platform services if not already listed
|
|
366
|
+
defaults = ["docker", "caddy", "ssh", "ufw", "tailscaled", "wg-quick@wg0"]
|
|
367
|
+
for u in defaults:
|
|
368
|
+
if u not in units:
|
|
369
|
+
units.append(u)
|
|
370
|
+
statuses = []
|
|
371
|
+
for unit in units:
|
|
372
|
+
try:
|
|
373
|
+
statuses.append(systemd.get_service_status(unit))
|
|
374
|
+
except systemd.SystemdError as exc:
|
|
375
|
+
statuses.append({"unit": unit, "active": "unknown", "error": str(exc)})
|
|
376
|
+
return jsonify({"services": statuses})
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
@app.post("/api/systemd/<unit>/<action>")
|
|
380
|
+
@login_required
|
|
381
|
+
def api_systemd_action(unit: str, action: str):
|
|
382
|
+
try:
|
|
383
|
+
systemd.service_action(unit, action)
|
|
384
|
+
return jsonify({"ok": True})
|
|
385
|
+
except (systemd.SystemdError, ValueError) as exc:
|
|
386
|
+
return jsonify({"error": str(exc)}), 500
|
|
387
|
+
|
|
388
|
+
# ---------------------------------------------------------------------------
|
|
389
|
+
# Recipe / role status
|
|
390
|
+
# ---------------------------------------------------------------------------
|
|
391
|
+
|
|
392
|
+
@app.get("/api/recipe")
|
|
393
|
+
@login_required
|
|
394
|
+
def api_recipe():
|
|
395
|
+
"""Return active role and dormant roles read from /opt/platypus/state.yml."""
|
|
396
|
+
import os
|
|
397
|
+
from pathlib import Path
|
|
398
|
+
|
|
399
|
+
state_file = Path("/opt/platypus/state.yml")
|
|
400
|
+
roles_dir = Path("/opt/platypus/roles")
|
|
401
|
+
|
|
402
|
+
# Parse state.yml (gracefully handle missing file)
|
|
403
|
+
active_name: str | None = None
|
|
404
|
+
activated_at: str | None = None
|
|
405
|
+
history: list[dict] = []
|
|
406
|
+
|
|
407
|
+
if state_file.exists():
|
|
408
|
+
try:
|
|
409
|
+
import yaml as _yaml
|
|
410
|
+
with state_file.open(encoding="utf-8") as fh:
|
|
411
|
+
raw = _yaml.safe_load(fh) or {}
|
|
412
|
+
active_name = raw.get("active")
|
|
413
|
+
activated_at = str(raw.get("activated_at") or "")
|
|
414
|
+
history = raw.get("history") or []
|
|
415
|
+
except Exception: # noqa: BLE001
|
|
416
|
+
pass
|
|
417
|
+
|
|
418
|
+
def _dir_size_mb(path: Path) -> float:
|
|
419
|
+
total = sum(
|
|
420
|
+
f.stat().st_size
|
|
421
|
+
for f in path.rglob("*")
|
|
422
|
+
if f.is_file()
|
|
423
|
+
)
|
|
424
|
+
return round(total / (1024 * 1024), 1)
|
|
425
|
+
|
|
426
|
+
# Build active entry
|
|
427
|
+
active: dict | None = None
|
|
428
|
+
if active_name:
|
|
429
|
+
data_dir = roles_dir / active_name / "data"
|
|
430
|
+
active = {
|
|
431
|
+
"name": active_name,
|
|
432
|
+
"status": "active",
|
|
433
|
+
"activated_at": activated_at,
|
|
434
|
+
"data_size_mb": _dir_size_mb(data_dir) if data_dir.exists() else 0.0,
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
# Build dormant list
|
|
438
|
+
dormant: list[dict] = []
|
|
439
|
+
if roles_dir.exists():
|
|
440
|
+
for role_dir in sorted(roles_dir.iterdir()):
|
|
441
|
+
if not role_dir.is_dir() or role_dir.name == active_name:
|
|
442
|
+
continue
|
|
443
|
+
data_dir = role_dir / "data"
|
|
444
|
+
answers_file = role_dir / "answers.yml"
|
|
445
|
+
last_active = next(
|
|
446
|
+
(
|
|
447
|
+
h.get("deactivated_at")
|
|
448
|
+
for h in reversed(history)
|
|
449
|
+
if h.get("role") == role_dir.name
|
|
450
|
+
),
|
|
451
|
+
None,
|
|
452
|
+
)
|
|
453
|
+
dormant.append({
|
|
454
|
+
"name": role_dir.name,
|
|
455
|
+
"status": "dormant",
|
|
456
|
+
"configured": answers_file.exists(),
|
|
457
|
+
"last_active": str(last_active) if last_active else None,
|
|
458
|
+
"data_size_mb": _dir_size_mb(data_dir) if data_dir.exists() else 0.0,
|
|
459
|
+
})
|
|
460
|
+
|
|
461
|
+
return jsonify({
|
|
462
|
+
"active": active,
|
|
463
|
+
"dormant": dormant,
|
|
464
|
+
"history": history[-10:], # last 10 transitions
|
|
465
|
+
})
|
|
466
|
+
|
|
467
|
+
|
|
468
|
+
# ---------------------------------------------------------------------------
|
|
469
|
+
# Entry point
|
|
470
|
+
# ---------------------------------------------------------------------------
|
|
471
|
+
|
|
472
|
+
def parse_dashboard_args(argv: list[str] | None = None) -> argparse.Namespace:
|
|
473
|
+
"""Parse dashboard CLI flags; defaults come from the environment."""
|
|
474
|
+
parser = argparse.ArgumentParser(
|
|
475
|
+
prog="platypus dashboard",
|
|
476
|
+
description="Platypus web dashboard.",
|
|
477
|
+
)
|
|
478
|
+
parser.add_argument(
|
|
479
|
+
"--host",
|
|
480
|
+
default=os.environ.get("DASHBOARD_HOST", "0.0.0.0"),
|
|
481
|
+
help="bind address (default: DASHBOARD_HOST env var, else 0.0.0.0)",
|
|
482
|
+
)
|
|
483
|
+
parser.add_argument(
|
|
484
|
+
"--port",
|
|
485
|
+
type=int,
|
|
486
|
+
default=int(os.environ.get("DASHBOARD_PORT", "5050")),
|
|
487
|
+
help="bind port (default: DASHBOARD_PORT env var, else 5050)",
|
|
488
|
+
)
|
|
489
|
+
return parser.parse_args(argv)
|
|
490
|
+
|
|
491
|
+
|
|
492
|
+
def main(argv: list[str] | None = None) -> None:
|
|
493
|
+
args = parse_dashboard_args(argv)
|
|
494
|
+
app.run(host=args.host, port=args.port, debug=False)
|
|
495
|
+
|
|
496
|
+
|
|
497
|
+
if __name__ == "__main__":
|
|
498
|
+
main()
|
dashboard/auth.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""Session-based authentication for the dashboard."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import functools
|
|
5
|
+
import os
|
|
6
|
+
|
|
7
|
+
from flask import jsonify, redirect, request, session, url_for
|
|
8
|
+
|
|
9
|
+
DASHBOARD_USER = os.environ.get("DASHBOARD_USER", "admin")
|
|
10
|
+
DASHBOARD_PASSWORD = os.environ.get("DASHBOARD_PASSWORD", "platypus")
|
|
11
|
+
|
|
12
|
+
# Warn at startup when defaults are still in use.
|
|
13
|
+
USING_DEFAULT_CREDENTIALS = (
|
|
14
|
+
DASHBOARD_USER == "admin" and DASHBOARD_PASSWORD == "platypus"
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def is_authenticated() -> bool:
|
|
19
|
+
return bool(session.get("authenticated"))
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def check_credentials(username: str, password: str) -> bool:
|
|
23
|
+
return username == DASHBOARD_USER and password == DASHBOARD_PASSWORD
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def login_required(f):
|
|
27
|
+
"""Decorator that redirects to /login (HTML) or returns 401 (API)."""
|
|
28
|
+
@functools.wraps(f)
|
|
29
|
+
def wrapper(*args, **kwargs):
|
|
30
|
+
if not is_authenticated():
|
|
31
|
+
if request.path.startswith("/api/"):
|
|
32
|
+
return jsonify({"error": "unauthorized"}), 401
|
|
33
|
+
return redirect(url_for("login_page"))
|
|
34
|
+
return f(*args, **kwargs)
|
|
35
|
+
return wrapper
|
dashboard/compose.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""Docker Compose stack management."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import subprocess
|
|
7
|
+
|
|
8
|
+
COMPOSE_DIR = os.environ.get("COMPOSE_DIR", "/opt/stacks")
|
|
9
|
+
_COMPOSE_FILES = (
|
|
10
|
+
"docker-compose.yml",
|
|
11
|
+
"docker-compose.yaml",
|
|
12
|
+
"compose.yml",
|
|
13
|
+
"compose.yaml",
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class ComposeError(RuntimeError):
|
|
18
|
+
"""Raised when a docker compose command fails."""
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _find_stacks() -> list[str]:
|
|
22
|
+
"""Return paths of directories under COMPOSE_DIR that have a compose file."""
|
|
23
|
+
paths: list[str] = []
|
|
24
|
+
try:
|
|
25
|
+
for entry in sorted(os.scandir(COMPOSE_DIR), key=lambda e: e.name):
|
|
26
|
+
if not entry.is_dir():
|
|
27
|
+
continue
|
|
28
|
+
if any(
|
|
29
|
+
os.path.exists(os.path.join(entry.path, f)) for f in _COMPOSE_FILES
|
|
30
|
+
):
|
|
31
|
+
paths.append(entry.path)
|
|
32
|
+
except (FileNotFoundError, PermissionError):
|
|
33
|
+
pass
|
|
34
|
+
return paths
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _run(cwd: str, args: list[str], timeout: int = 180) -> subprocess.CompletedProcess:
|
|
38
|
+
try:
|
|
39
|
+
return subprocess.run(
|
|
40
|
+
["docker", "compose", *args],
|
|
41
|
+
cwd=cwd,
|
|
42
|
+
capture_output=True,
|
|
43
|
+
text=True,
|
|
44
|
+
timeout=timeout,
|
|
45
|
+
)
|
|
46
|
+
except FileNotFoundError as exc:
|
|
47
|
+
raise ComposeError("docker compose not found") from exc
|
|
48
|
+
except subprocess.TimeoutExpired as exc:
|
|
49
|
+
raise ComposeError("docker compose timed out") from exc
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def list_stacks() -> list[dict]:
|
|
53
|
+
"""Return all discovered stacks with container counts and run status."""
|
|
54
|
+
result: list[dict] = []
|
|
55
|
+
for path in _find_stacks():
|
|
56
|
+
name = os.path.basename(path)
|
|
57
|
+
ps = _run(path, ["ps", "--format", "json"], timeout=10)
|
|
58
|
+
containers: list[dict] = []
|
|
59
|
+
if ps.returncode == 0:
|
|
60
|
+
for line in ps.stdout.strip().splitlines():
|
|
61
|
+
line = line.strip()
|
|
62
|
+
if not line:
|
|
63
|
+
continue
|
|
64
|
+
try:
|
|
65
|
+
containers.append(json.loads(line))
|
|
66
|
+
except json.JSONDecodeError:
|
|
67
|
+
pass
|
|
68
|
+
running = sum(
|
|
69
|
+
1 for c in containers
|
|
70
|
+
if (c.get("State") or c.get("status") or "").lower() == "running"
|
|
71
|
+
)
|
|
72
|
+
result.append(
|
|
73
|
+
{
|
|
74
|
+
"name": name,
|
|
75
|
+
"path": path,
|
|
76
|
+
"containers": len(containers),
|
|
77
|
+
"running": running,
|
|
78
|
+
}
|
|
79
|
+
)
|
|
80
|
+
return result
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def stack_action(name: str, action: str) -> str:
|
|
84
|
+
"""Execute up / down / pull on a named stack."""
|
|
85
|
+
allowed = {"up", "down", "pull"}
|
|
86
|
+
if action not in allowed:
|
|
87
|
+
raise ComposeError(f"Unknown action: {action}")
|
|
88
|
+
stacks_map = {os.path.basename(p): p for p in _find_stacks()}
|
|
89
|
+
if name not in stacks_map:
|
|
90
|
+
raise ComposeError(f"Stack '{name}' not found in {COMPOSE_DIR}")
|
|
91
|
+
path = stacks_map[name]
|
|
92
|
+
cmd_map: dict[str, list[str]] = {
|
|
93
|
+
"up": ["up", "-d"],
|
|
94
|
+
"down": ["down"],
|
|
95
|
+
"pull": ["pull"],
|
|
96
|
+
}
|
|
97
|
+
result = _run(path, cmd_map[action], timeout=300)
|
|
98
|
+
if result.returncode != 0:
|
|
99
|
+
detail = (result.stderr or result.stdout or f"compose {action} failed").strip()
|
|
100
|
+
raise ComposeError(detail)
|
|
101
|
+
lines = (result.stdout + result.stderr).strip().splitlines()
|
|
102
|
+
return lines[-1] if lines else "done"
|