|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | + * This file is part of the Ubirak package. |
| 5 | + * |
| 6 | + * (c) Ubirak team <[email protected]> |
| 7 | + * |
| 8 | + * For the full copyright and license information, please view the LICENSE |
| 9 | + * file that was distributed with this source code. |
| 10 | + */ |
| 11 | + |
| 12 | +declare(strict_types=1); |
| 13 | + |
| 14 | +namespace Ubirak\Component\Healthcheck; |
| 15 | + |
| 16 | +use Tolerance\Operation\Callback; |
| 17 | +use Tolerance\Operation\Runner\RetryOperationRunner; |
| 18 | +use Tolerance\Operation\Runner\CallbackOperationRunner; |
| 19 | +use Tolerance\Waiter\SleepWaiter; |
| 20 | +use Tolerance\Waiter\TimeOut; |
| 21 | +use Tolerance\Waiter\ExponentialBackOff; |
| 22 | +use Psr\Log\LoggerInterface; |
| 23 | +use Psr\Log\NullLogger; |
| 24 | + |
| 25 | +final class TcpHealthcheck implements Healthcheck |
| 26 | +{ |
| 27 | + private $maxExecutionTime; |
| 28 | + |
| 29 | + private $initialExponent; |
| 30 | + |
| 31 | + private $step; |
| 32 | + |
| 33 | + private $logger; |
| 34 | + |
| 35 | + /** |
| 36 | + * All values are expressed in seconds. |
| 37 | + */ |
| 38 | + public function __construct(float $initialExponent, float $step, float $maxExecutionTime, LoggerInterface $logger = null) |
| 39 | + { |
| 40 | + $this->initialExponent = $initialExponent; |
| 41 | + $this->step = $step; |
| 42 | + $this->maxExecutionTime = $maxExecutionTime; |
| 43 | + $this->logger = $logger ?? new NullLogger(); |
| 44 | + } |
| 45 | + |
| 46 | + public function isReachable(string $destination): bool |
| 47 | + { |
| 48 | + $this->logger->info('Start TCP healthcheck', ['target' => $destination]); |
| 49 | + |
| 50 | + if (false === filter_var($destination, FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED)) { |
| 51 | + throw InvalidDestination::ofProtocol('tcp'); |
| 52 | + } |
| 53 | + ['host' => $host, 'port' => $port] = parse_url($destination); |
| 54 | + |
| 55 | + $runner = new RetryOperationRunner( |
| 56 | + new CallbackOperationRunner(), |
| 57 | + new ExponentialBackOff( |
| 58 | + new Timeout(new SleepWaiter(), $this->maxExecutionTime), |
| 59 | + $this->initialExponent, |
| 60 | + $this->step |
| 61 | + ) |
| 62 | + ); |
| 63 | + $uri = "tcp://${host}:${port}"; |
| 64 | + |
| 65 | + try { |
| 66 | + $runner->run(new Callback(function () use ($uri) { |
| 67 | + $socket = @stream_socket_client($uri, $errno, $errstr, 5); |
| 68 | + if (false === $socket) { |
| 69 | + throw HealthcheckFailure::cannotConnectToUri($uri); |
| 70 | + } |
| 71 | + @fclose($socket); |
| 72 | + return true; |
| 73 | + })); |
| 74 | + $this->logger->info('[OK] TCP healthcheck', ['target' => $destination]); |
| 75 | + return true; |
| 76 | + } catch (\Exception $e) { |
| 77 | + $this->logger->info('[Fail] TCP healthcheck', ['target' => $destination]); |
| 78 | + return false; |
| 79 | + } |
| 80 | + } |
| 81 | +} |
0 commit comments