SocketHandler.php 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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 any socket - uses fsockopen() or pfsockopen().
  14. *
  15. * @author Pablo de Leon Belloc <pablolb@gmail.com>
  16. * @see http://php.net/manual/en/function.fsockopen.php
  17. */
  18. class SocketHandler extends AbstractProcessingHandler
  19. {
  20. private $connectionString;
  21. private $connectionTimeout;
  22. private $resource;
  23. private $timeout = 0;
  24. private $persistent = false;
  25. private $errno;
  26. private $errstr;
  27. /**
  28. * @param string $connectionString
  29. * @param integer $level The minimum logging level at which this handler will be triggered
  30. * @param Boolean $bubble Whether the messages that are handled can bubble up the stack or not
  31. */
  32. public function __construct($connectionString, $level = Logger::DEBUG, $bubble = true)
  33. {
  34. parent::__construct($level, $bubble);
  35. $this->connectionString = $connectionString;
  36. $this->connectionTimeout = (float) ini_get('default_socket_timeout');
  37. }
  38. /**
  39. * Connect (if necessary) and write to the socket
  40. *
  41. * @throws \UnexpectedValueException
  42. * @throws \RuntimeException
  43. * @param string $string
  44. */
  45. public function write(array $record)
  46. {
  47. $this->connectIfNotConnected();
  48. $this->writeToSocket((string) $record['formatted']);
  49. }
  50. /**
  51. * We will not close a PersistentSocket instance so it can be reused in other requests.
  52. */
  53. public function close()
  54. {
  55. if ($this->isPersistent()) {
  56. return;
  57. }
  58. $this->closeSocket();
  59. }
  60. public function closeSocket()
  61. {
  62. if (is_resource($this->resource)) {
  63. fclose($this->resource);
  64. $this->resource = null;
  65. }
  66. }
  67. public function setPersistent($boolean)
  68. {
  69. $this->persistent = (boolean) $boolean;
  70. }
  71. /**
  72. * Set connection timeout. Only has effect before we connect.
  73. *
  74. * @see http://php.net/manual/en/function.fsockopen.php
  75. * @param integer $seconds
  76. */
  77. public function setConnectionTimeout($seconds)
  78. {
  79. $this->validateTimeout($seconds);
  80. $this->connectionTimeout = (float) $seconds;
  81. }
  82. /**
  83. * Set write timeout. Only has effect before we connect.
  84. *
  85. * @see http://php.net/manual/en/function.stream-set-timeout.php
  86. * @param type $seconds
  87. */
  88. public function setTimeout($seconds)
  89. {
  90. $this->validateTimeout($seconds);
  91. $this->timeout = (int) $seconds;
  92. }
  93. private function validateTimeout($value)
  94. {
  95. $ok = filter_var($value, FILTER_VALIDATE_INT, array('options' => array(
  96. 'min_range' => 0,
  97. )));
  98. if ($ok === false) {
  99. throw new \InvalidArgumentException("Timeout must be 0 or a positive integer (got $value)");
  100. }
  101. }
  102. public function getConnectionString()
  103. {
  104. return $this->connectionString;
  105. }
  106. public function isPersistent()
  107. {
  108. return $this->persistent;
  109. }
  110. public function getConnectionTimeout()
  111. {
  112. return $this->connectionTimeout;
  113. }
  114. public function getTimeout()
  115. {
  116. return $this->timeout;
  117. }
  118. private function connectIfNotConnected()
  119. {
  120. if ($this->isConnected()) {
  121. return;
  122. }
  123. $this->connect();
  124. }
  125. /**
  126. * Check to see if the socket is currently available.
  127. *
  128. * UDP might appear to be connected but might fail when writing. See http://php.net/fsockopen for details.
  129. *
  130. * @return boolean
  131. */
  132. public function isConnected()
  133. {
  134. return is_resource($this->resource)
  135. && !feof($this->resource); // on TCP - other party can close connection.
  136. }
  137. private function connect()
  138. {
  139. $this->createSocketResource();
  140. $this->setSocketTimeout();
  141. }
  142. private function createSocketResource()
  143. {
  144. if ($this->isPersistent()) {
  145. $resource = $this->pfsockopen();
  146. } else {
  147. $resource = $this->fsockopen();
  148. }
  149. if (!$resource) {
  150. throw new \UnexpectedValueException("Failed connecting to $this->connectionString ($this->errno: $this->errstr)");
  151. }
  152. return $this->resource = $resource;
  153. }
  154. private function setSocketTimeout()
  155. {
  156. if (!$this->stream_set_timeout()) {
  157. throw new \UnexpectedValueException("Failed setting timeout with stream_set_timeout()");
  158. }
  159. }
  160. private function writeToSocket($data)
  161. {
  162. $length = strlen($data);
  163. $sent = 0;
  164. while ($this->isConnected() && $sent < $length) {
  165. $chunk = $this->fwrite(substr($data, $sent));
  166. if ($chunk === false) {
  167. throw new \RuntimeException("Could not write to socket");
  168. }
  169. $sent += $chunk;
  170. $socketInfo = $this->stream_get_meta_data();
  171. if ($socketInfo['timed_out']) {
  172. throw new \RuntimeException("Write timed-out");
  173. }
  174. }
  175. if (!$this->isConnected() && $sent < $length) {
  176. throw new \RuntimeException("End-of-file reached, probably we got disconnected (sent $sent of $length)");
  177. }
  178. }
  179. /**
  180. * Allow mock
  181. */
  182. protected function pfsockopen()
  183. {
  184. return @pfsockopen($this->connectionString, -1, $this->errno, $this->errstr, $this->connectionTimeout);
  185. }
  186. /**
  187. * Allow mock
  188. */
  189. protected function fsockopen()
  190. {
  191. return @fsockopen($this->connectionString, -1, $this->errno, $this->errstr, $this->connectionTimeout);
  192. }
  193. /**
  194. * Allow mock
  195. */
  196. protected function stream_set_timeout()
  197. {
  198. return stream_set_timeout($this->resource, $this->timeout);
  199. }
  200. /**
  201. * Allow mock
  202. */
  203. protected function fwrite($data)
  204. {
  205. return @fwrite($this->resource, $data);
  206. }
  207. /**
  208. * Allow mock
  209. */
  210. protected function stream_get_meta_data()
  211. {
  212. return stream_get_meta_data($this->resource);
  213. }
  214. }