gunk-dev/the-valley

worker.go

sourcecc72d5a3fbc9main's published tip history
27.5 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 runs it; it keeps no queue, lease or schedule of its own.
8//
9// A pass reads each project named with --repo, and works through the
10// project's ready changes:
11//
12// 1. It lists the ready changes whose active version has not landed, as
13// valley pending does (pending.go), and pins each one's active head.
14// 2. It derives the checks the head requires, as valley-go checks does
15// (checks.go), over the head's merge base with main. Both policy
16// layers are read at main's tip on origin, as approve reads them,
17// never from the change.
18// 3. It asks coverage (coverage.go) which of the head's nix checks origin
19// already holds evidence for. Command checks are left to approve.
20// 4. It runs the rest in one batch, with attest run --rev <head> under
21// the worker's key, and pushes the one attestation ref attest stored.
22// It pushes nothing else. Given --slots, the batch builds that many
23// checks at once; without it, attest's own default decides.
24//
25// The evidence is about the head's tree, so it stays true if the change
26// moves on while the batch runs. The pass does not read the change's
27// record again before it publishes.
28//
29// The attestation namespace admits creations only, so the worker never
30// builds what it could not publish. When origin already holds this
31// worker's ref for a tree and the ref lacks a required check, the pass
32// reports it and builds nothing. approve --build-here builds the rest
33// under the operator's key (bd-7b7d58f). When the worker's ref is stored
34// here but not on origin, an earlier pass built it and its push was lost,
35// so the pass pushes that same ref again rather than building it again.
36//
37// A batch that fails is not run again at once, and neither is a push that
38// fails. The pass records each failure in failures.json in the state
39// directory, under its project: a batch by the tree and the checks it
40// runs, and a push by the object it publishes. A failed batch waits
41// firstBuildWait before it runs again, and a failed push waits
42// firstPushWait. Each wait doubles with every failure in a row, up to
43// longestWait. The clock is read when the pass asks whether a wait is
44// over, and again when an attempt ends, so a long build does not use up
45// its own wait. A new version is a new batch, and runs at once. VALLEY_NOW,
46// when set, is the time the pass reads as now (main.go's clock). Deleting
47// the record lets everything run again at once.
48//
49// A pass forgets the failures it did not meet in a project, but only for
50// a project it read whole: every ready change's checks derived and its
51// evidence read. A pass over other projects, or one that could not read
52// this one, leaves this one's record as it is.
53//
54// Passes that share a state directory take turns: each holds the lock
55// file there while it runs, and a pass that finds it held waits for it.
56// attest is handed the lock too, so it stays held while a batch runs even
57// when the pass that started the batch is killed.
58//
59// A read of origin that fails stops the pass, because a read that did not
60// happen must not read as no changes or no evidence. Anything else that
61// goes wrong with one change is reported, and the pass goes on to the
62// next. The pass exits 1 when anything went wrong.
63//
64// Given --wake, a pass claims that wake directory's due mark before it
65// reads anything, and acknowledges the claim when it has handled what it
66// read (wake.go). A pass has handled it when it read every project whole
67// and everything that went wrong was a failed batch or push whose wait it
68// recorded: those are retried when their wait is over, by a pass the
69// timer starts, and a new mark for the same refs would only find them
70// still waiting. Anything else that went wrong (a policy that did not
71// read, checks that did not derive, a read that stopped the pass, a
72// record that was not written) leaves the claim unacknowledged. A pass
73// that could not claim due reads and builds all the same, and then exits
74// claimFailedStatus instead of 0 or 1.
75//
76// Given --telemetry, or VALLEY_TELEMETRY_DIR in its environment, which is
77// how the host module names it, a pass says what it is doing as it does it, and keeps
78// its recent attempts and the failures waiting out their backoff with
79// what each was about (workertelemetry.go). It hands attest the same
80// stream for each batch's progress.
81//
82// Given --keep-outputs, a pass keeps the outputs of the checks it builds
83// alive against nix's garbage collection, so a later batch whose checks
84// have the same derivations finds them built. It hands attest
85// --gc-roots with the directory roots in its state directory, where
86// attest makes one indirect root per output, named by the output's store
87// path basename, and makes it afresh whenever a batch uses the output.
88// Before its batches, the pass removes each root there that no batch has
89// used for longer than the age --keep-outputs gives (pruneRoots). It
90// removes only the symlink; nix's own garbage collection frees the output
91// later. Without --keep-outputs, attest roots nothing and the pass prunes
92// nothing.
93
94import (
95 "context"
96 "encoding/json"
97 "errors"
98 "fmt"
99 "io"
100 "os"
101 "os/exec"
102 "path/filepath"
103 "strconv"
104 "strings"
105 "syscall"
106 "time"
107
108 "the-valley/change"
109 "the-valley/composed"
110 "the-valley/telemetry"
111)
112
113const workUsage = "usage: valley-go work --repo <name>... --key <file> [--name <name>] [--state <dir>] [--wake <dir>] [--telemetry <dir>] [--slots <n>] [--keep-outputs <age>]"
114
115// projectLayer is the project's own policy layer, in main's tree.
116const projectLayer = "policy/project"
117
118// The waits after a failure before the same thing is tried again: the
119// first after a failed batch, the first after a failed push, and the
120// longest either grows to by doubling.
121const (
122 firstBuildWait = 15 * time.Minute
123 firstPushWait = time.Minute
124 longestWait = 24 * time.Hour
125)
126
127// worker is one pass: the signer it attests as, the lock it holds, what it
128// says, and what it has found going wrong.
129type worker struct {
130 key, name string
131 slots int // how many checks a batch builds at once, or 0 for attest's default
132 roots string // the directory attest roots the outputs it builds in, or "" to root nothing
133 keyhash string // the key hash an attestation ref of this signer ends in
134 lock *os.File // the state directory's lock, held for the pass
135 wake *wake // the wake directory's claim, or nil without --wake
136 tel *workerTelemetry
137 failures *failureRecord
138 stdout io.Writer
139 stderr io.Writer
140 troubles int // things that went wrong that did not stop the pass
141 waits int // of the troubles, the failures whose wait was recorded
142}
143
144func runWork(g git, args []string, stdout, stderr io.Writer) (err error) {
145 var repos []string
146 var key, name, state, wakeDir, telemetryDir string
147 slots := 0
148 var keep time.Duration
149 for i := 0; i < len(args); i++ {
150 opt, value, inline := strings.Cut(args[i], "=")
151 if opt != "--repo" && opt != "--key" && opt != "--name" && opt != "--state" && opt != "--wake" && opt != "--telemetry" && opt != "--slots" && opt != "--keep-outputs" {
152 return failure(workUsage)
153 }
154 if !inline {
155 if i+1 == len(args) {
156 return failure(workUsage)
157 }
158 i++
159 value = args[i]
160 }
161 switch opt {
162 case "--repo":
163 if !change.ValidPrincipal(value) {
164 return failure(fmt.Sprintf("--repo %s: not a project name", value))
165 }
166 repos = append(repos, value)
167 case "--key":
168 key = value
169 case "--name":
170 name = value
171 case "--state":
172 state = value
173 case "--wake":
174 wakeDir = value
175 case "--telemetry":
176 telemetryDir = value
177 case "--slots":
178 n, err := strconv.Atoi(value)
179 if err != nil || n < 1 {
180 return failure(fmt.Sprintf("--slots %s: not a whole number of at least 1", value))
181 }
182 slots = n
183 case "--keep-outputs":
184 d, err := time.ParseDuration(value)
185 if err != nil || d <= 0 {
186 return failure(fmt.Sprintf("--keep-outputs %s: not a positive duration, such as 168h", value))
187 }
188 keep = d
189 }
190 }
191 if len(repos) == 0 || key == "" {
192 return failure(workUsage)
193 }
194 if telemetryDir == "" {
195 telemetryDir = os.Getenv("VALLEY_TELEMETRY_DIR")
196 }
197 // From here on, a pass given --wake that ends without having claimed
198 // due exits claimFailedStatus, however it ends, so whatever started
199 // it for that due holds off before it starts another.
200 var claim *wake
201 if wakeDir != "" {
202 defer func() {
203 if claim != nil && claim.err == nil {
204 return
205 }
206 why := "due was not claimed"
207 if claim != nil {
208 why = claim.err.Error()
209 }
210 if err != nil {
211 fmt.Fprintf(stderr, "valley: %s\n", err)
212 }
213 err = claimFailure{fmt.Sprintf("%s, so the pass exits %d", why, claimFailedStatus)}
214 }()
215 }
216 // attest runs in the repository a project is read through, which may
217 // be a cache clone, so a key named relative to here is made absolute.
218 abs, err := filepath.Abs(key)
219 if err != nil {
220 return failure(fmt.Sprintf("--key %s: %v", key, err))
221 }
222 key = abs
223 if state == "" {
224 if state, err = stateDirectory(); err != nil {
225 return failure("no state directory: name one with --state")
226 }
227 }
228 if err := os.MkdirAll(state, 0o700); err != nil {
229 return failure(fmt.Sprintf("could not make the state directory %s", state))
230 }
231
232 lock, err := lockState(filepath.Join(state, "lock"), stderr)
233 if err != nil {
234 return failure(fmt.Sprintf("could not take the lock in %s: %v", state, err))
235 }
236 defer lock.Close() // close drops the flock; every attest handed it has ended by then
237
238 // The claim comes before any read, so a move marked after it is
239 // either read by this pass or left marked for the next.
240 if wakeDir != "" {
241 claim = claimWake(wakeDir, stderr)
242 defer claim.close()
243 if claim.err != nil {
244 fmt.Fprintf(stderr, "valley: %v; the pass reads everything all the same\n", claim.err)
245 }
246 }
247
248 // The signer is read before anything else is done, so a pass that
249 // could only end in "no key" says so before it reads anything.
250 keyArgs := []string{"key", "--key", key}
251 if name != "" {
252 keyArgs = append(keyArgs, "--name", name)
253 }
254 out, err := attestTool(g, keyArgs...)
255 fields := strings.SplitN(strings.TrimSpace(out), "+", 3)
256 if err != nil || len(fields) != 3 || len(fields[1]) != 8 {
257 return failure(fmt.Sprintf("could not read the signing key at %s: %s", key, refusalOf(out)))
258 }
259
260 w := &worker{key: key, name: name, slots: slots, keyhash: fields[1], lock: lock, wake: claim, stdout: stdout, stderr: stderr}
261 w.tel = openWorkerTelemetry(telemetryDir)
262 defer func() { w.tel.finish(w.failures, w.troubles, err) }()
263 w.failures = readFailures(filepath.Join(state, "failures.json"), stderr)
264 if keep > 0 {
265 // attest runs in each project's repository, so the roots are
266 // named absolutely, where this pass prunes them.
267 if w.roots, err = filepath.Abs(filepath.Join(state, "roots")); err != nil {
268 return failure(fmt.Sprintf("--state %s: %v", state, err))
269 }
270 if err := pruneRoots(w.roots, keep, clock()); err != nil {
271 fmt.Fprintf(stderr, "valley: could not prune the roots in %s: %v\n", w.roots, err)
272 w.troubles++
273 }
274 }
275 for _, repo := range repos {
276 if err := w.project(g, repo); err != nil {
277 return err
278 }
279 }
280 w.save()
281 if claim != nil && w.troubles == w.waits {
282 if err := claim.ack(); err != nil {
283 fmt.Fprintf(stderr, "valley: could not acknowledge %s: %v\n", filepath.Join(wakeDir, "claimed"), err)
284 w.troubles++
285 }
286 }
287 if w.troubles > 0 {
288 return failure(fmt.Sprintf("the pass finished, but %s went wrong in it; each is said above", counted(w.troubles, "thing")))
289 }
290 return nil
291}
292
293// stateDirectory is where the worker keeps its lock and its record of
294// failed batches by default: $XDG_STATE_HOME/valley/worker, or
295// ~/.local/state/valley/worker, beside attest's timing log.
296func stateDirectory() (string, error) {
297 state := os.Getenv("XDG_STATE_HOME")
298 if !filepath.IsAbs(state) {
299 home, err := os.UserHomeDir()
300 if err != nil {
301 return "", err
302 }
303 state = filepath.Join(home, ".local", "state")
304 }
305 return filepath.Join(state, "valley", "worker"), nil
306}
307
308// pruneRoots removes each symlink in dir whose modification time is more
309// than keep before now. attest makes a root afresh each time a batch uses
310// its output, so that time is the output's last use. Only symlinks are
311// removed, never what they point to, and a dir that does not exist yet
312// holds nothing to prune.
313func pruneRoots(dir string, keep time.Duration, now time.Time) error {
314 entries, err := os.ReadDir(dir)
315 if errors.Is(err, os.ErrNotExist) {
316 return nil
317 }
318 if err != nil {
319 return err
320 }
321 var errs []error
322 for _, e := range entries {
323 if e.Type()&os.ModeSymlink == 0 {
324 continue
325 }
326 info, err := e.Info()
327 if errors.Is(err, os.ErrNotExist) {
328 continue
329 }
330 if err != nil {
331 errs = append(errs, err)
332 continue
333 }
334 if now.Sub(info.ModTime()) > keep {
335 if err := os.Remove(filepath.Join(dir, e.Name())); err != nil && !errors.Is(err, os.ErrNotExist) {
336 errs = append(errs, err)
337 }
338 }
339 }
340 return errors.Join(errs...)
341}
342
343// lockState takes the lock file at path, waiting for whoever holds it, and
344// returns the open file, whose closing releases it. The lock is flock's,
345// as self-update's is. It belongs to the open file, so it is released when
346// every process holding that file has closed it or ended, however each
347// ends.
348func lockState(path string, stderr io.Writer) (*os.File, error) {
349 f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0o600)
350 if err != nil {
351 return nil, err
352 }
353 err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
354 if errors.Is(err, syscall.EWOULDBLOCK) {
355 fmt.Fprintf(stderr, "valley: another pass holds %s; waiting for it to end\n", path)
356 err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX)
357 }
358 if err != nil {
359 f.Close()
360 return nil, err
361 }
362 return f, nil
363}
364
365// project works through one project's ready changes. It returns an error
366// only when a read of origin failed, which stops the pass. When it has
367// read the project whole, it forgets the project's failures it did not
368// meet.
369func (w *worker) project(g git, name string) error {
370 list, _, err := sources(g, listing{repo: name}, w.stderr)
371 if err != nil {
372 return failure(fmt.Sprintf("%s: %v; the pass stops here", name, err))
373 }
374 repos := readSources(list, newVerifier())
375 r := repos[0]
376 if r.err != nil {
377 return failure(fmt.Sprintf("%s: %v; the pass stops here", name, r.err))
378 }
379 view := r.pendingView(handles(repos))
380 met := map[string]bool{} // the failures this pass met, by key
381 if len(view.Changes) == 0 {
382 w.failures.keep(name, met)
383 return nil
384 }
385 if r.snap.tip == "" {
386 fmt.Fprintf(w.stdout, "%s: origin has no main to read the policy at, so nothing is built\n", name)
387 w.troubles++
388 return nil
389 }
390 instance, project, done, err := policyLayers(r.g, r.snap.tip)
391 defer done()
392 if err != nil {
393 fmt.Fprintf(w.stdout, "%s: the policy at main did not read, so nothing is built: %v\n", name, err)
394 w.troubles++
395 return nil
396 }
397 whole := true
398 for _, c := range view.Changes {
399 read, err := w.change(r, instance, project, c, met)
400 if err != nil {
401 return err
402 }
403 whole = whole && read
404 }
405 if whole {
406 w.failures.keep(name, met)
407 }
408 return nil
409}
410
411// change builds and publishes what one ready change's head lacks. read
412// says whether it read the change through: derived its checks, and read
413// the evidence origin holds for them.
414func (w *worker) change(r listed, instance, project string, c jsonChange, met map[string]bool) (read bool, err error) {
415 v := c.Versions[c.Active-1]
416 head := v.Head
417 w.tel.change(r.name, c, v)
418 say := func(format string, args ...any) {
419 fmt.Fprintf(w.stdout, "%s: %s v%d at %s: %s\n", r.name, c.Handle, v.N, head[:min(7, len(head))], fmt.Sprintf(format, args...))
420 }
421 base, err := r.g.output(true, "merge-base", r.snap.tip, head)
422 if err != nil {
423 say("shares no history with main, so nothing is built")
424 w.troubles++
425 return false, nil
426 }
427 doc, err := derivedChecks(r.g, "", instance, project, base, head)
428 if err != nil {
429 say("its checks did not derive, so nothing is built: %v", err)
430 w.troubles++
431 return false, nil
432 }
433 var asked []nixCheck
434 for _, q := range doc.Required {
435 if q.Runner == "nix" {
436 asked = append(asked, nixCheck{q.Name, q.Attribute})
437 }
438 }
439 if len(asked) == 0 {
440 say("requires no nix check")
441 return true, nil
442 }
443
444 e, err := coverageOf(r.g, head, asked, w.stderr)
445 if err != nil {
446 return false, failure(fmt.Sprintf("%s: %s v%d: %v; the pass stops here", r.name, c.Handle, v.N, err))
447 }
448 var missing []nixCheck
449 var names []string
450 for _, q := range asked {
451 if _, ok := e.covered[q.name]; !ok {
452 missing = append(missing, q)
453 names = append(names, q.name)
454 }
455 }
456 if len(missing) == 0 {
457 say("origin holds evidence for every nix check it requires")
458 return true, nil
459 }
460
461 own := attestationRefs + e.digest + "/" + w.keyhash
462 if _, ok := e.listed[own]; ok {
463 say("origin already holds %s, this worker's evidence for its tree, and it does not cover %s. "+
464 "That namespace admits creations only, so approve --build-here builds the rest (bd-7b7d58f)", own, strings.Join(names, ", "))
465 return true, nil
466 }
467 if stored, found, err := r.g.ref(own); err == nil && found {
468 say("an earlier pass stored %s, and origin does not hold it", own)
469 w.publish(r, own, stored, met, say)
470 return true, nil
471 }
472
473 batch := "build " + e.digest + " " + strings.Join(names, ",")
474 met[batch] = true
475 if f, waiting := w.failures.waiting(r.name, batch, clock()); waiting {
476 say("its batch %s failed %s in a row, so it is not built again before %s", strings.Join(names, ", "), counted(f.Failures, "time"), f.Retry.Format(time.RFC3339))
477 return true, nil
478 }
479 say("building %s", strings.Join(names, ", "))
480 mark := w.tel.streamEnd()
481 attestRun := telemetry.NewRunID()
482 a := w.tel.begin("build", e.digest, names, map[string]any{"attest_run": attestRun})
483 if err := w.attest(r.g, head, missing, attestRun, r.name, c, v); err != nil {
484 // The wait runs from when the batch ended, not from when it began.
485 f := w.failures.failed(r.name, batch, clock(), firstBuildWait)
486 reason := fmt.Sprintf("attest run %s: %v", attestRun, err)
487 if failed := w.tel.failedChecks(attestRun, mark); len(failed) > 0 {
488 reason += "; " + strings.Join(failed, ", ")
489 }
490 w.tel.end(a, err, reason, r.name, batch, &f)
491 say("the batch did not pass (%v); it is not built again before %s", err, f.Retry.Format(time.RFC3339))
492 w.troubles++
493 w.waits++
494 w.save()
495 return true, nil
496 }
497 w.failures.passed(r.name, batch)
498 w.tel.end(a, nil, "", r.name, batch, nil)
499 stored, found, err := r.g.ref(own)
500 if err != nil || !found {
501 say("attest stored no %s, so nothing is published", own)
502 w.troubles++
503 return true, nil
504 }
505 w.publish(r, own, stored, met, say)
506 return true, nil
507}
508
509// attest runs one batch with attest run, which stores the notes at the
510// worker's attestation ref for the head's tree and publishes nothing.
511// What attest prints is passed on.
512//
513// attest is handed the lock file as well, and holds it until it ends, and
514// the wake directory's lock with it. The
515// flock belongs to the open file, so the lock stays held while attest
516// runs, and while anything it started that inherited the file runs, even
517// when this pass is killed. A later pass waits for all of it, and then
518// finds the ref attest stored.
519func (w *worker) attest(g git, head string, checks []nixCheck, run, project string, c jsonChange, v jsonVersion) error {
520 repo := g.dir
521 if repo == "" {
522 repo = "."
523 }
524 args := []string{"run", "--repo", repo, "--rev", head, "--key", w.key}
525 if w.name != "" {
526 args = append(args, "--name", w.name)
527 }
528 if w.slots > 0 {
529 args = append(args, "--slots", strconv.Itoa(w.slots))
530 }
531 if w.roots != "" {
532 args = append(args, "--gc-roots", w.roots)
533 }
534 for _, q := range checks {
535 args = append(args, "--check", q.name+"="+q.attribute)
536 }
537 if w.tel != nil {
538 args = append(args, "--telemetry", w.tel.stream(), "--telemetry-run", run, "--project", project,
539 "--change", c.ChangeID, "--change-version", strconv.Itoa(v.N))
540 }
541 cmd := exec.Command("attest", args...)
542 cmd.Env = g.env
543 cmd.Dir = g.dir
544 cmd.Stdout, cmd.Stderr = w.stdout, w.stderr
545 cmd.ExtraFiles = []*os.File{w.lock}
546 if w.wake != nil && w.wake.lock != nil {
547 cmd.ExtraFiles = append(cmd.ExtraFiles, w.wake.lock)
548 }
549 return cmd.Run()
550}
551
552// publish pushes one attestation ref to origin, and nothing else. The hook
553// verifies the notes against the tree and the signer whoever pushes them.
554// A push that fails leaves the ref stored here, and the same object is not
555// pushed again until its wait is over: by any pass, and for any change
556// whose tree it is about.
557func (w *worker) publish(r listed, ref, object string, met map[string]bool, say func(string, ...any)) {
558 key := "push " + object
559 met[key] = true
560 if f, waiting := w.failures.waiting(r.name, key, clock()); waiting {
561 say("publishing %s failed %s in a row, so it is not pushed again before %s", ref, counted(f.Failures, "time"), f.Retry.Format(time.RFC3339))
562 return
563 }
564 a := w.tel.begin("push", "", nil, map[string]any{"ref": ref, "object": object})
565 if _, err := r.g.output(false, "push", "--quiet", "origin", object+":"+ref); err != nil {
566 f := w.failures.failed(r.name, key, clock(), firstPushWait)
567 w.tel.end(a, err, fmt.Sprintf("pushing %s to origin: %v", ref, err), r.name, key, &f)
568 say("could not publish %s; it is not pushed again before %s", ref, f.Retry.Format(time.RFC3339))
569 w.troubles++
570 w.waits++
571 w.save()
572 return
573 }
574 w.failures.passed(r.name, key)
575 w.tel.end(a, nil, "", r.name, key, nil)
576 say("published %s", ref)
577}
578
579// save writes the failure record, and counts a write that fails as
580// something that went wrong.
581func (w *worker) save() {
582 if err := w.failures.save(); err != nil {
583 fmt.Fprintf(w.stderr, "valley: could not write %s: %v\n", w.failures.path, err)
584 w.troubles++
585 }
586}
587
588// policyLayers resolves the two policy layers a project's changes are
589// derived under, as approve resolves them (bin/valley's
590// resolve_instance_layer and resolve_project_layer), and returns what
591// removes them. Both are read at main's tip on origin. The floor is that
592// tip's own policy/instance when it carries one, and otherwise
593// policy/instance at the tip of main in the owning valley that
594// policy/valley names. A tip with no policy/project is derived under the
595// floor alone.
596func policyLayers(g git, tip string) (instance, project string, done func(), err error) {
597 ctx := context.Background()
598 var ends []func()
599 done = func() {
600 for _, end := range ends {
601 end()
602 }
603 }
604 repo := g.dir
605 if repo == "" {
606 repo = "."
607 }
608 floor := composed.Floor{Repo: repo, Ref: tip, Dir: instanceLayer}
609 if !g.succeeds(true, "cat-file", "-e", tip+":"+instanceLayer) {
610 pointer, err := g.output(true, "cat-file", "blob", tip+":"+valleyPointer)
611 if err != nil {
612 return "", "", done, fmt.Errorf("main names no owning valley at %s", valleyPointer)
613 }
614 url := pointerURL(pointer)
615 if url == "" {
616 return "", "", done, fmt.Errorf("%s on main names no repository", valleyPointer)
617 }
618 if err := checkURL(url); err != nil {
619 return "", "", done, err
620 }
621 scratch, err := os.MkdirTemp("", "valley-work-valley-")
622 if err != nil {
623 return "", "", done, err
624 }
625 ends = append(ends, func() { _ = os.RemoveAll(scratch) })
626 v := git{env: cacheEnvironment(g.env), stderr: g.stderr, dir: scratch}
627 if _, err := v.output(true, "init", "--quiet", "--bare"); err != nil {
628 return "", "", done, errors.New("no scratch repository to fetch the floor into")
629 }
630 // The valley's main is read by its exact name, and fetched by the
631 // object it names: given a ref name the valley lacks, fetch takes
632 // another ref whose name ends in it, such as
633 // refs/heads/refs/heads/main.
634 at, err := remoteRef(v, url, "refs/heads/main")
635 if err != nil {
636 return "", "", done, fmt.Errorf("could not fetch the owning valley %s", url)
637 } else if at == "" {
638 return "", "", done, fmt.Errorf("the owning valley %s has no refs/heads/main", url)
639 }
640 if _, err := v.output(true, "fetch", "--quiet", "--depth", "1", "--no-tags", "--end-of-options", url, at); err != nil {
641 return "", "", done, fmt.Errorf("could not fetch the owning valley %s", url)
642 }
643 floor = composed.Floor{Repo: scratch, Ref: at, Dir: instanceLayer}
644 }
645 instance, end, err := floor.Open(ctx, "valley-work-floor")
646 ends = append(ends, end)
647 if err != nil {
648 return "", "", done, err
649 }
650 project, _, end, err = composed.Project(ctx, repo, tip, projectLayer, "valley-work-project")
651 ends = append(ends, end)
652 return instance, project, done, err
653}
654
655// failureRecord is the worker's record of what failed, project by
656// project: each batch, keyed "build <tree digest> <check>,<check>", and
657// each push, keyed "push <object ID>". For each it holds how many times in
658// a row it failed, and the time before which it is not tried again. It is
659// kept as JSON at path.
660type failureRecord struct {
661 path string
662 Projects map[string]map[string]backoff `json:"projects"`
663}
664
665type backoff struct {
666 Failures int `json:"failures"`
667 Retry time.Time `json:"retry"`
668}
669
670// readFailures reads the record at path. A record that is not there is
671// empty. One that does not read is said, and started again empty: the
672// worst it costs is one more try of each thing it held.
673func readFailures(path string, stderr io.Writer) *failureRecord {
674 r := &failureRecord{path: path}
675 data, err := os.ReadFile(path)
676 if err == nil {
677 err = json.Unmarshal(data, r)
678 }
679 if err != nil && !errors.Is(err, os.ErrNotExist) {
680 fmt.Fprintf(stderr, "valley: %s does not read, so everything it held is tried again\n", path)
681 r.Projects = nil
682 }
683 if r.Projects == nil {
684 r.Projects = map[string]map[string]backoff{}
685 }
686 return r
687}
688
689// waiting reports whether something failed and its wait is not over.
690func (r *failureRecord) waiting(project, key string, now time.Time) (backoff, bool) {
691 f, ok := r.Projects[project][key]
692 return f, ok && now.Before(f.Retry)
693}
694
695// failed records one more failure in a row, and the time it may be tried
696// again: first after the first failure, doubled for each one after it, and
697// never more than longestWait.
698func (r *failureRecord) failed(project, key string, now time.Time, first time.Duration) backoff {
699 if r.Projects[project] == nil {
700 r.Projects[project] = map[string]backoff{}
701 }
702 f := r.Projects[project][key]
703 f.Failures++
704 wait := first
705 for i := 1; i < f.Failures && wait < longestWait; i++ {
706 wait *= 2
707 }
708 f.Retry = now.Add(min(wait, longestWait))
709 r.Projects[project][key] = f
710 return f
711}
712
713func (r *failureRecord) passed(project, key string) { delete(r.Projects[project], key) }
714
715// keep forgets every failure of the project that is not in met. Other
716// projects' failures are kept.
717func (r *failureRecord) keep(project string, met map[string]bool) {
718 for key := range r.Projects[project] {
719 if !met[key] {
720 delete(r.Projects[project], key)
721 }
722 }
723 if len(r.Projects[project]) == 0 {
724 delete(r.Projects, project)
725 }
726}
727
728// save writes the record whole, through a file renamed into place, so a
729// pass that is killed leaves the last record or the new one. An empty
730// record is no file.
731func (r *failureRecord) save() error {
732 for project, failures := range r.Projects {
733 if len(failures) == 0 {
734 delete(r.Projects, project)
735 }
736 }
737 if len(r.Projects) == 0 {
738 if err := os.Remove(r.path); err != nil && !errors.Is(err, os.ErrNotExist) {
739 return err
740 }
741 return nil
742 }
743 data, err := json.MarshalIndent(r, "", " ") // in key order
744 if err != nil {
745 return err
746 }
747 tmp, err := os.CreateTemp(filepath.Dir(r.path), ".failures-*")
748 if err != nil {
749 return err
750 }
751 _, err = tmp.Write(append(data, '\n'))
752 if cerr := tmp.Close(); err == nil {
753 err = cerr
754 }
755 if err == nil {
756 err = os.Rename(tmp.Name(), r.path)
757 }
758 if err != nil {
759 os.Remove(tmp.Name())
760 }
761 return err
762}