From a3d66bd89f9622c6213589b98f7e98b425da58cb Mon Sep 17 00:00:00 2001 From: Daniel Noel-Davies Date: Fri, 19 Jul 2019 11:31:19 +0100 Subject: [PATCH 01/28] Replace PHPUnit v with PHPUnit 7 --- composer.json | 4 ++-- examples/pushgateway.php | 3 ++- src/Prometheus/Collector.php | 7 ++++--- .../Exception/MetricNotFoundException.php | 4 +++- .../MetricsRegistrationException.php | 4 +++- src/Prometheus/Exception/StorageException.php | 4 +++- src/Prometheus/Histogram.php | 7 ++++--- src/Prometheus/PushGateway.php | 7 ++++--- src/Prometheus/Storage/APC.php | 13 +++++++------ src/Prometheus/Storage/Redis.php | 9 +++++++-- tests/Test/BlackBoxPushGatewayTest.php | 3 ++- tests/Test/BlackBoxTest.php | 4 ++-- .../AbstractCollectorRegistryTest.php | 19 ++++++++++--------- tests/Test/Prometheus/AbstractCounterTest.php | 9 +++++---- tests/Test/Prometheus/AbstractGaugeTest.php | 9 +++++---- .../Test/Prometheus/AbstractHistogramTest.php | 15 ++++++++------- tests/Test/Prometheus/Storage/RedisTest.php | 10 ++++++---- 17 files changed, 77 insertions(+), 54 deletions(-) diff --git a/composer.json b/composer.json index b941542..ef6c2cf 100644 --- a/composer.json +++ b/composer.json @@ -16,14 +16,14 @@ "symfony/polyfill-apcu": "^1.6" }, "require-dev": { - "phpunit/phpunit": "4.1.0" + "phpunit/phpunit": "^7.5" }, "suggest": { "ext-redis": "Required if using Redis.", "ext-apc": "Required if using APCu." }, "autoload": { - "psr-0": { + "psr-4": { "Prometheus\\": "src/" } }, diff --git a/examples/pushgateway.php b/examples/pushgateway.php index 984035d..feb2172 100644 --- a/examples/pushgateway.php +++ b/examples/pushgateway.php @@ -1,6 +1,7 @@ registerCounter('test', 'some_counter', 'it increases', ['type']); $counter->incBy(6, ['blue']); -$pushGateway = new \Prometheus\PushGateway('192.168.59.100:9091'); +$pushGateway = new PushGateway('192.168.59.100:9091'); $pushGateway->push($registry, 'my_job', array('instance'=>'foo')); diff --git a/src/Prometheus/Collector.php b/src/Prometheus/Collector.php index edc5e80..2b77554 100644 --- a/src/Prometheus/Collector.php +++ b/src/Prometheus/Collector.php @@ -3,6 +3,7 @@ namespace Prometheus; +use InvalidArgumentException; use Prometheus\Storage\Adapter; abstract class Collector @@ -26,13 +27,13 @@ public function __construct(Adapter $storageAdapter, $namespace, $name, $help, $ $this->storageAdapter = $storageAdapter; $metricName = ($namespace ? $namespace . '_' : '') . $name; if (!preg_match(self::RE_METRIC_LABEL_NAME, $metricName)) { - throw new \InvalidArgumentException("Invalid metric name: '" . $metricName . "'"); + throw new InvalidArgumentException("Invalid metric name: '" . $metricName . "'"); } $this->name = $metricName; $this->help = $help; foreach ($labels as $label) { if (!preg_match(self::RE_METRIC_LABEL_NAME, $label)) { - throw new \InvalidArgumentException("Invalid label name: '" . $label . "'"); + throw new InvalidArgumentException("Invalid label name: '" . $label . "'"); } } $this->labels = $labels; @@ -69,7 +70,7 @@ public function getKey() protected function assertLabelsAreDefinedCorrectly($labels) { if (count($labels) != count($this->labels)) { - throw new \InvalidArgumentException(sprintf('Labels are not defined correctly: ', print_r($labels, true))); + throw new InvalidArgumentException(sprintf('Labels are not defined correctly: ', print_r($labels, true))); } } } diff --git a/src/Prometheus/Exception/MetricNotFoundException.php b/src/Prometheus/Exception/MetricNotFoundException.php index ff67175..d35533f 100644 --- a/src/Prometheus/Exception/MetricNotFoundException.php +++ b/src/Prometheus/Exception/MetricNotFoundException.php @@ -4,10 +4,12 @@ namespace Prometheus\Exception; +use Exception; + /** * Exception thrown if a metric can't be found in the CollectorRegistry. */ -class MetricNotFoundException extends \Exception +class MetricNotFoundException extends Exception { } diff --git a/src/Prometheus/Exception/MetricsRegistrationException.php b/src/Prometheus/Exception/MetricsRegistrationException.php index 17f70be..673ad0b 100644 --- a/src/Prometheus/Exception/MetricsRegistrationException.php +++ b/src/Prometheus/Exception/MetricsRegistrationException.php @@ -4,10 +4,12 @@ namespace Prometheus\Exception; +use Exception; + /** * Exception thrown if an error occurs during metrics registration. */ -class MetricsRegistrationException extends \Exception +class MetricsRegistrationException extends Exception { } diff --git a/src/Prometheus/Exception/StorageException.php b/src/Prometheus/Exception/StorageException.php index 782e6e3..641a739 100644 --- a/src/Prometheus/Exception/StorageException.php +++ b/src/Prometheus/Exception/StorageException.php @@ -4,10 +4,12 @@ namespace Prometheus\Exception; +use Exception; + /** * Exception thrown if an error occurs during metrics storage. */ -class StorageException extends \Exception +class StorageException extends Exception { } diff --git a/src/Prometheus/Histogram.php b/src/Prometheus/Histogram.php index 9dbfda4..cafbcbe 100644 --- a/src/Prometheus/Histogram.php +++ b/src/Prometheus/Histogram.php @@ -3,6 +3,7 @@ namespace Prometheus; +use InvalidArgumentException; use Prometheus\Storage\Adapter; class Histogram extends Collector @@ -28,12 +29,12 @@ public function __construct(Adapter $adapter, $namespace, $name, $help, $labels } if (0 == count($buckets)) { - throw new \InvalidArgumentException("Histogram must have at least one bucket."); + throw new InvalidArgumentException("Histogram must have at least one bucket."); } for ($i = 0; $i < count($buckets) - 1; $i++) { if ($buckets[$i] >= $buckets[$i + 1]) { - throw new \InvalidArgumentException( + throw new InvalidArgumentException( "Histogram buckets must be in increasing order: " . $buckets[$i] . " >= " . $buckets[$i + 1] ); @@ -41,7 +42,7 @@ public function __construct(Adapter $adapter, $namespace, $name, $help, $labels } foreach ($labels as $label) { if ($label === 'le') { - throw new \InvalidArgumentException("Histogram cannot have a label named 'le'."); + throw new InvalidArgumentException("Histogram cannot have a label named 'le'."); } } $this->buckets = $buckets; diff --git a/src/Prometheus/PushGateway.php b/src/Prometheus/PushGateway.php index a4a3fd2..42f3197 100644 --- a/src/Prometheus/PushGateway.php +++ b/src/Prometheus/PushGateway.php @@ -5,6 +5,7 @@ use GuzzleHttp\Client; +use RuntimeException; class PushGateway { @@ -44,7 +45,7 @@ public function pushAdd(CollectorRegistry $collectorRegistry, $job, $groupingKey } /** - * Deletes metrics from the Pushgateway. + * Deletes metrics from the Push Gateway. * Uses HTTP POST. * @param $job * @param $groupingKey @@ -83,8 +84,8 @@ private function doRequest(CollectorRegistry $collectorRegistry, $job, $grouping $response = $client->request($method, $url, $requestOptions); $statusCode = $response->getStatusCode(); if ($statusCode != 202) { - $msg = "Unexpected status code " . $statusCode . " received from pushgateway " . $this->address . ": " . $response->getBody(); - throw new \RuntimeException($msg); + $msg = "Unexpected status code " . $statusCode . " received from push gateway " . $this->address . ": " . $response->getBody(); + throw new RuntimeException($msg); } } diff --git a/src/Prometheus/Storage/APC.php b/src/Prometheus/Storage/APC.php index b608e49..3d386fa 100644 --- a/src/Prometheus/Storage/APC.php +++ b/src/Prometheus/Storage/APC.php @@ -4,6 +4,7 @@ namespace Prometheus\Storage; +use APCUIterator; use Prometheus\MetricFamilySamples; use RuntimeException; @@ -148,7 +149,7 @@ private function metaData(array $data) private function collectCounters() { $counters = array(); - foreach (new \APCUIterator('/^prom:counter:.*:meta/') as $counter) { + foreach (new APCUIterator('/^prom:counter:.*:meta/') as $counter) { $metaData = json_decode($counter['value'], true); $data = array( 'name' => $metaData['name'], @@ -156,7 +157,7 @@ private function collectCounters() 'type' => $metaData['type'], 'labelNames' => $metaData['labelNames'], ); - foreach (new \APCUIterator('/^prom:counter:' . $metaData['name'] . ':.*:value/') as $value) { + foreach (new APCUIterator('/^prom:counter:' . $metaData['name'] . ':.*:value/') as $value) { $parts = explode(':', $value['key']); $labelValues = $parts[3]; $data['samples'][] = array( @@ -178,7 +179,7 @@ private function collectCounters() private function collectGauges() { $gauges = array(); - foreach (new \APCUIterator('/^prom:gauge:.*:meta/') as $gauge) { + foreach (new APCUIterator('/^prom:gauge:.*:meta/') as $gauge) { $metaData = json_decode($gauge['value'], true); $data = array( 'name' => $metaData['name'], @@ -186,7 +187,7 @@ private function collectGauges() 'type' => $metaData['type'], 'labelNames' => $metaData['labelNames'], ); - foreach (new \APCUIterator('/^prom:gauge:' . $metaData['name'] . ':.*:value/') as $value) { + foreach (new APCUIterator('/^prom:gauge:' . $metaData['name'] . ':.*:value/') as $value) { $parts = explode(':', $value['key']); $labelValues = $parts[3]; $data['samples'][] = array( @@ -209,7 +210,7 @@ private function collectGauges() private function collectHistograms() { $histograms = array(); - foreach (new \APCUIterator('/^prom:histogram:.*:meta/') as $histogram) { + foreach (new APCUIterator('/^prom:histogram:.*:meta/') as $histogram) { $metaData = json_decode($histogram['value'], true); $data = array( 'name' => $metaData['name'], @@ -223,7 +224,7 @@ private function collectHistograms() $data['buckets'][] = '+Inf'; $histogramBuckets = array(); - foreach (new \APCUIterator('/^prom:histogram:' . $metaData['name'] . ':.*:value/') as $value) { + foreach (new APCUIterator('/^prom:histogram:' . $metaData['name'] . ':.*:value/') as $value) { $parts = explode(':', $value['key']); $labelValues = $parts[3]; $bucket = $parts[4]; diff --git a/src/Prometheus/Storage/Redis.php b/src/Prometheus/Storage/Redis.php index 091577c..a099cd1 100644 --- a/src/Prometheus/Storage/Redis.php +++ b/src/Prometheus/Storage/Redis.php @@ -3,11 +3,13 @@ namespace Prometheus\Storage; +use InvalidArgumentException; use Prometheus\Counter; use Prometheus\Exception\StorageException; use Prometheus\Gauge; use Prometheus\Histogram; use Prometheus\MetricFamilySamples; +use RedisException; class Redis implements Adapter { @@ -59,6 +61,9 @@ public static function setPrefix($prefix) self::$prefix = $prefix; } + /** + * @throws StorageException + */ public function flushRedis() { $this->openConnection(); @@ -103,7 +108,7 @@ private function openConnection() $this->redis->setOption(\Redis::OPT_READ_TIMEOUT, $this->options['read_timeout']); - } catch (\RedisException $e) { + } catch (RedisException $e) { throw new StorageException("Can't connect to Redis server", 0, $e); } } @@ -342,7 +347,7 @@ private function getRedisCommand($cmd) case Adapter::COMMAND_SET: return 'hSet'; default: - throw new \InvalidArgumentException("Unknown command"); + throw new InvalidArgumentException("Unknown command"); } } diff --git a/tests/Test/BlackBoxPushGatewayTest.php b/tests/Test/BlackBoxPushGatewayTest.php index 26490c6..5453f43 100644 --- a/tests/Test/BlackBoxPushGatewayTest.php +++ b/tests/Test/BlackBoxPushGatewayTest.php @@ -2,13 +2,14 @@ namespace Test; use GuzzleHttp\Client; +use PHPUnit\Framework\TestCase; use PHPUnit_Framework_TestCase; use Prometheus\CollectorRegistry; use Prometheus\PushGateway; use Prometheus\Storage\APC; -class BlackBoxPushGatewayTest extends PHPUnit_Framework_TestCase +class BlackBoxPushGatewayTest extends TestCase { /** * @test diff --git a/tests/Test/BlackBoxTest.php b/tests/Test/BlackBoxTest.php index d57f3a3..f3a2dc0 100644 --- a/tests/Test/BlackBoxTest.php +++ b/tests/Test/BlackBoxTest.php @@ -3,9 +3,9 @@ use GuzzleHttp\Client; use GuzzleHttp\Promise; -use PHPUnit_Framework_TestCase; +use PHPUnit\Framework\TestCase; -class BlackBoxTest extends PHPUnit_Framework_TestCase +class BlackBoxTest extends TestCase { /** * @var Client diff --git a/tests/Test/Prometheus/AbstractCollectorRegistryTest.php b/tests/Test/Prometheus/AbstractCollectorRegistryTest.php index 237685c..e14f4e1 100644 --- a/tests/Test/Prometheus/AbstractCollectorRegistryTest.php +++ b/tests/Test/Prometheus/AbstractCollectorRegistryTest.php @@ -4,15 +4,16 @@ namespace Test\Prometheus; -use PHPUnit_Framework_TestCase; +use PHPUnit\Framework\TestCase; use Prometheus\CollectorRegistry; +use Prometheus\Exception\MetricNotFoundException; use Prometheus\Exception\MetricsRegistrationException; use Prometheus\Histogram; use Prometheus\RenderTextFormat; use Prometheus\Storage\Adapter; use Prometheus\Storage\Redis; -abstract class AbstractCollectorRegistryTest extends PHPUnit_Framework_TestCase +abstract class AbstractCollectorRegistryTest extends TestCase { /** * @var Adapter @@ -195,7 +196,7 @@ public function itShouldIncreaseACounterWithoutNamespace() /** * @test - * @expectedException \Prometheus\Exception\MetricsRegistrationException + * @expectedException MetricsRegistrationException */ public function itShouldForbidRegisteringTheSameCounterTwice() { @@ -206,7 +207,7 @@ public function itShouldForbidRegisteringTheSameCounterTwice() /** * @test - * @expectedException \Prometheus\Exception\MetricsRegistrationException + * @expectedException MetricsRegistrationException */ public function itShouldForbidRegisteringTheSameCounterWithDifferentLabels() { @@ -217,7 +218,7 @@ public function itShouldForbidRegisteringTheSameCounterWithDifferentLabels() /** * @test - * @expectedException \Prometheus\Exception\MetricsRegistrationException + * @expectedException MetricsRegistrationException */ public function itShouldForbidRegisteringTheSameHistogramTwice() { @@ -228,7 +229,7 @@ public function itShouldForbidRegisteringTheSameHistogramTwice() /** * @test - * @expectedException \Prometheus\Exception\MetricsRegistrationException + * @expectedException MetricsRegistrationException */ public function itShouldForbidRegisteringTheSameHistogramWithDifferentLabels() { @@ -239,7 +240,7 @@ public function itShouldForbidRegisteringTheSameHistogramWithDifferentLabels() /** * @test - * @expectedException \Prometheus\Exception\MetricsRegistrationException + * @expectedException MetricsRegistrationException */ public function itShouldForbidRegisteringTheSameGaugeTwice() { @@ -250,7 +251,7 @@ public function itShouldForbidRegisteringTheSameGaugeTwice() /** * @test - * @expectedException \Prometheus\Exception\MetricsRegistrationException + * @expectedException MetricsRegistrationException */ public function itShouldForbidRegisteringTheSameGaugeWithDifferentLabels() { @@ -261,7 +262,7 @@ public function itShouldForbidRegisteringTheSameGaugeWithDifferentLabels() /** * @test - * @expectedException \Prometheus\Exception\MetricNotFoundException + * @expectedException MetricNotFoundException */ public function itShouldThrowAnExceptionWhenGettingANonExistentMetric() { diff --git a/tests/Test/Prometheus/AbstractCounterTest.php b/tests/Test/Prometheus/AbstractCounterTest.php index 188310c..3487c0d 100644 --- a/tests/Test/Prometheus/AbstractCounterTest.php +++ b/tests/Test/Prometheus/AbstractCounterTest.php @@ -3,7 +3,8 @@ namespace Test\Prometheus; -use PHPUnit_Framework_TestCase; +use InvalidArgumentException; +use PHPUnit\Framework\TestCase; use Prometheus\Counter; use Prometheus\MetricFamilySamples; use Prometheus\Sample; @@ -12,7 +13,7 @@ /** * See https://prometheus.io/docs/instrumenting/exposition_formats/ */ -abstract class AbstractCounterTest extends PHPUnit_Framework_TestCase +abstract class AbstractCounterTest extends TestCase { /** * @var Adapter @@ -125,7 +126,7 @@ public function itShouldIncreaseTheCounterByAnArbitraryInteger() /** * @test - * @expectedException \InvalidArgumentException + * @expectedException InvalidArgumentException */ public function itShouldRejectInvalidMetricsNames() { @@ -134,7 +135,7 @@ public function itShouldRejectInvalidMetricsNames() /** * @test - * @expectedException \InvalidArgumentException + * @expectedException InvalidArgumentException */ public function itShouldRejectInvalidLabelNames() { diff --git a/tests/Test/Prometheus/AbstractGaugeTest.php b/tests/Test/Prometheus/AbstractGaugeTest.php index 33ad02c..32c2673 100644 --- a/tests/Test/Prometheus/AbstractGaugeTest.php +++ b/tests/Test/Prometheus/AbstractGaugeTest.php @@ -3,7 +3,8 @@ namespace Test\Prometheus; -use PHPUnit_Framework_TestCase; +use InvalidArgumentException; +use PHPUnit\Framework\TestCase; use Prometheus\Gauge; use Prometheus\MetricFamilySamples; use Prometheus\Sample; @@ -12,7 +13,7 @@ /** * See https://prometheus.io/docs/instrumenting/exposition_formats/ */ -abstract class AbstractGaugeTest extends PHPUnit_Framework_TestCase +abstract class AbstractGaugeTest extends TestCase { /** * @var Adapter @@ -293,7 +294,7 @@ public function itShouldOverwriteWhenSettingTwice() /** * @test - * @expectedException \InvalidArgumentException + * @expectedException InvalidArgumentException */ public function itShouldRejectInvalidMetricsNames() { @@ -302,7 +303,7 @@ public function itShouldRejectInvalidMetricsNames() /** * @test - * @expectedException \InvalidArgumentException + * @expectedException InvalidArgumentException */ public function itShouldRejectInvalidLabelNames() { diff --git a/tests/Test/Prometheus/AbstractHistogramTest.php b/tests/Test/Prometheus/AbstractHistogramTest.php index 358fcad..af982d5 100644 --- a/tests/Test/Prometheus/AbstractHistogramTest.php +++ b/tests/Test/Prometheus/AbstractHistogramTest.php @@ -3,7 +3,8 @@ namespace Test\Prometheus; -use PHPUnit_Framework_TestCase; +use InvalidArgumentException; +use PHPUnit\Framework\TestCase; use Prometheus\Histogram; use Prometheus\MetricFamilySamples; use Prometheus\Sample; @@ -13,7 +14,7 @@ /** * See https://prometheus.io/docs/instrumenting/exposition_formats/ */ -abstract class AbstractHistogramTest extends PHPUnit_Framework_TestCase +abstract class AbstractHistogramTest extends TestCase { /** * @var Adapter @@ -374,7 +375,7 @@ public function itShouldProvideDefaultBuckets() /** * @test - * @expectedException \InvalidArgumentException + * @expectedException InvalidArgumentException * @expectedExceptionMessage Histogram buckets must be in increasing order */ public function itShouldThrowAnExceptionWhenTheBucketSizesAreNotIncreasing() @@ -384,7 +385,7 @@ public function itShouldThrowAnExceptionWhenTheBucketSizesAreNotIncreasing() /** * @test - * @expectedException \InvalidArgumentException + * @expectedException InvalidArgumentException * @expectedExceptionMessage Histogram must have at least one bucket */ public function itShouldThrowAnExceptionWhenThereIsLessThanOneBucket() @@ -394,7 +395,7 @@ public function itShouldThrowAnExceptionWhenThereIsLessThanOneBucket() /** * @test - * @expectedException \InvalidArgumentException + * @expectedException InvalidArgumentException * @expectedExceptionMessage Histogram cannot have a label named */ public function itShouldThrowAnExceptionWhenThereIsALabelNamedLe() @@ -404,7 +405,7 @@ public function itShouldThrowAnExceptionWhenThereIsALabelNamedLe() /** * @test - * @expectedException \InvalidArgumentException + * @expectedException InvalidArgumentException * @expectedExceptionMessage Invalid metric name */ public function itShouldRejectInvalidMetricsNames() @@ -414,7 +415,7 @@ public function itShouldRejectInvalidMetricsNames() /** * @test - * @expectedException \InvalidArgumentException + * @expectedException InvalidArgumentException * @expectedExceptionMessage Invalid label name */ public function itShouldRejectInvalidLabelNames() diff --git a/tests/Test/Prometheus/Storage/RedisTest.php b/tests/Test/Prometheus/Storage/RedisTest.php index 8175475..dcaddba 100644 --- a/tests/Test/Prometheus/Storage/RedisTest.php +++ b/tests/Test/Prometheus/Storage/RedisTest.php @@ -1,21 +1,23 @@ 'doesntexist.test')); + $redis = new Redis(['host' => 'completely.fake.example.test']); $redis->flushRedis(); } From b2614eec085382a58e5951d0d931e199f69228f9 Mon Sep 17 00:00:00 2001 From: Daniel Noel-Davies Date: Fri, 19 Jul 2019 11:45:10 +0100 Subject: [PATCH 02/28] Add json extension requirement --- composer.json | 1 + 1 file changed, 1 insertion(+) diff --git a/composer.json b/composer.json index ef6c2cf..9feb833 100644 --- a/composer.json +++ b/composer.json @@ -12,6 +12,7 @@ ], "require": { "php": ">=5.6.3", + "ext-json": "*", "guzzlehttp/guzzle": "^6.2", "symfony/polyfill-apcu": "^1.6" }, From 1a0cc231f33e784096ca5d75927d1b80f7a1d11b Mon Sep 17 00:00:00 2001 From: Daniel Noel-Davies Date: Fri, 19 Jul 2019 11:45:44 +0100 Subject: [PATCH 03/28] Add docblocks --- src/Prometheus/Collector.php | 29 ++++++++++- src/Prometheus/CollectorRegistry.php | 18 +++++-- src/Prometheus/Counter.php | 2 - .../Exception/MetricNotFoundException.php | 3 -- .../MetricsRegistrationException.php | 3 -- src/Prometheus/Exception/StorageException.php | 3 -- src/Prometheus/Gauge.php | 16 +++++- src/Prometheus/Histogram.php | 4 +- src/Prometheus/MetricFamilySamples.php | 19 +++++++ src/Prometheus/PushGateway.php | 16 +++--- src/Prometheus/RenderTextFormat.php | 10 +++- src/Prometheus/Sample.php | 20 +++++++- src/Prometheus/Storage/APC.php | 12 +++++ src/Prometheus/Storage/InMemory.php | 23 +++++++-- src/Prometheus/Storage/Redis.php | 49 ++++++++++++++++++- 15 files changed, 195 insertions(+), 32 deletions(-) diff --git a/src/Prometheus/Collector.php b/src/Prometheus/Collector.php index 2b77554..bc85277 100644 --- a/src/Prometheus/Collector.php +++ b/src/Prometheus/Collector.php @@ -1,8 +1,6 @@ name; } + /** + * @return array + */ public function getLabelNames() { return $this->labels; } + /** + * @return string + */ public function getHelp() { return $this->help; } + /** + * @return string + */ public function getKey() { return sha1($this->getName() . serialize($this->getLabelNames())); diff --git a/src/Prometheus/CollectorRegistry.php b/src/Prometheus/CollectorRegistry.php index 9ff18e3..28a707a 100644 --- a/src/Prometheus/CollectorRegistry.php +++ b/src/Prometheus/CollectorRegistry.php @@ -1,9 +1,6 @@ storageAdapter = $redisAdapter; @@ -102,6 +106,7 @@ public function getGauge($namespace, $name) * @param string $help e.g. The duration something took in seconds. * @param array $labels e.g. ['controller', 'action'] * @return Gauge + * @throws MetricsRegistrationException */ public function getOrRegisterGauge($namespace, $name, $help, $labels = array()) { @@ -158,6 +163,7 @@ public function getCounter($namespace, $name) * @param string $help e.g. The number of requests made. * @param array $labels e.g. ['controller', 'action'] * @return Counter + * @throws MetricsRegistrationException */ public function getOrRegisterCounter($namespace, $name, $help, $labels = array()) { @@ -217,6 +223,7 @@ public function getHistogram($namespace, $name) * @param array $labels e.g. ['controller', 'action'] * @param array $buckets e.g. [100, 200, 300] * @return Histogram + * @throws MetricsRegistrationException */ public function getOrRegisterHistogram($namespace, $name, $help, $labels = array(), $buckets = null) { @@ -228,6 +235,11 @@ public function getOrRegisterHistogram($namespace, $name, $help, $labels = array return $histogram; } + /** + * @param $namespace + * @param $name + * @return string + */ private static function metricIdentifier($namespace, $name) { return $namespace . ":" . $name; diff --git a/src/Prometheus/Counter.php b/src/Prometheus/Counter.php index 3624c9c..e580ff6 100644 --- a/src/Prometheus/Counter.php +++ b/src/Prometheus/Counter.php @@ -1,8 +1,6 @@ incBy(1, $labels); } + /** + * @param $value + * @param array $labels + */ public function incBy($value, $labels = array()) { $this->assertLabelsAreDefinedCorrectly($labels); @@ -61,11 +66,18 @@ public function incBy($value, $labels = array()) ); } + /** + * @param array $labels + */ public function dec($labels = array()) { $this->decBy(1, $labels); } + /** + * @param $value + * @param array $labels + */ public function decBy($value, $labels = array()) { $this->incBy(-$value, $labels); diff --git a/src/Prometheus/Histogram.php b/src/Prometheus/Histogram.php index cafbcbe..a8e9107 100644 --- a/src/Prometheus/Histogram.php +++ b/src/Prometheus/Histogram.php @@ -2,7 +2,6 @@ namespace Prometheus; - use InvalidArgumentException; use Prometheus\Storage\Adapter; @@ -10,6 +9,9 @@ class Histogram extends Collector { const TYPE = 'histogram'; + /** + * @var array|null + */ private $buckets; /** diff --git a/src/Prometheus/MetricFamilySamples.php b/src/Prometheus/MetricFamilySamples.php index e88e9aa..a3c79c1 100644 --- a/src/Prometheus/MetricFamilySamples.php +++ b/src/Prometheus/MetricFamilySamples.php @@ -4,10 +4,29 @@ class MetricFamilySamples { + /** + * @var mixed + */ private $name; + + /** + * @var string + */ private $type; + + /** + * @var string + */ private $help; + + /** + * @var array + */ private $labelNames; + + /** + * @var array + */ private $samples = array(); /** diff --git a/src/Prometheus/PushGateway.php b/src/Prometheus/PushGateway.php index 42f3197..6cfc421 100644 --- a/src/Prometheus/PushGateway.php +++ b/src/Prometheus/PushGateway.php @@ -1,14 +1,15 @@ getName() . ' ' . $sample->getValue(); } + /** + * @param $v + * @return mixed + */ private function escapeLabelValue($v) { $v = str_replace("\\", "\\\\", $v); diff --git a/src/Prometheus/Sample.php b/src/Prometheus/Sample.php index 9d9d1b3..a88a027 100644 --- a/src/Prometheus/Sample.php +++ b/src/Prometheus/Sample.php @@ -2,14 +2,32 @@ namespace Prometheus; - class Sample { + /** + * @var string + */ private $name; + + /** + * @var array + */ private $labelNames; + + /** + * @var array + */ private $labelValues; + + /** + * @var int|double + */ private $value; + /** + * Sample constructor. + * @param array $data + */ public function __construct(array $data) { $this->name = $data['name']; diff --git a/src/Prometheus/Storage/APC.php b/src/Prometheus/Storage/APC.php index 3d386fa..4c03b9b 100644 --- a/src/Prometheus/Storage/APC.php +++ b/src/Prometheus/Storage/APC.php @@ -23,6 +23,9 @@ public function collect() return $metrics; } + /** + * @param array $data + */ public function updateHistogram(array $data) { // Initialize the sum @@ -56,6 +59,9 @@ public function updateHistogram(array $data) apcu_inc($this->histogramBucketValueKey($data, $bucketToIncrease)); } + /** + * @param array $data + */ public function updateGauge(array $data) { $valueKey = $this->valueKey($data); @@ -76,6 +82,9 @@ public function updateGauge(array $data) } } + /** + * @param array $data + */ public function updateCounter(array $data) { $new = apcu_add($this->valueKey($data), 0); @@ -298,6 +307,9 @@ private function fromInteger($val) return unpack('d', pack('Q', $val))[1]; } + /** + * @param array $samples + */ private function sortSamples(array &$samples) { usort($samples, function($a, $b){ diff --git a/src/Prometheus/Storage/InMemory.php b/src/Prometheus/Storage/InMemory.php index 313dbf4..1c56de7 100644 --- a/src/Prometheus/Storage/InMemory.php +++ b/src/Prometheus/Storage/InMemory.php @@ -31,6 +31,9 @@ public function flushMemory() $this->histograms = []; } + /** + * @return array + */ private function collectHistograms() { $histograms = []; @@ -104,6 +107,10 @@ private function collectHistograms() return $histograms; } + /** + * @param array $metrics + * @return array + */ private function internalCollect(array $metrics) { $result = []; @@ -131,6 +138,9 @@ private function internalCollect(array $metrics) return $result; } + /** + * @param array $data + */ public function updateHistogram(array $data) { // Initialize the sum @@ -164,6 +174,9 @@ public function updateHistogram(array $data) $this->histograms[$metaKey]['samples'][$bucketKey] += 1; } + /** + * @param array $data + */ public function updateGauge(array $data) { $metaKey = $this->metaKey($data); @@ -184,6 +197,9 @@ public function updateGauge(array $data) } } + /** + * @param array $data + */ public function updateCounter(array $data) { $metaKey = $this->metaKey($data); @@ -206,9 +222,7 @@ public function updateCounter(array $data) /** * @param array $data - * - * @param $bucket - * + * @param string $bucket * @return string */ private function histogramBucketValueKey(array $data, $bucket) @@ -256,6 +270,9 @@ private function metaData(array $data) return $metricsMetaData; } + /** + * @param array $samples + */ private function sortSamples(array &$samples) { usort($samples, function ($a, $b) { diff --git a/src/Prometheus/Storage/Redis.php b/src/Prometheus/Storage/Redis.php index a099cd1..5babba0 100644 --- a/src/Prometheus/Storage/Redis.php +++ b/src/Prometheus/Storage/Redis.php @@ -1,8 +1,6 @@ openConnection(); @@ -147,6 +170,10 @@ public function updateHistogram(array $data) ); } + /** + * @param array $data + * @throws StorageException + */ public function updateGauge(array $data) { $this->openConnection(); @@ -182,6 +209,11 @@ public function updateGauge(array $data) ); } + /** + * @param array $data + * @return mixed + * @throws StorageException + */ public function updateCounter(array $data) { $this->openConnection(); @@ -211,6 +243,9 @@ public function updateCounter(array $data) return $result; } + /** + * @return array + */ private function collectHistograms() { $keys = $this->redis->sMembers(self::$prefix . Histogram::TYPE . self::PROMETHEUS_METRIC_KEYS_SUFFIX); @@ -285,6 +320,9 @@ private function collectHistograms() return $histograms; } + /** + * @return array + */ private function collectGauges() { $keys = $this->redis->sMembers(self::$prefix . Gauge::TYPE . self::PROMETHEUS_METRIC_KEYS_SUFFIX); @@ -311,6 +349,9 @@ private function collectGauges() return $gauges; } + /** + * @return array + */ private function collectCounters() { $keys = $this->redis->sMembers(self::$prefix . Counter::TYPE . self::PROMETHEUS_METRIC_KEYS_SUFFIX); @@ -337,6 +378,10 @@ private function collectCounters() return $counters; } + /** + * @param string $cmd + * @return string + */ private function getRedisCommand($cmd) { switch ($cmd) { From f553bb1d68131d30442a265d93239768d89cd6a0 Mon Sep 17 00:00:00 2001 From: Daniel Noel-Davies Date: Fri, 19 Jul 2019 11:53:52 +0100 Subject: [PATCH 04/28] Fix full length expected exceptions in test suite --- .../Prometheus/AbstractCollectorRegistryTest.php | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/tests/Test/Prometheus/AbstractCollectorRegistryTest.php b/tests/Test/Prometheus/AbstractCollectorRegistryTest.php index e14f4e1..766c993 100644 --- a/tests/Test/Prometheus/AbstractCollectorRegistryTest.php +++ b/tests/Test/Prometheus/AbstractCollectorRegistryTest.php @@ -196,7 +196,7 @@ public function itShouldIncreaseACounterWithoutNamespace() /** * @test - * @expectedException MetricsRegistrationException + * @expectedException \Prometheus\Exception\MetricsRegistrationException */ public function itShouldForbidRegisteringTheSameCounterTwice() { @@ -207,7 +207,7 @@ public function itShouldForbidRegisteringTheSameCounterTwice() /** * @test - * @expectedException MetricsRegistrationException + * @expectedException \Prometheus\Exception\MetricsRegistrationException */ public function itShouldForbidRegisteringTheSameCounterWithDifferentLabels() { @@ -218,7 +218,7 @@ public function itShouldForbidRegisteringTheSameCounterWithDifferentLabels() /** * @test - * @expectedException MetricsRegistrationException + * @expectedException \Prometheus\Exception\MetricsRegistrationException */ public function itShouldForbidRegisteringTheSameHistogramTwice() { @@ -229,7 +229,7 @@ public function itShouldForbidRegisteringTheSameHistogramTwice() /** * @test - * @expectedException MetricsRegistrationException + * @expectedException \Prometheus\Exception\MetricsRegistrationException */ public function itShouldForbidRegisteringTheSameHistogramWithDifferentLabels() { @@ -240,7 +240,7 @@ public function itShouldForbidRegisteringTheSameHistogramWithDifferentLabels() /** * @test - * @expectedException MetricsRegistrationException + * @expectedException \Prometheus\Exception\MetricsRegistrationException */ public function itShouldForbidRegisteringTheSameGaugeTwice() { @@ -251,7 +251,7 @@ public function itShouldForbidRegisteringTheSameGaugeTwice() /** * @test - * @expectedException MetricsRegistrationException + * @expectedException \Prometheus\Exception\MetricsRegistrationException */ public function itShouldForbidRegisteringTheSameGaugeWithDifferentLabels() { @@ -262,7 +262,7 @@ public function itShouldForbidRegisteringTheSameGaugeWithDifferentLabels() /** * @test - * @expectedException MetricNotFoundException + * @expectedException \Prometheus\Exception\MetricNotFoundException */ public function itShouldThrowAnExceptionWhenGettingANonExistentMetric() { From f282d4cd93df3342bb85390e6c105c6b9a3d91fa Mon Sep 17 00:00:00 2001 From: Daniel Noel-Davies Date: Mon, 22 Jul 2019 10:23:22 +0100 Subject: [PATCH 05/28] Add typehints, return types and all-round php 7 goodness --- composer.json | 2 +- examples/flush_adapter.php | 2 +- examples/metrics.php | 2 +- examples/pushgateway.php | 4 +- examples/some_counter.php | 2 +- examples/some_gauge.php | 2 +- examples/some_histogram.php | 2 +- phpunit.xml | 26 +- src/Prometheus/Collector.php | 14 +- src/Prometheus/CollectorRegistry.php | 32 +- src/Prometheus/Counter.php | 14 +- .../Exception/MetricNotFoundException.php | 1 + .../MetricsRegistrationException.php | 1 + src/Prometheus/Exception/StorageException.php | 1 + src/Prometheus/Gauge.php | 25 +- src/Prometheus/Histogram.php | 19 +- src/Prometheus/MetricFamilySamples.php | 15 +- src/Prometheus/PushGateway.php | 41 +- src/Prometheus/RenderTextFormat.php | 23 +- src/Prometheus/Sample.php | 13 +- src/Prometheus/Storage/APC.php | 167 ++++---- src/Prometheus/Storage/Adapter.php | 22 +- src/Prometheus/Storage/InMemory.php | 79 ++-- src/Prometheus/Storage/Redis.php | 189 +++++---- tests/Test/BlackBoxPushGatewayTest.php | 4 +- .../AbstractCollectorRegistryTest.php | 84 ++-- tests/Test/Prometheus/AbstractCounterTest.php | 100 ++--- tests/Test/Prometheus/AbstractGaugeTest.php | 240 +++++------ .../Test/Prometheus/AbstractHistogramTest.php | 384 +++++++++--------- .../Redis/CollectorRegistryTest.php | 2 +- tests/Test/Prometheus/Redis/CounterTest.php | 2 +- tests/Test/Prometheus/Redis/GaugeTest.php | 2 +- tests/Test/Prometheus/Redis/HistogramTest.php | 2 +- tests/Test/Prometheus/Storage/RedisTest.php | 5 +- 34 files changed, 811 insertions(+), 712 deletions(-) diff --git a/composer.json b/composer.json index 9feb833..22eec8a 100644 --- a/composer.json +++ b/composer.json @@ -11,7 +11,7 @@ } ], "require": { - "php": ">=5.6.3", + "php": "^7.1", "ext-json": "*", "guzzlehttp/guzzle": "^6.2", "symfony/polyfill-apcu": "^1.6" diff --git a/examples/flush_adapter.php b/examples/flush_adapter.php index 0c3862d..028fdc7 100644 --- a/examples/flush_adapter.php +++ b/examples/flush_adapter.php @@ -6,7 +6,7 @@ if ($adapter === 'redis') { define('REDIS_HOST', isset($_SERVER['REDIS_HOST']) ? $_SERVER['REDIS_HOST'] : '127.0.0.1'); - $redisAdapter = new Prometheus\Storage\Redis(array('host' => REDIS_HOST)); + $redisAdapter = new Prometheus\Storage\Redis(['host' => REDIS_HOST]); $redisAdapter->flushRedis(); } elseif ($adapter === 'apc') { $apcAdapter = new Prometheus\Storage\APC(); diff --git a/examples/metrics.php b/examples/metrics.php index fa89247..74a111b 100644 --- a/examples/metrics.php +++ b/examples/metrics.php @@ -9,7 +9,7 @@ $adapter = $_GET['adapter']; if ($adapter === 'redis') { - Redis::setDefaultOptions(array('host' => isset($_SERVER['REDIS_HOST']) ? $_SERVER['REDIS_HOST'] : '127.0.0.1')); + Redis::setDefaultOptions(['host' => isset($_SERVER['REDIS_HOST']) ? $_SERVER['REDIS_HOST'] : '127.0.0.1']); $adapter = new Prometheus\Storage\Redis(); } elseif ($adapter === 'apc') { $adapter = new Prometheus\Storage\APC(); diff --git a/examples/pushgateway.php b/examples/pushgateway.php index feb2172..e78706f 100644 --- a/examples/pushgateway.php +++ b/examples/pushgateway.php @@ -8,7 +8,7 @@ $adapter = $_GET['adapter']; if ($adapter === 'redis') { - Redis::setDefaultOptions(array('host' => isset($_SERVER['REDIS_HOST']) ? $_SERVER['REDIS_HOST'] : '127.0.0.1')); + Redis::setDefaultOptions(['host' => isset($_SERVER['REDIS_HOST']) ? $_SERVER['REDIS_HOST'] : '127.0.0.1']); $adapter = new Prometheus\Storage\Redis(); } elseif ($adapter === 'apc') { $adapter = new Prometheus\Storage\APC(); @@ -22,4 +22,4 @@ $counter->incBy(6, ['blue']); $pushGateway = new PushGateway('192.168.59.100:9091'); -$pushGateway->push($registry, 'my_job', array('instance'=>'foo')); +$pushGateway->push($registry, 'my_job', ['instance'=>'foo']); diff --git a/examples/some_counter.php b/examples/some_counter.php index 823bfac..71e7290 100644 --- a/examples/some_counter.php +++ b/examples/some_counter.php @@ -8,7 +8,7 @@ $adapter = $_GET['adapter']; if ($adapter === 'redis') { - Redis::setDefaultOptions(array('host' => isset($_SERVER['REDIS_HOST']) ? $_SERVER['REDIS_HOST'] : '127.0.0.1')); + Redis::setDefaultOptions(['host' => isset($_SERVER['REDIS_HOST']) ? $_SERVER['REDIS_HOST'] : '127.0.0.1']); $adapter = new Prometheus\Storage\Redis(); } elseif ($adapter === 'apc') { $adapter = new Prometheus\Storage\APC(); diff --git a/examples/some_gauge.php b/examples/some_gauge.php index b3e2382..ca2180f 100644 --- a/examples/some_gauge.php +++ b/examples/some_gauge.php @@ -11,7 +11,7 @@ $adapter = $_GET['adapter']; if ($adapter === 'redis') { - Redis::setDefaultOptions(array('host' => isset($_SERVER['REDIS_HOST']) ? $_SERVER['REDIS_HOST'] : '127.0.0.1')); + Redis::setDefaultOptions(['host' => isset($_SERVER['REDIS_HOST']) ? $_SERVER['REDIS_HOST'] : '127.0.0.1']); $adapter = new Prometheus\Storage\Redis(); } elseif ($adapter === 'apc') { $adapter = new Prometheus\Storage\APC(); diff --git a/examples/some_histogram.php b/examples/some_histogram.php index 6b34809..babbced 100644 --- a/examples/some_histogram.php +++ b/examples/some_histogram.php @@ -10,7 +10,7 @@ $adapter = $_GET['adapter']; if ($adapter === 'redis') { - Redis::setDefaultOptions(array('host' => isset($_SERVER['REDIS_HOST']) ? $_SERVER['REDIS_HOST'] : '127.0.0.1')); + Redis::setDefaultOptions(['host' => isset($_SERVER['REDIS_HOST']) ? $_SERVER['REDIS_HOST'] : '127.0.0.1']); $adapter = new Prometheus\Storage\Redis(); } elseif ($adapter === 'apc') { $adapter = new Prometheus\Storage\APC(); diff --git a/phpunit.xml b/phpunit.xml index c09d661..ab027cb 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -1,7 +1,21 @@ - - - - ./tests/Test/Prometheus - - + + + + + ./tests/Test/Prometheus + + + + + ./src/Prometheus + + diff --git a/src/Prometheus/Collector.php b/src/Prometheus/Collector.php index bc85277..26e8275 100644 --- a/src/Prometheus/Collector.php +++ b/src/Prometheus/Collector.php @@ -1,4 +1,6 @@ storageAdapter = $storageAdapter; $metricName = ($namespace ? $namespace . '_' : '') . $name; @@ -60,7 +62,7 @@ public abstract function getType(); /** * @return string */ - public function getName() + public function getName(): string { return $this->name; } @@ -68,7 +70,7 @@ public function getName() /** * @return array */ - public function getLabelNames() + public function getLabelNames(): array { return $this->labels; } @@ -76,7 +78,7 @@ public function getLabelNames() /** * @return string */ - public function getHelp() + public function getHelp(): string { return $this->help; } @@ -84,7 +86,7 @@ public function getHelp() /** * @return string */ - public function getKey() + public function getKey(): string { return sha1($this->getName() . serialize($this->getLabelNames())); } @@ -92,7 +94,7 @@ public function getKey() /** * @param $labels */ - protected function assertLabelsAreDefinedCorrectly($labels) + protected function assertLabelsAreDefinedCorrectly($labels): void { if (count($labels) != count($this->labels)) { throw new InvalidArgumentException(sprintf('Labels are not defined correctly: ', print_r($labels, true))); diff --git a/src/Prometheus/CollectorRegistry.php b/src/Prometheus/CollectorRegistry.php index 28a707a..739e9c4 100644 --- a/src/Prometheus/CollectorRegistry.php +++ b/src/Prometheus/CollectorRegistry.php @@ -1,4 +1,6 @@ storageAdapter->collect(); } @@ -69,7 +71,7 @@ public function getMetricFamilySamples() * @return Gauge * @throws MetricsRegistrationException */ - public function registerGauge($namespace, $name, $help, $labels = array()) + public function registerGauge($namespace, $name, $help, $labels = []): Gauge { $metricIdentifier = self::metricIdentifier($namespace, $name); if (isset($this->gauges[$metricIdentifier])) { @@ -91,7 +93,7 @@ public function registerGauge($namespace, $name, $help, $labels = array()) * @return Gauge * @throws MetricNotFoundException */ - public function getGauge($namespace, $name) + public function getGauge($namespace, $name): Gauge { $metricIdentifier = self::metricIdentifier($namespace, $name); if (!isset($this->gauges[$metricIdentifier])) { @@ -108,7 +110,7 @@ public function getGauge($namespace, $name) * @return Gauge * @throws MetricsRegistrationException */ - public function getOrRegisterGauge($namespace, $name, $help, $labels = array()) + public function getOrRegisterGauge($namespace, $name, $help, $labels = []): Gauge { try { $gauge = $this->getGauge($namespace, $name); @@ -126,7 +128,7 @@ public function getOrRegisterGauge($namespace, $name, $help, $labels = array()) * @return Counter * @throws MetricsRegistrationException */ - public function registerCounter($namespace, $name, $help, $labels = array()) + public function registerCounter($namespace, $name, $help, $labels = []): Counter { $metricIdentifier = self::metricIdentifier($namespace, $name); if (isset($this->counters[$metricIdentifier])) { @@ -148,7 +150,7 @@ public function registerCounter($namespace, $name, $help, $labels = array()) * @return Counter * @throws MetricNotFoundException */ - public function getCounter($namespace, $name) + public function getCounter($namespace, $name): Counter { $metricIdentifier = self::metricIdentifier($namespace, $name); if (!isset($this->counters[$metricIdentifier])) { @@ -165,7 +167,7 @@ public function getCounter($namespace, $name) * @return Counter * @throws MetricsRegistrationException */ - public function getOrRegisterCounter($namespace, $name, $help, $labels = array()) + public function getOrRegisterCounter($namespace, $name, $help, $labels = []): Counter { try { $counter = $this->getCounter($namespace, $name); @@ -184,7 +186,7 @@ public function getOrRegisterCounter($namespace, $name, $help, $labels = array() * @return Histogram * @throws MetricsRegistrationException */ - public function registerHistogram($namespace, $name, $help, $labels = array(), $buckets = null) + public function registerHistogram($namespace, $name, $help, $labels = [], $buckets = null): Histogram { $metricIdentifier = self::metricIdentifier($namespace, $name); if (isset($this->histograms[$metricIdentifier])) { @@ -207,7 +209,7 @@ public function registerHistogram($namespace, $name, $help, $labels = array(), $ * @return Histogram * @throws MetricNotFoundException */ - public function getHistogram($namespace, $name) + public function getHistogram($namespace, $name): Histogram { $metricIdentifier = self::metricIdentifier($namespace, $name); if (!isset($this->histograms[$metricIdentifier])) { @@ -225,7 +227,7 @@ public function getHistogram($namespace, $name) * @return Histogram * @throws MetricsRegistrationException */ - public function getOrRegisterHistogram($namespace, $name, $help, $labels = array(), $buckets = null) + public function getOrRegisterHistogram($namespace, $name, $help, $labels = [], $buckets = null): Histogram { try { $histogram = $this->getHistogram($namespace, $name); @@ -240,7 +242,7 @@ public function getOrRegisterHistogram($namespace, $name, $help, $labels = array * @param $name * @return string */ - private static function metricIdentifier($namespace, $name) + private static function metricIdentifier($namespace, $name): string { return $namespace . ":" . $name; } diff --git a/src/Prometheus/Counter.php b/src/Prometheus/Counter.php index e580ff6..ae8e726 100644 --- a/src/Prometheus/Counter.php +++ b/src/Prometheus/Counter.php @@ -1,4 +1,6 @@ incBy(1, $labels); } @@ -27,20 +29,20 @@ public function inc(array $labels = array()) * @param int $count e.g. 2 * @param array $labels e.g. ['status', 'opcode'] */ - public function incBy($count, array $labels = array()) + public function incBy($count, array $labels = []): void { $this->assertLabelsAreDefinedCorrectly($labels); $this->storageAdapter->updateCounter( - array( + [ 'name' => $this->getName(), 'help' => $this->getHelp(), 'type' => $this->getType(), 'labelNames' => $this->getLabelNames(), 'labelValues' => $labels, 'value' => $count, - 'command' => Adapter::COMMAND_INCREMENT_INTEGER - ) + 'command' => Adapter::COMMAND_INCREMENT_INTEGER, + ] ); } } diff --git a/src/Prometheus/Exception/MetricNotFoundException.php b/src/Prometheus/Exception/MetricNotFoundException.php index f754777..bb3d51c 100644 --- a/src/Prometheus/Exception/MetricNotFoundException.php +++ b/src/Prometheus/Exception/MetricNotFoundException.php @@ -1,4 +1,5 @@ assertLabelsAreDefinedCorrectly($labels); $this->storageAdapter->updateGauge( - array( + [ 'name' => $this->getName(), 'help' => $this->getHelp(), 'type' => $this->getType(), 'labelNames' => $this->getLabelNames(), 'labelValues' => $labels, 'value' => $value, - 'command' => Adapter::COMMAND_SET - ) + 'command' => Adapter::COMMAND_SET, + ] ); } /** * @return string */ - public function getType() + public function getType(): string { return self::TYPE; } @@ -40,7 +41,7 @@ public function getType() /** * @param array $labels */ - public function inc($labels = array()) + public function inc($labels = []): void { $this->incBy(1, $labels); } @@ -49,27 +50,27 @@ public function inc($labels = array()) * @param $value * @param array $labels */ - public function incBy($value, $labels = array()) + public function incBy($value, array $labels = []): void { $this->assertLabelsAreDefinedCorrectly($labels); $this->storageAdapter->updateGauge( - array( + [ 'name' => $this->getName(), 'help' => $this->getHelp(), 'type' => $this->getType(), 'labelNames' => $this->getLabelNames(), 'labelValues' => $labels, 'value' => $value, - 'command' => Adapter::COMMAND_INCREMENT_FLOAT - ) + 'command' => Adapter::COMMAND_INCREMENT_FLOAT, + ] ); } /** * @param array $labels */ - public function dec($labels = array()) + public function dec($labels = []): void { $this->decBy(1, $labels); } @@ -78,7 +79,7 @@ public function dec($labels = array()) * @param $value * @param array $labels */ - public function decBy($value, $labels = array()) + public function decBy($value, $labels = []): void { $this->incBy(-$value, $labels); } diff --git a/src/Prometheus/Histogram.php b/src/Prometheus/Histogram.php index a8e9107..f36cf0f 100644 --- a/src/Prometheus/Histogram.php +++ b/src/Prometheus/Histogram.php @@ -1,4 +1,5 @@ assertLabelsAreDefinedCorrectly($labels); $this->storageAdapter->updateHistogram( - array( + [ 'value' => $value, 'name' => $this->getName(), 'help' => $this->getHelp(), @@ -78,14 +79,14 @@ public function observe($value, $labels = array()) 'labelNames' => $this->getLabelNames(), 'labelValues' => $labels, 'buckets' => $this->buckets, - ) + ] ); } /** * @return string */ - public function getType() + public function getType(): string { return self::TYPE; } diff --git a/src/Prometheus/MetricFamilySamples.php b/src/Prometheus/MetricFamilySamples.php index a3c79c1..f600540 100644 --- a/src/Prometheus/MetricFamilySamples.php +++ b/src/Prometheus/MetricFamilySamples.php @@ -1,4 +1,5 @@ name; } @@ -54,7 +55,7 @@ public function getName() /** * @return string */ - public function getType() + public function getType(): string { return $this->type; } @@ -62,7 +63,7 @@ public function getType() /** * @return string */ - public function getHelp() + public function getHelp(): string { return $this->help; } @@ -70,7 +71,7 @@ public function getHelp() /** * @return Sample[] */ - public function getSamples() + public function getSamples(): array { return $this->samples; } @@ -78,7 +79,7 @@ public function getSamples() /** * @return array */ - public function getLabelNames() + public function getLabelNames(): array { return $this->labelNames; } @@ -86,7 +87,7 @@ public function getLabelNames() /** * @return bool */ - public function hasLabelNames() + public function hasLabelNames(): bool { return !empty($this->labelNames); } diff --git a/src/Prometheus/PushGateway.php b/src/Prometheus/PushGateway.php index 6cfc421..e8792af 100644 --- a/src/Prometheus/PushGateway.php +++ b/src/Prometheus/PushGateway.php @@ -1,8 +1,10 @@ doRequest($collectorRegistry, $job, $groupingKey, 'put'); } @@ -40,9 +42,9 @@ public function push(CollectorRegistry $collectorRegistry, $job, $groupingKey = * @param CollectorRegistry $collectorRegistry * @param $job * @param $groupingKey - * @throws \GuzzleHttp\Exception\GuzzleException + * @throws GuzzleException */ - public function pushAdd(CollectorRegistry $collectorRegistry, $job, $groupingKey = null) + public function pushAdd(CollectorRegistry $collectorRegistry, string $job, array $groupingKey = null): void { $this->doRequest($collectorRegistry, $job, $groupingKey, 'post'); } @@ -50,11 +52,11 @@ public function pushAdd(CollectorRegistry $collectorRegistry, $job, $groupingKey /** * Deletes metrics from the Push Gateway. * Uses HTTP POST. - * @param $job - * @param $groupingKey - * @throws \GuzzleHttp\Exception\GuzzleException + * @param string $job + * @param array $groupingKey + * @throws GuzzleException */ - public function delete($job, $groupingKey = null) + public function delete(string $job, array $groupingKey = null): void { $this->doRequest(null, $job, $groupingKey, 'delete'); } @@ -62,11 +64,11 @@ public function delete($job, $groupingKey = null) /** * @param CollectorRegistry $collectorRegistry * @param string $job - * @param string $groupingKey + * @param array $groupingKey * @param string $method - * @throws \GuzzleHttp\Exception\GuzzleException + * @throws GuzzleException */ - private function doRequest(CollectorRegistry $collectorRegistry, $job, $groupingKey, $method) + private function doRequest(CollectorRegistry $collectorRegistry, string $job, array $groupingKey, $method): void { $url = "http://" . $this->address . "/metrics/job/" . $job; if (!empty($groupingKey)) { @@ -75,13 +77,13 @@ private function doRequest(CollectorRegistry $collectorRegistry, $job, $grouping } } $client = new Client(); - $requestOptions = array( - 'headers' => array( - 'Content-Type' => RenderTextFormat::MIME_TYPE - ), + $requestOptions = [ + 'headers' => [ + 'Content-Type' => RenderTextFormat::MIME_TYPE, + ], 'connect_timeout' => 10, 'timeout' => 20, - ); + ]; if ($method != 'delete') { $renderer = new RenderTextFormat(); $requestOptions['body'] = $renderer->render($collectorRegistry->getMetricFamilySamples()); @@ -89,7 +91,8 @@ private function doRequest(CollectorRegistry $collectorRegistry, $job, $grouping $response = $client->request($method, $url, $requestOptions); $statusCode = $response->getStatusCode(); if ($statusCode != 202) { - $msg = "Unexpected status code " . $statusCode . " received from push gateway " . $this->address . ": " . $response->getBody(); + $msg = "Unexpected status code " . $statusCode . " received from push gateway " . $this->address . ": " . $response->getBody( + ); throw new RuntimeException($msg); } } diff --git a/src/Prometheus/RenderTextFormat.php b/src/Prometheus/RenderTextFormat.php index 1af77d6..c0b3e70 100644 --- a/src/Prometheus/RenderTextFormat.php +++ b/src/Prometheus/RenderTextFormat.php @@ -1,4 +1,5 @@ getName(), $b->getName()); - }); + usort( + $metrics, + function (MetricFamilySamples $a, MetricFamilySamples $b) { + return strcmp($a->getName(), $b->getName()); + } + ); - $lines = array(); + $lines = []; foreach ($metrics as $metric) { $lines[] = "# HELP " . $metric->getName() . " {$metric->getHelp()}"; @@ -34,9 +37,9 @@ public function render(array $metrics) * @param Sample $sample * @return string */ - private function renderSample(MetricFamilySamples $metric, Sample $sample) + private function renderSample(MetricFamilySamples $metric, Sample $sample): string { - $escapedLabels = array(); + $escapedLabels = []; $labelNames = $metric->getLabelNames(); if ($metric->hasLabelNames() || $sample->hasLabelNames()) { @@ -51,9 +54,9 @@ private function renderSample(MetricFamilySamples $metric, Sample $sample) /** * @param $v - * @return mixed + * @return string */ - private function escapeLabelValue($v) + private function escapeLabelValue($v): string { $v = str_replace("\\", "\\\\", $v); $v = str_replace("\n", "\\n", $v); diff --git a/src/Prometheus/Sample.php b/src/Prometheus/Sample.php index a88a027..3ed624b 100644 --- a/src/Prometheus/Sample.php +++ b/src/Prometheus/Sample.php @@ -1,4 +1,5 @@ name; } @@ -47,7 +48,7 @@ public function getName() /** * @return array */ - public function getLabelNames() + public function getLabelNames(): array { return (array)$this->labelNames; } @@ -55,7 +56,7 @@ public function getLabelNames() /** * @return array */ - public function getLabelValues() + public function getLabelValues(): array { return (array)$this->labelValues; } @@ -63,15 +64,15 @@ public function getLabelValues() /** * @return int|double */ - public function getValue() + public function getValue(): string { - return $this->value; + return (string) $this->value; } /** * @return bool */ - public function hasLabelNames() + public function hasLabelNames(): bool { return !empty($this->labelNames); } diff --git a/src/Prometheus/Storage/APC.php b/src/Prometheus/Storage/APC.php index 4c03b9b..e7a8864 100644 --- a/src/Prometheus/Storage/APC.php +++ b/src/Prometheus/Storage/APC.php @@ -1,9 +1,8 @@ collectHistograms(); $metrics = array_merge($metrics, $this->collectGauges()); @@ -26,7 +25,7 @@ public function collect() /** * @param array $data */ - public function updateHistogram(array $data) + public function updateHistogram(array $data): void { // Initialize the sum $sumKey = $this->histogramBucketValueKey($data, 'sum'); @@ -62,7 +61,7 @@ public function updateHistogram(array $data) /** * @param array $data */ - public function updateGauge(array $data) + public function updateGauge(array $data): void { $valueKey = $this->valueKey($data); if ($data['command'] == Adapter::COMMAND_SET) { @@ -85,7 +84,7 @@ public function updateGauge(array $data) /** * @param array $data */ - public function updateCounter(array $data) + public function updateCounter(array $data): void { $new = apcu_add($this->valueKey($data), 0); if ($new) { @@ -94,56 +93,65 @@ public function updateCounter(array $data) apcu_inc($this->valueKey($data), $data['value']); } - public function flushAPC() + /** + * @return void + */ + public function flushAPC(): void { - apcu_clear_cache(); + apcu_clear_cache(); } /** * @param array $data * @return string */ - private function metaKey(array $data) + private function metaKey(array $data): string { - return implode(':', array(self::PROMETHEUS_PREFIX, $data['type'], $data['name'], 'meta')); + return implode(':', [self::PROMETHEUS_PREFIX, $data['type'], $data['name'], 'meta']); } /** * @param array $data * @return string */ - private function valueKey(array $data) + private function valueKey(array $data): string { - return implode(':', array( - self::PROMETHEUS_PREFIX, - $data['type'], - $data['name'], - $this->encodeLabelValues($data['labelValues']), - 'value' - )); + return implode( + ':', + [ + self::PROMETHEUS_PREFIX, + $data['type'], + $data['name'], + $this->encodeLabelValues($data['labelValues']), + 'value', + ] + ); } /** * @param array $data * @return string */ - private function histogramBucketValueKey(array $data, $bucket) + private function histogramBucketValueKey(array $data, $bucket): string { - return implode(':', array( - self::PROMETHEUS_PREFIX, - $data['type'], - $data['name'], - $this->encodeLabelValues($data['labelValues']), - $bucket, - 'value' - )); + return implode( + ':', + [ + self::PROMETHEUS_PREFIX, + $data['type'], + $data['name'], + $this->encodeLabelValues($data['labelValues']), + $bucket, + 'value', + ] + ); } /** * @param array $data * @return array */ - private function metaData(array $data) + private function metaData(array $data): array { $metricsMetaData = $data; unset($metricsMetaData['value']); @@ -155,26 +163,26 @@ private function metaData(array $data) /** * @return array */ - private function collectCounters() + private function collectCounters(): array { - $counters = array(); + $counters = []; foreach (new APCUIterator('/^prom:counter:.*:meta/') as $counter) { $metaData = json_decode($counter['value'], true); - $data = array( + $data = [ 'name' => $metaData['name'], 'help' => $metaData['help'], 'type' => $metaData['type'], 'labelNames' => $metaData['labelNames'], - ); + ]; foreach (new APCUIterator('/^prom:counter:' . $metaData['name'] . ':.*:value/') as $value) { $parts = explode(':', $value['key']); $labelValues = $parts[3]; - $data['samples'][] = array( + $data['samples'][] = [ 'name' => $metaData['name'], - 'labelNames' => array(), + 'labelNames' => [], 'labelValues' => $this->decodeLabelValues($labelValues), - 'value' => $value['value'] - ); + 'value' => $value['value'], + ]; } $this->sortSamples($data['samples']); $counters[] = new MetricFamilySamples($data); @@ -185,26 +193,26 @@ private function collectCounters() /** * @return array */ - private function collectGauges() + private function collectGauges(): array { - $gauges = array(); + $gauges = []; foreach (new APCUIterator('/^prom:gauge:.*:meta/') as $gauge) { $metaData = json_decode($gauge['value'], true); - $data = array( + $data = [ 'name' => $metaData['name'], 'help' => $metaData['help'], 'type' => $metaData['type'], 'labelNames' => $metaData['labelNames'], - ); + ]; foreach (new APCUIterator('/^prom:gauge:' . $metaData['name'] . ':.*:value/') as $value) { $parts = explode(':', $value['key']); $labelValues = $parts[3]; - $data['samples'][] = array( + $data['samples'][] = [ 'name' => $metaData['name'], - 'labelNames' => array(), + 'labelNames' => [], 'labelValues' => $this->decodeLabelValues($labelValues), - 'value' => $this->fromInteger($value['value']) - ); + 'value' => $this->fromInteger($value['value']), + ]; } $this->sortSamples($data['samples']); @@ -216,23 +224,23 @@ private function collectGauges() /** * @return array */ - private function collectHistograms() + private function collectHistograms(): array { - $histograms = array(); + $histograms = []; foreach (new APCUIterator('/^prom:histogram:.*:meta/') as $histogram) { $metaData = json_decode($histogram['value'], true); - $data = array( + $data = [ 'name' => $metaData['name'], 'help' => $metaData['help'], 'type' => $metaData['type'], 'labelNames' => $metaData['labelNames'], - 'buckets' => $metaData['buckets'] - ); + 'buckets' => $metaData['buckets'], + ]; // Add the Inf bucket so we can compute it later on $data['buckets'][] = '+Inf'; - $histogramBuckets = array(); + $histogramBuckets = []; foreach (new APCUIterator('/^prom:histogram:' . $metaData['name'] . ':.*:value/') as $value) { $parts = explode(':', $value['key']); $labelValues = $parts[3]; @@ -248,40 +256,40 @@ private function collectHistograms() $acc = 0; $decodedLabelValues = $this->decodeLabelValues($labelValues); foreach ($data['buckets'] as $bucket) { - $bucket = (string) $bucket; + $bucket = (string)$bucket; if (!isset($histogramBuckets[$labelValues][$bucket])) { - $data['samples'][] = array( + $data['samples'][] = [ 'name' => $metaData['name'] . '_bucket', - 'labelNames' => array('le'), - 'labelValues' => array_merge($decodedLabelValues, array($bucket)), - 'value' => $acc - ); + 'labelNames' => ['le'], + 'labelValues' => array_merge($decodedLabelValues, [$bucket]), + 'value' => $acc, + ]; } else { $acc += $histogramBuckets[$labelValues][$bucket]; - $data['samples'][] = array( + $data['samples'][] = [ 'name' => $metaData['name'] . '_' . 'bucket', - 'labelNames' => array('le'), - 'labelValues' => array_merge($decodedLabelValues, array($bucket)), - 'value' => $acc - ); + 'labelNames' => ['le'], + 'labelValues' => array_merge($decodedLabelValues, [$bucket]), + 'value' => $acc, + ]; } } // Add the count - $data['samples'][] = array( + $data['samples'][] = [ 'name' => $metaData['name'] . '_count', - 'labelNames' => array(), + 'labelNames' => [], 'labelValues' => $decodedLabelValues, - 'value' => $acc - ); + 'value' => $acc, + ]; // Add the sum - $data['samples'][] = array( + $data['samples'][] = [ 'name' => $metaData['name'] . '_sum', - 'labelNames' => array(), + 'labelNames' => [], 'labelValues' => $decodedLabelValues, - 'value' => $this->fromInteger($histogramBuckets[$labelValues]['sum']) - ); + 'value' => $this->fromInteger($histogramBuckets[$labelValues]['sum']), + ]; } $histograms[] = new MetricFamilySamples($data); @@ -293,16 +301,16 @@ private function collectHistograms() * @param mixed $val * @return int */ - private function toInteger($val) + private function toInteger($val): int { return unpack('Q', pack('d', $val))[1]; } /** * @param mixed $val - * @return int + * @return float */ - private function fromInteger($val) + private function fromInteger($val): float { return unpack('d', pack('Q', $val))[1]; } @@ -310,11 +318,14 @@ private function fromInteger($val) /** * @param array $samples */ - private function sortSamples(array &$samples) + private function sortSamples(array &$samples): void { - usort($samples, function($a, $b){ - return strcmp(implode("", $a['labelValues']), implode("", $b['labelValues'])); - }); + usort( + $samples, + function ($a, $b) { + return strcmp(implode("", $a['labelValues']), implode("", $b['labelValues'])); + } + ); } /** @@ -322,7 +333,7 @@ private function sortSamples(array &$samples) * @return string * @throws RuntimeException */ - private function encodeLabelValues(array $values) + private function encodeLabelValues(array $values): string { $json = json_encode($values); if (false === $json) { @@ -336,7 +347,7 @@ private function encodeLabelValues(array $values) * @return array * @throws RuntimeException */ - private function decodeLabelValues($values) + private function decodeLabelValues($values): array { $json = base64_decode($values, true); if (false === $json) { diff --git a/src/Prometheus/Storage/Adapter.php b/src/Prometheus/Storage/Adapter.php index e280f13..03f258e 100644 --- a/src/Prometheus/Storage/Adapter.php +++ b/src/Prometheus/Storage/Adapter.php @@ -1,9 +1,9 @@ internalCollect($this->counters); $metrics = array_merge($metrics, $this->internalCollect($this->gauges)); @@ -24,7 +24,7 @@ public function collect() return $metrics; } - public function flushMemory() + public function flushMemory(): void { $this->counters = []; $this->gauges = []; @@ -34,7 +34,7 @@ public function flushMemory() /** * @return array */ - private function collectHistograms() + private function collectHistograms(): array { $histograms = []; foreach ($this->histograms as $histogram) { @@ -44,7 +44,7 @@ private function collectHistograms() 'help' => $metaData['help'], 'type' => $metaData['type'], 'labelNames' => $metaData['labelNames'], - 'buckets' => $metaData['buckets'] + 'buckets' => $metaData['buckets'], ]; // Add the Inf bucket so we can compute it later on @@ -72,7 +72,7 @@ private function collectHistograms() 'name' => $metaData['name'] . '_bucket', 'labelNames' => ['le'], 'labelValues' => array_merge($decodedLabelValues, [$bucket]), - 'value' => $acc + 'value' => $acc, ]; } else { $acc += $histogramBuckets[$labelValues][$bucket]; @@ -80,7 +80,7 @@ private function collectHistograms() 'name' => $metaData['name'] . '_' . 'bucket', 'labelNames' => ['le'], 'labelValues' => array_merge($decodedLabelValues, [$bucket]), - 'value' => $acc + 'value' => $acc, ]; } } @@ -90,7 +90,7 @@ private function collectHistograms() 'name' => $metaData['name'] . '_count', 'labelNames' => [], 'labelValues' => $decodedLabelValues, - 'value' => $acc + 'value' => $acc, ]; // Add the sum @@ -98,7 +98,7 @@ private function collectHistograms() 'name' => $metaData['name'] . '_sum', 'labelNames' => [], 'labelValues' => $decodedLabelValues, - 'value' => $histogramBuckets[$labelValues]['sum'] + 'value' => $histogramBuckets[$labelValues]['sum'], ]; } @@ -111,7 +111,7 @@ private function collectHistograms() * @param array $metrics * @return array */ - private function internalCollect(array $metrics) + private function internalCollect(array $metrics): array { $result = []; foreach ($metrics as $metric) { @@ -129,7 +129,7 @@ private function internalCollect(array $metrics) 'name' => $metaData['name'], 'labelNames' => [], 'labelValues' => $this->decodeLabelValues($labelValues), - 'value' => $value + 'value' => $value, ]; } $this->sortSamples($data['samples']); @@ -140,15 +140,16 @@ private function internalCollect(array $metrics) /** * @param array $data + * @return void */ - public function updateHistogram(array $data) + public function updateHistogram(array $data): void { // Initialize the sum $metaKey = $this->metaKey($data); if (array_key_exists($metaKey, $this->histograms) === false) { $this->histograms[$metaKey] = [ 'meta' => $this->metaData($data), - 'samples' => [] + 'samples' => [], ]; } $sumKey = $this->histogramBucketValueKey($data, 'sum'); @@ -177,14 +178,14 @@ public function updateHistogram(array $data) /** * @param array $data */ - public function updateGauge(array $data) + public function updateGauge(array $data): void { $metaKey = $this->metaKey($data); $valueKey = $this->valueKey($data); if (array_key_exists($metaKey, $this->gauges) === false) { $this->gauges[$metaKey] = [ 'meta' => $this->metaData($data), - 'samples' => [] + 'samples' => [], ]; } if (array_key_exists($valueKey, $this->gauges[$metaKey]['samples']) === false) { @@ -200,14 +201,14 @@ public function updateGauge(array $data) /** * @param array $data */ - public function updateCounter(array $data) + public function updateCounter(array $data): void { $metaKey = $this->metaKey($data); $valueKey = $this->valueKey($data); if (array_key_exists($metaKey, $this->counters) === false) { $this->counters[$metaKey] = [ 'meta' => $this->metaData($data), - 'samples' => [] + 'samples' => [], ]; } if (array_key_exists($valueKey, $this->counters[$metaKey]['samples']) === false) { @@ -225,14 +226,17 @@ public function updateCounter(array $data) * @param string $bucket * @return string */ - private function histogramBucketValueKey(array $data, $bucket) + private function histogramBucketValueKey(array $data, $bucket): string { - return implode(':', [ - $data['type'], - $data['name'], - $this->encodeLabelValues($data['labelValues']), - $bucket - ]); + return implode( + ':', + [ + $data['type'], + $data['name'], + $this->encodeLabelValues($data['labelValues']), + $bucket, + ] + ); } /** @@ -240,7 +244,7 @@ private function histogramBucketValueKey(array $data, $bucket) * * @return string */ - private function metaKey(array $data) + private function metaKey(array $data): string { return implode(':', [$data['type'], $data['name'], 'meta']); } @@ -250,10 +254,12 @@ private function metaKey(array $data) * * @return string */ - private function valueKey(array $data) + private function valueKey(array $data): string { - return implode(':', - [$data['type'], $data['name'], $this->encodeLabelValues($data['labelValues']), 'value']); + return implode( + ':', + [$data['type'], $data['name'], $this->encodeLabelValues($data['labelValues']), 'value'] + ); } /** @@ -261,7 +267,7 @@ private function valueKey(array $data) * * @return array */ - private function metaData(array $data) + private function metaData(array $data): array { $metricsMetaData = $data; unset($metricsMetaData['value']); @@ -273,11 +279,14 @@ private function metaData(array $data) /** * @param array $samples */ - private function sortSamples(array &$samples) + private function sortSamples(array &$samples): void { - usort($samples, function ($a, $b) { - return strcmp(implode("", $a['labelValues']), implode("", $b['labelValues'])); - }); + usort( + $samples, + function ($a, $b) { + return strcmp(implode("", $a['labelValues']), implode("", $b['labelValues'])); + } + ); } /** @@ -285,7 +294,7 @@ private function sortSamples(array &$samples) * @return string * @throws RuntimeException */ - private function encodeLabelValues(array $values) + private function encodeLabelValues(array $values): string { $json = json_encode($values); if (false === $json) { @@ -299,7 +308,7 @@ private function encodeLabelValues(array $values) * @return array * @throws RuntimeException */ - private function decodeLabelValues($values) + private function decodeLabelValues($values): array { $json = base64_decode($values, true); if (false === $json) { diff --git a/src/Prometheus/Storage/Redis.php b/src/Prometheus/Storage/Redis.php index 5babba0..1d46d88 100644 --- a/src/Prometheus/Storage/Redis.php +++ b/src/Prometheus/Storage/Redis.php @@ -1,4 +1,6 @@ openConnection(); $this->redis->flushAll(); @@ -93,7 +95,7 @@ public function flushRedis() * @return MetricFamilySamples[] * @throws StorageException */ - public function collect() + public function collect(): array { $this->openConnection(); $metrics = $this->collectHistograms(); @@ -110,25 +112,40 @@ function (array $metric) { /** * @throws StorageException */ - private function openConnection() + private function openConnection(): void + { + $connectionStatus = $this->connectToServer(); + if ($connectionStatus === false) { + throw new StorageException("Can't connect to Redis server", 0); + } + + if ($this->options['password']) { + $this->redis->auth($this->options['password']); + } + if (isset($this->options['database'])) { + $this->redis->select($this->options['database']); + } + + $this->redis->setOption(\Redis::OPT_READ_TIMEOUT, $this->options['read_timeout']); + } + + /** + * @return bool + */ + private function connectToServer(): bool { try { if ($this->options['persistent_connections']) { - @$this->redis->pconnect($this->options['host'], $this->options['port'], $this->options['timeout']); - } else { - @$this->redis->connect($this->options['host'], $this->options['port'], $this->options['timeout']); - } - if ($this->options['password']) { - $this->redis->auth($this->options['password']); - } - if (isset($this->options['database'])) { - $this->redis->select($this->options['database']); + return $this->redis->pconnect( + $this->options['host'], + $this->options['port'], + $this->options['timeout'] + ); } - $this->redis->setOption(\Redis::OPT_READ_TIMEOUT, $this->options['read_timeout']); - - } catch (RedisException $e) { - throw new StorageException("Can't connect to Redis server", 0, $e); + return $this->redis->connect($this->options['host'], $this->options['port'], $this->options['timeout']); + } catch (\RedisException $e) { + return false; } } @@ -136,7 +153,7 @@ private function openConnection() * @param array $data * @throws StorageException */ - public function updateHistogram(array $data) + public function updateHistogram(array $data): void { $this->openConnection(); $bucketToIncrease = '+Inf'; @@ -149,7 +166,8 @@ public function updateHistogram(array $data) $metaData = $data; unset($metaData['value']); unset($metaData['labelValues']); - $this->redis->eval(<<redis->eval( + <<toMetricKey($data), - json_encode(array('b' => 'sum', 'labelValues' => $data['labelValues'])), - json_encode(array('b' => $bucketToIncrease, 'labelValues' => $data['labelValues'])), + json_encode(['b' => 'sum', 'labelValues' => $data['labelValues']]), + json_encode(['b' => $bucketToIncrease, 'labelValues' => $data['labelValues']]), self::$prefix . Histogram::TYPE . self::PROMETHEUS_METRIC_KEYS_SUFFIX, $data['value'], json_encode($metaData), - ), + ], 4 ); } @@ -174,14 +192,15 @@ public function updateHistogram(array $data) * @param array $data * @throws StorageException */ - public function updateGauge(array $data) + public function updateGauge(array $data): void { $this->openConnection(); $metaData = $data; unset($metaData['value']); unset($metaData['labelValues']); unset($metaData['command']); - $this->redis->eval(<<redis->eval( + <<toMetricKey($data), $this->getRedisCommand($data['command']), self::$prefix . Gauge::TYPE . self::PROMETHEUS_METRIC_KEYS_SUFFIX, json_encode($data['labelValues']), $data['value'], json_encode($metaData), - ), + ], 4 ); } /** * @param array $data - * @return mixed * @throws StorageException */ - public function updateCounter(array $data) + public function updateCounter(array $data): void { $this->openConnection(); $metaData = $data; unset($metaData['value']); unset($metaData['labelValues']); unset($metaData['command']); - $result = $this->redis->eval(<<redis->eval( + <<toMetricKey($data), $this->getRedisCommand($data['command']), self::$prefix . Counter::TYPE . self::PROMETHEUS_METRIC_KEYS_SUFFIX, json_encode($data['labelValues']), $data['value'], json_encode($metaData), - ), + ], 4 ); - return $result; } /** * @return array */ - private function collectHistograms() + private function collectHistograms(): array { $keys = $this->redis->sMembers(self::$prefix . Histogram::TYPE . self::PROMETHEUS_METRIC_KEYS_SUFFIX); sort($keys); - $histograms = array(); + $histograms = []; foreach ($keys as $key) { $raw = $this->redis->hGetAll($key); $histogram = json_decode($raw['__meta'], true); unset($raw['__meta']); - $histogram['samples'] = array(); + $histogram['samples'] = []; // Add the Inf bucket so we can compute it later on $histogram['buckets'][] = '+Inf'; - $allLabelValues = array(); + $allLabelValues = []; foreach (array_keys($raw) as $k) { $d = json_decode($k, true); if ($d['b'] == 'sum') { @@ -280,40 +298,40 @@ private function collectHistograms() // the previous one. $acc = 0; foreach ($histogram['buckets'] as $bucket) { - $bucketKey = json_encode(array('b' => $bucket, 'labelValues' => $labelValues)); + $bucketKey = json_encode(['b' => $bucket, 'labelValues' => $labelValues]); if (!isset($raw[$bucketKey])) { - $histogram['samples'][] = array( + $histogram['samples'][] = [ 'name' => $histogram['name'] . '_bucket', - 'labelNames' => array('le'), - 'labelValues' => array_merge($labelValues, array($bucket)), - 'value' => $acc - ); + 'labelNames' => ['le'], + 'labelValues' => array_merge($labelValues, [$bucket]), + 'value' => $acc, + ]; } else { $acc += $raw[$bucketKey]; - $histogram['samples'][] = array( + $histogram['samples'][] = [ 'name' => $histogram['name'] . '_bucket', - 'labelNames' => array('le'), - 'labelValues' => array_merge($labelValues, array($bucket)), - 'value' => $acc - ); + 'labelNames' => ['le'], + 'labelValues' => array_merge($labelValues, [$bucket]), + 'value' => $acc, + ]; } } // Add the count - $histogram['samples'][] = array( + $histogram['samples'][] = [ 'name' => $histogram['name'] . '_count', - 'labelNames' => array(), + 'labelNames' => [], 'labelValues' => $labelValues, - 'value' => $acc - ); + 'value' => $acc, + ]; // Add the sum - $histogram['samples'][] = array( + $histogram['samples'][] = [ 'name' => $histogram['name'] . '_sum', - 'labelNames' => array(), + 'labelNames' => [], 'labelValues' => $labelValues, - 'value' => $raw[json_encode(array('b' => 'sum', 'labelValues' => $labelValues))] - ); + 'value' => $raw[json_encode(['b' => 'sum', 'labelValues' => $labelValues])], + ]; } $histograms[] = $histogram; } @@ -323,27 +341,30 @@ private function collectHistograms() /** * @return array */ - private function collectGauges() + private function collectGauges(): array { $keys = $this->redis->sMembers(self::$prefix . Gauge::TYPE . self::PROMETHEUS_METRIC_KEYS_SUFFIX); sort($keys); - $gauges = array(); + $gauges = []; foreach ($keys as $key) { $raw = $this->redis->hGetAll($key); $gauge = json_decode($raw['__meta'], true); unset($raw['__meta']); - $gauge['samples'] = array(); + $gauge['samples'] = []; foreach ($raw as $k => $value) { - $gauge['samples'][] = array( + $gauge['samples'][] = [ 'name' => $gauge['name'], - 'labelNames' => array(), + 'labelNames' => [], 'labelValues' => json_decode($k, true), - 'value' => $value - ); + 'value' => $value, + ]; } - usort($gauge['samples'], function($a, $b){ - return strcmp(implode("", $a['labelValues']), implode("", $b['labelValues'])); - }); + usort( + $gauge['samples'], + function ($a, $b) { + return strcmp(implode("", $a['labelValues']), implode("", $b['labelValues'])); + } + ); $gauges[] = $gauge; } return $gauges; @@ -352,27 +373,30 @@ private function collectGauges() /** * @return array */ - private function collectCounters() + private function collectCounters(): array { $keys = $this->redis->sMembers(self::$prefix . Counter::TYPE . self::PROMETHEUS_METRIC_KEYS_SUFFIX); sort($keys); - $counters = array(); + $counters = []; foreach ($keys as $key) { $raw = $this->redis->hGetAll($key); $counter = json_decode($raw['__meta'], true); unset($raw['__meta']); - $counter['samples'] = array(); + $counter['samples'] = []; foreach ($raw as $k => $value) { - $counter['samples'][] = array( + $counter['samples'][] = [ 'name' => $counter['name'], - 'labelNames' => array(), + 'labelNames' => [], 'labelValues' => json_decode($k, true), - 'value' => $value - ); + 'value' => $value, + ]; } - usort($counter['samples'], function($a, $b){ - return strcmp(implode("", $a['labelValues']), implode("", $b['labelValues'])); - }); + usort( + $counter['samples'], + function ($a, $b) { + return strcmp(implode("", $a['labelValues']), implode("", $b['labelValues'])); + } + ); $counters[] = $counter; } return $counters; @@ -382,7 +406,7 @@ private function collectCounters() * @param string $cmd * @return string */ - private function getRedisCommand($cmd) + private function getRedisCommand($cmd): string { switch ($cmd) { case Adapter::COMMAND_INCREMENT_INTEGER: @@ -400,9 +424,8 @@ private function getRedisCommand($cmd) * @param array $data * @return string */ - private function toMetricKey(array $data) + private function toMetricKey(array $data): string { - return implode(':', array(self::$prefix, $data['type'], $data['name'])); + return implode(':', [self::$prefix, $data['type'], $data['name']]); } - } diff --git a/tests/Test/BlackBoxPushGatewayTest.php b/tests/Test/BlackBoxPushGatewayTest.php index 5453f43..47469be 100644 --- a/tests/Test/BlackBoxPushGatewayTest.php +++ b/tests/Test/BlackBoxPushGatewayTest.php @@ -23,7 +23,7 @@ public function pushGatewayShouldWork() $counter->incBy(6, ['blue']); $pushGateway = new PushGateway('pushgateway:9091'); - $pushGateway->push($registry, 'my_job', array('instance' => 'foo')); + $pushGateway->push($registry, 'my_job', ['instance' => 'foo']); $httpClient = new Client(); $metrics = $httpClient->get("http://pushgateway:9091/metrics")->getBody()->getContents(); @@ -34,7 +34,7 @@ public function pushGatewayShouldWork() $metrics ); - $pushGateway->delete('my_job', array('instance' => 'foo')); + $pushGateway->delete('my_job', ['instance' => 'foo']); $httpClient = new Client(); $metrics = $httpClient->get("http://pushgateway:9091/metrics")->getBody()->getContents(); diff --git a/tests/Test/Prometheus/AbstractCollectorRegistryTest.php b/tests/Test/Prometheus/AbstractCollectorRegistryTest.php index 766c993..82d9b64 100644 --- a/tests/Test/Prometheus/AbstractCollectorRegistryTest.php +++ b/tests/Test/Prometheus/AbstractCollectorRegistryTest.php @@ -6,8 +6,6 @@ use PHPUnit\Framework\TestCase; use Prometheus\CollectorRegistry; -use Prometheus\Exception\MetricNotFoundException; -use Prometheus\Exception\MetricsRegistrationException; use Prometheus\Histogram; use Prometheus\RenderTextFormat; use Prometheus\Storage\Adapter; @@ -38,17 +36,18 @@ public function itShouldSaveGauges() { $registry = new CollectorRegistry($this->adapter); - $g = $registry->registerGauge('test', 'some_metric', 'this is for testing', array('foo')); - $g->set(35, array('bbb')); - $g->set(35, array('ddd')); - $g->set(35, array('aaa')); - $g->set(35, array('ccc')); + $g = $registry->registerGauge('test', 'some_metric', 'this is for testing', ['foo']); + $g->set(35, ['bbb']); + $g->set(35, ['ddd']); + $g->set(35, ['aaa']); + $g->set(35, ['ccc']); $registry = new CollectorRegistry($this->adapter); $this->assertThat( $this->renderer->render($registry->getMetricFamilySamples()), - $this->equalTo(<<equalTo( + <<adapter); - $metric = $registry->registerCounter('test', 'some_metric', 'this is for testing', array('foo', 'bar')); - $metric->incBy(2, array('lalal', 'lululu')); - $registry->getCounter('test', 'some_metric', array('foo', 'bar'))->inc(array('lalal', 'lululu')); - $registry->getCounter('test', 'some_metric', array('foo', 'bar'))->inc(array('lalal', 'lvlvlv')); + $metric = $registry->registerCounter('test', 'some_metric', 'this is for testing', ['foo', 'bar']); + $metric->incBy(2, ['lalal', 'lululu']); + $registry->getCounter('test', 'some_metric', ['foo', 'bar'])->inc(['lalal', 'lululu']); + $registry->getCounter('test', 'some_metric', ['foo', 'bar'])->inc(['lalal', 'lvlvlv']); $registry = new CollectorRegistry($this->adapter); $this->assertThat( $this->renderer->render($registry->getMetricFamilySamples()), - $this->equalTo(<<equalTo( + <<adapter); - $metric = $registry->registerHistogram('test', 'some_metric', 'this is for testing', array('foo', 'bar'), array(0.1, 1, 5, 10)); - $metric->observe(2, array('lalal', 'lululu')); - $registry->getHistogram('test', 'some_metric', array('foo', 'bar'))->observe(7.1, array('lalal', 'lvlvlv')); - $registry->getHistogram('test', 'some_metric', array('foo', 'bar'))->observe(13, array('lalal', 'lululu')); - $registry->getHistogram('test', 'some_metric', array('foo', 'bar'))->observe(7.1, array('lalal', 'lululu')); - $registry->getHistogram('test', 'some_metric', array('foo', 'bar'))->observe(7.1, array('gnaaha', 'hihihi')); + $metric = $registry->registerHistogram( + 'test', + 'some_metric', + 'this is for testing', + ['foo', 'bar'], + [0.1, 1, 5, 10] + ); + $metric->observe(2, ['lalal', 'lululu']); + $registry->getHistogram('test', 'some_metric', ['foo', 'bar'])->observe(7.1, ['lalal', 'lvlvlv']); + $registry->getHistogram('test', 'some_metric', ['foo', 'bar'])->observe(13, ['lalal', 'lululu']); + $registry->getHistogram('test', 'some_metric', ['foo', 'bar'])->observe(7.1, ['lalal', 'lululu']); + $registry->getHistogram('test', 'some_metric', ['foo', 'bar'])->observe(7.1, ['gnaaha', 'hihihi']); $registry = new CollectorRegistry($this->adapter); $this->assertThat( $this->renderer->render($registry->getMetricFamilySamples()), - $this->equalTo(<<equalTo( + <<adapter); $this->assertThat( $this->renderer->render($registry->getMetricFamilySamples()), - $this->equalTo(<<equalTo( + <<adapter); + $registry = new CollectorRegistry($this->adapter); $registry ->registerCounter('', 'some_quick_counter', 'just a quick measurement') - ->inc(); + ->inc() + ; $this->assertThat( $this->renderer->render($registry->getMetricFamilySamples()), - $this->equalTo(<<equalTo( + <<adapter); + $registry = new CollectorRegistry($this->adapter); $registry->registerCounter('foo', 'metric', 'help'); $registry->registerCounter('foo', 'metric', 'help'); } @@ -211,9 +221,9 @@ public function itShouldForbidRegisteringTheSameCounterTwice() */ public function itShouldForbidRegisteringTheSameCounterWithDifferentLabels() { - $registry = new CollectorRegistry( $this->adapter); - $registry->registerCounter('foo', 'metric', 'help', array("foo", "bar")); - $registry->registerCounter('foo', 'metric', 'help', array("spam", "eggs")); + $registry = new CollectorRegistry($this->adapter); + $registry->registerCounter('foo', 'metric', 'help', ["foo", "bar"]); + $registry->registerCounter('foo', 'metric', 'help', ["spam", "eggs"]); } /** @@ -222,7 +232,7 @@ public function itShouldForbidRegisteringTheSameCounterWithDifferentLabels() */ public function itShouldForbidRegisteringTheSameHistogramTwice() { - $registry = new CollectorRegistry( $this->adapter); + $registry = new CollectorRegistry($this->adapter); $registry->registerHistogram('foo', 'metric', 'help'); $registry->registerHistogram('foo', 'metric', 'help'); } @@ -233,9 +243,9 @@ public function itShouldForbidRegisteringTheSameHistogramTwice() */ public function itShouldForbidRegisteringTheSameHistogramWithDifferentLabels() { - $registry = new CollectorRegistry( $this->adapter); - $registry->registerCounter('foo', 'metric', 'help', array("foo", "bar")); - $registry->registerCounter('foo', 'metric', 'help', array("spam", "eggs")); + $registry = new CollectorRegistry($this->adapter); + $registry->registerCounter('foo', 'metric', 'help', ["foo", "bar"]); + $registry->registerCounter('foo', 'metric', 'help', ["spam", "eggs"]); } /** @@ -244,7 +254,7 @@ public function itShouldForbidRegisteringTheSameHistogramWithDifferentLabels() */ public function itShouldForbidRegisteringTheSameGaugeTwice() { - $registry = new CollectorRegistry( $this->adapter); + $registry = new CollectorRegistry($this->adapter); $registry->registerGauge('foo', 'metric', 'help'); $registry->registerGauge('foo', 'metric', 'help'); } @@ -255,9 +265,9 @@ public function itShouldForbidRegisteringTheSameGaugeTwice() */ public function itShouldForbidRegisteringTheSameGaugeWithDifferentLabels() { - $registry = new CollectorRegistry( $this->adapter); - $registry->registerGauge('foo', 'metric', 'help', array("foo", "bar")); - $registry->registerGauge('foo', 'metric', 'help', array("spam", "eggs")); + $registry = new CollectorRegistry($this->adapter); + $registry->registerGauge('foo', 'metric', 'help', ["foo", "bar"]); + $registry->registerGauge('foo', 'metric', 'help', ["spam", "eggs"]); } /** @@ -266,7 +276,7 @@ public function itShouldForbidRegisteringTheSameGaugeWithDifferentLabels() */ public function itShouldThrowAnExceptionWhenGettingANonExistentMetric() { - $registry = new CollectorRegistry( $this->adapter); + $registry = new CollectorRegistry($this->adapter); $registry->getGauge("not_here", "go_away"); } diff --git a/tests/Test/Prometheus/AbstractCounterTest.php b/tests/Test/Prometheus/AbstractCounterTest.php index 3487c0d..d96b71e 100644 --- a/tests/Test/Prometheus/AbstractCounterTest.php +++ b/tests/Test/Prometheus/AbstractCounterTest.php @@ -25,36 +25,38 @@ public function setUp() $this->configureAdapter(); } + public abstract function configureAdapter(); + /** * @test */ public function itShouldIncreaseWithLabels() { - $gauge = new Counter($this->adapter, 'test', 'some_metric', 'this is for testing', array('foo', 'bar')); - $gauge->inc(array('lalal', 'lululu')); - $gauge->inc(array('lalal', 'lululu')); - $gauge->inc(array('lalal', 'lululu')); + $gauge = new Counter($this->adapter, 'test', 'some_metric', 'this is for testing', ['foo', 'bar']); + $gauge->inc(['lalal', 'lululu']); + $gauge->inc(['lalal', 'lululu']); + $gauge->inc(['lalal', 'lululu']); $this->assertThat( $this->adapter->collect(), $this->equalTo( - array( + [ new MetricFamilySamples( - array( + [ 'type' => Counter::TYPE, 'help' => 'this is for testing', 'name' => 'test_some_metric', - 'labelNames' => array('foo', 'bar'), - 'samples' => array( - array( - 'labelValues' => array('lalal', 'lululu'), + 'labelNames' => ['foo', 'bar'], + 'samples' => [ + [ + 'labelValues' => ['lalal', 'lululu'], 'value' => 3, 'name' => 'test_some_metric', - 'labelNames' => array() - ), - ) - ) - ) - ) + 'labelNames' => [], + ], + ], + ] + ), + ] ) ); } @@ -69,24 +71,24 @@ public function itShouldIncreaseWithoutLabelWhenNoLabelsAreDefined() $this->assertThat( $this->adapter->collect(), $this->equalTo( - array( + [ new MetricFamilySamples( - array( + [ 'type' => Counter::TYPE, 'help' => 'this is for testing', 'name' => 'test_some_metric', - 'labelNames' => array(), - 'samples' => array( - array( - 'labelValues' => array(), + 'labelNames' => [], + 'samples' => [ + [ + 'labelValues' => [], 'value' => 1, 'name' => 'test_some_metric', - 'labelNames' => array() - ), - ) - ) - ) - ) + 'labelNames' => [], + ], + ], + ] + ), + ] ) ); } @@ -96,30 +98,30 @@ public function itShouldIncreaseWithoutLabelWhenNoLabelsAreDefined() */ public function itShouldIncreaseTheCounterByAnArbitraryInteger() { - $gauge = new Counter($this->adapter, 'test', 'some_metric', 'this is for testing', array('foo', 'bar')); - $gauge->inc(array('lalal', 'lululu')); - $gauge->incBy(123, array('lalal', 'lululu')); + $gauge = new Counter($this->adapter, 'test', 'some_metric', 'this is for testing', ['foo', 'bar']); + $gauge->inc(['lalal', 'lululu']); + $gauge->incBy(123, ['lalal', 'lululu']); $this->assertThat( $this->adapter->collect(), $this->equalTo( - array( + [ new MetricFamilySamples( - array( + [ 'type' => Counter::TYPE, 'help' => 'this is for testing', 'name' => 'test_some_metric', - 'labelNames' => array('foo', 'bar'), - 'samples' => array( - array( - 'labelValues' => array('lalal', 'lululu'), + 'labelNames' => ['foo', 'bar'], + 'samples' => [ + [ + 'labelValues' => ['lalal', 'lululu'], 'value' => 124, 'name' => 'test_some_metric', - 'labelNames' => array() - ), - ) - ) - ) - ) + 'labelNames' => [], + ], + ], + ] + ), + ] ) ); } @@ -139,7 +141,7 @@ public function itShouldRejectInvalidMetricsNames() */ public function itShouldRejectInvalidLabelNames() { - new Counter($this->adapter, 'test', 'some_metric', 'help', array('invalid label')); + new Counter($this->adapter, 'test', 'some_metric', 'help', ['invalid label']); } /** @@ -151,8 +153,8 @@ public function itShouldRejectInvalidLabelNames() public function isShouldAcceptAnySequenceOfBasicLatinCharactersForLabelValues($value) { $label = 'foo'; - $histogram = new Counter($this->adapter, 'test', 'some_metric', 'help', array($label)); - $histogram->inc(array($value)); + $histogram = new Counter($this->adapter, 'test', 'some_metric', 'help', [$label]); + $histogram->inc([$value]); $metrics = $this->adapter->collect(); self::assertInternalType('array', $metrics); @@ -173,8 +175,8 @@ public function isShouldAcceptAnySequenceOfBasicLatinCharactersForLabelValues($v } /** - * @see isShouldAcceptArbitraryLabelValues * @return array + * @see isShouldAcceptArbitraryLabelValues */ public function labelValuesDataProvider() { @@ -182,10 +184,8 @@ public function labelValuesDataProvider() // Basic Latin // See https://en.wikipedia.org/wiki/List_of_Unicode_characters#Basic_Latin for ($i = 32; $i <= 121; $i++) { - $cases['ASCII code ' . $i] = array(chr($i)); + $cases['ASCII code ' . $i] = [chr($i)]; } return $cases; } - - public abstract function configureAdapter(); } diff --git a/tests/Test/Prometheus/AbstractGaugeTest.php b/tests/Test/Prometheus/AbstractGaugeTest.php index 32c2673..4536f48 100644 --- a/tests/Test/Prometheus/AbstractGaugeTest.php +++ b/tests/Test/Prometheus/AbstractGaugeTest.php @@ -25,34 +25,36 @@ public function setUp() $this->configureAdapter(); } + public abstract function configureAdapter(); + /** * @test */ public function itShouldAllowSetWithLabels() { - $gauge = new Gauge($this->adapter, 'test', 'some_metric', 'this is for testing', array('foo', 'bar')); - $gauge->set(123, array('lalal', 'lululu')); + $gauge = new Gauge($this->adapter, 'test', 'some_metric', 'this is for testing', ['foo', 'bar']); + $gauge->set(123, ['lalal', 'lululu']); $this->assertThat( $this->adapter->collect(), $this->equalTo( - array( + [ new MetricFamilySamples( - array( + [ 'name' => 'test_some_metric', 'help' => 'this is for testing', 'type' => Gauge::TYPE, - 'labelNames' => array('foo', 'bar'), - 'samples' => array( - array( + 'labelNames' => ['foo', 'bar'], + 'samples' => [ + [ 'name' => 'test_some_metric', - 'labelNames' => array(), - 'labelValues' => array('lalal', 'lululu'), + 'labelNames' => [], + 'labelValues' => ['lalal', 'lululu'], 'value' => 123, - ) - ) - ) - ) - ) + ], + ], + ] + ), + ] ) ); $this->assertThat($gauge->getHelp(), $this->equalTo('this is for testing')); @@ -69,24 +71,24 @@ public function itShouldAllowSetWithoutLabelWhenNoLabelsAreDefined() $this->assertThat( $this->adapter->collect(), $this->equalTo( - array( + [ new MetricFamilySamples( - array( + [ 'name' => 'test_some_metric', 'help' => 'this is for testing', 'type' => Gauge::TYPE, - 'labelNames' => array(), - 'samples' => array( - array( + 'labelNames' => [], + 'samples' => [ + [ 'name' => 'test_some_metric', - 'labelNames' => array(), - 'labelValues' => array(), + 'labelNames' => [], + 'labelValues' => [], 'value' => 123, - ) - ) - ) - ) - ) + ], + ], + ] + ), + ] ) ); $this->assertThat($gauge->getHelp(), $this->equalTo('this is for testing')); @@ -103,24 +105,24 @@ public function itShouldAllowSetWithAFloatValue() $this->assertThat( $this->adapter->collect(), $this->equalTo( - array( + [ new MetricFamilySamples( - array( + [ 'name' => 'test_some_metric', 'help' => 'this is for testing', 'type' => Gauge::TYPE, - 'labelNames' => array(), - 'samples' => array( - array( + 'labelNames' => [], + 'samples' => [ + [ 'name' => 'test_some_metric', - 'labelNames' => array(), - 'labelValues' => array(), + 'labelNames' => [], + 'labelValues' => [], 'value' => 123.5, - ) - ) - ) - ) - ) + ], + ], + ] + ), + ] ) ); $this->assertThat($gauge->getHelp(), $this->equalTo('this is for testing')); @@ -132,30 +134,30 @@ public function itShouldAllowSetWithAFloatValue() */ public function itShouldIncrementAValue() { - $gauge = new Gauge($this->adapter, 'test', 'some_metric', 'this is for testing', array('foo', 'bar')); - $gauge->inc(array('lalal', 'lululu')); - $gauge->incBy(123, array('lalal', 'lululu')); + $gauge = new Gauge($this->adapter, 'test', 'some_metric', 'this is for testing', ['foo', 'bar']); + $gauge->inc(['lalal', 'lululu']); + $gauge->incBy(123, ['lalal', 'lululu']); $this->assertThat( $this->adapter->collect(), $this->equalTo( - array( + [ new MetricFamilySamples( - array( + [ 'name' => 'test_some_metric', 'help' => 'this is for testing', 'type' => Gauge::TYPE, - 'labelNames' => array('foo', 'bar'), - 'samples' => array( - array( + 'labelNames' => ['foo', 'bar'], + 'samples' => [ + [ 'name' => 'test_some_metric', - 'labelNames' => array(), - 'labelValues' => array('lalal', 'lululu'), + 'labelNames' => [], + 'labelValues' => ['lalal', 'lululu'], 'value' => 124, - ) - ) - ) - ) - ) + ], + ], + ] + ), + ] ) ); } @@ -165,30 +167,30 @@ public function itShouldIncrementAValue() */ public function itShouldIncrementWithFloatValue() { - $gauge = new Gauge($this->adapter, 'test', 'some_metric', 'this is for testing', array('foo', 'bar')); - $gauge->inc(array('lalal', 'lululu')); - $gauge->incBy(123.5, array('lalal', 'lululu')); + $gauge = new Gauge($this->adapter, 'test', 'some_metric', 'this is for testing', ['foo', 'bar']); + $gauge->inc(['lalal', 'lululu']); + $gauge->incBy(123.5, ['lalal', 'lululu']); $this->assertThat( $this->adapter->collect(), $this->equalTo( - array( + [ new MetricFamilySamples( - array( + [ 'name' => 'test_some_metric', 'help' => 'this is for testing', 'type' => Gauge::TYPE, - 'labelNames' => array('foo', 'bar'), - 'samples' => array( - array( + 'labelNames' => ['foo', 'bar'], + 'samples' => [ + [ 'name' => 'test_some_metric', - 'labelNames' => array(), - 'labelValues' => array('lalal', 'lululu'), + 'labelNames' => [], + 'labelValues' => ['lalal', 'lululu'], 'value' => 124.5, - ) - ) - ) - ) - ) + ], + ], + ] + ), + ] ) ); } @@ -198,30 +200,30 @@ public function itShouldIncrementWithFloatValue() */ public function itShouldDecrementAValue() { - $gauge = new Gauge($this->adapter, 'test', 'some_metric', 'this is for testing', array('foo', 'bar')); - $gauge->dec(array('lalal', 'lululu')); - $gauge->decBy(123, array('lalal', 'lululu')); + $gauge = new Gauge($this->adapter, 'test', 'some_metric', 'this is for testing', ['foo', 'bar']); + $gauge->dec(['lalal', 'lululu']); + $gauge->decBy(123, ['lalal', 'lululu']); $this->assertThat( $this->adapter->collect(), $this->equalTo( - array( + [ new MetricFamilySamples( - array( + [ 'name' => 'test_some_metric', 'help' => 'this is for testing', 'type' => Gauge::TYPE, - 'labelNames' => array('foo', 'bar'), - 'samples' => array( - array( + 'labelNames' => ['foo', 'bar'], + 'samples' => [ + [ 'name' => 'test_some_metric', - 'labelNames' => array(), - 'labelValues' => array('lalal', 'lululu'), + 'labelNames' => [], + 'labelValues' => ['lalal', 'lululu'], 'value' => -124, - ) - ) - ) - ) - ) + ], + ], + ] + ), + ] ) ); } @@ -231,30 +233,30 @@ public function itShouldDecrementAValue() */ public function itShouldDecrementWithFloatValue() { - $gauge = new Gauge($this->adapter, 'test', 'some_metric', 'this is for testing', array('foo', 'bar')); - $gauge->dec(array('lalal', 'lululu')); - $gauge->decBy(123, array('lalal', 'lululu')); + $gauge = new Gauge($this->adapter, 'test', 'some_metric', 'this is for testing', ['foo', 'bar']); + $gauge->dec(['lalal', 'lululu']); + $gauge->decBy(123, ['lalal', 'lululu']); $this->assertThat( $this->adapter->collect(), $this->equalTo( - array( + [ new MetricFamilySamples( - array( + [ 'name' => 'test_some_metric', 'help' => 'this is for testing', 'type' => Gauge::TYPE, - 'labelNames' => array('foo', 'bar'), - 'samples' => array( - array( + 'labelNames' => ['foo', 'bar'], + 'samples' => [ + [ 'name' => 'test_some_metric', - 'labelNames' => array(), - 'labelValues' => array('lalal', 'lululu'), + 'labelNames' => [], + 'labelValues' => ['lalal', 'lululu'], 'value' => -124, - ) - ) - ) - ) - ) + ], + ], + ] + ), + ] ) ); } @@ -264,30 +266,30 @@ public function itShouldDecrementWithFloatValue() */ public function itShouldOverwriteWhenSettingTwice() { - $gauge = new Gauge($this->adapter, 'test', 'some_metric', 'this is for testing', array('foo', 'bar')); - $gauge->set(123, array('lalal', 'lululu')); - $gauge->set(321, array('lalal', 'lululu')); + $gauge = new Gauge($this->adapter, 'test', 'some_metric', 'this is for testing', ['foo', 'bar']); + $gauge->set(123, ['lalal', 'lululu']); + $gauge->set(321, ['lalal', 'lululu']); $this->assertThat( $this->adapter->collect(), $this->equalTo( - array( + [ new MetricFamilySamples( - array( + [ 'name' => 'test_some_metric', 'help' => 'this is for testing', 'type' => Gauge::TYPE, - 'labelNames' => array('foo', 'bar'), - 'samples' => array( - array( + 'labelNames' => ['foo', 'bar'], + 'samples' => [ + [ 'name' => 'test_some_metric', - 'labelNames' => array(), - 'labelValues' => array('lalal', 'lululu'), + 'labelNames' => [], + 'labelValues' => ['lalal', 'lululu'], 'value' => 321, - ) - ) - ) - ) - ) + ], + ], + ] + ), + ] ) ); } @@ -307,7 +309,7 @@ public function itShouldRejectInvalidMetricsNames() */ public function itShouldRejectInvalidLabelNames() { - new Gauge($this->adapter, 'test', 'some_metric', 'help', array('invalid label')); + new Gauge($this->adapter, 'test', 'some_metric', 'help', ['invalid label']); } /** @@ -319,8 +321,8 @@ public function itShouldRejectInvalidLabelNames() public function isShouldAcceptAnySequenceOfBasicLatinCharactersForLabelValues($value) { $label = 'foo'; - $histogram = new Gauge($this->adapter, 'test', 'some_metric', 'help', array($label)); - $histogram->inc(array($value)); + $histogram = new Gauge($this->adapter, 'test', 'some_metric', 'help', [$label]); + $histogram->inc([$value]); $metrics = $this->adapter->collect(); self::assertInternalType('array', $metrics); @@ -341,8 +343,8 @@ public function isShouldAcceptAnySequenceOfBasicLatinCharactersForLabelValues($v } /** - * @see isShouldAcceptArbitraryLabelValues * @return array + * @see isShouldAcceptArbitraryLabelValues */ public function labelValuesDataProvider() { @@ -350,10 +352,8 @@ public function labelValuesDataProvider() // Basic Latin // See https://en.wikipedia.org/wiki/List_of_Unicode_characters#Basic_Latin for ($i = 32; $i <= 121; $i++) { - $cases['ASCII code ' . $i] = array(chr($i)); + $cases['ASCII code ' . $i] = [chr($i)]; } return $cases; } - - public abstract function configureAdapter(); } diff --git a/tests/Test/Prometheus/AbstractHistogramTest.php b/tests/Test/Prometheus/AbstractHistogramTest.php index af982d5..c64d2d8 100644 --- a/tests/Test/Prometheus/AbstractHistogramTest.php +++ b/tests/Test/Prometheus/AbstractHistogramTest.php @@ -26,6 +26,8 @@ public function setUp() $this->configureAdapter(); } + public abstract function configureAdapter(); + /** * @test */ @@ -36,62 +38,62 @@ public function itShouldObserveWithLabels() 'test', 'some_metric', 'this is for testing', - array('foo', 'bar'), - array(100, 200, 300) + ['foo', 'bar'], + [100, 200, 300] ); - $histogram->observe(123, array('lalal', 'lululu')); - $histogram->observe(245, array('lalal', 'lululu')); + $histogram->observe(123, ['lalal', 'lululu']); + $histogram->observe(245, ['lalal', 'lululu']); $this->assertThat( $this->adapter->collect(), $this->equalTo( - array( + [ new MetricFamilySamples( - array( + [ 'name' => 'test_some_metric', 'help' => 'this is for testing', 'type' => Histogram::TYPE, - 'labelNames' => array('foo', 'bar'), - 'samples' => array( - array( + 'labelNames' => ['foo', 'bar'], + 'samples' => [ + [ 'name' => 'test_some_metric_bucket', - 'labelNames' => array('le'), - 'labelValues' => array('lalal', 'lululu', 100), + 'labelNames' => ['le'], + 'labelValues' => ['lalal', 'lululu', 100], 'value' => 0, - ), - array( + ], + [ 'name' => 'test_some_metric_bucket', - 'labelNames' => array('le'), - 'labelValues' => array('lalal', 'lululu', 200), + 'labelNames' => ['le'], + 'labelValues' => ['lalal', 'lululu', 200], 'value' => 1, - ), - array( + ], + [ 'name' => 'test_some_metric_bucket', - 'labelNames' => array('le'), - 'labelValues' => array('lalal', 'lululu', 300), + 'labelNames' => ['le'], + 'labelValues' => ['lalal', 'lululu', 300], 'value' => 2, - ), - array( + ], + [ 'name' => 'test_some_metric_bucket', - 'labelNames' => array('le'), - 'labelValues' => array('lalal', 'lululu', '+Inf'), + 'labelNames' => ['le'], + 'labelValues' => ['lalal', 'lululu', '+Inf'], 'value' => 2, - ), - array( + ], + [ 'name' => 'test_some_metric_count', - 'labelNames' => array(), - 'labelValues' => array('lalal', 'lululu'), + 'labelNames' => [], + 'labelValues' => ['lalal', 'lululu'], 'value' => 2, - ), - array( + ], + [ 'name' => 'test_some_metric_sum', - 'labelNames' => array(), - 'labelValues' => array('lalal', 'lululu'), + 'labelNames' => [], + 'labelValues' => ['lalal', 'lululu'], 'value' => 368, - ) - ) - ) - ) - ) + ], + ], + ] + ), + ] ) ); } @@ -106,61 +108,61 @@ public function itShouldObserveWithoutLabelWhenNoLabelsAreDefined() 'test', 'some_metric', 'this is for testing', - array(), - array(100, 200, 300) + [], + [100, 200, 300] ); $histogram->observe(245); $this->assertThat( $this->adapter->collect(), $this->equalTo( - array( + [ new MetricFamilySamples( - array( + [ 'name' => 'test_some_metric', 'help' => 'this is for testing', 'type' => Histogram::TYPE, - 'labelNames' => array(), - 'samples' => array( - array( + 'labelNames' => [], + 'samples' => [ + [ 'name' => 'test_some_metric_bucket', - 'labelNames' => array('le'), - 'labelValues' => array(100), + 'labelNames' => ['le'], + 'labelValues' => [100], 'value' => 0, - ), - array( + ], + [ 'name' => 'test_some_metric_bucket', - 'labelNames' => array('le'), - 'labelValues' => array(200), + 'labelNames' => ['le'], + 'labelValues' => [200], 'value' => 0, - ), - array( + ], + [ 'name' => 'test_some_metric_bucket', - 'labelNames' => array('le'), - 'labelValues' => array(300), + 'labelNames' => ['le'], + 'labelValues' => [300], 'value' => 1, - ), - array( + ], + [ 'name' => 'test_some_metric_bucket', - 'labelNames' => array('le'), - 'labelValues' => array('+Inf'), + 'labelNames' => ['le'], + 'labelValues' => ['+Inf'], 'value' => 1, - ), - array( + ], + [ 'name' => 'test_some_metric_count', - 'labelNames' => array(), - 'labelValues' => array(), + 'labelNames' => [], + 'labelValues' => [], 'value' => 1, - ), - array( + ], + [ 'name' => 'test_some_metric_sum', - 'labelNames' => array(), - 'labelValues' => array(), + 'labelNames' => [], + 'labelValues' => [], 'value' => 245, - ) - ) - ) - ) - ) + ], + ], + ] + ), + ] ) ); } @@ -175,62 +177,62 @@ public function itShouldObserveValuesOfTypeDouble() 'test', 'some_metric', 'this is for testing', - array(), - array(0.1, 0.2, 0.3) + [], + [0.1, 0.2, 0.3] ); $histogram->observe(0.11); $histogram->observe(0.3); $this->assertThat( $this->adapter->collect(), $this->equalTo( - array( + [ new MetricFamilySamples( - array( + [ 'name' => 'test_some_metric', 'help' => 'this is for testing', 'type' => Histogram::TYPE, - 'labelNames' => array(), - 'samples' => array( - array( + 'labelNames' => [], + 'samples' => [ + [ 'name' => 'test_some_metric_bucket', - 'labelNames' => array('le'), - 'labelValues' => array(0.1), + 'labelNames' => ['le'], + 'labelValues' => [0.1], 'value' => 0, - ), - array( + ], + [ 'name' => 'test_some_metric_bucket', - 'labelNames' => array('le'), - 'labelValues' => array(0.2), + 'labelNames' => ['le'], + 'labelValues' => [0.2], 'value' => 1, - ), - array( + ], + [ 'name' => 'test_some_metric_bucket', - 'labelNames' => array('le'), - 'labelValues' => array(0.3), + 'labelNames' => ['le'], + 'labelValues' => [0.3], 'value' => 2, - ), - array( + ], + [ 'name' => 'test_some_metric_bucket', - 'labelNames' => array('le'), - 'labelValues' => array('+Inf'), + 'labelNames' => ['le'], + 'labelValues' => ['+Inf'], 'value' => 2, - ), - array( + ], + [ 'name' => 'test_some_metric_count', - 'labelNames' => array(), - 'labelValues' => array(), + 'labelNames' => [], + 'labelValues' => [], 'value' => 2, - ), - array( + ], + [ 'name' => 'test_some_metric_sum', - 'labelNames' => array(), - 'labelValues' => array(), + 'labelNames' => [], + 'labelValues' => [], 'value' => 0.41, - ) - ) - ) - ) - ) + ], + ], + ] + ), + ] ) ); } @@ -247,7 +249,7 @@ public function itShouldProvideDefaultBuckets() 'test', 'some_metric', 'this is for testing', - array() + [] ); $histogram->observe(0.11); @@ -255,120 +257,120 @@ public function itShouldProvideDefaultBuckets() $this->assertThat( $this->adapter->collect(), $this->equalTo( - array( + [ new MetricFamilySamples( - array( + [ 'name' => 'test_some_metric', 'help' => 'this is for testing', 'type' => Histogram::TYPE, - 'labelNames' => array(), - 'samples' => array( - array( + 'labelNames' => [], + 'samples' => [ + [ 'name' => 'test_some_metric_bucket', - 'labelNames' => array('le'), - 'labelValues' => array(0.005), + 'labelNames' => ['le'], + 'labelValues' => [0.005], 'value' => 0, - ), - array( + ], + [ 'name' => 'test_some_metric_bucket', - 'labelNames' => array('le'), - 'labelValues' => array(0.01), + 'labelNames' => ['le'], + 'labelValues' => [0.01], 'value' => 0, - ), - array( + ], + [ 'name' => 'test_some_metric_bucket', - 'labelNames' => array('le'), - 'labelValues' => array(0.025), + 'labelNames' => ['le'], + 'labelValues' => [0.025], 'value' => 0, - ), - array( + ], + [ 'name' => 'test_some_metric_bucket', - 'labelNames' => array('le'), - 'labelValues' => array(0.05), + 'labelNames' => ['le'], + 'labelValues' => [0.05], 'value' => 1, - ), - array( + ], + [ 'name' => 'test_some_metric_bucket', - 'labelNames' => array('le'), - 'labelValues' => array(0.075), + 'labelNames' => ['le'], + 'labelValues' => [0.075], 'value' => 1, - ), - array( + ], + [ 'name' => 'test_some_metric_bucket', - 'labelNames' => array('le'), - 'labelValues' => array(0.1), + 'labelNames' => ['le'], + 'labelValues' => [0.1], 'value' => 1, - ), - array( + ], + [ 'name' => 'test_some_metric_bucket', - 'labelNames' => array('le'), - 'labelValues' => array(0.25), + 'labelNames' => ['le'], + 'labelValues' => [0.25], 'value' => 2, - ), - array( + ], + [ 'name' => 'test_some_metric_bucket', - 'labelNames' => array('le'), - 'labelValues' => array(0.5), + 'labelNames' => ['le'], + 'labelValues' => [0.5], 'value' => 2, - ), - array( + ], + [ 'name' => 'test_some_metric_bucket', - 'labelNames' => array('le'), - 'labelValues' => array(0.75), + 'labelNames' => ['le'], + 'labelValues' => [0.75], 'value' => 2, - ), - array( + ], + [ 'name' => 'test_some_metric_bucket', - 'labelNames' => array('le'), - 'labelValues' => array(1.0), + 'labelNames' => ['le'], + 'labelValues' => [1.0], 'value' => 2, - ), - array( + ], + [ 'name' => 'test_some_metric_bucket', - 'labelNames' => array('le'), - 'labelValues' => array(2.5), + 'labelNames' => ['le'], + 'labelValues' => [2.5], 'value' => 2, - ), - array( + ], + [ 'name' => 'test_some_metric_bucket', - 'labelNames' => array('le'), - 'labelValues' => array(5), + 'labelNames' => ['le'], + 'labelValues' => [5], 'value' => 2, - ), - array( + ], + [ 'name' => 'test_some_metric_bucket', - 'labelNames' => array('le'), - 'labelValues' => array(7.5), + 'labelNames' => ['le'], + 'labelValues' => [7.5], 'value' => 2, - ), - array( + ], + [ 'name' => 'test_some_metric_bucket', - 'labelNames' => array('le'), - 'labelValues' => array(10), + 'labelNames' => ['le'], + 'labelValues' => [10], 'value' => 2, - ), - array( + ], + [ 'name' => 'test_some_metric_bucket', - 'labelNames' => array('le'), - 'labelValues' => array('+Inf'), + 'labelNames' => ['le'], + 'labelValues' => ['+Inf'], 'value' => 2, - ), - array( + ], + [ 'name' => 'test_some_metric_count', - 'labelNames' => array(), - 'labelValues' => array(), + 'labelNames' => [], + 'labelValues' => [], 'value' => 2, - ), - array( + ], + [ 'name' => 'test_some_metric_sum', - 'labelNames' => array(), - 'labelValues' => array(), + 'labelNames' => [], + 'labelValues' => [], 'value' => 0.14, - ) - ) - ) - ) - ) + ], + ], + ] + ), + ] ) ); } @@ -380,7 +382,7 @@ public function itShouldProvideDefaultBuckets() */ public function itShouldThrowAnExceptionWhenTheBucketSizesAreNotIncreasing() { - new Histogram($this->adapter, 'test', 'some_metric', 'this is for testing', array(), array(1, 1)); + new Histogram($this->adapter, 'test', 'some_metric', 'this is for testing', [], [1, 1]); } /** @@ -390,7 +392,7 @@ public function itShouldThrowAnExceptionWhenTheBucketSizesAreNotIncreasing() */ public function itShouldThrowAnExceptionWhenThereIsLessThanOneBucket() { - new Histogram($this->adapter, 'test', 'some_metric', 'this is for testing', array(), array()); + new Histogram($this->adapter, 'test', 'some_metric', 'this is for testing', [], []); } /** @@ -400,7 +402,7 @@ public function itShouldThrowAnExceptionWhenThereIsLessThanOneBucket() */ public function itShouldThrowAnExceptionWhenThereIsALabelNamedLe() { - new Histogram($this->adapter, 'test', 'some_metric', 'this is for testing', array('le'), array(1)); + new Histogram($this->adapter, 'test', 'some_metric', 'this is for testing', ['le'], [1]); } /** @@ -410,7 +412,7 @@ public function itShouldThrowAnExceptionWhenThereIsALabelNamedLe() */ public function itShouldRejectInvalidMetricsNames() { - new Histogram($this->adapter, 'test', 'some invalid metric', 'help', array(), array(1)); + new Histogram($this->adapter, 'test', 'some invalid metric', 'help', [], [1]); } /** @@ -420,7 +422,7 @@ public function itShouldRejectInvalidMetricsNames() */ public function itShouldRejectInvalidLabelNames() { - new Histogram($this->adapter, 'test', 'some_metric', 'help', array('invalid label'), array(1)); + new Histogram($this->adapter, 'test', 'some_metric', 'help', ['invalid label'], [1]); } /** @@ -432,8 +434,8 @@ public function itShouldRejectInvalidLabelNames() public function isShouldAcceptAnySequenceOfBasicLatinCharactersForLabelValues($value) { $label = 'foo'; - $histogram = new Histogram($this->adapter, 'test', 'some_metric', 'help', array($label), array(1)); - $histogram->observe(1, array($value)); + $histogram = new Histogram($this->adapter, 'test', 'some_metric', 'help', [$label], [1]); + $histogram->observe(1, [$value]); $metrics = $this->adapter->collect(); self::assertInternalType('array', $metrics); @@ -454,8 +456,8 @@ public function isShouldAcceptAnySequenceOfBasicLatinCharactersForLabelValues($v } /** - * @see isShouldAcceptArbitraryLabelValues * @return array + * @see isShouldAcceptArbitraryLabelValues */ public function labelValuesDataProvider() { @@ -463,10 +465,8 @@ public function labelValuesDataProvider() // Basic Latin // See https://en.wikipedia.org/wiki/List_of_Unicode_characters#Basic_Latin for ($i = 32; $i <= 121; $i++) { - $cases['ASCII code ' . $i] = array(chr($i)); + $cases['ASCII code ' . $i] = [chr($i)]; } return $cases; } - - public abstract function configureAdapter(); } diff --git a/tests/Test/Prometheus/Redis/CollectorRegistryTest.php b/tests/Test/Prometheus/Redis/CollectorRegistryTest.php index 2e69ce9..b023e23 100644 --- a/tests/Test/Prometheus/Redis/CollectorRegistryTest.php +++ b/tests/Test/Prometheus/Redis/CollectorRegistryTest.php @@ -14,7 +14,7 @@ class CollectorRegistryTest extends AbstractCollectorRegistryTest { public function configureAdapter() { - $this->adapter = new Redis(array('host' => REDIS_HOST)); + $this->adapter = new Redis(['host' => REDIS_HOST]); $this->adapter->flushRedis(); } } diff --git a/tests/Test/Prometheus/Redis/CounterTest.php b/tests/Test/Prometheus/Redis/CounterTest.php index 088f9dd..2a59a7f 100644 --- a/tests/Test/Prometheus/Redis/CounterTest.php +++ b/tests/Test/Prometheus/Redis/CounterTest.php @@ -14,7 +14,7 @@ class CounterTest extends AbstractCounterTest { public function configureAdapter() { - $this->adapter = new Redis(array('host' => REDIS_HOST)); + $this->adapter = new Redis(['host' => REDIS_HOST]); $this->adapter->flushRedis(); } } diff --git a/tests/Test/Prometheus/Redis/GaugeTest.php b/tests/Test/Prometheus/Redis/GaugeTest.php index c359037..f5f363a 100644 --- a/tests/Test/Prometheus/Redis/GaugeTest.php +++ b/tests/Test/Prometheus/Redis/GaugeTest.php @@ -14,7 +14,7 @@ class GaugeTest extends AbstractGaugeTest { public function configureAdapter() { - $this->adapter = new Redis(array('host' => REDIS_HOST)); + $this->adapter = new Redis(['host' => REDIS_HOST]); $this->adapter->flushRedis(); } } diff --git a/tests/Test/Prometheus/Redis/HistogramTest.php b/tests/Test/Prometheus/Redis/HistogramTest.php index da15c25..806a348 100644 --- a/tests/Test/Prometheus/Redis/HistogramTest.php +++ b/tests/Test/Prometheus/Redis/HistogramTest.php @@ -14,7 +14,7 @@ class HistogramTest extends AbstractHistogramTest { public function configureAdapter() { - $this->adapter = new Redis(array('host' => REDIS_HOST)); + $this->adapter = new Redis(['host' => REDIS_HOST]); $this->adapter->flushRedis(); } } diff --git a/tests/Test/Prometheus/Storage/RedisTest.php b/tests/Test/Prometheus/Storage/RedisTest.php index dcaddba..9ba0c65 100644 --- a/tests/Test/Prometheus/Storage/RedisTest.php +++ b/tests/Test/Prometheus/Storage/RedisTest.php @@ -12,12 +12,13 @@ class RedisTest extends TestCase { /** * @test - * @expectedException StorageException + * @expectedException Prometheus\Exception\StorageException * @expectedExceptionMessage Can't connect to Redis server */ public function itShouldThrowAnExceptionOnConnectionFailure() { - $redis = new Redis(['host' => 'completely.fake.example.test']); + $redis = new Redis(['host' => '/dev/null']); + $redis->collect(); $redis->flushRedis(); } From 01405bc8254e35989ff5741dfb7d7f1234e9cc1f Mon Sep 17 00:00:00 2001 From: Daniel Noel-Davies Date: Mon, 22 Jul 2019 10:24:08 +0100 Subject: [PATCH 06/28] Add missing typehints and format exception message a little nicer --- src/Prometheus/PushGateway.php | 6 ++++-- src/Prometheus/RenderTextFormat.php | 2 +- src/Prometheus/Storage/Redis.php | 4 ++-- 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/src/Prometheus/PushGateway.php b/src/Prometheus/PushGateway.php index e8792af..24b6401 100644 --- a/src/Prometheus/PushGateway.php +++ b/src/Prometheus/PushGateway.php @@ -91,8 +91,10 @@ private function doRequest(CollectorRegistry $collectorRegistry, string $job, ar $response = $client->request($method, $url, $requestOptions); $statusCode = $response->getStatusCode(); if ($statusCode != 202) { - $msg = "Unexpected status code " . $statusCode . " received from push gateway " . $this->address . ": " . $response->getBody( - ); + $msg = "Unexpected status code " + . $statusCode + . " received from push gateway " + . $this->address . ": " . $response->getBody(); throw new RuntimeException($msg); } } diff --git a/src/Prometheus/RenderTextFormat.php b/src/Prometheus/RenderTextFormat.php index c0b3e70..1bbacf6 100644 --- a/src/Prometheus/RenderTextFormat.php +++ b/src/Prometheus/RenderTextFormat.php @@ -53,7 +53,7 @@ private function renderSample(MetricFamilySamples $metric, Sample $sample): stri } /** - * @param $v + * @param string $v * @return string */ private function escapeLabelValue($v): string diff --git a/src/Prometheus/Storage/Redis.php b/src/Prometheus/Storage/Redis.php index 1d46d88..434aab2 100644 --- a/src/Prometheus/Storage/Redis.php +++ b/src/Prometheus/Storage/Redis.php @@ -403,10 +403,10 @@ function ($a, $b) { } /** - * @param string $cmd + * @param int $cmd * @return string */ - private function getRedisCommand($cmd): string + private function getRedisCommand(int $cmd): string { switch ($cmd) { case Adapter::COMMAND_INCREMENT_INTEGER: From 4d33aec98430c4e1bb76cd4737a5e3882b9132e1 Mon Sep 17 00:00:00 2001 From: Daniel Noel-Davies Date: Mon, 22 Jul 2019 12:07:07 +0100 Subject: [PATCH 07/28] Use object property value declarations instead of using declarations within the constructor --- examples/flush_adapter.php | 2 +- examples/metrics.php | 2 +- examples/pushgateway.php | 2 +- examples/some_counter.php | 2 +- examples/some_gauge.php | 2 +- examples/some_histogram.php | 2 +- src/Prometheus/Storage/Redis.php | 34 ++++++++++---------------------- 7 files changed, 16 insertions(+), 30 deletions(-) diff --git a/examples/flush_adapter.php b/examples/flush_adapter.php index 028fdc7..08cd1e0 100644 --- a/examples/flush_adapter.php +++ b/examples/flush_adapter.php @@ -4,7 +4,7 @@ $adapter = $_GET['adapter']; if ($adapter === 'redis') { - define('REDIS_HOST', isset($_SERVER['REDIS_HOST']) ? $_SERVER['REDIS_HOST'] : '127.0.0.1'); + define('REDIS_HOST', $_SERVER['REDIS_HOST'] ?? '127.0.0.1'); $redisAdapter = new Prometheus\Storage\Redis(['host' => REDIS_HOST]); $redisAdapter->flushRedis(); diff --git a/examples/metrics.php b/examples/metrics.php index 74a111b..e523f79 100644 --- a/examples/metrics.php +++ b/examples/metrics.php @@ -9,7 +9,7 @@ $adapter = $_GET['adapter']; if ($adapter === 'redis') { - Redis::setDefaultOptions(['host' => isset($_SERVER['REDIS_HOST']) ? $_SERVER['REDIS_HOST'] : '127.0.0.1']); + Redis::setDefaultOptions(['host' => $_SERVER['REDIS_HOST'] ?? '127.0.0.1']); $adapter = new Prometheus\Storage\Redis(); } elseif ($adapter === 'apc') { $adapter = new Prometheus\Storage\APC(); diff --git a/examples/pushgateway.php b/examples/pushgateway.php index e78706f..f850f5c 100644 --- a/examples/pushgateway.php +++ b/examples/pushgateway.php @@ -8,7 +8,7 @@ $adapter = $_GET['adapter']; if ($adapter === 'redis') { - Redis::setDefaultOptions(['host' => isset($_SERVER['REDIS_HOST']) ? $_SERVER['REDIS_HOST'] : '127.0.0.1']); + Redis::setDefaultOptions(['host' => $_SERVER['REDIS_HOST'] ?? '127.0.0.1']); $adapter = new Prometheus\Storage\Redis(); } elseif ($adapter === 'apc') { $adapter = new Prometheus\Storage\APC(); diff --git a/examples/some_counter.php b/examples/some_counter.php index 71e7290..857e7e8 100644 --- a/examples/some_counter.php +++ b/examples/some_counter.php @@ -8,7 +8,7 @@ $adapter = $_GET['adapter']; if ($adapter === 'redis') { - Redis::setDefaultOptions(['host' => isset($_SERVER['REDIS_HOST']) ? $_SERVER['REDIS_HOST'] : '127.0.0.1']); + Redis::setDefaultOptions(['host' => $_SERVER['REDIS_HOST'] ?? '127.0.0.1']); $adapter = new Prometheus\Storage\Redis(); } elseif ($adapter === 'apc') { $adapter = new Prometheus\Storage\APC(); diff --git a/examples/some_gauge.php b/examples/some_gauge.php index ca2180f..255362b 100644 --- a/examples/some_gauge.php +++ b/examples/some_gauge.php @@ -11,7 +11,7 @@ $adapter = $_GET['adapter']; if ($adapter === 'redis') { - Redis::setDefaultOptions(['host' => isset($_SERVER['REDIS_HOST']) ? $_SERVER['REDIS_HOST'] : '127.0.0.1']); + Redis::setDefaultOptions(['host' => $_SERVER['REDIS_HOST'] ?? '127.0.0.1']); $adapter = new Prometheus\Storage\Redis(); } elseif ($adapter === 'apc') { $adapter = new Prometheus\Storage\APC(); diff --git a/examples/some_histogram.php b/examples/some_histogram.php index babbced..eaacb8a 100644 --- a/examples/some_histogram.php +++ b/examples/some_histogram.php @@ -10,7 +10,7 @@ $adapter = $_GET['adapter']; if ($adapter === 'redis') { - Redis::setDefaultOptions(['host' => isset($_SERVER['REDIS_HOST']) ? $_SERVER['REDIS_HOST'] : '127.0.0.1']); + Redis::setDefaultOptions(['host' => $_SERVER['REDIS_HOST'] ?? '127.0.0.1']); $adapter = new Prometheus\Storage\Redis(); } elseif ($adapter === 'apc') { $adapter = new Prometheus\Storage\APC(); diff --git a/src/Prometheus/Storage/Redis.php b/src/Prometheus/Storage/Redis.php index 434aab2..7074c53 100644 --- a/src/Prometheus/Storage/Redis.php +++ b/src/Prometheus/Storage/Redis.php @@ -9,7 +9,6 @@ use Prometheus\Gauge; use Prometheus\Histogram; use Prometheus\MetricFamilySamples; -use RedisException; class Redis implements Adapter { @@ -18,7 +17,14 @@ class Redis implements Adapter /** * @var array */ - private static $defaultOptions = []; + private static $defaultOptions = [ + 'host' => '127.0.0.1', + 'port' => 6379, + 'timeout' => 0.1, + 'read_timeout' => 10, + 'persistent_connections' => false, + 'password' => null, + ]; /** * @var string @@ -28,7 +34,7 @@ class Redis implements Adapter /** * @var array */ - private $options; + private $options = []; /** * @var \Redis @@ -41,27 +47,6 @@ class Redis implements Adapter */ public function __construct(array $options = []) { - // with php 5.3 we cannot initialize the options directly on the field definition - // so we initialize them here for now - if (!isset(self::$defaultOptions['host'])) { - self::$defaultOptions['host'] = '127.0.0.1'; - } - if (!isset(self::$defaultOptions['port'])) { - self::$defaultOptions['port'] = 6379; - } - if (!isset(self::$defaultOptions['timeout'])) { - self::$defaultOptions['timeout'] = 0.1; // in seconds - } - if (!isset(self::$defaultOptions['read_timeout'])) { - self::$defaultOptions['read_timeout'] = 10; // in seconds - } - if (!isset(self::$defaultOptions['persistent_connections'])) { - self::$defaultOptions['persistent_connections'] = false; - } - if (!isset(self::$defaultOptions['password'])) { - self::$defaultOptions['password'] = null; - } - $this->options = array_merge(self::$defaultOptions, $options); $this->redis = new \Redis(); } @@ -122,6 +107,7 @@ private function openConnection(): void if ($this->options['password']) { $this->redis->auth($this->options['password']); } + if (isset($this->options['database'])) { $this->redis->select($this->options['database']); } From 6a644c37d9316dfa363149c615f13adfd2bd7fbc Mon Sep 17 00:00:00 2001 From: Daniel Noel-Davies Date: Mon, 22 Jul 2019 12:13:08 +0100 Subject: [PATCH 08/28] Fix weird nesting issues --- src/Prometheus/RenderTextFormat.php | 9 ++---- src/Prometheus/Storage/APC.php | 45 ++++++++++++----------------- src/Prometheus/Storage/InMemory.php | 40 ++++++++++++------------- src/Prometheus/Storage/Redis.php | 18 ++++-------- 4 files changed, 47 insertions(+), 65 deletions(-) diff --git a/src/Prometheus/RenderTextFormat.php b/src/Prometheus/RenderTextFormat.php index 1bbacf6..fcd0679 100644 --- a/src/Prometheus/RenderTextFormat.php +++ b/src/Prometheus/RenderTextFormat.php @@ -13,12 +13,9 @@ class RenderTextFormat */ public function render(array $metrics): string { - usort( - $metrics, - function (MetricFamilySamples $a, MetricFamilySamples $b) { - return strcmp($a->getName(), $b->getName()); - } - ); + usort( $metrics, function (MetricFamilySamples $a, MetricFamilySamples $b) { + return strcmp($a->getName(), $b->getName()); + }); $lines = []; diff --git a/src/Prometheus/Storage/APC.php b/src/Prometheus/Storage/APC.php index e7a8864..397eb39 100644 --- a/src/Prometheus/Storage/APC.php +++ b/src/Prometheus/Storage/APC.php @@ -116,16 +116,13 @@ private function metaKey(array $data): string */ private function valueKey(array $data): string { - return implode( - ':', - [ - self::PROMETHEUS_PREFIX, - $data['type'], - $data['name'], - $this->encodeLabelValues($data['labelValues']), - 'value', - ] - ); + return implode(':', [ + self::PROMETHEUS_PREFIX, + $data['type'], + $data['name'], + $this->encodeLabelValues($data['labelValues']), + 'value', + ]); } /** @@ -134,17 +131,14 @@ private function valueKey(array $data): string */ private function histogramBucketValueKey(array $data, $bucket): string { - return implode( - ':', - [ - self::PROMETHEUS_PREFIX, - $data['type'], - $data['name'], - $this->encodeLabelValues($data['labelValues']), - $bucket, - 'value', - ] - ); + return implode(':', [ + self::PROMETHEUS_PREFIX, + $data['type'], + $data['name'], + $this->encodeLabelValues($data['labelValues']), + $bucket, + 'value', + ]); } /** @@ -320,12 +314,9 @@ private function fromInteger($val): float */ private function sortSamples(array &$samples): void { - usort( - $samples, - function ($a, $b) { - return strcmp(implode("", $a['labelValues']), implode("", $b['labelValues'])); - } - ); + usort($samples, function ($a, $b) { + return strcmp(implode("", $a['labelValues']), implode("", $b['labelValues'])); + }); } /** diff --git a/src/Prometheus/Storage/InMemory.php b/src/Prometheus/Storage/InMemory.php index 49ae4db..35c48e1 100644 --- a/src/Prometheus/Storage/InMemory.php +++ b/src/Prometheus/Storage/InMemory.php @@ -228,15 +228,12 @@ public function updateCounter(array $data): void */ private function histogramBucketValueKey(array $data, $bucket): string { - return implode( - ':', - [ - $data['type'], - $data['name'], - $this->encodeLabelValues($data['labelValues']), - $bucket, - ] - ); + return implode(':', [ + $data['type'], + $data['name'], + $this->encodeLabelValues($data['labelValues']), + $bucket, + ]); } /** @@ -246,7 +243,11 @@ private function histogramBucketValueKey(array $data, $bucket): string */ private function metaKey(array $data): string { - return implode(':', [$data['type'], $data['name'], 'meta']); + return implode(':', [ + $data['type'], + $data['name'], + 'meta' + ]); } /** @@ -256,10 +257,12 @@ private function metaKey(array $data): string */ private function valueKey(array $data): string { - return implode( - ':', - [$data['type'], $data['name'], $this->encodeLabelValues($data['labelValues']), 'value'] - ); + return implode(':', [ + $data['type'], + $data['name'], + $this->encodeLabelValues($data['labelValues']), + 'value' + ]); } /** @@ -281,12 +284,9 @@ private function metaData(array $data): array */ private function sortSamples(array &$samples): void { - usort( - $samples, - function ($a, $b) { - return strcmp(implode("", $a['labelValues']), implode("", $b['labelValues'])); - } - ); + usort($samples, function ($a, $b) { + return strcmp(implode("", $a['labelValues']), implode("", $b['labelValues'])); + }); } /** diff --git a/src/Prometheus/Storage/Redis.php b/src/Prometheus/Storage/Redis.php index 7074c53..45f4566 100644 --- a/src/Prometheus/Storage/Redis.php +++ b/src/Prometheus/Storage/Redis.php @@ -345,12 +345,9 @@ private function collectGauges(): array 'value' => $value, ]; } - usort( - $gauge['samples'], - function ($a, $b) { - return strcmp(implode("", $a['labelValues']), implode("", $b['labelValues'])); - } - ); + usort($gauge['samples'], function ($a, $b) { + return strcmp(implode("", $a['labelValues']), implode("", $b['labelValues'])); + }); $gauges[] = $gauge; } return $gauges; @@ -377,12 +374,9 @@ private function collectCounters(): array 'value' => $value, ]; } - usort( - $counter['samples'], - function ($a, $b) { - return strcmp(implode("", $a['labelValues']), implode("", $b['labelValues'])); - } - ); + usort($counter['samples'], function ($a, $b) { + return strcmp(implode("", $a['labelValues']), implode("", $b['labelValues'])); + }); $counters[] = $counter; } return $counters; From 417d335d9aabe040aaafb4471ecb61b5cbddb0b6 Mon Sep 17 00:00:00 2001 From: Daniel Noel-Davies Date: Mon, 22 Jul 2019 14:03:25 +0100 Subject: [PATCH 09/28] Fix autoloading with PSR-4 --- composer.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/composer.json b/composer.json index b941542..bce0026 100644 --- a/composer.json +++ b/composer.json @@ -23,8 +23,8 @@ "ext-apc": "Required if using APCu." }, "autoload": { - "psr-0": { - "Prometheus\\": "src/" + "psr-4": { + "Prometheus\\": "src/Prometheus/" } }, "autoload-dev": { From 9c40adca08f4da597c976317444bbb6543bfcea5 Mon Sep 17 00:00:00 2001 From: Daniel Noel-Davies Date: Mon, 22 Jul 2019 14:14:54 +0100 Subject: [PATCH 10/28] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 2c62cd7..03e9e75 100644 --- a/README.md +++ b/README.md @@ -89,7 +89,7 @@ Also look at the [examples](examples). ### Dependencies -* PHP 5.6 +* PHP 7.1 * PHP Redis extension * PHP APCu extension * [Composer](https://getcomposer.org/doc/00-intro.md#installation-linux-unix-osx) From 8c7fa911a53d2a3b9745a1f61ae19cf4e9ac772e Mon Sep 17 00:00:00 2001 From: Daniel Noel-Davies Date: Tue, 23 Jul 2019 15:49:28 +0100 Subject: [PATCH 11/28] Removed unused namespaces --- tests/Test/BlackBoxPushGatewayTest.php | 1 - tests/Test/Prometheus/APC/CollectorRegistryTest.php | 1 - tests/Test/Prometheus/APC/CounterTest.php | 1 - tests/Test/Prometheus/APC/GaugeTest.php | 1 - tests/Test/Prometheus/APC/HistogramTest.php | 1 - tests/Test/Prometheus/InMemory/CollectorRegistryTest.php | 1 - tests/Test/Prometheus/InMemory/CounterTest.php | 1 - tests/Test/Prometheus/InMemory/GaugeTest.php | 1 - tests/Test/Prometheus/InMemory/HistogramTest.php | 1 - tests/Test/Prometheus/Redis/CollectorRegistryTest.php | 2 -- tests/Test/Prometheus/Redis/CounterTest.php | 1 - tests/Test/Prometheus/Redis/GaugeTest.php | 1 - tests/Test/Prometheus/Redis/HistogramTest.php | 1 - 13 files changed, 14 deletions(-) diff --git a/tests/Test/BlackBoxPushGatewayTest.php b/tests/Test/BlackBoxPushGatewayTest.php index 47469be..6193fc4 100644 --- a/tests/Test/BlackBoxPushGatewayTest.php +++ b/tests/Test/BlackBoxPushGatewayTest.php @@ -3,7 +3,6 @@ use GuzzleHttp\Client; use PHPUnit\Framework\TestCase; -use PHPUnit_Framework_TestCase; use Prometheus\CollectorRegistry; use Prometheus\PushGateway; diff --git a/tests/Test/Prometheus/APC/CollectorRegistryTest.php b/tests/Test/Prometheus/APC/CollectorRegistryTest.php index 23f7b84..9d73fb7 100644 --- a/tests/Test/Prometheus/APC/CollectorRegistryTest.php +++ b/tests/Test/Prometheus/APC/CollectorRegistryTest.php @@ -1,6 +1,5 @@ Date: Wed, 11 Sep 2019 13:19:27 +0100 Subject: [PATCH 12/28] Bump version in composer and add contribution information --- composer.json | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 47aeab2..0800574 100644 --- a/composer.json +++ b/composer.json @@ -1,5 +1,6 @@ { - "name": "jimdo/prometheus_client_php", + "name": "endclothing/prometheus_client_php", + "version": "1.0.0", "authors": [ { "name": "Joscha", @@ -8,6 +9,10 @@ { "name": "Jan Brauer", "email": "jan.brauer@jimdo.com" + }, + { + "name": "Daniel Noel-Davies", + "email": "Daniel.Noel-Davies@endclothing.com" } ], "require": { From d56d5c42b29754db97256d5eebb163b525eaeae2 Mon Sep 17 00:00:00 2001 From: Daniel Date: Thu, 3 Oct 2019 17:16:19 +0100 Subject: [PATCH 13/28] Add exponential bucket static helper for easy generation of histogram buckets --- composer.json | 8 ----- src/Prometheus/Histogram.php | 30 ++++++++++++++++++ .../Test/Prometheus/AbstractHistogramTest.php | 31 +++++++++++++++++++ 3 files changed, 61 insertions(+), 8 deletions(-) diff --git a/composer.json b/composer.json index 0800574..fd50694 100644 --- a/composer.json +++ b/composer.json @@ -2,14 +2,6 @@ "name": "endclothing/prometheus_client_php", "version": "1.0.0", "authors": [ - { - "name": "Joscha", - "email": "joscha@schnipseljagd.org" - }, - { - "name": "Jan Brauer", - "email": "jan.brauer@jimdo.com" - }, { "name": "Daniel Noel-Davies", "email": "Daniel.Noel-Davies@endclothing.com" diff --git a/src/Prometheus/Histogram.php b/src/Prometheus/Histogram.php index f36cf0f..0c20e6c 100644 --- a/src/Prometheus/Histogram.php +++ b/src/Prometheus/Histogram.php @@ -62,6 +62,36 @@ public static function getDefaultBuckets(): array ]; } + /** + * @param float $start + * @param float $growthFactor + * @param int $numberOfBuckets + * @return array + */ + public static function exponentialBuckets(float $start, float $growthFactor, int $numberOfBuckets): array + { + if ($numberOfBuckets < 1) { + throw new \InvalidArgumentException('Number of buckets must be a positive integer'); + } + + if ($start <= 0) { + throw new \InvalidArgumentException('The starting position of a set of buckets must be a positive integer'); + } + + if ($growthFactor <= 1) { + throw new \InvalidArgumentException('The growth factor must greater than 1'); + } + + $buckets = []; + + for ($i = 0; $i < $numberOfBuckets; $i++) { + $buckets[$i] = $start; + $start *= $growthFactor; + } + + return $buckets; + } + /** * @param double $value e.g. 123 * @param array $labels e.g. ['status', 'opcode'] diff --git a/tests/Test/Prometheus/AbstractHistogramTest.php b/tests/Test/Prometheus/AbstractHistogramTest.php index c64d2d8..f170e70 100644 --- a/tests/Test/Prometheus/AbstractHistogramTest.php +++ b/tests/Test/Prometheus/AbstractHistogramTest.php @@ -455,6 +455,37 @@ public function isShouldAcceptAnySequenceOfBasicLatinCharactersForLabelValues($v } } + /** + * @test + */ + public function itShouldBeAbleToGenerateExponentialBucketsGivenSpecificBounds() + { + $start = 0.05; + $growthFactor = 1.5; + $numberOfbuckets = 14; + + $generatedBuckets = Histogram::exponentialBuckets($start, $growthFactor, $numberOfbuckets); + + $expectedBuckets = [ + 0.05, + 0.075, + 0.1125, + 0.16875, + 0.253125, + 0.3796875, + 0.56953125, + 0.854296875, + 1.2814453125, + 1.92216796875, + 2.883251953125, + 4.3248779296875, + 6.4873168945313, + 9.7309753417969, + ]; + + self::assertEquals($generatedBuckets, $expectedBuckets); + } + /** * @return array * @see isShouldAcceptArbitraryLabelValues From bc86c725a6a7c86b7fee67ffd6c3f539199661d1 Mon Sep 17 00:00:00 2001 From: Daniel Date: Thu, 3 Oct 2019 18:06:09 +0100 Subject: [PATCH 14/28] Added exponential bucket generation explaination for histograms into the readme. --- README.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/README.md b/README.md index 03e9e75..6731fe1 100644 --- a/README.md +++ b/README.md @@ -83,6 +83,20 @@ $renderer = new RenderTextFormat(); $result = $renderer->render($registry->getMetricFamilySamples()); ``` +### Advanced Usage + +#### Advanced Histogram Usage +On passing an empty array for the bucket parameter on instantiation, a set of default buckets will be used instead. +Whilst this is a good base for a typical web application, there is named constructor to assist in the generation of +exponential / geometric buckets. + +Eg: +``` +Histogram::exponentialBuckets(0.05, 1.5, 10); +``` + +This will start your buckets with a value of 1.5, grow them by a factor of 1.5 per bucket across a set of 10 buckets. + Also look at the [examples](examples). ## Development From ae9284f6921f7c591b3a76bea2bb17ec92b3f3aa Mon Sep 17 00:00:00 2001 From: Daniel Date: Fri, 4 Oct 2019 10:32:23 +0100 Subject: [PATCH 15/28] Clean up import statements in histogram --- src/Prometheus/Histogram.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Prometheus/Histogram.php b/src/Prometheus/Histogram.php index 0c20e6c..18b8706 100644 --- a/src/Prometheus/Histogram.php +++ b/src/Prometheus/Histogram.php @@ -1,5 +1,5 @@ Date: Fri, 4 Oct 2019 11:45:27 +0100 Subject: [PATCH 16/28] bump version to 1.0.1 --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index fd50694..305b6bd 100644 --- a/composer.json +++ b/composer.json @@ -1,6 +1,6 @@ { "name": "endclothing/prometheus_client_php", - "version": "1.0.0", + "version": "1.0.1", "authors": [ { "name": "Daniel Noel-Davies", From 25d00760175e580e242d2bc305114bfcc3c98db0 Mon Sep 17 00:00:00 2001 From: Daniel Date: Fri, 4 Oct 2019 12:16:04 +0100 Subject: [PATCH 17/28] Update php required version --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 305b6bd..16e8341 100644 --- a/composer.json +++ b/composer.json @@ -8,7 +8,7 @@ } ], "require": { - "php": "^7.1", + "php": "^7.3", "ext-json": "*", "guzzlehttp/guzzle": "^6.2", "symfony/polyfill-apcu": "^1.6" From b55c01b0dad5088fb66433878315683848e4f1d6 Mon Sep 17 00:00:00 2001 From: Dawid 'DeyV' Polak Date: Wed, 23 Oct 2019 08:00:52 +0200 Subject: [PATCH 18/28] Update README.md ^7.3 is required version of php --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6731fe1..497bdad 100644 --- a/README.md +++ b/README.md @@ -103,7 +103,7 @@ Also look at the [examples](examples). ### Dependencies -* PHP 7.1 +* PHP ^7.3 * PHP Redis extension * PHP APCu extension * [Composer](https://getcomposer.org/doc/00-intro.md#installation-linux-unix-osx) From fdd6a3dc816119a68b9849cb9ebdb364a05e27af Mon Sep 17 00:00:00 2001 From: Dawid 'DeyV' Polak Date: Wed, 23 Oct 2019 08:06:03 +0200 Subject: [PATCH 19/28] Update .travis.yml Run tests for PHP 7.3 and 7.4, no more support for < 7.3 (required in composer) --- .travis.yml | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/.travis.yml b/.travis.yml index 720eacf..cd51f3b 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,8 +1,7 @@ language: php -php: - - 5.6 - - 7.0 - - 7.1 +php: + - 7.3 + - 7.4 services: - redis-server From de702c629f4b42166ebe59bf6d506bd153f1030b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=A0imon=20Podlipsk=C3=BD?= Date: Tue, 5 Nov 2019 14:14:36 +0100 Subject: [PATCH 20/28] Add Installation instructions --- README.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/README.md b/README.md index 497bdad..260b5d8 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,14 @@ You can pick from three adapters. Redis, APC or an in memory adapter. While the first needs a separate binary running, the second just needs the [APC](https://pecl.php.net/package/APCU) extension to be installed. If you don't need persistent metrics between requests (e.g. a long running cron job or script) the in memory adapter might be suitable to use. +## Installation + +Add as [Composer](https://getcomposer.org/) dependency: + +```sh +composer require endclothing/prometheus_client_php +``` + ## Usage A simple counter: From c0ea8a389d783f779e15b412ece432cd53742e10 Mon Sep 17 00:00:00 2001 From: Florian Levis Date: Tue, 5 Nov 2019 10:31:56 +0100 Subject: [PATCH 21/28] fix(composer): add replace rule Add original package (`jimdo/prometheus_client_php`) to the replace list --- composer.json | 3 +++ 1 file changed, 3 insertions(+) diff --git a/composer.json b/composer.json index 16e8341..09c1442 100644 --- a/composer.json +++ b/composer.json @@ -7,6 +7,9 @@ "email": "Daniel.Noel-Davies@endclothing.com" } ], + "replace: { + "jimdo/prometheus_client_php": "*" + }, "require": { "php": "^7.3", "ext-json": "*", From 5930a030b142f9eac3c8eaf94d296d2d68617ad7 Mon Sep 17 00:00:00 2001 From: Martins Sipenko Date: Thu, 7 Nov 2019 13:26:23 +0200 Subject: [PATCH 22/28] Fix invalid json (typo) --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 09c1442..fcfb614 100644 --- a/composer.json +++ b/composer.json @@ -7,7 +7,7 @@ "email": "Daniel.Noel-Davies@endclothing.com" } ], - "replace: { + "replace": { "jimdo/prometheus_client_php": "*" }, "require": { From 63966cdd9402a08a22e184038420b358b14e1dbe Mon Sep 17 00:00:00 2001 From: Martins Sipenko Date: Tue, 19 Nov 2019 20:11:48 +0200 Subject: [PATCH 23/28] Introduce Continuous Integration (#20) * WIP CI * Move few things around in CI pipeline * remove unneeded CI job --- .circleci/config.yml | 81 +++++++++++++++++++++++++++++++++ .gitattributes | 12 +++++ .travis.yml | 19 -------- composer.json | 14 +++++- phpunit.xml => phpunit.xml.dist | 23 ++++++---- 5 files changed, 118 insertions(+), 31 deletions(-) create mode 100644 .circleci/config.yml create mode 100644 .gitattributes delete mode 100644 .travis.yml rename phpunit.xml => phpunit.xml.dist (51%) diff --git a/.circleci/config.yml b/.circleci/config.yml new file mode 100644 index 0000000..471eb48 --- /dev/null +++ b/.circleci/config.yml @@ -0,0 +1,81 @@ +unit-config: &unit-config + environment: + COMPOSER_PREFER_LOWEST: 0 + steps: + - checkout + + - run: + name: Install latest composer + command: | + php -r "copy('https://raw.githubusercontent.com/composer/getcomposer.org/master/web/installer', 'composer-setup.php');" + php composer-setup.php + php -r "unlink('composer-setup.php');" + mv composer.phar /usr/local/bin/composer + + - run: + name: Write COMPOSER_PREFER_LOWEST to file + command: echo "$COMPOSER_PREFER_LOWEST" > ~/COMPOSER_PREFER_LOWEST.txt + + # Download and cache dependencies + - restore_cache: + keys: + - v1-composer-cache-{{ checksum "~/COMPOSER_PREFER_LOWEST.txt" }}-{{ checksum "composer.json" }} + # Fall back to using the latest cache if no exact match is found. + - v1-composer-cache-{{ checksum "~/COMPOSER_PREFER_LOWEST.txt" }} + + - run: + name: Validate composer files + command: composer validate --strict + + - run: + name: Install PHP extensions + command: | + printf '\n' | sudo pecl install redis + sudo docker-php-ext-enable redis + + - run: + name: Install composer packages + command: | + if [ $COMPOSER_PREFER_LOWEST -eq "1" ]; then + composer update --no-ansi --no-progress --optimize-autoloader --no-interaction --no-plugins --no-scripts --prefer-dist --prefer-stable --prefer-lowest + else + composer update --no-ansi --no-progress --optimize-autoloader --no-interaction --no-plugins --no-scripts --prefer-dist --prefer-stable + fi + + - save_cache: + key: v1-composer-cache-{{ checksum "~/COMPOSER_PREFER_LOWEST.txt" }}-{{ checksum "composer.json" }} + paths: + - ./vendor + + - run: + name: Wait for backing services to start + command: dockerize -wait tcp://127.0.0.1:6379 -timeout 30s + + - run: + name: Run tests + command: ./vendor/bin/phpunit + +version: 2.1 +jobs: + php73: + <<: *unit-config + docker: + - image: circleci/php:7.3-cli-node + - image: circleci/redis:5-alpine + environment: + COMPOSER_PREFER_LOWEST: 0 + + php73-lowest: + <<: *unit-config + docker: + - image: circleci/php:7.3-cli-node + - image: circleci/redis:5-alpine + environment: + COMPOSER_PREFER_LOWEST: 1 + +workflows: + version: 2 + units: + jobs: + - php73 + - php73-lowest diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..1044039 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,12 @@ +* text=auto +/.circleci/ export-ignore +/.github/ export-ignore +/examples/ export-ignore +/nginx/ export-ignore +/php-fpm/ export-ignore +/tests/ export-ignore +.gitattributes export-ignore +.gitignore export-ignore +docker-compose.yml export-ignore +phpcs.xml.dist export-ignore +phpunit.xml.dist export-ignore diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index cd51f3b..0000000 --- a/.travis.yml +++ /dev/null @@ -1,19 +0,0 @@ -language: php -php: - - 7.3 - - 7.4 - -services: - - redis-server - -before_script: - - echo "apc.enabled = 1" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php.ini - - echo "apc.enable_cli = 1" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php.ini - - echo "extension = apcu.so" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php.ini - - echo "extension = redis.so" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php.ini - - composer self-update - - composer install --no-interaction --prefer-source --dev - - phpenv rehash - -script: - - vendor/bin/phpunit --verbose --colors diff --git a/composer.json b/composer.json index fcfb614..c985b44 100644 --- a/composer.json +++ b/composer.json @@ -1,6 +1,8 @@ { "name": "endclothing/prometheus_client_php", - "version": "1.0.1", + "description": "Prometheus instrumentation library for PHP applications.", + "type": "library", + "license": "Apache-2.0", "authors": [ { "name": "Daniel Noel-Davies", @@ -33,5 +35,13 @@ "Test\\Prometheus\\": "tests/" } }, - "license": "Apache-2.0" + "extra": { + "branch-alias": { + "dev-master": "1.0-dev" + } + }, + "config": { + "sort-packages": true + }, + "prefer-stable": true } diff --git a/phpunit.xml b/phpunit.xml.dist similarity index 51% rename from phpunit.xml rename to phpunit.xml.dist index ab027cb..9fc8a72 100644 --- a/phpunit.xml +++ b/phpunit.xml.dist @@ -7,15 +7,18 @@ convertNoticesToExceptions="true" convertWarningsToExceptions="true" processIsolation="false" + stopOnError="false" stopOnFailure="false"> - - - ./tests/Test/Prometheus - - - - - ./src/Prometheus - - + + + + ./tests/Test/Prometheus + + + + + + ./src/Prometheus + + From 4668eebd7858b3475a6ecbf53266e37c2eee78fd Mon Sep 17 00:00:00 2001 From: kswzr <31246037+kswzr@users.noreply.github.com> Date: Tue, 19 Nov 2019 19:13:26 +0100 Subject: [PATCH 24/28] Add support for prometheus/pushgateway:>=0.10 (#17) * allow status 202 in case of downwards compatibility * add allowance of status 200 for prometheus/pushgateway >=0.10.0 * fix grouping key, because of not matching declerations * simplify if to add more status code easier --- src/Prometheus/PushGateway.php | 25 ++++--- tests/Test/Prometheus/PushGatewayTest.php | 79 +++++++++++++++++++++++ 2 files changed, 96 insertions(+), 8 deletions(-) create mode 100644 tests/Test/Prometheus/PushGatewayTest.php diff --git a/src/Prometheus/PushGateway.php b/src/Prometheus/PushGateway.php index 24b6401..9f8dcd8 100644 --- a/src/Prometheus/PushGateway.php +++ b/src/Prometheus/PushGateway.php @@ -4,6 +4,7 @@ namespace Prometheus; use GuzzleHttp\Client; +use GuzzleHttp\ClientInterface; use GuzzleHttp\Exception\GuzzleException; use RuntimeException; @@ -14,13 +15,20 @@ class PushGateway */ private $address; + /** + * @var ClientInterface + */ + private $client; + /** * PushGateway constructor. - * @param $address string host:port of the push gateway + * @param string $address host:port of the push gateway + * @param ClientInterface $client */ - public function __construct($address) + public function __construct($address, ClientInterface $client = null) { $this->address = $address; + $this->client = $client ?? new Client(); } /** @@ -31,7 +39,7 @@ public function __construct($address) * @param array $groupingKey * @throws GuzzleException */ - public function push(CollectorRegistry $collectorRegistry, string $job, array $groupingKey = null): void + public function push(CollectorRegistry $collectorRegistry, string $job, array $groupingKey = []): void { $this->doRequest($collectorRegistry, $job, $groupingKey, 'put'); } @@ -44,7 +52,7 @@ public function push(CollectorRegistry $collectorRegistry, string $job, array $g * @param $groupingKey * @throws GuzzleException */ - public function pushAdd(CollectorRegistry $collectorRegistry, string $job, array $groupingKey = null): void + public function pushAdd(CollectorRegistry $collectorRegistry, string $job, array $groupingKey = []): void { $this->doRequest($collectorRegistry, $job, $groupingKey, 'post'); } @@ -56,7 +64,7 @@ public function pushAdd(CollectorRegistry $collectorRegistry, string $job, array * @param array $groupingKey * @throws GuzzleException */ - public function delete(string $job, array $groupingKey = null): void + public function delete(string $job, array $groupingKey = []): void { $this->doRequest(null, $job, $groupingKey, 'delete'); } @@ -76,7 +84,7 @@ private function doRequest(CollectorRegistry $collectorRegistry, string $job, ar $url .= "/" . $label . "/" . $value; } } - $client = new Client(); + $requestOptions = [ 'headers' => [ 'Content-Type' => RenderTextFormat::MIME_TYPE, @@ -84,13 +92,14 @@ private function doRequest(CollectorRegistry $collectorRegistry, string $job, ar 'connect_timeout' => 10, 'timeout' => 20, ]; + if ($method != 'delete') { $renderer = new RenderTextFormat(); $requestOptions['body'] = $renderer->render($collectorRegistry->getMetricFamilySamples()); } - $response = $client->request($method, $url, $requestOptions); + $response = $this->client->request($method, $url, $requestOptions); $statusCode = $response->getStatusCode(); - if ($statusCode != 202) { + if (!in_array($statusCode, [200, 202])) { $msg = "Unexpected status code " . $statusCode . " received from push gateway " diff --git a/tests/Test/Prometheus/PushGatewayTest.php b/tests/Test/Prometheus/PushGatewayTest.php new file mode 100644 index 0000000..d100944 --- /dev/null +++ b/tests/Test/Prometheus/PushGatewayTest.php @@ -0,0 +1,79 @@ +createMock(CollectorRegistry::class); + $mockedCollectorRegistry->method('getMetricFamilySamples')->with()->willReturn([ + $this->createMock(MetricFamilySamples::class) + ]); + + $mockHandler = new MockHandler([ + new Response(200), + new Response(202), + ]); + $handler = HandlerStack::create($mockHandler); + $client = new Client(['handler' => $handler]); + + $pushGateway = new PushGateway('http://foo.bar', $client); + $pushGateway->push($mockedCollectorRegistry, 'foo'); + } + + /** + * @test + * + * @doesNotPerformAnyAssertions + */ + public function invalidResponseShouldThrowRuntimeException(): void + { + $this->expectException(\RuntimeException::class); + + $mockedCollectorRegistry = $this->createMock(CollectorRegistry::class); + $mockedCollectorRegistry->method('getMetricFamilySamples')->with()->willReturn([ + $this->createMock(MetricFamilySamples::class) + ]); + + $mockHandler = new MockHandler([ + new Response(201), + new Response(300), + ]); + $handler = HandlerStack::create($mockHandler); + $client = new Client(['handler' => $handler]); + + $pushGateway = new PushGateway('http://foo.bar', $client); + $pushGateway->push($mockedCollectorRegistry, 'foo'); + } + + /** + * @test + */ + public function clientGetsDefinedIfNotSpecified(): void + { + $this->expectException(\RuntimeException::class); + + $mockedCollectorRegistry = $this->createMock(CollectorRegistry::class); + $mockedCollectorRegistry->method('getMetricFamilySamples')->with()->willReturn([ + $this->createMock(MetricFamilySamples::class) + ]); + + $pushGateway = new PushGateway('http://foo.bar'); + $pushGateway->push($mockedCollectorRegistry, 'foo'); + } +} \ No newline at end of file From f4c614c1fdb8ca8088595db7d400e5901e056d5f Mon Sep 17 00:00:00 2001 From: Martins Sipenko Date: Fri, 29 Nov 2019 13:30:44 +0200 Subject: [PATCH 25/28] Add code style check into CI pipeline (#21) Added CI using CircleCI --- .circleci/config.yml | 4 ++++ composer.json | 5 +++-- examples/flush_adapter.php | 2 +- examples/pushgateway.php | 2 +- examples/some_gauge.php | 2 +- examples/some_histogram.php | 2 +- phpcs.xml.dist | 12 ++++++++++++ src/Prometheus/Collector.php | 3 ++- src/Prometheus/CollectorRegistry.php | 1 + src/Prometheus/Counter.php | 3 ++- src/Prometheus/Gauge.php | 3 ++- src/Prometheus/Histogram.php | 1 + src/Prometheus/MetricFamilySamples.php | 3 ++- src/Prometheus/PushGateway.php | 3 ++- src/Prometheus/RenderTextFormat.php | 5 +++-- src/Prometheus/Sample.php | 3 ++- src/Prometheus/Storage/APC.php | 2 +- src/Prometheus/Storage/Adapter.php | 3 ++- src/Prometheus/Storage/InMemory.php | 2 +- src/Prometheus/Storage/Redis.php | 1 + tests/Test/BlackBoxPushGatewayTest.php | 2 +- tests/Test/BlackBoxTest.php | 1 + tests/Test/Prometheus/APC/HistogramTest.php | 1 - .../Prometheus/AbstractCollectorRegistryTest.php | 4 +--- tests/Test/Prometheus/AbstractCounterTest.php | 3 +-- tests/Test/Prometheus/AbstractGaugeTest.php | 3 +-- tests/Test/Prometheus/AbstractHistogramTest.php | 5 +---- tests/Test/Prometheus/InMemory/HistogramTest.php | 1 - tests/Test/Prometheus/PushGatewayTest.php | 2 +- tests/Test/Prometheus/Storage/RedisTest.php | 1 - 30 files changed, 52 insertions(+), 33 deletions(-) create mode 100644 phpcs.xml.dist diff --git a/.circleci/config.yml b/.circleci/config.yml index 471eb48..bcde4cf 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -51,6 +51,10 @@ unit-config: &unit-config name: Wait for backing services to start command: dockerize -wait tcp://127.0.0.1:6379 -timeout 30s + - run: + name: Run PHP Code Sniffer + command: ./vendor/bin/phpcs + - run: name: Run tests command: ./vendor/bin/phpunit diff --git a/composer.json b/composer.json index c985b44..83bfcd3 100644 --- a/composer.json +++ b/composer.json @@ -15,11 +15,12 @@ "require": { "php": "^7.3", "ext-json": "*", - "guzzlehttp/guzzle": "^6.2", + "guzzlehttp/guzzle": "^6.3", "symfony/polyfill-apcu": "^1.6" }, "require-dev": { - "phpunit/phpunit": "^7.5" + "phpunit/phpunit": "^7.5", + "squizlabs/php_codesniffer": "^3.5" }, "suggest": { "ext-redis": "Required if using Redis.", diff --git a/examples/flush_adapter.php b/examples/flush_adapter.php index 08cd1e0..8e2ca88 100644 --- a/examples/flush_adapter.php +++ b/examples/flush_adapter.php @@ -14,4 +14,4 @@ } elseif ($adapter === 'in-memory') { $inMemoryAdapter = new Prometheus\Storage\InMemory(); $inMemoryAdapter->flushMemory(); -} \ No newline at end of file +} diff --git a/examples/pushgateway.php b/examples/pushgateway.php index f850f5c..c337fea 100644 --- a/examples/pushgateway.php +++ b/examples/pushgateway.php @@ -22,4 +22,4 @@ $counter->incBy(6, ['blue']); $pushGateway = new PushGateway('192.168.59.100:9091'); -$pushGateway->push($registry, 'my_job', ['instance'=>'foo']); +$pushGateway->push($registry, 'my_job', ['instance' => 'foo']); diff --git a/examples/some_gauge.php b/examples/some_gauge.php index 255362b..f8202d2 100644 --- a/examples/some_gauge.php +++ b/examples/some_gauge.php @@ -6,7 +6,7 @@ use Prometheus\Storage\Redis; -error_log('c='. $_GET['c']); +error_log('c=' . $_GET['c']); $adapter = $_GET['adapter']; diff --git a/examples/some_histogram.php b/examples/some_histogram.php index eaacb8a..aeb5c1d 100644 --- a/examples/some_histogram.php +++ b/examples/some_histogram.php @@ -5,7 +5,7 @@ use Prometheus\CollectorRegistry; use Prometheus\Storage\Redis; -error_log('c='. $_GET['c']); +error_log('c=' . $_GET['c']); $adapter = $_GET['adapter']; diff --git a/phpcs.xml.dist b/phpcs.xml.dist new file mode 100644 index 0000000..78ea685 --- /dev/null +++ b/phpcs.xml.dist @@ -0,0 +1,12 @@ + + + src/ + tests/ + examples/ + + vendor/* + + + + + diff --git a/src/Prometheus/Collector.php b/src/Prometheus/Collector.php index 26e8275..5f0a440 100644 --- a/src/Prometheus/Collector.php +++ b/src/Prometheus/Collector.php @@ -1,4 +1,5 @@ getName(), $b->getName()); }); diff --git a/src/Prometheus/Sample.php b/src/Prometheus/Sample.php index 3ed624b..c8774e8 100644 --- a/src/Prometheus/Sample.php +++ b/src/Prometheus/Sample.php @@ -1,5 +1,6 @@ $decodedLabelValues, 'value' => $this->fromInteger($histogramBuckets[$labelValues]['sum']), ]; - } $histograms[] = new MetricFamilySamples($data); } diff --git a/src/Prometheus/Storage/Adapter.php b/src/Prometheus/Storage/Adapter.php index 03f258e..068e1d9 100644 --- a/src/Prometheus/Storage/Adapter.php +++ b/src/Prometheus/Storage/Adapter.php @@ -1,5 +1,6 @@ $decodedLabelValues, 'value' => $histogramBuckets[$labelValues]['sum'], ]; - } $histograms[] = new MetricFamilySamples($data); } diff --git a/src/Prometheus/Storage/Redis.php b/src/Prometheus/Storage/Redis.php index 45f4566..c81316b 100644 --- a/src/Prometheus/Storage/Redis.php +++ b/src/Prometheus/Storage/Redis.php @@ -1,4 +1,5 @@ adapter->flushAPC(); } } - diff --git a/tests/Test/Prometheus/AbstractCollectorRegistryTest.php b/tests/Test/Prometheus/AbstractCollectorRegistryTest.php index 82d9b64..4138026 100644 --- a/tests/Test/Prometheus/AbstractCollectorRegistryTest.php +++ b/tests/Test/Prometheus/AbstractCollectorRegistryTest.php @@ -1,9 +1,7 @@ configureAdapter(); } - public abstract function configureAdapter(); + abstract public function configureAdapter(); /** * @test diff --git a/tests/Test/Prometheus/AbstractGaugeTest.php b/tests/Test/Prometheus/AbstractGaugeTest.php index 4536f48..a744a97 100644 --- a/tests/Test/Prometheus/AbstractGaugeTest.php +++ b/tests/Test/Prometheus/AbstractGaugeTest.php @@ -1,6 +1,5 @@ configureAdapter(); } - public abstract function configureAdapter(); + abstract public function configureAdapter(); /** * @test diff --git a/tests/Test/Prometheus/AbstractHistogramTest.php b/tests/Test/Prometheus/AbstractHistogramTest.php index f170e70..9e7b348 100644 --- a/tests/Test/Prometheus/AbstractHistogramTest.php +++ b/tests/Test/Prometheus/AbstractHistogramTest.php @@ -1,6 +1,5 @@ configureAdapter(); } - public abstract function configureAdapter(); + abstract public function configureAdapter(); /** * @test @@ -250,7 +248,6 @@ public function itShouldProvideDefaultBuckets() 'some_metric', 'this is for testing', [] - ); $histogram->observe(0.11); $histogram->observe(0.03); diff --git a/tests/Test/Prometheus/InMemory/HistogramTest.php b/tests/Test/Prometheus/InMemory/HistogramTest.php index 6569bea..50d402d 100644 --- a/tests/Test/Prometheus/InMemory/HistogramTest.php +++ b/tests/Test/Prometheus/InMemory/HistogramTest.php @@ -17,4 +17,3 @@ public function configureAdapter() $this->adapter->flushMemory(); } } - diff --git a/tests/Test/Prometheus/PushGatewayTest.php b/tests/Test/Prometheus/PushGatewayTest.php index d100944..e04dbf1 100644 --- a/tests/Test/Prometheus/PushGatewayTest.php +++ b/tests/Test/Prometheus/PushGatewayTest.php @@ -76,4 +76,4 @@ public function clientGetsDefinedIfNotSpecified(): void $pushGateway = new PushGateway('http://foo.bar'); $pushGateway->push($mockedCollectorRegistry, 'foo'); } -} \ No newline at end of file +} diff --git a/tests/Test/Prometheus/Storage/RedisTest.php b/tests/Test/Prometheus/Storage/RedisTest.php index 9ba0c65..ce4dfbc 100644 --- a/tests/Test/Prometheus/Storage/RedisTest.php +++ b/tests/Test/Prometheus/Storage/RedisTest.php @@ -21,5 +21,4 @@ public function itShouldThrowAnExceptionOnConnectionFailure() $redis->collect(); $redis->flushRedis(); } - } From ce813f7caefb139c8ec2a4fb1a1c422a6e80571d Mon Sep 17 00:00:00 2001 From: Martins Sipenko Date: Fri, 29 Nov 2019 13:35:57 +0200 Subject: [PATCH 26/28] Inject Redis via named constructor (#8) * Inject Redis via named constructor * change method name * Added withExistingConnection test * Fix for redis prefix support and respective tests * removed unneeded code * phpcbf --- src/Prometheus/Storage/Redis.php | 75 ++++++++++++------- tests/Test/Prometheus/AbstractCounterTest.php | 18 ++--- .../Redis/CounterWithPrefixTest.php | 24 ++++++ .../Prometheus/Redis/GaugeWithPrefixTest.php | 24 ++++++ .../Redis/HistogramWithPrefixTest.php | 24 ++++++ tests/Test/Prometheus/Storage/RedisTest.php | 19 ++++- 6 files changed, 147 insertions(+), 37 deletions(-) create mode 100644 tests/Test/Prometheus/Redis/CounterWithPrefixTest.php create mode 100644 tests/Test/Prometheus/Redis/GaugeWithPrefixTest.php create mode 100644 tests/Test/Prometheus/Redis/HistogramWithPrefixTest.php diff --git a/src/Prometheus/Storage/Redis.php b/src/Prometheus/Storage/Redis.php index c81316b..85e3000 100644 --- a/src/Prometheus/Storage/Redis.php +++ b/src/Prometheus/Storage/Redis.php @@ -42,6 +42,11 @@ class Redis implements Adapter */ private $redis; + /** + * @var boolean + */ + private $connectionInitialized = false; + /** * Redis constructor. * @param array $options @@ -52,6 +57,19 @@ public function __construct(array $options = []) $this->redis = new \Redis(); } + public static function fromExistingConnection(\Redis $redis): self + { + if ($redis->isConnected() === false) { + throw new StorageException('Connection to Redis server not established'); + } + + $self = new self(); + $self->connectionInitialized = true; + $self->redis = $redis; + + return $self; + } + /** * @param array $options */ @@ -100,6 +118,10 @@ function (array $metric) { */ private function openConnection(): void { + if ($this->connectionInitialized === true) { + return; + } + $connectionStatus = $this->connectToServer(); if ($connectionStatus === false) { throw new StorageException("Can't connect to Redis server", 0); @@ -153,25 +175,26 @@ public function updateHistogram(array $data): void $metaData = $data; unset($metaData['value']); unset($metaData['labelValues']); + $this->redis->eval( <<toMetricKey($data), + self::$prefix . Histogram::TYPE . self::PROMETHEUS_METRIC_KEYS_SUFFIX, json_encode(['b' => 'sum', 'labelValues' => $data['labelValues']]), json_encode(['b' => $bucketToIncrease, 'labelValues' => $data['labelValues']]), - self::$prefix . Histogram::TYPE . self::PROMETHEUS_METRIC_KEYS_SUFFIX, $data['value'], json_encode($metaData), ], - 4 + 2 ); } @@ -188,30 +211,30 @@ public function updateGauge(array $data): void unset($metaData['command']); $this->redis->eval( <<toMetricKey($data), - $this->getRedisCommand($data['command']), self::$prefix . Gauge::TYPE . self::PROMETHEUS_METRIC_KEYS_SUFFIX, + $this->getRedisCommand($data['command']), json_encode($data['labelValues']), $data['value'], json_encode($metaData), ], - 4 + 2 ); } @@ -228,23 +251,23 @@ public function updateCounter(array $data): void unset($metaData['command']); $this->redis->eval( <<toMetricKey($data), - $this->getRedisCommand($data['command']), self::$prefix . Counter::TYPE . self::PROMETHEUS_METRIC_KEYS_SUFFIX, - json_encode($data['labelValues']), + $this->getRedisCommand($data['command']), $data['value'], + json_encode($data['labelValues']), json_encode($metaData), ], - 4 + 2 ); } @@ -257,7 +280,7 @@ private function collectHistograms(): array sort($keys); $histograms = []; foreach ($keys as $key) { - $raw = $this->redis->hGetAll($key); + $raw = $this->redis->hGetAll(str_replace($this->redis->_prefix(''), '', $key)); $histogram = json_decode($raw['__meta'], true); unset($raw['__meta']); $histogram['samples'] = []; @@ -334,7 +357,7 @@ private function collectGauges(): array sort($keys); $gauges = []; foreach ($keys as $key) { - $raw = $this->redis->hGetAll($key); + $raw = $this->redis->hGetAll(str_replace($this->redis->_prefix(''), '', $key)); $gauge = json_decode($raw['__meta'], true); unset($raw['__meta']); $gauge['samples'] = []; @@ -363,7 +386,7 @@ private function collectCounters(): array sort($keys); $counters = []; foreach ($keys as $key) { - $raw = $this->redis->hGetAll($key); + $raw = $this->redis->hGetAll(str_replace($this->redis->_prefix(''), '', $key)); $counter = json_decode($raw['__meta'], true); unset($raw['__meta']); $counter['samples'] = []; diff --git a/tests/Test/Prometheus/AbstractCounterTest.php b/tests/Test/Prometheus/AbstractCounterTest.php index c60295a..03caa22 100644 --- a/tests/Test/Prometheus/AbstractCounterTest.php +++ b/tests/Test/Prometheus/AbstractCounterTest.php @@ -31,10 +31,10 @@ abstract public function configureAdapter(); */ public function itShouldIncreaseWithLabels() { - $gauge = new Counter($this->adapter, 'test', 'some_metric', 'this is for testing', ['foo', 'bar']); - $gauge->inc(['lalal', 'lululu']); - $gauge->inc(['lalal', 'lululu']); - $gauge->inc(['lalal', 'lululu']); + $counter = new Counter($this->adapter, 'test', 'some_metric', 'this is for testing', ['foo', 'bar']); + $counter->inc(['lalal', 'lululu']); + $counter->inc(['lalal', 'lululu']); + $counter->inc(['lalal', 'lululu']); $this->assertThat( $this->adapter->collect(), $this->equalTo( @@ -65,8 +65,8 @@ public function itShouldIncreaseWithLabels() */ public function itShouldIncreaseWithoutLabelWhenNoLabelsAreDefined() { - $gauge = new Counter($this->adapter, 'test', 'some_metric', 'this is for testing'); - $gauge->inc(); + $counter = new Counter($this->adapter, 'test', 'some_metric', 'this is for testing'); + $counter->inc(); $this->assertThat( $this->adapter->collect(), $this->equalTo( @@ -97,9 +97,9 @@ public function itShouldIncreaseWithoutLabelWhenNoLabelsAreDefined() */ public function itShouldIncreaseTheCounterByAnArbitraryInteger() { - $gauge = new Counter($this->adapter, 'test', 'some_metric', 'this is for testing', ['foo', 'bar']); - $gauge->inc(['lalal', 'lululu']); - $gauge->incBy(123, ['lalal', 'lululu']); + $counter = new Counter($this->adapter, 'test', 'some_metric', 'this is for testing', ['foo', 'bar']); + $counter->inc(['lalal', 'lululu']); + $counter->incBy(123, ['lalal', 'lululu']); $this->assertThat( $this->adapter->collect(), $this->equalTo( diff --git a/tests/Test/Prometheus/Redis/CounterWithPrefixTest.php b/tests/Test/Prometheus/Redis/CounterWithPrefixTest.php new file mode 100644 index 0000000..0409140 --- /dev/null +++ b/tests/Test/Prometheus/Redis/CounterWithPrefixTest.php @@ -0,0 +1,24 @@ +connect(REDIS_HOST); + + $connection->setOption(\Redis::OPT_PREFIX, 'prefix:'); + + $this->adapter = Redis::fromExistingConnection($connection); + $this->adapter->flushRedis(); + } +} diff --git a/tests/Test/Prometheus/Redis/GaugeWithPrefixTest.php b/tests/Test/Prometheus/Redis/GaugeWithPrefixTest.php new file mode 100644 index 0000000..1ba4d0e --- /dev/null +++ b/tests/Test/Prometheus/Redis/GaugeWithPrefixTest.php @@ -0,0 +1,24 @@ +connect(REDIS_HOST); + + $connection->setOption(\Redis::OPT_PREFIX, 'prefix:'); + + $this->adapter = Redis::fromExistingConnection($connection); + $this->adapter->flushRedis(); + } +} diff --git a/tests/Test/Prometheus/Redis/HistogramWithPrefixTest.php b/tests/Test/Prometheus/Redis/HistogramWithPrefixTest.php new file mode 100644 index 0000000..4c25388 --- /dev/null +++ b/tests/Test/Prometheus/Redis/HistogramWithPrefixTest.php @@ -0,0 +1,24 @@ +connect(REDIS_HOST); + + $connection->setOption(\Redis::OPT_PREFIX, 'prefix:'); + + $this->adapter = Redis::fromExistingConnection($connection); + $this->adapter->flushRedis(); + } +} diff --git a/tests/Test/Prometheus/Storage/RedisTest.php b/tests/Test/Prometheus/Storage/RedisTest.php index ce4dfbc..9f2df78 100644 --- a/tests/Test/Prometheus/Storage/RedisTest.php +++ b/tests/Test/Prometheus/Storage/RedisTest.php @@ -12,13 +12,28 @@ class RedisTest extends TestCase { /** * @test - * @expectedException Prometheus\Exception\StorageException - * @expectedExceptionMessage Can't connect to Redis server */ public function itShouldThrowAnExceptionOnConnectionFailure() { $redis = new Redis(['host' => '/dev/null']); + + $this->expectException(StorageException::class); + $this->expectExceptionMessage("Can't connect to Redis server"); + $redis->collect(); $redis->flushRedis(); } + + /** + * @test + */ + public function itShouldThrowExceptionWhenInjectedRedisIsNotConnected() + { + $connection = new \Redis(); + + $this->expectException(StorageException::class); + $this->expectExceptionMessage('Connection to Redis server not established'); + + Redis::fromExistingConnection($connection); + } } From 44cccb41d77540f561c909b54e8752f31aee6735 Mon Sep 17 00:00:00 2001 From: Martins Sipenko Date: Fri, 29 Nov 2019 14:21:57 +0200 Subject: [PATCH 27/28] Update phpunit to version 8 (#23) * Update phpunit to version 8 * fix shield * Require PHPUnit version at least 8.4 --- .gitignore | 3 +- README.md | 6 ++-- composer.json | 2 +- .../AbstractCollectorRegistryTest.php | 25 +++++++++----- tests/Test/Prometheus/AbstractCounterTest.php | 16 ++++----- tests/Test/Prometheus/AbstractGaugeTest.php | 16 ++++----- .../Test/Prometheus/AbstractHistogramTest.php | 34 +++++++++---------- 7 files changed, 56 insertions(+), 46 deletions(-) diff --git a/.gitignore b/.gitignore index 44ab7a5..fc951dd 100644 --- a/.gitignore +++ b/.gitignore @@ -2,4 +2,5 @@ *.iml /.idea/ composer.lock -composer.phar \ No newline at end of file +composer.phar +.phpunit.result.cache diff --git a/README.md b/README.md index 260b5d8..35e4f1f 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # A prometheus client library written in PHP -[![Build Status](https://travis-ci.org/Jimdo/prometheus_client_php.svg?branch=master)](https://travis-ci.org/Jimdo/prometheus_client_php) +[![CircleCI](https://circleci.com/gh/endclothing/prometheus_client_php/tree/master.svg?style=shield)](https://circleci.com/gh/endclothing/prometheus_client_php/tree/master) This library uses Redis or APCu to do the client side aggregation. If using Redis, we recommend to run a local Redis instance next to your PHP workers. @@ -101,9 +101,9 @@ exponential / geometric buckets. Eg: ``` Histogram::exponentialBuckets(0.05, 1.5, 10); -``` +``` -This will start your buckets with a value of 1.5, grow them by a factor of 1.5 per bucket across a set of 10 buckets. +This will start your buckets with a value of 1.5, grow them by a factor of 1.5 per bucket across a set of 10 buckets. Also look at the [examples](examples). diff --git a/composer.json b/composer.json index 83bfcd3..e98dcf4 100644 --- a/composer.json +++ b/composer.json @@ -19,7 +19,7 @@ "symfony/polyfill-apcu": "^1.6" }, "require-dev": { - "phpunit/phpunit": "^7.5", + "phpunit/phpunit": "^8.4", "squizlabs/php_codesniffer": "^3.5" }, "suggest": { diff --git a/tests/Test/Prometheus/AbstractCollectorRegistryTest.php b/tests/Test/Prometheus/AbstractCollectorRegistryTest.php index 4138026..76f3160 100644 --- a/tests/Test/Prometheus/AbstractCollectorRegistryTest.php +++ b/tests/Test/Prometheus/AbstractCollectorRegistryTest.php @@ -8,6 +8,8 @@ use Prometheus\RenderTextFormat; use Prometheus\Storage\Adapter; use Prometheus\Storage\Redis; +use Prometheus\Exception\MetricsRegistrationException; +use Prometheus\Exception\MetricNotFoundException; abstract class AbstractCollectorRegistryTest extends TestCase { @@ -21,7 +23,7 @@ abstract class AbstractCollectorRegistryTest extends TestCase */ private $renderer; - public function setUp() + public function setUp(): void { $this->configureAdapter(); $this->renderer = new RenderTextFormat(); @@ -204,77 +206,84 @@ public function itShouldIncreaseACounterWithoutNamespace() /** * @test - * @expectedException \Prometheus\Exception\MetricsRegistrationException */ public function itShouldForbidRegisteringTheSameCounterTwice() { $registry = new CollectorRegistry($this->adapter); $registry->registerCounter('foo', 'metric', 'help'); + + $this->expectException(MetricsRegistrationException::class); $registry->registerCounter('foo', 'metric', 'help'); } /** * @test - * @expectedException \Prometheus\Exception\MetricsRegistrationException */ public function itShouldForbidRegisteringTheSameCounterWithDifferentLabels() { $registry = new CollectorRegistry($this->adapter); $registry->registerCounter('foo', 'metric', 'help', ["foo", "bar"]); + + $this->expectException(MetricsRegistrationException::class); $registry->registerCounter('foo', 'metric', 'help', ["spam", "eggs"]); } /** * @test - * @expectedException \Prometheus\Exception\MetricsRegistrationException */ public function itShouldForbidRegisteringTheSameHistogramTwice() { $registry = new CollectorRegistry($this->adapter); $registry->registerHistogram('foo', 'metric', 'help'); + + $this->expectException(MetricsRegistrationException::class); $registry->registerHistogram('foo', 'metric', 'help'); } /** * @test - * @expectedException \Prometheus\Exception\MetricsRegistrationException */ public function itShouldForbidRegisteringTheSameHistogramWithDifferentLabels() { $registry = new CollectorRegistry($this->adapter); $registry->registerCounter('foo', 'metric', 'help', ["foo", "bar"]); + + $this->expectException(MetricsRegistrationException::class); $registry->registerCounter('foo', 'metric', 'help', ["spam", "eggs"]); } /** * @test - * @expectedException \Prometheus\Exception\MetricsRegistrationException */ public function itShouldForbidRegisteringTheSameGaugeTwice() { $registry = new CollectorRegistry($this->adapter); $registry->registerGauge('foo', 'metric', 'help'); + + $this->expectException(MetricsRegistrationException::class); $registry->registerGauge('foo', 'metric', 'help'); } /** * @test - * @expectedException \Prometheus\Exception\MetricsRegistrationException */ public function itShouldForbidRegisteringTheSameGaugeWithDifferentLabels() { $registry = new CollectorRegistry($this->adapter); $registry->registerGauge('foo', 'metric', 'help', ["foo", "bar"]); + + $this->expectException(MetricsRegistrationException::class); $registry->registerGauge('foo', 'metric', 'help', ["spam", "eggs"]); } /** * @test - * @expectedException \Prometheus\Exception\MetricNotFoundException */ public function itShouldThrowAnExceptionWhenGettingANonExistentMetric() { $registry = new CollectorRegistry($this->adapter); + + $this->expectException(MetricNotFoundException::class); $registry->getGauge("not_here", "go_away"); } diff --git a/tests/Test/Prometheus/AbstractCounterTest.php b/tests/Test/Prometheus/AbstractCounterTest.php index 03caa22..a932939 100644 --- a/tests/Test/Prometheus/AbstractCounterTest.php +++ b/tests/Test/Prometheus/AbstractCounterTest.php @@ -19,7 +19,7 @@ abstract class AbstractCounterTest extends TestCase */ public $adapter; - public function setUp() + public function setUp(): void { $this->configureAdapter(); } @@ -127,19 +127,19 @@ public function itShouldIncreaseTheCounterByAnArbitraryInteger() /** * @test - * @expectedException InvalidArgumentException */ public function itShouldRejectInvalidMetricsNames() { + $this->expectException(InvalidArgumentException::class); new Counter($this->adapter, 'test', 'some metric invalid metric', 'help'); } /** * @test - * @expectedException InvalidArgumentException */ public function itShouldRejectInvalidLabelNames() { + $this->expectException(InvalidArgumentException::class); new Counter($this->adapter, 'test', 'some_metric', 'help', ['invalid label']); } @@ -156,20 +156,20 @@ public function isShouldAcceptAnySequenceOfBasicLatinCharactersForLabelValues($v $histogram->inc([$value]); $metrics = $this->adapter->collect(); - self::assertInternalType('array', $metrics); - self::assertCount(1, $metrics); - self::assertContainsOnlyInstancesOf(MetricFamilySamples::class, $metrics); + $this->assertIsArray($metrics); + $this->assertCount(1, $metrics); + $this->assertContainsOnlyInstancesOf(MetricFamilySamples::class, $metrics); $metric = reset($metrics); $samples = $metric->getSamples(); - self::assertContainsOnlyInstancesOf(Sample::class, $samples); + $this->assertContainsOnlyInstancesOf(Sample::class, $samples); foreach ($samples as $sample) { $labels = array_combine( array_merge($metric->getLabelNames(), $sample->getLabelNames()), $sample->getLabelValues() ); - self::assertEquals($value, $labels[$label]); + $this->assertEquals($value, $labels[$label]); } } diff --git a/tests/Test/Prometheus/AbstractGaugeTest.php b/tests/Test/Prometheus/AbstractGaugeTest.php index a744a97..393c087 100644 --- a/tests/Test/Prometheus/AbstractGaugeTest.php +++ b/tests/Test/Prometheus/AbstractGaugeTest.php @@ -19,7 +19,7 @@ abstract class AbstractGaugeTest extends TestCase */ public $adapter; - public function setUp() + public function setUp(): void { $this->configureAdapter(); } @@ -295,19 +295,19 @@ public function itShouldOverwriteWhenSettingTwice() /** * @test - * @expectedException InvalidArgumentException */ public function itShouldRejectInvalidMetricsNames() { + $this->expectException(InvalidArgumentException::class); new Gauge($this->adapter, 'test', 'some metric invalid metric', 'help'); } /** * @test - * @expectedException InvalidArgumentException */ public function itShouldRejectInvalidLabelNames() { + $this->expectException(InvalidArgumentException::class); new Gauge($this->adapter, 'test', 'some_metric', 'help', ['invalid label']); } @@ -324,20 +324,20 @@ public function isShouldAcceptAnySequenceOfBasicLatinCharactersForLabelValues($v $histogram->inc([$value]); $metrics = $this->adapter->collect(); - self::assertInternalType('array', $metrics); - self::assertCount(1, $metrics); - self::assertContainsOnlyInstancesOf(MetricFamilySamples::class, $metrics); + $this->assertIsArray($metrics); + $this->assertCount(1, $metrics); + $this->assertContainsOnlyInstancesOf(MetricFamilySamples::class, $metrics); $metric = reset($metrics); $samples = $metric->getSamples(); - self::assertContainsOnlyInstancesOf(Sample::class, $samples); + $this->assertContainsOnlyInstancesOf(Sample::class, $samples); foreach ($samples as $sample) { $labels = array_combine( array_merge($metric->getLabelNames(), $sample->getLabelNames()), $sample->getLabelValues() ); - self::assertEquals($value, $labels[$label]); + $this->assertEquals($value, $labels[$label]); } } diff --git a/tests/Test/Prometheus/AbstractHistogramTest.php b/tests/Test/Prometheus/AbstractHistogramTest.php index 9e7b348..d5f9ebb 100644 --- a/tests/Test/Prometheus/AbstractHistogramTest.php +++ b/tests/Test/Prometheus/AbstractHistogramTest.php @@ -19,7 +19,7 @@ abstract class AbstractHistogramTest extends TestCase */ public $adapter; - public function setUp() + public function setUp(): void { $this->configureAdapter(); } @@ -374,51 +374,51 @@ public function itShouldProvideDefaultBuckets() /** * @test - * @expectedException InvalidArgumentException - * @expectedExceptionMessage Histogram buckets must be in increasing order */ public function itShouldThrowAnExceptionWhenTheBucketSizesAreNotIncreasing() { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Histogram buckets must be in increasing order'); new Histogram($this->adapter, 'test', 'some_metric', 'this is for testing', [], [1, 1]); } /** * @test - * @expectedException InvalidArgumentException - * @expectedExceptionMessage Histogram must have at least one bucket */ public function itShouldThrowAnExceptionWhenThereIsLessThanOneBucket() { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Histogram must have at least one bucket'); new Histogram($this->adapter, 'test', 'some_metric', 'this is for testing', [], []); } /** * @test - * @expectedException InvalidArgumentException - * @expectedExceptionMessage Histogram cannot have a label named */ public function itShouldThrowAnExceptionWhenThereIsALabelNamedLe() { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Histogram cannot have a label named'); new Histogram($this->adapter, 'test', 'some_metric', 'this is for testing', ['le'], [1]); } /** * @test - * @expectedException InvalidArgumentException - * @expectedExceptionMessage Invalid metric name */ public function itShouldRejectInvalidMetricsNames() { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Invalid metric name'); new Histogram($this->adapter, 'test', 'some invalid metric', 'help', [], [1]); } /** * @test - * @expectedException InvalidArgumentException - * @expectedExceptionMessage Invalid label name */ public function itShouldRejectInvalidLabelNames() { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Invalid label name'); new Histogram($this->adapter, 'test', 'some_metric', 'help', ['invalid label'], [1]); } @@ -435,20 +435,20 @@ public function isShouldAcceptAnySequenceOfBasicLatinCharactersForLabelValues($v $histogram->observe(1, [$value]); $metrics = $this->adapter->collect(); - self::assertInternalType('array', $metrics); - self::assertCount(1, $metrics); - self::assertContainsOnlyInstancesOf(MetricFamilySamples::class, $metrics); + $this->assertIsArray($metrics); + $this->assertCount(1, $metrics); + $this->assertContainsOnlyInstancesOf(MetricFamilySamples::class, $metrics); $metric = reset($metrics); $samples = $metric->getSamples(); - self::assertContainsOnlyInstancesOf(Sample::class, $samples); + $this->assertContainsOnlyInstancesOf(Sample::class, $samples); foreach ($samples as $sample) { $labels = array_combine( array_merge($metric->getLabelNames(), $sample->getLabelNames()), $sample->getLabelValues() ); - self::assertEquals($value, $labels[$label]); + $this->assertEquals($value, $labels[$label]); } } @@ -480,7 +480,7 @@ public function itShouldBeAbleToGenerateExponentialBucketsGivenSpecificBounds() 9.7309753417969, ]; - self::assertEquals($generatedBuckets, $expectedBuckets); + $this->assertEquals($generatedBuckets, $expectedBuckets); } /** From 65662f51094ddfe047f3bdc8cde08d25bd7af494 Mon Sep 17 00:00:00 2001 From: Martins Sipenko Date: Fri, 29 Nov 2019 14:25:20 +0200 Subject: [PATCH 28/28] Run CI on PHP version 7.4 (#25) --- .circleci/config.yml | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/.circleci/config.yml b/.circleci/config.yml index bcde4cf..2d1525e 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -61,6 +61,22 @@ unit-config: &unit-config version: 2.1 jobs: + php74: + <<: *unit-config + docker: + - image: circleci/php:7.4-cli-node + - image: circleci/redis:5-alpine + environment: + COMPOSER_PREFER_LOWEST: 0 + + php74-lowest: + <<: *unit-config + docker: + - image: circleci/php:7.4-cli-node + - image: circleci/redis:5-alpine + environment: + COMPOSER_PREFER_LOWEST: 1 + php73: <<: *unit-config docker: @@ -81,5 +97,7 @@ workflows: version: 2 units: jobs: + - php74 + - php74-lowest - php73 - php73-lowest