Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow timestamp in metric samples #64

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions src/Prometheus/CollectorRegistry.php
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,8 @@ public function registerHistogram(
string $name,
string $help,
array $labels = [],
array $buckets = null
array $buckets = null,
?int $timestamp = null
): Histogram {
$metricIdentifier = self::metricIdentifier($namespace, $name);
if (isset($this->histograms[$metricIdentifier])) {
Expand All @@ -218,7 +219,8 @@ public function registerHistogram(
$name,
$help,
$labels,
$buckets
$buckets,
$timestamp
);
return $this->histograms[$metricIdentifier];
}
Expand Down Expand Up @@ -254,12 +256,13 @@ public function getOrRegisterHistogram(
string $name,
string $help,
array $labels = [],
array $buckets = null
array $buckets = null,
?int $timestamp = null
): Histogram {
try {
$histogram = $this->getHistogram($namespace, $name);
} catch (MetricNotFoundException $e) {
$histogram = $this->registerHistogram($namespace, $name, $help, $labels, $buckets);
$histogram = $this->registerHistogram($namespace, $name, $help, $labels, $buckets, $timestamp);
}
return $histogram;
}
Expand Down
7 changes: 4 additions & 3 deletions src/Prometheus/Counter.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,16 @@ public function getType(): string
/**
* @param string[] $labels e.g. ['status', 'opcode']
*/
public function inc(array $labels = []): void
public function inc(array $labels = [], ?int $timestamp = null): void
{
$this->incBy(1, $labels);
$this->incBy(1, $labels, $timestamp);
}

/**
* @param int|float $count e.g. 2
* @param mixed[] $labels e.g. ['status', 'opcode']
*/
public function incBy($count, array $labels = []): void
public function incBy($count, array $labels = [], ?int $timestamp = null): void
{
$this->assertLabelsAreDefinedCorrectly($labels);

Expand All @@ -41,6 +41,7 @@ public function incBy($count, array $labels = []): void
'type' => $this->getType(),
'labelNames' => $this->getLabelNames(),
'labelValues' => $labels,
'timestamp' => $timestamp,
'value' => $count,
'command' => is_float($count) ? Adapter::COMMAND_INCREMENT_FLOAT : Adapter::COMMAND_INCREMENT_INTEGER,
]
Expand Down
10 changes: 6 additions & 4 deletions src/Prometheus/Gauge.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ class Gauge extends Collector
* @param double $value e.g. 123
* @param string[] $labels e.g. ['status', 'opcode']
*/
public function set(float $value, array $labels = []): void
public function set(float $value, array $labels = [], ?int $timestamp = null): void
{
$this->assertLabelsAreDefinedCorrectly($labels);

Expand All @@ -26,6 +26,7 @@ public function set(float $value, array $labels = []): void
'labelNames' => $this->getLabelNames(),
'labelValues' => $labels,
'value' => $value,
'timestamp' => $timestamp,
'command' => Adapter::COMMAND_SET,
]
);
Expand All @@ -42,16 +43,16 @@ public function getType(): string
/**
* @param string[] $labels
*/
public function inc(array $labels = []): void
public function inc(array $labels = [], ?int $timestamp = null): void
{
$this->incBy(1, $labels);
$this->incBy(1, $labels, $timestamp);
}

/**
* @param int|float $value
* @param string[] $labels
*/
public function incBy($value, array $labels = []): void
public function incBy($value, array $labels = [], ?int $timestamp = null): void
{
$this->assertLabelsAreDefinedCorrectly($labels);

Expand All @@ -62,6 +63,7 @@ public function incBy($value, array $labels = []): void
'type' => $this->getType(),
'labelNames' => $this->getLabelNames(),
'labelValues' => $labels,
'timestamp' => $timestamp,
'value' => $value,
'command' => Adapter::COMMAND_INCREMENT_FLOAT,
]
Expand Down
2 changes: 1 addition & 1 deletion src/Prometheus/RegistryInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -111,5 +111,5 @@ public function getHistogram(string $namespace, string $name): Histogram;
* @return Histogram
* @throws MetricsRegistrationException
*/
public function getOrRegisterHistogram(string $namespace, string $name, string $help, array $labels = [], array $buckets = null): Histogram;
public function getOrRegisterHistogram(string $namespace, string $name, string $help, array $labels = [], array $buckets = null, ?int $timestamp = null): Histogram;
}
6 changes: 4 additions & 2 deletions src/Prometheus/RenderTextFormat.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,13 @@ public function render(array $metrics): string
private function renderSample(MetricFamilySamples $metric, Sample $sample): string
{
$labelNames = $metric->getLabelNames();
$timestamp = $sample->getTimestamp();
$timestampPart = $timestamp === null ? '' : ' ' . $timestamp;
if ($metric->hasLabelNames() || $sample->hasLabelNames()) {
$escapedLabels = $this->escapeAllLabels($labelNames, $sample);
return $sample->getName() . '{' . implode(',', $escapedLabels) . '} ' . $sample->getValue();
return $sample->getName() . '{' . implode(',', $escapedLabels) . '} ' . $sample->getValue() . $timestampPart;
}
return $sample->getName() . ' ' . $sample->getValue();
return $sample->getName() . ' ' . $sample->getValue() . $timestampPart;
}

/**
Expand Down
11 changes: 11 additions & 0 deletions src/Prometheus/Sample.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,11 @@ class Sample
*/
private $value;

/**
* @var int|null
*/
private $timestamp;

/**
* Sample constructor.
* @param mixed[] $data
Expand All @@ -36,6 +41,7 @@ public function __construct(array $data)
$this->labelNames = (array) $data['labelNames'];
$this->labelValues = (array) $data['labelValues'];
$this->value = $data['value'];
$this->timestamp = $data['timestamp'];
}

/**
Expand Down Expand Up @@ -70,6 +76,11 @@ public function getValue(): string
return (string) $this->value;
}

public function getTimestamp(): ?int
{
return $this->timestamp;
}

/**
* @return bool
*/
Expand Down
25 changes: 18 additions & 7 deletions src/Prometheus/Storage/InMemory.php
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ private function collectHistograms(): array
'labelNames' => ['le'],
'labelValues' => array_merge($decodedLabelValues, [$bucket]),
'value' => $acc,
'timestamp' => null,
];
} else {
$acc += $histogramBuckets[$labelValues][$bucket];
Expand All @@ -104,6 +105,7 @@ private function collectHistograms(): array
'labelNames' => ['le'],
'labelValues' => array_merge($decodedLabelValues, [$bucket]),
'value' => $acc,
'timestamp' => null,
];
}
}
Expand All @@ -114,6 +116,7 @@ private function collectHistograms(): array
'labelNames' => [],
'labelValues' => $decodedLabelValues,
'value' => $acc,
'timestamp' => null,
];

// Add the sum
Expand All @@ -122,6 +125,7 @@ private function collectHistograms(): array
'labelNames' => [],
'labelValues' => $decodedLabelValues,
'value' => $histogramBuckets[$labelValues]['sum'],
'timestamp' => null,
];
}
$histograms[] = new MetricFamilySamples($data);
Expand All @@ -145,14 +149,15 @@ private function internalCollect(array $metrics): array
'labelNames' => $metaData['labelNames'],
'samples' => [],
];
foreach ($metric['samples'] as $key => $value) {
foreach ($metric['samples'] as $key => [$value, $timestamp]) {
$parts = explode(':', $key);
$labelValues = $parts[2];
$data['samples'][] = [
'name' => $metaData['name'],
'labelNames' => [],
'labelValues' => $this->decodeLabelValues($labelValues),
'value' => $value,
'timestamp' => $timestamp,
];
}
$this->sortSamples($data['samples']);
Expand Down Expand Up @@ -212,12 +217,15 @@ public function updateGauge(array $data): void
];
}
if (array_key_exists($valueKey, $this->gauges[$metaKey]['samples']) === false) {
$this->gauges[$metaKey]['samples'][$valueKey] = 0;
$this->gauges[$metaKey]['samples'][$valueKey] = [0, $data['timestamp']];
}
if ($data['command'] === Adapter::COMMAND_SET) {
$this->gauges[$metaKey]['samples'][$valueKey] = $data['value'];
$this->gauges[$metaKey]['samples'][$valueKey] = [$data['value'], $data['timestamp']];
} else {
$this->gauges[$metaKey]['samples'][$valueKey] += $data['value'];
$this->gauges[$metaKey]['samples'][$valueKey] = [
$this->gauges[$metaKey]['samples'][$valueKey][0] + $data['value'],
$data['timestamp']
];
}
}

Expand All @@ -235,12 +243,15 @@ public function updateCounter(array $data): void
];
}
if (array_key_exists($valueKey, $this->counters[$metaKey]['samples']) === false) {
$this->counters[$metaKey]['samples'][$valueKey] = 0;
$this->counters[$metaKey]['samples'][$valueKey] = [0, $data['timestamp']];
}
if ($data['command'] === Adapter::COMMAND_SET) {
$this->counters[$metaKey]['samples'][$valueKey] = 0;
$this->counters[$metaKey]['samples'][$valueKey] = [0, $data['timestamp']];
} else {
$this->counters[$metaKey]['samples'][$valueKey] += $data['value'];
$this->counters[$metaKey]['samples'][$valueKey] = [
$this->counters[$metaKey]['samples'][$valueKey][0] + $data['value'],
$data['timestamp']
];
}
}

Expand Down
18 changes: 14 additions & 4 deletions tests/Test/Prometheus/RenderTextFormatTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,13 @@ private function buildSamples(): array
$registry = new CollectorRegistry(new InMemory(), false);
$registry->getOrRegisterCounter($namespace, 'counter', 'counter-help-text', ['label1', 'label2'])
->inc(['bob', 'al\ice']);
$registry->getOrRegisterGauge($namespace, 'gauge', 'counter-help-text', ['label1', 'label2'])
$registry->getOrRegisterCounter($namespace, 'counter_with_timestamp', 'counter-with-timestamp-help-text', ['label1', 'label2'])
->inc(['bob', 'al\ice'], 1395066363000);
$registry->getOrRegisterGauge($namespace, 'gauge', 'gauge-help-text', ['label1', 'label2'])
->inc(["bo\nb", 'ali\"ce']);
$registry->getOrRegisterHistogram($namespace, 'histogram', 'counter-help-text', ['label1', 'label2'], [0, 10, 100])
$registry->getOrRegisterGauge($namespace, 'gauge_with_timestamp', 'gauge-with-timestamp-help-text', ['label1', 'label2'])
->inc(["bo\nb", 'ali\"ce'], 1395066363000);
$registry->getOrRegisterHistogram($namespace, 'histogram', 'histogram-help-text', ['label1', 'label2'], [0, 10, 100])
->observe(5, ['bob', 'alice']);

return $registry->getMetricFamilySamples();
Expand All @@ -48,10 +52,16 @@ private function getExpectedOutput(): string
# HELP mynamespace_counter counter-help-text
# TYPE mynamespace_counter counter
mynamespace_counter{label1="bob",label2="al\\\\ice"} 1
# HELP mynamespace_gauge counter-help-text
# HELP mynamespace_counter_with_timestamp counter-with-timestamp-help-text
# TYPE mynamespace_counter_with_timestamp counter
mynamespace_counter_with_timestamp{label1="bob",label2="al\\\\ice"} 1 1395066363000
# HELP mynamespace_gauge gauge-help-text
# TYPE mynamespace_gauge gauge
mynamespace_gauge{label1="bo\\nb",label2="ali\\\\\"ce"} 1
# HELP mynamespace_histogram counter-help-text
# HELP mynamespace_gauge_with_timestamp gauge-with-timestamp-help-text
# TYPE mynamespace_gauge_with_timestamp gauge
mynamespace_gauge_with_timestamp{label1="bo\\nb",label2="ali\\\\\"ce"} 1 1395066363000
# HELP mynamespace_histogram histogram-help-text
# TYPE mynamespace_histogram histogram
mynamespace_histogram_bucket{label1="bob",label2="alice",le="0"} 0
mynamespace_histogram_bucket{label1="bob",label2="alice",le="10"} 1
Expand Down