gunk-dev/the-valley

worker-e2e.nix

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