diff --git a/docs/internals.md b/docs/internals.md index 12d232166..f62246f76 100644 --- a/docs/internals.md +++ b/docs/internals.md @@ -209,8 +209,11 @@ subsystem). Its traps are behavioral, not structural: that the child does not read while filling its own output can block; pass `null` and feed via `writeStdInput()` instead. - **Windows capture differs by PHP version.** On Windows < PHP 8.5 captured - output is backed by a `tmpfile()` (`stream_select()` did not work on - `proc_open` pipes before the 8.5 PeekNamedPipe fix); elsewhere it is anonymous + output is backed by a temporary file (`stream_select()` did not work on + `proc_open` pipes before the 8.5 PeekNamedPipe fix); the child writes and the + parent reads through separate handles, as an inherited handle shares the file + position, and the file is removed right after the start where the platform + allows (best effort, retried on close); elsewhere it is anonymous pipes drained non-blockingly via `stream_select()` (`readFromPipe`). ## Navigation map diff --git a/src/Utils/Process.php b/src/Utils/Process.php index 6a7831406..0f55477dc 100644 --- a/src/Utils/Process.php +++ b/src/Utils/Process.php @@ -46,6 +46,9 @@ final class Process /** @var array Output IDs whose pipe is backed by a temporary file (Windows < 8.5 workaround). */ private array $fileBackedOutputs = []; + + /** @var array Paths of the temporary files not removed yet. */ + private array $temporaryFiles = []; private float $startTime; private bool $detached = false; @@ -125,19 +128,32 @@ private function __construct( mixed $stderr, private readonly ?float $timeout, ) { - $descriptors = [ - self::StdIn => $this->createInputDescriptor($stdin), - self::StdOut => $this->createOutputDescriptor(self::StdOut, $stdout), - self::StdErr => $this->createOutputDescriptor(self::StdErr, $stderr), - ]; - - $process = @proc_open($command, $descriptors, $pipes, $directory, $env, $options); // @ is escalated to exception - if (!is_resource($process)) { - throw new ProcessFailedException('Failed to start process: ' . Helpers::getLastError()); + try { + $descriptors = [ + self::StdIn => $this->createInputDescriptor($stdin), + self::StdOut => $this->createOutputDescriptor(self::StdOut, $stdout), + self::StdErr => $this->createOutputDescriptor(self::StdErr, $stderr), + ]; + + $process = @proc_open($command, $descriptors, $pipes, $directory, $env, $options); // @ is escalated to exception + if (!is_resource($process)) { + throw new ProcessFailedException('Failed to start process: ' . Helpers::getLastError()); + } + } catch (\Throwable $e) { + unset($descriptors); // closes the writing handles of temporary files, so they can be removed + $this->closeOutputPipes(); + $this->removeTemporaryFiles(); + throw $e; } $this->process = $process; - [$this->inputPipe, $this->outputPipes[self::StdOut], $this->outputPipes[self::StdErr]] = $pipes + $descriptors; + // the parent reads the temporary files through its own handles + $readers = array_intersect_key($this->outputPipes, $this->fileBackedOutputs); + [$this->inputPipe, $this->outputPipes[self::StdOut], $this->outputPipes[self::StdErr]] = $pipes + $readers + $descriptors; + foreach ($this->fileBackedOutputs as $id => $_) { + fclose($descriptors[$id]); // the child has its own copy of the writing handle + } + $this->removeTemporaryFiles(); // best effort, the open handles keep working; close() and the destructor retry if ($stdin instanceof self) { // the source process hands over its STDOUT pipe; from now on this process owns it @@ -160,6 +176,7 @@ public function __destruct() } $this->outputBuffers = []; $this->terminate(); + $this->removeTemporaryFiles(); // again, if a file could not be removed at close() } @@ -435,8 +452,7 @@ private function readFromPipe(int $id, bool $final = false): void return; } elseif (isset($this->fileBackedOutputs[$id])) { - // Windows < 8.5: captured output is a temporary file; read whatever was appended since last time - fseek($pipe, strlen($this->outputBuffers[$id])); + // Windows < 8.5: captured output is a temporary file; the own handle reads on where it stopped $this->outputBuffers[$id] .= stream_get_contents($pipe); } elseif ($final) { @@ -526,8 +542,7 @@ private function createOutputDescriptor(int $id, mixed $output): mixed $this->outputBufferOffsets[$id] = 0; if (Helpers::IsWindows && PHP_VERSION_ID < 80500) { // Windows < 8.5: stream_select() doesn't work on pipes, capture into a temp file that reads non-blockingly - $this->fileBackedOutputs[$id] = true; - return tmpfile(); + return $this->createTemporaryFile($id); } return ['pipe', 'w']; @@ -537,6 +552,55 @@ private function createOutputDescriptor(int $id, mixed $output): mixed } + /** + * Creates the temporary file that captures an output on Windows < 8.5. The child writes through the returned handle, + * the parent reads through another one: with a single shared handle both would share the file position, and every + * read would move the position the child writes at. + * @return resource + */ + private function createTemporaryFile(int $id): mixed + { + // errors are reported by the exceptions below, not by the application's error handler + $error = ''; + $onError = function (string $message) use (&$error): void { + $error = $message; + }; + $writer = false; + for ($i = 0; $i < 10 && !$writer; $i++) { // 'x' fails if the name exists, so concurrent processes never share a file + $path = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'nette-process-' . bin2hex(random_bytes(8)) . '.tmp'; + $writer = Callback::invokeSafe('fopen', [$path, 'xb'], $onError); + } + if (!$writer) { + throw new ProcessFailedException("Unable to create a temporary file for the output: $error"); + } + $this->fileBackedOutputs[$id] = true; + $this->temporaryFiles[$id] = $path; + $reader = Callback::invokeSafe('fopen', [$path, 'rb'], $onError); + if (!$reader) { + fclose($writer); + throw new ProcessFailedException("Unable to open the temporary file '$path': $error"); + } + $this->outputPipes[$id] = $reader; + return $writer; + } + + + /** + * Tries to remove the temporary files of the captured output; called right after the start, the open handles keep + * working. A file that cannot be removed then (e.g. opened by other software without sharing deletion, or denied by + * the directory's permissions) is tried again in close() and by the destructor; if that fails too, it stays in the + * temporary directory. Never throws: a failure is not reported to the application's error handler either. + */ + private function removeTemporaryFiles(): void + { + foreach ($this->temporaryFiles as $id => $path) { + if (Callback::invokeSafe('unlink', [$path], fn() => null) || !is_file($path)) { + unset($this->temporaryFiles[$id]); + } + } + } + + /** * Closes all pipes and the process resource. */ @@ -546,12 +610,12 @@ private function close(): void $this->closeStdInput(); $this->closeOutputPipes(); proc_close($this->process); + $this->removeTemporaryFiles(); } /** * Closes the output pipes that this class opened; resources supplied by the caller are left untouched. - * (The temporary file backing captured output on Windows < 8.5 is removed by fclose() itself.) */ private function closeOutputPipes(): void { diff --git a/tests/Utils/Process.output.temporaryFile.phpt b/tests/Utils/Process.output.temporaryFile.phpt new file mode 100644 index 000000000..dac498bda --- /dev/null +++ b/tests/Utils/Process.output.temporaryFile.phpt @@ -0,0 +1,190 @@ + glob("$tempDir/*") ?: []; +$before = []; + +// 1 MiB per stream in 16 KiB writes with pauses: the caller reads many times while the child writes +$start = fn() => Process::runExecutable( + getPhpCliBinary(), + ['-f', __DIR__ . '/fixtures.process/binary.php', (string) (1 << 20), (string) (1 << 20), '16384', '100'], +); + + +test('final output collection is binary-exact on both streams', function () use ($start, $pattern) { + $process = $start(); + Assert::same(md5($pattern(1 << 20, false)), md5($process->getStdOutput())); + Assert::same(md5($pattern(1 << 20, true)), md5($process->getStdError())); +}); + + +test('incremental output collection is binary-exact on both streams', function () use ($start, $pattern) { + $process = $start(); + $output = $error = ''; + $reads = 0; + while ($process->isRunning()) { + $output .= $process->consumeStdOutput(); + $error .= $process->consumeStdError(); + $reads++; + usleep(1000); + } + $output .= $process->consumeStdOutput(); + $error .= $process->consumeStdError(); + + Assert::true($reads > 10); + Assert::same(strlen($pattern(1 << 20, false)), strlen($output)); + Assert::same(md5($pattern(1 << 20, false)), md5($output)); + Assert::same(md5($pattern(1 << 20, true)), md5($error)); +}); + + +test('wait() with a callback receives exact output', function () use ($start, $pattern) { + $process = $start(); + $output = $error = ''; + $process->wait(function (string $out, string $err) use (&$output, &$error) { + $output .= $out; + $error .= $err; + }); + Assert::same(md5($pattern(1 << 20, false)), md5($output)); + Assert::same(md5($pattern(1 << 20, true)), md5($error)); +}); + + +test('temporary files are removed', function () use ($temporaryFiles, $before) { + $process = Process::runExecutable(getPhpCliBinary(), ['-r', 'echo "x";']); + Assert::same('x', $process->getStdOutput()); + $process->terminate(); + Assert::same([], array_diff($temporaryFiles(), $before)); +}); + + +if (Helpers::IsWindows) { // POSIX starts the child and reports the missing executable by its exit code + test('temporary files are removed when the process cannot be started', function () use ($temporaryFiles, $before) { + Assert::exception( + fn() => Process::runExecutable(__DIR__ . '/nonexistent-' . uniqid()), + Nette\Utils\ProcessFailedException::class, + ); + Assert::same([], array_diff($temporaryFiles(), $before)); + }); +} + + +test('temporary files are removed when a later output cannot be opened', function () use ($temporaryFiles, $before) { + Assert::exception( + fn() => Process::runExecutable(getPhpCliBinary(), ['-r', 'echo 1;'], stderr: __DIR__ . '/nonexistent-dir/x.txt'), + Nette\IOException::class, + ); + Assert::same([], array_diff($temporaryFiles(), $before)); +}); + + +test('a descendant holding the output does not leave the temporary file behind', function () use ($temporaryFiles, $before) { + $process = Process::runExecutable(getPhpCliBinary(), ['-f', __DIR__ . '/fixtures.process/spawn.php', '1']); + Assert::same('parent', $process->getStdOutput()); + usleep(1_500_000); // the descendant has ended + $process = null; + Assert::same([], array_diff($temporaryFiles(), $before)); +}); + + +if (Helpers::IsWindows && PHP_VERSION_ID < 80500) { + test('temporary files are removed from the directory while the process runs', function () use ($temporaryFiles, $before) { + // the removal right after the start is best effort; where it succeeds, the open handles keep working + $process = Process::runExecutable(getPhpCliBinary(), ['-r', 'usleep(300000); echo "late";']); + Assert::same([], array_diff($temporaryFiles(), $before)); + Assert::same('late', $process->getStdOutput()); + }); +} + + +test('output appended after the reader reached the end is read by later calls', function () { + // the reader repeatedly reaches the current end of a growing output, which must not stop later reads + $process = Process::runExecutable(getPhpCliBinary(), ['-r', 'for ($i = 0; $i < 10; $i++) { fwrite(STDOUT, "x$i"); usleep(100_000); }']); + $chunks = []; + while ($process->isRunning()) { + if (($chunk = $process->consumeStdOutput()) !== '') { + $chunks[] = $chunk; + } + usleep(20_000); + } + $chunks[] = $process->consumeStdOutput(); + Assert::same('x0x1x2x3x4x5x6x7x8x9', implode($chunks)); + Assert::true(count(array_filter($chunks)) >= 5, 'output should arrive in several chunks'); +}); + + +test('an error handler that throws does not affect the handling of temporary files', function () use ($temporaryFiles, $before) { + set_error_handler(fn(int $severity, string $message) => throw new ErrorException($message, 0, $severity)); + try { + $process = Process::runExecutable(getPhpCliBinary(), ['-r', 'echo "ok";']); + Assert::same('ok', $process->getStdOutput()); + $process = null; + } finally { + restore_error_handler(); + } + Assert::same([], array_diff($temporaryFiles(), $before)); +}); + + +if (Helpers::IsWindows && PHP_VERSION_ID < 80500) { + $acl = function (string $dir, string $args): void { + exec('icacls ' . escapeshellarg($dir) . " $args 2>&1", $output, $code); + Assert::same(0, $code, implode("\n", $output)); + }; + $user = escapeshellarg((string) getenv('USERNAME')); + + + test('a failure to create a temporary file is reported', function () use ($tempDir, $temporaryFiles, $acl, $user) { + $acl($tempDir, "/deny $user:(WD)"); // no new files in the directory + set_error_handler(fn(int $severity, string $message) => throw new ErrorException($message, 0, $severity)); + try { + Assert::exception( + fn() => Process::runExecutable(getPhpCliBinary(), ['-r', 'echo 1;']), + Nette\Utils\ProcessFailedException::class, + 'Unable to create a temporary file for the output: %a%', + ); + } finally { + restore_error_handler(); + $acl($tempDir, "/remove:d $user"); + } + Assert::same([], $temporaryFiles()); + }); + + + test('a temporary file that cannot be removed stays silently', function () use ($tempDir, $temporaryFiles, $before, $acl, $user) { + $acl($tempDir, "/deny $user:(OI)(DE) /deny $user:(DC)"); // files in the directory cannot be deleted + set_error_handler(fn(int $severity, string $message) => throw new ErrorException($message, 0, $severity)); + try { + $process = Process::runExecutable(getPhpCliBinary(), ['-r', 'echo "kept";']); + Assert::same('kept', $process->getStdOutput()); + $process = null; // removal after the start, in close() and in the destructor all fail + $left = array_diff($temporaryFiles(), $before); + } finally { + restore_error_handler(); + $acl($tempDir, "/remove:d $user"); + } + Assert::count(2, $left); // STDOUT and STDERR + foreach ($left as $file) { + unlink($file); + } + }); +} diff --git a/tests/Utils/fixtures.process/binary.php b/tests/Utils/fixtures.process/binary.php new file mode 100644 index 000000000..9dd97729a --- /dev/null +++ b/tests/Utils/fixtures.process/binary.php @@ -0,0 +1,18 @@ + [chunk size = 65536] [pause in µs after each chunk = 0] + +[, $outBytes, $errBytes, $chunk, $pause] = $argv + [3 => 65536, 4 => 0]; +$block = implode(array_map('chr', range(0, 255))); +$pattern = fn(string $block, int $bytes) => substr(str_repeat($block, intdiv($bytes, 256) + 1), 0, $bytes); +$streams = [1 => STDOUT, 2 => STDERR]; +$left = [1 => $pattern($block, (int) $outBytes), 2 => $pattern(strrev($block), (int) $errBytes)]; + +while ($left = array_filter($left, fn($data) => $data !== '')) { + foreach ($left as $id => $data) { + fwrite($streams[$id], substr($data, 0, (int) $chunk)); + $left[$id] = substr($data, (int) $chunk); + } + usleep((int) $pause); +} diff --git a/tests/Utils/fixtures.process/spawn.php b/tests/Utils/fixtures.process/spawn.php new file mode 100644 index 000000000..546d5f1a5 --- /dev/null +++ b/tests/Utils/fixtures.process/spawn.php @@ -0,0 +1,6 @@ +, writes 'parent' and exits at once. + +$child = proc_open([PHP_BINARY, '-r', 'usleep((int) (' . (float) $argv[1] . ' * 1e6));'], [STDIN, STDOUT, STDERR], $pipes); +echo 'parent';