gunk-dev/the-valley

checkbuild.go

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