gunk-dev/the-valley

worker-e2e.nix

sourcedd85a8e116a8main's published tip history
39.6 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 side by side, as many at once as the host gives it
9# slots, through the machine's nix daemon, and the evidence is on origin
10# before anyone approves the change. The timer runs the next pass.
11#
12# Then the wake directory. A move the worker reads starts a pass with the
13# timer stopped, and a move during a pass gets the next one. A landing by
14# the integrator's own service marks the worker while the project's mirror
15# and the bus hang, and so does a ready push. A floor landed in the
16# instance, which the worker does not build, marks it, and the next pass
17# reads the new floor. With the timer at its minute, a
18# pass killed during a build, and a pass that cannot reach the
19# repositories, leave their claim, and the timer's next pass builds the
20# change with no new mark. A failed batch is not built again before its
21# wait, however many marks and timer passes come.
22#
23# Then the slice's caps, with builds that are not the worker's. A build
24# that wants six CPUs is held to the slice's quota. A change whose check eats memory without
25# end is built while two unrelated builds hold memory of their own. The
26# kernel kills the process in the slice using the most memory, so the
27# unrelated build bigger than the runaway is killed with it, the smaller
28# one finishes, and the rest of the host goes on as it was. Last, the key
29# is the same after many starts and a reboot.
30#
31# The slice's default caps are 4 CPUs and 8 GiB. The machine here has
32# 2 GiB, so the memory cap is lowered at runtime, after the check reads
33# the default values off the slice, to let builds run past it. module-eval
34# holds the values the module renders.
35{
36 pkgs,
37 lib,
38 self,
39 machineValley,
40 ...
41}:
42let
43 # Throwaway keys, made once at build time. They hold no authority
44 # anywhere: the machine that trusts them exists for one test run. The
45 # worker's key is not among them: the worker makes its own on the host.
46 keys = pkgs.runCommand "valley-worker-e2e-keys" { nativeBuildInputs = [ pkgs.openssh ]; } ''
47 mkdir $out
48 for who in integrator contributor; do
49 ssh-keygen -q -t ed25519 -N "" -C "$who" -f "$out/$who"
50 done
51 '';
52 pub = who: lib.fileContents "${keys}/${who}.pub";
53
54 declaration = pkgs.writeText "valley-worker-e2e.cue" ''
55 package valley
56
57 projects: {
58 // The instance repository, which carries the floor and the registry.
59 "instance": protection: refs: ["refs/heads/main"]
60 // The project's mirror is a local repository, which a scenario
61 // below makes hang.
62 "project": {
63 protection: {}
64 mirrors: ["/srv/hung.git"]
65 }
66 }
67 '';
68
69 # A floor that requires two nix checks of every change but one to the
70 # policy alone, so the instance's own floor lands by integration with no
71 # evidence. floorThird, which a scenario lands in the instance, requires a
72 # third check of the same attribute as the second.
73 floorWith = third: pkgs.writeText "floor.cue" ''
74 package verification
75
76 floor: {
77 checks: {
78 first: {runner: "nix", attribute: "first"}
79 second: {runner: "nix", attribute: "second"}
80 ${lib.optionalString third ''third: {runner: "nix", attribute: "second"}''}
81 }
82 classes: policy: {paths: {"policy/**": true}, requires: {}}
83 unclassified: {first: true, second: true${lib.optionalString third ", third: true"}}
84 }
85 '';
86 floor = floorWith false;
87 floorThird = floorWith true;
88
89 # The project's flake, with no inputs, so the machine builds it offline.
90 # Each check runs a script from the project's tree in the sandbox's
91 # shell, and the script is the derivation's one input. The project's own
92 # scripts spin for about half a second, several of the sampler's ticks,
93 # so the two builds a pass runs at once are seen at once, and write the
94 # cores the daemon gave them. The runaway change's first script instead
95 # doubles a string until something stops it.
96 flake = pkgs.writeText "flake.nix" ''
97 {
98 outputs =
99 { self }:
100 let
101 check = name: script: derivation {
102 inherit name;
103 system = "x86_64-linux";
104 builder = "/bin/sh";
105 args = [ script ];
106 };
107 in
108 {
109 checks.x86_64-linux = {
110 first = check "worker-first" ./first.sh;
111 second = check "worker-second" ./second.sh;
112 };
113 };
114 }
115 '';
116 flakeLock = pkgs.writeText "flake.lock" ''{"nodes":{"root":{}},"root":"root","version":7}'';
117 spin = pkgs.writeText "spin.sh" ''
118 i=0
119 while [ $i -lt 250000 ]; do i=$((i+1)); done
120 echo $NIX_BUILD_CORES > $out
121 '';
122 # A build long enough to be killed in: about twenty seconds of spinning.
123 slow = pkgs.writeText "slow.sh" ''
124 i=0
125 while [ $i -lt 10000000 ]; do i=$((i+1)); done
126 echo $NIX_BUILD_CORES > $out
127 '';
128 broken = pkgs.writeText "broken.sh" "exit 1";
129 runaway = pkgs.writeText "runaway.sh" ''
130 x=a
131 while :; do x=$x$x; done
132 '';
133
134 # Builds that are not the worker's, through the same daemon. small and
135 # big each hold a string of 1 MiB or 128 MiB. Then each waits without
136 # using a CPU, so it takes none from the worker's pass: it reads its own
137 # standard output, where no input ever arrives. big waits until it is
138 # stopped. small waits until it is sent SIGUSR1, and then finishes, so
139 # the test decides when it ends. cpu spins on six CPUs until it is
140 # stopped.
141 unrelated = pkgs.writeText "unrelated.nix" ''
142 { kind }:
143 let
144 hold = n: "x=a; n=0; while [ $n -lt ''${n} ]; do x=$x$x; n=$((n+1)); done";
145 idle = "read y < /proc/self/fd/1";
146 scripts = {
147 small = hold "20" + "; trap 'echo ok > $out; exit 0' USR1; ''${idle}";
148 big = hold "27" + "; ''${idle}";
149 cpu = "for i in 1 2 3 4 5 6; do (while :; do :; done) & done; wait";
150 };
151 in
152 derivation {
153 name = "unrelated-''${kind}";
154 system = "x86_64-linux";
155 builder = "/bin/sh";
156 args = [ "-c" scripts.''${kind} ];
157 }
158 '';
159
160 # What the daemon's builds look like while the worker runs: the number
161 # of build users with a process, and the cgroup of each such process,
162 # sampled ten times a second.
163 sampler = pkgs.writeShellScript "valley-worker-e2e-sampler" ''
164 PATH=${
165 lib.makeBinPath [
166 pkgs.coreutils
167 pkgs.gawk
168 pkgs.procps
169 ]
170 }
171 while :; do
172 ps -eo user:32=,cgroup:512= | awk '$1 ~ /^nixbld/' > /tmp/sample
173 awk '{print $1}' /tmp/sample | sort -u | wc -l >> /tmp/builders
174 awk '{print $2}' /tmp/sample >> /tmp/build-cgroups
175 sleep 0.1
176 done
177 '';
178in
179{
180 worker-e2e = pkgs.testers.runNixOSTest {
181 name = "valley-worker-e2e";
182 nodes.host = {
183 imports = [ self.nixosModules.default ];
184 # Six CPUs: more than the worker's slots, so the slots and not the
185 # CPU count decide how many checks build at once, and a build can
186 # want more CPUs than the slice's quota of four.
187 virtualisation.cores = 6;
188 virtualisation.memorySize = 2048;
189 environment.systemPackages = [
190 pkgs.git
191 machineValley
192 ];
193 services.valley = {
194 enable = true;
195 config = declaration;
196 buildSlice.enable = true;
197 authorizedKeys = [
198 {
199 principal = "contributor";
200 key = pub "contributor";
201 }
202 ];
203 identity.enable = true;
204 bus.enable = true;
205 integrator = {
206 enable = true;
207 signingKeyFile = "${keys}/integrator";
208 instanceProject = "instance";
209 signerProjects."worker/attestations" = [ "project" ];
210 };
211 # Two checks at once, each told it may use two cores, rather
212 # than the defaults of one check at a time on four.
213 worker = {
214 enable = true;
215 projects = [ "project" ];
216 signerName = "worker/attestations";
217 buildSlots = 2;
218 maxJobs = 2;
219 cores = 2;
220 };
221 };
222 # NixOS test machines panic on any OOM, a cgroup's included
223 # (test-instrumentation.nix). A host does not, and the runaway build
224 # below is stopped by the slice's OOM, so a host's default is restored.
225 boot.kernel.sysctl."vm.panic_on_oom" = 0;
226 # The test starts each pass itself until it checks the timer, so no
227 # pass runs before the test is ready for it. The interval stays the
228 # module's minute: the recovery scenarios wait for it. A timer pass
229 # starts within a second of it, rather than up to a minute of
230 # systemd's accuracy later.
231 systemd.timers.valley-worker.timerConfig.OnActiveSec = lib.mkForce "1h";
232 systemd.timers.valley-worker.timerConfig.AccuracySec = "1s";
233 # The machine has no network. Without these, every new build waits
234 # for the daemon's lookups in cache.nixos.org to fail, and every boot
235 # waits for a DHCP lease on an interface nothing here uses.
236 nix.settings.substituters = lib.mkForce [ ];
237 networking.useDHCP = false;
238 };
239
240 testScript = ''
241 import shlex
242
243 host.wait_for_unit("multi-user.target")
244 host.succeed("systemctl is-active valley-worker.timer valley-worker.path")
245 host.succeed("systemctl stop valley-worker.timer valley-worker.path")
246
247 git = "sudo -u git git"
248 wake = "/var/lib/valley-worker-wake"
249 state = "/var/lib/valley-worker"
250 ssh = shlex.quote(
251 "ssh -i /root/keys/contributor -o IdentitiesOnly=yes -o BatchMode=yes"
252 " -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null"
253 )
254 contributor = f"cd /root/project && GIT_SSH_COMMAND={ssh}"
255 commit = "git -c user.name=contributor -c user.email=contributor@localhost commit --quiet"
256
257 def journal():
258 return host.succeed("journalctl -u valley-worker -o cat")
259
260 def unrelated(kind):
261 host.succeed(
262 f"systemd-run --unit=unrelated-{kind} --remain-after-exit --setenv=NIX_REMOTE=daemon"
263 f" nix-build ${unrelated} --argstr kind {kind} --no-out-link"
264 )
265
266 def unit_property(name, prop):
267 return host.succeed(f"systemctl show -p {prop} --value {name}").strip()
268
269 def attestations():
270 return host.succeed(
271 f"{git} -C /srv/git/project.git for-each-ref --format='%(refname)' refs/the-valley/attestations/"
272 ).split()
273
274 def registry(worker):
275 principals = [
276 '"contributor": {',
277 ' kind: "human"',
278 ' keys: [{class: "ssh-ed25519", bound: "host", public: "${
279 lib.concatStringsSep " " (lib.take 2 (lib.splitString " " (pub "contributor")))
280 }"}]',
281 ' grants: {push: boundary: "push", govern: boundary: "registry"}',
282 "}",
283 ]
284 if worker:
285 principals += [
286 '"worker": {',
287 ' kind: "machine"',
288 f' keys: [{{class: "ssh-ed25519", bound: "host", public: "{worker}", signs: "worker/attestations"}}]',
289 ' grants: push: boundary: "push"',
290 ' expires: "2099-01-01"',
291 "}",
292 ]
293 return "\n".join(
294 [
295 "package identity",
296 'boundaries: {"push": kind: "git-push", "registry": kind: "registry"}',
297 'genesis: "contributor"',
298 "principals: {",
299 ]
300 + principals
301 + ["}"]
302 )
303
304 # The instance's main carries the floor and the registry. It is
305 # landed by a local write, which runs no hook, as an operator seeds
306 # a protected repository.
307 def land_instance(worker):
308 host.succeed(
309 "rm -rf /tmp/instance && mkdir -p /tmp/instance/policy/instance /tmp/instance/identity",
310 "cp ${floor} /tmp/instance/policy/instance/floor.cue",
311 f"cat > /tmp/instance/identity/registry.cue <<'EOF'\n{registry(worker)}\nEOF",
312 f"cd /tmp/instance && git init --quiet --initial-branch=main && git add -A && {commit} -m instance",
313 "chown -R git:git /tmp/instance",
314 f"{git} -C /srv/git/instance.git fetch --quiet --force /tmp/instance main:refs/heads/main",
315 "systemctl start valley-identity.service",
316 )
317
318 # A branch of the project with the first check's script given,
319 # pushed by the contributor and readied.
320 def ready(branch, first):
321 host.succeed(
322 f"cd /root/project && git checkout --quiet -b {branch} origin/main",
323 f"cp {first} /root/project/first.sh && echo {branch} >> /root/project/README.md",
324 f"cd /root/project && git add -A && {commit} -m {branch}",
325 f"{contributor} git push --quiet origin {branch}",
326 f"{contributor} valley ready {branch}",
327 )
328
329 with subtest("the instance and the project are seeded, and a change is ready"):
330 host.succeed("mkdir /srv/hung.git && chown git:git /srv/hung.git", f"{git} init --quiet --bare /srv/hung.git")
331 land_instance(None)
332 host.succeed(
333 "mkdir -p /tmp/project/policy",
334 "cp ${flake} /tmp/project/flake.nix",
335 "cp ${flakeLock} /tmp/project/flake.lock",
336 "cp ${spin} /tmp/project/first.sh",
337 "cp ${spin} /tmp/project/second.sh",
338 "echo 'git@host:instance.git' > /tmp/project/policy/valley",
339 "echo project > /tmp/project/README.md",
340 f"cd /tmp/project && git init --quiet --initial-branch=main && git add -A && {commit} -m project",
341 "chown -R git:git /tmp/project",
342 f"{git} -C /srv/git/project.git fetch --quiet /tmp/project main:refs/heads/main",
343 "mkdir -p /root/keys && install -m 600 ${keys}/contributor /root/keys/contributor",
344 f"GIT_SSH_COMMAND={ssh} git clone --quiet git@localhost:project.git /root/project",
345 "git -C /root/project config valley.principal contributor",
346 "git -C /root/project config user.name contributor",
347 "git -C /root/project config user.email contributor@localhost",
348 )
349 ready("good", "${spin}")
350
351 with subtest("the first start makes the key, readable by the worker alone, and says its public halves"):
352 host.fail(f"test -e {state}/key")
353 # What an earlier start killed half way leaves: a partial key and
354 # public half under the temporary names, and a public half with
355 # no key.
356 host.succeed(
357 f"sudo -u valley-worker sh -c 'echo partial > {state}/key.new;"
358 f" echo partial > {state}/key.new.pub; echo stale > {state}/key.pub'"
359 )
360 # Not enrolled yet, so the host's sshd turns the worker away and
361 # the pass stops before it builds anything.
362 host.fail("systemctl start valley-worker.service")
363 assert host.succeed(f"stat -c '%a %U %G' {state}").strip() == "700 valley-worker valley-worker"
364 assert host.succeed(f"stat -c '%a %U %G' {state}/key").strip() == "400 valley-worker valley-worker"
365 host.succeed(f"test -f {state}/key && test ! -L {state}/key")
366 for other in ["git", "valley-integrator", "nobody"]:
367 host.fail(f"sudo -u {other} cat {state}/key")
368 public = host.succeed(f"cat {state}/key.pub").strip()
369 verifier = host.succeed(f"cat {state}/verifier").strip()
370 assert verifier.startswith("worker/attestations+"), verifier
371 keyhash = verifier.split("+")[1]
372 said = journal()
373 assert f"the worker's ssh public key is {public}" in said, said
374 assert f"the worker's verifier line is {verifier}" in said, said
375 assert "PRIVATE KEY" not in said, said
376 assert host.succeed(f"ssh-keygen -y -f {state}/key").split()[1] == public.split()[1]
377 host.fail(f"ls {state} | grep -q '^key.new'")
378 fingerprint = host.succeed(f"ssh-keygen -lf {state}/key").strip()
379 assert attestations() == []
380
381 with subtest("enrolled in the registry, the worker builds the ready change's checks side by side and publishes them"):
382 land_instance(" ".join(public.split()[:2]))
383 host.succeed(f"grep -q '^worker/attestations+{keyhash}+' /var/lib/valley-identity/known-signers")
384 host.wait_until_succeeds(
385 f"{git} -C /srv/git/instance.git cat-file blob refs/the-valley/signers:known-signers"
386 f" | grep -q '^worker/attestations+{keyhash}+'",
387 timeout=60,
388 )
389 host.succeed("systemd-run --unit=valley-worker-e2e-sampler ${sampler}")
390 host.succeed("systemctl start valley-worker.service")
391 host.succeed("systemctl stop valley-worker-e2e-sampler")
392 said = journal()
393 assert "building first, second" in said, said
394 refs = attestations()
395 assert len(refs) == 1 and refs[0].endswith(f"/{keyhash}"), refs
396 assert f"published {refs[0]}" in said, said
397 for check in ["first", "second"]:
398 host.succeed(f"{git} -C /srv/git/project.git cat-file -e {refs[0]}:{check}/statement.note")
399 # Both checks at once, each in the daemon's cgroup, inside the
400 # slice, each told it may use the 2 cores the host configures.
401 builders = [int(n) for n in host.succeed("cat /tmp/builders").split()]
402 assert max(builders) >= 2, builders
403 cgroups = set(host.succeed("cat /tmp/build-cgroups").split())
404 assert cgroups and all(c.startswith("0::/valley.slice/valley-builds.slice/nix-daemon.service") for c in cgroups), cgroups
405 for check in ["first", "second"]:
406 assert host.succeed(f"cat /nix/store/*-worker-{check}").strip() == "2", check
407 for unit in ["valley-worker.service", "nix-daemon.service"]:
408 assert host.succeed(f"systemctl show -p Slice --value {unit}").strip() == "valley-builds.slice", unit
409
410 with subtest("the timer runs the next pass, which finds the evidence on origin and builds nothing"):
411 host.succeed("systemctl start valley-worker.timer")
412 host.wait_until_succeeds(
413 "journalctl -u valley-worker -o cat | grep -q 'origin holds evidence for every nix check it requires'",
414 timeout=150,
415 )
416 host.succeed("systemctl stop valley-worker.timer")
417 host.wait_until_succeeds("test \"$(systemctl show -p ActiveState --value valley-worker)\" != activating")
418 assert len(attestations()) == 1
419
420 def idle():
421 host.wait_until_succeeds(
422 "test \"$(systemctl show -p ActiveState --value valley-worker)\" != activating"
423 f" && test ! -e {wake}/due",
424 timeout=300,
425 )
426
427 def started():
428 return unit_property("valley-worker.service", "ExecMainStartTimestampMonotonic")
429
430 with subtest("the wake directory is the worker's and its writers', and the worker's access is unchanged"):
431 assert host.succeed(f"stat -c '%U %G %a' {wake}").strip() == "valley-worker valley-worker-wake 770"
432 assert "valley-worker-wake" in host.succeed("id -nG git").split()
433 assert "valley-worker-wake" in host.succeed(f"id -nG {unit_property('valley-integrator@project.service', 'User')}").split()
434 assert host.succeed("id -nG valley-worker").split() == ["valley-worker"]
435 host.fail("sudo -u valley-worker ls /srv/git/project.git/refs")
436 host.succeed("systemctl cat valley-worker.path | grep -qx 'PathExists=/var/lib/valley-worker-wake/due'")
437 assert unit_property("valley-worker.service", "StartLimitIntervalUSec") == "0"
438 assert unit_property("valley-worker.service", "RestartForceExitStatus") == "75"
439 host.fail("systemctl show -p WantedBy --value valley-worker.service | grep -q multi-user")
440 # The marks the seeding pushes and the signer publication left
441 # are read by one pass, which builds nothing.
442 host.succeed("systemctl start valley-worker.path")
443 idle()
444 host.succeed(f"test ! -e {wake}/claimed")
445 assert len(attestations()) == 1
446
447 with subtest("a ready push starts a pass at once with no timer, and a change readied during it gets the next pass"):
448 import time
449 host.fail("systemctl is-active valley-worker.timer")
450 building = journal().count("building first, second")
451 evidence = len(attestations())
452 ready("wake-first", "${spin}")
453 readied = time.monotonic()
454 host.wait_until_succeeds(
455 f"test $(journalctl -u valley-worker -o cat | grep -c 'building first, second') -gt {building}",
456 timeout=120,
457 )
458 print(f"ready to building: {time.monotonic() - readied:.1f}s")
459 assert unit_property("valley-worker.service", "ActiveState") == "activating"
460 ready("wake-second", "${spin}")
461 host.wait_until_succeeds(f"test -e {wake}/due -a -e {wake}/claimed")
462 host.wait_until_succeeds(
463 f"test $({git} -C /srv/git/project.git for-each-ref refs/the-valley/attestations/ | wc -l) -eq {evidence + 2}",
464 timeout=600,
465 )
466 idle()
467 host.fail("systemctl is-active valley-worker.timer")
468 assert journal().count("building first, second") == building + 2
469
470 with subtest("marks from the git user and the integrator's user are one file, and a stale mark builds nothing"):
471 host.succeed("systemctl stop valley-worker.path")
472 integrator = unit_property("valley-integrator@project.service", "User")
473 for who in ["git", integrator, "git", integrator]:
474 host.succeed(f"sudo -u {who} bash -c 'set -C; : > {wake}/due' 2>/dev/null || test -e {wake}/due")
475 assert host.succeed(f"ls -A {wake}").split() == ["due", "lock"]
476 host.succeed(f"rm {wake}/due && sudo -u {integrator} bash -c 'set -C; : > {wake}/due'")
477 building = journal().count("building first, second")
478 pushes = journal().count("published ")
479 host.succeed("systemctl start valley-worker.path")
480 idle()
481 assert host.succeed(f"ls -A {wake}").split() == ["lock"]
482 assert journal().count("building first, second") == building
483 assert journal().count("published ") == pushes
484
485 with subtest("a claim a killed pass left starts nothing, and the next pass acknowledges it"):
486 host.succeed(f"sudo -u valley-worker touch {wake}/claimed")
487 mark = started()
488 host.succeed("sleep 5")
489 assert started() == mark
490 host.succeed("systemctl start valley-worker.service")
491 host.succeed(f"test ! -e {wake}/claimed")
492
493 with subtest("a pass that cannot claim due reads all the same and is started again only after its hold-off"):
494 restarts = int(unit_property("valley-worker.service", "NRestarts"))
495 host.succeed(f"chmod 0550 {wake} && touch {wake}/due")
496 host.wait_until_succeeds("journalctl -u valley-worker -o cat | grep -q 'could not claim'", timeout=60)
497 host.wait_until_succeeds("test \"$(systemctl show -p SubState --value valley-worker)\" = auto-restart")
498 # due is still there, and nothing starts a pass for a minute.
499 mark = started()
500 host.sleep(20)
501 assert started() == mark
502 assert int(unit_property("valley-worker.service", "NRestarts")) == restarts
503 host.fail("systemctl is-failed valley-worker.path")
504 assert "origin holds evidence for every nix check it requires" in journal()
505 host.succeed(f"chmod 0770 {wake}")
506 idle()
507 host.succeed("systemctl is-active valley-worker.path")
508
509 with subtest("a push to the instance, which the worker does not build, marks it due, and knots and bookkeeping do not"):
510 host.succeed("systemctl stop valley-worker.path")
511 host.succeed(
512 f"cd /root && rm -rf instance && GIT_SSH_COMMAND={ssh} git clone --quiet git@localhost:instance.git instance",
513 f"cd /root/instance && git checkout --quiet -b floor-probe && echo probe > probe && git add probe && {commit} -m probe",
514 )
515 hook = "/srv/git/instance.git/hooks/post-receive.d/valley-wake"
516 zero = "0" * 40
517 host.succeed(f"echo '{zero} {zero} refs/the-valley/knots' | sudo -u git {hook}")
518 host.succeed(f"echo '{zero} {zero} refs/the-valley/integration-outcomes/main/x' | sudo -u git {hook}")
519 host.succeed(f"test ! -e {wake}/due")
520 host.succeed(f"cd /root/instance && GIT_SSH_COMMAND={ssh} git push --quiet origin floor-probe")
521 host.succeed(f"test -e {wake}/due")
522
523 with subtest("a signer publication marks the worker due only when it moves the ref"):
524 host.succeed(f"rm -f {wake}/due")
525 host.succeed("systemctl start valley-signers.service")
526 host.succeed(f"test ! -e {wake}/due")
527 host.succeed(f"{git} -C /srv/git/instance.git update-ref -d refs/the-valley/signers")
528 host.succeed("systemctl start valley-signers.service")
529 host.succeed(f"test -e {wake}/due")
530 host.succeed("systemctl start valley-worker.path")
531 idle()
532
533 def head(branch):
534 return host.succeed(f"git -C /root/project rev-parse --short=7 {branch}").strip()
535
536 def told(commit, what):
537 return journal().count(f" at {commit}: {what}")
538
539 def wait_said(commit, what, timeout):
540 host.wait_until_succeeds(f"journalctl -u valley-worker -o cat | grep -qF ' at {commit}: {what}'", timeout=timeout)
541
542 with subtest("with the mirror and the bus hung, a landing by the integrator's service and a ready push mark the worker at once"):
543 # The mirror takes the drain's push of main and never answers it,
544 # and what listens at the bus's address takes a connection and
545 # never answers it.
546 host.succeed(
547 "printf '#!/bin/sh\\nexec /run/current-system/sw/bin/sleep 100001\\n' > /srv/hung.git/hooks/pre-receive",
548 "chmod 755 /srv/hung.git/hooks/pre-receive",
549 "systemctl stop valley-bus.service",
550 "systemd-run --unit=hung-bus ${pkgs.socat}/bin/socat TCP-LISTEN:4222,bind=127.0.0.1,fork,reuseaddr"
551 " SYSTEM:'exec ${pkgs.coreutils}/bin/sleep 100000'",
552 )
553 host.wait_for_open_port(4222)
554 # The good change lands by the integrator's own service, which
555 # marks due from inside its sandbox. The request ref is written
556 # locally, which runs no hook, so the landing's mark is the only one.
557 host.succeed("systemctl stop valley-worker.path")
558 base = host.succeed(f"{git} -C /srv/git/project.git rev-parse refs/heads/main").strip()
559 good = host.succeed("git -C /root/project rev-parse good").strip()
560 host.succeed(f"{git} -C /srv/git/project.git update-ref refs/the-valley/integration-requests/main/good {good}")
561 host.wait_until_succeeds(
562 f"test \"$({git} -C /srv/git/project.git rev-parse refs/heads/main^)\" = {base}", timeout=120
563 )
564 landed = time.monotonic()
565 host.wait_until_succeeds(f"test -e {wake}/due", timeout=10)
566 print(f"landing to mark, mirror and bus hung: {time.monotonic() - landed:.1f}s")
567 host.wait_until_succeeds(
568 "journalctl -u valley-integrator@project -o cat | grep -q 'bus publish of .* FAILED'", timeout=120
569 )
570 said_by = host.succeed("journalctl -u valley-integrator@project -o cat")
571 assert said_by.index("wake the check worker is due") < said_by.index("bus publish of"), said_by
572 host.wait_until_succeeds("pgrep -f 'sleep 10000[1]'", timeout=60)
573 host.succeed("systemctl start valley-worker.path")
574 idle()
575 # With the mirror's push still hung, a ready push starts a pass.
576 ready("hung", "${spin}")
577 readied = time.monotonic()
578 wait_said(head("hung"), "building", 120)
579 print(f"ready to building, mirror and bus hung: {time.monotonic() - readied:.1f}s")
580 wait_said(head("hung"), "published", 120)
581 idle()
582 host.succeed("pgrep -f 'sleep 10000[1]'")
583 host.succeed(
584 "rm /srv/hung.git/hooks/pre-receive && pkill -f 'sleep 10000[1]'",
585 "systemctl stop hung-bus && systemctl start valley-bus.service",
586 )
587
588 with subtest("a floor landed in the instance, which the worker does not build, marks it, and the next pass reads the floor it landed"):
589 host.succeed("systemctl stop valley-worker.path")
590 floor_base = host.succeed(f"{git} -C /srv/git/instance.git rev-parse refs/heads/main").strip()
591 host.succeed(
592 "cp ${floorThird} /tmp/instance/policy/instance/floor.cue",
593 f"cd /tmp/instance && sudo -u git {commit} -am third",
594 f"{git} -C /srv/git/instance.git fetch --quiet /tmp/instance main:refs/the-valley/integration-requests/main/third",
595 )
596 host.wait_until_succeeds(
597 f"test \"$({git} -C /srv/git/instance.git rev-parse refs/heads/main^)\" = {floor_base}", timeout=120
598 )
599 host.wait_until_succeeds(f"test -e {wake}/due", timeout=10)
600 host.succeed("journalctl -u valley-integrator@instance -o cat | grep -q 'wake the check worker is due'")
601 # The pass reads the new floor. A change built before it holds this
602 # worker's evidence for its tree, which admits no addition, so the
603 # pass says the third check is not covered.
604 host.succeed("systemctl start valley-worker.path")
605 host.wait_until_succeeds(
606 "journalctl -u valley-worker -o cat | grep -q 'and it does not cover third'", timeout=120
607 )
608 idle()
609 assert "instance:" not in journal()
610
611 with subtest("a pass killed during a build leaves its claim, and the timer's next pass builds the change"):
612 # The push and the ready mark are made before the pass starts,
613 # so they are one due, which the pass claims.
614 host.succeed("systemctl stop valley-worker.path")
615 ready("killed", "${slow}")
616 killed = head("killed")
617 host.succeed("systemctl start valley-worker.path")
618 wait_said(killed, "building", 120)
619 host.wait_until_succeeds("ps -eo user= | grep -q '^nixbld'", timeout=60)
620 host.succeed("systemctl kill --signal=KILL valley-worker.service")
621 host.wait_until_succeeds("test \"$(systemctl show -p ActiveState --value valley-worker)\" = failed", timeout=60)
622 assert host.succeed(f"ls -A {wake}").split() == ["claimed", "lock"]
623 host.wait_until_succeeds("! ps -eo user= | grep -q '^nixbld'", timeout=60)
624 # Nothing watches claimed, so nothing starts a pass, until the
625 # timer runs the recovery scan a minute after the kill.
626 mark = started()
627 host.sleep(5)
628 assert started() == mark
629 assert told(killed, "published") == 0
630 host.succeed("systemctl start valley-worker.timer")
631 wait_said(killed, "published", 300)
632 idle()
633 host.succeed(f"test ! -e {wake}/claimed")
634 assert told(killed, "building") == 2
635
636 with subtest("a pass that cannot reach the repositories leaves its claim, and the timer's next pass builds the change with no new mark"):
637 host.succeed("systemctl stop valley-worker.path")
638 ready("outage", "${spin}")
639 outage = head("outage")
640 host.succeed("systemctl stop sshd.service")
641 host.succeed("systemctl start valley-worker.path")
642 host.wait_until_succeeds("test \"$(systemctl show -p ActiveState --value valley-worker)\" = failed", timeout=120)
643 assert host.succeed(f"ls -A {wake}").split() == ["claimed", "lock"]
644 assert told(outage, "building") == 0
645 triggered = unit_property("valley-worker.timer", "LastTriggerUSecMonotonic")
646 host.succeed("systemctl start sshd.service")
647 wait_said(outage, "published", 300)
648 assert unit_property("valley-worker.timer", "LastTriggerUSecMonotonic") != triggered
649 idle()
650 host.succeed(f"test ! -e {wake}/claimed")
651
652 with subtest("a failed batch is not built again before its wait, however many marks and timer passes come"):
653 ready("broken", "${broken}")
654 broken = head("broken")
655 wait_said(broken, "the batch did not pass", 120)
656 idle()
657 ready("unrelated", "${spin}")
658 wait_said(head("unrelated"), "published", 120)
659 idle()
660 host.succeed(
661 f"{git} -C /srv/git/instance.git update-ref -d refs/the-valley/signers",
662 "systemctl start valley-signers.service",
663 )
664 idle()
665 host.succeed(f"cd /root/instance && echo again >> probe && {commit} -am again && GIT_SSH_COMMAND={ssh} git push --quiet origin floor-probe")
666 idle()
667 triggered = unit_property("valley-worker.timer", "LastTriggerUSecMonotonic")
668 host.wait_until_succeeds(
669 f"test \"$(systemctl show -p LastTriggerUSecMonotonic --value valley-worker.timer)\" != '{triggered}'", timeout=150
670 )
671 idle()
672 assert told(broken, "building") == 1
673 assert told(broken, "the batch did not pass") == 1
674 assert told(broken, "its batch") >= 4, journal()
675 # The scenarios below start each pass themselves.
676 host.succeed("systemctl stop valley-worker.timer valley-worker.path")
677 host.wait_until_succeeds("test \"$(systemctl show -p ActiveState --value valley-worker)\" != activating")
678
679 with subtest("the slice holds its default caps"):
680 cgroup = "/sys/fs/cgroup/valley.slice/valley-builds.slice"
681 assert host.succeed(f"cat {cgroup}/cpu.max").strip() == "400000 100000"
682 assert host.succeed(f"cat {cgroup}/memory.max").strip() == str(8 * 1024**3)
683 assert host.succeed(f"cat {cgroup}/memory.swap.max").strip() == "0"
684
685 with subtest("a build that wants six CPUs is held to the slice's quota"):
686 # The machine running this test may cap the VM's own CPU, and no
687 # quota above that can throttle. One CPU is always below it.
688 host.succeed("systemctl set-property --runtime valley-builds.slice CPUQuota=100%")
689 unrelated("cpu")
690 host.wait_until_succeeds("test \"$(ps -eo user= | grep -c '^nixbld')\" -ge 7", timeout=60)
691 # The quota is enforced every 100 ms, so five seconds holds fifty
692 # of its periods.
693 host.sleep(1)
694 stat = lambda: dict(line.split() for line in host.succeed(f"cat {cgroup}/cpu.stat").splitlines())
695 before = stat()
696 host.sleep(5)
697 after = stat()
698 cpus = (int(after["usage_usec"]) - int(before["usage_usec"])) / 5e6
699 assert 0.8 < cpus < 1.5, cpus
700 assert int(after["nr_throttled"]) > int(before["nr_throttled"]), (before, after)
701 host.succeed("systemctl stop unrelated-cpu")
702 host.succeed("systemctl set-property --runtime valley-builds.slice CPUQuota=400%")
703 assert host.succeed(f"cat {cgroup}/cpu.max").strip() == "400000 100000"
704 host.wait_until_succeeds("! ps -eo user= | grep -q '^nixbld'", timeout=60)
705
706 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"):
707 evidence = len(attestations())
708 ready("runaway", "${runaway}")
709 failed_before = set(host.succeed("systemctl list-units --state=failed --no-legend --plain | cut -d' ' -f1").split())
710 # Two builds that are not the worker's, with room to make their
711 # strings. The shell takes about twice a string's size while it
712 # makes it, so what big holds is read once it stops growing.
713 host.succeed("systemctl set-property --runtime valley-builds.slice MemoryMax=1536M")
714 unrelated("small")
715 unrelated("big")
716 host.wait_until_succeeds("ps -eo user=,rss= | awk '$1 ~ /^nixbld/ && $2 > 100000' | grep -q .", timeout=60)
717 biggest = lambda: int(host.succeed("ps -eo user=,rss= | awk '$1 ~ /^nixbld/ {print $2}' | sort -n | tail -1").strip())
718 held = 0
719 for _ in range(30):
720 host.sleep(1)
721 now = biggest()
722 if now == held:
723 break
724 held = now
725 assert held > 100000, held
726 # The cap is what the slice cannot give back, and half of what big
727 # holds. The runaway reaches the cap while it is still smaller than
728 # big.
729 memory = dict(line.split() for line in host.succeed(f"cat {cgroup}/memory.stat").splitlines())
730 cap = int(memory["anon"]) + int(memory["shmem"]) + held * 1024 // 2
731 host.succeed(f"systemctl set-property --runtime valley-builds.slice MemoryMax={cap}")
732 host.fail("systemctl start valley-worker.service")
733 said = journal()
734 assert "the batch did not pass" in said, said
735 kills = host.succeed(f"sed -n 's/^oom_kill //p' {cgroup}/memory.events").strip()
736 assert int(kills) >= 2, kills
737 # Nothing for the runaway.
738 assert len(attestations()) == evidence
739 # The kernel killed the biggest process in the slice: the unrelated
740 # big build, before the runaway grew past it, and then the runaway.
741 # The small build was never the biggest. It is still running, and
742 # once it is told to finish, it does.
743 small = host.succeed("ps -eo pid=,user=,args= | awk '$2 ~ /^nixbld/ && /USR1/ {print $1}'").split()
744 assert len(small) == 1, small
745 host.succeed(f"kill -USR1 {small[0]}")
746 host.wait_until_succeeds("test \"$(systemctl show -p SubState --value unrelated-small)\" = exited", timeout=60)
747 assert unit_property("unrelated-small", "Result") == "success"
748 host.wait_until_succeeds("test \"$(systemctl show -p ActiveState --value unrelated-big)\" = failed", timeout=60)
749 # The units the host runs are as they were, the daemon still
750 # answers, and the git user still serves pushes and fetches.
751 host.succeed(
752 "systemctl is-active sshd.service nix-daemon.service nix-daemon.socket"
753 " valley-integrator@instance.service valley-integrator@project.service"
754 )
755 failed_after = set(host.succeed("systemctl list-units --state=failed --no-legend --plain | cut -d' ' -f1").split())
756 assert failed_after <= failed_before | {"valley-worker.service", "unrelated-big.service"}, failed_after
757 host.succeed("nix-store --store daemon --query --hash /run/current-system")
758 host.succeed(f"{contributor} git ls-remote origin refs/heads/runaway | grep -q runaway")
759 # The failed batch waits before it is built again.
760 host.succeed("systemctl start valley-worker.service")
761 assert "failed 1 time in a row, so it is not built again before" in journal()
762
763 with subtest("the key is the same after many starts and a reboot, and is not said again"):
764 assert host.succeed(f"ssh-keygen -lf {state}/key").strip() == fingerprint
765 host.shutdown()
766 host.start()
767 host.wait_for_unit("multi-user.target")
768 host.succeed("systemctl stop valley-worker.timer valley-worker.path")
769 host.succeed("systemctl start valley-worker.service")
770 assert host.succeed(f"ssh-keygen -lf {state}/key").strip() == fingerprint
771 assert host.succeed(f"cat {state}/verifier").strip() == verifier
772 host.fail("journalctl -b -u valley-worker -o cat | grep -q 'verifier line is'")
773 '';
774 };
775}