gunk-dev/the-valley

worker-e2e.nix

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