gunk-dev/the-valley

worker.go

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