ProcessHandler.php 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  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. /**
  39. * @var array<int, string[]>
  40. */
  41. protected const DESCRIPTOR_SPEC = [
  42. 0 => ['pipe', 'r'], // STDIN is a pipe that the child will read from
  43. 1 => ['pipe', 'w'], // STDOUT is a pipe that the child will write to
  44. 2 => ['pipe', 'w'], // STDERR is a pipe to catch the any errors
  45. ];
  46. /**
  47. * @param string $command Command for the process to start. Absolute paths are recommended,
  48. * especially if you do not use the $cwd parameter.
  49. * @param string|null $cwd "Current working directory" (CWD) for the process to be executed in.
  50. * @throws \InvalidArgumentException
  51. */
  52. public function __construct(string $command, int|string|Level $level = Level::Debug, bool $bubble = true, ?string $cwd = null)
  53. {
  54. if ($command === '') {
  55. throw new \InvalidArgumentException('The command argument must be a non-empty string.');
  56. }
  57. if ($cwd === '') {
  58. throw new \InvalidArgumentException('The optional CWD argument must be a non-empty string or null.');
  59. }
  60. parent::__construct($level, $bubble);
  61. $this->command = $command;
  62. $this->cwd = $cwd;
  63. }
  64. /**
  65. * Writes the record down to the log of the implementing handler
  66. *
  67. * @throws \UnexpectedValueException
  68. */
  69. protected function write(LogRecord $record): void
  70. {
  71. $this->ensureProcessIsStarted();
  72. $this->writeProcessInput($record->formatted);
  73. $errors = $this->readProcessErrors();
  74. if ($errors !== '') {
  75. throw new \UnexpectedValueException(sprintf('Errors while writing to process: %s', $errors));
  76. }
  77. }
  78. /**
  79. * Makes sure that the process is actually started, and if not, starts it,
  80. * assigns the stream pipes, and handles startup errors, if any.
  81. */
  82. private function ensureProcessIsStarted(): void
  83. {
  84. if (is_resource($this->process) === false) {
  85. $this->startProcess();
  86. $this->handleStartupErrors();
  87. }
  88. }
  89. /**
  90. * Starts the actual process and sets all streams to non-blocking.
  91. */
  92. private function startProcess(): void
  93. {
  94. $this->process = proc_open($this->command, static::DESCRIPTOR_SPEC, $this->pipes, $this->cwd);
  95. foreach ($this->pipes as $pipe) {
  96. stream_set_blocking($pipe, false);
  97. }
  98. }
  99. /**
  100. * Selects the STDERR stream, handles upcoming startup errors, and throws an exception, if any.
  101. *
  102. * @throws \UnexpectedValueException
  103. */
  104. private function handleStartupErrors(): void
  105. {
  106. $selected = $this->selectErrorStream();
  107. if (false === $selected) {
  108. throw new \UnexpectedValueException('Something went wrong while selecting a stream.');
  109. }
  110. $errors = $this->readProcessErrors();
  111. if (is_resource($this->process) === false || $errors !== '') {
  112. throw new \UnexpectedValueException(
  113. sprintf('The process "%s" could not be opened: ' . $errors, $this->command)
  114. );
  115. }
  116. }
  117. /**
  118. * Selects the STDERR stream.
  119. *
  120. * @return int|bool
  121. */
  122. protected function selectErrorStream()
  123. {
  124. $empty = [];
  125. $errorPipes = [$this->pipes[2]];
  126. return stream_select($errorPipes, $empty, $empty, 1);
  127. }
  128. /**
  129. * Reads the errors of the process, if there are any.
  130. *
  131. * @codeCoverageIgnore
  132. * @return string Empty string if there are no errors.
  133. */
  134. protected function readProcessErrors(): string
  135. {
  136. return (string) stream_get_contents($this->pipes[2]);
  137. }
  138. /**
  139. * Writes to the input stream of the opened process.
  140. *
  141. * @codeCoverageIgnore
  142. */
  143. protected function writeProcessInput(string $string): void
  144. {
  145. fwrite($this->pipes[0], $string);
  146. }
  147. /**
  148. * @inheritDoc
  149. */
  150. public function close(): void
  151. {
  152. if (is_resource($this->process)) {
  153. foreach ($this->pipes as $pipe) {
  154. fclose($pipe);
  155. }
  156. proc_close($this->process);
  157. $this->process = null;
  158. }
  159. }
  160. }