| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "errors" |
| 6 | "fmt" |
| 7 | "os" |
| 8 | "os/exec" |
| 9 | "path/filepath" |
| 10 | "slices" |
| 11 | "strconv" |
| 12 | "strings" |
| 13 | "syscall" |
| 14 | ) |
| 15 | |
| 16 | // A batch's evaluation is admitted by memory. The pass has a budget, the |
| 17 | // memory every evaluation it runs at once may hold together, and an |
| 18 | // estimate of each evaluation's peak. Every attest it starts is handed |
| 19 | // the reservations directory evaluations/ in the state directory, the |
| 20 | // budget and its estimate, and attest admits its own evaluation there |
| 21 | // (attest/admit.go): the evaluation starts when its estimate fits the |
| 22 | // budget beside those admitted before it. |
| 23 | // |
| 24 | // The budget is --eval-budget when given. Otherwise it is --eval-share of |
| 25 | // the most memory the worker may use: the smallest memory.max of its |
| 26 | // cgroup and every ancestor, such as the build slice the worker, attest |
| 27 | // and the nix daemon share, and never more than the host's memory |
| 28 | // (memoryLimit). When that limit cannot be found, the pass has no budget: |
| 29 | // it hands each attest a budget equal to its own estimate, so each |
| 30 | // evaluation runs alone, and it says once how to give a budget. |
| 31 | // |
| 32 | // A project's estimate is the largest of the peaks its last peakHistory |
| 33 | // successful evaluations measured, as attest reports them. An evaluation |
| 34 | // that failed or was killed stopped short of its high-water mark, as one |
| 35 | // the kernel's out-of-memory killer ended did, so its peak is not kept: |
| 36 | // the project's estimate becomes unknown, and its next evaluation runs |
| 37 | // alone, until one succeeds. A project with no peak yet counts as the |
| 38 | // largest peak recorded for any project, or as the whole budget when there |
| 39 | // is none, so it evaluates alone. The record is evaluations.json in the |
| 40 | // state directory. An estimate larger than the whole budget cannot fit |
| 41 | // beside anything, so that evaluation runs alone, and the pass reports it |
| 42 | // for each such batch. |
| 43 | |
| 44 | // defaultEvalShare is the share of the worker's memory limit its |
| 45 | // evaluations get together when neither --eval-budget nor --eval-share |
| 46 | // says: the host module's own default. The rest is left to the builds of |
| 47 | // the batches that are past their evaluations, to the nix daemon and to |
| 48 | // the worker itself. |
| 49 | const defaultEvalShare = 0.6 |
| 50 | |
| 51 | // peakHistory is how many of a project's latest evaluation peaks its |
| 52 | // estimate is the largest of. |
| 53 | const peakHistory = 5 |
| 54 | |
| 55 | // evaluations is a pass's evaluation budget and its record of peaks. |
| 56 | type evaluations struct { |
| 57 | dir string // the reservations directory attest admits evaluations through |
| 58 | path string // the record of peaks |
| 59 | budget int64 // the memory the evaluations running at once may hold together, in bytes, or 0 when none was found |
| 60 | source string // where the budget came from, or why none was found, for a report |
| 61 | peaks peakRecord |
| 62 | } |
| 63 | |
| 64 | // peakRecord is evaluations.json: each project's latest successful |
| 65 | // evaluation peaks, in bytes, oldest first, and the projects whose latest |
| 66 | // evaluation failed or was killed, whose estimate is unknown. |
| 67 | type peakRecord struct { |
| 68 | Projects map[string][]int64 `json:"projects"` |
| 69 | Unknown map[string]bool `json:"unknown,omitempty"` |
| 70 | } |
| 71 | |
| 72 | // openEvaluations works out the pass's budget and reads the record of |
| 73 | // peaks under state. A budget of 0 means none was given, and share of the |
| 74 | // worker's memory limit is used; when that limit cannot be found, the |
| 75 | // pass's budget is 0 and its source says why. Peak files a killed pass left behind are |
| 76 | // removed: no attest of an earlier pass runs once this one holds the |
| 77 | // state directory's lock. |
| 78 | func openEvaluations(state string, budget int64, share float64) (*evaluations, error) { |
| 79 | e := &evaluations{dir: filepath.Join(state, "evaluations"), path: filepath.Join(state, "evaluations.json")} |
| 80 | if err := os.MkdirAll(e.dir, 0o700); err != nil { |
| 81 | return nil, err |
| 82 | } |
| 83 | if left, err := filepath.Glob(filepath.Join(e.dir, "*.peak")); err == nil { |
| 84 | for _, f := range left { |
| 85 | os.Remove(f) |
| 86 | } |
| 87 | } |
| 88 | e.budget, e.source = budget, "--eval-budget" |
| 89 | if budget == 0 { |
| 90 | limit, of, err := memoryLimit() |
| 91 | if err != nil { |
| 92 | e.budget, e.source = 0, err.Error() |
| 93 | } else { |
| 94 | e.budget = int64(float64(limit) * share) |
| 95 | e.source = fmt.Sprintf("%s of %s, %s", strconv.FormatFloat(share, 'f', -1, 64), of, bytesText(limit)) |
| 96 | if e.budget < 1 { |
| 97 | return nil, fmt.Errorf("an evaluation budget of %d bytes holds no evaluation; give --eval-budget", e.budget) |
| 98 | } |
| 99 | } |
| 100 | } else if e.budget < 1 { |
| 101 | return nil, fmt.Errorf("an evaluation budget of %d bytes holds no evaluation; give --eval-budget", e.budget) |
| 102 | } |
| 103 | if data, err := os.ReadFile(e.path); err == nil { |
| 104 | json.Unmarshal(data, &e.peaks) |
| 105 | } |
| 106 | if e.peaks.Projects == nil { |
| 107 | e.peaks.Projects = map[string][]int64{} |
| 108 | } |
| 109 | if e.peaks.Unknown == nil { |
| 110 | e.peaks.Unknown = map[string]bool{} |
| 111 | } |
| 112 | return e, nil |
| 113 | } |
| 114 | |
| 115 | // estimate is the peak memory a project's next evaluation is expected to |
| 116 | // need, in bytes, and never less than one. A project whose estimate is |
| 117 | // unknown counts as the whole budget, or its own largest peak when that |
| 118 | // is more, so it evaluates alone. |
| 119 | func (e *evaluations) estimate(project string) int64 { |
| 120 | largest := func(peaks []int64) int64 { |
| 121 | var m int64 |
| 122 | for _, p := range peaks { |
| 123 | m = max(m, p) |
| 124 | } |
| 125 | return m |
| 126 | } |
| 127 | own := largest(e.peaks.Projects[project]) |
| 128 | if e.peaks.Unknown[project] { |
| 129 | return max(own, e.budget, 1) |
| 130 | } |
| 131 | if own > 0 { |
| 132 | return own |
| 133 | } |
| 134 | var m int64 |
| 135 | for _, peaks := range e.peaks.Projects { |
| 136 | m = max(m, largest(peaks)) |
| 137 | } |
| 138 | if m == 0 { |
| 139 | return max(e.budget, 1) |
| 140 | } |
| 141 | return m |
| 142 | } |
| 143 | |
| 144 | // handed is the budget a batch's attest is handed beside estimate: the |
| 145 | // pass's budget, or, when none was found, the estimate itself, so the |
| 146 | // evaluation fits only when no other is admitted before it. |
| 147 | func (e *evaluations) handed(estimate int64) int64 { |
| 148 | if e.budget == 0 { |
| 149 | return estimate |
| 150 | } |
| 151 | return e.budget |
| 152 | } |
| 153 | |
| 154 | // record keeps what a project's evaluation measured, as attest reported |
| 155 | // it, and writes the record. A peak counts only when the evaluation's |
| 156 | // outcome is "ok". Any other outcome, such as "failed" or "killed", |
| 157 | // makes the project's estimate unknown until an evaluation succeeds. An |
| 158 | // ok evaluation that measured nothing changes nothing. It reports why the |
| 159 | // record could not be written. |
| 160 | func (e *evaluations) record(project string, peak int64, outcome string) error { |
| 161 | switch { |
| 162 | case outcome == "ok" && peak > 0: |
| 163 | peaks := append(e.peaks.Projects[project], peak) |
| 164 | if len(peaks) > peakHistory { |
| 165 | peaks = peaks[len(peaks)-peakHistory:] |
| 166 | } |
| 167 | e.peaks.Projects[project] = peaks |
| 168 | delete(e.peaks.Unknown, project) |
| 169 | case outcome == "ok": |
| 170 | return nil |
| 171 | default: |
| 172 | e.peaks.Unknown[project] = true |
| 173 | } |
| 174 | data, err := json.MarshalIndent(e.peaks, "", " ") |
| 175 | if err != nil { |
| 176 | return err |
| 177 | } |
| 178 | tmp := e.path + ".new" |
| 179 | if err := os.WriteFile(tmp, append(data, '\n'), 0o600); err != nil { |
| 180 | return err |
| 181 | } |
| 182 | return os.Rename(tmp, e.path) |
| 183 | } |
| 184 | |
| 185 | // readPeak reads the file attest run --eval-peak wrote: the evaluation's |
| 186 | // peak in bytes and its outcome, on one line. Anything else says nothing. |
| 187 | func readPeak(text string) (int64, string) { |
| 188 | fields := strings.Fields(text) |
| 189 | if len(fields) != 2 { |
| 190 | return 0, "" |
| 191 | } |
| 192 | n, err := strconv.ParseInt(fields[0], 10, 64) |
| 193 | if err != nil || n < 0 { |
| 194 | return 0, "" |
| 195 | } |
| 196 | return n, fields[1] |
| 197 | } |
| 198 | |
| 199 | // endedBySignal says whether a process's error is that a signal ended it. |
| 200 | func endedBySignal(err error) bool { |
| 201 | var exit *exec.ExitError |
| 202 | if !errors.As(err, &exit) { |
| 203 | return false |
| 204 | } |
| 205 | ws, ok := exit.Sys().(syscall.WaitStatus) |
| 206 | return ok && ws.Signaled() |
| 207 | } |
| 208 | |
| 209 | // memoryLimit is the most memory this process may use, in bytes, and what |
| 210 | // sets it: the smallest memory.max of its cgroup and every ancestor up to |
| 211 | // the root of the cgroup2 mount, and never more than the host's memory. It |
| 212 | // finds the mount in /proc/self/mountinfo and the cgroup in |
| 213 | // /proc/self/cgroup (cgroupDir). An error says why the limit could not be |
| 214 | // found: a file it needs is missing or unreadable, no cgroup2 mount holds |
| 215 | // the process's cgroup, or a memory.max is unreadable or says neither a |
| 216 | // number nor "max". A memory.max that is missing is no limit: the root |
| 217 | // cgroup has none, and neither has a cgroup whose parent does not enable |
| 218 | // the memory controller for it. |
| 219 | func memoryLimit() (int64, string, error) { |
| 220 | host, err := hostMemory() |
| 221 | if err != nil { |
| 222 | return 0, "", fmt.Errorf("the host's memory could not be read: %v", err) |
| 223 | } |
| 224 | cgroup, err := os.ReadFile("/proc/self/cgroup") |
| 225 | if err != nil { |
| 226 | return 0, "", fmt.Errorf("the worker's cgroup could not be read: %v", err) |
| 227 | } |
| 228 | mountinfo, err := os.ReadFile("/proc/self/mountinfo") |
| 229 | if err != nil { |
| 230 | return 0, "", fmt.Errorf("the mounts could not be read: %v", err) |
| 231 | } |
| 232 | dir, top, path, err := cgroupDir(string(cgroup), string(mountinfo)) |
| 233 | if err != nil { |
| 234 | return 0, "", err |
| 235 | } |
| 236 | return cgroupLimit(dir, top, path, host) |
| 237 | } |
| 238 | |
| 239 | // cgroupLimit is the smallest memory.max of the cgroup directory dir, at |
| 240 | // path in the hierarchy, and of each ancestor up to top, and never more |
| 241 | // than host, the host's memory; and what sets it. |
| 242 | func cgroupLimit(dir, top, path string, host int64) (int64, string, error) { |
| 243 | limit, of := host, "the host's memory" |
| 244 | for { |
| 245 | file := filepath.Join(dir, "memory.max") |
| 246 | text, err := os.ReadFile(file) |
| 247 | value := strings.TrimSpace(string(text)) |
| 248 | n, perr := strconv.ParseInt(value, 10, 64) |
| 249 | switch { |
| 250 | case os.IsNotExist(err), err == nil && value == "max": |
| 251 | case err != nil: |
| 252 | return 0, "", fmt.Errorf("%s could not be read: %v", file, err) |
| 253 | case perr != nil || n < 0: |
| 254 | return 0, "", fmt.Errorf("%s says %q, neither a number of bytes nor max", file, value) |
| 255 | case n < limit: |
| 256 | limit, of = n, "the memory.max of the cgroup "+path |
| 257 | } |
| 258 | if dir == top { |
| 259 | return limit, of, nil |
| 260 | } |
| 261 | dir, path = filepath.Dir(dir), filepath.Dir(path) |
| 262 | } |
| 263 | } |
| 264 | |
| 265 | // cgroupDir finds this process's cgroup directory from the contents of |
| 266 | // /proc/self/cgroup and /proc/self/mountinfo: the cgroup2 mount whose root |
| 267 | // holds the cgroup's path, and the cgroup's directory under it. It |
| 268 | // returns that directory, the mount point, which is the last ancestor |
| 269 | // whose memory.max can be read, and the cgroup's path. |
| 270 | func cgroupDir(cgroup, mountinfo string) (dir, top, path string, err error) { |
| 271 | for _, line := range strings.Split(cgroup, "\n") { |
| 272 | if p, ok := strings.CutPrefix(line, "0::"); ok { |
| 273 | path = p |
| 274 | } |
| 275 | } |
| 276 | if !strings.HasPrefix(path, "/") || slices.Contains(strings.Split(path, "/"), "..") { |
| 277 | return "", "", "", fmt.Errorf("/proc/self/cgroup names no cgroup2 cgroup for the worker that it can see") |
| 278 | } |
| 279 | path = filepath.Clean(path) |
| 280 | for _, line := range strings.Split(mountinfo, "\n") { |
| 281 | // A line is: id, parent, device, root, mount point, options, |
| 282 | // optional fields, "-", file system type, source, options. |
| 283 | fields := strings.Fields(line) |
| 284 | sep := slices.Index(fields, "-") |
| 285 | if sep < 6 || sep+1 >= len(fields) || fields[sep+1] != "cgroup2" { |
| 286 | continue |
| 287 | } |
| 288 | root, point := unescapeMount(fields[3]), unescapeMount(fields[4]) |
| 289 | rel, ok := strings.CutPrefix(path, root) |
| 290 | if root == "/" { |
| 291 | rel, ok = path, true |
| 292 | } |
| 293 | if !ok || rel != "" && !strings.HasPrefix(rel, "/") { |
| 294 | continue |
| 295 | } |
| 296 | return filepath.Join(point, rel), point, path, nil |
| 297 | } |
| 298 | return "", "", "", fmt.Errorf("no cgroup2 mount in /proc/self/mountinfo holds the worker's cgroup %s", path) |
| 299 | } |
| 300 | |
| 301 | // unescapeMount undoes mountinfo's escapes: a space, tab, newline or |
| 302 | // backslash in a path is written as a backslash and three octal digits. |
| 303 | func unescapeMount(s string) string { |
| 304 | var b strings.Builder |
| 305 | for i := 0; i < len(s); i++ { |
| 306 | if s[i] == '\\' && i+3 < len(s) { |
| 307 | if n, err := strconv.ParseUint(s[i+1:i+4], 8, 8); err == nil { |
| 308 | b.WriteByte(byte(n)) |
| 309 | i += 3 |
| 310 | continue |
| 311 | } |
| 312 | } |
| 313 | b.WriteByte(s[i]) |
| 314 | } |
| 315 | return b.String() |
| 316 | } |
| 317 | |
| 318 | // parseSize reads a size in bytes as systemd's MemoryMax does: a whole |
| 319 | // number, optionally followed by K, M, G or T for powers of 1024. |
| 320 | func parseSize(text string) (int64, error) { |
| 321 | shift := 0 |
| 322 | if i := strings.IndexAny(text, "KMGT"); i >= 0 && i == len(text)-1 { |
| 323 | shift = 10 * (1 + strings.IndexByte("KMGT", text[i])) |
| 324 | text = text[:i] |
| 325 | } |
| 326 | n, err := strconv.ParseInt(text, 10, 64) |
| 327 | if err != nil || n < 1 || n > (1<<62)>>shift { |
| 328 | return 0, fmt.Errorf("not a size, such as 12G or 512M") |
| 329 | } |
| 330 | return n << shift, nil |
| 331 | } |
| 332 | |
| 333 | // bytesText says a number of bytes in GiB or MiB. |
| 334 | func bytesText(n int64) string { |
| 335 | if n >= 1<<30 { |
| 336 | return fmt.Sprintf("%.1f GiB", float64(n)/(1<<30)) |
| 337 | } |
| 338 | return fmt.Sprintf("%.0f MiB", float64(n)/(1<<20)) |
| 339 | } |