blob: 488b800cf0608ef7951a35a1c5f7a48ac450c43a [file]
// Copyright 2026 The Fuchsia Authors
//
// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0
// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT
// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
// This file may not be copied, modified, or distributed except according to
// those terms.
//! The `reproduce.py` wrapper written into every command log slot.
pub(super) fn reproduce_script(parents_depth: usize) -> String {
REPRODUCE_TEMPLATE.replace("__PARENTS_DEPTH__", &parents_depth.to_string())
}
const REPRODUCE_TEMPLATE: &str = r#"#!/usr/bin/env python3
# Copyright 2026 The Fuchsia Authors
#
# Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0
# <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT
# license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
# This file may not be copied, modified, or distributed except according to
# those terms.
import json
import os
import pathlib
import signal
import subprocess
import sys
here = pathlib.Path(__file__).resolve().parent
request = json.loads((here / 'invocation.json').read_text())
# Command bundles live at a fixed depth below the run root. A case may itself
# have a fixture named run.json, so metadata filenames cannot identify the root.
root = here.parents[__PARENTS_DEPTH__]
run_text = (root / 'run.json').read_text()
run = json.loads(run_text)
old = pathlib.Path(request['original_run_root'])
def relocate(value):
# Owned paths occupy a whole value. pathlib supplies the host's component
# and case rules; a bare string prefix would also match sibling names.
# Embedded path text and sibling names remain literal values.
path = pathlib.Path(value)
try:
relative = path.relative_to(old)
except ValueError:
return value
if '..' in relative.parts:
return value
# Keep the original suffix: source/ can select directory contents while
# source selects the directory itself. Rebuilding a Path drops that final
# separator and can change the recorded operation.
prefix = str(old)
if value.startswith(prefix):
return str(root) + value[len(prefix):]
# Native alternative spellings still use pathlib's ownership check.
separators = os.sep + (os.altsep or '')
trailing = value[len(value.rstrip(separators)):]
return str(root / relative) + trailing
print(run_text, file=sys.stderr)
timeout = run['process_timeout_seconds']
cmd = [relocate(request['executable'])] + list(map(relocate, request['arguments']))
cwd = relocate(request['working_directory'])
env = {k: relocate(v) for k, v in request['environment'].items()}
popen_kwargs = {'cwd': cwd, 'env': env, 'stdin': subprocess.DEVNULL}
if os.name == 'posix':
if sys.version_info >= (3, 11):
popen_kwargs['process_group'] = 0
else:
popen_kwargs['start_new_session'] = True
proc = subprocess.Popen(cmd, **popen_kwargs)
def forward_signal(signum, _frame):
if os.name == 'posix':
try:
os.killpg(proc.pid, signum)
except ProcessLookupError:
pass
else:
proc.terminate()
if os.name == 'posix':
for sig in (signal.SIGINT, signal.SIGTERM):
signal.signal(sig, forward_signal)
try:
returncode = proc.wait(timeout=timeout)
except subprocess.TimeoutExpired:
if os.name == 'posix':
try:
os.killpg(proc.pid, signal.SIGKILL)
except ProcessLookupError:
pass
else:
proc.kill()
proc.wait()
# The exception may report a remaining wait interval, not this deadline.
print(f'process timed out after {timeout} seconds', file=sys.stderr)
sys.exit(124)
if os.name == 'posix' and returncode < 0:
signum = -returncode
print(f'process terminated by signal {signum}', file=sys.stderr, flush=True)
# Python ignores SIGPIPE and can inherit other handlers or a signal mask.
# Restore the default action so replay retains signal termination instead
# of converting a negative return code into a normal exit modulo 256.
if signum not in (signal.SIGKILL, signal.SIGSTOP):
signal.signal(signum, signal.SIG_DFL)
if hasattr(signal, 'pthread_sigmask'):
signal.pthread_sigmask(signal.SIG_UNBLOCK, {signum})
os.kill(os.getpid(), signum)
sys.exit(f'could not reproduce termination by signal {signum}')
sys.exit(returncode)
"#;