gunk-dev/the-valley

check.go

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