gunk-dev/the-valley

worker.go

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