d7a3253740
- 'Dein Stack' zeigt echtes Modell (Dateiname) hinter coder/scout/vision. - Top-News-Karte auf der Uebersicht (neben Stack). - Toolbar-Update-Badges: /api/updates (OS via apt-Cache + Modell-Upgrades), klickbar -> Server bzw. News. compute_upgrades aus cookbook wiederverwendet. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
127 lines
4.7 KiB
Python
127 lines
4.7 KiB
Python
"""
|
|
Wartungs-Router: Container/Toolbox aktualisieren.
|
|
|
|
Der konkrete Befehl steckt in MC_UPDATE_CMD (z.B. kyuz0 refresh-Skript) und
|
|
laeuft als Hintergrund-Job mit Live-Log. Spaeter wandert hier ggf. mehr
|
|
Server-Wartung hinein (siehe Roadmap: Server-Management).
|
|
"""
|
|
|
|
import shlex
|
|
import subprocess
|
|
import asyncio
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException, WebSocket, WebSocketDisconnect
|
|
from pydantic import BaseModel
|
|
|
|
from auth import auth
|
|
from config import UPDATE_CMD, SOURCE_DIR, PROD_DIR
|
|
from jobengine import start_job
|
|
|
|
router = APIRouter(prefix="/api", dependencies=[Depends(auth)])
|
|
|
|
class PwdReq(BaseModel):
|
|
password: str
|
|
|
|
@router.post("/update")
|
|
def update():
|
|
"""LLM-Engine (llama.cpp) aktualisieren — Befehl aus MC_UPDATE_CMD."""
|
|
if not UPDATE_CMD:
|
|
raise HTTPException(400, "Kein Update-Befehl gesetzt (MC_UPDATE_CMD).")
|
|
job_id = start_job(shlex.split(UPDATE_CMD), "llama.cpp-Update")
|
|
return {"job_id": job_id}
|
|
|
|
@router.post("/self-update")
|
|
def self_update():
|
|
"""Mission Control selbst aktualisieren: Quelle pullen -> nach Prod rsyncen -> Dienst neu starten.
|
|
git pull liest aus Gitea; der Restart laeuft ueber die NOPASSWD-sudoers-Whitelist. Die einzelnen
|
|
Schritte sind mit && verkettet -> bei einem Fehler (z.B. Gitea offline) bricht es sauber ab."""
|
|
cmd = (
|
|
f"cd {shlex.quote(SOURCE_DIR)} && git pull --ff-only && "
|
|
f"rsync -a --exclude=.git --exclude=.venv --exclude=__pycache__ --exclude='*.pyc' "
|
|
f"{shlex.quote(SOURCE_DIR)}/ {shlex.quote(PROD_DIR)}/ && "
|
|
f"sudo systemctl restart mission-control"
|
|
)
|
|
job_id = start_job(["bash", "-c", cmd], "Mission Control Update",
|
|
log_cmd="$ git pull && rsync -> /opt && systemctl restart mission-control")
|
|
return {"job_id": job_id}
|
|
|
|
@router.post("/os-update")
|
|
def os_update(req: PwdReq):
|
|
# Passwort ueber stdin an sudo -S — NICHT als Klartext-Arg (sonst im Job-Log/ps sichtbar).
|
|
args = ["sudo", "-S", "bash", "-c",
|
|
"apt-get update && DEBIAN_FRONTEND=noninteractive apt-get upgrade -y"]
|
|
job_id = start_job(args, "OS-Update (apt)", stdin_data=req.password + "\n",
|
|
log_cmd="$ sudo apt-get update && apt-get upgrade -y")
|
|
return {"job_id": job_id}
|
|
|
|
@router.post("/service/{name}/restart")
|
|
def service_restart(name: str):
|
|
if name not in ("llama-swap", "mission-control"):
|
|
raise HTTPException(400, "Dienst nicht erlaubt.")
|
|
subprocess.Popen(["sudo", "systemctl", "restart", name])
|
|
return {"ok": True, "note": f"Restart {name} getriggert."}
|
|
|
|
@router.post("/reboot")
|
|
def reboot(req: PwdReq):
|
|
# Passwort ueber stdin (nicht in argv -> nicht in ps sichtbar).
|
|
proc = subprocess.Popen(["sudo", "-S", "reboot"], stdin=subprocess.PIPE, text=True)
|
|
try:
|
|
proc.stdin.write(req.password + "\n")
|
|
proc.stdin.flush()
|
|
except Exception: # noqa: BLE001
|
|
pass
|
|
return {"ok": True, "note": "Reboot getriggert."}
|
|
|
|
@router.get("/updates")
|
|
def updates():
|
|
"""Ausstehende Updates für die Toolbar: OS-Pakete (apt-Cache) + Modell-Upgrades."""
|
|
import psutil
|
|
from routers.cookbook import compute_upgrades
|
|
os_count = 0
|
|
try:
|
|
out = subprocess.run(
|
|
["bash", "-c", "apt list --upgradable 2>/dev/null | grep -c upgradable || true"],
|
|
capture_output=True, text=True, timeout=10)
|
|
os_count = int((out.stdout or "0").strip() or 0)
|
|
except Exception: # noqa: BLE001
|
|
os_count = 0
|
|
try:
|
|
models = len(compute_upgrades(psutil.virtual_memory().total / (1024 ** 3)))
|
|
except Exception: # noqa: BLE001
|
|
models = 0
|
|
return {"os": os_count, "models": models}
|
|
|
|
@router.websocket("/logs/{service}")
|
|
async def stream_logs(websocket: WebSocket, service: str):
|
|
await websocket.accept()
|
|
if service not in ("llama-swap", "mission-control", "system"):
|
|
await websocket.close(code=1008)
|
|
return
|
|
|
|
if service == "system":
|
|
cmd = ["sudo", "journalctl", "-n", "100", "-f"] # ganzer Server (alle Units)
|
|
else:
|
|
cmd = ["sudo", "journalctl", "-u", service, "-n", "100", "-f"]
|
|
process = await asyncio.create_subprocess_exec(
|
|
*cmd,
|
|
stdout=asyncio.subprocess.PIPE,
|
|
stderr=asyncio.subprocess.PIPE
|
|
)
|
|
try:
|
|
while True:
|
|
line = await process.stdout.readline()
|
|
if not line:
|
|
break
|
|
line_str = line.decode("utf-8", errors="replace")
|
|
# Filter spammy polls
|
|
if '"GET /running HTTP' in line_str or '"GET /api/' in line_str:
|
|
continue
|
|
await websocket.send_text(line_str)
|
|
except WebSocketDisconnect:
|
|
pass
|
|
finally:
|
|
try:
|
|
process.terminate()
|
|
except OSError:
|
|
pass
|