| 364 | |
| 365 | |
| 366 | def _run(evidence, label, argv, environment, timeout, cwd, watch_raw=False): |
| 367 | selector = selectors.DefaultSelector() |
| 368 | streams = {"stdout": bytearray(), "stderr": bytearray()} |
| 369 | started = time.monotonic() |
| 370 | proc = None |
| 371 | failure = None |
| 372 | quiescent, cleanup = False, [] |
| 373 | try: |
| 374 | proc = subprocess.Popen(argv, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, |
| 375 | stderr=subprocess.PIPE, env=environment, cwd=cwd, |
| 376 | start_new_session=True, bufsize=0) |
| 377 | for name, pipe in (("stdout", proc.stdout), ("stderr", proc.stderr)): |
| 378 | os.set_blocking(pipe.fileno(), False) |
| 379 | selector.register(pipe, selectors.EVENT_READ, name) |
| 380 | while True: |
| 381 | if watch_raw: |
| 382 | evidence.inventory() |
| 383 | left = timeout - (time.monotonic() - started) |
| 384 | if left <= 0: |
| 385 | failure = "timeout" |
| 386 | break |
| 387 | for key, _ in selector.select(min(left, 0.05)): |
| 388 | part = os.read(key.fd, 65536) |
| 389 | if not part: |
| 390 | selector.unregister(key.fileobj) |
| 391 | continue |
| 392 | used = sum(len(data) for data in streams.values()) |
| 393 | allowed = min(evidence.args.max_output_bytes - used, |
| 394 | evidence.args.max_total_output_bytes - evidence.captured_bytes - used) |
| 395 | streams[key.data].extend(part[:max(0, allowed)]) |
| 396 | if len(part) > allowed: |
| 397 | failure = "resource_limit" |
| 398 | break |
| 399 | if failure: |
| 400 | break |
| 401 | if proc.poll() is not None: |
| 402 | if _group_exists(proc.pid): |
| 403 | failure = "quiescence" |
| 404 | break |
| 405 | if not selector.get_map(): |
| 406 | break |
| 407 | except CollectionError as error: |
| 408 | failure = error.kind |
| 409 | except (OSError, ValueError): |
| 410 | failure = "process" |
| 411 | finally: |
| 412 | if proc is not None: |
| 413 | quiescent, cleanup = _quiesce(proc) |
| 414 | if not quiescent: |
| 415 | failure = "quiescence" |
| 416 | if cleanup and failure is None: |
| 417 | failure = "quiescence" |
| 418 | proc.stdout.close() |
| 419 | proc.stderr.close() |
| 420 | selector.close() |
| 421 | record = {"label": label, "argv": argv, "returncode": proc.returncode if proc else None, |
| 422 | "failure": failure, "quiescent": quiescent, "cleanup": cleanup, |
| 423 | "wall_s": round(time.monotonic() - started, 6), "timeout_s": timeout} |