|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +/** |
| 6 | + * This file is part of Hyperf + OpenCodeCo |
| 7 | + * |
| 8 | + * @link https://opencodeco.dev |
| 9 | + * @document https://hyperf.wiki |
| 10 | + |
| 11 | + * @license https://github.com/opencodeco/hyperf-metric/blob/main/LICENSE |
| 12 | + */ |
| 13 | + |
| 14 | +namespace Hyperf\Metric\Listener; |
| 15 | + |
| 16 | +use Hyperf\Contract\ConfigInterface; |
| 17 | +use Hyperf\Contract\ContainerInterface; |
| 18 | +use Hyperf\Coordinator\Timer; |
| 19 | +use Hyperf\Event\Contract\ListenerInterface; |
| 20 | +use Hyperf\Framework\Event\BeforeWorkerStart; |
| 21 | +use Hyperf\Metric\Metric; |
| 22 | +use Hyperf\Pool\SimplePool\PoolFactory; |
| 23 | +use Hyperf\Server\Event\MainCoroutineServerStart; |
| 24 | + |
| 25 | +class HttpPoolWatcher implements ListenerInterface |
| 26 | +{ |
| 27 | + private const GUZZLE_PREFIX = 'guzzle.handler'; |
| 28 | + |
| 29 | + protected Timer $timer; |
| 30 | + |
| 31 | + public function __construct(protected ContainerInterface $container) |
| 32 | + { |
| 33 | + $this->timer = new Timer(); |
| 34 | + } |
| 35 | + |
| 36 | + public function listen(): array |
| 37 | + { |
| 38 | + return [ |
| 39 | + BeforeWorkerStart::class, |
| 40 | + MainCoroutineServerStart::class, |
| 41 | + ]; |
| 42 | + } |
| 43 | + |
| 44 | + public function process(object $event): void |
| 45 | + { |
| 46 | + /** @var PoolFactory $factory */ |
| 47 | + $factory = $this->container->get(PoolFactory::class); |
| 48 | + $worker = (string) ($event->workerId ?? 0); |
| 49 | + |
| 50 | + $config = $this->container->get(ConfigInterface::class); |
| 51 | + |
| 52 | + $timer_interval = $config->get('metric.default_metric_interval', 5); |
| 53 | + |
| 54 | + $this->timer->tick($timer_interval, function () use ($factory, $worker) { |
| 55 | + foreach ($factory->getPoolNames() as $name) { |
| 56 | + if (strpos($name, self::GUZZLE_PREFIX) !== 0) { |
| 57 | + continue; |
| 58 | + } |
| 59 | + |
| 60 | + $pool = $factory->get($name, function () {}); |
| 61 | + |
| 62 | + $labels = [ |
| 63 | + 'worker' => $worker, |
| 64 | + 'pool' => implode('.', array_slice(explode('.', (string) $name), 2, -2)), |
| 65 | + ]; |
| 66 | + |
| 67 | + Metric::gauge('http_connections_in_use', (float) $pool->getCurrentConnections(), $labels); |
| 68 | + Metric::gauge('http_connections_in_waiting', (float) $pool->getConnectionsInChannel(), $labels); |
| 69 | + Metric::gauge('http_max_connections', (float) $pool->getOption()->getMaxConnections(), $labels); |
| 70 | + } |
| 71 | + }); |
| 72 | + } |
| 73 | +} |
0 commit comments