| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "os" |
| 6 | "os/exec" |
| 7 | "path/filepath" |
| 8 | "runtime" |
| 9 | "strconv" |
| 10 | "strings" |
| 11 | "syscall" |
| 12 | "testing" |
| 13 | "time" |
| 14 | ) |
| 15 | |
| 16 | // An evaluation starts when the reservations made before it, plus its |
| 17 | // own estimate, fit the budget, or when it is first in line. Reservations |
| 18 | // made after it never hold it back, and one made before it that still |
| 19 | // waits counts as if it ran, so runs start in the order they asked. |
| 20 | func TestFits(t *testing.T) { |
| 21 | r := func(order, estimate int64) reservation { return reservation{Order: order, Estimate: estimate} } |
| 22 | for _, c := range []struct { |
| 23 | why string |
| 24 | others []reservation |
| 25 | mine reservation |
| 26 | want bool |
| 27 | }{ |
| 28 | {"first in line", nil, r(1, 6), true}, |
| 29 | {"fits exactly beside one", []reservation{r(1, 4)}, r(2, 6), true}, |
| 30 | {"does not fit beside one", []reservation{r(1, 4)}, r(2, 7), false}, |
| 31 | {"larger than the budget, first in line, runs alone", []reservation{r(5, 1)}, r(3, 20), true}, |
| 32 | {"larger than the budget, behind another, waits", []reservation{r(1, 1)}, r(2, 20), false}, |
| 33 | {"behind one larger than the budget, waits", []reservation{r(1, 20)}, r(2, 1), false}, |
| 34 | {"reservations made later do not count", []reservation{r(4, 9), r(5, 9)}, r(3, 5), true}, |
| 35 | {"a run that waits ahead is not passed over", []reservation{r(1, 3), r(2, 8)}, r(3, 2), false}, |
| 36 | {"several fit together", []reservation{r(1, 3), r(2, 3)}, r(3, 4), true}, |
| 37 | {"huge estimates do not wrap around to fit", []reservation{r(1, 1<<62), r(2, 1<<62)}, r(3, 1<<62), false}, |
| 38 | {"a huge estimate behind a small one waits", []reservation{r(1, 1)}, r(2, 1<<63-1), false}, |
| 39 | } { |
| 40 | if got := fits(c.others, c.mine, 10); got != c.want { |
| 41 | t.Errorf("%s: fits = %v, want %v", c.why, got, c.want) |
| 42 | } |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | // hold makes a reservation file as a running attest does and keeps its |
| 47 | // flock, as another process would, until the test releases it. |
| 48 | func hold(t *testing.T, dir string, r reservation) func() { |
| 49 | t.Helper() |
| 50 | data, _ := json.Marshal(r) |
| 51 | path := filepath.Join(dir, strconv.Itoa(r.PID)) |
| 52 | if err := os.WriteFile(path, data, 0o600); err != nil { |
| 53 | t.Fatal(err) |
| 54 | } |
| 55 | f, err := os.Open(path) |
| 56 | if err != nil { |
| 57 | t.Fatal(err) |
| 58 | } |
| 59 | if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil { |
| 60 | t.Fatal(err) |
| 61 | } |
| 62 | return func() { os.Remove(path); f.Close() } |
| 63 | } |
| 64 | |
| 65 | // A reservation no running attest holds, left by one that was killed, |
| 66 | // does not count and is removed; a held one counts; files not named by a |
| 67 | // pid are not reservations. A held file that is not a valid reservation |
| 68 | // for its pid counts as stale too: its estimate or place in line is |
| 69 | // negative, too large to follow or to parse, or it names another pid. |
| 70 | func TestScanSkipsStaleReservations(t *testing.T) { |
| 71 | dir := t.TempDir() |
| 72 | stale := filepath.Join(dir, "4000001") |
| 73 | data, _ := json.Marshal(reservation{Order: 1, PID: 4000001, Estimate: 9}) |
| 74 | if err := os.WriteFile(stale, data, 0o600); err != nil { |
| 75 | t.Fatal(err) |
| 76 | } |
| 77 | if err := os.WriteFile(filepath.Join(dir, "run.peak"), []byte("7\n"), 0o600); err != nil { |
| 78 | t.Fatal(err) |
| 79 | } |
| 80 | defer hold(t, dir, reservation{Order: 2, PID: 4000002, Estimate: 3})() |
| 81 | invalid := []string{ |
| 82 | `{"order":1,"pid":4000003,"estimate_bytes":-5}`, |
| 83 | `{"order":-1,"pid":4000004,"estimate_bytes":5}`, |
| 84 | `{"order":9223372036854775807,"pid":4000005,"estimate_bytes":5}`, |
| 85 | `{"order":1,"pid":4000006,"estimate_bytes":92233720368547758070}`, |
| 86 | `{"order":1,"pid":1,"estimate_bytes":5}`, |
| 87 | `not json`, |
| 88 | } |
| 89 | for i, text := range invalid { |
| 90 | path := filepath.Join(dir, strconv.Itoa(4000003+i)) |
| 91 | if err := os.WriteFile(path, []byte(text), 0o600); err != nil { |
| 92 | t.Fatal(err) |
| 93 | } |
| 94 | f, err := os.Open(path) |
| 95 | if err != nil { |
| 96 | t.Fatal(err) |
| 97 | } |
| 98 | defer f.Close() |
| 99 | if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil { |
| 100 | t.Fatal(err) |
| 101 | } |
| 102 | } |
| 103 | a := &admission{dir: dir, estimate: 4, budget: 10} |
| 104 | live, err := a.look(os.Getpid()) |
| 105 | if err != nil { |
| 106 | t.Fatal(err) |
| 107 | } |
| 108 | if len(live) != 1 || live[0].PID != 4000002 || live[0].Estimate != 3 { |
| 109 | t.Fatalf("live reservations %+v, want only the held one", live) |
| 110 | } |
| 111 | if _, err := os.Stat(stale); !os.IsNotExist(err) { |
| 112 | t.Fatalf("the stale reservation is still there: %v", err) |
| 113 | } |
| 114 | for i := range invalid { |
| 115 | if _, err := os.Stat(filepath.Join(dir, strconv.Itoa(4000003+i))); !os.IsNotExist(err) { |
| 116 | t.Errorf("the invalid reservation %s is still there: %v", invalid[i], err) |
| 117 | } |
| 118 | } |
| 119 | } |
| 120 | |
| 121 | // A run that cannot make its reservation does not evaluate: runPure |
| 122 | // fails before it runs any nix, and before it reports any check. |
| 123 | func TestAdmissionFailureEvaluatesNothing(t *testing.T) { |
| 124 | file := filepath.Join(t.TempDir(), "file") |
| 125 | if err := os.WriteFile(file, nil, 0o600); err != nil { |
| 126 | t.Fatal(err) |
| 127 | } |
| 128 | bin := t.TempDir() |
| 129 | ran := filepath.Join(bin, "ran") |
| 130 | if err := os.WriteFile(filepath.Join(bin, "nix"), []byte("#!/bin/sh\ntouch '"+ran+"'\n"), 0o755); err != nil { |
| 131 | t.Fatal(err) |
| 132 | } |
| 133 | t.Setenv("PATH", bin+":"+os.Getenv("PATH")) |
| 134 | reported := false |
| 135 | runs, err := runPure(t.TempDir(), "x86_64-linux", []checkSpec{{name: "a", attribute: "a"}}, false, 1, "", |
| 136 | &admission{dir: filepath.Join(file, "reservations"), estimate: 1, budget: 10}, "", func(ranCheck) { reported = true }, nil) |
| 137 | if err == nil || runs != nil || reported { |
| 138 | t.Fatalf("runPure = %v, %v, reported %v; want an error and nothing run", runs, err, reported) |
| 139 | } |
| 140 | if _, err := os.Stat(ran); !os.IsNotExist(err) { |
| 141 | t.Fatalf("nix ran without a reservation: %v", err) |
| 142 | } |
| 143 | } |
| 144 | |
| 145 | // The evaluation helper is attest in TestKilledRunHoldsItsReservation: it |
| 146 | // admits an evaluation through the reservations directory it is given and |
| 147 | // evaluates one check with the nix first on PATH, which never ends. |
| 148 | func TestEvaluationHelper(t *testing.T) { |
| 149 | dir := os.Getenv("ATTEST_HELPER_RESERVATIONS") |
| 150 | if dir == "" { |
| 151 | t.Skip("run by TestKilledRunHoldsItsReservation") |
| 152 | } |
| 153 | runPure(t.TempDir(), "x86_64-linux", []checkSpec{{name: "slow", attribute: "slow"}}, false, 1, "", |
| 154 | &admission{dir: dir, estimate: 5, budget: 10}, "", nil, nil) |
| 155 | } |
| 156 | |
| 157 | // gone says whether a process has exited: it is no longer listed, or it |
| 158 | // is a zombie, which holds no files. |
| 159 | func gone(pid int) bool { |
| 160 | data, err := os.ReadFile("/proc/" + strconv.Itoa(pid) + "/stat") |
| 161 | if err != nil { |
| 162 | return true |
| 163 | } |
| 164 | fields := strings.Fields(string(data[strings.LastIndexByte(string(data), ')')+1:])) |
| 165 | return len(fields) == 0 || fields[0] == "Z" |
| 166 | } |
| 167 | |
| 168 | // A run killed during its evaluation takes its nix eval with it, and its |
| 169 | // reservation is held while any process of that evaluation still runs: |
| 170 | // here nix leaves behind a child that inherited the locked file, and the |
| 171 | // reservation counts until that child is gone too. |
| 172 | func TestKilledRunHoldsItsReservation(t *testing.T) { |
| 173 | if runtime.GOOS != "linux" { |
| 174 | t.Skip("a child is killed with its parent only on Linux") |
| 175 | } |
| 176 | dir, bin, pids := t.TempDir(), t.TempDir(), t.TempDir() |
| 177 | script := "#!/bin/sh\necho $$ > '" + pids + "/nix.new' && mv '" + pids + "/nix.new' '" + pids + "/nix'\n" + |
| 178 | "sleep 300 &\necho $! > '" + pids + "/child.new' && mv '" + pids + "/child.new' '" + pids + "/child'\nwait\n" |
| 179 | if err := os.WriteFile(filepath.Join(bin, "nix"), []byte(script), 0o755); err != nil { |
| 180 | t.Fatal(err) |
| 181 | } |
| 182 | attest := exec.Command(os.Args[0], "-test.run=^TestEvaluationHelper$") |
| 183 | attest.Env = append(os.Environ(), "ATTEST_HELPER_RESERVATIONS="+dir, "PATH="+bin+":"+os.Getenv("PATH")) |
| 184 | if err := attest.Start(); err != nil { |
| 185 | t.Fatal(err) |
| 186 | } |
| 187 | pidOf := func(name string) int { |
| 188 | for deadline := time.Now().Add(20 * time.Second); time.Now().Before(deadline); time.Sleep(20 * time.Millisecond) { |
| 189 | if text, err := os.ReadFile(filepath.Join(pids, name)); err == nil { |
| 190 | pid, _ := strconv.Atoi(strings.TrimSpace(string(text))) |
| 191 | t.Cleanup(func() { syscall.Kill(pid, syscall.SIGKILL) }) |
| 192 | return pid |
| 193 | } |
| 194 | } |
| 195 | attest.Process.Kill() |
| 196 | t.Fatalf("the evaluation's %s never started", name) |
| 197 | return 0 |
| 198 | } |
| 199 | nix, child := pidOf("nix"), pidOf("child") |
| 200 | looker := &admission{dir: dir, budget: 10} |
| 201 | held := func() bool { |
| 202 | live, err := looker.look(os.Getpid()) |
| 203 | if err != nil { |
| 204 | t.Fatal(err) |
| 205 | } |
| 206 | return len(live) == 1 && live[0].PID == attest.Process.Pid |
| 207 | } |
| 208 | if !held() { |
| 209 | t.Fatal("no reservation counts while the run evaluates") |
| 210 | } |
| 211 | |
| 212 | attest.Process.Kill() |
| 213 | attest.Wait() |
| 214 | for deadline := time.Now().Add(10 * time.Second); !gone(nix); time.Sleep(20 * time.Millisecond) { |
| 215 | if time.Now().After(deadline) { |
| 216 | t.Fatal("nix eval outlived the attest that started it") |
| 217 | } |
| 218 | } |
| 219 | if !held() { |
| 220 | t.Fatal("the reservation stopped counting while a process of the evaluation still runs") |
| 221 | } |
| 222 | |
| 223 | syscall.Kill(child, syscall.SIGKILL) |
| 224 | for deadline := time.Now().Add(10 * time.Second); held(); time.Sleep(20 * time.Millisecond) { |
| 225 | if time.Now().After(deadline) { |
| 226 | t.Fatal("the reservation still counts after every process of the evaluation is gone") |
| 227 | } |
| 228 | } |
| 229 | if _, err := os.Stat(filepath.Join(dir, strconv.Itoa(attest.Process.Pid))); !os.IsNotExist(err) { |
| 230 | t.Fatalf("the killed run's reservation was not removed: %v", err) |
| 231 | } |
| 232 | } |
| 233 | |
| 234 | // A run whose estimate does not fit beside a running evaluation waits |
| 235 | // until that evaluation's reservation goes, then starts, and its own |
| 236 | // reservation is gone once it releases it. A stale reservation ahead of |
| 237 | // it never holds it back. |
| 238 | func TestAdmitWaitsForRoom(t *testing.T) { |
| 239 | dir := t.TempDir() |
| 240 | stale, _ := json.Marshal(reservation{Order: 1, PID: 4000001, Estimate: 10}) |
| 241 | if err := os.WriteFile(filepath.Join(dir, "4000001"), stale, 0o600); err != nil { |
| 242 | t.Fatal(err) |
| 243 | } |
| 244 | release := hold(t, dir, reservation{Order: 2, PID: 4000002, Estimate: 6}) |
| 245 | go func() { |
| 246 | time.Sleep(600 * time.Millisecond) |
| 247 | release() |
| 248 | }() |
| 249 | waited, held, done, err := admit(&admission{dir: dir, estimate: 6, budget: 10}) |
| 250 | if err != nil || held == nil { |
| 251 | t.Fatalf("admit: %v, held %v", err, held) |
| 252 | } |
| 253 | if waited < 500*time.Millisecond { |
| 254 | t.Errorf("admitted after %v, before the running evaluation ended", waited) |
| 255 | } |
| 256 | mine := filepath.Join(dir, strconv.Itoa(os.Getpid())) |
| 257 | if _, err := os.Stat(mine); err != nil { |
| 258 | t.Fatalf("no reservation while evaluating: %v", err) |
| 259 | } |
| 260 | done() |
| 261 | if _, err := os.Stat(mine); !os.IsNotExist(err) { |
| 262 | t.Fatalf("the reservation outlived the evaluation: %v", err) |
| 263 | } |
| 264 | |
| 265 | // With room for both, a run starts at once beside a running one. |
| 266 | defer hold(t, dir, reservation{Order: 1, PID: 4000003, Estimate: 4})() |
| 267 | waited, _, done, err = admit(&admission{dir: dir, estimate: 6, budget: 10}) |
| 268 | if err != nil { |
| 269 | t.Fatal(err) |
| 270 | } |
| 271 | done() |
| 272 | if waited > 200*time.Millisecond { |
| 273 | t.Errorf("a run that fits waited %v", waited) |
| 274 | } |
| 275 | } |
| 276 | |
| 277 | // A reservation still held under this run's pid, by an evaluation of an |
| 278 | // earlier run with the same pid, is neither emptied nor replaced: the run |
| 279 | // fails, and the held reservation still counts. |
| 280 | func TestReserveLeavesHeldReservationAlone(t *testing.T) { |
| 281 | dir := t.TempDir() |
| 282 | held := reservation{Order: 3, PID: os.Getpid(), Estimate: 7} |
| 283 | release := hold(t, dir, held) |
| 284 | defer release() |
| 285 | path := filepath.Join(dir, strconv.Itoa(os.Getpid())) |
| 286 | before, err := os.ReadFile(path) |
| 287 | if err != nil { |
| 288 | t.Fatal(err) |
| 289 | } |
| 290 | if _, f, err := reserve(&admission{dir: dir, estimate: 1, budget: 10}); err == nil { |
| 291 | f.Close() |
| 292 | t.Fatal("reserve succeeded over a held reservation") |
| 293 | } |
| 294 | after, err := os.ReadFile(path) |
| 295 | if err != nil || string(after) != string(before) { |
| 296 | t.Fatalf("held reservation is now %q, %v; want %q", after, err, before) |
| 297 | } |
| 298 | others, err := (&admission{dir: dir}).look(os.Getpid() + 1) |
| 299 | if err != nil || len(others) != 1 || others[0] != held { |
| 300 | t.Fatalf("look = %v, %v; want the held reservation to count", others, err) |
| 301 | } |
| 302 | } |