SocketHandler.php 9.6 KB

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