gunk-dev/the-valley

checkbuild.go

source58e68be0d151main's published tip history
34.7 KiB
1package main
2
3// checks --build asks one question: does origin hold passing evidence for
4// every nix check HEAD requires? It asks the host's check worker to build
5// what is missing, and waits.
6//
7// It derives HEAD's checks as the worker derives a check request's
8// (worker.go): over HEAD's merge base with main as origin holds it now,
9// under both policy layers read there (checks.go). It reads origin's
10// evidence for HEAD's tree as approve does (coverage.go); evidence that
11// does not count for a check, whatever it records, is no evidence for it.
12// When one read covers every check, it passes without filing anything.
13//
14// Otherwise it takes the worktree's lock, reads or makes the worktree's
15// token under it, deletes the requests the worktree left on origin, each
16// leased on the commit listed, takes a cursor at the end of the worker's
17// telemetry, and files a check request (../change/checkrequest.go) for
18// HEAD with a new attempt token. It follows the telemetry from the cursor
19// as a wake-up only: the wait ends when a batch for HEAD's tree fails or
20// ends unpassed, when a publish for the tree ends (a batch that passed
21// publishes before the evidence is on origin, so its batch.end is no
22// wake-up), when a pass ends whose pass.start came after the stream's end
23// read once the push returned, with no batch for the tree running, when a
24// record says its producer lost records (dropped_before), or when the
25// stream cannot be read. The cursor comes before the filing so a worker
26// quick to finish is not missed. It also reads origin's evidence every
27// evidenceEvery. No record is taken as this request's result.
28//
29// It has two outcomes. Passed (exit 0) only when one read, the last,
30// completes and covers every check. Anything else is not established
31// (exit 1): it says why it stopped, and prints the check.result records
32// the worker wrote for HEAD's tree, labelled as such, with the nix log
33// command that reads each failed check's build log from the derivation
34// its result names, the error and build error its result records, or
35// else the command
36// that builds that check here.
37//
38// The command runs as a child of itself in a process group of its own.
39// The parent fixes the deadline (--wait) before the child starts, and
40// kills the child's group when the child ends, the deadline passes or a
41// signal comes; a program that made a group of its own escapes that. The
42// child tells the parent on a pipe, in validated values only, what it
43// filed or is deleting, and whether it passed; the parent deletes, leased,
44// what the child left, and exits 0 only on a reported pass. A push that
45// did not report success leaves the request's existence unknown: it is
46// deleted, leased, and unless origin then lists it absent after a push
47// origin refused, the leased delete is printed.
48
49import (
50 "bufio"
51 "bytes"
52 "cmp"
53 "context"
54 "encoding/base64"
55 "encoding/json"
56 "errors"
57 "fmt"
58 "io"
59 "os"
60 "os/exec"
61 "os/signal"
62 "path/filepath"
63 "regexp"
64 "runtime"
65 "sort"
66 "strconv"
67 "strings"
68 "syscall"
69 "time"
70
71 "the-valley/change"
72 "the-valley/telemetry"
73)
74
75const checkBuildUsage = "usage: valley checks --build [--wait <duration>]"
76
77const (
78 // checkBuildChild is the verb the parent runs the command as, with
79 // the state pipe at the descriptor checkBuildState names.
80 checkBuildChild = "checks-build-child"
81 checkBuildState = "VALLEY_CHECK_BUILD_STATE"
82 // What the command keeps in a worktree's git directory.
83 worktreeTokenFile = "valley-check-request"
84 requestLockFile = "valley-check-request.lock"
85)
86
87// defaultWait is --wait's default. A ready change has first claim on the
88// worker, so a request can wait behind the host's whole queue; two hours
89// outlasts a busy host's queue and one cold build of a large check set.
90const defaultWait = 2 * time.Hour
91
92// evidenceEvery is how often the wait reads origin's evidence whatever the
93// telemetry says, since the stream can drop a wake-up unseen; cleanupBound
94// is how long deleting the request may take.
95const (
96 evidenceEvery = 3 * time.Minute
97 cleanupBound = 30 * time.Second
98)
99
100// errorRunes is how much of a result's error is kept: attest clips the
101// errors it records shorter, so this bounds only what another writer put
102// in the worker's stream.
103const errorRunes = 400
104
105// runCheckBuild is valley checks --build: the parent, which watches the
106// child that does the work.
107func runCheckBuild(g git, args []string, stdout, stderr io.Writer) int {
108 wait, err := buildWait(args)
109 if err != nil {
110 fmt.Fprintf(stderr, "valley: %v\n%s\n", err, checkBuildUsage)
111 return 1
112 }
113 self, err := os.Executable()
114 if err != nil {
115 fmt.Fprintf(stderr, "valley: %v\n", err)
116 return 1
117 }
118 signals := make(chan os.Signal, 2)
119 signal.Notify(signals, os.Interrupt, syscall.SIGTERM, syscall.SIGHUP)
120 defer signal.Stop(signals)
121 return watch(g, self, wait, stdout, stderr, signals)
122}
123
124// buildMode reports whether a checks command line asks for --build.
125func buildMode(args []string) bool {
126 for _, a := range args {
127 if a == "--" {
128 return false
129 }
130 if a == "--build" {
131 return true
132 }
133 }
134 return false
135}
136
137// buildWait reads a checks --build command line: --build, and --wait with
138// a positive duration.
139func buildWait(args []string) (time.Duration, error) {
140 wait := defaultWait
141 for i := 0; i < len(args); i++ {
142 opt, value, inline := strings.Cut(args[i], "=")
143 switch {
144 case args[i] == "--build":
145 case opt == "--wait":
146 if !inline {
147 if i+1 >= len(args) {
148 return 0, errors.New("--wait needs a duration, such as 30m")
149 }
150 i++
151 value = args[i]
152 }
153 d, err := time.ParseDuration(value)
154 if err != nil || d <= 0 {
155 return 0, fmt.Errorf("--wait takes a positive duration, such as 30m or 2h, not %q", value)
156 }
157 wait = d
158 default:
159 return 0, errors.New("--build works on HEAD, and takes no option but --wait and no revision")
160 }
161 }
162 return wait, nil
163}
164
165// watch runs self as the child, and returns the exit status. When wait
166// passes or a signal comes first, it kills the child's process group,
167// deletes the request the child filed and did not delete, and says the
168// outcome is not established.
169func watch(g git, self string, wait time.Duration, stdout, stderr io.Writer, signals <-chan os.Signal) int {
170 deadline := time.NewTimer(wait)
171 defer deadline.Stop()
172 r, w, err := os.Pipe()
173 if err != nil {
174 fmt.Fprintf(stderr, "valley: %v\n", err)
175 return 1
176 }
177 defer r.Close()
178 cmd := exec.Command(self, checkBuildChild)
179 cmd.Env = append(os.Environ(), checkBuildState+"=3")
180 cmd.Stdout, cmd.Stderr, cmd.ExtraFiles = stdout, stderr, []*os.File{w}
181 cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
182 err = cmd.Start()
183 w.Close()
184 if err != nil {
185 fmt.Fprintf(stderr, "valley: %v\n", err)
186 return 1
187 }
188 // The pipe ends when the child does, since no program it starts holds
189 // it. The child is then unreaped, so its group can still be killed,
190 // with whatever the child left running.
191 var s childState
192 read := make(chan struct{})
193 go func() { s.read(r); close(read) }()
194 why := ""
195 select {
196 case <-read:
197 case <-deadline.C:
198 why = "time limit"
199 case <-signals:
200 why = "interrupted"
201 }
202 syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
203 err = cmd.Wait()
204 <-read
205 s.settle(g, stderr, signals)
206 var exit *exec.ExitError
207 switch {
208 case s.err != nil || err != nil && !errors.As(err, &exit):
209 fmt.Fprintf(stderr, "valley: the command did not end cleanly (%v), so whether its requests are deleted is not established\n", oneLine(errors.Join(err, s.err).Error()))
210 return 1
211 case why == "" && err == nil && s.passed:
212 return 0
213 case why == "" && err == nil:
214 fmt.Fprintln(stderr, "valley: the command ended without an outcome")
215 return 1
216 case why == "":
217 return exit.ExitCode()
218 }
219 t := terminalOf(stdout)
220 subject := s.short
221 if subject == "" {
222 subject = "HEAD"
223 }
224 fmt.Fprintln(stdout, t.tint(colourWaiting, "◇")+" "+t.strong(subject)+" not established · "+why)
225 report(stdout, s.results, s.attrs)
226 if why == "interrupted" {
227 return interruptedStatus
228 }
229 return 1
230}
231
232// childState is what the child told the parent. settled means the child
233// tried to delete its request, and said so when it could not; stale is
234// each earlier request whose delete the child started and did not end.
235type childState struct {
236 short, ref, head, pushed string
237 settled, passed bool
238 attrs, stale map[string]string
239 results []treeResult
240 err error
241}
242
243// treeResult is a check.result the worker wrote for HEAD's tree: drv is
244// the derivation whose build decided it, a validated store path or "";
245// err the error it records and buildErr how its nix build ended, both
246// untrusted. A build that ended before its builder started leaves nix no
247// log, and buildErr is then the whole diagnosis.
248type treeResult struct {
249 run, check, result string
250 ms int64
251 drv, err, buildErr string
252}
253
254func (s *childState) read(r io.Reader) {
255 s.attrs, s.stale = map[string]string{}, map[string]string{}
256 sc := bufio.NewScanner(r)
257 defer func() { s.err = sc.Err() }()
258 for sc.Scan() {
259 f := strings.Fields(sc.Text())
260 switch {
261 case len(f) == 2 && f[0] == "head":
262 s.short = f[1]
263 case len(f) == 3 && f[0] == "check":
264 s.attrs[f[1]] = f[2]
265 case len(f) == 8 && f[0] == "result":
266 ms, _ := strconv.ParseInt(f[4], 10, 64)
267 r := treeResult{run: f[1], check: f[2], result: f[3], ms: ms, err: decoded(f[6]), buildErr: decoded(f[7])}
268 if storeDrv.MatchString(f[5]) {
269 r.drv = f[5]
270 }
271 s.results = append(s.results, r)
272 case len(f) == 3 && f[0] == "filing":
273 s.ref, s.head, s.pushed, s.settled = f[1], f[2], "unknown", false
274 case len(f) == 2 && f[0] == "pushed":
275 s.pushed = f[1]
276 case len(f) == 1 && f[0] == "settled":
277 s.settled = true
278 case len(f) == 1 && f[0] == "passed":
279 s.passed = true
280 case len(f) == 3 && f[0] == "stale":
281 s.stale[f[1]] = f[2]
282 case len(f) == 2 && f[0] == "cleared":
283 delete(s.stale, f[1])
284 }
285 }
286}
287
288// settle deletes the requests the child left, within cleanupBound or until
289// a second signal.
290func (s *childState) settle(g git, stderr io.Writer, signals <-chan os.Signal) {
291 if (s.ref == "" || s.settled) && len(s.stale) == 0 {
292 return
293 }
294 ctx, cancel := context.WithTimeout(context.Background(), cleanupBound)
295 defer cancel()
296 go func() {
297 select {
298 case <-signals:
299 cancel()
300 case <-ctx.Done():
301 }
302 }()
303 if s.ref != "" && !s.settled && !deleteRequest(ctx, g, true, s.ref, s.head, s.pushed) {
304 unsettled(stderr, s.ref, s.head)
305 }
306 for ref, oid := range s.stale {
307 if !deleteRequest(ctx, g, true, ref, oid, "ok") {
308 unsettled(stderr, ref, oid)
309 }
310 }
311}
312
313// deleteRequest deletes ref on origin, leased on head, after a push that
314// reported pushed: ok, rejected or unknown. It reports whether origin is
315// known not to hold the request: the delete went through, or origin lists
316// it absent and the push did not leave its existence unknown.
317func deleteRequest(ctx context.Context, g git, group bool, ref, head, pushed string) bool {
318 if pushed != "rejected" {
319 if result, _ := pushOrigin(ctx, g, group, "--force-with-lease="+ref+":"+head, ":"+ref); result == "ok" {
320 return true
321 }
322 }
323 out, _, err := gitIn(ctx, g, group, "ls-remote", "--refs", "origin", ref)
324 return err == nil && !strings.Contains(out, "\t"+ref+"\n") && pushed != "unknown"
325}
326
327func unsettled(stderr io.Writer, ref, head string) {
328 fmt.Fprintf(stderr, "valley: whether origin still holds the check request is not established\n run: git push --force-with-lease=%s:%s origin :%s\n", ref, head, ref)
329}
330
331// pushOrigin pushes spec to origin, and says what origin reported: ok,
332// rejected when it refused the update, or unknown when the push ended
333// without saying, as a transport that failed does.
334func pushOrigin(ctx context.Context, g git, group bool, lease, spec string) (string, error) {
335 out, errs, err := gitIn(ctx, g, group, "push", "--porcelain", lease, "origin", spec)
336 if err == nil {
337 return "ok", nil
338 }
339 var said []string
340 for _, line := range strings.Split(errs, "\n") {
341 if remote, ok := strings.CutPrefix(line, "remote: "); ok && strings.TrimSpace(remote) != "" {
342 said = append(said, strings.TrimSpace(remote))
343 }
344 }
345 if len(said) == 0 {
346 said = []string{strings.TrimSpace(errs)}
347 }
348 return pushStatus(out, spec[strings.Index(spec, ":")+1:]), errors.New(strings.Join(said, "; "))
349}
350
351// pushStatus is what git push --porcelain reported for ref: rejected only
352// when its line rejects that ref, and unknown otherwise, as for a remote
353// that failed to report status.
354func pushStatus(out, ref string) string {
355 for _, line := range strings.Split(out, "\n") {
356 f := strings.SplitN(line, "\t", 3)
357 if len(f) == 3 && f[0] == "!" && strings.HasSuffix(f[1], ":"+ref) &&
358 (strings.HasPrefix(f[2], "[rejected]") || strings.HasPrefix(f[2], "[remote rejected]")) {
359 return "rejected"
360 }
361 }
362 return "unknown"
363}
364
365// gitIn runs git under ctx. In a group of its own, ending ctx kills the
366// group; the parent runs its git so, while the child runs its git in the
367// child's group, which the parent kills whole.
368func gitIn(ctx context.Context, g git, group bool, args ...string) (stdout, stderr string, err error) {
369 cmd := exec.CommandContext(ctx, "git", args...)
370 cmd.Env, cmd.Dir = g.env, g.dir
371 if group {
372 cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
373 cmd.Cancel = func() error { return syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) }
374 }
375 cmd.WaitDelay = 2 * time.Second
376 var out, errs bytes.Buffer
377 cmd.Stdout, cmd.Stderr = &out, &errs
378 processStarted()
379 err = cmd.Run()
380 return out.String(), errs.String(), err
381}
382
383// runCheckBuildChild is the child: the command's work.
384func runCheckBuildChild(g git, args []string, stdout, stderr io.Writer) int {
385 if os.Getenv(checkBuildState) != "3" || len(args) != 0 {
386 fmt.Fprintf(stderr, "valley: unknown verb: %s\n", checkBuildChild)
387 return 1
388 }
389 syscall.CloseOnExec(3)
390 a := newAsking(g, stdout, stderr)
391 a.states = os.NewFile(3, "state")
392 status := a.run()
393 if status == 0 {
394 a.state("passed")
395 }
396 return status
397}
398
399// asking is the child's work.
400type asking struct {
401 g git
402 stdout, stderr io.Writer
403 t terminal
404 states io.Writer // the pipe to the parent
405 began time.Time
406 readEvery time.Duration
407 lock *os.File // the worktree's lock, held while the process runs
408
409 head, short, project, tree string
410 mark int64 // the stream's newest record once the request was filed
411 required int
412 nix []nixCheck
413 commands []string
414 ref string
415 results []treeResult
416
417 derive func() error
418 cover func(checks []nixCheck) (evidence, error)
419 stream workerStream
420}
421
422func newAsking(g git, stdout, stderr io.Writer) *asking {
423 a := &asking{g: g, stdout: stdout, stderr: stderr, t: terminalOf(stdout), states: io.Discard,
424 began: time.Now(), readEvery: evidenceEvery}
425 a.derive = a.prepare
426 a.cover = func(checks []nixCheck) (evidence, error) {
427 if _, err := exec.LookPath("attest"); err != nil {
428 return evidence{}, failure("the attest helper is not installed; nix run .#valley bundles it")
429 }
430 quiet := a.g
431 quiet.stderr = io.Discard
432 return coverageOf(quiet, a.head, checks, io.Discard)
433 }
434 return a
435}
436
437func (a *asking) run() int {
438 if err := a.derive(); err != nil {
439 return a.fail(err)
440 }
441 a.state("head", a.short)
442 if a.required == 0 {
443 a.say("✓", colourDone, a.short, "no checks required")
444 return 0
445 }
446 for _, c := range a.nix {
447 a.state("check", c.name, c.attribute)
448 }
449 covered, err := a.read()
450 if err != nil {
451 return a.fail(err)
452 }
453 if len(covered) == len(a.nix) {
454 return a.verdict(covered, nil, "")
455 }
456 principal, err := a.g.output(true, "config", "valley.principal")
457 if err != nil || !change.ValidPrincipal(principal) {
458 return a.fail(failure("a check request is filed under the principal your key pushes as, and git config valley.principal names none; set it with git config valley.principal <name>"))
459 }
460 token, err := a.claim(principal)
461 if err != nil {
462 return a.fail(err)
463 }
464 a.recoverStale(principal, token)
465 a.say("◐", colourWorking, a.short, countOf(len(a.nix), "nix check")+" required",
466 fmt.Sprintf("%d with evidence", len(covered)), "asking the worker")
467 cursor, err := a.stream.end(context.Background())
468 if err != nil {
469 fmt.Fprintf(a.stderr, "valley: %s\n", oneLine(err.Error()))
470 covered, err = a.read()
471 return a.verdict(covered, err, "telemetry unreadable")
472 }
473 attempt, err := change.NewCheckRequestToken()
474 if err != nil {
475 return a.fail(err)
476 }
477 a.ref, _ = change.CheckRequestRef(principal, token, attempt)
478 a.state("filing", a.ref, a.head)
479 pushed, err := pushOrigin(context.Background(), a.g, false, "--force-with-lease="+a.ref+":", a.head+":"+a.ref)
480 a.state("pushed", pushed)
481 why := ""
482 covered = nil
483 switch pushed {
484 case "rejected":
485 fmt.Fprintf(a.stderr, "valley: origin refused the check request: %s\n", oneLine(err.Error()))
486 why = "the request was refused"
487 case "unknown":
488 fmt.Fprintf(a.stderr, "valley: the check request's push did not finish: %s\n", oneLine(err.Error()))
489 why = "the request's push did not finish"
490 default:
491 why, covered = a.wait(cursor)
492 }
493 var readErr error
494 if covered == nil {
495 covered, readErr = a.read()
496 }
497 ctx, cancel := context.WithTimeout(context.Background(), cleanupBound)
498 defer cancel()
499 if !deleteRequest(ctx, a.g, false, a.ref, a.head, pushed) {
500 unsettled(a.stderr, a.ref, a.head)
501 }
502 a.state("settled")
503 return a.verdict(covered, readErr, why)
504}
505
506// state tells the parent one fact. A value outside stateValue, which no
507// newline or space is in, is never sent.
508func (a *asking) state(fields ...string) {
509 for _, f := range fields {
510 if !stateValue.MatchString(f) {
511 return
512 }
513 }
514 fmt.Fprintln(a.states, strings.Join(fields, " "))
515}
516
517var (
518 stateValue = regexp.MustCompile(`^[A-Za-z0-9._/:@+?=-]+$`)
519 runName = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$`) // telemetry's run names
520 // storeDrv is a derivation's path in the nix store, the only form of
521 // a check.result's drv printed as a command to run.
522 storeDrv = regexp.MustCompile(`^/nix/store/[0-9a-df-np-sv-z]{32}-[A-Za-z0-9+_?=-][A-Za-z0-9+._?=-]{0,210}\.drv$`)
523)
524
525// read reads origin's evidence for HEAD's tree, and returns the checks it
526// covers.
527func (a *asking) read() (map[string]bool, error) {
528 e, err := a.cover(a.nix)
529 if err != nil {
530 return nil, fmt.Errorf("could not read the evidence origin holds for HEAD's tree: %v", err)
531 }
532 a.tree = e.digest
533 covered := map[string]bool{}
534 for _, c := range a.nix {
535 if _, ok := e.covered[c.name]; ok {
536 covered[c.name] = true
537 }
538 }
539 return covered, nil
540}
541
542// claim takes the worktree's lock, held until the process ends, and reads
543// or makes the worktree's token under it.
544func (a *asking) claim(principal string) (string, error) {
545 gitDir, err := a.g.output(true, "rev-parse", "--absolute-git-dir")
546 if err != nil {
547 return "", failure("not a git repository")
548 }
549 lock, err := os.OpenFile(filepath.Join(gitDir, requestLockFile), os.O_CREATE|os.O_RDWR, 0o600)
550 if err != nil {
551 return "", err
552 }
553 if err := syscall.Flock(int(lock.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
554 lock.Close()
555 return "", failure("another valley checks --build is running in this worktree")
556 }
557 a.lock = lock
558 path := filepath.Join(gitDir, worktreeTokenFile)
559 if data, err := os.ReadFile(path); err == nil {
560 token := strings.TrimSpace(string(data))
561 if _, ok := change.CheckRequestRef(principal, token, token); ok {
562 return token, nil
563 }
564 return "", failure(path + " holds no check request token; remove it, and the next run makes one")
565 } else if !os.IsNotExist(err) {
566 return "", err
567 }
568 token, err := change.NewCheckRequestToken()
569 if err != nil {
570 return "", err
571 }
572 if err := os.WriteFile(path+".new", []byte(token+"\n"), 0o600); err != nil {
573 return "", err
574 }
575 return token, os.Rename(path+".new", path)
576}
577
578// recoverStale deletes the requests origin lists under the worktree's
579// token, each leased on the commit listed. One it cannot delete is said,
580// with the leased delete.
581func (a *asking) recoverStale(principal, token string) {
582 prefix, _ := change.CheckRequestRef(principal, token, token)
583 prefix = strings.TrimSuffix(prefix, token)
584 out, err := a.g.output(true, "ls-remote", "--refs", "origin", prefix+"*")
585 if err != nil {
586 fmt.Fprintf(a.stderr, "valley: could not list this worktree's earlier check requests on origin: %s\n", oneLine(err.Error()))
587 return
588 }
589 for _, line := range strings.Split(out, "\n") {
590 oid, ref, ok := strings.Cut(line, "\t")
591 if !ok || !strings.HasPrefix(ref, prefix) {
592 continue
593 }
594 if _, _, _, valid := change.ParseCheckRequestRef(ref); !valid || !isObjectID(oid) {
595 fmt.Fprintf(a.stderr, "valley: %s is no check request, so it is skipped\n", oneLine(ref))
596 continue
597 }
598 a.state("stale", ref, oid)
599 if result, _ := pushOrigin(context.Background(), a.g, false, "--force-with-lease="+ref+":"+oid, ":"+ref); result != "ok" {
600 unsettled(a.stderr, ref, oid)
601 }
602 a.state("cleared", ref)
603 }
604}
605
606// wait follows the worker's telemetry from cursor, taken before the
607// filing, until a wake-up, reading origin's evidence every a.readEvery. It
608// returns why it stopped, or the read that covered every check.
609func (a *asking) wait(cursor string) (string, map[string]bool) {
610 // Where the stream ended once the push returned: a pass that starts
611 // after it started after the filing.
612 mark, err := a.stream.end(context.Background())
613 if c, perr := telemetry.ParseCursor(mark); err == nil && perr == nil && c[workerSource] != (telemetry.Position{}) {
614 a.mark = c[workerSource].Seq
615 } else {
616 fmt.Fprintf(a.stderr, "valley: the worker's stream gave no position after the filing: %s\n", oneLine(fmt.Sprint(err)))
617 return "telemetry unreadable", nil
618 }
619 a.say("◇", colourWaiting, a.short, "waiting for the worker")
620 started, running := map[string]bool{}, map[string]bool{}
621 last := time.Now()
622 for {
623 seconds := int(max(a.readEvery-time.Since(last), 0)/time.Second) + 1
624 ctx, cancel := context.WithCancel(context.Background())
625 records := make(chan workerRecord, 256)
626 var next string
627 var ferr error
628 go func() {
629 defer close(records)
630 next, ferr = a.stream.follow(ctx, cursor, seconds, records)
631 }()
632 why := ""
633 for r := range records {
634 if why == "" {
635 if why = a.wake(r, started, running); why != "" {
636 cancel()
637 }
638 }
639 }
640 cancel()
641 switch {
642 case why != "":
643 return why, nil
644 case ferr != nil:
645 fmt.Fprintf(a.stderr, "valley: %s\n", oneLine(ferr.Error()))
646 return "telemetry unreadable", nil
647 }
648 cursor = next
649 if time.Since(last) >= a.readEvery {
650 last = time.Now()
651 if covered, err := a.read(); err == nil && len(covered) == len(a.nix) {
652 return "", covered
653 }
654 }
655 }
656}
657
658// wake takes one worker record, keeps a check.result for the tree, and
659// says why the wait should end, or "".
660func (a *asking) wake(r workerRecord, started, running map[string]bool) string {
661 if n, _ := r.Data["dropped_before"].(float64); n > 0 {
662 return "telemetry lost records"
663 }
664 switch r.Type {
665 case "pass.start":
666 started[r.Run] = r.Seq > a.mark
667 return ""
668 case "pass.end":
669 if started[r.Run] && len(running) == 0 {
670 return "a worker pass ended"
671 }
672 return ""
673 }
674 if r.Project != a.project || r.Tree != a.tree {
675 return ""
676 }
677 run, _ := r.Data["attest_run"].(string)
678 result, _ := r.Data["result"].(string)
679 switch r.Type {
680 case "batch.start":
681 running[run] = true
682 case "check.result":
683 if _, required := a.attrs()[r.Check]; !required || !runName.MatchString(r.Run) ||
684 result != checkPassed && result != checkFailed && result != "error" {
685 return ""
686 }
687 ms := int64(-1)
688 for _, key := range []string{"check_ms", "build_ms"} {
689 if v, ok := r.Data[key].(float64); ok {
690 ms = int64(v)
691 break
692 }
693 }
694 t := treeResult{run: r.Run, check: r.Check, result: result, ms: ms}
695 if drv, _ := r.Data["drv"].(string); storeDrv.MatchString(drv) {
696 t.drv = drv
697 }
698 t.err, t.buildErr = errorText(r.Data["error"]), errorText(r.Data["build_error"])
699 a.results = append(a.results, t)
700 // "-" is no derivation, and the errors, untrusted, go encoded.
701 a.state("result", r.Run, r.Check, result, strconv.FormatInt(ms, 10),
702 cmp.Or(t.drv, "-"), encoded(t.err), encoded(t.buildErr))
703 case "batch.end":
704 // A batch that passed publishes next, and its publish.end says so.
705 delete(running, run)
706 if result == checkFailed {
707 return "the worker's batch for this tree ended with failures"
708 } else if result != checkPassed {
709 return "the worker's batch for this tree ended"
710 }
711 case "publish.end":
712 if result == checkPassed {
713 return "the worker published for this tree"
714 }
715 return "the worker could not publish for this tree"
716 }
717 return ""
718}
719
720// verdict prints the outcome, and returns the exit status.
721func (a *asking) verdict(covered map[string]bool, readErr error, why string) int {
722 took := time.Since(a.began).Round(time.Second).String()
723 if readErr == nil && len(covered) == len(a.nix) {
724 clauses := []string{countOf(len(a.nix), "check") + " passed"}
725 if len(a.nix) == 0 {
726 clauses = []string{"no nix checks required"}
727 }
728 if len(a.commands) > 0 {
729 clauses = append(clauses, fmt.Sprintf("%d run at approval", len(a.commands)))
730 }
731 a.say("✓", colourDone, a.short, append(clauses, took)...)
732 return 0
733 }
734 if readErr != nil {
735 fmt.Fprintf(a.stderr, "valley: %s\n", oneLine(readErr.Error()))
736 why = strings.TrimPrefix(why+" · evidence unreadable", " · ")
737 }
738 for _, c := range a.nix {
739 if !covered[c.name] {
740 a.say("◇", colourWaiting, c.name, "no evidence on origin")
741 }
742 }
743 a.say("◇", colourWaiting, a.short, "not established", why,
744 fmt.Sprintf("%d of %d with evidence", len(covered), len(a.nix)), took)
745 report(a.stdout, a.results, a.attrs())
746 return 1
747}
748
749// attrs is each required nix check's flake attribute, by check.
750func (a *asking) attrs() map[string]string {
751 attrs := map[string]string{}
752 for _, c := range a.nix {
753 attrs[c.name] = c.attribute
754 }
755 return attrs
756}
757
758// report prints the check.results the worker wrote for HEAD's tree while
759// the command waited, which any batch for the tree may have written. For
760// each failed check it prints the error its result records, and the nix
761// log command that reads the build log of the derivation it names from
762// the worker's nix store, or, with neither, the command that builds the
763// check here. With any failed check it points at the worker's output:
764// nix holds no log for a check whose dependency failed to build, and the
765// worker's output names that dependency.
766func report(w io.Writer, results []treeResult, attrs map[string]string) {
767 if len(results) > 0 {
768 fmt.Fprintln(w, " the worker's recent records for this tree, not this request's result:")
769 }
770 failed := map[string]treeResult{}
771 var order []string
772 for _, r := range results {
773 took := ""
774 if r.ms >= 0 {
775 took = " · " + duration(r.ms)
776 }
777 fmt.Fprintf(w, " %s %s%s\n", oneLine(r.check), oneLine(r.result), took)
778 if r.result != checkPassed {
779 if _, seen := failed[r.check]; !seen {
780 order = append(order, r.check)
781 }
782 failed[r.check] = r
783 }
784 }
785 sort.Strings(order)
786 for _, name := range order {
787 r := failed[name]
788 line := " " + oneLine(name) + " · " + oneLine(r.result)
789 if r.err != "" {
790 line += " · the worker's error, untrusted: " + oneLine(r.err)
791 }
792 if r.buildErr != "" {
793 line += " · the worker's build error, untrusted: " + oneLine(r.buildErr)
794 }
795 fmt.Fprintln(w, line)
796 switch attr := attrs[name]; {
797 case r.drv != "":
798 // A store name may hold ? and =, which a shell expands;
799 // storeDrv admits no quote, so single quotes keep it whole.
800 drv := r.drv
801 if strings.ContainsAny(drv, "?=") {
802 drv = "'" + drv + "'"
803 }
804 fmt.Fprintf(w, " run: nix log %s\n", drv)
805 case r.err == "" && attr != "":
806 fmt.Fprintf(w, " run: nix build --no-link -L .#checks.%s.%s\n", buildSystem(), attr)
807 }
808 }
809 if len(order) > 0 {
810 fmt.Fprintln(w, " see: valley telemetry read --source worker --logs · when nix log has none")
811 }
812}
813
814// errorText is a record's error, bounded by errorRunes, or "".
815func errorText(v any) string {
816 e, _ := v.(string)
817 if runes := []rune(e); len(runes) > errorRunes {
818 e = string(runes[:errorRunes]) + "…"
819 }
820 return e
821}
822
823// encoded is untrusted text as one state value, "-" when empty; decoded
824// reads it back.
825func encoded(s string) string {
826 return cmp.Or(base64.RawURLEncoding.EncodeToString([]byte(s)), "-")
827}
828
829func decoded(v string) string {
830 if b, err := base64.RawURLEncoding.DecodeString(v); v != "-" && err == nil {
831 return string(b)
832 }
833 return ""
834}
835
836// oneLine is untrusted text made safe to show on one line.
837func oneLine(s string) string {
838 return strings.NewReplacer("\n", `\n`, "\t", `\t`).Replace(telemetry.Sanitize(s))
839}
840
841// buildSystem is the flake system attest builds a check for here
842// (attest/check.go).
843func buildSystem() string {
844 arch := map[string]string{"amd64": "x86_64", "arm64": "aarch64", "386": "i686"}[runtime.GOARCH]
845 if arch == "" {
846 arch = runtime.GOARCH
847 }
848 return arch + "-" + runtime.GOOS
849}
850
851// prepare reads HEAD, fetches main from origin, and derives the checks
852// HEAD requires under the policy at that tip.
853func (a *asking) prepare() error {
854 g := a.g
855 head, err := commitOf(g, "HEAD")
856 if err != nil {
857 return err
858 }
859 a.head = head
860 if a.short, err = g.output(true, "rev-parse", "--short", head); err != nil {
861 return failure("could not read HEAD")
862 }
863 if changed, err := g.output(true, "status", "--porcelain"); err == nil && changed != "" {
864 fmt.Fprintln(a.stderr, "valley: the working tree has uncommitted changes; these are HEAD's checks, not the working tree's")
865 }
866 // The worker derives under main as origin holds it now; a local copy
867 // may be older, with another policy or another merge base.
868 if _, err := g.output(false, "fetch", "--quiet", "origin", "+refs/heads/main:refs/remotes/origin/main"); err != nil {
869 return failure("could not fetch main from origin; nothing derived")
870 }
871 tip, ok, err := g.ref("refs/remotes/origin/main")
872 if err != nil || !ok {
873 return failure("could not read origin/main; nothing derived")
874 }
875 base, err := g.output(true, "merge-base", tip, head)
876 if err != nil || !isObjectID(base) {
877 return failure("HEAD shares no history with main on origin; nothing derived")
878 }
879 instance, layer, done, err := policyLayers(g, tip)
880 defer done()
881 if err != nil {
882 return failure(err.Error() + "; nothing derived")
883 }
884 doc, err := derivedChecks(g, "", instance, layer, base, head)
885 if err != nil {
886 return err
887 }
888 a.required = len(doc.Required)
889 for _, q := range doc.Required {
890 if q.Runner == "nix" {
891 a.nix = append(a.nix, nixCheck{q.Name, q.Attribute})
892 } else {
893 a.commands = append(a.commands, q.Name)
894 }
895 }
896 a.project = project(g)
897 if a.stream == nil {
898 if dest, err := telemetryRemote(g, ""); err == nil {
899 a.stream = sshStream{dest}
900 } else {
901 a.stream = brokenStream{err}
902 }
903 }
904 return nil
905}
906
907// say prints a line: the glyph in its colour, the subject in bold, and the
908// clauses.
909func (a *asking) say(glyph, colour, subject string, clauses ...string) {
910 var kept []string
911 for _, c := range clauses {
912 if c != "" {
913 kept = append(kept, c)
914 }
915 }
916 fmt.Fprintln(a.stdout, a.t.tint(colour, glyph)+" "+a.t.strong(subject)+" "+strings.Join(kept, " · "))
917}
918
919func (a *asking) fail(err error) int {
920 fmt.Fprintf(a.stderr, "valley: %s\n", oneLine(err.Error()))
921 return 1
922}
923
924// workerRecord is one record of the worker's telemetry stream.
925type workerRecord struct {
926 Seq int64 `json:"seq"`
927 Type string `json:"type"`
928 Run string `json:"run"`
929 Project string `json:"project"`
930 Tree string `json:"tree"`
931 Check string `json:"check"`
932 Data map[string]any `json:"data"`
933}
934
935// workerStream reads the worker's telemetry.
936type workerStream interface {
937 // end is a cursor at the stream's newest record.
938 end(ctx context.Context) (string, error)
939 // follow hands records each record stored after cursor, for up to
940 // seconds, and returns the cursor it ended at.
941 follow(ctx context.Context, cursor string, seconds int, records chan<- workerRecord) (string, error)
942}
943
944// brokenStream is a stream that cannot be reached, and why.
945type brokenStream struct{ err error }
946
947func (b brokenStream) end(context.Context) (string, error) { return "", b.err }
948func (b brokenStream) follow(context.Context, string, int, chan<- workerRecord) (string, error) {
949 return "", b.err
950}
951
952// sshStream reads the worker source of a host over ssh, as valley
953// telemetry does.
954type sshStream struct{ dest sshDest }
955
956func (s sshStream) end(ctx context.Context) (string, error) {
957 cursor, err := s.answer(ctx, telemetry.Request{V: 1, Op: telemetry.OpRead, Source: workerSource, Limit: 1}, time.Minute, nil)
958 if c, perr := telemetry.ParseCursor(cursor); err == nil && (perr != nil || c[workerSource] == (telemetry.Position{})) {
959 err = fmt.Errorf("%s holds no stream for its %s source", s.dest.host, workerSource)
960 }
961 return cursor, err
962}
963
964func (s sshStream) follow(ctx context.Context, cursor string, seconds int, records chan<- workerRecord) (string, error) {
965 req := telemetry.Request{V: 1, Op: telemetry.OpFollow, Source: workerSource, Cursor: cursor, Seconds: min(seconds, telemetry.MaxFollowSeconds)}
966 return s.answer(ctx, req, time.Duration(req.Seconds+60)*time.Second, func(r workerRecord) {
967 select {
968 case records <- r:
969 case <-ctx.Done():
970 }
971 })
972}
973
974// answer runs one telemetry request on the host, hands each record of
975// the worker's stream it answers with to onRecord, and returns the cursor
976// it ended at. A refusal, a line that is not JSON,
977// a gap, a source that could not be read, or an answer that never ends is
978// an error.
979func (s sshStream) answer(ctx context.Context, req telemetry.Request, timeout time.Duration, onRecord func(workerRecord)) (string, error) {
980 ctx, cancel := context.WithTimeout(ctx, timeout)
981 defer cancel()
982 cmd := sshCommand(ctx, s.dest, req.Command())
983 out, err := cmd.StdoutPipe()
984 if err != nil {
985 return "", err
986 }
987 var sshErr bytes.Buffer
988 cmd.Stderr = &sshErr
989 processStarted()
990 if err := cmd.Start(); err != nil {
991 return "", fmt.Errorf("could not run ssh: %v", err)
992 }
993 cursor, ended, why := "", false, ""
994 sc := bufio.NewScanner(out)
995 sc.Buffer(make([]byte, 64<<10), telemetry.MaxResponseBytes)
996 for why == "" && sc.Scan() {
997 var m struct {
998 Kind, Error, What, Reason, Cursor, Stream string
999 workerRecord
1000 }
1001 if json.Unmarshal(sc.Bytes(), &m) != nil {
1002 why = "an answer line is not JSON"
1003 break
1004 }
1005 switch {
1006 case m.Kind == "error":
1007 why = "the host refused: " + telemetry.Sanitize(m.Error)
1008 case m.Kind == "unavailable" && m.What != "journal":
1009 why = fmt.Sprintf("the host could not read %s: %s", telemetry.Sanitize(m.What), telemetry.Sanitize(m.Error))
1010 case m.Kind == "gap":
1011 why = fmt.Sprintf("the worker's stream lost records since the cursor (%s)", telemetry.Sanitize(m.Reason))
1012 case m.Kind == "record" && m.Stream == workerSource && onRecord != nil:
1013 onRecord(m.workerRecord)
1014 case m.Kind == "end":
1015 cursor, ended = m.Cursor, true
1016 }
1017 }
1018 if why != "" {
1019 cancel()
1020 }
1021 waitErr := cmd.Wait()
1022 switch {
1023 case why != "":
1024 return "", errors.New(why)
1025 case !ended:
1026 why = strings.TrimSpace(telemetry.Sanitize(sshErr.String()))
1027 if why == "" && waitErr != nil {
1028 why = waitErr.Error()
1029 }
1030 return "", fmt.Errorf("the telemetry answer from %s did not end: %s", s.dest.host, why)
1031 }
1032 return cursor, nil
1033}