SocketHandler.php 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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 = 0;
  25. private $lastSentBytes = null;
  26. private $persistent = false;
  27. private $errno;
  28. private $errstr;
  29. /**
  30. * @param string $connectionString Socket connection string
  31. * @param integer $level The minimum logging level at which this handler will be triggered
  32. * @param Boolean $bubble Whether the messages that are handled can bubble up the stack or not
  33. */
  34. public function __construct($connectionString, $level = Logger::DEBUG, $bubble = true)
  35. {
  36. parent::__construct($level, $bubble);
  37. $this->connectionString = $connectionString;
  38. $this->connectionTimeout = (float) ini_get('default_socket_timeout');
  39. }
  40. /**
  41. * Connect (if necessary) and write to the socket
  42. *
  43. * @param array $record
  44. *
  45. * @throws \UnexpectedValueException
  46. * @throws \RuntimeException
  47. */
  48. protected function write(array $record)
  49. {
  50. $this->connectIfNotConnected();
  51. $data = $this->generateDataStream($record);
  52. $this->writeToSocket($data);
  53. }
  54. /**
  55. * We will not close a PersistentSocket instance so it can be reused in other requests.
  56. */
  57. public function close()
  58. {
  59. if (!$this->isPersistent()) {
  60. $this->closeSocket();
  61. }
  62. }
  63. /**
  64. * Close socket, if open
  65. */
  66. public function closeSocket()
  67. {
  68. if (is_resource($this->resource)) {
  69. fclose($this->resource);
  70. $this->resource = null;
  71. }
  72. }
  73. /**
  74. * Set socket connection to nbe persistent. It only has effect before the connection is initiated.
  75. *
  76. * @param boolean $persistent
  77. */
  78. public function setPersistent($persistent)
  79. {
  80. $this->persistent = (boolean) $persistent;
  81. }
  82. /**
  83. * Set connection timeout. Only has effect before we connect.
  84. *
  85. * @param float $seconds
  86. *
  87. * @see http://php.net/manual/en/function.fsockopen.php
  88. */
  89. public function setConnectionTimeout($seconds)
  90. {
  91. $this->validateTimeout($seconds);
  92. $this->connectionTimeout = (float) $seconds;
  93. }
  94. /**
  95. * Set write timeout. Only has effect before we connect.
  96. *
  97. * @param float $seconds
  98. *
  99. * @see http://php.net/manual/en/function.stream-set-timeout.php
  100. */
  101. public function setTimeout($seconds)
  102. {
  103. $this->validateTimeout($seconds);
  104. $this->timeout = (float) $seconds;
  105. }
  106. /**
  107. * Set writing timeout. Only has effect during connection in the writing cycle.
  108. *
  109. * @param float $seconds 0 for no timeout
  110. *
  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 boolean
  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 boolean
  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. private function connect()
  232. {
  233. $this->createSocketResource();
  234. $this->setSocketTimeout();
  235. }
  236. private function createSocketResource()
  237. {
  238. if ($this->isPersistent()) {
  239. $resource = $this->pfsockopen();
  240. } else {
  241. $resource = $this->fsockopen();
  242. }
  243. if (!$resource) {
  244. throw new \UnexpectedValueException("Failed connecting to $this->connectionString ($this->errno: $this->errstr)");
  245. }
  246. $this->resource = $resource;
  247. }
  248. private function setSocketTimeout()
  249. {
  250. if (!$this->streamSetTimeout()) {
  251. throw new \UnexpectedValueException("Failed setting timeout with stream_set_timeout()");
  252. }
  253. }
  254. private function writeToSocket($data)
  255. {
  256. $length = strlen($data);
  257. $sent = 0;
  258. $this->lastSentBytes = $sent;
  259. while ($this->isConnected() && $sent < $length) {
  260. if (0 == $sent) {
  261. $chunk = $this->fwrite($data);
  262. } else {
  263. $chunk = $this->fwrite(substr($data, $sent));
  264. }
  265. if ($chunk === false) {
  266. throw new \RuntimeException("Could not write to socket");
  267. }
  268. $sent += $chunk;
  269. $socketInfo = $this->streamGetMetadata();
  270. if ($socketInfo['timed_out']) {
  271. throw new \RuntimeException("Write timed-out");
  272. }
  273. if ($this->writingIsTimedOut($sent)) {
  274. throw new \RuntimeException("Write timed-out, no data sent for `{$this->writingTimeout}` seconds, probably we got disconnected (sent $sent of $length)");
  275. }
  276. }
  277. if (!$this->isConnected() && $sent < $length) {
  278. throw new \RuntimeException("End-of-file reached, probably we got disconnected (sent $sent of $length)");
  279. }
  280. }
  281. private function writingIsTimedOut($sent)
  282. {
  283. $writingTimeout = (int) floor($this->writingTimeout);
  284. if (0 === $writingTimeout) {
  285. return false;
  286. }
  287. if ($sent !== $this->lastSentBytes) {
  288. $this->lastWritingAt = time();
  289. $this->lastSentBytes = $sent;
  290. } else {
  291. usleep(100);
  292. }
  293. if ((time() - $this->lastWritingAt) >= $writingTimeout) {
  294. $this->closeSocket();
  295. return true;
  296. }
  297. return false;
  298. }
  299. }