Debian Codegraph @

Lib/test/libregrtest/run_workers.py

raw
1 import contextlib
2 import dataclasses
3 import faulthandler
4 import os.path
5 import queue
6 import signal
7 import subprocess
8 import sys
9 import tempfile
10 import threading
11 import time
12 import traceback
13 from typing import Any, Literal, TextIO
14
15 from test import support
16 from test.support import os_helper, MS_WINDOWS
17
18 from .logger import Logger
19 from .result import TestResult, State
20 from .results import TestResults
21 from .runtests import RunTests, WorkerRunTests, JsonFile, JsonFileType
22 from .single import PROGRESS_MIN_TIME
23 from .utils import (
24 StrPath, TestName,
25 format_duration, print_warning, count, plural, get_signal_name)
26 from .worker import create_worker_process, USE_PROCESS_GROUP
27
28 if MS_WINDOWS:
29 import locale
30 import msvcrt
31
32
33
34 # Display the running tests if nothing happened last N seconds
35 PROGRESS_UPDATE = 30.0 # seconds
36 assert PROGRESS_UPDATE >= PROGRESS_MIN_TIME
37
38 # Kill the main process after 5 minutes. It is supposed to write an update
39 # every PROGRESS_UPDATE seconds. Tolerate 5 minutes for Python slowest
40 # buildbot workers.
41 MAIN_PROCESS_TIMEOUT = 5 * 60.0
42 assert MAIN_PROCESS_TIMEOUT >= PROGRESS_UPDATE
43
44 # Time to wait until a worker completes: should be immediate
45 WAIT_COMPLETED_TIMEOUT = 30.0 # seconds
46
47 # Time to wait a killed process (in seconds)
48 WAIT_KILLED_TIMEOUT = 60.0
49
50
51 # We do not use a generator so multiple threads can call next().
52 class MultiprocessIterator:
53
54 """A thread-safe iterator over tests for multiprocess mode."""
55
56 def __init__(self, tests_iter):
57 self.lock = threading.Lock()
58 self.tests_iter = tests_iter
59
60 def __iter__(self):
61 return self
62
63 def __next__(self):
64 with self.lock:
65 if self.tests_iter is None:
66 raise StopIteration
67 return next(self.tests_iter)
68
69 def stop(self):
70 with self.lock:
71 self.tests_iter = None
72
73
74 @dataclasses.dataclass(slots=True, frozen=True)
75 class MultiprocessResult:
76 result: TestResult
77 # bpo-45410: stderr is written into stdout to keep messages order
78 worker_stdout: str | None = None
79 err_msg: str | None = None
80
81
82 class WorkerThreadExited:
83 """Indicates that a worker thread has exited"""
84
85 ExcStr = str
86 QueueOutput = tuple[Literal[False], MultiprocessResult] | tuple[Literal[True], ExcStr]
87 QueueContent = QueueOutput | WorkerThreadExited
88
89
90 class ExitThread(Exception):
91 pass
92
93
94 class WorkerError(Exception):
95 def __init__(self,
96 test_name: TestName,
97 err_msg: str | None,
98 stdout: str | None,
99 state: str):
100 result = TestResult(test_name, state=state)
101 self.mp_result = MultiprocessResult(result, stdout, err_msg)
102 super().__init__()
103
104
105 _NOT_RUNNING = "<not running>"
106
107
108 class WorkerThread(threading.Thread):
109 def __init__(self, worker_id: int, runner: "RunWorkers") -> None:
110 super().__init__()
111 self.worker_id = worker_id
112 self.runtests = runner.runtests
113 self.pending = runner.pending
114 self.output = runner.output
115 self.timeout = runner.worker_timeout
116 self.log = runner.log
117 self.test_name = _NOT_RUNNING
118 self.start_time = time.monotonic()
119 self._popen: subprocess.Popen[str] | None = None
120 self._killed = False
121 self._stopped = False
122
123 def __repr__(self) -> str:
124 info = [f'WorkerThread #{self.worker_id}']
125 if self.is_alive():
126 info.append("running")
127 else:
128 info.append('stopped')
129 test = self.test_name
130 if test:
131 info.append(f'test={test}')
132 popen = self._popen
133 if popen is not None:
134 dt = time.monotonic() - self.start_time
135 info.extend((f'pid={popen.pid}',
136 f'time={format_duration(dt)}'))
137 return '<%s>' % ' '.join(info)
138
139 def _kill(self) -> None:
140 popen = self._popen
141 if popen is None:
142 return
143
144 if self._killed:
145 return
146 self._killed = True
147
148 if USE_PROCESS_GROUP:
149 what = f"{self} process group"
150 else:
151 what = f"{self} process"
152
153 print(f"Kill {what}", file=sys.stderr, flush=True)
154 try:
155 if USE_PROCESS_GROUP:
156 os.killpg(popen.pid, signal.SIGKILL)
157 else:
158 popen.kill()
159 except ProcessLookupError:
160 # popen.kill(): the process completed, the WorkerThread thread
161 # read its exit status, but Popen.send_signal() read the returncode
162 # just before Popen.wait() set returncode.
163 pass
164 except OSError as exc:
165 print_warning(f"Failed to kill {what}: {exc!r}")
166
167 def stop(self) -> None:
168 # Method called from a different thread to stop this thread
169 self._stopped = True
170 self._kill()
171
172 def _run_process(self, runtests: WorkerRunTests, output_fd: int,
173 tmp_dir: StrPath | None = None) -> int | None:
174 popen = create_worker_process(runtests, output_fd, tmp_dir)
175 self._popen = popen
176 self._killed = False
177
178 try:
179 if self._stopped:
180 # If kill() has been called before self._popen is set,
181 # self._popen is still running. Call again kill()
182 # to ensure that the process is killed.
183 self._kill()
184 raise ExitThread
185
186 try:
187 # gh-94026: stdout+stderr are written to tempfile
188 retcode = popen.wait(timeout=self.timeout)
189 assert retcode is not None
190 return retcode
191 except subprocess.TimeoutExpired:
192 if self._stopped:
193 # kill() has been called: communicate() fails on reading
194 # closed stdout
195 raise ExitThread
196
197 # On timeout, kill the process
198 self._kill()
199
200 # None means TIMEOUT for the caller
201 retcode = None
202 # bpo-38207: Don't attempt to call communicate() again: on it
203 # can hang until all child processes using stdout
204 # pipes completes.
205 except OSError:
206 if self._stopped:
207 # kill() has been called: communicate() fails
208 # on reading closed stdout
209 raise ExitThread
210 raise
211 return None
212 except:
213 self._kill()
214 raise
215 finally:
216 self._wait_completed()
217 self._popen = None
218
219 def create_stdout(self, stack: contextlib.ExitStack) -> TextIO:
220 """Create stdout temporary file (file descriptor)."""
221
222 if MS_WINDOWS:
223 # gh-95027: When stdout is not a TTY, Python uses the ANSI code
224 # page for the sys.stdout encoding. If the main process runs in a
225 # terminal, sys.stdout uses WindowsConsoleIO with UTF-8 encoding.
226 encoding = locale.getencoding()
227 else:
228 encoding = sys.stdout.encoding
229
230 # gh-94026: Write stdout+stderr to a tempfile as workaround for
231 # non-blocking pipes on Emscripten with NodeJS.
232 # gh-109425: Use "backslashreplace" error handler: log corrupted
233 # stdout+stderr, instead of failing with a UnicodeDecodeError and not
234 # logging stdout+stderr at all.
235 stdout_file = tempfile.TemporaryFile('w+',
236 encoding=encoding,
237 errors='backslashreplace')
238 stack.enter_context(stdout_file)
239 return stdout_file
240
241 def create_json_file(self, stack: contextlib.ExitStack) -> tuple[JsonFile, TextIO | None]:
242 """Create JSON file."""
243
244 json_file_use_stdout = self.runtests.json_file_use_stdout()
245 if json_file_use_stdout:
246 json_file = JsonFile(None, JsonFileType.STDOUT)
247 json_tmpfile = None
248 else:
249 json_tmpfile = tempfile.TemporaryFile('w+', encoding='utf8')
250 stack.enter_context(json_tmpfile)
251
252 json_fd = json_tmpfile.fileno()
253 if MS_WINDOWS:
254 # The msvcrt module is only available on Windows;
255 # we run mypy with `--platform=linux` in CI
256 json_handle: int = msvcrt.get_osfhandle(json_fd) # type: ignore[attr-defined]
257 json_file = JsonFile(json_handle,
258 JsonFileType.WINDOWS_HANDLE)
259 else:
260 json_file = JsonFile(json_fd, JsonFileType.UNIX_FD)
261 return (json_file, json_tmpfile)
262
263 def create_worker_runtests(self, test_name: TestName, json_file: JsonFile) -> WorkerRunTests:
264 tests = (test_name,)
265 if self.runtests.rerun:
266 match_tests = self.runtests.get_match_tests(test_name)
267 else:
268 match_tests = None
269
270 kwargs: dict[str, Any] = {}
271 if match_tests:
272 kwargs['match_tests'] = [(test, True) for test in match_tests]
273 if self.runtests.output_on_failure:
274 kwargs['verbose'] = True
275 kwargs['output_on_failure'] = False
276 return self.runtests.create_worker_runtests(
277 tests=tests,
278 json_file=json_file,
279 **kwargs)
280
281 def run_tmp_files(self, worker_runtests: WorkerRunTests,
282 stdout_fd: int) -> tuple[int | None, list[StrPath]]:
283 # gh-93353: Check for leaked temporary files in the parent process,
284 # since the deletion of temporary files can happen late during
285 # Python finalization: too late for libregrtest.
286 if not support.is_wasi:
287 # Don't check for leaked temporary files and directories if Python is
288 # run on WASI. WASI doesn't pass environment variables like TMPDIR to
289 # worker processes.
290 tmp_dir = tempfile.mkdtemp(prefix="test_python_")
291 tmp_dir = os.path.abspath(tmp_dir)
292 try:
293 retcode = self._run_process(worker_runtests,
294 stdout_fd, tmp_dir)
295 finally:
296 tmp_files = os.listdir(tmp_dir)
297 os_helper.rmtree(tmp_dir)
298 else:
299 retcode = self._run_process(worker_runtests, stdout_fd)
300 tmp_files = []
301
302 return (retcode, tmp_files)
303
304 def read_stdout(self, stdout_file: TextIO) -> str:
305 stdout_file.seek(0)
306 try:
307 return stdout_file.read().strip()
308 except Exception as exc:
309 # gh-101634: Catch UnicodeDecodeError if stdout cannot be
310 # decoded from encoding
311 raise WorkerError(self.test_name,
312 f"Cannot read process stdout: {exc}",
313 stdout=None,
314 state=State.WORKER_BUG)
315
316 def read_json(self, json_file: JsonFile, json_tmpfile: TextIO | None,
317 stdout: str) -> tuple[TestResult, str]:
318 try:
319 if json_tmpfile is not None:
320 json_tmpfile.seek(0)
321 worker_json = json_tmpfile.read()
322 elif json_file.file_type == JsonFileType.STDOUT:
323 stdout, _, worker_json = stdout.rpartition("\n")
324 stdout = stdout.rstrip()
325 else:
326 with json_file.open(encoding='utf8') as json_fp:
327 worker_json = json_fp.read()
328 except Exception as exc:
329 # gh-101634: Catch UnicodeDecodeError if stdout cannot be
330 # decoded from encoding
331 err_msg = f"Failed to read worker process JSON: {exc}"
332 raise WorkerError(self.test_name, err_msg, stdout,
333 state=State.WORKER_BUG)
334
335 if not worker_json:
336 raise WorkerError(self.test_name, "empty JSON", stdout,
337 state=State.WORKER_BUG)
338
339 try:
340 result = TestResult.from_json(worker_json)
341 except Exception as exc:
342 # gh-101634: Catch UnicodeDecodeError if stdout cannot be
343 # decoded from encoding
344 err_msg = f"Failed to parse worker process JSON: {exc}"
345 raise WorkerError(self.test_name, err_msg, stdout,
346 state=State.WORKER_BUG)
347
348 return (result, stdout)
349
350 def _runtest(self, test_name: TestName) -> MultiprocessResult:
351 with contextlib.ExitStack() as stack:
352 stdout_file = self.create_stdout(stack)
353 json_file, json_tmpfile = self.create_json_file(stack)
354 worker_runtests = self.create_worker_runtests(test_name, json_file)
355
356 retcode: str | int | None
357 retcode, tmp_files = self.run_tmp_files(worker_runtests,
358 stdout_file.fileno())
359
360 stdout = self.read_stdout(stdout_file)
361
362 if retcode is None:
363 raise WorkerError(self.test_name, stdout=stdout,
364 err_msg=None,
365 state=State.TIMEOUT)
366 if retcode != 0:
367 name = get_signal_name(retcode)
368 if name:
369 retcode = f"{retcode} ({name})"
370 raise WorkerError(self.test_name, f"Exit code {retcode}", stdout,
371 state=State.WORKER_FAILED)
372
373 result, stdout = self.read_json(json_file, json_tmpfile, stdout)
374
375 if tmp_files:
376 msg = (f'\n\n'
377 f'Warning -- {test_name} leaked temporary files '
378 f'({len(tmp_files)}): {", ".join(sorted(tmp_files))}')
379 stdout += msg
380 result.set_env_changed()
381
382 return MultiprocessResult(result, stdout)
383
384 def run(self) -> None:
385 fail_fast = self.runtests.fail_fast
386 fail_env_changed = self.runtests.fail_env_changed
387 try:
388 while not self._stopped:
389 try:
390 test_name = next(self.pending)
391 except StopIteration:
392 break
393
394 self.start_time = time.monotonic()
395 self.test_name = test_name
396 try:
397 mp_result = self._runtest(test_name)
398 except WorkerError as exc:
399 mp_result = exc.mp_result
400 finally:
401 self.test_name = _NOT_RUNNING
402 mp_result.result.duration = time.monotonic() - self.start_time
403 self.output.put((False, mp_result))
404
405 if mp_result.result.must_stop(fail_fast, fail_env_changed):
406 break
407 except ExitThread:
408 pass
409 except BaseException:
410 self.output.put((True, traceback.format_exc()))
411 finally:
412 self.output.put(WorkerThreadExited())
413
414 def _wait_completed(self) -> None:
415 popen = self._popen
416 # only needed for mypy:
417 if popen is None:
418 raise ValueError("Should never access `._popen` before calling `.run()`")
419
420 try:
421 popen.wait(WAIT_COMPLETED_TIMEOUT)
422 except (subprocess.TimeoutExpired, OSError) as exc:
423 print_warning(f"Failed to wait for {self} completion "
424 f"(timeout={format_duration(WAIT_COMPLETED_TIMEOUT)}): "
425 f"{exc!r}")
426
427 def wait_stopped(self, start_time: float) -> None:
428 # bpo-38207: RunWorkers.stop_workers() called self.stop()
429 # which killed the process. Sometimes, killing the process from the
430 # main thread does not interrupt popen.communicate() in
431 # WorkerThread thread. This loop with a timeout is a workaround
432 # for that.
433 #
434 # Moreover, if this method fails to join the thread, it is likely
435 # that Python will hang at exit while calling threading._shutdown()
436 # which tries again to join the blocked thread. Regrtest.main()
437 # uses EXIT_TIMEOUT to workaround this second bug.
438 while True:
439 # Write a message every second
440 self.join(1.0)
441 if not self.is_alive():
442 break
443 dt = time.monotonic() - start_time
444 self.log(f"Waiting for {self} thread for {format_duration(dt)}")
445 if dt > WAIT_KILLED_TIMEOUT:
446 print_warning(f"Failed to join {self} in {format_duration(dt)}")
447 break
448
449
450 def get_running(workers: list[WorkerThread]) -> str | None:
451 running: list[str] = []
452 for worker in workers:
453 test_name = worker.test_name
454 if test_name == _NOT_RUNNING:
455 continue
456 dt = time.monotonic() - worker.start_time
457 if dt >= PROGRESS_MIN_TIME:
458 text = f'{test_name} ({format_duration(dt)})'
459 running.append(text)
460 if not running:
461 return None
462 return f"running ({len(running)}): {', '.join(running)}"
463
464
465 class RunWorkers:
466 def __init__(self, num_workers: int, runtests: RunTests,
467 logger: Logger, results: TestResults) -> None:
468 self.num_workers = num_workers
469 self.runtests = runtests
470 self.log = logger.log
471 self.display_progress = logger.display_progress
472 self.results: TestResults = results
473 self.live_worker_count = 0
474
475 self.output: queue.Queue[QueueContent] = queue.Queue()
476 tests_iter = runtests.iter_tests()
477 self.pending = MultiprocessIterator(tests_iter)
478 self.timeout = runtests.timeout
479 if self.timeout is not None:
480 # Rely on faulthandler to kill a worker process. This timouet is
481 # when faulthandler fails to kill a worker process. Give a maximum
482 # of 5 minutes to faulthandler to kill the worker.
483 self.worker_timeout: float | None = min(self.timeout * 1.5, self.timeout + 5 * 60)
484 else:
485 self.worker_timeout = None
486 self.workers: list[WorkerThread] = []
487
488 jobs = self.runtests.get_jobs()
489 if jobs is not None:
490 # Don't spawn more threads than the number of jobs:
491 # these worker threads would never get anything to do.
492 self.num_workers = min(self.num_workers, jobs)
493
494 def start_workers(self) -> None:
495 self.workers = [WorkerThread(index, self)
496 for index in range(1, self.num_workers + 1)]
497 jobs = self.runtests.get_jobs()
498 if jobs is not None:
499 tests = count(jobs, 'test')
500 else:
501 tests = 'tests'
502 nworkers = len(self.workers)
503 processes = plural(nworkers, "process", "processes")
504 msg = (f"Run {tests} in parallel using "
505 f"{nworkers} worker {processes}")
506 if self.timeout and self.worker_timeout is not None:
507 msg += (" (timeout: %s, worker timeout: %s)"
508 % (format_duration(self.timeout),
509 format_duration(self.worker_timeout)))
510 self.log(msg)
511 for worker in self.workers:
512 worker.start()
513 self.live_worker_count += 1
514
515 def stop_workers(self) -> None:
516 start_time = time.monotonic()
517 for worker in self.workers:
518 worker.stop()
519 for worker in self.workers:
520 worker.wait_stopped(start_time)
521
522 def _get_result(self) -> QueueOutput | None:
523 pgo = self.runtests.pgo
524 use_faulthandler = (self.timeout is not None)
525
526 # bpo-46205: check the status of workers every iteration to avoid
527 # waiting forever on an empty queue.
528 while self.live_worker_count > 0:
529 if use_faulthandler:
530 faulthandler.dump_traceback_later(MAIN_PROCESS_TIMEOUT,
531 exit=True)
532
533 # wait for a thread
534 try:
535 result = self.output.get(timeout=PROGRESS_UPDATE)
536 if isinstance(result, WorkerThreadExited):
537 self.live_worker_count -= 1
538 continue
539 return result
540 except queue.Empty:
541 pass
542
543 if not pgo:
544 # display progress
545 running = get_running(self.workers)
546 if running:
547 self.log(running)
548 return None
549
550 def display_result(self, mp_result: MultiprocessResult) -> None:
551 result = mp_result.result
552 pgo = self.runtests.pgo
553
554 text = str(result)
555 if mp_result.err_msg:
556 # WORKER_BUG
557 text += ' (%s)' % mp_result.err_msg
558 elif (result.duration and result.duration >= PROGRESS_MIN_TIME and not pgo):
559 text += ' (%s)' % format_duration(result.duration)
560 if not pgo:
561 running = get_running(self.workers)
562 if running:
563 text += f' -- {running}'
564 self.display_progress(self.test_index, text)
565
566 def _process_result(self, item: QueueOutput) -> TestResult:
567 """Returns True if test runner must stop."""
568 if item[0]:
569 # Thread got an exception
570 format_exc = item[1]
571 print_warning(f"regrtest worker thread failed: {format_exc}")
572 result = TestResult("<regrtest worker>", state=State.WORKER_BUG)
573 self.results.accumulate_result(result, self.runtests)
574 return result
575
576 self.test_index += 1
577 mp_result = item[1]
578 result = mp_result.result
579 self.results.accumulate_result(result, self.runtests)
580 self.display_result(mp_result)
581
582 # Display worker stdout
583 if not self.runtests.output_on_failure:
584 show_stdout = True
585 else:
586 # --verbose3 ignores stdout on success
587 show_stdout = (result.state != State.PASSED)
588 if show_stdout:
589 stdout = mp_result.worker_stdout
590 if stdout:
591 print(stdout, flush=True)
592
593 return result
594
595 def run(self) -> None:
596 fail_fast = self.runtests.fail_fast
597 fail_env_changed = self.runtests.fail_env_changed
598
599 self.start_workers()
600
601 self.test_index = 0
602 try:
603 while True:
604 item = self._get_result()
605 if item is None:
606 break
607
608 result = self._process_result(item)
609 if result.must_stop(fail_fast, fail_env_changed):
610 break
611 except KeyboardInterrupt:
612 print()
613 self.results.interrupted = True
614 finally:
615 if self.timeout is not None:
616 faulthandler.cancel_dump_traceback_later()
617
618 # Always ensure that all worker processes are no longer
619 # worker when we exit this function
620 self.pending.stop()
621 self.stop_workers()