SocketHandler.php 7.2 KB

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