gunk-dev/the-valley

run.go

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