feat(cli): restore live container status and default two-axis columns in workload.list

- Query live container status via get_docker_status() for Sites apps and Core services
- Inspect local Git checkout offline by default and query remotes only when --fetch is passed
- Fix get_docker_status failure semantics to return Unknown instead of Stopped when Docker is unreachable
- Format appctl list table with 5 canonical columns (SERVICE | DEPLOYMENT | PROVENANCE | STATUS | DOMAIN)
- Append CERT column when --ssl is passed (6 columns)
- Add comprehensive router and CLI unit tests covering live status and manifest error branches
- Mark item completed in todo.txt

Closes #10
Refs #10
This commit is contained in:
kiskaadee committed 2026-10-30 08:54:16 -05:00
1 parent 7c1b9b75c5
commit 021c01171b
7 files changed
+342 -27

No files matched your search

+20 -13
View File
@@ -58,28 +58,33 @@ def _format_workload_table(workloads: list[dict[str, Any]]) -> str:
if has_ssl: if has_ssl:
lines.append( lines.append(
f"{'SERVICE':<18} {'TYPE':<14} {'DOMAIN':<30} {'CERT':<24} {'DESCRIPTION'}" f"{'SERVICE':<16} {'DEPLOYMENT':<22} {'PROVENANCE':<22} {'STATUS':<15} {'DOMAIN':<28} {'CERT'}"
) )
lines.append( lines.append(
f"{'-------':<18} {'----':<14} {'------':<30} {'----':<24} {'-----------'}" f"{'-------':<16} {'----------':<22} {'----------':<22} {'------':<15} {'------':<28} {'----'}"
) )
else: else:
lines.append( lines.append(
f"{'SERVICE':<18} {'TYPE':<14} {'DOMAIN':<30} {'DESCRIPTION'}" f"{'SERVICE':<16} {'DEPLOYMENT':<22} {'PROVENANCE':<24} {'STATUS':<15} {'DOMAIN'}"
) )
lines.append( lines.append(
f"{'-------':<18} {'----':<14} {'------':<30} {'-----------'}" f"{'-------':<16} {'----------':<22} {'----------':<24} {'------':<15} {'------'}"
) )
for w in workloads: for w in workloads:
name = str(w.get("name", "-")) name = str(w.get("name") or "-")
w_type = str(w.get("type", w.get("app_type", "app"))) domain = str(w.get("domain") or "-")
domain = str(w.get("domain", "-")) status = str(w.get("status") or "-")
desc = str(w.get("description", ""))
if w.get("manifest_error"): if w.get("manifest_error"):
desc = f"⚠️ {w['manifest_error']}" dep = "⚠️ Manifest Error"
elif w.get("deployment_status"): prov = "⚠️ Invalid Manifest"
desc = f"{w['deployment_status']} ({w.get('provenance_status', '-')})" elif "deployment_status" in w:
dep = str(w["deployment_status"])
prov = str(w.get("provenance_status") or "-")
else:
dep = "-"
prov = str(w.get("provenance_status") or "-")
if has_ssl: if has_ssl:
ssl_info = w.get("ssl") ssl_info = w.get("ssl")
@@ -89,10 +94,12 @@ def _format_workload_table(workloads: list[dict[str, Any]]) -> str:
else "-" else "-"
) )
lines.append( lines.append(
f"{name:<18} {w_type:<14} {domain:<30} {cert_status:<24} {desc}" f"{name:<16} {dep:<22} {prov:<22} {status:<15} {domain:<28} {cert_status}"
) )
else: else:
lines.append(f"{name:<18} {w_type:<14} {domain:<30} {desc}") lines.append(
f"{name:<16} {dep:<22} {prov:<24} {status:<15} {domain}"
)
return "\n".join(lines) return "\n".join(lines)
+15
View File
@@ -108,6 +108,10 @@ class CoreService(App):
app_type: str = "core_service" app_type: str = "core_service"
dir_path: str = CORE_DIR dir_path: str = CORE_DIR
@property
def container_name(self) -> str:
return self.container
@dataclass @dataclass
class SitesApp(App): class SitesApp(App):
@@ -411,6 +415,11 @@ def get_docker_status(
text=True, text=True,
check=False, check=False,
) )
if inspect_res.returncode != 0:
err = (inspect_res.stderr or "").lower()
if "no such object" in err or "no such container" in err:
return "🔴 Stopped"
return "❓ Unknown"
state = inspect_res.stdout.strip() state = inspect_res.stdout.strip()
if state.lower() == "true": if state.lower() == "true":
return "🟢 Running (1)" return "🟢 Running (1)"
@@ -431,6 +440,9 @@ def get_docker_status(
text=True, text=True,
check=False, check=False,
) )
if res.returncode != 0:
return "❓ Unknown"
container_ids = [c for c in res.stdout.strip().splitlines() if c] container_ids = [c for c in res.stdout.strip().splitlines() if c]
if not container_ids: if not container_ids:
return "🔴 Stopped" return "🔴 Stopped"
@@ -441,6 +453,9 @@ def get_docker_status(
text=True, text=True,
check=False, check=False,
) )
if inspect_res.returncode != 0:
return "❓ Unknown"
running_states = inspect_res.stdout.strip().splitlines() running_states = inspect_res.stdout.strip().splitlines()
running_count = sum(1 for s in running_states if s.lower() == "true") running_count = sum(1 for s in running_states if s.lower() == "true")
total_count = len(container_ids) total_count = len(container_ids)
+20 -4
View File
@@ -63,6 +63,7 @@ from appctl_engine import (
check_ssl_cert, check_ssl_cert,
cmd_sync_homepage, cmd_sync_homepage,
get_core_services, get_core_services,
get_docker_status,
get_sites_apps, get_sites_apps,
resolve_app, resolve_app,
) )
@@ -74,7 +75,7 @@ from core_manifest import (
parse_manifest, parse_manifest,
) )
from gitops_dispatcher import validate_compose_security from gitops_dispatcher import validate_compose_security
from provenance import inspect_workload_two_axis from provenance import get_local_checkout_status, inspect_workload_two_axis
MAX_OUTPUT_BYTES = 256 * 1024 # 256 KiB cap per invocation MAX_OUTPUT_BYTES = 256 * 1024 # 256 KiB cap per invocation
@@ -667,24 +668,39 @@ class OperationalRouter:
for app in apps: for app in apps:
item = app.to_dict() item = app.to_dict()
app_path = Path(app.dir_path) app_path = Path(app.dir_path)
if params.fetch: docker_status = get_docker_status(dir_path=app_path)
item["status"] = docker_status
if app.manifest_error:
item["deployment_status"] = "⚠️ Manifest Error"
item["provenance_status"] = "⚠️ Invalid Manifest"
else:
manifest_obj = app.manifest_obj or Manifest( manifest_obj = app.manifest_obj or Manifest(
name=app.name, domain=app.domain name=app.name, domain=app.domain
) )
two_axis = inspect_workload_two_axis( two_axis = inspect_workload_two_axis(
app_dir=app_path, app_dir=app_path,
manifest=manifest_obj, manifest=manifest_obj,
fetch_upstream=True, fetch_upstream=params.fetch,
docker_status=docker_status,
) )
item["deployment_status"] = two_axis.checkout.status_label item["deployment_status"] = two_axis.checkout.status_label
item["provenance_status"] = two_axis.provenance.status.value item["provenance_status"] = two_axis.provenance.status.value
if params.ssl and not app.is_internal: if params.ssl and not app.is_internal:
item["ssl"] = check_ssl_cert(app.domain) item["ssl"] = check_ssl_cert(app.domain)
apps_data.append(item) apps_data.append(item)
if params.core: if params.core:
for svc in get_core_services(core_dir=str(self.core_dir)): core_checkout = get_local_checkout_status(self.core_dir)
for i, svc in enumerate(get_core_services(core_dir=str(self.core_dir))):
svc_dict = svc.to_dict() svc_dict = svc.to_dict()
svc_dict["status"] = get_docker_status(
dir_path=self.core_dir,
container_name=svc.container_name,
)
svc_dict["deployment_status"] = core_checkout.status_label if i == 0 else ""
svc_dict["provenance_status"] = "— Core Platform"
if params.ssl and not svc.is_internal: if params.ssl and not svc.is_internal:
svc_dict["ssl"] = check_ssl_cert(svc.domain) svc_dict["ssl"] = check_ssl_cert(svc.domain)
apps_data.append(svc_dict) apps_data.append(svc_dict)
+87 -9
View File
@@ -116,7 +116,7 @@ def test_cli_handles_missing_socket():
def test_cli_format_response_renders_workload_list_table(): def test_cli_format_response_renders_workload_list_table():
"""Ensure workload.list renders a human-readable table instead of suppressing it behind result['message'].""" """Ensure workload.list renders the canonical 5-column layout matching docs/appctl.md."""
resp = OperationResponse( resp = OperationResponse(
version="1.0", version="1.0",
success=True, success=True,
@@ -129,13 +129,17 @@ def test_cli_format_response_renders_workload_list_table():
"name": "snappymail", "name": "snappymail",
"type": "app", "type": "app",
"domain": "mail.example.test", "domain": "mail.example.test",
"description": "Webmail client", "deployment_status": "✓ Synced (main)",
"provenance_status": "✓ Synced",
"status": "🟢 Running (1)",
}, },
{ {
"name": "traefik", "name": "traefik",
"type": "core_service", "type": "core_service",
"domain": "traefik.example.test", "domain": "traefik.example.test",
"description": "Edge Reverse Proxy", "deployment_status": "",
"provenance_status": "— Core Platform",
"status": "🟢 Running (1)",
}, },
], ],
"message": "Found 2 workloads", "message": "Found 2 workloads",
@@ -143,15 +147,89 @@ def test_cli_format_response_renders_workload_list_table():
output="", output="",
) )
rendered = format_response(resp, raw_json=False) rendered = format_response(resp, raw_json=False)
assert "SERVICE" in rendered lines = rendered.splitlines()
assert "DOMAIN" in rendered assert len(lines) >= 4
assert "snappymail" in rendered assert lines[0] == "SERVICE DEPLOYMENT PROVENANCE STATUS DOMAIN"
assert "mail.example.test" in rendered assert lines[1] == "------- ---------- ---------- ------ ------"
assert "traefik" in rendered assert "snappymail" in lines[2]
assert "Edge Reverse Proxy" in rendered assert "✓ Synced (main)" in lines[2]
assert "✓ Synced" in lines[2]
assert "🟢 Running (1)" in lines[2]
assert "mail.example.test" in lines[2]
assert "traefik" in lines[3]
assert "— Core Platform" in lines[3]
assert "🟢 Running (1)" in lines[3]
assert "traefik.example.test" in lines[3]
assert "✨ Found 2 workloads" not in rendered assert "✨ Found 2 workloads" not in rendered
def test_cli_format_response_renders_workload_list_table_with_ssl():
"""Ensure workload.list with SSL renders the canonical 6-column layout with CERT."""
resp = OperationResponse(
version="1.0",
success=True,
operation_id="op_list_ssl_01",
operation=OperationType.WORKLOAD_LIST,
result={
"total": 1,
"workloads": [
{
"name": "snappymail",
"type": "app",
"domain": "mail.example.test",
"deployment_status": "✓ Synced (main)",
"provenance_status": "✓ Synced",
"status": "🟢 Running (1)",
"ssl": {"status": "🟢 80d remaining"},
},
],
"message": "Found 1 workloads",
},
output="",
)
rendered = format_response(resp, raw_json=False)
lines = rendered.splitlines()
assert len(lines) >= 3
assert lines[0] == "SERVICE DEPLOYMENT PROVENANCE STATUS DOMAIN CERT"
assert lines[1] == "------- ---------- ---------- ------ ------ ----"
assert "snappymail" in lines[2]
assert "🟢 80d remaining" in lines[2]
def test_cli_format_response_renders_workload_list_table_with_manifest_error():
"""Ensure workload.list renders ⚠️ Manifest Error and ⚠️ Invalid Manifest, and status=None renders as '-'."""
resp = OperationResponse(
version="1.0",
success=True,
operation_id="op_list_err",
operation=OperationType.WORKLOAD_LIST,
result={
"total": 1,
"workloads": [
{
"name": "broken-app",
"type": "app",
"domain": "broken.example.test",
"manifest_error": "Syntax error in app.yaml",
"status": None,
},
],
"message": "Found 1 workloads",
},
output="",
)
rendered = format_response(resp, raw_json=False)
lines = rendered.splitlines()
assert len(lines) >= 3
assert "broken-app" in lines[2]
assert "⚠️ Manifest Error" in lines[2]
assert "⚠️ Invalid Manifest" in lines[2]
# Ensure status is '-' and NOT 'None'
assert " None " not in lines[2]
assert " - " in lines[2]
def test_cli_format_response_renders_workload_get_info(): def test_cli_format_response_renders_workload_get_info():
"""Ensure workload.get (appctl info) renders structured workload metadata.""" """Ensure workload.get (appctl info) renders structured workload metadata."""
resp = OperationResponse( resp = OperationResponse(
+70
View File
@@ -200,6 +200,7 @@ def test_docker_status_parser_running(monkeypatch):
def mock_run(args, **kwargs): def mock_run(args, **kwargs):
mock = MagicMock() mock = MagicMock()
mock.returncode = 0
if "ps" in args: if "ps" in args:
mock.stdout = "container123\n" mock.stdout = "container123\n"
if "inspect" in args: if "inspect" in args:
@@ -217,6 +218,7 @@ def test_docker_status_parser_stopped(monkeypatch):
def mock_run(args, **kwargs): def mock_run(args, **kwargs):
mock = MagicMock() mock = MagicMock()
mock.returncode = 0
if "ps" in args: if "ps" in args:
mock.stdout = "" mock.stdout = ""
return mock return mock
@@ -232,6 +234,7 @@ def test_docker_status_parser_degraded(monkeypatch):
def mock_run(args, **kwargs): def mock_run(args, **kwargs):
mock = MagicMock() mock = MagicMock()
mock.returncode = 0
if "ps" in args: if "ps" in args:
mock.stdout = "c1\nc2\n" mock.stdout = "c1\nc2\n"
if "inspect" in args: if "inspect" in args:
@@ -256,6 +259,7 @@ def test_docker_status_single_container(monkeypatch):
def mock_run(args, **kwargs): def mock_run(args, **kwargs):
mock = MagicMock() mock = MagicMock()
mock.returncode = 0
if "authelia" in args: if "authelia" in args:
mock.stdout = "true\n" mock.stdout = "true\n"
else: else:
@@ -268,6 +272,72 @@ def test_docker_status_single_container(monkeypatch):
assert engine.get_docker_status("", container_name="traefik") == "🔴 Stopped" assert engine.get_docker_status("", container_name="traefik") == "🔴 Stopped"
def test_docker_status_compose_ps_daemon_error(monkeypatch):
"""Ensure get_docker_status returns '❓ Unknown' when docker compose ps fails (e.g. daemon unreachable)."""
import subprocess
def mock_run(args, **kwargs):
return subprocess.CompletedProcess(
args=args,
returncode=1,
stdout="",
stderr="Cannot connect to the Docker daemon at unix:///var/run/docker.sock",
)
monkeypatch.setattr("subprocess.run", mock_run)
assert engine.get_docker_status("/fake/dir") == "❓ Unknown"
def test_docker_status_compose_inspect_error(monkeypatch):
"""Ensure get_docker_status returns '❓ Unknown' when docker inspect fails for compose containers."""
import subprocess
def mock_run(args, **kwargs):
if "ps" in args:
return subprocess.CompletedProcess(args=args, returncode=0, stdout="c1\n", stderr="")
return subprocess.CompletedProcess(
args=args,
returncode=1,
stdout="",
stderr="Cannot connect to the Docker daemon at unix:///var/run/docker.sock",
)
monkeypatch.setattr("subprocess.run", mock_run)
assert engine.get_docker_status("/fake/dir") == "❓ Unknown"
def test_docker_status_single_container_daemon_error(monkeypatch):
"""Ensure get_docker_status returns '❓ Unknown' when inspecting single container fails due to daemon error."""
import subprocess
def mock_run(args, **kwargs):
return subprocess.CompletedProcess(
args=args,
returncode=1,
stdout="",
stderr="Cannot connect to the Docker daemon at unix:///var/run/docker.sock",
)
monkeypatch.setattr("subprocess.run", mock_run)
assert engine.get_docker_status("", container_name="traefik") == "❓ Unknown"
def test_docker_status_single_container_no_such_object(monkeypatch):
"""Ensure get_docker_status returns '🔴 Stopped' when container does not exist."""
import subprocess
def mock_run(args, **kwargs):
return subprocess.CompletedProcess(
args=args,
returncode=1,
stdout="",
stderr="Error: No such object: traefik",
)
monkeypatch.setattr("subprocess.run", mock_run)
assert engine.get_docker_status("", container_name="traefik") == "🔴 Stopped"
def test_docker_status_error_handling(monkeypatch): def test_docker_status_error_handling(monkeypatch):
"""Ensure get_docker_status handles subprocess failures gracefully.""" """Ensure get_docker_status handles subprocess failures gracefully."""
+129
View File
@@ -829,3 +829,132 @@ def test_operational_router_workload_list_honors_filter_params(
assert mock_ssl.call_count >= 1 assert mock_ssl.call_count >= 1
def test_operational_router_workload_list_includes_live_docker_and_two_axis_status(
tmp_path: Path,
viewer_principal: Principal,
mock_workload_dir: Path,
mock_core_dir: Path,
):
"""Ensure workload.list always inspects docker status and computes two-axis status for apps and core."""
router = OperationalRouter(
audit_logger=AuditLogger(tmp_path / "audit.jsonl"),
lock_manager=TargetLockManager(tmp_path / "locks"),
sites_dir=mock_workload_dir.parent,
core_dir=mock_core_dir,
)
with patch("appctl_router.get_docker_status", return_value="🟢 Running (1)") as mock_docker:
# 1. Sites workload offline (fetch=False)
resp = router.dispatch(
OperationRequest.model_validate({
"operation": "workload.list",
"parameters": {"core": False, "fetch": False, "ssl": False},
}),
viewer_principal,
)
assert resp.success is True
assert resp.result is not None
workload = resp.result["workloads"][0]
assert workload["name"] == "snappymail"
assert workload["status"] == "🟢 Running (1)"
assert "deployment_status" in workload
assert "provenance_status" in workload
assert workload["provenance_status"] == "— Not Checked"
mock_docker.assert_called_with(dir_path=mock_workload_dir)
# 2. Core services included (core=True)
resp_core = router.dispatch(
OperationRequest.model_validate({
"operation": "workload.list",
"parameters": {"core": True, "fetch": False, "ssl": False},
}),
viewer_principal,
)
assert resp_core.success is True
assert resp_core.result is not None
core_workloads = {w["name"]: w for w in resp_core.result["workloads"]}
assert "traefik" in core_workloads
traefik = core_workloads["traefik"]
assert traefik["status"] == "🟢 Running (1)"
assert traefik["provenance_status"] == "— Core Platform"
assert "deployment_status" in traefik
def test_operational_router_workload_list_fetch_passes_fetch_upstream(
tmp_path: Path,
viewer_principal: Principal,
mock_workload_dir: Path,
mock_core_dir: Path,
):
"""Ensure workload.list with fetch=True calls inspect_workload_two_axis with fetch_upstream=True."""
router = OperationalRouter(
audit_logger=AuditLogger(tmp_path / "audit.jsonl"),
lock_manager=TargetLockManager(tmp_path / "locks"),
sites_dir=mock_workload_dir.parent,
core_dir=mock_core_dir,
)
with (
patch("appctl_router.get_docker_status", return_value="🟢 Running (1)"),
patch("appctl_router.inspect_workload_two_axis") as mock_inspect,
):
mock_two_axis = MagicMock()
mock_two_axis.checkout.status_label = "✓ Synced (main)"
mock_two_axis.provenance.status.value = "✓ Synced"
mock_inspect.return_value = mock_two_axis
resp_fetch = router.dispatch(
OperationRequest.model_validate({
"operation": "workload.list",
"parameters": {"core": False, "fetch": True, "ssl": False},
}),
viewer_principal,
)
assert resp_fetch.success is True
assert resp_fetch.result is not None
mock_inspect.assert_called_once()
_, kwargs = mock_inspect.call_args
assert kwargs.get("fetch_upstream") is True
w = resp_fetch.result["workloads"][0]
assert w["deployment_status"] == "✓ Synced (main)"
assert w["provenance_status"] == "✓ Synced"
def test_operational_router_workload_list_handles_manifest_error(
tmp_path: Path,
viewer_principal: Principal,
mock_sites_dir: Path,
mock_core_dir: Path,
):
"""Ensure workload.list sets deployment_status and provenance_status correctly for apps with manifest errors."""
broken_app_dir = mock_sites_dir / "broken-app"
broken_app_dir.mkdir(parents=True, exist_ok=True)
(broken_app_dir / "app.yaml").write_text("invalid_yaml: [unclosed list", encoding="utf-8")
router = OperationalRouter(
audit_logger=AuditLogger(tmp_path / "audit.jsonl"),
lock_manager=TargetLockManager(tmp_path / "locks"),
sites_dir=mock_sites_dir,
core_dir=mock_core_dir,
)
with patch("appctl_router.get_docker_status", return_value="🔴 Stopped"):
resp = router.dispatch(
OperationRequest.model_validate({
"operation": "workload.list",
"parameters": {"core": False, "fetch": False, "ssl": False},
}),
viewer_principal,
)
assert resp.success is True
assert resp.result is not None
apps = {w["name"]: w for w in resp.result["workloads"]}
assert "broken-app" in apps
broken = apps["broken-app"]
assert broken["manifest_error"] is not None
assert broken["deployment_status"] == "⚠️ Manifest Error"
assert broken["provenance_status"] == "⚠️ Invalid Manifest"
+1 -1
View File
@@ -40,7 +40,7 @@ x 2026-10-23 (A) Derive LLDAP_LDAP_BASE_DN dynamically from homelab.domain in ni
x 2026-10-23 (A) Change systemd.tmpfiles.rules to recursive A+ ACLs for Sites and homepage in nixos/modules/homeserver.nix +nixos @perms x 2026-10-23 (A) Change systemd.tmpfiles.rules to recursive A+ ACLs for Sites and homepage in nixos/modules/homeserver.nix +nixos @perms
x 2026-10-23 (A) Declare global Git safe.directory for /home/operator/Sites/* in nixos/configuration.nix +nixos @git x 2026-10-23 (A) Declare global Git safe.directory for /home/operator/Sites/* in nixos/configuration.nix +nixos @git
x 2026-10-30 (B) Enforce fail-closed check on daemon socket availability and remove silent Bash fallback in scripts/appctl +cli @security x 2026-10-30 (B) Enforce fail-closed check on daemon socket availability and remove silent Bash fallback in scripts/appctl +cli @security
(B) Restore live container status inspection in workload.list and format STATUS column in scripts/appctl_cli.py +cli @ux x 2026-10-30 (B) Restore live container status inspection in workload.list and format STATUS column in scripts/appctl_cli.py +cli @ux
(B) Bootstrap operator admin token provisioning helper and documentation in docs/appctl.md and docs/secrets-and-state.md +docs @auth (B) Bootstrap operator admin token provisioning helper and documentation in docs/appctl.md and docs/secrets-and-state.md +docs @auth
(B) Wire --build/--no-cache and pass --pull during compose_build in scripts/appctl_router.py and scripts/appctl_cli.py +build @p4 (B) Wire --build/--no-cache and pass --pull during compose_build in scripts/appctl_router.py and scripts/appctl_cli.py +build @p4
(C) Deprecate P6 on-server AI authoring compiler in favor of external Homelab MCP Gateway in ROADMAP.md and ADR 0002 +docs @roadmap (C) Deprecate P6 on-server AI authoring compiler in favor of external Homelab MCP Gateway in ROADMAP.md and ADR 0002 +docs @roadmap