gunk-dev/the-valley

worker.go

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