ProcessHandler.php 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. <?php
  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
  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 int $command Command for the process to start. Absolute paths are recommended,
  53. * especially if you do not use the $cwd parameter.
  54. * @param bool|int $level The minimum logging level at which this handler will be triggered.
  55. * @param bool|true $bubble Whether the messages that are handled can bubble up the stack or not.
  56. * @param string|null $cwd "Current working directory" (CWD) for the process to be executed in.
  57. * @throws \InvalidArgumentException
  58. */
  59. public function __construct($command, $level = Logger::DEBUG, $bubble = true, $cwd = null)
  60. {
  61. $this->guardAgainstInvalidCommand($command);
  62. $this->guardAgainstInvalidCwd($cwd);
  63. parent::__construct($level, $bubble);
  64. $this->command = $command;
  65. $this->cwd = $cwd;
  66. }
  67. /**
  68. * @param string $command
  69. * @throws \InvalidArgumentException
  70. * @return void
  71. */
  72. private function guardAgainstInvalidCommand($command)
  73. {
  74. if (empty($command) || is_string($command) === false) {
  75. throw new \InvalidArgumentException('The command argument must be a non-empty string.');
  76. }
  77. }
  78. /**
  79. * @param string $cwd
  80. * @throws \InvalidArgumentException
  81. * @return void
  82. */
  83. private function guardAgainstInvalidCwd($cwd)
  84. {
  85. if ($cwd !== null && (empty($cwd) || is_string($cwd) === false)) {
  86. throw new \InvalidArgumentException('The optional CWD argument must be a non-empty string, if any.');
  87. }
  88. }
  89. /**
  90. * Writes the record down to the log of the implementing handler
  91. *
  92. * @param array $record
  93. * @throws \UnexpectedValueException
  94. * @return void
  95. */
  96. protected function write(array $record)
  97. {
  98. $this->ensureProcessIsStarted();
  99. $this->writeProcessInput($record['formatted']);
  100. $errors = $this->readProcessErrors();
  101. if (empty($errors) === false) {
  102. throw new \UnexpectedValueException('Errors while writing to process: ' . var_export($errors, true));
  103. }
  104. }
  105. /**
  106. * Makes sure that the process is actually started, and if not, starts it,
  107. * assigns the stream pipes, and handles startup errors, if any.
  108. *
  109. * @return void
  110. */
  111. private function ensureProcessIsStarted()
  112. {
  113. if (is_resource($this->process) === false) {
  114. $this->startProcess();
  115. $this->handleStartupErrors();
  116. }
  117. }
  118. /**
  119. * Starts the actual process and sets all streams to non-blocking.
  120. *
  121. * @return void
  122. */
  123. private function startProcess()
  124. {
  125. $this->process = proc_open($this->command, self::DESCRIPTOR_SPEC, $this->pipes, $this->cwd);
  126. foreach ($this->pipes as $pipe) {
  127. stream_set_blocking($pipe, false);
  128. }
  129. }
  130. /**
  131. * Selects the STDERR stream, handles upcoming startup errors, and throws an exception, if any.
  132. *
  133. * @throws \UnexpectedValueException
  134. * @return void
  135. */
  136. private function handleStartupErrors()
  137. {
  138. $selected = $this->selectErrorStream();
  139. if (false === $selected) {
  140. throw new \UnexpectedValueException('Something went wrong while selecting a stream.');
  141. }
  142. $errors = $this->readProcessErrors();
  143. if (is_resource($this->process) === false || empty($errors) === false) {
  144. throw new \UnexpectedValueException(
  145. sprintf('The process "%s" could not be opened: ' . $errors, $this->command)
  146. );
  147. }
  148. }
  149. /**
  150. * Selects the STDERR stream.
  151. *
  152. * @return int|bool
  153. */
  154. protected function selectErrorStream()
  155. {
  156. $empty = [];
  157. $errorPipes = [$this->pipes[2]];
  158. return stream_select($errorPipes, $empty, $empty, 1);
  159. }
  160. /**
  161. * Reads the errors of the process, if there are any.
  162. *
  163. * @codeCoverageIgnore
  164. * @return string Empty string if there are no errors.
  165. */
  166. protected function readProcessErrors()
  167. {
  168. return stream_get_contents($this->pipes[2]);
  169. }
  170. /**
  171. * Writes to the input stream of the opened process.
  172. *
  173. * @codeCoverageIgnore
  174. * @param $string
  175. * @return void
  176. */
  177. protected function writeProcessInput($string)
  178. {
  179. fwrite($this->pipes[0], (string)$string);
  180. }
  181. /**
  182. * {@inheritdoc}
  183. */
  184. public function close()
  185. {
  186. if (is_resource($this->process)) {
  187. foreach ($this->pipes as $pipe) {
  188. fclose($pipe);
  189. }
  190. proc_close($this->process);
  191. }
  192. $this->process = null;
  193. }
  194. }