gunk-dev/the-valley

worker.go

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