ProcessHandler.php 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. <?php declare(strict_types=1);
  2. /*
  3. * This file is part of the Monolog package.
  4. *
  5. * (c) Jordi Boggiano <j.boggiano@seld.be>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Monolog\Handler;
  11. use Monolog\Level;
  12. use Monolog\LogRecord;
  13. /**
  14. * Stores to STDIN of any process, specified by a command.
  15. *
  16. * Usage example:
  17. * <pre>
  18. * $log = new Logger('myLogger');
  19. * $log->pushHandler(new ProcessHandler('/usr/bin/php /var/www/monolog/someScript.php'));
  20. * </pre>
  21. *
  22. * @author Kolja Zuelsdorf <koljaz@web.de>
  23. */
  24. class ProcessHandler extends AbstractProcessingHandler
  25. {
  26. /**
  27. * Holds the process to receive data on its STDIN.
  28. *
  29. * @var resource|bool|null
  30. */
  31. private $process;
  32. private string $command;
  33. private ?string $cwd;
  34. /**
  35. * @var resource[]
  36. */
  37. private array $pipes = [];
  38. private float $timeout;
  39. /**
  40. * @var array<int, list<string>>
  41. */
  42. protected const DESCRIPTOR_SPEC = [
  43. 0 => ['pipe', 'r'], // STDIN is a pipe that the child will read from
  44. 1 => ['pipe', 'w'], // STDOUT is a pipe that the child will write to
  45. 2 => ['pipe', 'w'], // STDERR is a pipe to catch the any errors
  46. ];
  47. /**
  48. * @param string $command Command for the process to start. Absolute paths are recommended,
  49. * especially if you do not use the $cwd parameter.
  50. * @param string|null $cwd "Current working directory" (CWD) for the process to be executed in.
  51. * @param float $timeout The maximum timeout (in seconds) for the stream_select() function.
  52. * @throws \InvalidArgumentException
  53. */
  54. public function __construct(string $command, int|string|Level $level = Level::Debug, bool $bubble = true, ?string $cwd = null, float $timeout = 1.0)
  55. {
  56. if ($command === '') {
  57. throw new \InvalidArgumentException('The command argument must be a non-empty string.');
  58. }
  59. if ($cwd === '') {
  60. throw new \InvalidArgumentException('The optional CWD argument must be a non-empty string or null.');
  61. }
  62. parent::__construct($level, $bubble);
  63. $this->command = $command;
  64. $this->cwd = $cwd;
  65. $this->timeout = $timeout;
  66. }
  67. /**
  68. * Writes the record down to the log of the implementing handler
  69. *
  70. * @throws \UnexpectedValueException
  71. */
  72. protected function write(LogRecord $record): void
  73. {
  74. $this->ensureProcessIsStarted();
  75. $this->writeProcessInput($record->formatted);
  76. $errors = $this->readProcessErrors();
  77. if ($errors !== '') {
  78. throw new \UnexpectedValueException(sprintf('Errors while writing to process: %s', $errors));
  79. }
  80. }
  81. /**
  82. * Makes sure that the process is actually started, and if not, starts it,
  83. * assigns the stream pipes, and handles startup errors, if any.
  84. */
  85. private function ensureProcessIsStarted(): void
  86. {
  87. if (\is_resource($this->process) === false) {
  88. $this->startProcess();
  89. $this->handleStartupErrors();
  90. }
  91. }
  92. /**
  93. * Starts the actual process and sets all streams to non-blocking.
  94. */
  95. private function startProcess(): void
  96. {
  97. $this->process = proc_open($this->command, static::DESCRIPTOR_SPEC, $this->pipes, $this->cwd);
  98. foreach ($this->pipes as $pipe) {
  99. stream_set_blocking($pipe, false);
  100. }
  101. }
  102. /**
  103. * Selects the STDERR stream, handles upcoming startup errors, and throws an exception, if any.
  104. *
  105. * @throws \UnexpectedValueException
  106. */
  107. private function handleStartupErrors(): void
  108. {
  109. $selected = $this->selectErrorStream();
  110. if (false === $selected) {
  111. throw new \UnexpectedValueException('Something went wrong while selecting a stream.');
  112. }
  113. $errors = $this->readProcessErrors();
  114. if (\is_resource($this->process) === false || $errors !== '') {
  115. throw new \UnexpectedValueException(
  116. sprintf('The process "%s" could not be opened: ' . $errors, $this->command)
  117. );
  118. }
  119. }
  120. /**
  121. * Selects the STDERR stream.
  122. *
  123. * @return int|bool
  124. */
  125. protected function selectErrorStream()
  126. {
  127. $empty = [];
  128. $errorPipes = [$this->pipes[2]];
  129. $seconds = (int) $this->timeout;
  130. return stream_select($errorPipes, $empty, $empty, $seconds, (int) (($this->timeout - $seconds) * 1000000));
  131. }
  132. /**
  133. * Reads the errors of the process, if there are any.
  134. *
  135. * @codeCoverageIgnore
  136. * @return string Empty string if there are no errors.
  137. */
  138. protected function readProcessErrors(): string
  139. {
  140. return (string) stream_get_contents($this->pipes[2]);
  141. }
  142. /**
  143. * Writes to the input stream of the opened process.
  144. *
  145. * @codeCoverageIgnore
  146. */
  147. protected function writeProcessInput(string $string): void
  148. {
  149. fwrite($this->pipes[0], $string);
  150. }
  151. /**
  152. * @inheritDoc
  153. */
  154. public function close(): void
  155. {
  156. if (\is_resource($this->process)) {
  157. foreach ($this->pipes as $pipe) {
  158. fclose($pipe);
  159. }
  160. proc_close($this->process);
  161. $this->process = null;
  162. }
  163. }
  164. }