gunk-dev/the-valley

worker.go

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