gunk-dev/the-valley

worker.go

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