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