ProcessHandler.php 5.4 KB

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