SocketHandler.php 12 KB

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