gunk-dev/the-valley

check.go

sourced76157dbe10cmain's published tip history
18.0 KiB
1package main
2
3// Running a check, and the digests a run yields.
4//
5// The nix runner claims purity strongly: it builds a flake check
6// derivation, so the check's inputs, the derivation itself and its output
7// are all named, and any verifier holding the same tree can re-derive
8// them. The command runner claims nothing beyond having run — its
9// statement is a notarization naming the environment and the time
10// (archive/design/verification.md).
11
12import (
13 "bytes"
14 "context"
15 "encoding/json"
16 "fmt"
17 "io"
18 "os"
19 "os/exec"
20 "path/filepath"
21 "regexp"
22 "runtime"
23 "strings"
24 "syscall"
25 "time"
26)
27
28type checkSpec struct {
29 name string
30 attribute string // nix runner
31 command string // command runner
32}
33
34func (c checkSpec) runner() string {
35 if c.command != "" {
36 return "command"
37 }
38 return "nix"
39}
40
41// checkOutcome is what running one check produced: whether it passed, the
42// output a reader needs when it did not, how it was satisfied, and the
43// digests of a pure run.
44type checkOutcome struct {
45 spec checkSpec
46 passed bool
47 log string
48 satisfied string
49
50 inputs string
51 derivation string
52 output string
53 observedAt string
54}
55
56// ranCheck is one check as a run ran it: its outcome, or the error that
57// kept it from having one, and when it started and how long it took. eval
58// is how long a pure check took to evaluate, and is zero for a command.
59type ranCheck struct {
60 out checkOutcome
61 err error
62 began time.Time
63 took time.Duration
64 eval time.Duration
65}
66
67// nixSystem is the flake system attribute of the machine running the
68// check. A check is built where the work was written, so this is the
69// runner's own system and never something the caller states about another
70// machine.
71func nixSystem() string {
72 arch := runtime.GOARCH
73 switch arch {
74 case "amd64":
75 arch = "x86_64"
76 case "arm64":
77 arch = "aarch64"
78 case "386":
79 arch = "i686"
80 }
81 return arch + "-" + runtime.GOOS
82}
83
84func nix(dir string, args ...string) (string, string, error) {
85 cmd := exec.Command("nix", args...)
86 cmd.Dir = dir
87 var out, errb bytes.Buffer
88 cmd.Stdout = &out
89 cmd.Stderr = &errb
90 err := cmd.Run()
91 return out.String(), errb.String(), err
92}
93
94// nixStore runs nix-store, and stops it when ctx is done.
95func nixStore(ctx context.Context, args ...string) (string, string, error) {
96 cmd := exec.CommandContext(ctx, "nix-store", args...)
97 cmd.WaitDelay = time.Second
98 var out, errb bytes.Buffer
99 cmd.Stdout = &out
100 cmd.Stderr = &errb
101 err := cmd.Run()
102 return out.String(), errb.String(), err
103}
104
105// flakeChecks lists every check attribute a flake defines for a system —
106// what "the repo's canonical checks" means when the caller names none.
107func flakeChecks(tree, system string) ([]string, error) {
108 out, errb, err := nix(tree, "eval", "--json", "--apply", "builtins.attrNames", tree+"#checks."+system)
109 if err != nil {
110 return nil, fmt.Errorf("listing checks: %w: %s", err, strings.TrimSpace(errb))
111 }
112 var names []string
113 if err := json.Unmarshal([]byte(out), &names); err != nil {
114 return nil, fmt.Errorf("listing checks: %w", err)
115 }
116 return names, nil
117}
118
119// closure is what evaluating a pure check names before anything is built:
120// the derivation, and the digest of its input closure. Both are functions
121// of the tree alone, so an integrator can recompute the closure digest on a
122// rebased tree without running the check — which is the whole of the pure
123// transfer rule (dcr-439b771).
124type closure struct {
125 drv string
126 derivation string
127 inputs string
128}
129
130// evalClosure evaluates one flake check over an exported tree and digests
131// what the evaluation named. Nothing is built.
132func evalClosure(tree, system string, spec checkSpec) (closure, error) {
133 attr := tree + "#checks." + system + "." + spec.attribute
134 drv, errb, err := nix(tree, "eval", "--raw", attr+".drvPath")
135 if err != nil {
136 return closure{}, fmt.Errorf("evaluating %s: %w: %s", attr, err, strings.TrimSpace(errb))
137 }
138 return closureOf(strings.TrimSpace(drv))
139}
140
141// closureOf digests a derivation an evaluation named: the derivation file
142// itself, and the store paths it reads.
143func closureOf(drv string) (closure, error) {
144 drvBytes, err := os.ReadFile(drv)
145 if err != nil {
146 return closure{}, err
147 }
148 inputs, err := drvInputs(drv)
149 if err != nil {
150 return closure{}, err
151 }
152 return closure{
153 drv: drv,
154 derivation: fmt.Sprintf("%x", sha256sum(drvBytes)),
155 inputs: inputsDigest(inputs),
156 }, nil
157}
158
159// evaluation is one pure check's evaluation: the closure it named, or why
160// it named none, and how long it took.
161type evaluation struct {
162 closure
163 err error
164 took time.Duration
165}
166
167// plainAttribute is a check attribute the shared evaluation can name in a
168// nix string as it is: one attribute, with no dot, quote, backslash or
169// dollar sign in it.
170var plainAttribute = regexp.MustCompile(`^[A-Za-z0-9_'+-]+$`)
171
172// evalClosures evaluates every pure check over the exported tree. One nix
173// evaluation names the derivations of all of them together, so nixpkgs and
174// whatever else the checks share are evaluated once and not once per
175// check. A check that evaluation could not name is evaluated alone, as
176// evalClosure does, so an error is reported against the check that has it
177// and stops no other. Each check is timed as the shared evaluation plus
178// whatever was done for it alone.
179func evalClosures(tree, system string, specs []checkSpec) []evaluation {
180 var attrs []string
181 shared := map[string]bool{}
182 for _, spec := range specs {
183 if plainAttribute.MatchString(spec.attribute) && !shared[spec.attribute] {
184 shared[spec.attribute] = true
185 attrs = append(attrs, spec.attribute)
186 }
187 }
188 began := time.Now()
189 drvs := evalDrvPaths(tree, system, attrs)
190 sharedTook := time.Since(began)
191
192 evals := make([]evaluation, len(specs))
193 for i, spec := range specs {
194 began := time.Now()
195 var c closure
196 var err error
197 if drv, ok := drvs[spec.attribute]; ok {
198 c, err = closureOf(drv)
199 } else {
200 c, err = evalClosure(tree, system, spec)
201 }
202 evals[i] = evaluation{closure: c, err: err, took: time.Since(began)}
203 if shared[spec.attribute] {
204 evals[i].took += sharedTook
205 }
206 }
207 return evals
208}
209
210// evalDrvPaths names the derivation of every check attribute given, in one
211// nix evaluation. A check whose evaluation throws, or that is missing or
212// is not a derivation, is left out of the answer. Some evaluation errors
213// cannot be caught inside nix, such as a type error, and they end the
214// whole evaluation; then the answer is empty, and every check is evaluated
215// alone. One attribute has nothing to share, so it is left to be evaluated
216// alone from the start.
217func evalDrvPaths(tree, system string, attrs []string) map[string]string {
218 drvs := map[string]string{}
219 if len(attrs) < 2 {
220 return drvs
221 }
222 quoted := make([]string, len(attrs))
223 for i, a := range attrs {
224 quoted[i] = `"` + a + `"`
225 }
226 apply := `checks: builtins.listToAttrs (map (name: { inherit name; value = ` +
227 `let r = builtins.tryEval (if checks ? ${name} && checks.${name} ? drvPath then checks.${name}.drvPath else null); ` +
228 `in if r.success then r.value else null; }) [ ` + strings.Join(quoted, " ") + ` ])`
229 out, _, err := nix(tree, "eval", "--json", "--apply", apply, tree+"#checks."+system)
230 if err != nil {
231 return drvs
232 }
233 var named map[string]any
234 if json.Unmarshal([]byte(out), &named) != nil {
235 return drvs
236 }
237 for _, a := range attrs {
238 if drv, ok := named[a].(string); ok && drv != "" {
239 drvs[a] = drv
240 }
241 }
242 return drvs
243}
244
245// defaultSlots is how many nix build processes attest run starts at once
246// when --slots does not say: one per CPU attest may run on.
247var defaultSlots = runtime.NumCPU()
248
249// runPure runs every pure check and returns their runs in the order given.
250// It evaluates them all together (evalClosures), then builds each
251// derivation that evaluated in a nix build of its own, slots of them at
252// once, so the nix daemon builds them side by side (buildChecks).
253// Checks that evaluate to the same derivation share its one build. With
254// report, it hands each run to report in the order given, as soon as that
255// check and every one before it have ended.
256//
257// Each check's outcome is its own derivation's build: the exit status and
258// standard error of the nix build that built it, exactly as when checks
259// were built one at a time. With probe, it first asks the nix store
260// whether each output is already there, for the check's timing; without,
261// it asks nothing about outputs.
262//
263// A check is timed from the start of the shared evaluation. Its duration
264// is its evaluation, its probe, and its derivation's build. One that does
265// not evaluate ends at its evaluation error.
266//
267// With an evaluation lock, the evaluation waits for that lock and holds it
268// until the evaluation ends, and the builds run after it is released
269// (takeEvalLock). The wait is not part of any check's time: eval.end
270// records it apart, as eval_wait_ms.
271//
272// With roots, every output path a build prints is rooted under that
273// directory (rootOutputs), whether nix built it or found it valid.
274func runPure(tree, system string, specs []checkSpec, probe bool, slots int, roots string, evalLock *os.File, report func(ranCheck), obs *observer) []ranCheck {
275 waited, release := takeEvalLock(evalLock)
276 began := time.Now()
277 obs.emit("eval.start", "", map[string]any{"checks": specNames(specs)})
278 evals := evalClosures(tree, system, specs)
279 obs.emit("eval.end", "", map[string]any{"eval_ms": time.Since(began).Milliseconds(), "eval_wait_ms": waited.Milliseconds()})
280 release()
281 runs := make([]ranCheck, len(specs))
282 for i, spec := range specs {
283 e := evals[i]
284 runs[i] = ranCheck{out: checkOutcome{spec: spec}, began: began, took: e.took, eval: e.took, err: e.err}
285 if e.err != nil {
286 obs.emit("check.result", spec.name, map[string]any{"result": "error", "error": clipError(e.err.Error()), "eval_ms": e.took.Milliseconds()})
287 continue
288 }
289 runs[i].out.derivation, runs[i].out.inputs = e.derivation, e.inputs
290 if probe {
291 probed := time.Now()
292 runs[i].out.satisfied = outputsCached(e.drv)
293 runs[i].took += time.Since(probed)
294 }
295 obs.name(e.drv, spec.name)
296 obs.emit("check.queued", spec.name, map[string]any{"eval_ms": e.took.Milliseconds(), "probe_ms": (runs[i].took - e.took).Milliseconds()})
297 }
298
299 drvs := make([]string, len(evals))
300 for i, e := range evals {
301 drvs[i] = e.drv
302 }
303 build := func(drv string) (string, string, error) {
304 return nix(tree, "build", "--no-link", "--print-out-paths", drv+"^*")
305 }
306 if obs != nil {
307 build = func(drv string) (string, string, error) { return obs.nixBuild(tree, drv) }
308 }
309 if roots != "" {
310 built := build
311 build = func(drv string) (string, string, error) {
312 out, errText, err := built(drv)
313 rootOutputs(roots, out)
314 return out, errText, err
315 }
316 }
317 buildChecks(runs, drvs, slots, build, report, obs)
318 return runs
319}
320
321// takeEvalLock waits for an exclusive flock on lock and returns how long
322// it waited, and the function that releases it. Runs handed the same lock
323// file evaluate one at a time, so their evaluations never need memory
324// together; their builds still overlap. Without a lock it waits for
325// nothing. The flock belongs to the open file, which attest's children do
326// not inherit, so it is released when attest exits, however it ends: a run
327// killed during its evaluation leaves nothing held. A lock that cannot be
328// taken is warned about, and the evaluation runs without it.
329func takeEvalLock(lock *os.File) (time.Duration, func()) {
330 if lock == nil {
331 return 0, func() {}
332 }
333 began := time.Now()
334 err := syscall.Flock(int(lock.Fd()), syscall.LOCK_EX)
335 for err == syscall.EINTR {
336 err = syscall.Flock(int(lock.Fd()), syscall.LOCK_EX)
337 }
338 waited := time.Since(began)
339 if err != nil {
340 fmt.Fprintf(os.Stderr, "attest: warning: evaluating without the lock %s: %v\n", lock.Name(), err)
341 return waited, func() {}
342 }
343 return waited, func() { syscall.Flock(int(lock.Fd()), syscall.LOCK_UN) }
344}
345
346// rootOutputs registers an indirect garbage-collector root in dir for each
347// store path in built, which is what nix build --print-out-paths printed.
348// A root is a symlink named by its path's basename, so an output is rooted
349// once however many trees use it. nix-store makes the symlink afresh each
350// time, so its modification time is when the output was last used. The
351// daemon records the root, so a user who is not root can add one. A root
352// that cannot be added is warned about and changes no check's outcome.
353func rootOutputs(dir, built string) {
354 for _, path := range strings.Fields(built) {
355 root := filepath.Join(dir, filepath.Base(path))
356 if _, errText, err := nixStore(context.Background(), "--add-root", root, "--realise", path); err != nil {
357 fmt.Fprintf(os.Stderr, "attest: warning: %s is not rooted: %v: %s\n", path, err, strings.TrimSpace(errText))
358 }
359 }
360}
361
362func specNames(specs []checkSpec) []string {
363 names := make([]string, len(specs))
364 for i, s := range specs {
365 names[i] = s.name
366 }
367 return names
368}
369
370// buildChecks builds the derivation of every run that has no error yet
371// and decides each from its derivation's build (pureOutcome). drvs[i] is
372// runs[i]'s derivation, and build builds one derivation, returning what it
373// printed on standard output and standard error and how it ended. Builds
374// start in the order of runs, at most slots of them at once, and runs that
375// share a derivation share its one build. Each run is handed to report in
376// order, as soon as it and every run before it have ended. With obs, each
377// build's start and end and each run's result are recorded as they
378// happen, whatever the order.
379func buildChecks(runs []ranCheck, drvs []string, slots int, build func(drv string) (string, string, error), report func(ranCheck), obs *observer) {
380 builds := map[string]*drvBuild{}
381 users := map[string][]int{} // the runs each derivation decides
382 pending := make([]bool, len(runs))
383 var order []*drvBuild
384 for i := range runs {
385 if runs[i].err != nil {
386 continue
387 }
388 pending[i] = true
389 users[drvs[i]] = append(users[drvs[i]], i)
390 if builds[drvs[i]] != nil {
391 continue
392 }
393 b := &drvBuild{drv: drvs[i], done: make(chan struct{})}
394 builds[drvs[i]] = b
395 order = append(order, b)
396 }
397 free := make(chan struct{}, max(slots, 1))
398 go func() {
399 for _, b := range order {
400 queued := time.Now()
401 free <- struct{}{}
402 wait := time.Since(queued)
403 go func() {
404 defer close(b.done)
405 defer func() { <-free }()
406 for _, i := range users[b.drv] {
407 obs.emit("check.build-start", runs[i].out.spec.name, map[string]any{"slot_wait_ms": wait.Milliseconds()})
408 }
409 began := time.Now()
410 b.paths, b.log, b.err = build(b.drv)
411 b.took = time.Since(began)
412 ended := time.Now()
413 // Each run the build decides is decided as soon as it
414 // ends, and its result recorded then; it is reported in
415 // order below.
416 for _, i := range users[b.drv] {
417 runs[i].took += b.took
418 runs[i].err = pureOutcome(b, &runs[i].out)
419 if obs != nil {
420 d := buildData(b, wait, began, ended, obs.logOf(b.drv))
421 if obs.capacity != "" {
422 d["capacity"] = obs.capacity
423 }
424 obs.emit("check.build-end", runs[i].out.spec.name, d)
425 d["result"] = resultOf(runs[i])
426 d["eval_ms"] = runs[i].eval.Milliseconds()
427 d["check_ms"] = runs[i].took.Milliseconds()
428 obs.emit("check.result", runs[i].out.spec.name, d)
429 }
430 }
431 }()
432 }
433 }()
434 for i := range runs {
435 if pending[i] {
436 <-builds[drvs[i]].done
437 }
438 if report != nil {
439 report(runs[i])
440 }
441 }
442}
443
444// resultOf is a run's result as a timing and a record name it.
445func resultOf(r ranCheck) string {
446 switch {
447 case r.err != nil:
448 return "error"
449 case !r.out.passed:
450 return "failed"
451 }
452 return "passed"
453}
454
455// drvBuild is the nix build of one derivation: what it printed on standard
456// output and on standard error, how it ended, and how long it took. done
457// is closed once it has ended.
458type drvBuild struct {
459 drv string
460 done chan struct{}
461 paths string
462 log string
463 err error
464 took time.Duration
465}
466
467// pureOutcome decides one pure check from its derivation's build, and
468// digests the output when the build succeeded. Building from the
469// derivation path rather than the attribute a second time guarantees the
470// thing built is the thing recorded. The build's standard error is the
471// check's log. A build that failed with nothing on standard error, as when
472// nix could not be started or was killed by a signal, gets the error that
473// ended it as its log instead.
474func pureOutcome(b *drvBuild, out *checkOutcome) error {
475 out.log = strings.TrimSpace(b.log)
476 if b.err != nil {
477 if out.log == "" {
478 out.log = b.err.Error()
479 }
480 return nil // a failed check is an outcome, not an error
481 }
482 paths := strings.Fields(b.paths)
483 if len(paths) != 1 {
484 return fmt.Errorf("%s produced %d outputs; a check attribute must produce exactly one", out.spec.name, len(paths))
485 }
486 entries, err := fsEntries(paths[0])
487 if err != nil {
488 return err
489 }
490 out.output = treeDigest(entries)
491 out.passed = true
492 return nil
493}
494
495// drvInputs collects the store paths a derivation reads: the derivations
496// it depends on and the sources it takes directly. A .drv's references are
497// exactly that set, and `nix-store --query --references` prints them as
498// lines — a shape that has not changed in the lifetime of nix, unlike the
499// versioned JSON of `nix derivation show`.
500func drvInputs(drv string) ([]string, error) {
501 out, errb, err := nixStore(context.Background(), "--query", "--references", drv)
502 if err != nil {
503 return nil, fmt.Errorf("querying the inputs of %s: %w: %s", drv, err, strings.TrimSpace(errb))
504 }
505 inputs := strings.Fields(out)
506 if len(inputs) == 0 {
507 return nil, fmt.Errorf("%s has no inputs at all", drv)
508 }
509 return inputs, nil
510}
511
512// runEffectful runs a command over the exported tree and notarizes what it
513// observed. No digests: there is nothing to re-derive, which is exactly
514// what the effectful predicate type says.
515func runEffectful(tree string, spec checkSpec, logTo io.Writer) checkOutcome {
516 out := checkOutcome{spec: spec, satisfied: satisfiedRan}
517 cmd := exec.Command("sh", "-c", spec.command)
518 cmd.Dir = tree
519 var log bytes.Buffer
520 if logTo == nil {
521 logTo = io.Discard
522 }
523 cmd.Stdout = io.MultiWriter(&log, logTo)
524 cmd.Stderr = cmd.Stdout
525 err := cmd.Run()
526 out.log = strings.TrimSpace(log.String())
527 out.observedAt = time.Now().UTC().Format("2006-01-02T15:04:05Z")
528 out.passed = err == nil
529 return out
530}