gunk-dev/the-valley

worker.go

sourceb39557ff3f00main's published tip history
47.3 KiB
1package main
2
3// work is one pass of a check worker. It builds the nix checks that ready
4// changes require before anyone approves them, and publishes the evidence
5// on origin, where approve (bin/valley) reuses it instead of building it,
6// and where the integrator finds it for a request approve filed without it.
7// A timer starts a pass, and so does a wake mark. A pass keeps nothing
8// between passes but its record of failures.
9//
10// A pass reads each project named with --repo, and works out what each
11// of the project's ready changes needs:
12//
13// 1. It lists the ready changes whose active version has not landed, as
14// valley pending does (pending.go), and pins each one's active head.
15// 2. It derives the checks the head requires, as valley-go checks does
16// (checks.go), over the head's merge base with main. Both policy
17// layers are read at main's tip on origin, as approve reads them,
18// never from the change.
19// 3. It asks coverage (coverage.go) which of the head's nix checks origin
20// already holds evidence for. Command checks are left to approve.
21// 4. The rest is one batch: attest run --rev <head> under the worker's
22// key, which stores one attestation ref, and a push of that ref alone.
23// Given --slots, the batch builds that many checks at once; without
24// it, attest's own default decides.
25//
26// That read of every project is a scan. A pass is one loop, the
27// scheduler, which runs scans and batches until there is nothing left to
28// do. The loop alone starts batches, publishes, writes the failure record
29// and the telemetry, and claims wake marks. Each batch is one attest run,
30// which a goroutine waits for. When attest ends, the goroutine hands the
31// loop what the batch did, and changes nothing itself.
32//
33// Up to --batches batches run at once; without it, one. The loop starts
34// the batches a scan found in the order their versions became ready.
35// Change records carry no time, so that order is the order in which this
36// pass first saw each version ready. Versions first seen in the same scan
37// go by project name, then by change ID. A pass started by a timer or a
38// mark sees all the versions ready then in its first scan.
39//
40// One batch at a time builds a tree's evidence. A batch's destination is
41// the ref it stores and pushes: the project, the tree's digest and this
42// worker's key hash. A destination is held from the moment its batch
43// starts until its push has been tried, and no second batch for it starts
44// meanwhile. attest stores its ref with a plain update-ref, so two
45// batches for one ref must never run at once. Two changes whose heads
46// hold the same tree, or two versions of a change with the same tree,
47// share one batch. Right before it starts a batch, the loop reads the
48// head's evidence on origin and the refs stored here again, as a scan
49// does. Evidence that arrived since the scan is not built again.
50//
51// The loop scans again when a batch ends, when a wake mark arrives, and
52// every --interval while batches run. It drops a job that has not
53// started when a later scan does not find it: its version was superseded,
54// landed, or has the evidence it lacked. A batch that runs goes on to its
55// end, and its evidence is published: it is about the head's tree, so it
56// stays true if the change moves on meanwhile. The pass ends when nothing
57// runs and a scan finds nothing to start.
58//
59// When a batch ends, its slot takes the next job from the last scan's
60// queue at once, and the scan comes after. So a version superseded since
61// that scan can build once. That is accepted: its evidence is true of its
62// tree, and a free slot does not wait for a read of every project.
63//
64// A scan forgets each version it did not find ready that no batch builds:
65// when the pass first saw it, and the notes said about it. A pass lives as
66// long as work keeps arriving, and holds no more than the versions it
67// still meets.
68//
69// The attestation namespace admits creations only, so the worker never
70// builds what it could not publish. When origin already holds this
71// worker's ref for a tree and the ref lacks a required check, the pass
72// reports it and builds nothing. approve --build-here builds the rest
73// under the operator's key (bd-7b7d58f). When the worker's ref is stored
74// here but not on origin, an earlier batch built it and its push was
75// lost, so the pass pushes that same ref again rather than building it
76// again.
77//
78// A batch that fails is not run again at once, and neither is a push that
79// fails. The pass records each failure in failures.json in the state
80// directory, under its project, as soon as it happens: a batch by the
81// tree and the checks it runs, and a push by the object it publishes. A
82// failed batch waits firstBuildWait before it runs again, and a failed
83// push waits firstPushWait. Each wait doubles with every failure in a
84// row, up to longestWait. A wait runs from when the attempt ended, so a
85// long build does not use up its own wait. A scan in a pass that is still
86// busy starts a batch whose wait is over. A new version is a new batch,
87// and runs at once. VALLEY_NOW, when set, is the time the pass reads as
88// now (main.go's clock). Deleting the record lets everything run again at
89// once.
90//
91// A scan forgets the failures it did not meet in a project, but only for
92// a project it read whole: every ready change's checks derived and its
93// evidence read. It never forgets the failure key of a batch still
94// running. A scan over other projects, or one that could not read this
95// one, leaves this one's record as it is.
96//
97// Passes that share a state directory take turns: each holds the lock
98// file there while it runs, and a pass that finds it held waits for it.
99// Every attest is handed the lock too, so it stays held while a batch
100// runs even when the pass that started the batch is killed. A stop of
101// the unit stops the pass and every attest it started.
102//
103// A read of origin that fails stops the pass, because a read that did not
104// happen must not read as no changes or no evidence. The loop starts
105// nothing more, lets the running batches end, publishes and records what
106// they did, and then fails. Anything else that goes wrong with one change
107// or one batch is reported, and the pass goes on with the rest. The pass
108// exits 1 when anything went wrong.
109//
110// Given --wake, a pass claims that wake directory's due mark before it
111// reads anything, and claims again each mark made while it runs, before
112// the scan that mark starts (wake.go). It acknowledges the claim when it
113// ends having handled what it read. A pass has handled it when every scan
114// read every project whole and everything that went wrong was a failed
115// batch or push whose wait it recorded: those are retried when their
116// wait is over, and a new mark for the same refs would only find them
117// still waiting. Anything else that went wrong (a policy that did not
118// read, checks that did not derive, a read that stopped the pass, a
119// record that was not written) leaves the claim unacknowledged. The
120// worker's own pushes mark due, so a pass that publishes scans once more,
121// finds nothing new, and ends. A pass that could not claim due reads and
122// builds all the same, and then exits claimFailedStatus instead of 0 or
123// 1.
124//
125// Given --telemetry, or VALLEY_TELEMETRY_DIR in its environment, which is
126// how the host module names it, a pass says what it is doing as it does
127// it, and keeps its recent attempts, its running batches and the failures
128// waiting out their backoff with what each was about
129// (workertelemetry.go). It hands attest the same stream for each batch's
130// progress.
131//
132// Given --keep-outputs, a pass keeps the outputs of the checks it builds
133// alive against nix's garbage collection, so a later batch whose checks
134// have the same derivations finds them built. It hands attest
135// --gc-roots with the directory roots in its state directory, where
136// attest makes one indirect root per output, named by the output's store
137// path basename, and makes it afresh whenever a batch uses the output.
138// Before its batches, the pass removes each root there that no batch has
139// used for longer than the age --keep-outputs gives (pruneRoots). It
140// removes only the symlink; nix's own garbage collection frees the output
141// later. Without --keep-outputs, attest roots nothing and the pass prunes
142// nothing.
143
144import (
145 "cmp"
146 "context"
147 "encoding/json"
148 "errors"
149 "fmt"
150 "io"
151 "math"
152 "os"
153 "os/exec"
154 "path/filepath"
155 "sort"
156 "strconv"
157 "strings"
158 "sync"
159 "syscall"
160 "time"
161
162 "the-valley/change"
163 "the-valley/composed"
164 "the-valley/telemetry"
165)
166
167const workUsage = "usage: valley-go work --repo <name>... --key <file> [--name <name>] [--state <dir>] [--wake <dir>] [--telemetry <dir>] [--slots <n>] [--batches <n>] [--interval <span>] [--keep-outputs <age>]"
168
169// projectLayer is the project's own policy layer, in main's tree.
170const projectLayer = "policy/project"
171
172// The waits after a failure before the same thing is tried again: the
173// first after a failed batch, the first after a failed push, and the
174// longest either grows to by doubling.
175const (
176 firstBuildWait = 15 * time.Minute
177 firstPushWait = time.Minute
178 longestWait = 24 * time.Hour
179)
180
181// defaultInterval is how often a pass with batches running scans again
182// when --interval is not given: the host module's own default.
183const defaultInterval = time.Minute
184
185// markPoll is how often a pass with batches running looks for a new wake
186// mark.
187const markPoll = time.Second
188
189// worker is one pass: the signer it attests as, the lock it holds, what it
190// says, what it has found going wrong, and the scheduler's state. Only the
191// loop reads or changes any of it once the first batch starts.
192type worker struct {
193 key, name string
194 slots int // how many checks a batch builds at once, or 0 for attest's default
195 batches int // how many batches run at once
196 interval time.Duration // how often a pass with batches running scans again
197 roots string // the directory attest roots the outputs it builds in, or "" to root nothing
198 keyhash string // the key hash an attestation ref of this signer ends in
199 lock *os.File // the state directory's lock, held for the pass
200 wake *wake // the wake directory's claim, or nil without --wake
201 tel *workerTelemetry
202 failures *failureRecord
203 stdout io.Writer
204 stderr io.Writer
205 out, errs io.Writer // the files attest writes to: the pass's own stdout and stderr
206 troubles int // things that went wrong that did not stop the pass
207 waits int // of the troubles, the failures whose wait was recorded
208
209 scans int // the scans so far
210 seen map[string]int // the scan that first saw each version ready, by job.version
211 ready map[string]bool // the versions the scan under way has found ready, by job.version
212 running map[string]*batch // the batches running, by job.dest
213 queue []*job // what the last scan found to build and has not started, in order
214 said map[string]map[string]bool // the notes said about each version or project since the pass last acted on it
215 fresh map[string]map[string]bool // the failure keys recorded since the scan began, by project
216 done chan completion // how a batch's goroutine hands the loop what the batch did
217
218 // How the loop reads a project, reassesses a job right before its
219 // batch starts, and starts a batch's attest run: project, assess and
220 // attest, unless a test gives its own.
221 read func(g git, name string) ([]*job, error)
222 recheck func(j *job) (bool, error)
223 launch func(b *batch)
224}
225
226// job is one ready version as a scan read it: its head, the nix checks the
227// head requires and the ones origin holds no evidence for, and the batch
228// that would build them.
229type job struct {
230 r listed
231 c jsonChange
232 v jsonVersion
233 asked []nixCheck // every nix check the head requires
234 missing []nixCheck // the ones origin holds no evidence for
235 digest string // the head's tree digest
236 ref string // this worker's attestation ref for the tree
237 key string // the batch's key in the failure record
238 seen int // the scan that first saw the version ready
239}
240
241// version names the job's change version, project by project.
242func (j *job) version() string { return versionName(j.r.name, j.c.ChangeID, j.v.N) }
243
244// versionName names a change version, project by project.
245func versionName(project, change string, n int) string {
246 return project + " " + change + " " + strconv.Itoa(n)
247}
248
249// dest is the batch's destination: the project and the ref it stores.
250func (j *job) dest() string { return j.r.name + " " + j.ref }
251
252func (j *job) names() []string {
253 var names []string
254 for _, q := range j.missing {
255 names = append(names, q.name)
256 }
257 return names
258}
259
260// line opens every line said about the job's version.
261func (j *job) line() string {
262 return fmt.Sprintf("%s: %s v%d at %s", j.r.name, j.c.Handle, j.v.N, j.v.Head[:min(7, len(j.v.Head))])
263}
264
265func (j *job) identity() identity {
266 return identity{project: j.r.name, change: j.c.ChangeID, cv: j.v.N, head: j.v.Head, tree: j.digest}
267}
268
269// jobBefore orders jobs: by the scan that first saw each version ready, then
270// by project name, then by change ID.
271func jobBefore(a, b *job) bool {
272 if a.seen != b.seen {
273 return a.seen < b.seen
274 }
275 if a.r.name != b.r.name {
276 return a.r.name < b.r.name
277 }
278 return a.c.ChangeID < b.c.ChangeID
279}
280
281// batch is a job whose attest run has started.
282type batch struct {
283 job *job
284 run string // the attest run's ID
285 mark int64 // the newest record in the telemetry stream when it started
286 attempt *attempt
287}
288
289// completion is what a batch did, as its goroutine hands it to the loop:
290// how attest ended and when, the object it stored at the job's ref, and
291// the checks it recorded as not passing. It is not changed once sent.
292type completion struct {
293 b *batch
294 err error
295 ended time.Time
296 stored string // "" when attest stored nothing there
297 failed []string
298}
299
300func runWork(g git, args []string, stdout, stderr io.Writer) (err error) {
301 var repos []string
302 var key, name, state, wakeDir, telemetryDir string
303 slots, batches := 0, 1
304 interval := defaultInterval
305 var keep time.Duration
306 for i := 0; i < len(args); i++ {
307 opt, value, inline := strings.Cut(args[i], "=")
308 switch opt {
309 case "--repo", "--key", "--name", "--state", "--wake", "--telemetry", "--slots", "--batches", "--interval", "--keep-outputs":
310 default:
311 return failure(workUsage)
312 }
313 if !inline {
314 if i+1 == len(args) {
315 return failure(workUsage)
316 }
317 i++
318 value = args[i]
319 }
320 switch opt {
321 case "--repo":
322 if !change.ValidPrincipal(value) {
323 return failure(fmt.Sprintf("--repo %s: not a project name", value))
324 }
325 repos = append(repos, value)
326 case "--key":
327 key = value
328 case "--name":
329 name = value
330 case "--state":
331 state = value
332 case "--wake":
333 wakeDir = value
334 case "--telemetry":
335 telemetryDir = value
336 case "--slots", "--batches":
337 n, err := strconv.Atoi(value)
338 if err != nil || n < 1 {
339 return failure(fmt.Sprintf("%s %s: not a whole number of at least 1", opt, value))
340 }
341 if opt == "--slots" {
342 slots = n
343 } else {
344 batches = n
345 }
346 case "--interval":
347 d, err := timeSpan(value)
348 if err != nil {
349 return failure(fmt.Sprintf("--interval: %v; give a systemd time span, such as 1m, 15s or 5min", err))
350 }
351 // A pass reads its projects no more often than it looks for
352 // a mark, so a span of 0, which a timer takes, does not spin.
353 interval = max(d, markPoll)
354 case "--keep-outputs":
355 d, err := time.ParseDuration(value)
356 if err != nil || d <= 0 {
357 return failure(fmt.Sprintf("--keep-outputs %s: not a positive duration, such as 168h", value))
358 }
359 keep = d
360 }
361 }
362 if len(repos) == 0 || key == "" {
363 return failure(workUsage)
364 }
365 if telemetryDir == "" {
366 telemetryDir = os.Getenv("VALLEY_TELEMETRY_DIR")
367 }
368 // The pass's own lines go out whole, one Write each; every attest
369 // writes to the files beneath.
370 files, errFiles := stdout, stderr
371 stdout, stderr = &lineSink{to: stdout}, &lineSink{to: stderr}
372 // From here on, a pass given --wake that ends without having claimed
373 // due exits claimFailedStatus, however it ends, so whatever started
374 // it for that due holds off before it starts another.
375 var claim *wake
376 if wakeDir != "" {
377 defer func() {
378 if claim != nil && claim.err == nil {
379 return
380 }
381 why := "due was not claimed"
382 if claim != nil {
383 why = claim.err.Error()
384 }
385 if err != nil {
386 fmt.Fprintf(stderr, "valley: %s\n", err)
387 }
388 err = claimFailure{fmt.Sprintf("%s, so the pass exits %d", why, claimFailedStatus)}
389 }()
390 }
391 // attest runs in the repository a project is read through, which may
392 // be a cache clone, so a key named relative to here is made absolute.
393 abs, err := filepath.Abs(key)
394 if err != nil {
395 return failure(fmt.Sprintf("--key %s: %v", key, err))
396 }
397 key = abs
398 if state == "" {
399 if state, err = stateDirectory(); err != nil {
400 return failure("no state directory: name one with --state")
401 }
402 }
403 if err := os.MkdirAll(state, 0o700); err != nil {
404 return failure(fmt.Sprintf("could not make the state directory %s", state))
405 }
406
407 lock, err := lockState(filepath.Join(state, "lock"), stderr)
408 if err != nil {
409 return failure(fmt.Sprintf("could not take the lock in %s: %v", state, err))
410 }
411 defer lock.Close() // close drops the flock; every attest handed it has ended by then
412
413 // The claim comes before any read, so a move marked after it is
414 // either read by this pass or left marked for the next.
415 if wakeDir != "" {
416 claim = claimWake(wakeDir, stderr)
417 defer claim.close()
418 if claim.err != nil {
419 fmt.Fprintf(stderr, "valley: %v; the pass reads everything all the same\n", claim.err)
420 }
421 }
422
423 // The signer is read before anything else is done, so a pass that
424 // could only end in "no key" says so before it reads anything.
425 keyArgs := []string{"key", "--key", key}
426 if name != "" {
427 keyArgs = append(keyArgs, "--name", name)
428 }
429 out, err := attestTool(g, keyArgs...)
430 fields := strings.SplitN(strings.TrimSpace(out), "+", 3)
431 if err != nil || len(fields) != 3 || len(fields[1]) != 8 {
432 return failure(fmt.Sprintf("could not read the signing key at %s: %s", key, refusalOf(out)))
433 }
434
435 w := &worker{key: key, name: name, slots: slots, batches: batches, interval: interval, keyhash: fields[1],
436 lock: lock, wake: claim, stdout: stdout, stderr: stderr, out: files, errs: errFiles,
437 seen: map[string]int{}, running: map[string]*batch{}, said: map[string]map[string]bool{}}
438 w.read, w.launch = w.project, w.attest
439 w.recheck = func(j *job) (bool, error) { return w.assess(j, nil) }
440 w.tel = openWorkerTelemetry(telemetryDir)
441 // The loop returns only once no batch runs, so nothing changes the
442 // state the telemetry finishes with.
443 defer func() { w.tel.finish(w.failures, w.troubles, err) }()
444 w.failures = readFailures(filepath.Join(state, "failures.json"), stderr)
445 if keep > 0 {
446 // attest runs in each project's repository, so the roots are
447 // named absolutely, where this pass prunes them.
448 if w.roots, err = filepath.Abs(filepath.Join(state, "roots")); err != nil {
449 return failure(fmt.Sprintf("--state %s: %v", state, err))
450 }
451 if err := pruneRoots(w.roots, keep, clock()); err != nil {
452 fmt.Fprintf(stderr, "valley: could not prune the roots in %s: %v\n", w.roots, err)
453 w.troubles++
454 }
455 }
456 return w.pass(g, repos)
457}
458
459// pass runs the loop, writes the failure record, and acknowledges the
460// wake claim when the pass handled what it read. It returns the error of
461// a read of origin that failed, and otherwise says how many things went
462// wrong.
463func (w *worker) pass(g git, repos []string) error {
464 stop := w.loop(g, repos)
465 w.save()
466 if stop != nil {
467 return stop
468 }
469 if w.wake != nil && w.troubles == w.waits {
470 if err := w.wake.ack(); err != nil {
471 fmt.Fprintf(w.stderr, "valley: could not acknowledge %s: %v\n", filepath.Join(w.wake.dir, "claimed"), err)
472 w.troubles++
473 }
474 }
475 if w.troubles > 0 {
476 return failure(fmt.Sprintf("the pass finished, but %s went wrong in it; each is said above", counted(w.troubles, "thing")))
477 }
478 return nil
479}
480
481// spanUnits are the units of a systemd time span in microseconds, in the
482// order systemd tries them (extract_multiplier in its time-util.c): the
483// first a span's text starts with is its unit. A month is 30.44 days and a
484// year 365.25 days, as systemd counts them.
485var spanUnits = []struct {
486 name string
487 usec uint64
488}{
489 {"seconds", 1e6}, {"second", 1e6}, {"sec", 1e6}, {"s", 1e6},
490 {"minutes", 60e6}, {"minute", 60e6}, {"min", 60e6},
491 {"months", 2629800e6}, {"month", 2629800e6}, {"M", 2629800e6},
492 {"msec", 1e3}, {"ms", 1e3}, {"m", 60e6},
493 {"hours", 3600e6}, {"hour", 3600e6}, {"hr", 3600e6}, {"h", 3600e6},
494 {"days", 86400e6}, {"day", 86400e6}, {"d", 86400e6},
495 {"weeks", 604800e6}, {"week", 604800e6}, {"w", 604800e6},
496 {"years", 31557600e6}, {"year", 31557600e6}, {"y", 31557600e6},
497 {"usec", 1}, {"us", 1}, {"\u03bcs", 1}, {"\u00b5s", 1},
498}
499
500// timeSpan reads a time span as systemd reads a timer's (parse_sec in its
501// time-util.c), such as 1m, 15s, 5min, "1h 30min", 1.5h, 2months or
502// infinity. A number with no unit is seconds. Like systemd, it counts
503// whole microseconds, and refuses a span of 2^64-1 microseconds or more.
504// A span longer than a time.Duration holds, about 292 years, reads as the
505// longest one, as infinity does.
506func timeSpan(s string) (time.Duration, error) {
507 const space = " \t\n\r"
508 bad := fmt.Errorf("%q is not a time span", s)
509 long := fmt.Errorf("%q is longer than systemd reads", s)
510 rest := strings.TrimLeft(s, space)
511 if after, ok := strings.CutPrefix(rest, "infinity"); ok {
512 if strings.TrimLeft(after, space) != "" {
513 return 0, bad
514 }
515 return math.MaxInt64, nil
516 }
517 digits := func(s string) string { return s[:len(s)-len(strings.TrimLeft(s, "0123456789"))] }
518 if rest == "" {
519 return 0, bad
520 }
521 var usec uint64
522 for ; rest != ""; rest = strings.TrimLeft(rest, space) {
523 whole := digits(rest)
524 after := rest[len(whole):]
525 fraction := ""
526 if tail, dot := strings.CutPrefix(after, "."); dot {
527 if fraction = digits(tail); fraction == "" {
528 return 0, bad
529 }
530 after = tail[len(fraction):]
531 } else if whole == "" {
532 return 0, bad
533 }
534 // The unit may follow a space. A number followed at once by
535 // anything else, such as 12.34.56, is not a span.
536 unit, mult := strings.TrimLeft(after, space), uint64(1e6)
537 matched := false
538 for _, u := range spanUnits {
539 if strings.HasPrefix(unit, u.name) {
540 unit, mult, matched = unit[len(u.name):], u.usec, true
541 break
542 }
543 }
544 if !matched && unit == after && after != "" {
545 return 0, bad
546 }
547 rest = unit
548 n, err := strconv.ParseInt(cmp.Or(whole, "0"), 10, 64)
549 if err != nil || uint64(n) >= math.MaxUint64/mult {
550 return 0, long
551 }
552 if k := uint64(n) * mult; k < math.MaxUint64-usec {
553 usec += k
554 } else {
555 return 0, long
556 }
557 for i, m := 0, mult/10; i < len(fraction); i, m = i+1, m/10 {
558 k := uint64(fraction[i]-'0') * m
559 if k >= math.MaxUint64-usec {
560 return 0, long
561 }
562 usec += k
563 }
564 }
565 if usec > math.MaxInt64/uint64(time.Microsecond) {
566 return math.MaxInt64, nil
567 }
568 return time.Duration(usec) * time.Microsecond, nil
569}
570
571// lineSink passes on the pass's own lines, so that no two of its Writes
572// overlap.
573type lineSink struct {
574 mu sync.Mutex
575 to io.Writer
576}
577
578func (s *lineSink) Write(p []byte) (int, error) {
579 s.mu.Lock()
580 defer s.mu.Unlock()
581 return s.to.Write(p)
582}
583
584// stateDirectory is where the worker keeps its lock and its record of
585// failed batches by default: $XDG_STATE_HOME/valley/worker, or
586// ~/.local/state/valley/worker, beside attest's timing log.
587func stateDirectory() (string, error) {
588 state := os.Getenv("XDG_STATE_HOME")
589 if !filepath.IsAbs(state) {
590 home, err := os.UserHomeDir()
591 if err != nil {
592 return "", err
593 }
594 state = filepath.Join(home, ".local", "state")
595 }
596 return filepath.Join(state, "valley", "worker"), nil
597}
598
599// pruneRoots removes each symlink in dir whose modification time is more
600// than keep before now. attest makes a root afresh each time a batch uses
601// its output, so that time is the output's last use. Only symlinks are
602// removed, never what they point to, and a dir that does not exist yet
603// holds nothing to prune.
604func pruneRoots(dir string, keep time.Duration, now time.Time) error {
605 entries, err := os.ReadDir(dir)
606 if errors.Is(err, os.ErrNotExist) {
607 return nil
608 }
609 if err != nil {
610 return err
611 }
612 var errs []error
613 for _, e := range entries {
614 if e.Type()&os.ModeSymlink == 0 {
615 continue
616 }
617 info, err := e.Info()
618 if errors.Is(err, os.ErrNotExist) {
619 continue
620 }
621 if err != nil {
622 errs = append(errs, err)
623 continue
624 }
625 if now.Sub(info.ModTime()) > keep {
626 if err := os.Remove(filepath.Join(dir, e.Name())); err != nil && !errors.Is(err, os.ErrNotExist) {
627 errs = append(errs, err)
628 }
629 }
630 }
631 return errors.Join(errs...)
632}
633
634// lockState takes the lock file at path, waiting for whoever holds it, and
635// returns the open file, whose closing releases it. The lock is flock's,
636// as self-update's is. It belongs to the open file, so it is released when
637// every process holding that file has closed it or ended, however each
638// ends.
639func lockState(path string, stderr io.Writer) (*os.File, error) {
640 f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0o600)
641 if err != nil {
642 return nil, err
643 }
644 err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
645 if errors.Is(err, syscall.EWOULDBLOCK) {
646 fmt.Fprintf(stderr, "valley: another pass holds %s; waiting for it to end\n", path)
647 err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX)
648 }
649 if err != nil {
650 f.Close()
651 return nil, err
652 }
653 return f, nil
654}
655
656// loop is the pass's scheduler. It scans, starts what the scan found, and
657// handles each batch as it ends, until nothing runs and a scan finds
658// nothing to start. It returns the error of a read of origin that failed,
659// once every batch running then has ended and been handled. It never
660// returns while a batch runs.
661func (w *worker) loop(g git, repos []string) error {
662 w.done = make(chan completion)
663 tick := time.NewTicker(w.interval)
664 defer tick.Stop()
665 poll := time.NewTicker(markPoll)
666 defer poll.Stop()
667 var stop error
668 scan := true
669 for {
670 if scan && stop == nil {
671 scan = false
672 // A mark made since the last claim is claimed before the
673 // scan reads anything, as the first is.
674 w.wake.again(w.stderr)
675 if stop = w.scan(g, repos); stop == nil {
676 stop = w.admit()
677 }
678 w.tel.settle()
679 }
680 if len(w.running) == 0 {
681 if stop != nil || !w.wake.marked() {
682 return stop
683 }
684 scan = true
685 continue
686 }
687 select {
688 case c := <-w.done:
689 w.complete(c)
690 // A freed slot takes the next job from the last scan's
691 // queue at once, before the scan that follows finds what
692 // changed meanwhile. A version superseded since that scan
693 // can build once this way; its evidence is about its tree,
694 // so it is still true.
695 if err := w.reap(); stop == nil {
696 if stop = err; stop == nil {
697 stop = w.admit()
698 }
699 }
700 scan = true
701 case <-tick.C:
702 scan = true
703 case <-poll.C:
704 scan = scan || w.wake.marked()
705 }
706 }
707}
708
709// scan reads every project, and makes the queue what it found to build,
710// in order. It returns an error only when a read of origin failed.
711func (w *worker) scan(g git, repos []string) error {
712 w.scans++
713 w.fresh = map[string]map[string]bool{}
714 w.ready = map[string]bool{}
715 var found []*job
716 for _, name := range repos {
717 jobs, err := w.read(g, name)
718 if err != nil {
719 w.queue = nil
720 return err
721 }
722 found = append(found, jobs...)
723 }
724 w.queue = w.order(found)
725 w.forget(repos)
726 return nil
727}
728
729// forget drops what the pass keeps about each version that the scan just
730// ended did not find ready and no batch builds: when it was first seen,
731// and the notes said about it. A pass lives as long as work keeps
732// arriving, and this keeps what it holds to the versions it still meets.
733// A version found ready again later is seen anew.
734func (w *worker) forget(repos []string) {
735 keep := map[string]bool{}
736 for v := range w.ready {
737 keep[v] = true
738 }
739 for _, b := range w.running {
740 keep[b.job.version()] = true
741 }
742 for v := range w.seen {
743 if !keep[v] {
744 delete(w.seen, v)
745 }
746 }
747 for _, name := range repos {
748 keep[name] = true // the notes said about a project as a whole
749 }
750 for about := range w.said {
751 if !keep[about] {
752 delete(w.said, about)
753 }
754 }
755}
756
757// order sorts what a scan found, and keeps the first job for each
758// destination. A later job for the same destination is the same tree
759// under the same signer, which the first job's batch builds.
760func (w *worker) order(found []*job) []*job {
761 sort.SliceStable(found, func(a, b int) bool { return jobBefore(found[a], found[b]) })
762 first := map[string]*job{}
763 var queue []*job
764 for _, j := range found {
765 if f, ok := first[j.dest()]; ok {
766 w.note(j, "the batch for %s v%d builds the same tree", f.c.Handle, f.v.N)
767 continue
768 }
769 first[j.dest()] = j
770 queue = append(queue, j)
771 }
772 return queue
773}
774
775// project reads one project's ready changes, and returns the jobs that
776// need a batch. It returns an error only when a read of origin failed.
777// When it has read the project whole, it forgets the project's failures
778// it did not meet.
779func (w *worker) project(g git, name string) ([]*job, error) {
780 list, _, err := sources(g, listing{repo: name}, w.stderr)
781 if err != nil {
782 return nil, failure(fmt.Sprintf("%s: %v; the pass stops here", name, err))
783 }
784 repos := readSources(list, newVerifier())
785 r := repos[0]
786 if r.err != nil {
787 return nil, failure(fmt.Sprintf("%s: %v; the pass stops here", name, r.err))
788 }
789 view := r.pendingView(handles(repos))
790 for _, c := range view.Changes {
791 w.ready[versionName(name, c.ChangeID, c.Versions[c.Active-1].N)] = true
792 }
793 met := map[string]bool{} // the failures this scan met, by key
794 if len(view.Changes) == 0 {
795 w.prune(name, met)
796 return nil, nil
797 }
798 if r.snap.tip == "" {
799 if w.noteAs(name, name+": origin has no main to read the policy at, so nothing is built") {
800 w.troubles++
801 }
802 return nil, nil
803 }
804 instance, project, done, err := policyLayers(r.g, r.snap.tip)
805 defer done()
806 if err != nil {
807 if w.noteAs(name, fmt.Sprintf("%s: the policy at main did not read, so nothing is built: %v", name, err)) {
808 w.troubles++
809 }
810 return nil, nil
811 }
812 delete(w.said, name)
813 whole := true
814 var jobs []*job
815 for _, c := range view.Changes {
816 // A scan reads one change after another, which can take a while,
817 // so a batch that ended meanwhile is handled between them.
818 if err := w.reap(); err != nil {
819 return nil, err
820 }
821 j, read, err := w.change(r, instance, project, c, met)
822 if err != nil {
823 return nil, err
824 }
825 whole = whole && read
826 if j != nil {
827 jobs = append(jobs, j)
828 }
829 }
830 if whole {
831 w.prune(name, met)
832 }
833 return jobs, nil
834}
835
836// prune forgets the project's failures that a scan which read the project
837// whole did not meet. It never forgets the key of a batch still running,
838// nor a failure recorded since the scan began, which the scan's reads may
839// have come too early to meet.
840func (w *worker) prune(project string, met map[string]bool) {
841 for _, b := range w.running {
842 if b.job.r.name == project {
843 met[b.job.key] = true
844 }
845 }
846 for key := range w.fresh[project] {
847 met[key] = true
848 }
849 w.failures.keep(project, met)
850}
851
852// failed records a failure, and that it was recorded during this scan.
853func (w *worker) failed(project, key string, at time.Time, first time.Duration) backoff {
854 if w.fresh != nil {
855 if w.fresh[project] == nil {
856 w.fresh[project] = map[string]bool{}
857 }
858 w.fresh[project][key] = true
859 }
860 return w.failures.failed(project, key, at, first)
861}
862
863// reap handles every batch that has ended and not been handled, and then
864// starts what the queue holds in the slots they freed. It returns an
865// error only when a read of origin failed.
866func (w *worker) reap() error {
867 ended := false
868 for {
869 select {
870 case c := <-w.done:
871 w.complete(c)
872 ended = true
873 continue
874 default:
875 }
876 break
877 }
878 if !ended {
879 return nil
880 }
881 return w.admit()
882}
883
884// change reads one ready change, and returns its job when it needs a
885// batch. read says whether it read the change through: derived its
886// checks, and read the evidence origin holds for them.
887func (w *worker) change(r listed, instance, project string, c jsonChange, met map[string]bool) (j *job, read bool, err error) {
888 v := c.Versions[c.Active-1]
889 j = &job{r: r, c: c, v: v}
890 first, ok := w.seen[j.version()]
891 if !ok {
892 first = w.scans
893 w.seen[j.version()] = first
894 }
895 j.seen = first
896 w.tel.reading(r.name, c, v, !ok)
897 base, err := r.g.output(true, "merge-base", r.snap.tip, v.Head)
898 if err != nil {
899 if w.note(j, "shares no history with main, so nothing is built") {
900 w.troubles++
901 }
902 return nil, false, nil
903 }
904 doc, err := derivedChecks(r.g, "", instance, project, base, v.Head)
905 if err != nil {
906 if w.note(j, "its checks did not derive, so nothing is built: %v", err) {
907 w.troubles++
908 }
909 return nil, false, nil
910 }
911 for _, q := range doc.Required {
912 if q.Runner == "nix" {
913 j.asked = append(j.asked, nixCheck{q.Name, q.Attribute})
914 }
915 }
916 if len(j.asked) == 0 {
917 w.note(j, "requires no nix check")
918 return nil, true, nil
919 }
920 needed, err := w.assess(j, met)
921 if err != nil || !needed {
922 return nil, err == nil, err
923 }
924 return j, true, nil
925}
926
927// assess reads the evidence origin holds for a job's head, and reports
928// whether the job needs a batch now. It does not when origin covers every
929// check, when a batch for its destination runs, when origin already holds
930// this worker's ref for the tree, when its batch is waiting out a
931// failure, or when a batch stored the ref here and origin lacks it, which
932// it publishes. met, when given, gets the failure keys it meets. It
933// returns an error only when a read of origin failed.
934func (w *worker) assess(j *job, met map[string]bool) (bool, error) {
935 e, err := coverageOf(j.r.g, j.v.Head, j.asked, w.stderr)
936 if err != nil {
937 return false, failure(fmt.Sprintf("%s: %s v%d: %v; the pass stops here", j.r.name, j.c.Handle, j.v.N, err))
938 }
939 j.digest, j.missing = e.digest, nil
940 j.ref = attestationRefs + e.digest + "/" + w.keyhash
941 for _, q := range j.asked {
942 if _, ok := e.covered[q.name]; !ok {
943 j.missing = append(j.missing, q)
944 }
945 }
946 if len(j.missing) == 0 {
947 w.note(j, "origin holds evidence for every nix check it requires")
948 return false, nil
949 }
950 if b, ok := w.running[j.dest()]; ok {
951 if b.job.version() != j.version() {
952 w.note(j, "the batch for %s v%d builds the same tree", b.job.c.Handle, b.job.v.N)
953 }
954 return false, nil
955 }
956 names := strings.Join(j.names(), ", ")
957 if _, ok := e.listed[j.ref]; ok {
958 w.note(j, "origin already holds %s, this worker's evidence for its tree, and it does not cover %s. "+
959 "That namespace admits creations only, so approve --build-here builds the rest (bd-7b7d58f)", j.ref, names)
960 return false, nil
961 }
962 if stored, found, err := j.r.g.ref(j.ref); err == nil && found {
963 w.note(j, "an earlier pass stored %s, and origin does not hold it", j.ref)
964 w.publish(j, stored, met)
965 return false, nil
966 }
967 j.key = "build " + e.digest + " " + strings.Join(j.names(), ",")
968 if met != nil {
969 met[j.key] = true
970 }
971 if f, waiting := w.failures.waiting(j.r.name, j.key, clock()); waiting {
972 w.note(j, "its batch %s failed %s in a row, so it is not built again before %s", names, counted(f.Failures, "time"), f.Retry.Format(time.RFC3339))
973 return false, nil
974 }
975 return true, nil
976}
977
978// admit starts the queue's jobs in order while fewer than w.batches run.
979// It assesses each job again right before it starts it, so evidence that
980// arrived since the scan is not built again. A job whose destination a
981// batch holds, or that finds no slot, stays queued for the next scan to
982// find again. It returns an error only when a read of origin failed.
983func (w *worker) admit() error {
984 var left []*job
985 for i, j := range w.queue {
986 if len(w.running) >= w.batches {
987 left = append(left, w.queue[i:]...)
988 break
989 }
990 if _, held := w.running[j.dest()]; held {
991 left = append(left, j)
992 continue
993 }
994 needed, err := w.recheck(j)
995 if err != nil {
996 w.queue = nil
997 return err
998 }
999 if needed {
1000 w.start(j)
1001 }
1002 }
1003 w.queue = left
1004 return nil
1005}
1006
1007// start runs a job's batch: it holds the job's destination, starts attest
1008// run, and leaves a goroutine to wait for it. The goroutine reads what
1009// attest stored and recorded, and hands it to the loop; it changes
1010// nothing the loop owns.
1011//
1012// attest is handed the lock file as well, and holds it until it ends, and
1013// the wake directory's lock with it. The flock belongs to the open file,
1014// so the lock stays held while attest runs, and while anything it started
1015// that inherited the file runs, even when this pass is killed. A later
1016// pass waits for all of it, and then finds the ref attest stored.
1017func (w *worker) start(j *job) {
1018 b := &batch{job: j, run: telemetry.NewRunID(), mark: w.tel.streamEnd()}
1019 w.say(j, "building %s", strings.Join(j.names(), ", "))
1020 b.attempt = w.tel.begin("build", j.identity(), j.names(), b.run, map[string]any{"attest_run": b.run})
1021 w.running[j.dest()] = b
1022 w.launch(b)
1023}
1024
1025// attest starts a batch's attest run, and a goroutine that waits for it
1026// and hands the loop its completion.
1027func (w *worker) attest(b *batch) {
1028 j := b.job
1029 repo := j.r.g.dir
1030 if repo == "" {
1031 repo = "."
1032 }
1033 args := []string{"run", "--repo", repo, "--rev", j.v.Head, "--key", w.key}
1034 if w.name != "" {
1035 args = append(args, "--name", w.name)
1036 }
1037 if w.slots > 0 {
1038 args = append(args, "--slots", strconv.Itoa(w.slots))
1039 }
1040 if w.roots != "" {
1041 args = append(args, "--gc-roots", w.roots)
1042 }
1043 for _, q := range j.missing {
1044 args = append(args, "--check", q.name+"="+q.attribute)
1045 }
1046 stream := ""
1047 if w.tel != nil {
1048 stream = w.tel.stream()
1049 args = append(args, "--telemetry", stream, "--telemetry-run", b.run, "--project", j.r.name,
1050 "--change", j.c.ChangeID, "--change-version", strconv.Itoa(j.v.N))
1051 }
1052 // attest writes to the pass's own output files, not through a pipe the
1053 // pass reads: an attest that outlives a killed pass must still be able
1054 // to write, and store its ref.
1055 cmd := exec.Command("attest", args...)
1056 cmd.Env = j.r.g.env
1057 cmd.Dir = j.r.g.dir
1058 cmd.Stdout, cmd.Stderr = w.out, w.errs
1059 cmd.ExtraFiles = []*os.File{w.lock}
1060 if w.wake != nil && w.wake.lock != nil {
1061 cmd.ExtraFiles = append(cmd.ExtraFiles, w.wake.lock)
1062 }
1063 if err := cmd.Start(); err != nil {
1064 go func() { w.done <- completion{b: b, err: err, ended: clock()} }()
1065 return
1066 }
1067 g, ref, run, mark := j.r.g, j.ref, b.run, b.mark
1068 go func() {
1069 err := cmd.Wait()
1070 c := completion{b: b, err: err, ended: clock()}
1071 if err != nil {
1072 c.failed = failedChecks(stream, run, mark)
1073 } else if stored, found, rerr := g.ref(ref); rerr == nil && found {
1074 c.stored = stored
1075 }
1076 w.done <- c
1077 }()
1078}
1079
1080// complete handles what one batch did: it records a failure at once, with
1081// its wait measured from when the batch ended, or publishes what the batch
1082// stored. The batch's destination is held until its push has been tried.
1083func (w *worker) complete(c completion) {
1084 b, j := c.b, c.b.job
1085 defer func() {
1086 delete(w.running, j.dest())
1087 w.tel.settle()
1088 }()
1089 if c.err != nil {
1090 f := w.failed(j.r.name, j.key, c.ended, firstBuildWait)
1091 reason := fmt.Sprintf("attest run %s: %v", b.run, c.err)
1092 if len(c.failed) > 0 {
1093 reason += "; " + strings.Join(c.failed, ", ")
1094 }
1095 w.tel.end(b.attempt, c.err, reason, j.key, &f)
1096 w.say(j, "the batch did not pass (%v); it is not built again before %s", c.err, f.Retry.Format(time.RFC3339))
1097 w.troubles++
1098 w.waits++
1099 w.save()
1100 return
1101 }
1102 w.failures.passed(j.r.name, j.key)
1103 w.tel.end(b.attempt, nil, "", j.key, nil)
1104 w.save()
1105 if c.stored == "" {
1106 w.say(j, "attest stored no %s, so nothing is published", j.ref)
1107 w.troubles++
1108 return
1109 }
1110 w.publish(j, c.stored, nil)
1111}
1112
1113// publish pushes a job's attestation ref to origin, and nothing else. The
1114// hook verifies the notes against the tree and the signer whoever pushes
1115// them. A push that fails leaves the ref stored here, and the same object
1116// is not pushed again until its wait is over: by any pass, and for any
1117// change whose tree it is about. met, when given, gets the push's key.
1118func (w *worker) publish(j *job, object string, met map[string]bool) {
1119 key := "push " + object
1120 if met != nil {
1121 met[key] = true
1122 }
1123 if f, waiting := w.failures.waiting(j.r.name, key, clock()); waiting {
1124 w.note(j, "publishing %s failed %s in a row, so it is not pushed again before %s", j.ref, counted(f.Failures, "time"), f.Retry.Format(time.RFC3339))
1125 return
1126 }
1127 a := w.tel.begin("push", j.identity(), nil, "", map[string]any{"ref": j.ref, "object": object})
1128 if _, err := j.r.g.output(false, "push", "--quiet", "origin", object+":"+j.ref); err != nil {
1129 f := w.failed(j.r.name, key, clock(), firstPushWait)
1130 w.tel.end(a, err, fmt.Sprintf("pushing %s to origin: %v", j.ref, err), key, &f)
1131 w.say(j, "could not publish %s; it is not pushed again before %s", j.ref, f.Retry.Format(time.RFC3339))
1132 w.troubles++
1133 w.waits++
1134 w.save()
1135 return
1136 }
1137 w.failures.passed(j.r.name, key)
1138 w.tel.end(a, nil, "", key, nil)
1139 w.say(j, "published %s", j.ref)
1140}
1141
1142// say prints a line about what the pass did with a version. The version's
1143// notes may be said again after it.
1144func (w *worker) say(j *job, format string, args ...any) {
1145 delete(w.said, j.version())
1146 fmt.Fprintf(w.stdout, "%s: %s\n", j.line(), fmt.Sprintf(format, args...))
1147}
1148
1149// note prints a line about how a version stands, unless the pass has said
1150// that line of it since it last did something with it, so a scan that
1151// finds things as they were says nothing new. It reports whether it
1152// printed.
1153func (w *worker) note(j *job, format string, args ...any) bool {
1154 return w.noteAs(j.version(), j.line()+": "+fmt.Sprintf(format, args...))
1155}
1156
1157func (w *worker) noteAs(about, line string) bool {
1158 if w.said[about][line] {
1159 return false
1160 }
1161 if w.said[about] == nil {
1162 w.said[about] = map[string]bool{}
1163 }
1164 w.said[about][line] = true
1165 fmt.Fprintln(w.stdout, line)
1166 return true
1167}
1168
1169// save writes the failure record, and counts a write that fails as
1170// something that went wrong.
1171func (w *worker) save() {
1172 if err := w.failures.save(); err != nil {
1173 fmt.Fprintf(w.stderr, "valley: could not write %s: %v\n", w.failures.path, err)
1174 w.troubles++
1175 }
1176}
1177
1178// policyLayers resolves the two policy layers a project's changes are
1179// derived under, as approve resolves them (bin/valley's
1180// resolve_instance_layer and resolve_project_layer), and returns what
1181// removes them. Both are read at main's tip on origin. The floor is that
1182// tip's own policy/instance when it carries one, and otherwise
1183// policy/instance at the tip of main in the owning valley that
1184// policy/valley names. A tip with no policy/project is derived under the
1185// floor alone.
1186func policyLayers(g git, tip string) (instance, project string, done func(), err error) {
1187 ctx := context.Background()
1188 var ends []func()
1189 done = func() {
1190 for _, end := range ends {
1191 end()
1192 }
1193 }
1194 repo := g.dir
1195 if repo == "" {
1196 repo = "."
1197 }
1198 floor := composed.Floor{Repo: repo, Ref: tip, Dir: instanceLayer}
1199 if !g.succeeds(true, "cat-file", "-e", tip+":"+instanceLayer) {
1200 pointer, err := g.output(true, "cat-file", "blob", tip+":"+valleyPointer)
1201 if err != nil {
1202 return "", "", done, fmt.Errorf("main names no owning valley at %s", valleyPointer)
1203 }
1204 url := pointerURL(pointer)
1205 if url == "" {
1206 return "", "", done, fmt.Errorf("%s on main names no repository", valleyPointer)
1207 }
1208 if err := checkURL(url); err != nil {
1209 return "", "", done, err
1210 }
1211 scratch, err := os.MkdirTemp("", "valley-work-valley-")
1212 if err != nil {
1213 return "", "", done, err
1214 }
1215 ends = append(ends, func() { _ = os.RemoveAll(scratch) })
1216 v := git{env: cacheEnvironment(g.env), stderr: g.stderr, dir: scratch}
1217 if _, err := v.output(true, "init", "--quiet", "--bare"); err != nil {
1218 return "", "", done, errors.New("no scratch repository to fetch the floor into")
1219 }
1220 // The valley's main is read by its exact name, and fetched by the
1221 // object it names: given a ref name the valley lacks, fetch takes
1222 // another ref whose name ends in it, such as
1223 // refs/heads/refs/heads/main.
1224 at, err := remoteRef(v, url, "refs/heads/main")
1225 if err != nil {
1226 return "", "", done, fmt.Errorf("could not fetch the owning valley %s", url)
1227 } else if at == "" {
1228 return "", "", done, fmt.Errorf("the owning valley %s has no refs/heads/main", url)
1229 }
1230 if _, err := v.output(true, "fetch", "--quiet", "--depth", "1", "--no-tags", "--end-of-options", url, at); err != nil {
1231 return "", "", done, fmt.Errorf("could not fetch the owning valley %s", url)
1232 }
1233 floor = composed.Floor{Repo: scratch, Ref: at, Dir: instanceLayer}
1234 }
1235 instance, end, err := floor.Open(ctx, "valley-work-floor")
1236 ends = append(ends, end)
1237 if err != nil {
1238 return "", "", done, err
1239 }
1240 project, _, end, err = composed.Project(ctx, repo, tip, projectLayer, "valley-work-project")
1241 ends = append(ends, end)
1242 return instance, project, done, err
1243}
1244
1245// failureRecord is the worker's record of what failed, project by
1246// project: each batch, keyed "build <tree digest> <check>,<check>", and
1247// each push, keyed "push <object ID>". For each it holds how many times in
1248// a row it failed, and the time before which it is not tried again. It is
1249// kept as JSON at path.
1250type failureRecord struct {
1251 path string
1252 Projects map[string]map[string]backoff `json:"projects"`
1253}
1254
1255type backoff struct {
1256 Failures int `json:"failures"`
1257 Retry time.Time `json:"retry"`
1258}
1259
1260// readFailures reads the record at path. A record that is not there is
1261// empty. One that does not read is said, and started again empty: the
1262// worst it costs is one more try of each thing it held.
1263func readFailures(path string, stderr io.Writer) *failureRecord {
1264 r := &failureRecord{path: path}
1265 data, err := os.ReadFile(path)
1266 if err == nil {
1267 err = json.Unmarshal(data, r)
1268 }
1269 if err != nil && !errors.Is(err, os.ErrNotExist) {
1270 fmt.Fprintf(stderr, "valley: %s does not read, so everything it held is tried again\n", path)
1271 r.Projects = nil
1272 }
1273 if r.Projects == nil {
1274 r.Projects = map[string]map[string]backoff{}
1275 }
1276 return r
1277}
1278
1279// waiting reports whether something failed and its wait is not over.
1280func (r *failureRecord) waiting(project, key string, now time.Time) (backoff, bool) {
1281 f, ok := r.Projects[project][key]
1282 return f, ok && now.Before(f.Retry)
1283}
1284
1285// failed records one more failure in a row, and the time it may be tried
1286// again: first after the first failure, doubled for each one after it, and
1287// never more than longestWait.
1288func (r *failureRecord) failed(project, key string, now time.Time, first time.Duration) backoff {
1289 if r.Projects[project] == nil {
1290 r.Projects[project] = map[string]backoff{}
1291 }
1292 f := r.Projects[project][key]
1293 f.Failures++
1294 wait := first
1295 for i := 1; i < f.Failures && wait < longestWait; i++ {
1296 wait *= 2
1297 }
1298 f.Retry = now.Add(min(wait, longestWait))
1299 r.Projects[project][key] = f
1300 return f
1301}
1302
1303func (r *failureRecord) passed(project, key string) { delete(r.Projects[project], key) }
1304
1305// keep forgets every failure of the project that is not in met. Other
1306// projects' failures are kept.
1307func (r *failureRecord) keep(project string, met map[string]bool) {
1308 for key := range r.Projects[project] {
1309 if !met[key] {
1310 delete(r.Projects[project], key)
1311 }
1312 }
1313 if len(r.Projects[project]) == 0 {
1314 delete(r.Projects, project)
1315 }
1316}
1317
1318// save writes the record whole, through a file renamed into place, so a
1319// pass that is killed leaves the last record or the new one. An empty
1320// record is no file.
1321func (r *failureRecord) save() error {
1322 for project, failures := range r.Projects {
1323 if len(failures) == 0 {
1324 delete(r.Projects, project)
1325 }
1326 }
1327 if len(r.Projects) == 0 {
1328 if err := os.Remove(r.path); err != nil && !errors.Is(err, os.ErrNotExist) {
1329 return err
1330 }
1331 return nil
1332 }
1333 data, err := json.MarshalIndent(r, "", " ") // in key order
1334 if err != nil {
1335 return err
1336 }
1337 tmp, err := os.CreateTemp(filepath.Dir(r.path), ".failures-*")
1338 if err != nil {
1339 return err
1340 }
1341 _, err = tmp.Write(append(data, '\n'))
1342 if cerr := tmp.Close(); err == nil {
1343 err = cerr
1344 }
1345 if err == nil {
1346 err = os.Rename(tmp.Name(), r.path)
1347 }
1348 if err != nil {
1349 os.Remove(tmp.Name())
1350 }
1351 return err
1352}