gunk-dev/the-valley

run.go

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