gunk-dev/the-valley

worker-e2e.nix

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