SocketHandler.php 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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 Socket connection string
  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. * @param array $record
  42. *
  43. * @throws \UnexpectedValueException
  44. * @throws \RuntimeException
  45. */
  46. public function write(array $record)
  47. {
  48. $this->connectIfNotConnected();
  49. $this->writeToSocket((string) $record['formatted']);
  50. }
  51. /**
  52. * We will not close a PersistentSocket instance so it can be reused in other requests.
  53. */
  54. public function close()
  55. {
  56. if (!$this->isPersistent()) {
  57. $this->closeSocket();
  58. }
  59. }
  60. /**
  61. * Close socket, if open
  62. */
  63. public function closeSocket()
  64. {
  65. if (is_resource($this->resource)) {
  66. fclose($this->resource);
  67. $this->resource = null;
  68. }
  69. }
  70. /**
  71. * Set socket connection to nbe persistent. It only has effect before the connection is initiated.
  72. *
  73. * @param type $boolean
  74. */
  75. public function setPersistent($boolean)
  76. {
  77. $this->persistent = (boolean) $boolean;
  78. }
  79. /**
  80. * Set connection timeout. Only has effect before we connect.
  81. *
  82. * @param float $seconds
  83. *
  84. * @see http://php.net/manual/en/function.fsockopen.php
  85. */
  86. public function setConnectionTimeout($seconds)
  87. {
  88. $this->validateTimeout($seconds);
  89. $this->connectionTimeout = (float) $seconds;
  90. }
  91. /**
  92. * Set write timeout. Only has effect before we connect.
  93. *
  94. * @param float $seconds
  95. *
  96. * @see http://php.net/manual/en/function.stream-set-timeout.php
  97. */
  98. public function setTimeout($seconds)
  99. {
  100. $this->validateTimeout($seconds);
  101. $this->timeout = (float) $seconds;
  102. }
  103. /**
  104. * Get current connection string
  105. *
  106. * @return string
  107. */
  108. public function getConnectionString()
  109. {
  110. return $this->connectionString;
  111. }
  112. /**
  113. * Get persistent setting
  114. *
  115. * @return boolean
  116. */
  117. public function isPersistent()
  118. {
  119. return $this->persistent;
  120. }
  121. /**
  122. * Get current connection timeout setting
  123. *
  124. * @return float
  125. */
  126. public function getConnectionTimeout()
  127. {
  128. return $this->connectionTimeout;
  129. }
  130. /**
  131. * Get current in-transfer timeout
  132. *
  133. * @return float
  134. */
  135. public function getTimeout()
  136. {
  137. return $this->timeout;
  138. }
  139. /**
  140. * Check to see if the socket is currently available.
  141. *
  142. * UDP might appear to be connected but might fail when writing. See http://php.net/fsockopen for details.
  143. *
  144. * @return boolean
  145. */
  146. public function isConnected()
  147. {
  148. return is_resource($this->resource)
  149. && !feof($this->resource); // on TCP - other party can close connection.
  150. }
  151. /**
  152. * Wrapper to allow mocking
  153. */
  154. protected function pfsockopen()
  155. {
  156. return @pfsockopen($this->connectionString, -1, $this->errno, $this->errstr, $this->connectionTimeout);
  157. }
  158. /**
  159. * Wrapper to allow mocking
  160. */
  161. protected function fsockopen()
  162. {
  163. return @fsockopen($this->connectionString, -1, $this->errno, $this->errstr, $this->connectionTimeout);
  164. }
  165. /**
  166. * Wrapper to allow mocking
  167. *
  168. * @see http://php.net/manual/en/function.stream-set-timeout.php
  169. */
  170. protected function streamSetTimeout()
  171. {
  172. $seconds = floor($this->timeout);
  173. $microseconds = round(($this->timeout - $seconds)*1e6);
  174. return stream_set_timeout($this->resource, $seconds, $microseconds);
  175. }
  176. /**
  177. * Wrapper to allow mocking
  178. */
  179. protected function fwrite($data)
  180. {
  181. return @fwrite($this->resource, $data);
  182. }
  183. /**
  184. * Wrapper to allow mocking
  185. */
  186. protected function streamGetMetadata()
  187. {
  188. return stream_get_meta_data($this->resource);
  189. }
  190. private function validateTimeout($value)
  191. {
  192. $ok = filter_var($value, FILTER_VALIDATE_FLOAT);
  193. if ($ok === false || $value < 0) {
  194. throw new \InvalidArgumentException("Timeout must be 0 or a positive float (got $value)");
  195. }
  196. }
  197. private function connectIfNotConnected()
  198. {
  199. if ($this->isConnected()) {
  200. return;
  201. }
  202. $this->connect();
  203. }
  204. private function connect()
  205. {
  206. $this->createSocketResource();
  207. $this->setSocketTimeout();
  208. }
  209. private function createSocketResource()
  210. {
  211. if ($this->isPersistent()) {
  212. $resource = $this->pfsockopen();
  213. } else {
  214. $resource = $this->fsockopen();
  215. }
  216. if (!$resource) {
  217. throw new \UnexpectedValueException("Failed connecting to $this->connectionString ($this->errno: $this->errstr)");
  218. }
  219. $this->resource = $resource;
  220. }
  221. private function setSocketTimeout()
  222. {
  223. if (!$this->streamSetTimeout()) {
  224. throw new \UnexpectedValueException("Failed setting timeout with stream_set_timeout()");
  225. }
  226. }
  227. private function writeToSocket($data)
  228. {
  229. $length = strlen($data);
  230. $sent = 0;
  231. while ($this->isConnected() && $sent < $length) {
  232. if (0 == $sent) {
  233. $chunk = $this->fwrite($data);
  234. } else {
  235. $chunk = $this->fwrite(substr($data, $sent));
  236. }
  237. if ($chunk === false) {
  238. throw new \RuntimeException("Could not write to socket");
  239. }
  240. $sent += $chunk;
  241. $socketInfo = $this->streamGetMetadata();
  242. if ($socketInfo['timed_out']) {
  243. throw new \RuntimeException("Write timed-out");
  244. }
  245. }
  246. if (!$this->isConnected() && $sent < $length) {
  247. throw new \RuntimeException("End-of-file reached, probably we got disconnected (sent $sent of $length)");
  248. }
  249. }
  250. }