-
Notifications
You must be signed in to change notification settings - Fork 101
/
Copy pathRenderTextFormat.php
81 lines (68 loc) · 2.42 KB
/
RenderTextFormat.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<?php
declare(strict_types=1);
namespace Prometheus;
use RuntimeException;
class RenderTextFormat implements RendererInterface
{
const MIME_TYPE = 'text/plain; version=0.0.4';
/**
* @param MetricFamilySamples[] $metrics
* @return string
*/
public function render(array $metrics): string
{
usort($metrics, function (MetricFamilySamples $a, MetricFamilySamples $b): int {
return strcmp($a->getName(), $b->getName());
});
$lines = [];
foreach ($metrics as $metric) {
$lines[] = "# HELP " . $metric->getName() . " {$metric->getHelp()}";
$lines[] = "# TYPE " . $metric->getName() . " {$metric->getType()}";
foreach ($metric->getSamples() as $sample) {
$lines[] = $this->renderSample($metric, $sample);
}
}
return implode("\n", $lines) . "\n";
}
/**
* @param MetricFamilySamples $metric
* @param Sample $sample
* @return string
*/
private function renderSample(MetricFamilySamples $metric, Sample $sample): string
{
$labelNames = $metric->getLabelNames();
if ($metric->hasLabelNames() || $sample->hasLabelNames()) {
$escapedLabels = $this->escapeAllLabels($metric, $labelNames, $sample);
return $sample->getName() . '{' . implode(',', $escapedLabels) . '} ' . $sample->getValue();
}
return $sample->getName() . ' ' . $sample->getValue();
}
/**
* @param string $v
* @return string
*/
private function escapeLabelValue(string $v): string
{
return str_replace(["\\", "\n", "\""], ["\\\\", "\\n", "\\\""], $v);
}
/**
* @param MetricFamilySamples $metric
* @param string[] $labelNames
* @param Sample $sample
*
* @return string[]
*/
private function escapeAllLabels(MetricFamilySamples $metric, array $labelNames, Sample $sample): array
{
$escapedLabels = [];
$labels = array_combine(array_merge($labelNames, $sample->getLabelNames()), $sample->getLabelValues());
if ($labels === false) {
throw new RuntimeException('Unable to combine labels for metric named ' . $metric->getName());
}
foreach ($labels as $labelName => $labelValue) {
$escapedLabels[] = $labelName . '="' . $this->escapeLabelValue((string)$labelValue) . '"';
}
return $escapedLabels;
}
}