| 1 | package main |
| 2 | |
| 3 | // Running a check, and the digests a run yields. |
| 4 | // |
| 5 | // The nix runner claims purity strongly: it builds a flake check |
| 6 | // derivation, so the check's inputs, the derivation itself and its output |
| 7 | // are all named, and any verifier holding the same tree can re-derive |
| 8 | // them. The command runner claims nothing beyond having run — its |
| 9 | // statement is a notarization naming the environment and the time |
| 10 | // (archive/design/verification.md). |
| 11 | |
| 12 | import ( |
| 13 | "bytes" |
| 14 | "context" |
| 15 | "encoding/json" |
| 16 | "fmt" |
| 17 | "os" |
| 18 | "os/exec" |
| 19 | "regexp" |
| 20 | "runtime" |
| 21 | "strings" |
| 22 | "time" |
| 23 | ) |
| 24 | |
| 25 | type checkSpec struct { |
| 26 | name string |
| 27 | attribute string // nix runner |
| 28 | command string // command runner |
| 29 | } |
| 30 | |
| 31 | func (c checkSpec) runner() string { |
| 32 | if c.command != "" { |
| 33 | return "command" |
| 34 | } |
| 35 | return "nix" |
| 36 | } |
| 37 | |
| 38 | // checkOutcome is what running one check produced: whether it passed, the |
| 39 | // output a reader needs when it did not, how it was satisfied, and the |
| 40 | // digests of a pure run. |
| 41 | type checkOutcome struct { |
| 42 | spec checkSpec |
| 43 | passed bool |
| 44 | log string |
| 45 | satisfied string |
| 46 | |
| 47 | inputs string |
| 48 | derivation string |
| 49 | output string |
| 50 | observedAt string |
| 51 | } |
| 52 | |
| 53 | // ranCheck is one check as a run ran it: its outcome, or the error that |
| 54 | // kept it from having one, and when it started and how long it took. eval |
| 55 | // is how long a pure check took to evaluate, and is zero for a command. |
| 56 | type ranCheck struct { |
| 57 | out checkOutcome |
| 58 | err error |
| 59 | began time.Time |
| 60 | took time.Duration |
| 61 | eval time.Duration |
| 62 | } |
| 63 | |
| 64 | // nixSystem is the flake system attribute of the machine running the |
| 65 | // check. A check is built where the work was written, so this is the |
| 66 | // runner's own system and never something the caller states about another |
| 67 | // machine. |
| 68 | func nixSystem() string { |
| 69 | arch := runtime.GOARCH |
| 70 | switch arch { |
| 71 | case "amd64": |
| 72 | arch = "x86_64" |
| 73 | case "arm64": |
| 74 | arch = "aarch64" |
| 75 | case "386": |
| 76 | arch = "i686" |
| 77 | } |
| 78 | return arch + "-" + runtime.GOOS |
| 79 | } |
| 80 | |
| 81 | func nix(dir string, args ...string) (string, string, error) { |
| 82 | cmd := exec.Command("nix", args...) |
| 83 | cmd.Dir = dir |
| 84 | var out, errb bytes.Buffer |
| 85 | cmd.Stdout = &out |
| 86 | cmd.Stderr = &errb |
| 87 | err := cmd.Run() |
| 88 | return out.String(), errb.String(), err |
| 89 | } |
| 90 | |
| 91 | // nixStore runs nix-store, and stops it when ctx is done. |
| 92 | func nixStore(ctx context.Context, args ...string) (string, string, error) { |
| 93 | cmd := exec.CommandContext(ctx, "nix-store", args...) |
| 94 | cmd.WaitDelay = time.Second |
| 95 | var out, errb bytes.Buffer |
| 96 | cmd.Stdout = &out |
| 97 | cmd.Stderr = &errb |
| 98 | err := cmd.Run() |
| 99 | return out.String(), errb.String(), err |
| 100 | } |
| 101 | |
| 102 | // flakeChecks lists every check attribute a flake defines for a system — |
| 103 | // what "the repo's canonical checks" means when the caller names none. |
| 104 | func flakeChecks(tree, system string) ([]string, error) { |
| 105 | out, errb, err := nix(tree, "eval", "--json", "--apply", "builtins.attrNames", tree+"#checks."+system) |
| 106 | if err != nil { |
| 107 | return nil, fmt.Errorf("listing checks: %w: %s", err, strings.TrimSpace(errb)) |
| 108 | } |
| 109 | var names []string |
| 110 | if err := json.Unmarshal([]byte(out), &names); err != nil { |
| 111 | return nil, fmt.Errorf("listing checks: %w", err) |
| 112 | } |
| 113 | return names, nil |
| 114 | } |
| 115 | |
| 116 | // closure is what evaluating a pure check names before anything is built: |
| 117 | // the derivation, and the digest of its input closure. Both are functions |
| 118 | // of the tree alone, so an integrator can recompute the closure digest on a |
| 119 | // rebased tree without running the check — which is the whole of the pure |
| 120 | // transfer rule (dcr-439b771). |
| 121 | type closure struct { |
| 122 | drv string |
| 123 | derivation string |
| 124 | inputs string |
| 125 | } |
| 126 | |
| 127 | // evalClosure evaluates one flake check over an exported tree and digests |
| 128 | // what the evaluation named. Nothing is built. |
| 129 | func evalClosure(tree, system string, spec checkSpec) (closure, error) { |
| 130 | attr := tree + "#checks." + system + "." + spec.attribute |
| 131 | drv, errb, err := nix(tree, "eval", "--raw", attr+".drvPath") |
| 132 | if err != nil { |
| 133 | return closure{}, fmt.Errorf("evaluating %s: %w: %s", attr, err, strings.TrimSpace(errb)) |
| 134 | } |
| 135 | return closureOf(strings.TrimSpace(drv)) |
| 136 | } |
| 137 | |
| 138 | // closureOf digests a derivation an evaluation named: the derivation file |
| 139 | // itself, and the store paths it reads. |
| 140 | func closureOf(drv string) (closure, error) { |
| 141 | drvBytes, err := os.ReadFile(drv) |
| 142 | if err != nil { |
| 143 | return closure{}, err |
| 144 | } |
| 145 | inputs, err := drvInputs(drv) |
| 146 | if err != nil { |
| 147 | return closure{}, err |
| 148 | } |
| 149 | return closure{ |
| 150 | drv: drv, |
| 151 | derivation: fmt.Sprintf("%x", sha256sum(drvBytes)), |
| 152 | inputs: inputsDigest(inputs), |
| 153 | }, nil |
| 154 | } |
| 155 | |
| 156 | // evaluation is one pure check's evaluation: the closure it named, or why |
| 157 | // it named none, and how long it took. |
| 158 | type evaluation struct { |
| 159 | closure |
| 160 | err error |
| 161 | took time.Duration |
| 162 | } |
| 163 | |
| 164 | // plainAttribute is a check attribute the shared evaluation can name in a |
| 165 | // nix string as it is: one attribute, with no dot, quote, backslash or |
| 166 | // dollar sign in it. |
| 167 | var plainAttribute = regexp.MustCompile(`^[A-Za-z0-9_'+-]+$`) |
| 168 | |
| 169 | // evalClosures evaluates every pure check over the exported tree. One nix |
| 170 | // evaluation names the derivations of all of them together, so nixpkgs and |
| 171 | // whatever else the checks share are evaluated once and not once per |
| 172 | // check. A check that evaluation could not name is evaluated alone, as |
| 173 | // evalClosure does, so an error is reported against the check that has it |
| 174 | // and stops no other. Each check is timed as the shared evaluation plus |
| 175 | // whatever was done for it alone. |
| 176 | func evalClosures(tree, system string, specs []checkSpec) []evaluation { |
| 177 | var attrs []string |
| 178 | shared := map[string]bool{} |
| 179 | for _, spec := range specs { |
| 180 | if plainAttribute.MatchString(spec.attribute) && !shared[spec.attribute] { |
| 181 | shared[spec.attribute] = true |
| 182 | attrs = append(attrs, spec.attribute) |
| 183 | } |
| 184 | } |
| 185 | began := time.Now() |
| 186 | drvs := evalDrvPaths(tree, system, attrs) |
| 187 | sharedTook := time.Since(began) |
| 188 | |
| 189 | evals := make([]evaluation, len(specs)) |
| 190 | for i, spec := range specs { |
| 191 | began := time.Now() |
| 192 | var c closure |
| 193 | var err error |
| 194 | if drv, ok := drvs[spec.attribute]; ok { |
| 195 | c, err = closureOf(drv) |
| 196 | } else { |
| 197 | c, err = evalClosure(tree, system, spec) |
| 198 | } |
| 199 | evals[i] = evaluation{closure: c, err: err, took: time.Since(began)} |
| 200 | if shared[spec.attribute] { |
| 201 | evals[i].took += sharedTook |
| 202 | } |
| 203 | } |
| 204 | return evals |
| 205 | } |
| 206 | |
| 207 | // evalDrvPaths names the derivation of every check attribute given, in one |
| 208 | // nix evaluation. A check whose evaluation throws, or that is missing or |
| 209 | // is not a derivation, is left out of the answer. Some evaluation errors |
| 210 | // cannot be caught inside nix, such as a type error, and they end the |
| 211 | // whole evaluation; then the answer is empty, and every check is evaluated |
| 212 | // alone. |
| 213 | func evalDrvPaths(tree, system string, attrs []string) map[string]string { |
| 214 | drvs := map[string]string{} |
| 215 | if len(attrs) == 0 { |
| 216 | return drvs |
| 217 | } |
| 218 | quoted := make([]string, len(attrs)) |
| 219 | for i, a := range attrs { |
| 220 | quoted[i] = `"` + a + `"` |
| 221 | } |
| 222 | apply := `checks: builtins.listToAttrs (map (name: { inherit name; value = ` + |
| 223 | `let r = builtins.tryEval (if checks ? ${name} && checks.${name} ? drvPath then checks.${name}.drvPath else null); ` + |
| 224 | `in if r.success then r.value else null; }) [ ` + strings.Join(quoted, " ") + ` ])` |
| 225 | out, _, err := nix(tree, "eval", "--json", "--apply", apply, tree+"#checks."+system) |
| 226 | if err != nil { |
| 227 | return drvs |
| 228 | } |
| 229 | var named map[string]any |
| 230 | if json.Unmarshal([]byte(out), &named) != nil { |
| 231 | return drvs |
| 232 | } |
| 233 | for _, a := range attrs { |
| 234 | if drv, ok := named[a].(string); ok && drv != "" { |
| 235 | drvs[a] = drv |
| 236 | } |
| 237 | } |
| 238 | return drvs |
| 239 | } |
| 240 | |
| 241 | // runPure runs every pure check together and returns their runs in the |
| 242 | // order given. It evaluates them all (evalClosures), then builds every |
| 243 | // derivation that evaluated in one nix build, so nix builds them side by |
| 244 | // side under the machine's own max-jobs and cores settings. --keep-going |
| 245 | // lets every build finish whatever another does. |
| 246 | // |
| 247 | // Each check's outcome is still its own, decided from the store after the |
| 248 | // build: it passed when every output of its derivation is there. Building |
| 249 | // from the derivation path rather than the attribute a second time |
| 250 | // guarantees the thing built is the thing recorded. With probe, it first |
| 251 | // asks the nix store whether each output is already there, for the check's |
| 252 | // timing; without, it asks nothing before the build. |
| 253 | // |
| 254 | // A check is timed from the start of the evaluation. One that does not |
| 255 | // evaluate ends there. Every other one ends when the whole build does, |
| 256 | // since nix gives no time for one derivation in a build of many. |
| 257 | func runPure(tree, system string, specs []checkSpec, probe bool) []ranCheck { |
| 258 | began := time.Now() |
| 259 | evals := evalClosures(tree, system, specs) |
| 260 | runs := make([]ranCheck, len(specs)) |
| 261 | var drvs []string |
| 262 | for i, spec := range specs { |
| 263 | e := evals[i] |
| 264 | runs[i] = ranCheck{out: checkOutcome{spec: spec}, began: began, took: e.took, eval: e.took, err: e.err} |
| 265 | if e.err != nil { |
| 266 | continue |
| 267 | } |
| 268 | runs[i].out.derivation, runs[i].out.inputs = e.derivation, e.inputs |
| 269 | if probe { |
| 270 | runs[i].out.satisfied = outputsCached(e.drv) |
| 271 | } |
| 272 | drvs = append(drvs, e.drv) |
| 273 | } |
| 274 | if len(drvs) == 0 { |
| 275 | return runs |
| 276 | } |
| 277 | |
| 278 | buildLog := buildAll(tree, drvs) |
| 279 | for i := range runs { |
| 280 | if runs[i].err == nil { |
| 281 | runs[i].err = pureOutcome(tree, evals[i].drv, buildLog, &runs[i].out) |
| 282 | } |
| 283 | } |
| 284 | took := time.Since(began) |
| 285 | for i := range runs { |
| 286 | if evals[i].err == nil { |
| 287 | runs[i].took = took |
| 288 | } |
| 289 | } |
| 290 | return runs |
| 291 | } |
| 292 | |
| 293 | // buildAll builds every output of every derivation given in one nix build, |
| 294 | // and returns what nix wrote on standard error. Its exit status says |
| 295 | // nothing about any one check, and when any build fails nix prints no |
| 296 | // output path at all, so neither is read: each check's outcome is read |
| 297 | // from the store afterwards. |
| 298 | func buildAll(tree string, drvs []string) string { |
| 299 | args := []string{"build", "--no-link", "--keep-going"} |
| 300 | seen := map[string]bool{} |
| 301 | for _, drv := range drvs { |
| 302 | if !seen[drv] { |
| 303 | seen[drv] = true |
| 304 | args = append(args, drv+"^*") |
| 305 | } |
| 306 | } |
| 307 | _, errb, err := nix(tree, args...) |
| 308 | if log := strings.TrimSpace(errb); log != "" || err == nil { |
| 309 | return log |
| 310 | } |
| 311 | return err.Error() |
| 312 | } |
| 313 | |
| 314 | // pureOutcome decides one pure check after the shared build, and digests |
| 315 | // its output when it passed. A check whose outputs are not all in the |
| 316 | // store failed, and its log is the one nix kept for its derivation. A |
| 317 | // derivation nix holds no log for, such as one whose dependency failed so |
| 318 | // that it never started, gets the whole build's log instead. |
| 319 | func pureOutcome(tree, drv, buildLog string, out *checkOutcome) error { |
| 320 | paths, built, err := storeOutputs(context.Background(), drv) |
| 321 | if err != nil { |
| 322 | return fmt.Errorf("%s: %w", out.spec.name, err) |
| 323 | } |
| 324 | if !built { |
| 325 | log, _, err := nix(tree, "log", drv) |
| 326 | out.log = strings.TrimSpace(log) |
| 327 | if err != nil || out.log == "" { |
| 328 | out.log = buildLog |
| 329 | } |
| 330 | return nil // a failed check is an outcome, not an error |
| 331 | } |
| 332 | if len(paths) != 1 { |
| 333 | return fmt.Errorf("%s produced %d outputs; a check attribute must produce exactly one", out.spec.name, len(paths)) |
| 334 | } |
| 335 | entries, err := fsEntries(paths[0]) |
| 336 | if err != nil { |
| 337 | return err |
| 338 | } |
| 339 | out.output = treeDigest(entries) |
| 340 | out.passed = true |
| 341 | return nil |
| 342 | } |
| 343 | |
| 344 | // storeOutputs names every output of a derivation and says whether all of |
| 345 | // them are in the local nix store. |
| 346 | func storeOutputs(ctx context.Context, drv string) ([]string, bool, error) { |
| 347 | outputs, errb, err := nixStore(ctx, "--query", "--outputs", drv) |
| 348 | if err != nil { |
| 349 | return nil, false, fmt.Errorf("querying the outputs of %s: %w: %s", drv, err, strings.TrimSpace(errb)) |
| 350 | } |
| 351 | paths := strings.Fields(outputs) |
| 352 | if len(paths) == 0 { |
| 353 | return nil, false, fmt.Errorf("%s names no outputs", drv) |
| 354 | } |
| 355 | invalid, errb, err := nixStore(ctx, append([]string{"--check-validity", "--print-invalid"}, paths...)...) |
| 356 | if err != nil { |
| 357 | return nil, false, fmt.Errorf("checking the outputs of %s: %w: %s", drv, err, strings.TrimSpace(errb)) |
| 358 | } |
| 359 | return paths, strings.TrimSpace(invalid) == "", nil |
| 360 | } |
| 361 | |
| 362 | // drvInputs collects the store paths a derivation reads: the derivations |
| 363 | // it depends on and the sources it takes directly. A .drv's references are |
| 364 | // exactly that set, and `nix-store --query --references` prints them as |
| 365 | // lines — a shape that has not changed in the lifetime of nix, unlike the |
| 366 | // versioned JSON of `nix derivation show`. |
| 367 | func drvInputs(drv string) ([]string, error) { |
| 368 | out, errb, err := nixStore(context.Background(), "--query", "--references", drv) |
| 369 | if err != nil { |
| 370 | return nil, fmt.Errorf("querying the inputs of %s: %w: %s", drv, err, strings.TrimSpace(errb)) |
| 371 | } |
| 372 | inputs := strings.Fields(out) |
| 373 | if len(inputs) == 0 { |
| 374 | return nil, fmt.Errorf("%s has no inputs at all", drv) |
| 375 | } |
| 376 | return inputs, nil |
| 377 | } |
| 378 | |
| 379 | // runEffectful runs a command over the exported tree and notarizes what it |
| 380 | // observed. No digests: there is nothing to re-derive, which is exactly |
| 381 | // what the effectful predicate type says. |
| 382 | func runEffectful(tree string, spec checkSpec) checkOutcome { |
| 383 | out := checkOutcome{spec: spec, satisfied: satisfiedRan} |
| 384 | cmd := exec.Command("sh", "-c", spec.command) |
| 385 | cmd.Dir = tree |
| 386 | log, err := cmd.CombinedOutput() |
| 387 | out.log = strings.TrimSpace(string(log)) |
| 388 | out.observedAt = time.Now().UTC().Format("2006-01-02T15:04:05Z") |
| 389 | out.passed = err == nil |
| 390 | return out |
| 391 | } |