gunk-dev/the-valley

run.go

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