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