SocketHandler.php 8.7 KB

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