| 1 | #!/usr/bin/env python3 |
| 2 | """Run one command while holding one of this machine's Codewhale build slots. |
| 3 | |
| 4 | scripts/build-lock.py <lock-file> -- <command> [args...] |
| 5 | |
| 6 | Several agents share one checkout and one machine. Cargo's own lock is per |
| 7 | target directory, so builds into different target dirs still run concurrently |
| 8 | and can exhaust memory. This holds an exclusive flock on one of |
| 9 | CODEWHALE_BUILD_SLOTS lock files (default 2: `<lock-file>`, `<lock-file>.1`, |
| 10 | ...) under the persistent cache root for the lifetime of the command, and says |
| 11 | who holds every slot while waiting. Slot 0 is `<lock-file>` itself, so an older |
| 12 | single-slot copy of this script still excludes the build in that slot. |
| 13 | |
| 14 | The command runs as a child, never via exec: a daemon it spawns (an sccache |
| 15 | server, say) must not inherit the descriptor and pin the lock after the build |
| 16 | exits. Nested invocations see CODEWHALE_BUILD_LOCK_HELD and run unlocked. |
| 17 | |
| 18 | Known limitation: advisory only. Cargo started outside scripts/dev-cargo.sh |
| 19 | does not take the lock, and on a platform without fcntl (Windows) the |
| 20 | command runs unlocked after a warning. |
| 21 | """ |
| 22 | |
| 23 | import os |
| 24 | import signal |
| 25 | import subprocess |
| 26 | import sys |
| 27 | import tempfile |
| 28 | import time |
| 29 | |
| 30 | |
| 31 | META_ONLY_VALUE_FLAGS = {"--manifest-path"} |
| 32 | META_BUILD_VALUE_FLAGS = {"-Z"} |
| 33 | META_BUILD_RUN_VALUE_FLAGS = {"--config"} |
| 34 | META_BUILD_BOOL_FLAGS = {"--frozen", "--locked", "--offline"} |
| 35 | BUILD_ONLY_VALUE_FLAGS = { |
| 36 | "-p", |
| 37 | "--package", |
| 38 | "--exclude", |
| 39 | "--bin", |
| 40 | "--example", |
| 41 | "--test", |
| 42 | "--bench", |
| 43 | "-F", |
| 44 | "--features", |
| 45 | "--build-jobs", |
| 46 | "--cargo-profile", |
| 47 | "--target", |
| 48 | "--target-dir", |
| 49 | } |
| 50 | BUILD_ONLY_BOOL_FLAGS = { |
| 51 | "--workspace", |
| 52 | "--all", |
| 53 | "--lib", |
| 54 | "--bins", |
| 55 | "--examples", |
| 56 | "--tests", |
| 57 | "--benches", |
| 58 | "--all-targets", |
| 59 | "--all-features", |
| 60 | "--no-default-features", |
| 61 | "-r", |
| 62 | "--release", |
| 63 | "--cargo-quiet", |
| 64 | "--cargo-verbose", |
| 65 | "--ignore-rust-version", |
| 66 | "--future-incompat-report", |
| 67 | } |
| 68 | BUILD_RUN_VALUE_FLAGS = { |
| 69 | "-P", |
| 70 | "--profile", |
| 71 | "--config-file", |
| 72 | "--user-config-file", |
| 73 | "--tool-config-file", |
| 74 | "--color", |
| 75 | } |
| 76 | BUILD_RUN_BOOL_FLAGS = {"--no-pager", "-v", "--verbose"} |
| 77 | RUN_ONLY_VALUE_FLAGS = { |
| 78 | "-E", |
| 79 | "--filterset", |
| 80 | "--run-ignored", |
| 81 | "--partition", |
| 82 | "--platform-filter", |
| 83 | "-j", |
| 84 | "--test-threads", |
| 85 | "--jobs", |
| 86 | "--retries", |
| 87 | "--flaky-result", |
| 88 | "--status-level", |
| 89 | "--final-status-level", |
| 90 | "--failure-output", |
| 91 | "--success-output", |
| 92 | "--max-fail", |
| 93 | "--message-format", |
| 94 | "--message-format-version", |
| 95 | "--no-tests", |
| 96 | "--show-progress", |
| 97 | "--workspace-remap", |
| 98 | "--target-dir-remap", |
| 99 | "--build-dir-remap", |
| 100 | } |
| 101 | RUN_ONLY_BOOL_FLAGS = { |
| 102 | "--ignore-default-filter", |
| 103 | "--fail-fast", |
| 104 | "--no-fail-fast", |
| 105 | "--no-capture", |
| 106 | "--nocapture", |
| 107 | "--hide-progress-bar", |
| 108 | } |
| 109 | REUSE_FLAGS = {"--archive-file", "--binaries-metadata", "--cargo-metadata"} |
| 110 | SHORT_VALUE_FLAGS = {"-p", "-F", "-P", "-E", "-j", "-Z"} |
| 111 | |
| 112 | |
| 113 | def run_child(command, env=None, stdout=None) -> int: |
| 114 | use_pgrp = os.name == "posix" |
| 115 | child = subprocess.Popen( |
| 116 | command, |
| 117 | env=env, |
| 118 | stdout=stdout, |
| 119 | start_new_session=use_pgrp, |
| 120 | ) |
| 121 | previous = {} |
| 122 | |
| 123 | def forward_signal(signum, _frame): |
| 124 | try: |
| 125 | if use_pgrp: |
| 126 | os.killpg(child.pid, signum) |
| 127 | else: |
| 128 | child.send_signal(signum) |
| 129 | except ProcessLookupError: |
| 130 | pass |
| 131 | |
| 132 | signals = [signal.SIGTERM, signal.SIGINT] |
| 133 | if hasattr(signal, "SIGHUP"): |
| 134 | signals.append(signal.SIGHUP) |
| 135 | for forwarded in signals: |
| 136 | previous[forwarded] = signal.signal(forwarded, forward_signal) |
| 137 | try: |
| 138 | status = child.wait() |
| 139 | finally: |
| 140 | for forwarded, handler in previous.items(): |
| 141 | signal.signal(forwarded, handler) |
| 142 | return 128 - status if status < 0 else status |
| 143 | |
| 144 | |
| 145 | def acquire_lock(lock_path: str, command: list[str]): |
| 146 | try: |
| 147 | import fcntl |
| 148 | except ImportError: |
| 149 | print( |
| 150 | "build-lock: fcntl unavailable; running without the machine build lock", |
| 151 | file=sys.stderr, |
| 152 | ) |
| 153 | return None |
| 154 | |
| 155 | try: |
| 156 | slots = max(1, int(os.environ.get("CODEWHALE_BUILD_SLOTS", "2"))) |
| 157 | except ValueError: |
| 158 | print("build-lock: CODEWHALE_BUILD_SLOTS must be a positive integer", file=sys.stderr) |
| 159 | sys.exit(2) |
| 160 | os.makedirs(os.path.dirname(lock_path) or ".", exist_ok=True) |
| 161 | fds = [ |
| 162 | os.open(lock_path if slot == 0 else f"{lock_path}.{slot}", os.O_RDWR | os.O_CREAT, 0o600) |
| 163 | for slot in range(slots) |
| 164 | ] |
| 165 | |
| 166 | def try_slots(): |
| 167 | for slot_fd in fds: |
| 168 | try: |
| 169 | fcntl.flock(slot_fd, fcntl.LOCK_EX | fcntl.LOCK_NB) |
| 170 | return slot_fd |
| 171 | except BlockingIOError: |
| 172 | continue |
| 173 | return None |
| 174 | |
| 175 | fd = try_slots() |
| 176 | if fd is None: |
| 177 | holders = "; ".join( |
| 178 | os.pread(slot_fd, 512, 0).decode(errors="replace").strip() or "holder unknown" |
| 179 | for slot_fd in fds |
| 180 | ) |
| 181 | print( |
| 182 | f"build-lock: all {slots} build slots are busy ({holders}); " |
| 183 | "set CODEWHALE_BUILD_LOCK=0 to skip", |
| 184 | file=sys.stderr, |
| 185 | flush=True, |
| 186 | ) |
| 187 | started = time.monotonic() |
| 188 | while fd is None: |
| 189 | time.sleep(1) |
| 190 | fd = try_slots() |
| 191 | print( |
| 192 | f"build-lock: acquired after {time.monotonic() - started:.0f}s", |
| 193 | file=sys.stderr, |
| 194 | flush=True, |
| 195 | ) |
| 196 | for slot_fd in fds: |
| 197 | if slot_fd != fd: |
| 198 | os.close(slot_fd) |
| 199 | os.ftruncate(fd, 0) |
| 200 | summary = " ".join(command[:5]) |
| 201 | os.pwrite(fd, f"pid {os.getpid()} in {os.getcwd()}: {summary}\n".encode(), 0) |
| 202 | return fd |
| 203 | |
| 204 | |
| 205 | def insert_no_run(command: list[str]) -> list[str]: |
| 206 | if "--" in command: |
| 207 | idx = command.index("--") |
| 208 | return command[:idx] + ["--no-run"] + command[idx:] |
| 209 | return command + ["--no-run"] |
| 210 | |
| 211 | |
| 212 | def split_nextest_run_args(command: list[str]): |
| 213 | if len(command) < 3: |
| 214 | return ("fallback", None) |
| 215 | cargo_bin = command[0] |
| 216 | idx = 1 |
| 217 | toolchain = [] |
| 218 | if idx < len(command) and command[idx].startswith("+"): |
| 219 | toolchain = [command[idx]] |
| 220 | idx += 1 |
| 221 | if idx + 1 >= len(command) or command[idx] != "nextest" or command[idx + 1] not in ("run", "r"): |
| 222 | return ("fallback", None) |
| 223 | subcmd = command[idx + 1] |
| 224 | rest = command[idx + 2 :] |
| 225 | |
| 226 | meta_args = [] |
| 227 | build_args = [] |
| 228 | run_args = [] |
| 229 | |
| 230 | i = 0 |
| 231 | while i < len(rest): |
| 232 | arg = rest[i] |
| 233 | if arg == "--": |
| 234 | run_args.extend(rest[i:]) |
| 235 | break |
| 236 | if not arg.startswith("-") or arg == "-": |
| 237 | run_args.append(arg) |
| 238 | i += 1 |
| 239 | continue |
| 240 | |
| 241 | if "=" in arg: |
| 242 | flag, value = arg.split("=", 1) |
| 243 | pair = [arg] |
| 244 | if flag in REUSE_FLAGS: |
| 245 | return ("reuse", None) |
| 246 | if flag == "--timings": |
| 247 | build_args.append(arg) |
| 248 | i += 1 |
| 249 | continue |
| 250 | if flag in META_ONLY_VALUE_FLAGS: |
| 251 | meta_args.extend(pair) |
| 252 | elif flag in META_BUILD_VALUE_FLAGS: |
| 253 | meta_args.extend(pair) |
| 254 | build_args.extend(pair) |
| 255 | elif flag in META_BUILD_RUN_VALUE_FLAGS: |
| 256 | meta_args.extend(pair) |
| 257 | build_args.extend(pair) |
| 258 | run_args.extend(pair) |
| 259 | elif flag in BUILD_ONLY_VALUE_FLAGS: |
| 260 | build_args.extend(pair) |
| 261 | elif flag in BUILD_RUN_VALUE_FLAGS: |
| 262 | build_args.extend(pair) |
| 263 | run_args.extend(pair) |
| 264 | elif flag in RUN_ONLY_VALUE_FLAGS: |
| 265 | run_args.extend(pair) |
| 266 | else: |
| 267 | return ("fallback", None) |
| 268 | i += 1 |
| 269 | continue |
| 270 | |
| 271 | if arg in REUSE_FLAGS: |
| 272 | return ("reuse", None) |
| 273 | if arg == "--timings": |
| 274 | build_args.append(arg) |
| 275 | i += 1 |
| 276 | continue |
| 277 | if arg in META_BUILD_BOOL_FLAGS: |
| 278 | meta_args.append(arg) |
| 279 | build_args.append(arg) |
| 280 | i += 1 |
| 281 | continue |
| 282 | if arg in BUILD_ONLY_BOOL_FLAGS: |
| 283 | build_args.append(arg) |
| 284 | i += 1 |
| 285 | continue |
| 286 | if arg in BUILD_RUN_BOOL_FLAGS: |
| 287 | build_args.append(arg) |
| 288 | run_args.append(arg) |
| 289 | i += 1 |
| 290 | continue |
| 291 | if arg in RUN_ONLY_BOOL_FLAGS: |
| 292 | run_args.append(arg) |
| 293 | i += 1 |
| 294 | continue |
| 295 | |
| 296 | short_attached = None |
| 297 | if len(arg) > 2 and arg[:2] in SHORT_VALUE_FLAGS: |
| 298 | short_attached = arg[:2] |
| 299 | |
| 300 | flag = short_attached or arg |
| 301 | if short_attached is not None: |
| 302 | pair = [arg] |
| 303 | step = 1 |
| 304 | elif ( |
| 305 | flag in META_ONLY_VALUE_FLAGS |
| 306 | or flag in META_BUILD_VALUE_FLAGS |
| 307 | or flag in META_BUILD_RUN_VALUE_FLAGS |
| 308 | or flag in BUILD_ONLY_VALUE_FLAGS |
| 309 | or flag in BUILD_RUN_VALUE_FLAGS |
| 310 | or flag in RUN_ONLY_VALUE_FLAGS |
| 311 | ): |
| 312 | if i + 1 >= len(rest): |
| 313 | return ("fallback", None) |
| 314 | pair = [arg, rest[i + 1]] |
| 315 | step = 2 |
| 316 | else: |
| 317 | return ("fallback", None) |
| 318 | |
| 319 | if flag in META_ONLY_VALUE_FLAGS: |
| 320 | meta_args.extend(pair) |
| 321 | elif flag in META_BUILD_VALUE_FLAGS: |
| 322 | meta_args.extend(pair) |
| 323 | build_args.extend(pair) |
| 324 | elif flag in META_BUILD_RUN_VALUE_FLAGS: |
| 325 | meta_args.extend(pair) |
| 326 | build_args.extend(pair) |
| 327 | run_args.extend(pair) |
| 328 | elif flag in BUILD_ONLY_VALUE_FLAGS: |
| 329 | build_args.extend(pair) |
| 330 | elif flag in BUILD_RUN_VALUE_FLAGS: |
| 331 | build_args.extend(pair) |
| 332 | run_args.extend(pair) |
| 333 | elif flag in RUN_ONLY_VALUE_FLAGS: |
| 334 | run_args.extend(pair) |
| 335 | i += step |
| 336 | |
| 337 | return ("split", (cargo_bin, toolchain, subcmd, meta_args, build_args, run_args)) |
| 338 | |
| 339 | |
| 340 | def run_nextest_split(lock_path: str, command: list[str]) -> int: |
| 341 | kind, parts = split_nextest_run_args(command) |
| 342 | unlocked_env = dict(os.environ, CARGOWHALE="off") |
| 343 | unlocked_env.pop("CODEWHALE_BUILD_LOCK_HELD", None) |
| 344 | |
| 345 | if kind == "reuse": |
| 346 | return run_child(command, env=unlocked_env) |
| 347 | |
| 348 | locked_env = dict(os.environ, CARGOWHALE="off", CODEWHALE_BUILD_LOCK_HELD="1") |
| 349 | if kind == "fallback": |
| 350 | compile_cmd = insert_no_run(command) |
| 351 | fd = acquire_lock(lock_path, compile_cmd) |
| 352 | try: |
| 353 | rc = run_child(compile_cmd, env=locked_env) |
| 354 | finally: |
| 355 | if fd is not None: |
| 356 | os.close(fd) |
| 357 | if rc != 0: |
| 358 | return rc |
| 359 | return run_child(command, env=unlocked_env) |
| 360 | |
| 361 | cargo_bin, toolchain, subcmd, meta_args, build_args, run_args = parts |
| 362 | with tempfile.TemporaryDirectory(prefix="cw-nextest-") as tmp_dir: |
| 363 | meta_path = os.path.join(tmp_dir, "cargo-metadata.json") |
| 364 | bins_path = os.path.join(tmp_dir, "binaries-metadata.json") |
| 365 | meta_cmd = [cargo_bin, *toolchain, "metadata", "--format-version", "1", *meta_args] |
| 366 | list_cmd = [ |
| 367 | cargo_bin, |
| 368 | *toolchain, |
| 369 | "nextest", |
| 370 | "list", |
| 371 | "--list-type", |
| 372 | "binaries-only", |
| 373 | "--message-format", |
| 374 | "json", |
| 375 | "--cargo-metadata", |
| 376 | meta_path, |
| 377 | *build_args, |
| 378 | ] |
| 379 | run_cmd = [ |
| 380 | cargo_bin, |
| 381 | *toolchain, |
| 382 | "nextest", |
| 383 | subcmd, |
| 384 | "--cargo-metadata", |
| 385 | meta_path, |
| 386 | "--binaries-metadata", |
| 387 | bins_path, |
| 388 | *run_args, |
| 389 | ] |
| 390 | fd = acquire_lock(lock_path, list_cmd) |
| 391 | try: |
| 392 | with open(meta_path, "wb") as meta_file: |
| 393 | rc = run_child(meta_cmd, env=locked_env, stdout=meta_file) |
| 394 | if rc != 0: |
| 395 | return rc |
| 396 | with open(bins_path, "wb") as bins_file: |
| 397 | rc = run_child(list_cmd, env=locked_env, stdout=bins_file) |
| 398 | if rc != 0: |
| 399 | return rc |
| 400 | finally: |
| 401 | if fd is not None: |
| 402 | os.close(fd) |
| 403 | return run_child(run_cmd, env=unlocked_env) |
| 404 | |
| 405 | |
| 406 | def main() -> int: |
| 407 | nextest_split = False |
| 408 | argv = sys.argv[1:] |
| 409 | if argv and argv[0] == "--nextest-split": |
| 410 | nextest_split = True |
| 411 | argv = argv[1:] |
| 412 | if len(argv) < 3 or argv[1] != "--": |
| 413 | print( |
| 414 | "usage: build-lock.py [--nextest-split] <lock-file> -- <command> [args...]", |
| 415 | file=sys.stderr, |
| 416 | ) |
| 417 | return 2 |
| 418 | lock_path, command = argv[0], argv[2:] |
| 419 | if os.environ.get("CODEWHALE_BUILD_LOCK_HELD") or os.environ.get( |
| 420 | "CODEWHALE_BUILD_LOCK", "1" |
| 421 | ) in ("0", "false", "no", "off", "never", "disabled"): |
| 422 | return run_child(command) |
| 423 | if nextest_split: |
| 424 | return run_nextest_split(lock_path, command) |
| 425 | env = dict(os.environ, CODEWHALE_BUILD_LOCK_HELD="1") |
| 426 | fd = acquire_lock(lock_path, command) |
| 427 | try: |
| 428 | return run_child(command, env=env) |
| 429 | finally: |
| 430 | if fd is not None: |
| 431 | os.close(fd) |
| 432 | |
| 433 | |
| 434 | if __name__ == "__main__": |
| 435 | sys.exit(main()) |
| 436 |