gunk-dev/the-valley

check.go

source5facbe322680main's published tip history
5.7 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// (design/verification.md).
11
12import (
13 "bytes"
14 "encoding/json"
15 "fmt"
16 "os"
17 "os/exec"
18 "runtime"
19 "strings"
20 "time"
21)
22
23type checkSpec struct {
24 name string
25 attribute string // nix runner
26 command string // command runner
27}
28
29func (c checkSpec) runner() string {
30 if c.command != "" {
31 return "command"
32 }
33 return "nix"
34}
35
36// checkOutcome is what running one check produced: whether it passed, the
37// output a reader needs when it did not, and the digests of a pure run.
38type checkOutcome struct {
39 spec checkSpec
40 passed bool
41 log string
42
43 inputs string
44 derivation string
45 output string
46 observedAt string
47}
48
49// nixSystem is the flake system attribute of the machine running the
50// check. A check is built where the work was written, so this is the
51// runner's own system and never something the caller states about another
52// machine.
53func nixSystem() string {
54 arch := runtime.GOARCH
55 switch arch {
56 case "amd64":
57 arch = "x86_64"
58 case "arm64":
59 arch = "aarch64"
60 case "386":
61 arch = "i686"
62 }
63 return arch + "-" + runtime.GOOS
64}
65
66func nix(dir string, args ...string) (string, string, error) {
67 cmd := exec.Command("nix", args...)
68 cmd.Dir = dir
69 var out, errb bytes.Buffer
70 cmd.Stdout = &out
71 cmd.Stderr = &errb
72 err := cmd.Run()
73 return out.String(), errb.String(), err
74}
75
76// flakeChecks lists every check attribute a flake defines for a system —
77// what "the repo's canonical checks" means when the caller names none.
78func flakeChecks(tree, system string) ([]string, error) {
79 out, errb, err := nix(tree, "eval", "--json", "--apply", "builtins.attrNames", tree+"#checks."+system)
80 if err != nil {
81 return nil, fmt.Errorf("listing checks: %w: %s", err, strings.TrimSpace(errb))
82 }
83 var names []string
84 if err := json.Unmarshal([]byte(out), &names); err != nil {
85 return nil, fmt.Errorf("listing checks: %w", err)
86 }
87 return names, nil
88}
89
90// closure is what evaluating a pure check names before anything is built:
91// the derivation, and the digest of its input closure. Both are functions
92// of the tree alone, so an integrator can recompute the closure digest on a
93// rebased tree without running the check — which is the whole of the pure
94// transfer rule (dcr-439b771).
95type closure struct {
96 drv string
97 derivation string
98 inputs string
99}
100
101// evalClosure evaluates one flake check over an exported tree and digests
102// what the evaluation named. Nothing is built.
103func evalClosure(tree, system string, spec checkSpec) (closure, error) {
104 attr := tree + "#checks." + system + "." + spec.attribute
105 drv, errb, err := nix(tree, "eval", "--raw", attr+".drvPath")
106 if err != nil {
107 return closure{}, fmt.Errorf("evaluating %s: %w: %s", attr, err, strings.TrimSpace(errb))
108 }
109 drv = strings.TrimSpace(drv)
110
111 drvBytes, err := os.ReadFile(drv)
112 if err != nil {
113 return closure{}, err
114 }
115 inputs, err := drvInputs(drv)
116 if err != nil {
117 return closure{}, err
118 }
119 return closure{
120 drv: drv,
121 derivation: fmt.Sprintf("%x", sha256sum(drvBytes)),
122 inputs: inputsDigest(inputs),
123 }, nil
124}
125
126// runPure builds one flake check over the exported tree and digests what
127// the build named: the derivation's inputs, the derivation, and its
128// output. Building from the derivation path rather than the attribute a
129// second time guarantees the thing built is the thing recorded.
130func runPure(tree, system string, spec checkSpec) (checkOutcome, error) {
131 out := checkOutcome{spec: spec}
132 c, err := evalClosure(tree, system, spec)
133 if err != nil {
134 return out, err
135 }
136 out.derivation, out.inputs = c.derivation, c.inputs
137
138 built, buildLog, err := nix(tree, "build", "--no-link", "--print-out-paths", c.drv+"^*")
139 out.log = strings.TrimSpace(buildLog)
140 if err != nil {
141 return out, nil // a failed check is an outcome, not an error
142 }
143 paths := strings.Fields(built)
144 if len(paths) != 1 {
145 return out, fmt.Errorf("%s produced %d outputs; a check attribute must produce exactly one", spec.name, len(paths))
146 }
147 entries, err := fsEntries(paths[0])
148 if err != nil {
149 return out, err
150 }
151 out.output = treeDigest(entries)
152 out.passed = true
153 return out, nil
154}
155
156// drvInputs collects the store paths a derivation reads: the derivations
157// it depends on and the sources it takes directly. A .drv's references are
158// exactly that set, and `nix-store --query --references` prints them as
159// lines — a shape that has not changed in the lifetime of nix, unlike the
160// versioned JSON of `nix derivation show`.
161func drvInputs(drv string) ([]string, error) {
162 cmd := exec.Command("nix-store", "--query", "--references", drv)
163 var out, errb bytes.Buffer
164 cmd.Stdout = &out
165 cmd.Stderr = &errb
166 if err := cmd.Run(); err != nil {
167 return nil, fmt.Errorf("querying the inputs of %s: %w: %s", drv, err, strings.TrimSpace(errb.String()))
168 }
169 inputs := strings.Fields(out.String())
170 if len(inputs) == 0 {
171 return nil, fmt.Errorf("%s has no inputs at all", drv)
172 }
173 return inputs, nil
174}
175
176// runEffectful runs a command over the exported tree and notarizes what it
177// observed. No digests: there is nothing to re-derive, which is exactly
178// what the effectful predicate type says.
179func runEffectful(tree string, spec checkSpec) checkOutcome {
180 out := checkOutcome{spec: spec}
181 cmd := exec.Command("sh", "-c", spec.command)
182 cmd.Dir = tree
183 log, err := cmd.CombinedOutput()
184 out.log = strings.TrimSpace(string(log))
185 out.observedAt = time.Now().UTC().Format("2006-01-02T15:04:05Z")
186 out.passed = err == nil
187 return out
188}