Debian Codegraph @

vendor/react/child-process/src/Process.php

raw
1 <?php
2
3 namespace React\ChildProcess;
4
5 use Evenement\EventEmitter;
6 use React\EventLoop\Loop;
7 use React\EventLoop\LoopInterface;
8 use React\Stream\ReadableResourceStream;
9 use React\Stream\ReadableStreamInterface;
10 use React\Stream\WritableResourceStream;
11 use React\Stream\WritableStreamInterface;
12 use React\Stream\DuplexResourceStream;
13 use React\Stream\DuplexStreamInterface;
14
15 /**
16 * Process component.
17 *
18 * This class borrows logic from Symfony's Process component for ensuring
19 * compatibility when PHP is compiled with the --enable-sigchild option.
20 *
21 * This class also implements the `EventEmitterInterface`
22 * which allows you to react to certain events:
23 *
24 * exit event:
25 * The `exit` event will be emitted whenever the process is no longer running.
26 * Event listeners will receive the exit code and termination signal as two
27 * arguments:
28 *
29 * ```php
30 * $process = new Process('sleep 10');
31 * $process->start();
32 *
33 * $process->on('exit', function ($code, $term) {
34 * if ($term === null) {
35 * echo 'exit with code ' . $code . PHP_EOL;
36 * } else {
37 * echo 'terminated with signal ' . $term . PHP_EOL;
38 * }
39 * });
40 * ```
41 *
42 * Note that `$code` is `null` if the process has terminated, but the exit
43 * code could not be determined (for example
44 * [sigchild compatibility](#sigchild-compatibility) was disabled).
45 * Similarly, `$term` is `null` unless the process has terminated in response to
46 * an uncaught signal sent to it.
47 * This is not a limitation of this project, but actual how exit codes and signals
48 * are exposed on POSIX systems, for more details see also
49 * [here](https://unix.stackexchange.com/questions/99112/default-exit-code-when-process-is-terminated).
50 *
51 * It's also worth noting that process termination depends on all file descriptors
52 * being closed beforehand.
53 * This means that all [process pipes](#stream-properties) will emit a `close`
54 * event before the `exit` event and that no more `data` events will arrive after
55 * the `exit` event.
56 * Accordingly, if either of these pipes is in a paused state (`pause()` method
57 * or internally due to a `pipe()` call), this detection may not trigger.
58 */
59 class Process extends EventEmitter
60 {
61 /**
62 * @var WritableStreamInterface|null|DuplexStreamInterface|ReadableStreamInterface
63 */
64 public $stdin;
65
66 /**
67 * @var ReadableStreamInterface|null|DuplexStreamInterface|WritableStreamInterface
68 */
69 public $stdout;
70
71 /**
72 * @var ReadableStreamInterface|null|DuplexStreamInterface|WritableStreamInterface
73 */
74 public $stderr;
75
76 /**
77 * Array with all process pipes (once started)
78 *
79 * Unless explicitly configured otherwise during construction, the following
80 * standard I/O pipes will be assigned by default:
81 * - 0: STDIN (`WritableStreamInterface`)
82 * - 1: STDOUT (`ReadableStreamInterface`)
83 * - 2: STDERR (`ReadableStreamInterface`)
84 *
85 * @var array<ReadableStreamInterface|WritableStreamInterface|DuplexStreamInterface>
86 */
87 public $pipes = array();
88
89 private $cmd;
90 private $cwd;
91 private $env;
92 private $fds;
93
94 private $enhanceSigchildCompatibility;
95 private $sigchildPipe;
96
97 private $process;
98 private $status;
99 private $exitCode;
100 private $fallbackExitCode;
101 private $stopSignal;
102 private $termSignal;
103
104 private static $sigchild;
105
106 /**
107 * Constructor.
108 *
109 * @param string $cmd Command line to run
110 * @param null|string $cwd Current working directory or null to inherit
111 * @param null|array $env Environment variables or null to inherit
112 * @param null|array $fds File descriptors to allocate for this process (or null = default STDIO streams)
113 * @throws \LogicException On windows or when proc_open() is not installed
114 */
115 public function __construct($cmd, $cwd = null, $env = null, $fds = null)
116 {
117 if ($env !== null && !\is_array($env)) { // manual type check to support legacy PHP < 7.1
118 throw new \InvalidArgumentException('Argument #3 ($env) expected null|array');
119 }
120 if ($fds !== null && !\is_array($fds)) { // manual type check to support legacy PHP < 7.1
121 throw new \InvalidArgumentException('Argument #4 ($fds) expected null|array');
122 }
123 if (!\function_exists('proc_open')) {
124 throw new \LogicException('The Process class relies on proc_open(), which is not available on your PHP installation.');
125 }
126
127 $this->cmd = $cmd;
128 $this->cwd = $cwd;
129
130 if (null !== $env) {
131 $this->env = array();
132 foreach ($env as $key => $value) {
133 $this->env[(string) $key] = (string) $value;
134 }
135 }
136
137 if ($fds === null) {
138 $fds = array(
139 array('pipe', 'r'), // stdin
140 array('pipe', 'w'), // stdout
141 array('pipe', 'w'), // stderr
142 );
143 }
144
145 if (\DIRECTORY_SEPARATOR === '\\') {
146 foreach ($fds as $fd) {
147 if (isset($fd[0]) && $fd[0] === 'pipe') {
148 throw new \LogicException('Process pipes are not supported on Windows due to their blocking nature on Windows');
149 }
150 }
151 }
152
153 $this->fds = $fds;
154 $this->enhanceSigchildCompatibility = self::isSigchildEnabled();
155 }
156
157 /**
158 * Start the process.
159 *
160 * After the process is started, the standard I/O streams will be constructed
161 * and available via public properties.
162 *
163 * This method takes an optional `LoopInterface|null $loop` parameter that can be used to
164 * pass the event loop instance to use for this process. You can use a `null` value
165 * here in order to use the [default loop](https://github.com/reactphp/event-loop#loop).
166 * This value SHOULD NOT be given unless you're sure you want to explicitly use a
167 * given event loop instance.
168 *
169 * @param ?LoopInterface $loop Loop interface for stream construction
170 * @param float $interval Interval to periodically monitor process state (seconds)
171 * @throws \RuntimeException If the process is already running or fails to start
172 */
173 public function start($loop = null, $interval = 0.1)
174 {
175 if ($loop !== null && !$loop instanceof LoopInterface) { // manual type check to support legacy PHP < 7.1
176 throw new \InvalidArgumentException('Argument #1 ($loop) expected null|React\EventLoop\LoopInterface');
177 }
178 if ($this->isRunning()) {
179 throw new \RuntimeException('Process is already running');
180 }
181
182 $loop = $loop ?: Loop::get();
183 $cmd = $this->cmd;
184 $fdSpec = $this->fds;
185 $sigchild = null;
186
187 // Read exit code through fourth pipe to work around --enable-sigchild
188 if ($this->enhanceSigchildCompatibility) {
189 $fdSpec[] = array('pipe', 'w');
190 \end($fdSpec);
191 $sigchild = \key($fdSpec);
192
193 // make sure this is fourth or higher (do not mess with STDIO)
194 if ($sigchild < 3) {
195 $fdSpec[3] = $fdSpec[$sigchild];
196 unset($fdSpec[$sigchild]);
197 $sigchild = 3;
198 }
199
200 $cmd = \sprintf('(%s) ' . $sigchild . '>/dev/null; code=$?; echo $code >&' . $sigchild . '; exit $code', $cmd);
201 }
202
203 // on Windows, we do not launch the given command line in a shell (cmd.exe) by default and omit any error dialogs
204 // the cmd.exe shell can explicitly be given as part of the command as detailed in both documentation and tests
205 $options = array();
206 if (\DIRECTORY_SEPARATOR === '\\') {
207 $options['bypass_shell'] = true;
208 $options['suppress_errors'] = true;
209 }
210
211 $errstr = '';
212 \set_error_handler(function ($_, $error) use (&$errstr) {
213 // Match errstr from PHP's warning message.
214 // proc_open(/dev/does-not-exist): Failed to open stream: No such file or directory
215 $errstr = $error;
216 });
217
218 $pipes = array();
219 $this->process = @\proc_open($cmd, $fdSpec, $pipes, $this->cwd, $this->env, $options);
220
221 \restore_error_handler();
222
223 if (!\is_resource($this->process)) {
224 throw new \RuntimeException('Unable to launch a new process: ' . $errstr);
225 }
226
227 // count open process pipes and await close event for each to drain buffers before detecting exit
228 $that = $this;
229 $closeCount = 0;
230 $streamCloseHandler = function () use (&$closeCount, $loop, $interval, $that) {
231 $closeCount--;
232
233 if ($closeCount > 0) {
234 return;
235 }
236
237 // process already closed => report immediately
238 if (!$that->isRunning()) {
239 $that->close();
240 $that->emit('exit', array($that->getExitCode(), $that->getTermSignal()));
241 return;
242 }
243
244 // close not detected immediately => check regularly
245 $loop->addPeriodicTimer($interval, function ($timer) use ($that, $loop) {
246 if (!$that->isRunning()) {
247 $loop->cancelTimer($timer);
248 $that->close();
249 $that->emit('exit', array($that->getExitCode(), $that->getTermSignal()));
250 }
251 });
252 };
253
254 if ($sigchild !== null) {
255 $this->sigchildPipe = $pipes[$sigchild];
256 unset($pipes[$sigchild]);
257 }
258
259 foreach ($pipes as $n => $fd) {
260 // use open mode from stream meta data or fall back to pipe open mode for legacy HHVM
261 $meta = \stream_get_meta_data($fd);
262 $mode = $meta['mode'] === '' ? ($this->fds[$n][1] === 'r' ? 'w' : 'r') : $meta['mode'];
263
264 if ($mode === 'r+') {
265 $stream = new DuplexResourceStream($fd, $loop);
266 $stream->on('close', $streamCloseHandler);
267 $closeCount++;
268 } elseif ($mode === 'w') {
269 $stream = new WritableResourceStream($fd, $loop);
270 } else {
271 $stream = new ReadableResourceStream($fd, $loop);
272 $stream->on('close', $streamCloseHandler);
273 $closeCount++;
274 }
275 $this->pipes[$n] = $stream;
276 }
277
278 $this->stdin = isset($this->pipes[0]) ? $this->pipes[0] : null;
279 $this->stdout = isset($this->pipes[1]) ? $this->pipes[1] : null;
280 $this->stderr = isset($this->pipes[2]) ? $this->pipes[2] : null;
281
282 // immediately start checking for process exit when started without any I/O pipes
283 if (!$closeCount) {
284 $streamCloseHandler();
285 }
286 }
287
288 /**
289 * Close the process.
290 *
291 * This method should only be invoked via the periodic timer that monitors
292 * the process state.
293 */
294 public function close()
295 {
296 if ($this->process === null) {
297 return;
298 }
299
300 foreach ($this->pipes as $pipe) {
301 $pipe->close();
302 }
303
304 if ($this->enhanceSigchildCompatibility) {
305 $this->pollExitCodePipe();
306 $this->closeExitCodePipe();
307 }
308
309 $exitCode = \proc_close($this->process);
310 $this->process = null;
311
312 if ($this->exitCode === null && $exitCode !== -1) {
313 $this->exitCode = $exitCode;
314 }
315
316 if ($this->exitCode === null && $this->status['exitcode'] !== -1) {
317 $this->exitCode = $this->status['exitcode'];
318 }
319
320 if ($this->exitCode === null && $this->fallbackExitCode !== null) {
321 $this->exitCode = $this->fallbackExitCode;
322 $this->fallbackExitCode = null;
323 }
324 }
325
326 /**
327 * Terminate the process with an optional signal.
328 *
329 * @param int $signal Optional signal (default: SIGTERM)
330 * @return bool Whether the signal was sent successfully
331 */
332 public function terminate($signal = null)
333 {
334 if ($this->process === null) {
335 return false;
336 }
337
338 if ($signal !== null) {
339 return \proc_terminate($this->process, $signal);
340 }
341
342 return \proc_terminate($this->process);
343 }
344
345 /**
346 * Get the command string used to launch the process.
347 *
348 * @return string
349 */
350 public function getCommand()
351 {
352 return $this->cmd;
353 }
354
355 /**
356 * Get the exit code returned by the process.
357 *
358 * This value is only meaningful if isRunning() has returned false. Null
359 * will be returned if the process is still running.
360 *
361 * Null may also be returned if the process has terminated, but the exit
362 * code could not be determined (e.g. sigchild compatibility was disabled).
363 *
364 * @return int|null
365 */
366 public function getExitCode()
367 {
368 return $this->exitCode;
369 }
370
371 /**
372 * Get the process ID.
373 *
374 * @return int|null
375 */
376 public function getPid()
377 {
378 $status = $this->getCachedStatus();
379
380 return $status !== null ? $status['pid'] : null;
381 }
382
383 /**
384 * Get the signal that caused the process to stop its execution.
385 *
386 * This value is only meaningful if isStopped() has returned true. Null will
387 * be returned if the process was never stopped.
388 *
389 * @return int|null
390 */
391 public function getStopSignal()
392 {
393 return $this->stopSignal;
394 }
395
396 /**
397 * Get the signal that caused the process to terminate its execution.
398 *
399 * This value is only meaningful if isTerminated() has returned true. Null
400 * will be returned if the process was never terminated.
401 *
402 * @return int|null
403 */
404 public function getTermSignal()
405 {
406 return $this->termSignal;
407 }
408
409 /**
410 * Return whether the process is still running.
411 *
412 * @return bool
413 */
414 public function isRunning()
415 {
416 if ($this->process === null) {
417 return false;
418 }
419
420 $status = $this->getFreshStatus();
421
422 return $status !== null ? $status['running'] : false;
423 }
424
425 /**
426 * Return whether the process has been stopped by a signal.
427 *
428 * @return bool
429 */
430 public function isStopped()
431 {
432 $status = $this->getFreshStatus();
433
434 return $status !== null ? $status['stopped'] : false;
435 }
436
437 /**
438 * Return whether the process has been terminated by an uncaught signal.
439 *
440 * @return bool
441 */
442 public function isTerminated()
443 {
444 $status = $this->getFreshStatus();
445
446 return $status !== null ? $status['signaled'] : false;
447 }
448
449 /**
450 * Return whether PHP has been compiled with the '--enable-sigchild' option.
451 *
452 * @see \Symfony\Component\Process\Process::isSigchildEnabled()
453 * @return bool
454 */
455 public final static function isSigchildEnabled()
456 {
457 if (null !== self::$sigchild) {
458 return self::$sigchild;
459 }
460
461 if (!\function_exists('phpinfo')) {
462 return self::$sigchild = false; // @codeCoverageIgnore
463 }
464
465 \ob_start();
466 \phpinfo(INFO_GENERAL);
467
468 return self::$sigchild = false !== \strpos(\ob_get_clean(), '--enable-sigchild');
469 }
470
471 /**
472 * Enable or disable sigchild compatibility mode.
473 *
474 * Sigchild compatibility mode is required to get the exit code and
475 * determine the success of a process when PHP has been compiled with
476 * the --enable-sigchild option.
477 *
478 * @param bool $sigchild
479 * @return void
480 */
481 public final static function setSigchildEnabled($sigchild)
482 {
483 self::$sigchild = (bool) $sigchild;
484 }
485
486 /**
487 * Check the fourth pipe for an exit code.
488 *
489 * This should only be used if --enable-sigchild compatibility was enabled.
490 */
491 private function pollExitCodePipe()
492 {
493 if ($this->sigchildPipe === null) {
494 return;
495 }
496
497 $r = array($this->sigchildPipe);
498 $w = $e = null;
499
500 $n = @\stream_select($r, $w, $e, 0);
501
502 if (1 !== $n) {
503 return;
504 }
505
506 $data = \fread($r[0], 8192);
507
508 if (\strlen($data) > 0) {
509 $this->fallbackExitCode = (int) $data;
510 }
511 }
512
513 /**
514 * Close the fourth pipe used to relay an exit code.
515 *
516 * This should only be used if --enable-sigchild compatibility was enabled.
517 */
518 private function closeExitCodePipe()
519 {
520 if ($this->sigchildPipe === null) {
521 return;
522 }
523
524 \fclose($this->sigchildPipe);
525 $this->sigchildPipe = null;
526 }
527
528 /**
529 * Return the cached process status.
530 *
531 * @return array
532 */
533 private function getCachedStatus()
534 {
535 if ($this->status === null) {
536 $this->updateStatus();
537 }
538
539 return $this->status;
540 }
541
542 /**
543 * Return the updated process status.
544 *
545 * @return array
546 */
547 private function getFreshStatus()
548 {
549 $this->updateStatus();
550
551 return $this->status;
552 }
553
554 /**
555 * Update the process status, stop/term signals, and exit code.
556 *
557 * Stop/term signals are only updated if the process is currently stopped or
558 * signaled, respectively. Otherwise, signal values will remain as-is so the
559 * corresponding getter methods may be used at a later point in time.
560 */
561 private function updateStatus()
562 {
563 if ($this->process === null) {
564 return;
565 }
566
567 $this->status = \proc_get_status($this->process);
568
569 if ($this->status === false) {
570 throw new \UnexpectedValueException('proc_get_status() failed');
571 }
572
573 if ($this->status['stopped']) {
574 $this->stopSignal = $this->status['stopsig'];
575 }
576
577 if ($this->status['signaled']) {
578 $this->termSignal = $this->status['termsig'];
579 }
580
581 if (!$this->status['running'] && -1 !== $this->status['exitcode']) {
582 $this->exitCode = $this->status['exitcode'];
583 }
584 }
585 }