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