Matthias Nott
2026-02-22 7d94ec0d18b46893e23680cf8438109a34cc2a10
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
"""
Container lifecycle operations via Coolify API + SSH.
Three operations:
  restart  – docker restart {containers} via SSH (no Coolify, no image pruning)
  rebuild  – Coolify stop → docker build → Coolify start
  recreate – Coolify stop → wipe data → docker build → Coolify start → show backups banner
"""
import json
import os
import urllib.request
import urllib.error
from datetime import datetime, timezone
from typing import AsyncGenerator
import yaml
from fastapi import APIRouter, Depends, Query
from fastapi.responses import StreamingResponse
from app.auth import verify_token
from app.ops_runner import (
    _BACKUP_TIMEOUT,
    run_command,
    run_command_host,
    stream_command_host,
)
router = APIRouter()
# ---------------------------------------------------------------------------
# Configuration
# ---------------------------------------------------------------------------
_REGISTRY_PATH = os.environ.get(
    "REGISTRY_PATH",
    "/opt/infrastructure/servers/hetzner-vps/registry.yaml",
)
_COOLIFY_BASE = os.environ.get(
    "COOLIFY_BASE_URL",
    "https://cockpit.tekmidian.com/api/v1",
)
_COOLIFY_TOKEN = os.environ.get(
    "COOLIFY_API_TOKEN",
    "3|f1fa8ee5791440ddd37e6cecafd964c8cd734dd4a8891180c424efad6bfdb7f5",
)
_COOLIFY_TIMEOUT = 30   # seconds for API calls
_POLL_INTERVAL  = 5    # seconds between container status polls
_POLL_MAX_WAIT  = 180  # max seconds to wait for containers to stop/start
# ---------------------------------------------------------------------------
# Registry helpers
# ---------------------------------------------------------------------------
def _load_registry() -> dict:
    with open(_REGISTRY_PATH) as f:
        return yaml.safe_load(f) or {}
def _project_cfg(project: str) -> dict:
    reg = _load_registry()
    projects = reg.get("projects", {})
    if project not in projects:
        raise ValueError(f"Unknown project '{project}'")
    return projects[project]
def _coolify_uuid(project: str, env: str) -> str:
    cfg = _project_cfg(project)
    uuids = cfg.get("coolify_uuids", {})
    uuid = uuids.get(env)
    if not uuid:
        raise ValueError(
            f"No coolify_uuid configured for {project}/{env} in registry.yaml"
        )
    return uuid
def _data_dir(project: str, env: str) -> str:
    cfg = _project_cfg(project)
    template = cfg.get("data_dir", "")
    if not template:
        raise ValueError(f"No data_dir configured for {project} in registry.yaml")
    return template.replace("{env}", env)
def _build_cfg(project: str, env: str) -> dict | None:
    """Return build config or None if the project uses registry-only images."""
    cfg = _project_cfg(project)
    build = cfg.get("build", {})
    if build.get("no_local_image"):
        return None
    ctx_template = build.get("build_context", "")
    if not ctx_template:
        return None
    return {
        "build_context": ctx_template.replace("{env}", env),
        "image_name": build.get("image_name", project),
        "env": env,
    }
# ---------------------------------------------------------------------------
# SSE helpers
# ---------------------------------------------------------------------------
def _sse(payload: dict) -> str:
    return f"data: {json.dumps(payload)}\n\n"
def _now() -> str:
    return datetime.now(timezone.utc).isoformat()
def _line(text: str) -> str:
    return _sse({"line": text, "timestamp": _now()})
def _done(success: bool, project: str, env: str, action: str) -> str:
    return _sse({
        "done": True,
        "success": success,
        "project": project,
        "env": env,
        "action": action,
    })
# ---------------------------------------------------------------------------
# Coolify API (synchronous — called from async context via run_in_executor)
# ---------------------------------------------------------------------------
def _coolify_request(method: str, path: str) -> dict:
    """Make a Coolify API request. Returns parsed JSON body."""
    url = f"{_COOLIFY_BASE}{path}"
    req = urllib.request.Request(
        url,
        method=method,
        headers={
            "Authorization": f"Bearer {_COOLIFY_TOKEN}",
            "Content-Type": "application/json",
            "Accept": "application/json",
        },
    )
    try:
        with urllib.request.urlopen(req, timeout=_COOLIFY_TIMEOUT) as resp:
            body = resp.read()
            return json.loads(body) if body else {}
    except urllib.error.HTTPError as exc:
        body = exc.read()
        raise RuntimeError(
            f"Coolify API {method} {path} returned HTTP {exc.code}: {body.decode(errors='replace')[:500]}"
        ) from exc
    except Exception as exc:
        raise RuntimeError(f"Coolify API call failed: {exc}") from exc
async def _coolify_action(action: str, uuid: str) -> dict:
    """Call a Coolify service action endpoint (stop/start/restart)."""
    import asyncio
    loop = asyncio.get_event_loop()
    return await loop.run_in_executor(
        None, _coolify_request, "POST", f"/services/{uuid}/{action}"
    )
# ---------------------------------------------------------------------------
# Container polling helpers
# ---------------------------------------------------------------------------
async def _find_containers_for_service(project: str, env: str) -> list[str]:
    """
    Find all running Docker containers belonging to a project/env.
    Uses the registry name_prefix and matches {env}-{prefix}-* pattern.
    """
    cfg = _project_cfg(project)
    prefix = cfg.get("name_prefix", project)
    name_pattern = f"{env}-{prefix}-"
    result = await run_command(
        ["docker", "ps", "--filter", f"name={name_pattern}", "--format", "{{.Names}}"],
        timeout=15,
    )
    containers = []
    if result["success"]:
        for name in result["output"].strip().splitlines():
            name = name.strip()
            if name and name.startswith(name_pattern):
                containers.append(name)
    return containers
async def _poll_until_stopped(
    project: str,
    env: str,
    max_wait: int = _POLL_MAX_WAIT,
) -> bool:
    """Poll until no containers for project/env are running. Returns True if stopped."""
    import asyncio
    cfg = _project_cfg(project)
    prefix = cfg.get("name_prefix", project)
    name_pattern = f"{env}-{prefix}-"
    waited = 0
    while waited < max_wait:
        result = await run_command(
            ["docker", "ps", "--filter", f"name={name_pattern}", "--format", "{{.Names}}"],
            timeout=15,
        )
        running = [
            n.strip()
            for n in result["output"].strip().splitlines()
            if n.strip().startswith(name_pattern)
        ] if result["success"] else []
        if not running:
            return True
        await asyncio.sleep(_POLL_INTERVAL)
        waited += _POLL_INTERVAL
    return False
async def _poll_until_running(
    project: str,
    env: str,
    max_wait: int = _POLL_MAX_WAIT,
) -> bool:
    """Poll until at least one container for project/env is running. Returns True if up."""
    import asyncio
    cfg = _project_cfg(project)
    prefix = cfg.get("name_prefix", project)
    name_pattern = f"{env}-{prefix}-"
    waited = 0
    while waited < max_wait:
        result = await run_command(
            ["docker", "ps", "--filter", f"name={name_pattern}", "--format", "{{.Names}}"],
            timeout=15,
        )
        running = [
            n.strip()
            for n in result["output"].strip().splitlines()
            if n.strip().startswith(name_pattern)
        ] if result["success"] else []
        if running:
            return True
        await asyncio.sleep(_POLL_INTERVAL)
        waited += _POLL_INTERVAL
    return False
# ---------------------------------------------------------------------------
# Operation: Restart
# ---------------------------------------------------------------------------
async def _op_restart(project: str, env: str) -> AsyncGenerator[str, None]:
    """
    Restart: docker restart {containers} via SSH/nsenter.
    No Coolify involvement — avoids the image-pruning stop/start cycle.
    """
    yield _line(f"[restart] Finding containers for {project}/{env}...")
    try:
        containers = await _find_containers_for_service(project, env)
    except Exception as exc:
        yield _line(f"[error] Registry lookup failed: {exc}")
        yield _done(False, project, env, "restart")
        return
    if not containers:
        yield _line(f"[error] No running containers found for {project}/{env}")
        yield _done(False, project, env, "restart")
        return
    yield _line(f"[restart] Restarting {len(containers)} container(s): {', '.join(containers)}")
    cmd = ["docker", "restart"] + containers
    result = await run_command(cmd, timeout=120)
    if result["output"].strip():
        for line in result["output"].strip().splitlines():
            yield _line(line)
    if result["error"].strip():
        for line in result["error"].strip().splitlines():
            yield _line(f"[stderr] {line}")
    if result["success"]:
        yield _line(f"[restart] All containers restarted successfully.")
        yield _done(True, project, env, "restart")
    else:
        yield _line(f"[error] docker restart failed (exit code non-zero)")
        yield _done(False, project, env, "restart")
# ---------------------------------------------------------------------------
# Operation: Rebuild
# ---------------------------------------------------------------------------
async def _op_rebuild(project: str, env: str) -> AsyncGenerator[str, None]:
    """
    Rebuild: Coolify stop → docker build → Coolify start.
    No data loss. For code/Dockerfile changes.
    """
    try:
        uuid = _coolify_uuid(project, env)
        build = _build_cfg(project, env)
    except ValueError as exc:
        yield _line(f"[error] Config error: {exc}")
        yield _done(False, project, env, "rebuild")
        return
    # Step 1: Stop via Coolify
    yield _line(f"[rebuild] Stopping {project}/{env} via Coolify (uuid={uuid})...")
    try:
        await _coolify_action("stop", uuid)
        yield _line(f"[rebuild] Coolify stop queued. Waiting for containers to stop...")
        # Step 2: Poll until stopped
        stopped = await _poll_until_stopped(project, env)
        if not stopped:
            yield _line(f"[warn] Containers may still be running after {_POLL_MAX_WAIT}s — proceeding anyway")
        else:
            yield _line(f"[rebuild] All containers stopped.")
    except RuntimeError as exc:
        if "already stopped" in str(exc).lower():
            yield _line(f"[rebuild] Service already stopped — continuing with build.")
        else:
            yield _line(f"[error] Coolify stop failed: {exc}")
            yield _done(False, project, env, "rebuild")
            return
    # Step 3: Build image (if project uses local images)
    if build:
        ctx = build["build_context"]
        image = f"{build['image_name']}:{env}"
        yield _line(f"[rebuild] Building Docker image: {image}")
        yield _line(f"[rebuild] Build context: {ctx}")
        async for line in stream_command_host(
            ["docker", "build", "-t", image, ctx],
            timeout=_BACKUP_TIMEOUT,
        ):
            yield _line(line)
    else:
        yield _line(f"[rebuild] No local image build needed (registry images only).")
    # Step 4: Start via Coolify
    yield _line(f"[rebuild] Starting {project}/{env} via Coolify...")
    try:
        await _coolify_action("start", uuid)
        yield _line(f"[rebuild] Coolify start queued. Waiting for containers...")
    except RuntimeError as exc:
        yield _line(f"[error] Coolify start failed: {exc}")
        yield _done(False, project, env, "rebuild")
        return
    # Step 5: Poll until running
    running = await _poll_until_running(project, env)
    if running:
        yield _line(f"[rebuild] Containers are up.")
        yield _done(True, project, env, "rebuild")
    else:
        yield _line(f"[warn] Containers did not appear healthy within {_POLL_MAX_WAIT}s — check Coolify logs.")
        yield _done(False, project, env, "rebuild")
# ---------------------------------------------------------------------------
# Operation: Recreate (Disaster Recovery)
# ---------------------------------------------------------------------------
async def _op_recreate(project: str, env: str) -> AsyncGenerator[str, None]:
    """
    Recreate: Coolify stop → wipe data → docker build → Coolify start.
    DESTRUCTIVE — wipes all data volumes. Shows "Go to Backups" banner on success.
    """
    try:
        uuid = _coolify_uuid(project, env)
        build = _build_cfg(project, env)
        data_dir = _data_dir(project, env)
        cfg = _project_cfg(project)
    except ValueError as exc:
        yield _line(f"[error] Config error: {exc}")
        yield _done(False, project, env, "recreate")
        return
    # Step 1: Stop via Coolify
    yield _line(f"[recreate] Stopping {project}/{env} via Coolify (uuid={uuid})...")
    try:
        await _coolify_action("stop", uuid)
        yield _line(f"[recreate] Coolify stop queued. Waiting for containers to stop...")
        # Step 2: Poll until stopped
        stopped = await _poll_until_stopped(project, env)
        if not stopped:
            yield _line(f"[warn] Containers may still be running after {_POLL_MAX_WAIT}s — proceeding anyway")
        else:
            yield _line(f"[recreate] All containers stopped.")
    except RuntimeError as exc:
        if "already stopped" in str(exc).lower():
            yield _line(f"[recreate] Service already stopped — skipping stop step.")
        else:
            yield _line(f"[error] Coolify stop failed: {exc}")
            yield _done(False, project, env, "recreate")
            return
    # Step 3: Wipe data volumes
    yield _line(f"[recreate] WARNING: Wiping data directory: {data_dir}")
    # Verify THIS env's containers are actually stopped before wiping
    name_prefix = cfg.get("name_prefix", project)
    # Use grep to AND-match both prefix and env (docker --filter uses OR for multiple name filters)
    verify = await run_command_host(
        ["sh", "-c", f"docker ps --format '{{{{.Names}}}}' | grep '^{env}-{name_prefix}\\|^{name_prefix}-{env}' || true"],
        timeout=30,
    )
    running = verify["output"].strip()
    if running:
        yield _line(f"[error] Containers still running for {project}/{env}:")
        for line in running.splitlines():
            yield _line(f"  {line}")
        yield _done(False, project, env, "recreate")
        return
    wipe_result = await run_command_host(
        ["sh", "-c", f"rm -r {data_dir}/* 2>&1; echo EXIT_CODE=$?"],
        timeout=120,
    )
    for line in (wipe_result["output"].strip() + "\n" + wipe_result["error"].strip()).strip().splitlines():
        if line:
            yield _line(line)
    if "EXIT_CODE=0" in wipe_result["output"]:
        yield _line(f"[recreate] Data directory wiped.")
    else:
        yield _line(f"[error] Wipe may have failed — check output above.")
        yield _done(False, project, env, "recreate")
        return
    # Step 4: Build image (if project uses local images)
    if build:
        ctx = build["build_context"]
        image = f"{build['image_name']}:{env}"
        yield _line(f"[recreate] Building Docker image: {image}")
        yield _line(f"[recreate] Build context: {ctx}")
        async for line in stream_command_host(
            ["docker", "build", "-t", image, ctx],
            timeout=_BACKUP_TIMEOUT,
        ):
            yield _line(line)
    else:
        yield _line(f"[recreate] No local image build needed (registry images only).")
    # Step 5: Start via Coolify
    yield _line(f"[recreate] Starting {project}/{env} via Coolify...")
    try:
        await _coolify_action("start", uuid)
        yield _line(f"[recreate] Coolify start queued. Waiting for containers...")
    except RuntimeError as exc:
        yield _line(f"[error] Coolify start failed: {exc}")
        yield _done(False, project, env, "recreate")
        return
    # Step 6: Poll until running
    running = await _poll_until_running(project, env)
    if running:
        yield _line(f"[recreate] Containers are up. Restore a backup to complete recovery.")
        yield _done(True, project, env, "recreate")
    else:
        yield _line(f"[warn] Containers did not appear within {_POLL_MAX_WAIT}s — check Coolify logs.")
        # Still return success=True so the "Go to Backups" banner appears
        yield _done(True, project, env, "recreate")
# ---------------------------------------------------------------------------
# Dispatch wrapper
# ---------------------------------------------------------------------------
async def _op_generator(
    project: str,
    env: str,
    action: str,
) -> AsyncGenerator[str, None]:
    """Route to the correct operation generator."""
    if action == "restart":
        async for chunk in _op_restart(project, env):
            yield chunk
    elif action == "rebuild":
        async for chunk in _op_rebuild(project, env):
            yield chunk
    elif action == "recreate":
        async for chunk in _op_recreate(project, env):
            yield chunk
    else:
        yield _line(f"[error] Unknown action '{action}'. Valid: restart, rebuild, recreate")
        yield _done(False, project, env, action)
# ---------------------------------------------------------------------------
# Endpoint
# ---------------------------------------------------------------------------
@router.get(
    "/{project}/{env}",
    summary="Container lifecycle operation with real-time SSE output",
)
async def lifecycle_op(
    project: str,
    env: str,
    action: str = Query(
        default="restart",
        description="Operation: restart | rebuild | recreate",
    ),
    _: str = Depends(verify_token),
) -> StreamingResponse:
    """
    Stream a container lifecycle operation via SSE.
    - restart:  docker restart containers (safe, fast)
    - rebuild:  stop via Coolify, rebuild image, start via Coolify
    - recreate: stop, wipe data, rebuild image, start (destructive — DR only)
    """
    return StreamingResponse(
        _op_generator(project, env, action),
        media_type="text/event-stream",
        headers={
            "Cache-Control": "no-cache",
            "X-Accel-Buffering": "no",
        },
    )