gunk-dev/the-valley

worker-e2e.nix

sourceb8640be0aecdmain's published tip history
21.4 KiB
1# The check worker on a host: one NixOS machine running the module with the
2# build slice and the worker on, beside the controllers and the registry
3# compiler, and a project with ready changes. The worker makes its key the
4# first time it starts, readable by it alone, and says its public halves.
5# An earlier start that was interrupted leaves nothing that stands in the
6# way. Until the registry holds the key, the worker cannot reach the
7# host's repositories. Once it does, a pass builds the nix checks a ready
8# change requires, one build at a time, through the machine's nix daemon,
9# and the evidence is on origin before anyone approves the change. The
10# timer runs the next pass.
11#
12# Then the slice's caps, with builds that are not the worker's. A build
13# that wants six CPUs gets four. A change whose check eats memory without
14# end is built while two unrelated builds hold memory of their own. The
15# kernel kills the process in the slice using the most memory, so the
16# unrelated build bigger than the runaway is killed with it, the smaller
17# one finishes, and the rest of the host goes on as it was. Last, the key
18# is the same after many starts and a reboot.
19#
20# The slice's default caps are 4 CPUs and 8 GiB. The machine here has
21# 2 GiB, so the memory cap is lowered at runtime, after the check reads
22# the default values off the slice, to let builds run past it. module-eval
23# holds the values the module renders.
24{
25 pkgs,
26 lib,
27 self,
28 packages,
29 ...
30}:
31let
32 # Throwaway keys, made once at build time. They hold no authority
33 # anywhere: the machine that trusts them exists for one test run. The
34 # worker's key is not among them: the worker makes its own on the host.
35 keys = pkgs.runCommand "valley-worker-e2e-keys" { nativeBuildInputs = [ pkgs.openssh ]; } ''
36 mkdir $out
37 for who in integrator contributor; do
38 ssh-keygen -q -t ed25519 -N "" -C "$who" -f "$out/$who"
39 done
40 '';
41 pub = who: lib.fileContents "${keys}/${who}.pub";
42
43 declaration = pkgs.writeText "valley-worker-e2e.cue" ''
44 package valley
45
46 projects: {
47 // The instance repository, which carries the floor and the registry.
48 "instance": protection: refs: ["refs/heads/main"]
49 "project": protection: {}
50 }
51 '';
52
53 # A floor that requires two nix checks of every change.
54 floor = pkgs.writeText "floor.cue" ''
55 package verification
56
57 floor: {
58 checks: {
59 first: {runner: "nix", attribute: "first"}
60 second: {runner: "nix", attribute: "second"}
61 }
62 classes: {}
63 unclassified: {first: true, second: true}
64 }
65 '';
66
67 # The project's flake, with no inputs, so the machine builds it offline.
68 # Each check runs a script from the project's tree in the sandbox's
69 # shell, and the script is the derivation's one input. The project's own
70 # scripts spin for a few seconds, so two builds at once would be seen at
71 # once, and write the cores the daemon gave them. The runaway change's
72 # first script instead doubles a string until something stops it.
73 flake = pkgs.writeText "flake.nix" ''
74 {
75 outputs =
76 { self }:
77 let
78 check = name: script: derivation {
79 inherit name;
80 system = "x86_64-linux";
81 builder = "/bin/sh";
82 args = [ script ];
83 };
84 in
85 {
86 checks.x86_64-linux = {
87 first = check "worker-first" ./first.sh;
88 second = check "worker-second" ./second.sh;
89 };
90 };
91 }
92 '';
93 flakeLock = pkgs.writeText "flake.lock" ''{"nodes":{"root":{}},"root":"root","version":7}'';
94 spin = pkgs.writeText "spin.sh" ''
95 i=0
96 while [ $i -lt 1000000 ]; do i=$((i+1)); done
97 echo $NIX_BUILD_CORES > $out
98 '';
99 runaway = pkgs.writeText "runaway.sh" ''
100 x=a
101 while :; do x=$x$x; done
102 '';
103
104 # Builds that are not the worker's, through the same daemon. small and
105 # big each hold a string of 1 MiB or 128 MiB and then spin for a while;
106 # cpu spins on six CPUs until it is stopped.
107 unrelated = pkgs.writeText "unrelated.nix" ''
108 { kind }:
109 let
110 hold = n: "x=a; n=0; while [ $n -lt ''${n} ]; do x=$x$x; n=$((n+1)); done; i=0; while [ $i -lt 8000000 ]; do i=$((i+1)); done; echo ok > $out";
111 scripts = {
112 small = hold "20";
113 big = hold "27";
114 cpu = "for i in 1 2 3 4 5 6; do (while :; do :; done) & done; wait";
115 };
116 in
117 derivation {
118 name = "unrelated-''${kind}";
119 system = "x86_64-linux";
120 builder = "/bin/sh";
121 args = [ "-c" scripts.''${kind} ];
122 }
123 '';
124
125 # What the daemon's builds look like while the worker runs: the number
126 # of build users with a process, and the cgroup of each such process,
127 # sampled ten times a second.
128 sampler = pkgs.writeShellScript "valley-worker-e2e-sampler" ''
129 PATH=${
130 lib.makeBinPath [
131 pkgs.coreutils
132 pkgs.gawk
133 pkgs.procps
134 ]
135 }
136 while :; do
137 ps -eo user:32=,cgroup:512= | awk '$1 ~ /^nixbld/' > /tmp/sample
138 awk '{print $1}' /tmp/sample | sort -u | wc -l >> /tmp/builders
139 awk '{print $2}' /tmp/sample >> /tmp/build-cgroups
140 sleep 0.1
141 done
142 '';
143in
144{
145 worker-e2e = pkgs.testers.runNixOSTest {
146 name = "valley-worker-e2e";
147 nodes.host = {
148 imports = [ self.nixosModules.default ];
149 # Six CPUs: attest could run six builds at once if the unit let it,
150 # and a build can want more CPUs than the slice's quota of four.
151 virtualisation.cores = 6;
152 virtualisation.memorySize = 2048;
153 environment.systemPackages = [
154 pkgs.git
155 packages.valley
156 ];
157 services.valley = {
158 enable = true;
159 config = declaration;
160 buildSlice.enable = true;
161 authorizedKeys = [
162 {
163 principal = "contributor";
164 key = pub "contributor";
165 }
166 ];
167 identity.enable = true;
168 integrator = {
169 enable = true;
170 signingKeyFile = "${keys}/integrator";
171 instanceProject = "instance";
172 signerProjects."worker/attestations" = [ "project" ];
173 };
174 worker = {
175 enable = true;
176 projects = [ "project" ];
177 signerName = "worker/attestations";
178 };
179 };
180 # NixOS test machines panic on any OOM, a cgroup's included
181 # (test-instrumentation.nix). A host does not, and the runaway build
182 # below is stopped by the slice's OOM, so a host's default is restored.
183 boot.kernel.sysctl."vm.panic_on_oom" = 0;
184 # The test starts each pass itself until it checks the timer, so no
185 # pass runs before the test is ready for it. When it checks the timer,
186 # the next pass starts a second after the last one ended, rather than
187 # a minute and up to a minute of systemd's accuracy later.
188 systemd.timers.valley-worker.timerConfig.OnActiveSec = lib.mkForce "1h";
189 services.valley.worker.interval = "1s";
190 systemd.timers.valley-worker.timerConfig.AccuracySec = "1s";
191 # The machine has no network. Without these, every new build waits
192 # for the daemon's lookups in cache.nixos.org to fail, and every boot
193 # waits for a DHCP lease on an interface nothing here uses.
194 nix.settings.substituters = lib.mkForce [ ];
195 networking.useDHCP = false;
196 };
197
198 testScript = ''
199 import shlex
200
201 host.wait_for_unit("multi-user.target")
202 host.succeed("systemctl is-active valley-worker.timer")
203 host.succeed("systemctl stop valley-worker.timer")
204
205 git = "sudo -u git git"
206 state = "/var/lib/valley-worker"
207 ssh = shlex.quote(
208 "ssh -i /root/keys/contributor -o IdentitiesOnly=yes -o BatchMode=yes"
209 " -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null"
210 )
211 contributor = f"cd /root/project && GIT_SSH_COMMAND={ssh}"
212 commit = "git -c user.name=contributor -c user.email=contributor@localhost commit --quiet"
213
214 def journal():
215 return host.succeed("journalctl -u valley-worker -o cat")
216
217 def unrelated(kind):
218 host.succeed(
219 f"systemd-run --unit=unrelated-{kind} --remain-after-exit --setenv=NIX_REMOTE=daemon"
220 f" nix-build ${unrelated} --argstr kind {kind} --no-out-link"
221 )
222
223 def unit_property(name, prop):
224 return host.succeed(f"systemctl show -p {prop} --value {name}").strip()
225
226 def attestations():
227 return host.succeed(
228 f"{git} -C /srv/git/project.git for-each-ref --format='%(refname)' refs/the-valley/attestations/"
229 ).split()
230
231 def registry(worker):
232 principals = [
233 '"contributor": {',
234 ' kind: "human"',
235 ' keys: [{class: "ssh-ed25519", bound: "host", public: "${
236 lib.concatStringsSep " " (lib.take 2 (lib.splitString " " (pub "contributor")))
237 }"}]',
238 ' grants: {push: boundary: "push", govern: boundary: "registry"}',
239 "}",
240 ]
241 if worker:
242 principals += [
243 '"worker": {',
244 ' kind: "machine"',
245 f' keys: [{{class: "ssh-ed25519", bound: "host", public: "{worker}", signs: "worker/attestations"}}]',
246 ' grants: push: boundary: "push"',
247 ' expires: "2099-01-01"',
248 "}",
249 ]
250 return "\n".join(
251 [
252 "package identity",
253 'boundaries: {"push": kind: "git-push", "registry": kind: "registry"}',
254 'genesis: "contributor"',
255 "principals: {",
256 ]
257 + principals
258 + ["}"]
259 )
260
261 # The instance's main carries the floor and the registry. It is
262 # landed by a local write, which runs no hook, as an operator seeds
263 # a protected repository.
264 def land_instance(worker):
265 host.succeed(
266 "rm -rf /tmp/instance && mkdir -p /tmp/instance/policy/instance /tmp/instance/identity",
267 "cp ${floor} /tmp/instance/policy/instance/floor.cue",
268 f"cat > /tmp/instance/identity/registry.cue <<'EOF'\n{registry(worker)}\nEOF",
269 f"cd /tmp/instance && git init --quiet --initial-branch=main && git add -A && {commit} -m instance",
270 "chown -R git:git /tmp/instance",
271 f"{git} -C /srv/git/instance.git fetch --quiet --force /tmp/instance main:refs/heads/main",
272 "systemctl start valley-identity.service",
273 )
274
275 # A branch of the project with the first check's script given,
276 # pushed by the contributor and readied.
277 def ready(branch, first):
278 host.succeed(
279 f"cd /root/project && git checkout --quiet -b {branch} origin/main",
280 f"cp {first} /root/project/first.sh && echo {branch} >> /root/project/README.md",
281 f"cd /root/project && git add -A && {commit} -m {branch}",
282 f"{contributor} git push --quiet origin {branch}",
283 f"{contributor} valley ready {branch}",
284 )
285
286 with subtest("the instance and the project are seeded, and a change is ready"):
287 land_instance(None)
288 host.succeed(
289 "mkdir -p /tmp/project/policy",
290 "cp ${flake} /tmp/project/flake.nix",
291 "cp ${flakeLock} /tmp/project/flake.lock",
292 "cp ${spin} /tmp/project/first.sh",
293 "cp ${spin} /tmp/project/second.sh",
294 "echo 'git@host:instance.git' > /tmp/project/policy/valley",
295 "echo project > /tmp/project/README.md",
296 f"cd /tmp/project && git init --quiet --initial-branch=main && git add -A && {commit} -m project",
297 "chown -R git:git /tmp/project",
298 f"{git} -C /srv/git/project.git fetch --quiet /tmp/project main:refs/heads/main",
299 "mkdir -p /root/keys && install -m 600 ${keys}/contributor /root/keys/contributor",
300 f"GIT_SSH_COMMAND={ssh} git clone --quiet git@localhost:project.git /root/project",
301 "git -C /root/project config valley.principal contributor",
302 "git -C /root/project config user.name contributor",
303 "git -C /root/project config user.email contributor@localhost",
304 )
305 ready("good", "${spin}")
306
307 with subtest("the first start makes the key, readable by the worker alone, and says its public halves"):
308 host.fail(f"test -e {state}/key")
309 # What an earlier start killed half way leaves: a partial key and
310 # public half under the temporary names, and a public half with
311 # no key.
312 host.succeed(
313 f"sudo -u valley-worker sh -c 'echo partial > {state}/key.new;"
314 f" echo partial > {state}/key.new.pub; echo stale > {state}/key.pub'"
315 )
316 # Not enrolled yet, so the host's sshd turns the worker away and
317 # the pass stops before it builds anything.
318 host.fail("systemctl start valley-worker.service")
319 assert host.succeed(f"stat -c '%a %U %G' {state}").strip() == "700 valley-worker valley-worker"
320 assert host.succeed(f"stat -c '%a %U %G' {state}/key").strip() == "400 valley-worker valley-worker"
321 host.succeed(f"test -f {state}/key && test ! -L {state}/key")
322 for other in ["git", "valley-integrator", "nobody"]:
323 host.fail(f"sudo -u {other} cat {state}/key")
324 public = host.succeed(f"cat {state}/key.pub").strip()
325 verifier = host.succeed(f"cat {state}/verifier").strip()
326 assert verifier.startswith("worker/attestations+"), verifier
327 keyhash = verifier.split("+")[1]
328 said = journal()
329 assert f"the worker's ssh public key is {public}" in said, said
330 assert f"the worker's verifier line is {verifier}" in said, said
331 assert "PRIVATE KEY" not in said, said
332 assert host.succeed(f"ssh-keygen -y -f {state}/key").split()[1] == public.split()[1]
333 host.fail(f"ls {state} | grep -q '^key.new'")
334 fingerprint = host.succeed(f"ssh-keygen -lf {state}/key").strip()
335 assert attestations() == []
336
337 with subtest("enrolled in the registry, the worker builds the ready change's checks one at a time and publishes them"):
338 land_instance(" ".join(public.split()[:2]))
339 host.succeed(f"grep -q '^worker/attestations+{keyhash}+' /var/lib/valley-identity/known-signers")
340 host.wait_until_succeeds(
341 f"{git} -C /srv/git/instance.git cat-file blob refs/the-valley/signers:known-signers"
342 f" | grep -q '^worker/attestations+{keyhash}+'",
343 timeout=60,
344 )
345 host.succeed("systemd-run --unit=valley-worker-e2e-sampler ${sampler}")
346 host.succeed("systemctl start valley-worker.service")
347 host.succeed("systemctl stop valley-worker-e2e-sampler")
348 said = journal()
349 assert "building first, second" in said, said
350 refs = attestations()
351 assert len(refs) == 1 and refs[0].endswith(f"/{keyhash}"), refs
352 assert f"published {refs[0]}" in said, said
353 for check in ["first", "second"]:
354 host.succeed(f"{git} -C /srv/git/project.git cat-file -e {refs[0]}:{check}/statement.note")
355 # One build at a time, each in the daemon's cgroup, inside the
356 # slice, each told it may use 4 cores.
357 builders = [int(n) for n in host.succeed("cat /tmp/builders").split()]
358 assert max(builders) == 1, builders
359 cgroups = set(host.succeed("cat /tmp/build-cgroups").split())
360 assert cgroups and all(c.startswith("0::/valley.slice/valley-builds.slice/nix-daemon.service") for c in cgroups), cgroups
361 for check in ["first", "second"]:
362 assert host.succeed(f"cat /nix/store/*-worker-{check}").strip() == "4", check
363 for unit in ["valley-worker.service", "nix-daemon.service"]:
364 assert host.succeed(f"systemctl show -p Slice --value {unit}").strip() == "valley-builds.slice", unit
365
366 with subtest("the timer runs the next pass, which finds the evidence on origin and builds nothing"):
367 host.succeed("systemctl start valley-worker.timer")
368 host.wait_until_succeeds(
369 "journalctl -u valley-worker -o cat | grep -q 'origin holds evidence for every nix check it requires'",
370 timeout=150,
371 )
372 host.succeed("systemctl stop valley-worker.timer")
373 host.wait_until_succeeds("test \"$(systemctl show -p ActiveState --value valley-worker)\" != activating")
374 assert len(attestations()) == 1
375
376 with subtest("the slice holds its default caps"):
377 cgroup = "/sys/fs/cgroup/valley.slice/valley-builds.slice"
378 assert host.succeed(f"cat {cgroup}/cpu.max").strip() == "400000 100000"
379 assert host.succeed(f"cat {cgroup}/memory.max").strip() == str(8 * 1024**3)
380 assert host.succeed(f"cat {cgroup}/memory.swap.max").strip() == "0"
381
382 with subtest("a build that wants six CPUs gets the slice's four"):
383 unrelated("cpu")
384 host.wait_until_succeeds("test \"$(ps -eo user= | grep -c '^nixbld')\" -ge 7", timeout=60)
385 host.sleep(2)
386 stat = lambda: dict(line.split() for line in host.succeed(f"cat {cgroup}/cpu.stat").splitlines())
387 before = stat()
388 host.sleep(10)
389 after = stat()
390 cpus = (int(after["usage_usec"]) - int(before["usage_usec"])) / 10e6
391 assert 3.0 < cpus < 4.5, cpus
392 assert int(after["nr_throttled"]) > int(before["nr_throttled"]), (before, after)
393 host.succeed("systemctl stop unrelated-cpu")
394 host.wait_until_succeeds("! ps -eo user= | grep -q '^nixbld'", timeout=60)
395
396 with subtest("a runaway build is stopped at the memory cap, a bigger unrelated build is stopped with it, and the rest of the host stays healthy"):
397 ready("runaway", "${runaway}")
398 failed_before = set(host.succeed("systemctl list-units --state=failed --no-legend --plain | cut -d' ' -f1").split())
399 # Two builds that are not the worker's, with room to make their
400 # strings. The shell takes about twice a string's size while it
401 # makes it, so what big holds is read once it stops growing.
402 host.succeed("systemctl set-property --runtime valley-builds.slice MemoryMax=1536M")
403 unrelated("small")
404 unrelated("big")
405 host.wait_until_succeeds("ps -eo user=,rss= | awk '$1 ~ /^nixbld/ && $2 > 100000' | grep -q .", timeout=60)
406 biggest = lambda: int(host.succeed("ps -eo user=,rss= | awk '$1 ~ /^nixbld/ {print $2}' | sort -n | tail -1").strip())
407 held = 0
408 for _ in range(30):
409 host.sleep(1)
410 now = biggest()
411 if now == held:
412 break
413 held = now
414 assert held > 100000, held
415 # The cap is what the slice cannot give back, and half of what big
416 # holds. The runaway reaches the cap while it is still smaller than
417 # big.
418 memory = dict(line.split() for line in host.succeed(f"cat {cgroup}/memory.stat").splitlines())
419 cap = int(memory["anon"]) + int(memory["shmem"]) + held * 1024 // 2
420 host.succeed(f"systemctl set-property --runtime valley-builds.slice MemoryMax={cap}")
421 host.fail("systemctl start valley-worker.service")
422 said = journal()
423 assert "the batch did not pass" in said, said
424 kills = host.succeed(f"sed -n 's/^oom_kill //p' {cgroup}/memory.events").strip()
425 assert int(kills) >= 2, kills
426 assert len(attestations()) == 1
427 # The kernel killed the biggest process in the slice: the unrelated
428 # big build, before the runaway grew past it, and then the runaway.
429 # The small build was never the biggest, and it finishes.
430 host.wait_until_succeeds("test \"$(systemctl show -p SubState --value unrelated-small)\" = exited", timeout=300)
431 assert unit_property("unrelated-small", "Result") == "success"
432 host.wait_until_succeeds("test \"$(systemctl show -p ActiveState --value unrelated-big)\" = failed", timeout=60)
433 # The units the host runs are as they were, the daemon still
434 # answers, and the git user still serves pushes and fetches.
435 host.succeed(
436 "systemctl is-active sshd.service nix-daemon.service nix-daemon.socket"
437 " valley-integrator@instance.service valley-integrator@project.service"
438 )
439 failed_after = set(host.succeed("systemctl list-units --state=failed --no-legend --plain | cut -d' ' -f1").split())
440 assert failed_after <= failed_before | {"valley-worker.service", "unrelated-big.service"}, failed_after
441 host.succeed("nix-store --store daemon --query --hash /run/current-system")
442 host.succeed(f"{contributor} git ls-remote origin refs/heads/runaway | grep -q runaway")
443 # The failed batch waits before it is built again.
444 host.succeed("systemctl start valley-worker.service")
445 assert "failed 1 time in a row, so it is not built again before" in journal()
446
447 with subtest("the key is the same after many starts and a reboot, and is not said again"):
448 assert host.succeed(f"ssh-keygen -lf {state}/key").strip() == fingerprint
449 host.shutdown()
450 host.start()
451 host.wait_for_unit("multi-user.target")
452 host.succeed("systemctl stop valley-worker.timer")
453 host.succeed("systemctl start valley-worker.service")
454 assert host.succeed(f"ssh-keygen -lf {state}/key").strip() == fingerprint
455 assert host.succeed(f"cat {state}/verifier").strip() == verifier
456 host.fail("journalctl -b -u valley-worker -o cat | grep -q 'verifier line is'")
457 '';
458 };
459}