diff --git a/lib/default.nix b/lib/default.nix index bcf538be0d..7fb3af3919 100644 --- a/lib/default.nix +++ b/lib/default.nix @@ -1307,6 +1307,15 @@ let python3 ${../pkgs/deploy/test_dupkeys_property.py} ${../pkgs/deploy/deploy.py} mkdir -p $out ''; + deploy-slice2-tests = + pkgs.runCommandLocal "check-deploy-slice2-tests" + { + nativeBuildInputs = [ pkgs.python3 ]; + } + '' + python3 ${../pkgs/deploy/test_deploy_slice2.py} ${../pkgs/deploy/deploy.py} + mkdir -p $out + ''; deploy-list-malformed = pkgs.runCommandLocal "check-deploy-list-malformed" { } '' expect_invalid() { registry="$1" diff --git a/pkgs/deploy/default.nix b/pkgs/deploy/default.nix index 278f1681a8..0c3c468b7b 100644 --- a/pkgs/deploy/default.nix +++ b/pkgs/deploy/default.nix @@ -1,4 +1,5 @@ -# The deploy registry + CLI — issue #5766, slice 1 (registry + list). +# The deploy registry + CLI — issue #5766, slices 1-2 (registry + list; +# unit/plist rendering, --dry-run plans, generation log, status/rollback logic). # # deployTargets: this repo's service definitions (services.nix) in the # design §3 shape, with each definition's `package` still a derivation — @@ -43,7 +44,7 @@ in { nativeBuildInputs = [ makeWrapper ]; meta = { - description = "Deploy CLI (slice 1: registry list + definition validation) for the services deployment layer"; + description = "Deploy CLI (slices 1-2: registry list + validation, unit rendering, dry-run plans, generation log, status/rollback logic) for the services deployment layer"; mainProgram = "deploy"; }; } diff --git a/pkgs/deploy/deploy.py b/pkgs/deploy/deploy.py index 8c85f137d8..b10bad9eaa 100644 --- a/pkgs/deploy/deploy.py +++ b/pkgs/deploy/deploy.py @@ -1,31 +1,58 @@ #!/usr/bin/env python3 -"""deploy — the deployment-architecture CLI (issue #5766, slice 1). +"""deploy — the deployment-architecture CLI (issue #5766, slices 1-2). -Slice 1 ships the registry foundation only: `deploy list` enumerates the -`deployTargets` registry (name, class, targets) after validating every +Slice 1 ships the registry foundation: enumerates the + registry (name, class, targets) after validating every definition against the design §3 option shape -(doc/2026-11-04_deployment-architecture-services-layer.md). Activation, -status, and rollback are later slices of issue #5766 and are NOT -implemented here — those subcommands say so and exit non-zero. +(doc/2026-11-04_deployment-architecture-services-layer.md). + +Slice 2 adds the command logic that does not itself activate anything: + +- systemd unit rendering (and a launchd plist stub) from a definition: + the unit's ExecStart points at the service's per-service nix profile + `current` link (design §4.1), never at a bare store path, so a + generation flip is a profile repoint, not a unit rewrite. +- `deploy --dry-run`: the ordered activation plan (build, + install the next generation into the profile, write the unit, + daemon-reload, restart only that unit, health check, flip back on + failure) with no side effects. +- The generation log: one append-only JSONL file per target under the + state dir (design §4.6: generation id, source rev, artifact, + timestamp, actor). folds the log into + current/previous generations and reports health; selects + the previous distinct generation — repointing, never rebuilding. +- Real activation (nix-env profile install, systemctl restart, + health-check flip-back) is the next slice of issue #5766: the + non-dry-run deploy/rollback paths say so and exit non-zero rather + than pretending to have activated something. The registry is JSON baked into the package at build time (the Nix -expression renders the attrset definitions, replacing each `package` +expression renders the attrset definitions, replacing each derivation with its store path). `--registry PATH` (or $DEPLOY_REGISTRY) points the CLI at another registry file, which is how the flake checks -exercise the malformed-definition path. +exercise the malformed-definition path. `--state-dir PATH` (or +$DEPLOY_STATE_DIR) relocates the generation logs, `--profile-base PATH` +(or $DEPLOY_PROFILE_BASE) the per-service profile root; both exist so +tests and dry runs never touch the real profile tree. The validation below is the oracle for "well-formed definition": a -definition is valid iff it carries exactly the §3 fields (plus `class`), +definition is valid iff it carries exactly the §3 fields (plus ), each of the right type and in range. Any violation is reported by field -and makes `list` exit non-zero — a registry that cannot be validated +and makes exit non-zero — a registry that cannot be validated must never be enumerated as if it were trustworthy. """ +import getpass import json import os import re +import shlex import sys +import urllib.error +import urllib.request +from datetime import datetime, timezone from urllib.parse import urlsplit +from xml.sax.saxutils import escape as xml_escape CLASSES = {"systemd", "launchd", "cloudflare", "sandbox", "container"} RESTART_POLICIES = { @@ -52,6 +79,12 @@ } NAME_RE = re.compile(r"^[a-z0-9][a-z0-9-]*$") +# Design §4.1: each systemd target owns a per-service nix profile under +# this root (system scope); the rendered unit points at the profile's +# `current` link. +DEFAULT_PROFILE_BASE = "/nix/var/nix/profiles/per-service" +ACTIVATION_CLASSES = {"systemd", "launchd"} + def validate(registry): """Return a list of validation errors (empty = registry is valid).""" @@ -205,30 +238,375 @@ def cmd_list(registry): return 0 +# --- Rendering (slice 2) ------------------------------------------------- +# +# Oracle: design §4.1/§4.2 and issue #5766. A rendered unit/plist points +# at the per-service profile's `current` link, so activation and +# rollback are profile repoints; the rendered file itself does not +# change between generations of the same definition. + + +def profile_base(explicit=None): + return explicit or os.environ.get("DEPLOY_PROFILE_BASE") or DEFAULT_PROFILE_BASE + + +def profile_link(name, base=None): + return os.path.join(profile_base(base), name) + + +def unit_name(name): + return f"{name}.service" + + +def _systemd_quote(value): + # systemd unit syntax is not shell: values with whitespace or + # specials are double-quoted, with backslash/quote escaped and the + # specifier/variable introducers (% and $) doubled. + if value and not any(c in value for c in ' \t"\\%$'): + return value + escaped = ( + value.replace("\\", "\\\\") + .replace('"', '\\"') + .replace("%", "%%") + .replace("$", "$$") + ) + return f'"{escaped}"' + + +def render_unit(name, defn, base=None): + """Render the systemd unit for a definition (design §4.1).""" + link = profile_link(name, base) + exec_start = os.path.join(link, "current", defn["entryPoint"]) + argv = " ".join(_systemd_quote(a) for a in [exec_start, *defn["args"]]) + lines = [ + "[Unit]", + f"Description=deploy target {name} (issue #5766)", + "After=network.target", + "", + "[Service]", + f"ExecStart={argv}", + f"User={defn['user']}", + f"Restart={defn['restart']}", + ] + for key in sorted(defn["environment"]): + pair = f"{key}={defn['environment'][key]}" + lines.append(f"Environment={_systemd_quote(pair)}") + if defn["secrets"]: + names = ", ".join(defn["secrets"]) + lines.append(f"# secrets resolved by name at activation time: {names}") + lines += ["", "[Install]", "WantedBy=multi-user.target", ""] + return "\n".join(lines) + + +def render_plist(name, defn, base=None): + """Launchd stub rendering (design §4.2): same definition shape, + the agent program points at the profile `current` link.""" + link = profile_link(name, base) + program = os.path.join(link, "current", defn["entryPoint"]) + args = [program, *defn["args"]] + arg_xml = "\n".join(f" {xml_escape(a)}" for a in args) + env_xml = "\n".join( + f" {xml_escape(k)}\n {xml_escape(v)}" + for k, v in sorted(defn["environment"].items()) + ) + keep_alive = "true" if defn["restart"] != "no" else "false" + return ( + '\n' + '\n\n' + f" Label\n com.developing-today.deploy.{xml_escape(name)}\n" + f" ProgramArguments\n \n{arg_xml}\n \n" + f" EnvironmentVariables\n \n{env_xml}\n \n" + f" KeepAlive\n <{keep_alive}/>\n" + " RunAtLoad\n \n" + "\n\n" + ) + + +# --- Generation log (slice 2) -------------------------------------------- +# +# Oracle: design §4.6. The log is append-only, one JSON object per +# activation event; two generations are always retained because the +# log is never truncated. Current/previous are DERIVED by folding the +# events in order: a deploy event makes its generation current, a +# rollback event makes the generation it repointed to current; the +# previous generation is the last distinct generation before the +# current one in that folded history. Rollback therefore never needs +# a rebuild: it re-selects an already-recorded generation. + + +def state_dir(explicit=None): + return ( + explicit + or os.environ.get("DEPLOY_STATE_DIR") + or os.path.expanduser("~/.local/state/deploy") + ) + + +def generations_path(name, explicit_state=None): + return os.path.join(state_dir(explicit_state), "generations", f"{name}.jsonl") + + +def read_generations(name, explicit_state=None): + path = generations_path(name, explicit_state) + if not os.path.exists(path): + return [] + entries = [] + with open(path, "r", encoding="utf-8") as fh: + for lineno, line in enumerate(fh, 1): + line = line.strip() + if not line: + continue + try: + entries.append(json.loads(line)) + except ValueError as exc: + raise ValueError( + f"generation log {path} line {lineno} is not valid JSON: {exc}" + ) from exc + return entries + + +def next_generation_id(entries): + ids = [e["generation"] for e in entries if isinstance(e.get("generation"), int)] + return (max(ids) + 1) if ids else 1 + + +def record_generation( + name, + *, + artifact, + source_rev, + actor, + action="deploy", + generation=None, + result="activated", + at=None, + explicit_state=None, +): + entries = read_generations(name, explicit_state) + if generation is None: + generation = next_generation_id(entries) + entry = { + "generation": generation, + "target": name, + "artifact": artifact, + "source_rev": source_rev, + "actor": actor, + "action": action, + "result": result, + "at": at or datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), + } + path = generations_path(name, explicit_state) + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "a", encoding="utf-8") as fh: + fh.write(json.dumps(entry, sort_keys=True) + "\n") + return entry + + +def current_previous(entries): + # Fold successful activation events into a history of generations + # that were current at some point, most recent last. + history = [] + by_generation = {} + for entry in entries: + gen = entry.get("generation") + if not isinstance(gen, int): + continue + by_generation.setdefault(gen, entry) + if entry.get("result") in ("activated", "rolled-back") or entry.get( + "action" + ) in ("deploy", "rollback"): + history.append(gen) + if not history: + return None, None + current = history[-1] + previous = None + for gen in reversed(history[:-1]): + if gen != current: + previous = gen + break + return by_generation.get(current), ( + by_generation.get(previous) if previous is not None else None + ) + + +# --- Plans, status, rollback logic (slice 2) ------------------------------ + + +def _health_step(defn): + if defn["healthCheck"]: + return f"run the health check: {defn['healthCheck']}" + return "no health check defined for this target; skip the health step" + + +def _flip_back_step(current): + if current is not None: + return ( + "on any failure: flip the profile back to generation " + f"{current['generation']} and restart on it" + ) + return "on any failure: stop the unit (no previous generation to flip back to)" + + +def plan_deploy(name, defn, entries, base=None): + # The ordered activation plan of design §4.1. Returns None when the + # target class has no activation renderer in this slice. + if defn["class"] not in ACTIVATION_CLASSES: + return None + link = profile_link(name, base) + current, _previous = current_previous(entries) + next_id = next_generation_id(entries) + steps = [ + f"build the service package: {defn['package']}", + f"install generation {next_id} into the profile {link} " + f"(nix-env --profile {link} --set {defn['package']})", + ] + if defn["class"] == "systemd": + steps.append( + f"write the unit {unit_name(name)} pointing at " + f"{os.path.join(link, 'current', defn['entryPoint'])}" + ) + steps.append("daemon-reload (systemctl)") + steps.append(f"restart only {unit_name(name)}") + else: # launchd stub + steps.append( + f"write the launchd plist for {name} pointing at " + f"{os.path.join(link, 'current', defn['entryPoint'])}" + ) + steps.append(f"launchctl bootout/bootstrap only the {name} agent") + steps.append(_health_step(defn)) + steps.append(_flip_back_step(current)) + steps.append( + f"append generation {next_id} to the generation log for {name} " + "(generation id, source rev, artifact, timestamp, actor)" + ) + return steps + + +def plan_rollback(name, defn, entries, base=None): + # Returns (steps, None) or (None, error). Rollback is a repoint at + # the previous distinct generation (design §4.1/§4.6), so it is + # only defined when the folded history has one. + if defn["class"] not in ACTIVATION_CLASSES: + return None, ( + f"rollback for class {defn['class']!r} is not an activation-class " + "operation in this slice" + ) + current, previous = current_previous(entries) + if current is None: + return None, f"no generations recorded for {name!r}; nothing to roll back" + if previous is None: + return None, ( + f"only one generation recorded for {name!r}; rollback needs a " + "previous generation (two generations are always retained, §4.6)" + ) + link = profile_link(name, base) + steps = [ + f"repoint the profile {link} at generation {previous['generation']} " + f"({previous['artifact']}) — no rebuild, no re-upload", + ] + if defn["class"] == "systemd": + steps.append(f"restart only {unit_name(name)}") + else: + steps.append(f"launchctl bootout/bootstrap only the {name} agent") + steps.append(_health_step(defn)) + steps.append( + f"on any failure: flip the profile back to generation " + f"{current['generation']} and restart on it" + ) + steps.append( + f"append a rollback event (to generation {previous['generation']}) " + f"to the generation log for {name}" + ) + return steps, None + + +def probe_health(url, timeout=2.0): + # Returns (ok, detail). A probe is a plain GET; 2xx/3xx is healthy. + try: + req = urllib.request.Request(url, method="GET") + with urllib.request.urlopen(req, timeout=timeout) as resp: + return (200 <= resp.status < 400), f"HTTP {resp.status}" + except urllib.error.HTTPError as exc: + return False, f"HTTP {exc.code}" + except Exception as exc: # unreachable, DNS, timeout — all just failed + return False, f"{type(exc).__name__}: {exc}" + + +def format_status(name, defn, entries, health=None): + current, previous = current_previous(entries) + + def describe(entry): + if entry is None: + return "none recorded" + return ( + f"generation {entry['generation']} (source rev {entry.get('source_rev')}, " + f"activated {entry.get('at')} by {entry.get('actor')}, " + f"artifact {entry.get('artifact')})" + ) + + lines = [ + f"{name}: class={defn['class']} targets={','.join(defn['targets'])}", + f"current: {describe(current)}", + f"previous: {describe(previous)}", + ] + if defn["healthCheck"] is None: + lines.append("health: not checked (no healthCheck defined)") + elif health is None: + lines.append(f"health: {defn['healthCheck']} (not probed)") + else: + ok, detail = health + verdict = "ok" if ok else "FAILED" + lines.append(f"health: {defn['healthCheck']} -> {verdict} ({detail})") + return "\n".join(lines) + + +# --- Command dispatch ------------------------------------------------------ + +NOT_IMPLEMENTED = ( + "real activation (nix profile install + service restart + health-check " + "flip-back) is the next slice of issue #5766; slice 2 ships rendering, " + "--dry-run plans, the generation log, and status/rollback logic — " + "no changes were made" +) + + +def _take_value_flag(args, flag): + while flag in args: + idx = args.index(flag) + if idx + 1 >= len(args): + return None, args, False + value = args[idx + 1] + del args[idx : idx + 2] + return value, args, True + return None, args, True + + def main(argv): args = list(argv) registry_path = os.environ.get("DEPLOY_REGISTRY") - # --registry may appear before or after the subcommand. - while "--registry" in args: - idx = args.index("--registry") - if idx + 1 >= len(args): - print("deploy: --registry needs a path", file=sys.stderr) + explicit_state = None + explicit_base = None + for flag in ("--registry", "--state-dir", "--profile-base"): + value, args, ok = _take_value_flag(args, flag) + if not ok: + print(f"deploy: {flag} needs a path", file=sys.stderr) return 2 - registry_path = args[idx + 1] - del args[idx : idx + 2] + if value is not None: + if flag == "--registry": + registry_path = value + elif flag == "--state-dir": + explicit_state = value + else: + explicit_base = value + dry_run = "--dry-run" in args + args = [a for a in args if a != "--dry-run"] + usage = ( + "usage: deploy [--registry PATH] [--state-dir PATH] list | " + " [rollback|status] [--dry-run]" + ) if not args: print(__doc__.splitlines()[0], file=sys.stderr) - print( - "usage: deploy [--registry PATH] list | [rollback|status] [--dry-run]", - file=sys.stderr, - ) - return 2 - if args[0] != "list": - print( - f"deploy: {args[0]!r} is not implemented in slice 1 of issue #5766 " - "(registry + list only; activation/status/rollback are later slices)", - file=sys.stderr, - ) + print(usage, file=sys.stderr) return 2 if registry_path is None: print( @@ -241,7 +619,62 @@ def main(argv): except (OSError, ValueError) as exc: print(f"deploy: cannot load registry {registry_path}: {exc}", file=sys.stderr) return 1 - return cmd_list(registry) + if args[0] == "list": + return cmd_list(registry) + errors = validate(registry) + if errors: + for err in errors: + print(f"deploy: invalid definition: {err}", file=sys.stderr) + return 1 + name = args[0] + if name not in registry: + print(f"deploy: unknown target {name!r}", file=sys.stderr) + return 1 + defn = registry[name] + action = args[1] if len(args) > 1 else "deploy" + if len(args) > 2 or action not in ("deploy", "rollback", "status"): + print(usage, file=sys.stderr) + return 2 + try: + entries = read_generations(name, explicit_state) + except ValueError as exc: + print(f"deploy: {exc}", file=sys.stderr) + return 1 + if action == "status": + health = None + if defn["healthCheck"] is not None: + health = probe_health(defn["healthCheck"]) + print(format_status(name, defn, entries, health)) + return 0 + if action == "deploy": + steps = plan_deploy(name, defn, entries, explicit_base) + if steps is None: + print( + f"deploy: activation for class {defn['class']!r} is a different " + "slice of the deployment architecture (see issue #5767); this " + "slice covers the systemd/launchd classes", + file=sys.stderr, + ) + return 2 + if not dry_run: + print(f"deploy: {NOT_IMPLEMENTED}", file=sys.stderr) + return 2 + print(f"deploy {name} --dry-run: no changes made") + for i, step in enumerate(steps, 1): + print(f" {i}. {step}") + return 0 + # action == rollback + steps, error = plan_rollback(name, defn, entries, explicit_base) + if error is not None: + print(f"deploy: {error}", file=sys.stderr) + return 1 + if not dry_run: + print(f"deploy: {NOT_IMPLEMENTED}", file=sys.stderr) + return 2 + print(f"deploy {name} rollback --dry-run: no changes made") + for i, step in enumerate(steps, 1): + print(f" {i}. {step}") + return 0 if __name__ == "__main__": diff --git a/pkgs/deploy/test_deploy_slice2.py b/pkgs/deploy/test_deploy_slice2.py new file mode 100644 index 0000000000..fcd247b1b8 --- /dev/null +++ b/pkgs/deploy/test_deploy_slice2.py @@ -0,0 +1,276 @@ +#!/usr/bin/env python3 +"""Coverage for the deploy slice-2 invariants (issue #5766). + +Oracle: doc/2026-11-04_deployment-architecture-services-layer.md §4.1, +§4.2 and §4.6, plus the issue text. The invariants under test: + +- A rendered systemd unit (or launchd plist) points at the target's + per-service nix profile `current` link, never at a bare package + path, so a generation flip is a profile repoint and the rendered + file is identical for every generation of the same definition. +- The generation log is append-only; current/previous generations are + the fold of its activation events, and rollback selects the + previous DISTINCT generation — repointing, never rebuilding — and + is refused when fewer than two distinct generations were current. +- `deploy --dry-run` prints the §4.1 plan in order (build, + profile install, unit write, reload, restart only that unit, + health check, flip-back, log append) and creates no state. +- Status reports the folded current/previous generations and the + health verdict for the target's healthCheck URL (or that no check + is defined). + +Stdlib-only, deterministic. CLI cases run deploy.py as a subprocess +against a fixture registry in a temp state dir. + +Usage: test_deploy_slice2.py [path-to-deploy.py] +""" + +import importlib.util +import json +import os +import subprocess +import sys +import tempfile +import unittest + +DEPLOY_PATH = sys.argv[1] if len(sys.argv) > 1 else os.path.join( + os.path.dirname(os.path.abspath(__file__)), "deploy.py" +) + +spec = importlib.util.spec_from_file_location("deploy", DEPLOY_PATH) +deploy = importlib.util.module_from_spec(spec) +spec.loader.exec_module(deploy) + +DEFN = { + "package": "/nix/store/aaa-svc-1.0", + "entryPoint": "bin/svc", + "args": ["--port", "8080", "--greeting", "hello world"], + "environment": {"MODE": "prod", "PCT": "100%"}, + "secrets": ["svc.api-key"], + "user": "svcuser", + "ports": [8080], + "restart": "on-failure", + "healthCheck": "http://127.0.0.1:8080/health", + "targets": ["laptop"], + "class": "systemd", +} +BASE = "/profiles" + + +def record(state, gen, artifact, action="deploy", result="activated"): + return deploy.record_generation( + "svc", + artifact=artifact, + source_rev=f"rev{gen}", + actor="tester", + action=action, + generation=gen, + result=result, + at=f"2026-11-08T00:0{gen}:00Z", + explicit_state=state, + ) + + +class RenderTests(unittest.TestCase): + def test_unit_points_at_profile_current_link(self): + unit = deploy.render_unit("svc", DEFN, base=BASE) + self.assertIn( + "ExecStart=/profiles/svc/current/bin/svc --port 8080 " + '--greeting "hello world"', + unit, + ) + self.assertNotIn("/nix/store/aaa-svc-1.0/bin/svc", unit) + self.assertIn("User=svcuser", unit) + self.assertIn("Restart=on-failure", unit) + + def test_unit_environment_quoting_escapes_percent(self): + unit = deploy.render_unit("svc", DEFN, base=BASE) + self.assertIn('Environment="PCT=100%%"', unit) + self.assertIn("Environment=MODE=prod", unit) + self.assertIn("# secrets resolved by name at activation time: svc.api-key", unit) + + def test_unit_render_is_generation_independent(self): + # The flip-is-a-repoint invariant: the rendered unit cannot + # depend on which generation is current. + self.assertEqual( + deploy.render_unit("svc", DEFN, base=BASE), + deploy.render_unit("svc", dict(DEFN, package="/nix/store/zzz-svc-2.0"), base=BASE), + ) + + def test_plist_stub_points_at_profile_current_link(self): + plist = deploy.render_plist("svc", DEFN, base=BASE) + self.assertIn("com.developing-today.deploy.svc", plist) + self.assertIn("/profiles/svc/current/bin/svc", plist) + self.assertIn("", plist) # KeepAlive for restart != "no" + no_restart = deploy.render_plist("svc", dict(DEFN, restart="no"), base=BASE) + self.assertIn("", no_restart) + + +class GenerationLogTests(unittest.TestCase): + def test_round_trip_and_fold(self): + with tempfile.TemporaryDirectory() as state: + record(state, 1, "/nix/store/aaa-svc-1.0") + record(state, 2, "/nix/store/bbb-svc-1.1") + entries = deploy.read_generations("svc", state) + self.assertEqual([e["generation"] for e in entries], [1, 2]) + current, previous = deploy.current_previous(entries) + self.assertEqual(current["generation"], 2) + self.assertEqual(previous["generation"], 1) + self.assertEqual(deploy.next_generation_id(entries), 3) + + def test_rollback_fold_makes_previous_current(self): + with tempfile.TemporaryDirectory() as state: + record(state, 1, "/nix/store/aaa-svc-1.0") + record(state, 2, "/nix/store/bbb-svc-1.1") + record(state, 1, "/nix/store/aaa-svc-1.0", action="rollback", result="rolled-back") + current, previous = deploy.current_previous( + deploy.read_generations("svc", state) + ) + self.assertEqual(current["generation"], 1) + self.assertEqual(previous["generation"], 2) + + def test_empty_log_has_no_current(self): + with tempfile.TemporaryDirectory() as state: + self.assertEqual(deploy.read_generations("svc", state), []) + self.assertEqual(deploy.current_previous([]), (None, None)) + + def test_malformed_log_line_is_named(self): + with tempfile.TemporaryDirectory() as state: + record(state, 1, "/nix/store/aaa-svc-1.0") + with open(deploy.generations_path("svc", state), "a", encoding="utf-8") as fh: + fh.write("not json\n") + with self.assertRaises(ValueError) as ctx: + deploy.read_generations("svc", state) + self.assertIn("line 2", str(ctx.exception)) + + +class PlanTests(unittest.TestCase): + def test_deploy_plan_order_and_flip_back(self): + with tempfile.TemporaryDirectory() as state: + record(state, 1, "/nix/store/aaa-svc-1.0") + entries = deploy.read_generations("svc", state) + steps = deploy.plan_deploy("svc", DEFN, entries, base=BASE) + text = "\n".join(steps) + order = [ + text.index("build the service package"), + text.index("install generation 2 into the profile"), + text.index("write the unit svc.service"), + text.index("daemon-reload"), + text.index("restart only svc.service"), + text.index("health check"), + text.index("flip the profile back to generation 1"), + text.index("append generation 2 to the generation log"), + ] + self.assertEqual(order, sorted(order)) + self.assertIn("nix-env --profile /profiles/svc --set", text) + + def test_deploy_plan_refuses_other_classes(self): + cf = dict(DEFN, **{"class": "cloudflare"}) + self.assertIsNone(deploy.plan_deploy("svc", cf, [], base=BASE)) + + def test_rollback_plan_selects_previous_without_rebuild(self): + with tempfile.TemporaryDirectory() as state: + record(state, 1, "/nix/store/aaa-svc-1.0") + record(state, 2, "/nix/store/bbb-svc-1.1") + steps, error = deploy.plan_rollback( + "svc", DEFN, deploy.read_generations("svc", state), base=BASE + ) + self.assertIsNone(error) + text = "\n".join(steps) + self.assertIn("repoint the profile /profiles/svc at generation 1", text) + self.assertIn("no rebuild", text) + self.assertIn("restart only svc.service", text) + + def test_rollback_refused_with_one_generation(self): + with tempfile.TemporaryDirectory() as state: + record(state, 1, "/nix/store/aaa-svc-1.0") + steps, error = deploy.plan_rollback( + "svc", DEFN, deploy.read_generations("svc", state), base=BASE + ) + self.assertIsNone(steps) + self.assertIn("only one generation", error) + + def test_rollback_refused_with_no_generations(self): + steps, error = deploy.plan_rollback("svc", DEFN, [], base=BASE) + self.assertIsNone(steps) + self.assertIn("no generations recorded", error) + + +class StatusTests(unittest.TestCase): + def test_status_reports_fold_and_unprobed_health(self): + with tempfile.TemporaryDirectory() as state: + record(state, 1, "/nix/store/aaa-svc-1.0") + record(state, 2, "/nix/store/bbb-svc-1.1") + out = deploy.format_status( + "svc", DEFN, deploy.read_generations("svc", state) + ) + self.assertIn("current: generation 2 (source rev rev2", out) + self.assertIn("previous: generation 1 (source rev rev1", out) + self.assertIn("(not probed)", out) + + def test_status_no_healthcheck_defined(self): + out = deploy.format_status("svc", dict(DEFN, healthCheck=None), []) + self.assertIn("current: none recorded", out) + self.assertIn("health: not checked (no healthCheck defined)", out) + + def test_status_health_verdicts(self): + out = deploy.format_status("svc", DEFN, [], health=(True, "HTTP 200")) + self.assertIn("-> ok (HTTP 200)", out) + out = deploy.format_status("svc", DEFN, [], health=(False, "HTTP 500")) + self.assertIn("-> FAILED (HTTP 500)", out) + + +class CliTests(unittest.TestCase): + def run_cli(self, state, *argv): + registry = {"svc": DEFN} + reg_path = os.path.join(state, "registry.json") + with open(reg_path, "w", encoding="utf-8") as fh: + json.dump(registry, fh) + env = dict(os.environ, DEPLOY_STATE_DIR=state) + return subprocess.run( + [sys.executable, DEPLOY_PATH, "--registry", reg_path, *argv], + capture_output=True, text=True, env=env, timeout=30, + ) + + def test_dry_run_prints_plan_and_creates_no_state(self): + with tempfile.TemporaryDirectory() as state: + proc = self.run_cli(state, "svc", "--dry-run") + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertIn("no changes made", proc.stdout) + self.assertIn("install generation 1 into the profile", proc.stdout) + self.assertFalse(os.path.exists(os.path.join(state, "generations"))) + + def test_real_deploy_is_refused_in_this_slice(self): + with tempfile.TemporaryDirectory() as state: + proc = self.run_cli(state, "svc") + self.assertEqual(proc.returncode, 2) + self.assertIn("next slice of issue #5766", proc.stderr) + self.assertFalse(os.path.exists(os.path.join(state, "generations"))) + + def test_cli_rollback_dry_run_refused_with_one_generation(self): + with tempfile.TemporaryDirectory() as state: + record(state, 1, "/nix/store/aaa-svc-1.0") + proc = self.run_cli(state, "svc", "rollback", "--dry-run") + self.assertEqual(proc.returncode, 1) + self.assertIn("only one generation", proc.stderr) + + def test_cli_status_reads_seeded_log(self): + with tempfile.TemporaryDirectory() as state: + record(state, 1, "/nix/store/aaa-svc-1.0") + record(state, 2, "/nix/store/bbb-svc-1.1") + # healthCheck points at a closed port: status still exits 0 + # and reports the FAILED verdict — status is the audit surface. + proc = self.run_cli(state, "svc", "status") + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertIn("current: generation 2", proc.stdout) + self.assertIn("health: http://127.0.0.1:8080/health -> FAILED", proc.stdout) + + def test_cli_unknown_target(self): + with tempfile.TemporaryDirectory() as state: + proc = self.run_cli(state, "nope", "status") + self.assertEqual(proc.returncode, 1) + self.assertIn("unknown target", proc.stderr) + + +if __name__ == "__main__": + unittest.main(argv=[sys.argv[0]])