| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "fmt" |
| 6 | "io" |
| 7 | "math" |
| 8 | "os" |
| 9 | "path/filepath" |
| 10 | "strconv" |
| 11 | "syscall" |
| 12 | "time" |
| 13 | ) |
| 14 | |
| 15 | // Evaluations that share a reservations directory are admitted by a |
| 16 | // memory budget. Each attest run handed the directory makes a reservation |
| 17 | // there before it evaluates: a file named by its pid, holding its place in |
| 18 | // line and its estimate of the evaluation's peak memory. It keeps an |
| 19 | // exclusive flock on that file until its evaluation ends, and then removes |
| 20 | // the file. The evaluation's nix processes inherit the locked file |
| 21 | // (nixPeak), so the reservation is held while attest or any of them runs, |
| 22 | // and each of them is killed if attest dies. A reservation no one holds, |
| 23 | // left by a run that was killed, does not count, and neither does one |
| 24 | // whose contents are not a valid reservation: the next run to look removes |
| 25 | // it. The directory's lock file guards every look and every new |
| 26 | // reservation, so no two runs read the line while it changes. |
| 27 | // |
| 28 | // A run starts its evaluation when its estimate plus the estimates of |
| 29 | // every reservation made before it fit the budget, or when no reservation |
| 30 | // was made before it (fits). Runs that waited go first, so a large |
| 31 | // evaluation is not passed over by small ones that keep arriving. An |
| 32 | // estimate larger than the whole budget starts only at the head of the |
| 33 | // line, and no reservation made after it starts until it ends: it runs |
| 34 | // alone. A run that cannot make its reservation or read the line does not |
| 35 | // evaluate at all, so no evaluation runs without being counted. |
| 36 | |
| 37 | // admissionPoll is how often a run waiting to be admitted looks again. |
| 38 | const admissionPoll = 250 * time.Millisecond |
| 39 | |
| 40 | // reservation is one run's place in line and the memory it expects its |
| 41 | // evaluation to need. |
| 42 | type reservation struct { |
| 43 | Order int64 `json:"order"` |
| 44 | PID int `json:"pid"` |
| 45 | Estimate int64 `json:"estimate_bytes"` |
| 46 | } |
| 47 | |
| 48 | // admission is where a run's evaluation is admitted: the reservations |
| 49 | // directory, the run's estimate, and the budget every evaluation admitted |
| 50 | // there shares. |
| 51 | type admission struct { |
| 52 | dir string |
| 53 | estimate int64 |
| 54 | budget int64 |
| 55 | } |
| 56 | |
| 57 | // fits says whether the reservation mine may start its evaluation, given |
| 58 | // the other live reservations: when the estimates of those made before it, |
| 59 | // plus its own, fit the budget, or when none was made before it. The sum |
| 60 | // is never taken past the budget, so no estimate, however large, wraps it |
| 61 | // around to one that fits. |
| 62 | func fits(others []reservation, mine reservation, budget int64) bool { |
| 63 | ahead, before, over := int64(0), 0, false |
| 64 | for _, r := range others { |
| 65 | if r.Order < mine.Order { |
| 66 | before++ |
| 67 | if r.Estimate > budget-ahead { |
| 68 | over = true |
| 69 | } else { |
| 70 | ahead += r.Estimate |
| 71 | } |
| 72 | } |
| 73 | } |
| 74 | return before == 0 || !over && mine.Estimate <= budget-ahead |
| 75 | } |
| 76 | |
| 77 | // admit makes the run's reservation and waits until its evaluation fits. |
| 78 | // It returns how long it waited, the reservation's locked file, which the |
| 79 | // evaluation's nix processes inherit, and the function that removes the |
| 80 | // reservation once the evaluation ends. Without an admission it waits for |
| 81 | // nothing and holds no file. A reservation that cannot be made, or a line |
| 82 | // that cannot be read, is an error, and the run must not evaluate. |
| 83 | func admit(a *admission) (time.Duration, *os.File, func(), error) { |
| 84 | if a == nil { |
| 85 | return 0, nil, func() {}, nil |
| 86 | } |
| 87 | began := time.Now() |
| 88 | mine, held, err := reserve(a) |
| 89 | if err != nil { |
| 90 | return time.Since(began), nil, nil, fmt.Errorf("making a reservation for the evaluation in %s: %w", a.dir, err) |
| 91 | } |
| 92 | release := func() { |
| 93 | os.Remove(held.Name()) |
| 94 | held.Close() |
| 95 | } |
| 96 | for { |
| 97 | others, err := a.look(mine.PID) |
| 98 | if err != nil { |
| 99 | release() |
| 100 | return time.Since(began), nil, nil, fmt.Errorf("reading the evaluation reservations in %s: %w", a.dir, err) |
| 101 | } |
| 102 | if fits(others, mine, a.budget) { |
| 103 | break |
| 104 | } |
| 105 | time.Sleep(admissionPoll) |
| 106 | } |
| 107 | return time.Since(began), held, release, nil |
| 108 | } |
| 109 | |
| 110 | // reserve makes this run's reservation, last in line, and returns it with |
| 111 | // the file whose flock keeps it live. If a live evaluation of an earlier |
| 112 | // run with the same pid still holds that name, the file is left alone and |
| 113 | // reserve fails. |
| 114 | func reserve(a *admission) (reservation, *os.File, error) { |
| 115 | unlock, err := a.lock() |
| 116 | if err != nil { |
| 117 | return reservation{}, nil, err |
| 118 | } |
| 119 | defer unlock() |
| 120 | others, err := a.scan(os.Getpid()) |
| 121 | if err != nil { |
| 122 | return reservation{}, nil, err |
| 123 | } |
| 124 | mine := reservation{Order: 1, PID: os.Getpid(), Estimate: a.estimate} |
| 125 | for _, r := range others { |
| 126 | mine.Order = max(mine.Order, r.Order+1) |
| 127 | } |
| 128 | data, err := json.Marshal(mine) |
| 129 | if err != nil { |
| 130 | return reservation{}, nil, err |
| 131 | } |
| 132 | // The file is not truncated before the lock is held: a run killed with |
| 133 | // a nix eval still holding its reservation can leave a live one under |
| 134 | // this pid, and emptying it would make the scan drop it as stale. |
| 135 | f, err := os.OpenFile(filepath.Join(a.dir, strconv.Itoa(mine.PID)), os.O_CREATE|os.O_RDWR, 0o600) |
| 136 | if err != nil { |
| 137 | return reservation{}, nil, err |
| 138 | } |
| 139 | if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil { |
| 140 | f.Close() |
| 141 | if err == syscall.EWOULDBLOCK { |
| 142 | return reservation{}, nil, fmt.Errorf("the reservation for pid %d is held by an evaluation that is still running; it is left as it is", mine.PID) |
| 143 | } |
| 144 | return reservation{}, nil, err |
| 145 | } |
| 146 | if err := f.Truncate(0); err != nil { |
| 147 | os.Remove(f.Name()) |
| 148 | f.Close() |
| 149 | return reservation{}, nil, err |
| 150 | } |
| 151 | if _, err := f.Write(append(data, '\n')); err != nil { |
| 152 | os.Remove(f.Name()) |
| 153 | f.Close() |
| 154 | return reservation{}, nil, err |
| 155 | } |
| 156 | return mine, f, nil |
| 157 | } |
| 158 | |
| 159 | // look reads the live reservations other than pid's, under the |
| 160 | // directory's lock. |
| 161 | func (a *admission) look(pid int) ([]reservation, error) { |
| 162 | unlock, err := a.lock() |
| 163 | if err != nil { |
| 164 | return nil, err |
| 165 | } |
| 166 | defer unlock() |
| 167 | return a.scan(pid) |
| 168 | } |
| 169 | |
| 170 | // lock waits for the exclusive flock on the directory's lock file, making |
| 171 | // both if they are missing, and returns the function that releases it. |
| 172 | func (a *admission) lock() (func(), error) { |
| 173 | if err := os.MkdirAll(a.dir, 0o700); err != nil { |
| 174 | return nil, err |
| 175 | } |
| 176 | f, err := os.OpenFile(filepath.Join(a.dir, "lock"), os.O_CREATE|os.O_RDWR, 0o600) |
| 177 | if err != nil { |
| 178 | return nil, err |
| 179 | } |
| 180 | err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX) |
| 181 | for err == syscall.EINTR { |
| 182 | err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX) |
| 183 | } |
| 184 | if err != nil { |
| 185 | f.Close() |
| 186 | return nil, err |
| 187 | } |
| 188 | return func() { f.Close() }, nil |
| 189 | } |
| 190 | |
| 191 | // scan reads every reservation in the directory but pid's, and removes |
| 192 | // those that do not count: one no run holds, and one whose contents are |
| 193 | // not a valid reservation for its pid (valid). Only files named by a pid |
| 194 | // are reservations. A reservation that cannot be opened or read is an |
| 195 | // error, since it may be a running evaluation's. The caller holds the |
| 196 | // directory's lock. |
| 197 | func (a *admission) scan(pid int) ([]reservation, error) { |
| 198 | entries, err := os.ReadDir(a.dir) |
| 199 | if err != nil { |
| 200 | return nil, err |
| 201 | } |
| 202 | var live []reservation |
| 203 | for _, e := range entries { |
| 204 | n, err := strconv.Atoi(e.Name()) |
| 205 | if err != nil || n <= 0 || n == pid { |
| 206 | continue |
| 207 | } |
| 208 | path := filepath.Join(a.dir, e.Name()) |
| 209 | f, err := os.Open(path) |
| 210 | if os.IsNotExist(err) { |
| 211 | // Its run removed it since the directory was read. |
| 212 | continue |
| 213 | } |
| 214 | if err != nil { |
| 215 | return nil, err |
| 216 | } |
| 217 | if syscall.Flock(int(f.Fd()), syscall.LOCK_SH|syscall.LOCK_NB) == nil { |
| 218 | os.Remove(path) |
| 219 | f.Close() |
| 220 | continue |
| 221 | } |
| 222 | data, err := io.ReadAll(f) |
| 223 | f.Close() |
| 224 | if err != nil { |
| 225 | return nil, err |
| 226 | } |
| 227 | r, ok := valid(data, n) |
| 228 | if !ok { |
| 229 | os.Remove(path) |
| 230 | continue |
| 231 | } |
| 232 | live = append(live, r) |
| 233 | } |
| 234 | return live, nil |
| 235 | } |
| 236 | |
| 237 | // valid reads a reservation file's contents and says whether they are a |
| 238 | // reservation attest could have written for pid: its own pid, a place in |
| 239 | // line from 1 that a later reservation can still follow, and an estimate |
| 240 | // of at least one byte. Numbers too large for 64 bits do not parse. |
| 241 | func valid(data []byte, pid int) (reservation, bool) { |
| 242 | var r reservation |
| 243 | if json.Unmarshal(data, &r) != nil { |
| 244 | return reservation{}, false |
| 245 | } |
| 246 | return r, r.PID == pid && r.Order >= 1 && r.Order < math.MaxInt64 && r.Estimate >= 1 |
| 247 | } |