Peter Wen | b1f3b1d | 2021-02-02 21:30:20 | [diff] [blame] | 1 | #!/usr/bin/env python3 |
Avi Drissman | 73a09d1 | 2022-09-08 20:33:38 | [diff] [blame] | 2 | # Copyright 2021 The Chromium Authors |
Peter Wen | b1f3b1d | 2021-02-02 21:30:20 | [diff] [blame] | 3 | # Use of this source code is governed by a BSD-style license that can be |
| 4 | # found in the LICENSE file. |
| 5 | """Creates an server to offload non-critical-path GN targets.""" |
| 6 | |
Peter Wen | cd460ff5 | 2021-02-23 22:40:05 | [diff] [blame] | 7 | from __future__ import annotations |
| 8 | |
Peter Wen | b1f3b1d | 2021-02-02 21:30:20 | [diff] [blame] | 9 | import argparse |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 10 | import collections |
| 11 | import contextlib |
Andrew Grieve | 0d6e8a75 | 2025-02-05 21:20:50 | [diff] [blame^] | 12 | import dataclasses |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 13 | import datetime |
Peter Wen | b1f3b1d | 2021-02-02 21:30:20 | [diff] [blame] | 14 | import os |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 15 | import pathlib |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 16 | import re |
Mohamed Heikal | abf646e | 2024-12-12 16:06:05 | [diff] [blame] | 17 | import signal |
Andrew Grieve | d863d0f | 2024-12-13 20:13:01 | [diff] [blame] | 18 | import shlex |
Peter Wen | 6e7e52b | 2021-02-13 02:39:28 | [diff] [blame] | 19 | import shutil |
Peter Wen | b1f3b1d | 2021-02-02 21:30:20 | [diff] [blame] | 20 | import socket |
| 21 | import subprocess |
| 22 | import sys |
Peter Wen | f409c0c | 2021-02-09 19:33:02 | [diff] [blame] | 23 | import threading |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 24 | import traceback |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 25 | import time |
| 26 | from typing import Callable, Dict, List, Optional, Tuple, IO |
Peter Wen | b1f3b1d | 2021-02-02 21:30:20 | [diff] [blame] | 27 | |
| 28 | sys.path.append(os.path.join(os.path.dirname(__file__), 'gyp')) |
| 29 | from util import server_utils |
| 30 | |
Mohamed Heikal | abf646e | 2024-12-12 16:06:05 | [diff] [blame] | 31 | _SOCKET_TIMEOUT = 60 # seconds |
Peter Wen | 6e7e52b | 2021-02-13 02:39:28 | [diff] [blame] | 32 | |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 33 | _LOGFILE_NAME = 'buildserver.log' |
| 34 | _MAX_LOGFILES = 6 |
| 35 | |
Andrew Grieve | 0d6e8a75 | 2025-02-05 21:20:50 | [diff] [blame^] | 36 | FIRST_LOG_LINE = """\ |
| 37 | #### Start of log for build: {build_id} |
| 38 | #### CWD: {outdir} |
| 39 | """ |
| 40 | BUILD_ID_RE = re.compile(r'^#### Start of log for build: (?P<build_id>.+)') |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 41 | |
| 42 | |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 43 | def log(msg: str, quiet: bool = False): |
| 44 | if quiet: |
| 45 | return |
| 46 | # Ensure we start our message on a new line. |
Mohamed Heikal | 9984e43 | 2024-12-03 18:21:40 | [diff] [blame] | 47 | print('\n' + msg) |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 48 | |
| 49 | |
Mohamed Heikal | 9984e43 | 2024-12-03 18:21:40 | [diff] [blame] | 50 | def set_status(msg: str, *, quiet: bool = False, build_id: str = None): |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 51 | prefix = f'[{TaskStats.prefix()}] ' |
| 52 | # if message is specific to a build then also output to its logfile. |
| 53 | if build_id: |
Mohamed Heikal | 08b467e0 | 2025-01-27 20:54:25 | [diff] [blame] | 54 | LogfileManager.log_to_file(f'{prefix}{msg}', build_id=build_id) |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 55 | |
| 56 | # No need to also output to the terminal if quiet. |
| 57 | if quiet: |
| 58 | return |
Peter Wen | cd460ff5 | 2021-02-23 22:40:05 | [diff] [blame] | 59 | # Shrink the message (leaving a 2-char prefix and use the rest of the room |
| 60 | # for the suffix) according to terminal size so it is always one line. |
| 61 | width = shutil.get_terminal_size().columns |
Peter Wen | cd460ff5 | 2021-02-23 22:40:05 | [diff] [blame] | 62 | max_msg_width = width - len(prefix) |
| 63 | if len(msg) > max_msg_width: |
| 64 | length_to_show = max_msg_width - 5 # Account for ellipsis and header. |
| 65 | msg = f'{msg[:2]}...{msg[-length_to_show:]}' |
| 66 | # \r to return the carriage to the beginning of line. |
| 67 | # \033[K to replace the normal \n to erase until the end of the line. |
| 68 | # Avoid the default line ending so the next \r overwrites the same line just |
| 69 | # like ninja's output. |
Mohamed Heikal | 9984e43 | 2024-12-03 18:21:40 | [diff] [blame] | 70 | print(f'\r{prefix}{msg}\033[K', end='', flush=True) |
Peter Wen | cd460ff5 | 2021-02-23 22:40:05 | [diff] [blame] | 71 | |
| 72 | |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 73 | def _exception_hook(exctype: type, exc: Exception, tb): |
Mohamed Heikal | d764eca | 2025-01-31 01:06:35 | [diff] [blame] | 74 | # Let KeyboardInterrupt through. |
| 75 | if issubclass(exctype, KeyboardInterrupt): |
| 76 | sys.__excepthook__(exctype, exc, tb) |
| 77 | return |
| 78 | stacktrace = ''.join(traceback.format_exception(exctype, exc, tb)) |
| 79 | stacktrace_lines = [f'\n⛔{line}' for line in stacktrace.splitlines()] |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 80 | # Output uncaught exceptions to all live terminals |
Andrew Grieve | 0d6e8a75 | 2025-02-05 21:20:50 | [diff] [blame^] | 81 | # Extra newline since siso's output often erases the current line. |
| 82 | BuildManager.broadcast(''.join(stacktrace_lines) + '\n') |
Mohamed Heikal | 9984e43 | 2024-12-03 18:21:40 | [diff] [blame] | 83 | # Cancel all pending tasks cleanly (i.e. delete stamp files if necessary). |
| 84 | TaskManager.deactivate() |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 85 | |
| 86 | |
Mohamed Heikal | 08b467e0 | 2025-01-27 20:54:25 | [diff] [blame] | 87 | class LogfileManager: |
| 88 | _open_logfiles: dict[str, IO[str]] = {} |
| 89 | |
| 90 | @classmethod |
| 91 | def log_to_file(cls, message: str, build_id: str): |
| 92 | # No lock needed since this is only called by threads started after |
| 93 | # create_logfile was called on the main thread. |
| 94 | logfile = cls._open_logfiles[build_id] |
| 95 | print(message, file=logfile, flush=True) |
| 96 | |
| 97 | @classmethod |
| 98 | def create_logfile(cls, build_id, outdir): |
| 99 | # No lock needed since this is only called by the main thread. |
| 100 | if logfile := cls._open_logfiles.get(build_id, None): |
| 101 | return logfile |
| 102 | |
| 103 | outdir = pathlib.Path(outdir) |
| 104 | latest_logfile = outdir / f'{_LOGFILE_NAME}.0' |
| 105 | |
| 106 | if latest_logfile.exists(): |
| 107 | with latest_logfile.open('rt') as f: |
| 108 | first_line = f.readline() |
| 109 | if log_build_id := BUILD_ID_RE.search(first_line): |
| 110 | # If the newest logfile on disk is referencing the same build we are |
| 111 | # currently processing, we probably crashed previously and we should |
| 112 | # pick up where we left off in the same logfile. |
| 113 | if log_build_id.group('build_id') == build_id: |
| 114 | cls._open_logfiles[build_id] = latest_logfile.open('at') |
| 115 | return cls._open_logfiles[build_id] |
| 116 | |
| 117 | # Do the logfile name shift. |
| 118 | filenames = os.listdir(outdir) |
| 119 | logfiles = {f for f in filenames if f.startswith(_LOGFILE_NAME)} |
| 120 | for idx in reversed(range(_MAX_LOGFILES)): |
| 121 | current_name = f'{_LOGFILE_NAME}.{idx}' |
| 122 | next_name = f'{_LOGFILE_NAME}.{idx+1}' |
| 123 | if current_name in logfiles: |
| 124 | shutil.move(os.path.join(outdir, current_name), |
| 125 | os.path.join(outdir, next_name)) |
| 126 | |
| 127 | # Create a new 0th logfile. |
| 128 | logfile = latest_logfile.open('wt') |
| 129 | # Logfiles are never closed thus are leaked but there should not be too many |
| 130 | # of them since only one per build is created and the server exits on idle |
| 131 | # in normal operation. |
| 132 | cls._open_logfiles[build_id] = logfile |
Andrew Grieve | 0d6e8a75 | 2025-02-05 21:20:50 | [diff] [blame^] | 133 | logfile.write(FIRST_LOG_LINE.format(build_id=build_id, outdir=outdir)) |
Mohamed Heikal | 08b467e0 | 2025-01-27 20:54:25 | [diff] [blame] | 134 | logfile.flush() |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 135 | return logfile |
| 136 | |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 137 | |
Peter Wen | cd460ff5 | 2021-02-23 22:40:05 | [diff] [blame] | 138 | class TaskStats: |
| 139 | """Class to keep track of aggregate stats for all tasks across threads.""" |
| 140 | _num_processes = 0 |
| 141 | _completed_tasks = 0 |
| 142 | _total_tasks = 0 |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 143 | _total_task_count_per_build = collections.defaultdict(int) |
| 144 | _completed_task_count_per_build = collections.defaultdict(int) |
| 145 | _running_processes_count_per_build = collections.defaultdict(int) |
Andrew Grieve | d863d0f | 2024-12-13 20:13:01 | [diff] [blame] | 146 | _lock = threading.RLock() |
Peter Wen | 6e7e52b | 2021-02-13 02:39:28 | [diff] [blame] | 147 | |
| 148 | @classmethod |
Peter Wen | cd460ff5 | 2021-02-23 22:40:05 | [diff] [blame] | 149 | def no_running_processes(cls): |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 150 | with cls._lock: |
| 151 | return cls._num_processes == 0 |
Peter Wen | 6e7e52b | 2021-02-13 02:39:28 | [diff] [blame] | 152 | |
| 153 | @classmethod |
Andrew Grieve | 0d6e8a75 | 2025-02-05 21:20:50 | [diff] [blame^] | 154 | def add_task(cls, build_id: str): |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 155 | with cls._lock: |
| 156 | cls._total_tasks += 1 |
| 157 | cls._total_task_count_per_build[build_id] += 1 |
Peter Wen | cd460ff5 | 2021-02-23 22:40:05 | [diff] [blame] | 158 | |
| 159 | @classmethod |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 160 | def add_process(cls, build_id: str): |
Peter Wen | cd460ff5 | 2021-02-23 22:40:05 | [diff] [blame] | 161 | with cls._lock: |
| 162 | cls._num_processes += 1 |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 163 | cls._running_processes_count_per_build[build_id] += 1 |
Peter Wen | cd460ff5 | 2021-02-23 22:40:05 | [diff] [blame] | 164 | |
| 165 | @classmethod |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 166 | def remove_process(cls, build_id: str): |
Peter Wen | cd460ff5 | 2021-02-23 22:40:05 | [diff] [blame] | 167 | with cls._lock: |
| 168 | cls._num_processes -= 1 |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 169 | cls._running_processes_count_per_build[build_id] -= 1 |
Peter Wen | cd460ff5 | 2021-02-23 22:40:05 | [diff] [blame] | 170 | |
| 171 | @classmethod |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 172 | def complete_task(cls, build_id: str): |
Peter Wen | cd460ff5 | 2021-02-23 22:40:05 | [diff] [blame] | 173 | with cls._lock: |
| 174 | cls._completed_tasks += 1 |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 175 | cls._completed_task_count_per_build[build_id] += 1 |
Peter Wen | cd460ff5 | 2021-02-23 22:40:05 | [diff] [blame] | 176 | |
| 177 | @classmethod |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 178 | def num_pending_tasks(cls, build_id: str = None): |
| 179 | with cls._lock: |
| 180 | if build_id: |
| 181 | return cls._total_task_count_per_build[ |
| 182 | build_id] - cls._completed_task_count_per_build[build_id] |
| 183 | return cls._total_tasks - cls._completed_tasks |
| 184 | |
| 185 | @classmethod |
| 186 | def num_completed_tasks(cls, build_id: str = None): |
| 187 | with cls._lock: |
| 188 | if build_id: |
| 189 | return cls._completed_task_count_per_build[build_id] |
| 190 | return cls._completed_tasks |
| 191 | |
| 192 | @classmethod |
Andrew Grieve | 6c764fff | 2025-01-30 21:02:03 | [diff] [blame] | 193 | def total_tasks(cls, build_id: str = None): |
| 194 | with cls._lock: |
| 195 | if build_id: |
| 196 | return cls._total_task_count_per_build[build_id] |
| 197 | return cls._total_tasks |
| 198 | |
| 199 | @classmethod |
Andrew Grieve | d863d0f | 2024-12-13 20:13:01 | [diff] [blame] | 200 | def query_build(cls, query_build_id: str = None): |
| 201 | with cls._lock: |
| 202 | active_builds = BuildManager.get_live_builds() |
Andrew Grieve | 0d6e8a75 | 2025-02-05 21:20:50 | [diff] [blame^] | 203 | active_build_ids = [b.id for b in active_builds] |
Andrew Grieve | d863d0f | 2024-12-13 20:13:01 | [diff] [blame] | 204 | if query_build_id: |
| 205 | build_ids = [query_build_id] |
| 206 | else: |
| 207 | build_ids = sorted( |
Andrew Grieve | 0d6e8a75 | 2025-02-05 21:20:50 | [diff] [blame^] | 208 | set(active_build_ids) | set(cls._total_task_count_per_build)) |
Andrew Grieve | d863d0f | 2024-12-13 20:13:01 | [diff] [blame] | 209 | builds = [] |
| 210 | for build_id in build_ids: |
Andrew Grieve | 0d6e8a75 | 2025-02-05 21:20:50 | [diff] [blame^] | 211 | build = next((b for b in active_builds if b.id == build_id), None) |
Andrew Grieve | d863d0f | 2024-12-13 20:13:01 | [diff] [blame] | 212 | current_tasks = TaskManager.get_current_tasks(build_id) |
| 213 | builds.append({ |
| 214 | 'build_id': build_id, |
Andrew Grieve | 0d6e8a75 | 2025-02-05 21:20:50 | [diff] [blame^] | 215 | 'is_active': build is not None, |
Andrew Grieve | d863d0f | 2024-12-13 20:13:01 | [diff] [blame] | 216 | 'completed_tasks': cls.num_completed_tasks(build_id), |
| 217 | 'pending_tasks': cls.num_pending_tasks(build_id), |
| 218 | 'active_tasks': [t.cmd for t in current_tasks], |
Andrew Grieve | 0d6e8a75 | 2025-02-05 21:20:50 | [diff] [blame^] | 219 | 'outdir': build.cwd if build else None, |
Andrew Grieve | d863d0f | 2024-12-13 20:13:01 | [diff] [blame] | 220 | }) |
| 221 | return { |
| 222 | 'pid': os.getpid(), |
| 223 | 'builds': builds, |
| 224 | } |
| 225 | |
| 226 | @classmethod |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 227 | def prefix(cls, build_id: str = None): |
Peter Wen | 6e7e52b | 2021-02-13 02:39:28 | [diff] [blame] | 228 | # Ninja's prefix is: [205 processes, 6/734 @ 6.5/s : 0.922s ] |
| 229 | # Time taken and task completion rate are not important for the build server |
| 230 | # since it is always running in the background and uses idle priority for |
| 231 | # its tasks. |
Peter Wen | cd460ff5 | 2021-02-23 22:40:05 | [diff] [blame] | 232 | with cls._lock: |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 233 | if build_id: |
| 234 | _num_processes = cls._running_processes_count_per_build[build_id] |
| 235 | _completed_tasks = cls._completed_task_count_per_build[build_id] |
| 236 | _total_tasks = cls._total_task_count_per_build[build_id] |
| 237 | else: |
| 238 | _num_processes = cls._num_processes |
| 239 | _completed_tasks = cls._completed_tasks |
| 240 | _total_tasks = cls._total_tasks |
| 241 | word = 'process' if _num_processes == 1 else 'processes' |
| 242 | return (f'{_num_processes} {word}, ' |
| 243 | f'{_completed_tasks}/{_total_tasks}') |
Peter Wen | b1f3b1d | 2021-02-02 21:30:20 | [diff] [blame] | 244 | |
Peter Wen | f409c0c | 2021-02-09 19:33:02 | [diff] [blame] | 245 | |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 246 | def check_pid_alive(pid: int): |
| 247 | try: |
| 248 | os.kill(pid, 0) |
| 249 | except OSError: |
| 250 | return False |
| 251 | return True |
| 252 | |
| 253 | |
Andrew Grieve | 0d6e8a75 | 2025-02-05 21:20:50 | [diff] [blame^] | 254 | @dataclasses.dataclass |
| 255 | class Build: |
| 256 | id: str |
| 257 | pid: int |
| 258 | env: dict |
| 259 | isatty: bool |
| 260 | stdout: IO[str] |
| 261 | cwd: Optional[str] = None |
| 262 | |
| 263 | def set_title(self, title): |
| 264 | if self.isatty: |
| 265 | self.stdout.write(f'\033]2;{title}\007') |
| 266 | self.stdout.flush() |
| 267 | |
| 268 | |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 269 | class BuildManager: |
Andrew Grieve | 0d6e8a75 | 2025-02-05 21:20:50 | [diff] [blame^] | 270 | _builds_by_id: dict[str, Build] = dict() |
Mohamed Heikal | 08b467e0 | 2025-01-27 20:54:25 | [diff] [blame] | 271 | _cached_ttys: dict[(int, int), IO[str]] = dict() |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 272 | _lock = threading.RLock() |
| 273 | |
| 274 | @classmethod |
Andrew Grieve | 0d6e8a75 | 2025-02-05 21:20:50 | [diff] [blame^] | 275 | def register_builder(cls, env, pid, cwd): |
| 276 | build_id = env['AUTONINJA_BUILD_ID'] |
| 277 | stdout = cls.open_tty(env['AUTONINJA_STDOUT_NAME']) |
| 278 | # Tells the script not to re-delegate to build server. |
| 279 | env[server_utils.BUILD_SERVER_ENV_VARIABLE] = '1' |
| 280 | |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 281 | with cls._lock: |
Andrew Grieve | 0d6e8a75 | 2025-02-05 21:20:50 | [diff] [blame^] | 282 | build = Build(id=build_id, |
| 283 | pid=pid, |
| 284 | cwd=cwd, |
| 285 | env=env, |
| 286 | isatty=stdout.isatty(), |
| 287 | stdout=stdout) |
| 288 | build.set_title('Analysis Steps: 0/0') |
| 289 | stdout.flush() |
| 290 | cls.maybe_init_cwd(build, cwd) |
| 291 | cls._builds_by_id[build_id] = build |
| 292 | |
| 293 | @classmethod |
| 294 | def maybe_init_cwd(cls, build, cwd): |
| 295 | if cwd is not None: |
| 296 | with cls._lock: |
| 297 | if build.cwd is None: |
| 298 | build.cwd = cwd |
| 299 | LogfileManager.create_logfile(build.id, cwd) |
| 300 | else: |
| 301 | assert cwd == build.cwd, f'{repr(cwd)} != {repr(build.cwd)}' |
| 302 | |
| 303 | @classmethod |
| 304 | def get_build(cls, build_id): |
| 305 | with cls._lock: |
| 306 | return cls._builds_by_id[build_id] |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 307 | |
| 308 | @classmethod |
Mohamed Heikal | 08b467e0 | 2025-01-27 20:54:25 | [diff] [blame] | 309 | def open_tty(cls, tty_path): |
| 310 | # Do not open the same tty multiple times. Use st_ino and st_dev to compare |
| 311 | # file descriptors. |
Andrew Grieve | 0d6e8a75 | 2025-02-05 21:20:50 | [diff] [blame^] | 312 | tty = open(tty_path, 'at') |
Mohamed Heikal | db4fd9c | 2025-01-29 20:56:27 | [diff] [blame] | 313 | st = os.stat(tty.fileno()) |
Mohamed Heikal | 08b467e0 | 2025-01-27 20:54:25 | [diff] [blame] | 314 | tty_key = (st.st_ino, st.st_dev) |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 315 | with cls._lock: |
Mohamed Heikal | 08b467e0 | 2025-01-27 20:54:25 | [diff] [blame] | 316 | # Dedupes ttys |
| 317 | if tty_key not in cls._cached_ttys: |
| 318 | # TTYs are kept open for the lifetime of the server so that broadcast |
| 319 | # messages (e.g. uncaught exceptions) can be sent to them even if they |
| 320 | # are not currently building anything. |
Mohamed Heikal | db4fd9c | 2025-01-29 20:56:27 | [diff] [blame] | 321 | cls._cached_ttys[tty_key] = tty |
| 322 | else: |
| 323 | tty.close() |
Mohamed Heikal | 08b467e0 | 2025-01-27 20:54:25 | [diff] [blame] | 324 | return cls._cached_ttys[tty_key] |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 325 | |
| 326 | @classmethod |
| 327 | def get_live_builds(cls): |
| 328 | with cls._lock: |
Andrew Grieve | 0d6e8a75 | 2025-02-05 21:20:50 | [diff] [blame^] | 329 | for build in list(cls._builds_by_id.values()): |
| 330 | if not check_pid_alive(build.pid): |
| 331 | # Setting an empty title causes most terminals to go back to the |
| 332 | # default title (and at least prevents the tab title from being |
| 333 | # "Analysis Steps: N/N" forevermore. |
| 334 | build.set_title('') |
| 335 | del cls._builds_by_id[build.id] |
| 336 | return list(cls._builds_by_id.values()) |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 337 | |
| 338 | @classmethod |
| 339 | def broadcast(cls, msg: str): |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 340 | with cls._lock: |
Mohamed Heikal | 08b467e0 | 2025-01-27 20:54:25 | [diff] [blame] | 341 | for tty in cls._cached_ttys.values(): |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 342 | try: |
| 343 | tty.write(msg + '\n') |
| 344 | tty.flush() |
| 345 | except BrokenPipeError: |
| 346 | pass |
Mohamed Heikal | d764eca | 2025-01-31 01:06:35 | [diff] [blame] | 347 | # Write to the current terminal if we have not written to it yet. |
| 348 | st = os.stat(sys.stderr.fileno()) |
| 349 | stderr_key = (st.st_ino, st.st_dev) |
| 350 | if stderr_key not in cls._cached_ttys: |
| 351 | print(msg, file=sys.stderr) |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 352 | |
| 353 | @classmethod |
| 354 | def has_live_builds(cls): |
| 355 | return bool(cls.get_live_builds()) |
| 356 | |
| 357 | |
Peter Wen | cd460ff5 | 2021-02-23 22:40:05 | [diff] [blame] | 358 | class TaskManager: |
| 359 | """Class to encapsulate a threadsafe queue and handle deactivating it.""" |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 360 | _queue: collections.deque[Task] = collections.deque() |
Mohamed Heikal | abf646e | 2024-12-12 16:06:05 | [diff] [blame] | 361 | _current_tasks: set[Task] = set() |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 362 | _deactivated = False |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 363 | _lock = threading.RLock() |
Peter Wen | cd460ff5 | 2021-02-23 22:40:05 | [diff] [blame] | 364 | |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 365 | @classmethod |
| 366 | def add_task(cls, task: Task, options): |
| 367 | assert not cls._deactivated |
Andrew Grieve | 0d6e8a75 | 2025-02-05 21:20:50 | [diff] [blame^] | 368 | TaskStats.add_task(task.build.id) |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 369 | with cls._lock: |
| 370 | cls._queue.appendleft(task) |
| 371 | set_status(f'QUEUED {task.name}', |
| 372 | quiet=options.quiet, |
Andrew Grieve | 0d6e8a75 | 2025-02-05 21:20:50 | [diff] [blame^] | 373 | build_id=task.build.id) |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 374 | cls._maybe_start_tasks() |
Peter Wen | cd460ff5 | 2021-02-23 22:40:05 | [diff] [blame] | 375 | |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 376 | @classmethod |
Mohamed Heikal | abf646e | 2024-12-12 16:06:05 | [diff] [blame] | 377 | def task_done(cls, task: Task): |
Andrew Grieve | 0d6e8a75 | 2025-02-05 21:20:50 | [diff] [blame^] | 378 | TaskStats.complete_task(build_id=task.build.id) |
| 379 | |
| 380 | total = TaskStats.total_tasks(task.build.id) |
| 381 | completed = TaskStats.num_completed_tasks(task.build.id) |
| 382 | task.build.set_title(f'Analysis Steps: {completed}/{total}') |
Andrew Grieve | 6c764fff | 2025-01-30 21:02:03 | [diff] [blame] | 383 | |
Mohamed Heikal | abf646e | 2024-12-12 16:06:05 | [diff] [blame] | 384 | with cls._lock: |
Mohamed Heikal | 651c992 | 2025-01-16 19:12:21 | [diff] [blame] | 385 | cls._current_tasks.discard(task) |
Mohamed Heikal | abf646e | 2024-12-12 16:06:05 | [diff] [blame] | 386 | |
| 387 | @classmethod |
Andrew Grieve | d863d0f | 2024-12-13 20:13:01 | [diff] [blame] | 388 | def get_current_tasks(cls, build_id): |
| 389 | with cls._lock: |
Andrew Grieve | 0d6e8a75 | 2025-02-05 21:20:50 | [diff] [blame^] | 390 | return [t for t in cls._current_tasks if t.build.id == build_id] |
Andrew Grieve | d863d0f | 2024-12-13 20:13:01 | [diff] [blame] | 391 | |
| 392 | @classmethod |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 393 | def deactivate(cls): |
| 394 | cls._deactivated = True |
Mohamed Heikal | abf646e | 2024-12-12 16:06:05 | [diff] [blame] | 395 | tasks_to_terminate: list[Task] = [] |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 396 | with cls._lock: |
| 397 | while cls._queue: |
| 398 | task = cls._queue.pop() |
Mohamed Heikal | abf646e | 2024-12-12 16:06:05 | [diff] [blame] | 399 | tasks_to_terminate.append(task) |
| 400 | # Cancel possibly running tasks. |
| 401 | tasks_to_terminate.extend(cls._current_tasks) |
| 402 | # Terminate outside lock since task threads need the lock to finish |
| 403 | # terminating. |
| 404 | for task in tasks_to_terminate: |
| 405 | task.terminate() |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 406 | |
| 407 | @classmethod |
| 408 | def cancel_build(cls, build_id): |
Mohamed Heikal | abf646e | 2024-12-12 16:06:05 | [diff] [blame] | 409 | terminated_pending_tasks: list[Task] = [] |
| 410 | terminated_current_tasks: list[Task] = [] |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 411 | with cls._lock: |
Mohamed Heikal | abf646e | 2024-12-12 16:06:05 | [diff] [blame] | 412 | # Cancel pending tasks. |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 413 | for task in cls._queue: |
Andrew Grieve | 0d6e8a75 | 2025-02-05 21:20:50 | [diff] [blame^] | 414 | if task.build.id == build_id: |
Mohamed Heikal | abf646e | 2024-12-12 16:06:05 | [diff] [blame] | 415 | terminated_pending_tasks.append(task) |
| 416 | for task in terminated_pending_tasks: |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 417 | cls._queue.remove(task) |
Mohamed Heikal | abf646e | 2024-12-12 16:06:05 | [diff] [blame] | 418 | # Cancel running tasks. |
| 419 | for task in cls._current_tasks: |
Andrew Grieve | 0d6e8a75 | 2025-02-05 21:20:50 | [diff] [blame^] | 420 | if task.build.id == build_id: |
Mohamed Heikal | abf646e | 2024-12-12 16:06:05 | [diff] [blame] | 421 | terminated_current_tasks.append(task) |
| 422 | # Terminate tasks outside lock since task threads need the lock to finish |
| 423 | # terminating. |
| 424 | for task in terminated_pending_tasks: |
| 425 | task.terminate() |
| 426 | for task in terminated_current_tasks: |
| 427 | task.terminate() |
Peter Wen | cd460ff5 | 2021-02-23 22:40:05 | [diff] [blame] | 428 | |
| 429 | @staticmethod |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 430 | # pylint: disable=inconsistent-return-statements |
Peter Wen | cd460ff5 | 2021-02-23 22:40:05 | [diff] [blame] | 431 | def _num_running_processes(): |
| 432 | with open('/proc/stat') as f: |
| 433 | for line in f: |
| 434 | if line.startswith('procs_running'): |
| 435 | return int(line.rstrip().split()[1]) |
| 436 | assert False, 'Could not read /proc/stat' |
| 437 | |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 438 | @classmethod |
| 439 | def _maybe_start_tasks(cls): |
| 440 | if cls._deactivated: |
Peter Wen | cd460ff5 | 2021-02-23 22:40:05 | [diff] [blame] | 441 | return |
| 442 | # Include load avg so that a small dip in the number of currently running |
| 443 | # processes will not cause new tasks to be started while the overall load is |
| 444 | # heavy. |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 445 | cur_load = max(cls._num_running_processes(), os.getloadavg()[0]) |
Peter Wen | cd460ff5 | 2021-02-23 22:40:05 | [diff] [blame] | 446 | num_started = 0 |
| 447 | # Always start a task if we don't have any running, so that all tasks are |
| 448 | # eventually finished. Try starting up tasks when the overall load is light. |
| 449 | # Limit to at most 2 new tasks to prevent ramping up too fast. There is a |
| 450 | # chance where multiple threads call _maybe_start_tasks and each gets to |
| 451 | # spawn up to 2 new tasks, but since the only downside is some build tasks |
| 452 | # get worked on earlier rather than later, it is not worth mitigating. |
| 453 | while num_started < 2 and (TaskStats.no_running_processes() |
| 454 | or num_started + cur_load < os.cpu_count()): |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 455 | with cls._lock: |
| 456 | try: |
| 457 | next_task = cls._queue.pop() |
Mohamed Heikal | abf646e | 2024-12-12 16:06:05 | [diff] [blame] | 458 | cls._current_tasks.add(next_task) |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 459 | except IndexError: |
| 460 | return |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 461 | num_started += next_task.start(cls._maybe_start_tasks) |
Peter Wen | cd460ff5 | 2021-02-23 22:40:05 | [diff] [blame] | 462 | |
| 463 | |
| 464 | # TODO(wnwen): Break this into Request (encapsulating what ninja sends) and Task |
| 465 | # when a Request starts to be run. This would eliminate ambiguity |
| 466 | # about when and whether _proc/_thread are initialized. |
Peter Wen | f409c0c | 2021-02-09 19:33:02 | [diff] [blame] | 467 | class Task: |
Peter Wen | cd460ff5 | 2021-02-23 22:40:05 | [diff] [blame] | 468 | """Class to represent one task and operations on it.""" |
| 469 | |
Andrew Grieve | 0d6e8a75 | 2025-02-05 21:20:50 | [diff] [blame^] | 470 | def __init__(self, name: str, build: Build, cmd: List[str], stamp_file: str, |
| 471 | options): |
Peter Wen | cd460ff5 | 2021-02-23 22:40:05 | [diff] [blame] | 472 | self.name = name |
Andrew Grieve | 0d6e8a75 | 2025-02-05 21:20:50 | [diff] [blame^] | 473 | self.build = build |
Peter Wen | cd460ff5 | 2021-02-23 22:40:05 | [diff] [blame] | 474 | self.cmd = cmd |
| 475 | self.stamp_file = stamp_file |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 476 | self.options = options |
Peter Wen | cd460ff5 | 2021-02-23 22:40:05 | [diff] [blame] | 477 | self._terminated = False |
Mohamed Heikal | 9984e43 | 2024-12-03 18:21:40 | [diff] [blame] | 478 | self._replaced = False |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 479 | self._lock = threading.RLock() |
Peter Wen | cd460ff5 | 2021-02-23 22:40:05 | [diff] [blame] | 480 | self._proc: Optional[subprocess.Popen] = None |
| 481 | self._thread: Optional[threading.Thread] = None |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 482 | self._delete_stamp_thread: Optional[threading.Thread] = None |
Peter Wen | cd460ff5 | 2021-02-23 22:40:05 | [diff] [blame] | 483 | self._return_code: Optional[int] = None |
Peter Wen | f409c0c | 2021-02-09 19:33:02 | [diff] [blame] | 484 | |
Peter Wen | 6e7e52b | 2021-02-13 02:39:28 | [diff] [blame] | 485 | @property |
| 486 | def key(self): |
Andrew Grieve | 0d6e8a75 | 2025-02-05 21:20:50 | [diff] [blame^] | 487 | return (self.build.cwd, self.name) |
Peter Wen | f409c0c | 2021-02-09 19:33:02 | [diff] [blame] | 488 | |
Mohamed Heikal | abf646e | 2024-12-12 16:06:05 | [diff] [blame] | 489 | def __hash__(self): |
Andrew Grieve | 0d6e8a75 | 2025-02-05 21:20:50 | [diff] [blame^] | 490 | return hash((self.key, self.build.id)) |
Mohamed Heikal | abf646e | 2024-12-12 16:06:05 | [diff] [blame] | 491 | |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 492 | def __eq__(self, other): |
Andrew Grieve | 0d6e8a75 | 2025-02-05 21:20:50 | [diff] [blame^] | 493 | return self.key == other.key and self.build is other.build |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 494 | |
Peter Wen | cd460ff5 | 2021-02-23 22:40:05 | [diff] [blame] | 495 | def start(self, on_complete_callback: Callable[[], None]) -> int: |
| 496 | """Starts the task if it has not already been terminated. |
| 497 | |
| 498 | Returns the number of processes that have been started. This is called at |
| 499 | most once when the task is popped off the task queue.""" |
Peter Wen | cd460ff5 | 2021-02-23 22:40:05 | [diff] [blame] | 500 | with self._lock: |
| 501 | if self._terminated: |
| 502 | return 0 |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 503 | |
Peter Wen | cd460ff5 | 2021-02-23 22:40:05 | [diff] [blame] | 504 | # Use os.nice(19) to ensure the lowest priority (idle) for these analysis |
| 505 | # tasks since we want to avoid slowing down the actual build. |
| 506 | # TODO(wnwen): Use ionice to reduce resource consumption. |
Andrew Grieve | 0d6e8a75 | 2025-02-05 21:20:50 | [diff] [blame^] | 507 | TaskStats.add_process(self.build.id) |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 508 | set_status(f'STARTING {self.name}', |
| 509 | quiet=self.options.quiet, |
Andrew Grieve | 0d6e8a75 | 2025-02-05 21:20:50 | [diff] [blame^] | 510 | build_id=self.build.id) |
Peter Wen | 1cdf05d8 | 2022-04-05 17:31:23 | [diff] [blame] | 511 | # This use of preexec_fn is sufficiently simple, just one os.nice call. |
| 512 | # pylint: disable=subprocess-popen-preexec-fn |
Peter Wen | cd460ff5 | 2021-02-23 22:40:05 | [diff] [blame] | 513 | self._proc = subprocess.Popen( |
| 514 | self.cmd, |
| 515 | stdout=subprocess.PIPE, |
| 516 | stderr=subprocess.STDOUT, |
Andrew Grieve | 0d6e8a75 | 2025-02-05 21:20:50 | [diff] [blame^] | 517 | cwd=self.build.cwd, |
| 518 | env=self.build.env, |
Peter Wen | cd460ff5 | 2021-02-23 22:40:05 | [diff] [blame] | 519 | text=True, |
| 520 | preexec_fn=lambda: os.nice(19), |
| 521 | ) |
| 522 | self._thread = threading.Thread( |
| 523 | target=self._complete_when_process_finishes, |
| 524 | args=(on_complete_callback, )) |
| 525 | self._thread.start() |
| 526 | return 1 |
Peter Wen | f409c0c | 2021-02-09 19:33:02 | [diff] [blame] | 527 | |
Mohamed Heikal | 9984e43 | 2024-12-03 18:21:40 | [diff] [blame] | 528 | def terminate(self, replaced=False): |
Peter Wen | cd460ff5 | 2021-02-23 22:40:05 | [diff] [blame] | 529 | """Can be called multiple times to cancel and ignore the task's output.""" |
Peter Wen | cd460ff5 | 2021-02-23 22:40:05 | [diff] [blame] | 530 | with self._lock: |
| 531 | if self._terminated: |
| 532 | return |
| 533 | self._terminated = True |
Mohamed Heikal | 9984e43 | 2024-12-03 18:21:40 | [diff] [blame] | 534 | self._replaced = replaced |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 535 | |
Peter Wen | cd460ff5 | 2021-02-23 22:40:05 | [diff] [blame] | 536 | # It is safe to access _proc and _thread outside of _lock since they are |
| 537 | # only changed by self.start holding _lock when self._terminate is false. |
| 538 | # Since we have just set self._terminate to true inside of _lock, we know |
| 539 | # that neither _proc nor _thread will be changed from this point onwards. |
Peter Wen | 6e7e52b | 2021-02-13 02:39:28 | [diff] [blame] | 540 | if self._proc: |
| 541 | self._proc.terminate() |
| 542 | self._proc.wait() |
Peter Wen | cd460ff5 | 2021-02-23 22:40:05 | [diff] [blame] | 543 | # Ensure that self._complete is called either by the thread or by us. |
Peter Wen | 6e7e52b | 2021-02-13 02:39:28 | [diff] [blame] | 544 | if self._thread: |
| 545 | self._thread.join() |
Peter Wen | cd460ff5 | 2021-02-23 22:40:05 | [diff] [blame] | 546 | else: |
| 547 | self._complete() |
Peter Wen | f409c0c | 2021-02-09 19:33:02 | [diff] [blame] | 548 | |
Peter Wen | cd460ff5 | 2021-02-23 22:40:05 | [diff] [blame] | 549 | def _complete_when_process_finishes(self, |
| 550 | on_complete_callback: Callable[[], None]): |
Peter Wen | 6e7e52b | 2021-02-13 02:39:28 | [diff] [blame] | 551 | assert self._proc |
| 552 | # We know Popen.communicate will return a str and not a byte since it is |
| 553 | # constructed with text=True. |
| 554 | stdout: str = self._proc.communicate()[0] |
| 555 | self._return_code = self._proc.returncode |
Andrew Grieve | 0d6e8a75 | 2025-02-05 21:20:50 | [diff] [blame^] | 556 | TaskStats.remove_process(build_id=self.build.id) |
Peter Wen | 6e7e52b | 2021-02-13 02:39:28 | [diff] [blame] | 557 | self._complete(stdout) |
Peter Wen | cd460ff5 | 2021-02-23 22:40:05 | [diff] [blame] | 558 | on_complete_callback() |
Peter Wen | f409c0c | 2021-02-09 19:33:02 | [diff] [blame] | 559 | |
Peter Wen | cd460ff5 | 2021-02-23 22:40:05 | [diff] [blame] | 560 | def _complete(self, stdout: str = ''): |
| 561 | """Update the user and ninja after the task has run or been terminated. |
| 562 | |
| 563 | This method should only be run once per task. Avoid modifying the task so |
| 564 | that this method does not need locking.""" |
| 565 | |
Mohamed Heikal | 9984e43 | 2024-12-03 18:21:40 | [diff] [blame] | 566 | delete_stamp = False |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 567 | status_string = 'FINISHED' |
Peter Wen | 6e7e52b | 2021-02-13 02:39:28 | [diff] [blame] | 568 | if self._terminated: |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 569 | status_string = 'TERMINATED' |
Mohamed Heikal | 9984e43 | 2024-12-03 18:21:40 | [diff] [blame] | 570 | # When tasks are replaced, avoid deleting the stamp file, context: |
| 571 | # https://issuetracker.google.com/301961827. |
| 572 | if not self._replaced: |
| 573 | delete_stamp = True |
| 574 | elif stdout or self._return_code != 0: |
| 575 | status_string = 'FAILED' |
| 576 | delete_stamp = True |
| 577 | preamble = [ |
| 578 | f'FAILED: {self.name}', |
| 579 | f'Return code: {self._return_code}', |
Andrew Grieve | 38c8046 | 2024-12-17 21:33:27 | [diff] [blame] | 580 | 'CMD: ' + shlex.join(self.cmd), |
Mohamed Heikal | 9984e43 | 2024-12-03 18:21:40 | [diff] [blame] | 581 | 'STDOUT:', |
| 582 | ] |
| 583 | |
| 584 | message = '\n'.join(preamble + [stdout]) |
Andrew Grieve | 0d6e8a75 | 2025-02-05 21:20:50 | [diff] [blame^] | 585 | LogfileManager.log_to_file(message, build_id=self.build.id) |
Mohamed Heikal | 9984e43 | 2024-12-03 18:21:40 | [diff] [blame] | 586 | log(message, quiet=self.options.quiet) |
Andrew Grieve | 0d6e8a75 | 2025-02-05 21:20:50 | [diff] [blame^] | 587 | |
| 588 | # Add emoji to show that output is from the build server. |
| 589 | preamble = [f'⏩ {line}' for line in preamble] |
| 590 | remote_message = '\n'.join(preamble + [stdout]) |
| 591 | # Add a new line at start of message to clearly delineate from previous |
| 592 | # output/text already on the remote tty we are printing to. |
| 593 | self.build.stdout.write(f'\n{remote_message}') |
| 594 | self.build.stdout.flush() |
Mohamed Heikal | 9984e43 | 2024-12-03 18:21:40 | [diff] [blame] | 595 | if delete_stamp: |
| 596 | # Force siso to consider failed targets as dirty. |
| 597 | try: |
Andrew Grieve | 0d6e8a75 | 2025-02-05 21:20:50 | [diff] [blame^] | 598 | os.unlink(os.path.join(self.build.cwd, self.stamp_file)) |
Mohamed Heikal | 9984e43 | 2024-12-03 18:21:40 | [diff] [blame] | 599 | except FileNotFoundError: |
| 600 | pass |
| 601 | else: |
| 602 | # We do not care about the action writing a too new mtime. Siso only cares |
| 603 | # about the mtime that is recorded in its database at the time the |
| 604 | # original action finished. |
| 605 | pass |
Mohamed Heikal | abf646e | 2024-12-12 16:06:05 | [diff] [blame] | 606 | TaskManager.task_done(self) |
| 607 | set_status(f'{status_string} {self.name}', |
| 608 | quiet=self.options.quiet, |
Andrew Grieve | 0d6e8a75 | 2025-02-05 21:20:50 | [diff] [blame^] | 609 | build_id=self.build.id) |
Peter Wen | b1f3b1d | 2021-02-02 21:30:20 | [diff] [blame] | 610 | |
| 611 | |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 612 | def _handle_add_task(data, current_tasks: Dict[Tuple[str, str], Task], options): |
| 613 | """Handle messages of type ADD_TASK.""" |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 614 | build_id = data['build_id'] |
Andrew Grieve | 0d6e8a75 | 2025-02-05 21:20:50 | [diff] [blame^] | 615 | build = BuildManager.get_build(build_id) |
| 616 | BuildManager.maybe_init_cwd(build, data.get('cwd')) |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 617 | |
| 618 | new_task = Task(name=data['name'], |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 619 | cmd=data['cmd'], |
Andrew Grieve | 0d6e8a75 | 2025-02-05 21:20:50 | [diff] [blame^] | 620 | build=build, |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 621 | stamp_file=data['stamp_file'], |
| 622 | options=options) |
| 623 | existing_task = current_tasks.get(new_task.key) |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 624 | if existing_task: |
Mohamed Heikal | 9984e43 | 2024-12-03 18:21:40 | [diff] [blame] | 625 | existing_task.terminate(replaced=True) |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 626 | current_tasks[new_task.key] = new_task |
| 627 | |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 628 | TaskManager.add_task(new_task, options) |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 629 | |
| 630 | |
| 631 | def _handle_query_build(data, connection: socket.socket): |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 632 | """Handle messages of type QUERY_BUILD.""" |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 633 | build_id = data['build_id'] |
Andrew Grieve | d863d0f | 2024-12-13 20:13:01 | [diff] [blame] | 634 | response = TaskStats.query_build(build_id) |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 635 | try: |
| 636 | with connection: |
Mohamed Heikal | f11b6f3 | 2025-01-30 19:44:29 | [diff] [blame] | 637 | server_utils.SendMessage(connection, response) |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 638 | except BrokenPipeError: |
| 639 | # We should not die because the client died. |
| 640 | pass |
| 641 | |
| 642 | |
| 643 | def _handle_heartbeat(connection: socket.socket): |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 644 | """Handle messages of type POLL_HEARTBEAT.""" |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 645 | try: |
| 646 | with connection: |
Mohamed Heikal | f11b6f3 | 2025-01-30 19:44:29 | [diff] [blame] | 647 | server_utils.SendMessage(connection, { |
| 648 | 'status': 'OK', |
| 649 | 'pid': os.getpid(), |
| 650 | }) |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 651 | except BrokenPipeError: |
| 652 | # We should not die because the client died. |
| 653 | pass |
| 654 | |
| 655 | |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 656 | def _handle_register_builder(data): |
| 657 | """Handle messages of type REGISTER_BUILDER.""" |
Andrew Grieve | 0d6e8a75 | 2025-02-05 21:20:50 | [diff] [blame^] | 658 | env = data['env'] |
| 659 | pid = int(data['builder_pid']) |
| 660 | cwd = data['cwd'] |
| 661 | |
| 662 | BuildManager.register_builder(env, pid, cwd) |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 663 | |
| 664 | |
| 665 | def _handle_cancel_build(data): |
| 666 | """Handle messages of type CANCEL_BUILD.""" |
| 667 | build_id = data['build_id'] |
| 668 | TaskManager.cancel_build(build_id) |
| 669 | |
| 670 | |
| 671 | def _listen_for_request_data(sock: socket.socket): |
| 672 | """Helper to encapsulate getting a new message.""" |
| 673 | while True: |
| 674 | conn = sock.accept()[0] |
Mohamed Heikal | f11b6f3 | 2025-01-30 19:44:29 | [diff] [blame] | 675 | message = server_utils.ReceiveMessage(conn) |
| 676 | if message: |
| 677 | yield message, conn |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 678 | |
| 679 | |
Mohamed Heikal | abf646e | 2024-12-12 16:06:05 | [diff] [blame] | 680 | def _register_cleanup_signal_handlers(options): |
| 681 | original_sigint_handler = signal.getsignal(signal.SIGINT) |
| 682 | original_sigterm_handler = signal.getsignal(signal.SIGTERM) |
| 683 | |
| 684 | def _cleanup(signum, frame): |
| 685 | log('STOPPING SERVER...', quiet=options.quiet) |
| 686 | # Gracefully shut down the task manager, terminating all queued tasks. |
| 687 | TaskManager.deactivate() |
| 688 | log('STOPPED', quiet=options.quiet) |
| 689 | if signum == signal.SIGINT: |
| 690 | if callable(original_sigint_handler): |
| 691 | original_sigint_handler(signum, frame) |
| 692 | else: |
| 693 | raise KeyboardInterrupt() |
| 694 | if signum == signal.SIGTERM: |
| 695 | # Sometimes sigterm handler is not a callable. |
| 696 | if callable(original_sigterm_handler): |
| 697 | original_sigterm_handler(signum, frame) |
| 698 | else: |
| 699 | sys.exit(1) |
| 700 | |
| 701 | signal.signal(signal.SIGINT, _cleanup) |
| 702 | signal.signal(signal.SIGTERM, _cleanup) |
| 703 | |
| 704 | |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 705 | def _process_requests(sock: socket.socket, options): |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 706 | """Main loop for build server receiving request messages.""" |
Peter Wen | 6e7e52b | 2021-02-13 02:39:28 | [diff] [blame] | 707 | # Since dicts in python can contain anything, explicitly type tasks to help |
| 708 | # make static type checking more useful. |
| 709 | tasks: Dict[Tuple[str, str], Task] = {} |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 710 | log( |
| 711 | 'READY... Remember to set android_static_analysis="build_server" in ' |
| 712 | 'args.gn files', |
| 713 | quiet=options.quiet) |
Mohamed Heikal | abf646e | 2024-12-12 16:06:05 | [diff] [blame] | 714 | _register_cleanup_signal_handlers(options) |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 715 | # pylint: disable=too-many-nested-blocks |
Mohamed Heikal | abf646e | 2024-12-12 16:06:05 | [diff] [blame] | 716 | while True: |
| 717 | try: |
| 718 | for data, connection in _listen_for_request_data(sock): |
| 719 | message_type = data.get('message_type', server_utils.ADD_TASK) |
| 720 | if message_type == server_utils.POLL_HEARTBEAT: |
| 721 | _handle_heartbeat(connection) |
Mohamed Heikal | f11b6f3 | 2025-01-30 19:44:29 | [diff] [blame] | 722 | elif message_type == server_utils.ADD_TASK: |
Mohamed Heikal | abf646e | 2024-12-12 16:06:05 | [diff] [blame] | 723 | connection.close() |
| 724 | _handle_add_task(data, tasks, options) |
Mohamed Heikal | f11b6f3 | 2025-01-30 19:44:29 | [diff] [blame] | 725 | elif message_type == server_utils.QUERY_BUILD: |
Mohamed Heikal | abf646e | 2024-12-12 16:06:05 | [diff] [blame] | 726 | _handle_query_build(data, connection) |
Mohamed Heikal | f11b6f3 | 2025-01-30 19:44:29 | [diff] [blame] | 727 | elif message_type == server_utils.REGISTER_BUILDER: |
Mohamed Heikal | abf646e | 2024-12-12 16:06:05 | [diff] [blame] | 728 | connection.close() |
| 729 | _handle_register_builder(data) |
Mohamed Heikal | f11b6f3 | 2025-01-30 19:44:29 | [diff] [blame] | 730 | elif message_type == server_utils.CANCEL_BUILD: |
Mohamed Heikal | abf646e | 2024-12-12 16:06:05 | [diff] [blame] | 731 | connection.close() |
| 732 | _handle_cancel_build(data) |
Mohamed Heikal | f11b6f3 | 2025-01-30 19:44:29 | [diff] [blame] | 733 | else: |
| 734 | connection.close() |
Mohamed Heikal | abf646e | 2024-12-12 16:06:05 | [diff] [blame] | 735 | except TimeoutError: |
| 736 | # If we have not received a new task in a while and do not have any |
| 737 | # pending tasks or running builds, then exit. Otherwise keep waiting. |
| 738 | if (TaskStats.num_pending_tasks() == 0 |
| 739 | and not BuildManager.has_live_builds() and options.exit_on_idle): |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 740 | break |
Mohamed Heikal | abf646e | 2024-12-12 16:06:05 | [diff] [blame] | 741 | except KeyboardInterrupt: |
| 742 | break |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 743 | |
| 744 | |
Mohamed Heikal | f11b6f3 | 2025-01-30 19:44:29 | [diff] [blame] | 745 | def query_build_info(build_id=None): |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 746 | """Communicates with the main server to query build info.""" |
Mohamed Heikal | f11b6f3 | 2025-01-30 19:44:29 | [diff] [blame] | 747 | return _send_message_with_response({ |
| 748 | 'message_type': server_utils.QUERY_BUILD, |
| 749 | 'build_id': build_id, |
| 750 | }) |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 751 | |
| 752 | |
| 753 | def _wait_for_build(build_id): |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 754 | """Comunicates with the main server waiting for a build to complete.""" |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 755 | start_time = datetime.datetime.now() |
| 756 | while True: |
Andrew Grieve | d863d0f | 2024-12-13 20:13:01 | [diff] [blame] | 757 | try: |
| 758 | build_info = query_build_info(build_id)['builds'][0] |
| 759 | except ConnectionRefusedError: |
| 760 | print('No server running. It likely finished all tasks.') |
| 761 | print('You can check $OUTDIR/buildserver.log.0 to be sure.') |
| 762 | return 0 |
| 763 | |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 764 | pending_tasks = build_info['pending_tasks'] |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 765 | |
| 766 | if pending_tasks == 0: |
| 767 | print(f'\nAll tasks completed for build_id: {build_id}.') |
| 768 | return 0 |
| 769 | |
| 770 | current_time = datetime.datetime.now() |
| 771 | duration = current_time - start_time |
| 772 | print(f'\rWaiting for {pending_tasks} tasks [{str(duration)}]\033[K', |
| 773 | end='', |
| 774 | flush=True) |
| 775 | time.sleep(1) |
| 776 | |
| 777 | |
Mohamed Heikal | f11b6f3 | 2025-01-30 19:44:29 | [diff] [blame] | 778 | def _wait_for_idle(): |
| 779 | """Communicates with the main server waiting for all builds to complete.""" |
| 780 | start_time = datetime.datetime.now() |
| 781 | while True: |
| 782 | try: |
| 783 | builds = query_build_info()['builds'] |
| 784 | except ConnectionRefusedError: |
| 785 | print('No server running. It likely finished all tasks.') |
| 786 | print('You can check $OUTDIR/buildserver.log.0 to be sure.') |
| 787 | return 0 |
| 788 | |
| 789 | all_pending_tasks = 0 |
| 790 | all_completed_tasks = 0 |
| 791 | for build_info in builds: |
| 792 | pending_tasks = build_info['pending_tasks'] |
| 793 | completed_tasks = build_info['completed_tasks'] |
| 794 | active = build_info['is_active'] |
| 795 | # Ignore completed builds. |
| 796 | if active or pending_tasks: |
| 797 | all_pending_tasks += pending_tasks |
| 798 | all_completed_tasks += completed_tasks |
| 799 | total_tasks = all_pending_tasks + all_completed_tasks |
| 800 | |
| 801 | if all_pending_tasks == 0: |
| 802 | print('\nServer Idle, All tasks complete.') |
| 803 | return 0 |
| 804 | |
| 805 | current_time = datetime.datetime.now() |
| 806 | duration = current_time - start_time |
| 807 | print( |
| 808 | f'\rWaiting for {all_pending_tasks} remaining tasks. ' |
| 809 | f'({all_completed_tasks}/{total_tasks} tasks complete) ' |
| 810 | f'[{str(duration)}]\033[K', |
| 811 | end='', |
| 812 | flush=True) |
| 813 | time.sleep(0.5) |
| 814 | |
| 815 | |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 816 | def _check_if_running(): |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 817 | """Communicates with the main server to make sure its running.""" |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 818 | with socket.socket(socket.AF_UNIX) as sock: |
| 819 | try: |
| 820 | sock.connect(server_utils.SOCKET_ADDRESS) |
Mohamed Heikal | f11b6f3 | 2025-01-30 19:44:29 | [diff] [blame] | 821 | except OSError: |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 822 | print('Build server is not running and ' |
| 823 | 'android_static_analysis="build_server" is set.\nPlease run ' |
| 824 | 'this command in a separate terminal:\n\n' |
| 825 | '$ build/android/fast_local_dev_server.py\n') |
| 826 | return 1 |
| 827 | else: |
| 828 | return 0 |
| 829 | |
| 830 | |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 831 | def _send_message_and_close(message_dict): |
| 832 | with contextlib.closing(socket.socket(socket.AF_UNIX)) as sock: |
| 833 | sock.connect(server_utils.SOCKET_ADDRESS) |
Mohamed Heikal | f11b6f3 | 2025-01-30 19:44:29 | [diff] [blame] | 834 | sock.settimeout(1) |
| 835 | server_utils.SendMessage(sock, message_dict) |
| 836 | |
| 837 | |
| 838 | def _send_message_with_response(message_dict): |
| 839 | with contextlib.closing(socket.socket(socket.AF_UNIX)) as sock: |
| 840 | sock.connect(server_utils.SOCKET_ADDRESS) |
| 841 | sock.settimeout(1) |
| 842 | server_utils.SendMessage(sock, message_dict) |
| 843 | return server_utils.ReceiveMessage(sock) |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 844 | |
| 845 | |
| 846 | def _send_cancel_build(build_id): |
| 847 | _send_message_and_close({ |
| 848 | 'message_type': server_utils.CANCEL_BUILD, |
| 849 | 'build_id': build_id, |
| 850 | }) |
| 851 | return 0 |
| 852 | |
| 853 | |
Andrew Grieve | 0d6e8a75 | 2025-02-05 21:20:50 | [diff] [blame^] | 854 | def _register_builder(build_id, builder_pid, output_directory): |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 855 | for _attempt in range(3): |
| 856 | try: |
Andrew Grieve | 0d6e8a75 | 2025-02-05 21:20:50 | [diff] [blame^] | 857 | # Ensure environment variables that the server expects to be there are |
| 858 | # present. |
| 859 | server_utils.AssertEnvironmentVariables() |
| 860 | |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 861 | _send_message_and_close({ |
| 862 | 'message_type': server_utils.REGISTER_BUILDER, |
Andrew Grieve | 0d6e8a75 | 2025-02-05 21:20:50 | [diff] [blame^] | 863 | 'env': dict(os.environ), |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 864 | 'builder_pid': builder_pid, |
Andrew Grieve | 0d6e8a75 | 2025-02-05 21:20:50 | [diff] [blame^] | 865 | 'cwd': output_directory, |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 866 | }) |
| 867 | return 0 |
Mohamed Heikal | f11b6f3 | 2025-01-30 19:44:29 | [diff] [blame] | 868 | except OSError: |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 869 | time.sleep(0.05) |
| 870 | print(f'Failed to register builer for build_id={build_id}.') |
| 871 | return 1 |
| 872 | |
| 873 | |
Mohamed Heikal | f11b6f3 | 2025-01-30 19:44:29 | [diff] [blame] | 874 | def poll_server(retries=3): |
| 875 | """Communicates with the main server to query build info.""" |
| 876 | for _attempt in range(retries): |
| 877 | try: |
| 878 | response = _send_message_with_response( |
| 879 | {'message_type': server_utils.POLL_HEARTBEAT}) |
| 880 | if response: |
| 881 | break |
| 882 | except OSError: |
| 883 | time.sleep(0.05) |
| 884 | else: |
| 885 | return None |
| 886 | return response['pid'] |
| 887 | |
| 888 | |
Andrew Grieve | d863d0f | 2024-12-13 20:13:01 | [diff] [blame] | 889 | def _print_build_status_all(): |
| 890 | try: |
| 891 | query_data = query_build_info(None) |
| 892 | except ConnectionRefusedError: |
| 893 | print('No server running. Consult $OUTDIR/buildserver.log.0') |
| 894 | return 0 |
| 895 | builds = query_data['builds'] |
| 896 | pid = query_data['pid'] |
| 897 | all_active_tasks = [] |
| 898 | print(f'Build server (PID={pid}) has {len(builds)} registered builds') |
| 899 | for build_info in builds: |
| 900 | build_id = build_info['build_id'] |
| 901 | pending_tasks = build_info['pending_tasks'] |
| 902 | completed_tasks = build_info['completed_tasks'] |
| 903 | active_tasks = build_info['active_tasks'] |
| 904 | out_dir = build_info['outdir'] |
| 905 | active = build_info['is_active'] |
| 906 | total_tasks = pending_tasks + completed_tasks |
| 907 | all_active_tasks += active_tasks |
| 908 | if total_tasks == 0 and not active: |
| 909 | status = 'Finished without any jobs' |
| 910 | else: |
| 911 | if active: |
| 912 | status = 'Siso still running' |
| 913 | else: |
| 914 | status = 'Siso finished' |
| 915 | if out_dir: |
| 916 | status += f' in {out_dir}' |
| 917 | status += f'. Completed [{completed_tasks}/{total_tasks}].' |
| 918 | if completed_tasks < total_tasks: |
| 919 | status += f' {len(active_tasks)} tasks currently executing' |
| 920 | print(f'{build_id}: {status}') |
| 921 | if all_active_tasks: |
| 922 | total = len(all_active_tasks) |
| 923 | to_show = min(4, total) |
| 924 | print(f'Currently executing (showing {to_show} of {total}):') |
| 925 | for cmd in sorted(all_active_tasks)[:to_show]: |
| 926 | truncated = shlex.join(cmd) |
| 927 | if len(truncated) > 200: |
| 928 | truncated = truncated[:200] + '...' |
| 929 | print(truncated) |
| 930 | return 0 |
| 931 | |
| 932 | |
Mohamed Heikal | 6b56cf6 | 2024-12-10 23:14:55 | [diff] [blame] | 933 | def _print_build_status(build_id): |
Andrew Grieve | d863d0f | 2024-12-13 20:13:01 | [diff] [blame] | 934 | try: |
| 935 | build_info = query_build_info(build_id)['builds'][0] |
| 936 | except ConnectionRefusedError: |
| 937 | print('No server running. Consult $OUTDIR/buildserver.log.0') |
| 938 | return 0 |
Mohamed Heikal | 6b56cf6 | 2024-12-10 23:14:55 | [diff] [blame] | 939 | pending_tasks = build_info['pending_tasks'] |
| 940 | completed_tasks = build_info['completed_tasks'] |
| 941 | total_tasks = pending_tasks + completed_tasks |
| 942 | |
| 943 | # Print nothing if we never got any tasks. |
| 944 | if completed_tasks: |
Andrew Grieve | 5201141 | 2025-02-03 18:57:59 | [diff] [blame] | 945 | print(f'Build Server Status: [{completed_tasks}/{total_tasks}]') |
Mohamed Heikal | 6b56cf6 | 2024-12-10 23:14:55 | [diff] [blame] | 946 | if pending_tasks: |
Mohamed Heikal | 6b56cf6 | 2024-12-10 23:14:55 | [diff] [blame] | 947 | server_path = os.path.relpath(str(server_utils.SERVER_SCRIPT)) |
Andrew Grieve | 5201141 | 2025-02-03 18:57:59 | [diff] [blame] | 948 | print('To wait for jobs:', shlex.join([server_path, '--wait-for-idle'])) |
Mohamed Heikal | 6b56cf6 | 2024-12-10 23:14:55 | [diff] [blame] | 949 | return 0 |
| 950 | |
| 951 | |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 952 | def _wait_for_task_requests(args): |
| 953 | with socket.socket(socket.AF_UNIX) as sock: |
| 954 | sock.settimeout(_SOCKET_TIMEOUT) |
| 955 | try: |
| 956 | sock.bind(server_utils.SOCKET_ADDRESS) |
Mohamed Heikal | f11b6f3 | 2025-01-30 19:44:29 | [diff] [blame] | 957 | except OSError as e: |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 958 | # errno 98 is Address already in use |
| 959 | if e.errno == 98: |
Mohamed Heikal | 08b467e0 | 2025-01-27 20:54:25 | [diff] [blame] | 960 | if not args.quiet: |
Mohamed Heikal | f11b6f3 | 2025-01-30 19:44:29 | [diff] [blame] | 961 | pid = poll_server() |
| 962 | print(f'Another instance is already running (pid: {pid}).', |
| 963 | file=sys.stderr) |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 964 | return 1 |
| 965 | raise |
| 966 | sock.listen() |
| 967 | _process_requests(sock, args) |
| 968 | return 0 |
Peter Wen | b1f3b1d | 2021-02-02 21:30:20 | [diff] [blame] | 969 | |
| 970 | |
| 971 | def main(): |
Andrew Grieve | d863d0f | 2024-12-13 20:13:01 | [diff] [blame] | 972 | # pylint: disable=too-many-return-statements |
Peter Wen | f409c0c | 2021-02-09 19:33:02 | [diff] [blame] | 973 | parser = argparse.ArgumentParser(description=__doc__) |
Peter Wen | d70f486 | 2022-02-02 16:00:16 | [diff] [blame] | 974 | parser.add_argument( |
| 975 | '--fail-if-not-running', |
| 976 | action='store_true', |
| 977 | help='Used by GN to fail fast if the build server is not running.') |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 978 | parser.add_argument( |
| 979 | '--exit-on-idle', |
| 980 | action='store_true', |
| 981 | help='Server started on demand. Exit when all tasks run out.') |
| 982 | parser.add_argument('--quiet', |
| 983 | action='store_true', |
| 984 | help='Do not output status updates.') |
| 985 | parser.add_argument('--wait-for-build', |
| 986 | metavar='BUILD_ID', |
| 987 | help='Wait for build server to finish with all tasks ' |
| 988 | 'for BUILD_ID and output any pending messages.') |
Mohamed Heikal | f11b6f3 | 2025-01-30 19:44:29 | [diff] [blame] | 989 | parser.add_argument('--wait-for-idle', |
| 990 | action='store_true', |
| 991 | help='Wait for build server to finish with all ' |
| 992 | 'pending tasks.') |
Mohamed Heikal | 6b56cf6 | 2024-12-10 23:14:55 | [diff] [blame] | 993 | parser.add_argument('--print-status', |
| 994 | metavar='BUILD_ID', |
| 995 | help='Print the current state of a build.') |
Andrew Grieve | d863d0f | 2024-12-13 20:13:01 | [diff] [blame] | 996 | parser.add_argument('--print-status-all', |
| 997 | action='store_true', |
| 998 | help='Print the current state of all active builds.') |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 999 | parser.add_argument( |
| 1000 | '--register-build-id', |
| 1001 | metavar='BUILD_ID', |
| 1002 | help='Inform the build server that a new build has started.') |
Andrew Grieve | 0d6e8a75 | 2025-02-05 21:20:50 | [diff] [blame^] | 1003 | parser.add_argument('--output-directory', |
| 1004 | help='Build directory (use with --register-build-id)') |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 1005 | parser.add_argument('--builder-pid', |
| 1006 | help='Builder process\'s pid for build BUILD_ID.') |
| 1007 | parser.add_argument('--cancel-build', |
| 1008 | metavar='BUILD_ID', |
| 1009 | help='Cancel all pending and running tasks for BUILD_ID.') |
Peter Wen | d70f486 | 2022-02-02 16:00:16 | [diff] [blame] | 1010 | args = parser.parse_args() |
| 1011 | if args.fail_if_not_running: |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 1012 | return _check_if_running() |
| 1013 | if args.wait_for_build: |
| 1014 | return _wait_for_build(args.wait_for_build) |
Mohamed Heikal | f11b6f3 | 2025-01-30 19:44:29 | [diff] [blame] | 1015 | if args.wait_for_idle: |
| 1016 | return _wait_for_idle() |
Mohamed Heikal | 6b56cf6 | 2024-12-10 23:14:55 | [diff] [blame] | 1017 | if args.print_status: |
| 1018 | return _print_build_status(args.print_status) |
Andrew Grieve | d863d0f | 2024-12-13 20:13:01 | [diff] [blame] | 1019 | if args.print_status_all: |
| 1020 | return _print_build_status_all() |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 1021 | if args.register_build_id: |
Andrew Grieve | 0d6e8a75 | 2025-02-05 21:20:50 | [diff] [blame^] | 1022 | return _register_builder(args.register_build_id, args.builder_pid, |
| 1023 | args.output_directory) |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 1024 | if args.cancel_build: |
| 1025 | return _send_cancel_build(args.cancel_build) |
Mohamed Heikal | f746b57f | 2024-11-13 21:20:17 | [diff] [blame] | 1026 | return _wait_for_task_requests(args) |
Peter Wen | b1f3b1d | 2021-02-02 21:30:20 | [diff] [blame] | 1027 | |
| 1028 | |
| 1029 | if __name__ == '__main__': |
Mohamed Heikal | b752b77 | 2024-11-25 23:05:44 | [diff] [blame] | 1030 | sys.excepthook = _exception_hook |
Peter Wen | b1f3b1d | 2021-02-02 21:30:20 | [diff] [blame] | 1031 | sys.exit(main()) |