ProcessHandler.php 5.1 KB

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