1#!/usr/bin/env python3
2import json
3import os
4from pathlib import Path
5import subprocess
6import tempfile
7from types import SimpleNamespace
8import unittest
9from unittest.mock import patch
10
11import release
12
13
14class HostConfiguration(unittest.TestCase):
15 def test_vm_limit_changes_invalidate_the_host_configuration(self):
16 with tempfile.TemporaryDirectory() as temporary:
17 root = Path(temporary)
18 (root / 'tools').mkdir()
19 limits = root / 'tools/vm-ai-limits.json'
20 limits.write_text('{"host_total":8}')
21 before = release.host_digest(root)
22 limits.write_text('{"host_total":4}')
23 self.assertNotEqual(release.host_digest(root), before)
24
25 def select(self, hostname, configurations):
26 with patch.object(release.os, "uname", return_value=SimpleNamespace(nodename=hostname)), patch.object(
27 release.subprocess, "run", return_value=subprocess.CompletedProcess([], 0, json.dumps(configurations)),
28 ) as command:
29 result = release.host_configuration(Path("/release"))
30 command.assert_called_once_with(
31 ["nix", "--extra-experimental-features", "nix-command flakes", "eval", "--json", "path:/release#nixosConfigurations", "--apply", "builtins.attrNames"],
32 check=True, capture_output=True, text=True,
33 )
34 return result
35
36 def test_canonical_hostname(self):
37 for hostname in ("snowglobe", "snowglobe.paperclover.net"):
38 with self.subTest(hostname=hostname):
39 self.assertEqual(self.select(hostname, ["installer", "snowglobe", "vm"]), "snowglobe")
40
41 def test_rehearsal_stays_on_vm(self):
42 self.assertEqual(self.select("snowglobe-rehearsal", ["installer", "snowglobe", "vm"]), "vm")
43
44 def test_unrelated_host_is_not_retargeted(self):
45 self.assertEqual(self.select("fixture", ["fixture", "vm"]), "fixture")
46 for hostname in ("fixture", "snowglobe", "snowglobe-rehearsal"):
47 with self.subTest(hostname=hostname), self.assertRaisesRegex(ValueError, "no NixOS configuration"):
48 self.select(hostname, ["installer"])
49
50
51class ActivationEnvironment(unittest.TestCase):
52 def test_host_switch_refreshes_inherited_name_and_preserves_overrides(self):
53 for before, after, inherited, expected in (
54 ("fixture", "snowglobe", "fixture", "snowglobe"),
55 ("fixture", "snowglobe", None, "snowglobe"),
56 ("fixture", "snowglobe", "test-override", "test-override"),
57 ("snowglobe-rehearsal", "snowglobe-rehearsal", "snowglobe-rehearsal", "snowglobe-rehearsal"),
58 ):
59 with self.subTest(before=before, inherited=inherited), tempfile.TemporaryDirectory() as temporary:
60 root = Path(temporary)
61 source = root / "release"
62 source.mkdir()
63 (source / "tools").mkdir()
64 (source / "tools/snowglobe.py").touch()
65 (source / ".snowglobe-release.json").write_text('{"version":1}')
66 hostname = before
67 observed = []
68 calls = []
69 read_text = Path.read_text
70
71 def run(argv, **kwargs):
72 nonlocal hostname
73 calls.append(argv)
74 if argv[:3] == ["hostnamectl", "set-hostname", "--transient"]:
75 hostname = after
76 if argv[-1] == "deploy":
77 observed.append(kwargs["env"].get("SNOWGLOBE_NODE_NAME"))
78 return subprocess.CompletedProcess(argv, 0, '"leader"')
79
80 with patch.dict(os.environ), patch.object(release, "ROOT", root), patch.object(
81 release, "STATE", root,
82 ), patch.object(release, "check_release", return_value=source), patch.object(
83 release, "current_release", return_value=None,
84 ), patch.object(release, "host_digest", return_value="new"), patch.object(
85 release, "host_configuration", return_value="fixture",
86 ), patch.object(release, "jobs", return_value=set()), patch.object(
87 release.os, "uname", side_effect=lambda: SimpleNamespace(nodename=hostname),
88 ), patch.object(release.subprocess, "run", side_effect=run):
89 if inherited is None:
90 os.environ.pop("SNOWGLOBE_NODE_NAME", None)
91 else:
92 os.environ["SNOWGLOBE_NODE_NAME"] = inherited
93 with patch.object(
94 Path, "read_text", autospec=True,
95 side_effect=lambda path: after + "\n" if path == Path("/etc/hostname") else read_text(path),
96 ):
97 release.activate("0123456789abcdef", initial=True)
98 self.assertEqual(observed, [expected])
99 self.assertEqual(hostname, after)
100 changes = [argv for argv in calls if argv[0] == "hostnamectl"]
101 self.assertEqual(changes, [["hostnamectl", "set-hostname", "--transient", after]] if before != after else [])
102 if changes:
103 switch = next(i for i, argv in enumerate(calls) if argv[:2] == ["nixos-rebuild", "switch"])
104 rename = calls.index(changes[0])
105 deploy = next(i for i, argv in enumerate(calls) if argv[-1] == "deploy")
106 self.assertLess(switch, rename)
107 self.assertLess(rename, deploy)
108
109
110class BootPreparation(unittest.TestCase):
111 def test_installs_a_boot_entry_and_preserves_the_default_without_activation(self):
112 entries = [
113 [{"id": "previous.conf", "isDefault": True}],
114 [{"id": "candidate.conf", "options": "init=/candidate/init loglevel=4"}],
115 ]
116 calls = []
117
118 def run(argv, **kwargs):
119 calls.append(argv)
120 return subprocess.CompletedProcess(argv, 0, json.dumps(entries.pop(0)) if argv[:2] == ["bootctl", "list"] else "")
121
122 with patch.object(release, "check_release", return_value=Path("/candidate")), patch.object(
123 release, "host_configuration", return_value="snowglobe",
124 ), patch.object(release.subprocess, "run", side_effect=run), patch.object(
125 Path, "resolve", return_value=Path("/candidate"),
126 ):
127 release.prepare_boot("0123456789abcdef")
128 self.assertEqual(calls, [
129 ["bootctl", "list", "--json=short"],
130 ["nixos-rebuild", "boot", "--flake", "path:/candidate#snowglobe"],
131 ["bootctl", "set-default", "previous.conf"],
132 ["bootctl", "list", "--json=short"],
133 ])
134
135 def test_failed_build_restores_the_default_without_selecting_a_candidate(self):
136 with patch.object(release, "check_release", return_value=Path("/candidate")), patch.object(
137 release, "host_configuration", return_value="snowglobe",
138 ), patch.object(release.subprocess, "run", side_effect=[
139 subprocess.CompletedProcess([], 0, '[{"id":"previous.conf","isDefault":true}]'),
140 subprocess.CalledProcessError(1, "nixos-rebuild"),
141 subprocess.CompletedProcess([], 0),
142 ]) as command:
143 with self.assertRaises(subprocess.CalledProcessError):
144 release.prepare_boot("0123456789abcdef")
145 self.assertEqual(command.call_args.args[0], ["bootctl", "set-default", "previous.conf"])
146 self.assertEqual(command.call_count, 3)
147
148
149if __name__ == "__main__":
150 unittest.main()