gunk-dev/the-valley

worker.go

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