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