gunk-dev/the-valley

run.go

source1ef1288a69f6main's published tip history
13.2 KiB
1package main
2
3import (
4 "encoding/json"
5 "errors"
6 "fmt"
7 "os"
8 "path/filepath"
9 "sort"
10 "strings"
11 "time"
12
13 "the-valley/telemetry"
14)
15
16// cmdRun is the whole protocol in order: digest the subject tree, run the
17// checks, compose a statement per check, vet each against the schema,
18// write each out and sign it as a note, store the notes at one ref keyed
19// by the subject digest, and publish with a single atomic push. Every
20// check runs whatever another's result, and then any step failing stops
21// the run before the next — a failed check publishes nothing, and neither
22// does a statement the schema rejects. How long each check took is
23// printed, and logged with --timings (timing.go), whatever the check's
24// result. With --telemetry, the run's progress is recorded as it happens
25// (progress.go).
26func cmdRun(args []string) (err error) {
27 fs := newFlagSet("run")
28 repo := fs.String("repo", "", "repository")
29 rev := fs.String("rev", "HEAD", "revision")
30 key := fs.String("key", "", "ed25519 private key")
31 name := fs.String("name", defaultSignerName(), "the name that key signs under")
32 environment := fs.String("environment", "local", "environment an effectful statement names")
33 provenanceFile := fs.String("provenance", "", "json run provenance")
34 schemaFlag := fs.String("schema", "", "attestation schema")
35 system := fs.String("system", nixSystem(), "flake system")
36 push := fs.String("push", "", "remote to publish to")
37 branch := fs.String("branch", "", "branch pushed alongside")
38 timings := fs.Bool("timings", false, "append each check's timing to the timing log")
39 changeID := fs.String("change", "", "the change ID a timing names")
40 changeVersion := fs.Int("change-version", 0, "the change version a timing names")
41 telemetryDir := fs.String("telemetry", "", "a telemetry stream to record the run's progress in")
42 telemetryRun := fs.String("telemetry-run", "", "the run ID the progress records name")
43 project := fs.String("project", "", "the project the progress records name")
44 capacity := fs.String("capacity", "", "the capacity the builds' progress records name")
45 slots := fs.Int("slots", defaultSlots, "how many nix builds run at once")
46 gcRoots := fs.String("gc-roots", "", "a directory to root every built output in")
47 evalReservations := fs.String("eval-reservations", "", "a directory of reservations the flake checks' evaluation is admitted by")
48 evalEstimate := fs.Int64("eval-estimate", 0, "the peak memory the evaluation is expected to need, in bytes")
49 evalBudget := fs.Int64("eval-budget", 0, "the memory the evaluations admitted by --eval-reservations share, in bytes")
50 evalPeak := fs.String("eval-peak", "", "a file to write the evaluation's peak memory to, in bytes")
51 var checks, commands, costs repeatable
52 fs.Var(&checks, "check", "flake check to run")
53 fs.Var(&commands, "command", "effectful check to run")
54 fs.Var(&costs, "cost", "a check's declared cost class, for its timing")
55 if err := fs.Parse(args); err != nil {
56 return err
57 }
58 if *slots < 1 {
59 return fmt.Errorf("--slots %d: at least one build must run at a time", *slots)
60 }
61 classes, err := costClasses(costs)
62 if err != nil {
63 return err
64 }
65 roots := ""
66 if *gcRoots != "" {
67 if roots, err = filepath.Abs(*gcRoots); err != nil {
68 return fmt.Errorf("--gc-roots %s: %v", *gcRoots, err)
69 }
70 if err := os.MkdirAll(roots, 0o755); err != nil {
71 return fmt.Errorf("--gc-roots %s: %v", *gcRoots, err)
72 }
73 }
74
75 var adm *admission
76 if *evalReservations != "" {
77 if *evalBudget < 1 {
78 return fmt.Errorf("--eval-reservations needs --eval-budget: the memory the evaluations share, in bytes")
79 }
80 if *evalEstimate < 0 {
81 return fmt.Errorf("--eval-estimate %d: not a number of bytes", *evalEstimate)
82 }
83 dir, err := filepath.Abs(*evalReservations)
84 if err != nil {
85 return fmt.Errorf("--eval-reservations %s: %v", *evalReservations, err)
86 }
87 // An evaluation with no estimate counts as the whole budget, so it
88 // runs alone.
89 adm = &admission{dir: dir, estimate: *evalEstimate, budget: *evalBudget}
90 if adm.estimate == 0 {
91 adm.estimate = adm.budget
92 }
93 }
94 peakFile := ""
95 if *evalPeak != "" {
96 if peakFile, err = filepath.Abs(*evalPeak); err != nil {
97 return fmt.Errorf("--eval-peak %s: %v", *evalPeak, err)
98 }
99 }
100
101 root, err := repoRoot(*repo)
102 if err != nil {
103 return err
104 }
105 schema, err := schemaPath(*schemaFlag, root)
106 if err != nil {
107 return err
108 }
109 prov, err := loadProvenance(*provenanceFile)
110 if err != nil {
111 return err
112 }
113
114 // The signer is checked before any work is done: a run that can only
115 // end in "no key" should say so before it builds anything.
116 host, err := loadSigner(*key, *name)
117 if err != nil {
118 return err
119 }
120
121 subj, err := composeSubject(root, *rev)
122 if err != nil {
123 return err
124 }
125 fmt.Printf("subject %s:%s\n", subj.Primary, subj.Digest[subj.Primary])
126 for _, alg := range sortedKeys(subj.Digest) {
127 if alg != subj.Primary {
128 fmt.Printf(" %s:%s (advisory)\n", alg, subj.Digest[alg])
129 }
130 }
131 fmt.Printf("signer %s\n", host.verifierKey())
132
133 tel := telemetry.NewEmitter(*telemetryDir, telemetry.Self("attest", ""), *telemetryRun)
134 tel.Correlate(telemetry.Record{Project: *project, Change: *changeID, Version: *changeVersion,
135 Head: subj.Digest["git-sha1"] + subj.Digest["git-sha256"], Tree: subj.Digest[subj.Primary]})
136 tel.Emit("run.start", telemetry.Record{}, map[string]any{"checks": append(append([]string{}, checks...), commands...), "slots": *slots, "system": *system})
137 defer func() {
138 result := "passed"
139 if err != nil {
140 result = "failed"
141 }
142 tel.Emit("run.end", telemetry.Record{}, map[string]any{"result": result})
143 }()
144 obs := newObserver(tel)
145 if obs != nil {
146 obs.capacity = *capacity
147 }
148
149 tree, err := os.MkdirTemp("", "valley-attest-tree")
150 if err != nil {
151 return err
152 }
153 defer os.RemoveAll(tree)
154 if err := exportTree(root, *rev, tree); err != nil {
155 return err
156 }
157
158 specs, err := checkSpecs(tree, *system, checks, commands)
159 if err != nil {
160 return err
161 }
162 if len(specs) == 0 {
163 return fmt.Errorf("no checks to run")
164 }
165
166 log := &timingLog{warn: timingStderr()}
167 repository := ""
168 if *timings {
169 path, pathErr := timingsPath()
170 if pathErr != nil {
171 fmt.Fprintf(timingStderr(), "attest: warning: timings not logged: %v\n", pathErr)
172 }
173 log.path = path
174 repository = repositoryName(root)
175 }
176 commit := subj.Digest["git-sha1"] + subj.Digest["git-sha256"]
177
178 // The pure checks are evaluated together and built side by side first
179 // (runPure), each reported in the order given as soon as it and those
180 // before it have ended. The command checks then run one at a time,
181 // each reported as it ends. A check that fails or cannot run stops no
182 // other.
183 var pure, effectful []checkSpec
184 for _, spec := range specs {
185 if spec.runner() == "nix" {
186 pure = append(pure, spec)
187 } else {
188 effectful = append(effectful, spec)
189 }
190 }
191 outcomes := make([]checkOutcome, 0, len(specs))
192 var errs []error
193 failed := 0
194 report := func(r ranCheck) {
195 result := "passed"
196 switch {
197 case r.err != nil:
198 result = "error"
199 case !r.out.passed:
200 result = "failed"
201 failed++
202 }
203 t := checkTiming{
204 Time: r.began.UTC().Format("2006-01-02T15:04:05.000Z"),
205 Repository: repository,
206 Change: *changeID,
207 Version: *changeVersion,
208 Head: commit,
209 Check: r.out.spec.name,
210 Runner: r.out.spec.runner(),
211 Cost: classes[r.out.spec.name],
212 Result: result,
213 Satisfied: r.out.satisfied,
214 DurationMS: r.took.Milliseconds(),
215 EvalMS: r.eval.Milliseconds(),
216 }
217 if t.Satisfied == "" {
218 t.Satisfied = satisfiedUnknown
219 }
220 log.append(t)
221 if r.err != nil {
222 fmt.Fprintln(timingStdout(), timingLine(t, r.took))
223 errs = append(errs, r.err)
224 return
225 }
226 fmt.Printf("check %-24s %-8s %s\n", r.out.spec.name, r.out.spec.runner(), result)
227 fmt.Fprintln(timingStdout(), timingLine(t, r.took))
228 outcomes = append(outcomes, r.out)
229 }
230 if _, err := runPure(tree, *system, pure, *timings, *slots, roots, adm, peakFile, report, obs); err != nil {
231 return err
232 }
233 for _, spec := range effectful {
234 began := time.Now()
235 obs.emit("check.start", spec.name, nil)
236 log := tel.Log(spec.name)
237 out := runEffectful(tree, spec, log)
238 bytes, truncated := log.Close()
239 r := ranCheck{out: out, began: began, took: time.Since(began)}
240 obs.emit("check.result", spec.name, map[string]any{"result": resultOf(r), "check_ms": r.took.Milliseconds(), "log_bytes": bytes, "log_truncated": truncated})
241 report(r)
242 }
243 if failed > 0 {
244 for _, out := range outcomes {
245 if !out.passed && out.log != "" {
246 fmt.Fprintf(os.Stderr, "\n--- %s ---\n%s\n", out.spec.name, out.log)
247 }
248 }
249 }
250 if len(errs) > 0 {
251 return errors.Join(errs...)
252 }
253 if failed > 0 {
254 return fmt.Errorf("%d of %d checks failed; nothing published", failed, len(specs))
255 }
256
257 // Compose, validate, render. Every statement is vetted before any of
258 // them is written out, so a malformed one cannot leave a half-signed
259 // set behind. The schema is the gate and it reads JSON; the text is
260 // what a signature covers, and it carries exactly what the JSON does.
261 texts := make([][]byte, len(outcomes))
262 for i, out := range outcomes {
263 st := composeStatement(subj, out, *environment, prov)
264 doc, err := json.Marshal(st)
265 if err != nil {
266 return err
267 }
268 if err := vetStatement(schema, doc); err != nil {
269 return fmt.Errorf("%s: %w\nnothing published", out.spec.name, err)
270 }
271 if texts[i], err = renderJSON(doc); err != nil {
272 return fmt.Errorf("%s: %w\nnothing published", out.spec.name, err)
273 }
274 }
275
276 subtrees := map[string]string{}
277 for i, out := range outcomes {
278 note, err := signNote(texts[i], host)
279 if err != nil {
280 return err
281 }
282 noteBlob, err := writeBlob(root, note)
283 if err != nil {
284 return err
285 }
286 sub, err := mkTree(root, map[string]string{"statement.note": noteBlob}, nil)
287 if err != nil {
288 return err
289 }
290 subtrees[out.spec.name] = sub
291 }
292 top, err := mkTree(root, nil, subtrees)
293 if err != nil {
294 return err
295 }
296 ref := attestationRef(subj.Digest[subj.Primary], fmt.Sprintf("%08x", host.hash))
297 if _, err := git(root, "update-ref", ref, top); err != nil {
298 return err
299 }
300 fmt.Printf("stored %s -> %s\n", ref, top)
301 tel.Emit("evidence.stored", telemetry.Record{}, map[string]any{"ref": ref, "object": top})
302
303 if *push == "" {
304 return nil
305 }
306 head := *branch
307 if head == "" {
308 head, err = gitLine(root, "symbolic-ref", "--short", "HEAD")
309 if err != nil {
310 return fmt.Errorf("no branch to push: %w", err)
311 }
312 }
313 head = strings.TrimPrefix(head, "refs/heads/")
314 branchSpec := fmt.Sprintf("refs/heads/%s:refs/heads/%s", head, head)
315 refSpec := ref + ":" + ref
316 out, err := gitPush(root, "--atomic", *push, branchSpec, refSpec)
317 if err != nil {
318 return err
319 }
320 fmt.Printf("pushed %s --atomic %s %s\n%s", *push, branchSpec, refSpec, out)
321 return nil
322}
323
324// composeSubject builds the digest set: the content-addressed tree digest
325// as the member that IS the identity, and the commit as an advisory member
326// for finding the change.
327func composeSubject(root, rev string) (subject, error) {
328 entries, err := gitTreeEntries(root, rev)
329 if err != nil {
330 return subject{}, err
331 }
332 commit, err := gitLine(root, "rev-parse", rev+"^{commit}")
333 if err != nil {
334 return subject{}, err
335 }
336 subj := subject{Primary: treeScheme, Digest: map[string]string{treeScheme: treeDigest(entries)}}
337 switch len(commit) {
338 case 40:
339 subj.Digest["git-sha1"] = commit
340 case 64:
341 subj.Digest["git-sha256"] = commit
342 default:
343 return subject{}, fmt.Errorf("unexpected object id %q", commit)
344 }
345 return subj, nil
346}
347
348func composeStatement(subj subject, out checkOutcome, environment string, prov json.RawMessage) statement {
349 result := "failed"
350 if out.passed {
351 result = "passed"
352 }
353 st := statement{
354 StatementType: statementType,
355 Subject: subj,
356 Provenance: prov,
357 Predicate: predicate{
358 Check: checkRun{
359 Name: out.spec.name,
360 Runner: out.spec.runner(),
361 Attribute: out.spec.attribute,
362 Command: out.spec.command,
363 },
364 Result: result,
365 },
366 }
367 if out.spec.runner() == "nix" {
368 st.PredicateType = predicatePure
369 st.Predicate.Inputs = map[string]string{inputsScheme: out.inputs}
370 st.Predicate.Derivation = map[string]string{"sha256": out.derivation}
371 st.Predicate.Output = map[string]string{treeScheme: out.output}
372 } else {
373 st.PredicateType = predicateEffect
374 st.Predicate.Environment = environment
375 st.Predicate.ObservedAt = out.observedAt
376 }
377 return st
378}
379
380// checkSpecs resolves what to run. Naming no check means the repo's whole
381// canonical set: every check the flake defines for this system.
382func checkSpecs(tree, system string, checks, commands repeatable) ([]checkSpec, error) {
383 var specs []checkSpec
384 for _, c := range checks {
385 name, attr, found := strings.Cut(c, "=")
386 if !found {
387 attr = name
388 }
389 specs = append(specs, checkSpec{name: name, attribute: attr})
390 }
391 for _, c := range commands {
392 name, command, found := strings.Cut(c, "=")
393 if !found {
394 return nil, fmt.Errorf("--command %q: expected NAME=COMMAND", c)
395 }
396 specs = append(specs, checkSpec{name: name, command: command})
397 }
398 if len(specs) > 0 {
399 return specs, nil
400 }
401 names, err := flakeChecks(tree, system)
402 if err != nil {
403 return nil, err
404 }
405 for _, n := range names {
406 specs = append(specs, checkSpec{name: n, attribute: n})
407 }
408 return specs, nil
409}
410
411func sortedKeys(m map[string]string) []string {
412 keys := make([]string, 0, len(m))
413 for k := range m {
414 keys = append(keys, k)
415 }
416 sort.Strings(keys)
417 return keys
418}