diff --git a/scripts/appctl_cli.py b/scripts/appctl_cli.py index 01df017..1fa520e 100755 --- a/scripts/appctl_cli.py +++ b/scripts/appctl_cli.py @@ -58,28 +58,33 @@ def _format_workload_table(workloads: list[dict[str, Any]]) -> str: if has_ssl: 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( - f"{'-------':<18} {'----':<14} {'------':<30} {'----':<24} {'-----------'}" + f"{'-------':<16} {'----------':<22} {'----------':<22} {'------':<15} {'------':<28} {'----'}" ) else: lines.append( - f"{'SERVICE':<18} {'TYPE':<14} {'DOMAIN':<30} {'DESCRIPTION'}" + f"{'SERVICE':<16} {'DEPLOYMENT':<22} {'PROVENANCE':<24} {'STATUS':<15} {'DOMAIN'}" ) lines.append( - f"{'-------':<18} {'----':<14} {'------':<30} {'-----------'}" + f"{'-------':<16} {'----------':<22} {'----------':<24} {'------':<15} {'------'}" ) for w in workloads: - name = str(w.get("name", "-")) - w_type = str(w.get("type", w.get("app_type", "app"))) - domain = str(w.get("domain", "-")) - desc = str(w.get("description", "")) + name = str(w.get("name") or "-") + domain = str(w.get("domain") or "-") + status = str(w.get("status") or "-") + if w.get("manifest_error"): - desc = f"⚠️ {w['manifest_error']}" - elif w.get("deployment_status"): - desc = f"{w['deployment_status']} ({w.get('provenance_status', '-')})" + dep = "⚠️ Manifest Error" + prov = "⚠️ Invalid Manifest" + 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: ssl_info = w.get("ssl") @@ -89,10 +94,12 @@ def _format_workload_table(workloads: list[dict[str, Any]]) -> str: else "-" ) 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: - 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) diff --git a/scripts/appctl_engine.py b/scripts/appctl_engine.py index 1db4413..c03bb7a 100755 --- a/scripts/appctl_engine.py +++ b/scripts/appctl_engine.py @@ -108,6 +108,10 @@ class CoreService(App): app_type: str = "core_service" dir_path: str = CORE_DIR + @property + def container_name(self) -> str: + return self.container + @dataclass class SitesApp(App): @@ -411,6 +415,11 @@ def get_docker_status( text=True, 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() if state.lower() == "true": return "🟢 Running (1)" @@ -431,6 +440,9 @@ def get_docker_status( text=True, check=False, ) + if res.returncode != 0: + return "❓ Unknown" + container_ids = [c for c in res.stdout.strip().splitlines() if c] if not container_ids: return "🔴 Stopped" @@ -441,6 +453,9 @@ def get_docker_status( text=True, check=False, ) + if inspect_res.returncode != 0: + return "❓ Unknown" + running_states = inspect_res.stdout.strip().splitlines() running_count = sum(1 for s in running_states if s.lower() == "true") total_count = len(container_ids) diff --git a/scripts/appctl_router.py b/scripts/appctl_router.py index 2b51e21..e106af1 100644 --- a/scripts/appctl_router.py +++ b/scripts/appctl_router.py @@ -63,6 +63,7 @@ from appctl_engine import ( check_ssl_cert, cmd_sync_homepage, get_core_services, + get_docker_status, get_sites_apps, resolve_app, ) @@ -74,7 +75,7 @@ from core_manifest import ( parse_manifest, ) 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 @@ -667,24 +668,39 @@ class OperationalRouter: for app in apps: item = app.to_dict() 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( name=app.name, domain=app.domain ) two_axis = inspect_workload_two_axis( app_dir=app_path, manifest=manifest_obj, - fetch_upstream=True, + fetch_upstream=params.fetch, + docker_status=docker_status, ) item["deployment_status"] = two_axis.checkout.status_label item["provenance_status"] = two_axis.provenance.status.value + if params.ssl and not app.is_internal: item["ssl"] = check_ssl_cert(app.domain) apps_data.append(item) 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["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: svc_dict["ssl"] = check_ssl_cert(svc.domain) apps_data.append(svc_dict) diff --git a/tests/unit/test_appctl_cli.py b/tests/unit/test_appctl_cli.py index cd085e9..5c2ec94 100644 --- a/tests/unit/test_appctl_cli.py +++ b/tests/unit/test_appctl_cli.py @@ -116,7 +116,7 @@ def test_cli_handles_missing_socket(): 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( version="1.0", success=True, @@ -129,13 +129,17 @@ def test_cli_format_response_renders_workload_list_table(): "name": "snappymail", "type": "app", "domain": "mail.example.test", - "description": "Webmail client", + "deployment_status": "✓ Synced (main)", + "provenance_status": "✓ Synced", + "status": "🟢 Running (1)", }, { "name": "traefik", "type": "core_service", "domain": "traefik.example.test", - "description": "Edge Reverse Proxy", + "deployment_status": "", + "provenance_status": "— Core Platform", + "status": "🟢 Running (1)", }, ], "message": "Found 2 workloads", @@ -143,15 +147,89 @@ def test_cli_format_response_renders_workload_list_table(): output="", ) rendered = format_response(resp, raw_json=False) - assert "SERVICE" in rendered - assert "DOMAIN" in rendered - assert "snappymail" in rendered - assert "mail.example.test" in rendered - assert "traefik" in rendered - assert "Edge Reverse Proxy" in rendered + lines = rendered.splitlines() + assert len(lines) >= 4 + assert lines[0] == "SERVICE DEPLOYMENT PROVENANCE STATUS DOMAIN" + assert lines[1] == "------- ---------- ---------- ------ ------" + assert "snappymail" in lines[2] + 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 +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(): """Ensure workload.get (appctl info) renders structured workload metadata.""" resp = OperationResponse( diff --git a/tests/unit/test_appctl_engine.py b/tests/unit/test_appctl_engine.py index 1ec3378..2721061 100644 --- a/tests/unit/test_appctl_engine.py +++ b/tests/unit/test_appctl_engine.py @@ -200,6 +200,7 @@ def test_docker_status_parser_running(monkeypatch): def mock_run(args, **kwargs): mock = MagicMock() + mock.returncode = 0 if "ps" in args: mock.stdout = "container123\n" if "inspect" in args: @@ -217,6 +218,7 @@ def test_docker_status_parser_stopped(monkeypatch): def mock_run(args, **kwargs): mock = MagicMock() + mock.returncode = 0 if "ps" in args: mock.stdout = "" return mock @@ -232,6 +234,7 @@ def test_docker_status_parser_degraded(monkeypatch): def mock_run(args, **kwargs): mock = MagicMock() + mock.returncode = 0 if "ps" in args: mock.stdout = "c1\nc2\n" if "inspect" in args: @@ -256,6 +259,7 @@ def test_docker_status_single_container(monkeypatch): def mock_run(args, **kwargs): mock = MagicMock() + mock.returncode = 0 if "authelia" in args: mock.stdout = "true\n" else: @@ -268,6 +272,72 @@ def test_docker_status_single_container(monkeypatch): 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): """Ensure get_docker_status handles subprocess failures gracefully.""" diff --git a/tests/unit/test_appctl_router.py b/tests/unit/test_appctl_router.py index 50d0cd1..26b802a 100644 --- a/tests/unit/test_appctl_router.py +++ b/tests/unit/test_appctl_router.py @@ -829,3 +829,132 @@ def test_operational_router_workload_list_honors_filter_params( 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" + + + + diff --git a/todo.txt b/todo.txt index 0f22d4b..a24cc22 100644 --- a/todo.txt +++ b/todo.txt @@ -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) 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 -(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) 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