-
Notifications
You must be signed in to change notification settings - Fork 96
/
APCng.php
803 lines (744 loc) · 30.4 KB
/
APCng.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
<?php
declare(strict_types=1);
namespace Prometheus\Storage;
use APCUIterator;
use Prometheus\Exception\StorageException;
use Prometheus\Math;
use Prometheus\MetricFamilySamples;
use RuntimeException;
class APCng implements Adapter
{
/** @var string Default prefix to use for APCu keys. */
const PROMETHEUS_PREFIX = 'prom';
/** @var int Number of retries before we give on apcu_cas(). This can prevent an infinite-loop if we fill up APCu. */
const CAS_LOOP_RETRIES = 2000;
/** @var int Number of seconds for cache object to live in APCu. When new metrics are created by other threads, this is the maximum delay until they are discovered.
Setting this to a value less than 1 will disable the cache, which will negatively impact performance when making multiple collect*() function-calls.
If more than a few thousand metrics are being tracked, disabling cache will be faster, due to apcu_store/fetch serialization being slow. */
private $metainfoCacheTTL = 1;
/** @var string APCu key where array of all discovered+created metainfo keys is stored */
private $metainfoCacheKey;
/** @var string Prefix to use for APCu keys. */
private $prometheusPrefix;
/**
* APCng constructor.
*
* @param string $prometheusPrefix Prefix for APCu keys (defaults to {@see PROMETHEUS_PREFIX}).
*
* @throws StorageException
*/
public function __construct(string $prometheusPrefix = self::PROMETHEUS_PREFIX)
{
if (!extension_loaded('apcu')) {
throw new StorageException('APCu extension is not loaded');
}
if (!apcu_enabled()) {
throw new StorageException('APCu is not enabled');
}
$this->prometheusPrefix = $prometheusPrefix;
$this->metainfoCacheKey = implode(':', [ $this->prometheusPrefix, 'metainfocache' ]);
}
/**
* @return MetricFamilySamples[]
*/
public function collect(): array
{
$metrics = $this->collectHistograms();
$metrics = array_merge($metrics, $this->collectGauges());
$metrics = array_merge($metrics, $this->collectCounters());
$metrics = array_merge($metrics, $this->collectSummaries());
return $metrics;
}
/**
* @param mixed[] $data
* @throws RuntimeException
*/
public function updateHistogram(array $data): void
{
// Initialize or atomically increment the sum
// Taken from https://github.com/prometheus/client_golang/blob/66058aac3a83021948e5fb12f1f408ff556b9037/prometheus/value.go#L91
$sumKey = $this->histogramBucketValueKey($data, 'sum');
$done = false;
$loopCatcher = self::CAS_LOOP_RETRIES;
while (!$done && $loopCatcher-- > 0) {
$old = apcu_fetch($sumKey);
if ($old !== false) {
$done = apcu_cas($sumKey, $old, $this->toBinaryRepresentationAsInteger($this->fromBinaryRepresentationAsInteger($old) + $data['value']));
} else {
// If sum does not exist, initialize it, store the metadata for the new histogram
apcu_add($sumKey, $this->toBinaryRepresentationAsInteger(0));
apcu_store($this->metaKey($data), json_encode($this->metaData($data)));
$this->storeLabelKeys($data);
}
}
if ($loopCatcher <= 0) {
throw new RuntimeException('Caught possible infinite loop in ' . __METHOD__ . '()');
}
// Figure out in which bucket the observation belongs
$bucketToIncrease = '+Inf';
foreach ($data['buckets'] as $bucket) {
if ($data['value'] <= $bucket) {
$bucketToIncrease = $bucket;
break;
}
}
// Initialize and increment the bucket
apcu_add($this->histogramBucketValueKey($data, $bucketToIncrease), 0);
apcu_inc($this->histogramBucketValueKey($data, $bucketToIncrease));
}
/**
* For each second, store an incrementing counter which points to each individual observation, like this:
* prom:bla..blabla:value:16781560:observations = 199
* Then we know that for the 1-second period at unix timestamp 16781560, 199 observations are stored, and they can
* be retrieved using APC keynames "prom:...:16781560.0" thorough "prom:...:16781560.198"
* We can deterministically calculate the intervening timestamps by subtracting maxAge, to get a range of seconds
* when generating a summary, e.g. 16781560 back to 16780960 for a 600sec maxAge. Then collect observation counts
* for each second, programmatically generate the APC keys for each individual observation, and we're able to avoid
* performing a full APC key scan, which can block for several seconds if APCu contains a few million keys.
*
* @param mixed[] $data
* @throws RuntimeException
*/
public function updateSummary(array $data): void
{
// store value key; store metadata & labels if new
$valueKey = $this->valueKey($data);
$new = apcu_add($valueKey, $this->encodeLabelValues($data['labelValues']));
if ($new) {
apcu_add($this->metaKey($data), $this->metaData($data));
$this->storeLabelKeys($data);
}
$sampleKeyPrefix = $valueKey . ':' . time();
$sampleCountKey = $sampleKeyPrefix . ':observations';
// Check if sample counter for this timestamp already exists, so we can deterministically store observations+counts, one key per second
// Atomic increment of the observation counter, or initialize if new
$done = false;
$loopCatcher = self::CAS_LOOP_RETRIES;
while (!$done && $loopCatcher-- > 0) {
$sampleCount = apcu_fetch($sampleCountKey);
if ($sampleCount !== false) {
$done = apcu_cas($sampleCountKey, $sampleCount, $sampleCount + 1);
} else {
apcu_add($sampleCountKey, 0, $data['maxAgeSeconds']);
}
}
if ($loopCatcher <= 0) {
throw new RuntimeException('Caught possible infinite loop in ' . __METHOD__ . '()');
}
// We now have a deterministic keyname for this observation; let's save the observed value
$sampleKey = $sampleKeyPrefix . '.' . $sampleCount;
apcu_add($sampleKey, $data['value'], $data['maxAgeSeconds']);
}
/**
* @param mixed[] $data
* @throws RuntimeException
*/
public function updateGauge(array $data): void
{
$valueKey = $this->valueKey($data);
if ($data['command'] === Adapter::COMMAND_SET) {
apcu_store($valueKey, $this->toBinaryRepresentationAsInteger($data['value']));
apcu_store($this->metaKey($data), json_encode($this->metaData($data)));
$this->storeLabelKeys($data);
} else {
// Taken from https://github.com/prometheus/client_golang/blob/66058aac3a83021948e5fb12f1f408ff556b9037/prometheus/value.go#L91
$done = false;
$loopCatcher = self::CAS_LOOP_RETRIES;
while (!$done && $loopCatcher-- > 0) {
$old = apcu_fetch($valueKey);
if ($old !== false) {
$done = apcu_cas($valueKey, $old, $this->toBinaryRepresentationAsInteger($this->fromBinaryRepresentationAsInteger($old) + $data['value']));
} else {
apcu_add($valueKey, $this->toBinaryRepresentationAsInteger(0));
apcu_store($this->metaKey($data), json_encode($this->metaData($data)));
$this->storeLabelKeys($data);
}
}
if ($loopCatcher <= 0) {
throw new RuntimeException('Caught possible infinite loop in ' . __METHOD__ . '()');
}
}
}
/**
* @param mixed[] $data
* @throws RuntimeException
*/
public function updateCounter(array $data): void
{
// Taken from https://github.com/prometheus/client_golang/blob/66058aac3a83021948e5fb12f1f408ff556b9037/prometheus/value.go#L91
$valueKey = $this->valueKey($data);
$done = false;
$loopCatcher = self::CAS_LOOP_RETRIES;
while (!$done && $loopCatcher-- > 0) {
$old = apcu_fetch($valueKey);
if ($old !== false) {
$done = apcu_cas($valueKey, $old, $this->toBinaryRepresentationAsInteger($this->fromBinaryRepresentationAsInteger($old) + $data['value']));
} else {
apcu_add($valueKey, 0);
apcu_store($this->metaKey($data), json_encode($this->metaData($data)));
$this->storeLabelKeys($data);
}
}
if ($loopCatcher <= 0) {
throw new RuntimeException('Caught possible infinite loop in ' . __METHOD__ . '()');
}
}
/**
* @param array<string> $metaData
* @param string $labels
* @return string
*/
private function assembleLabelKey(array $metaData, string $labels): string
{
return implode(':', [ $this->prometheusPrefix, $metaData['type'], $metaData['name'], $labels, 'label' ]);
}
/**
* Store ':label' keys for each metric's labelName in APCu.
*
* @param array<mixed> $data
* @return void
*/
private function storeLabelKeys(array $data): void
{
// Store labelValues in each labelName key
foreach ($data['labelNames'] as $seq => $label) {
$this->addItemToKey(implode(':', [
$this->prometheusPrefix,
$data['type'],
$data['name'],
$label,
'label'
]), isset($data['labelValues']) ? $data['labelValues'][$seq] : ''); // may not need the isset check
}
}
/**
* Ensures an array serialized into APCu contains exactly one copy of a given string
*
* @return void
* @throws RuntimeException
*/
private function addItemToKey(string $key, string $item): void
{
// Modify serialized array stored in $key
$arr = apcu_fetch($key);
if (false === $arr) {
$arr = [];
}
if (!array_key_exists($item, $arr)) {
$arr[$this->encodeLabelKey($item)] = 1;
apcu_store($key, $arr);
}
}
/**
* Removes all previously stored data from apcu
*
* NOTE: This is non-atomic: while it's iterating APCu, another thread could write a new Prometheus key that doesn't get erased.
* In case this happens, getMetas() calls scanAndBuildMetainfoCache before reading metainfo back: this will ensure "orphaned"
* metainfo gets enumerated.
*
* @return void
*/
public function wipeStorage(): void
{
// / / | PCRE expresion boundary
// ^ | match from first character only
// %s: | common prefix substitute with colon suffix
// .+ | at least one additional character
$matchAll = sprintf('/^%s:.+/', $this->prometheusPrefix);
foreach (new APCUIterator($matchAll) as $key => $value) {
apcu_delete($key);
}
}
/**
* Sets the metainfo cache TTL; how long to retain metainfo before scanning APCu keyspace again (default 1 second)
*
* @param int $ttl
* @return void
*/
public function setMetainfoTTL(int $ttl): void
{
$this->metainfoCacheTTL = $ttl;
}
/**
* Scans the APCu keyspace for all metainfo keys. A new metainfo cache array is built,
* which references all metadata keys in APCu at that moment. This prevents a corner-case
* where an orphaned key, while remaining writable, is rendered permanently invisible when reading
* or enumerating metrics.
*
* Writing the cache to APCu allows it to be shared by other threads and by subsequent calls to getMetas(). This
* reduces contention on APCu from repeated scans, and provides about a 2.5x speed-up when calling $this->collect().
* The cache TTL is very short (default: 1sec), so if new metrics are tracked after the cache is built, they will
* be readable at most 1 second after being written.
*
* Setting $apc_ttl less than 1 will disable the cache.
*
* @param int $apc_ttl
* @return array<string>
*/
private function scanAndBuildMetainfoCache(int $apc_ttl = 1): array
{
$arr = [];
$matchAllMeta = sprintf('/^%s:.*:meta/', $this->prometheusPrefix);
foreach (new APCUIterator($matchAllMeta) as $apc_record) {
$arr[] = $apc_record['key'];
}
if ($apc_ttl >= 1) {
apcu_store($this->metainfoCacheKey, $arr, $apc_ttl);
}
return $arr;
}
/**
* @param mixed[] $data
* @return string
*/
private function metaKey(array $data): string
{
return implode(':', [$this->prometheusPrefix, $data['type'], $data['name'], 'meta']);
}
/**
* @param mixed[] $data
* @return string
*/
private function valueKey(array $data): string
{
return implode(':', [
$this->prometheusPrefix,
$data['type'],
$data['name'],
$this->encodeLabelValues($data['labelValues']),
'value',
]);
}
/**
* @param mixed[] $data
* @param string|int $bucket
* @return string
*/
private function histogramBucketValueKey(array $data, $bucket): string
{
return implode(':', [
$this->prometheusPrefix,
$data['type'],
$data['name'],
$this->encodeLabelValues($data['labelValues']),
$bucket,
'value',
]);
}
/**
* @param mixed[] $data
* @return mixed[]
*/
private function metaData(array $data): array
{
$metricsMetaData = $data;
unset($metricsMetaData['value'], $metricsMetaData['command'], $metricsMetaData['labelValues']);
return $metricsMetaData;
}
/**
* When given a ragged 2D array $labelValues of arbitrary size, and a 1D array $labelNames containing one
* string labeling each row of $labelValues, return an array-of-arrays containing all possible permutations
* of labelValues, with the sub-array elements in order of labelName.
*
* Example input:
* $labelNames: ['endpoint', 'method', 'result']
* $labelValues: [0] => ['/', '/private', '/metrics'], // "endpoint"
* [1] => ['put', 'get', 'post'], // "method"
* [2] => ['success', 'fail'] // "result"
* Returned array:
* [0] => ['/', 'put', 'success'], [1] => ['/', 'put', 'fail'], [2] => ['/', 'get', 'success'],
* [3] => ['/', 'get', 'fail'], [4] => ['/', 'post', 'success'], [5] => ['/', 'post', 'fail'],
* [6] => ['/private', 'put', 'success'], [7] => ['/private', 'put', 'fail'], [8] => ['/private', 'get', 'success'],
* [9] => ['/private', 'get', 'fail'], [10] => ['/private', 'post', 'success'], [11] => ['/private', 'post', 'fail'],
* [12] => ['/metrics', 'put', 'success'], [13] => ['/metrics', 'put', 'fail'], [14] => ['/metrics', 'get', 'success'],
* [15] => ['/metrics', 'get', 'fail'], [16] => ['/metrics', 'post', 'success'], [17] => ['/metrics', 'post', 'fail']
* @param array<string> $labelNames
* @param array<array> $labelValues
* @return array<array>
*/
private function buildPermutationTree(array $labelNames, array $labelValues): array
{
$treeRowCount = count(array_keys($labelNames));
$numElements = 1;
$treeInfo = [];
for ($i = $treeRowCount - 1; $i >= 0; $i--) {
$treeInfo[$i]['numInRow'] = count($labelValues[$i]);
$numElements *= $treeInfo[$i]['numInRow'];
$treeInfo[$i]['numInTree'] = $numElements;
}
$map = array_fill(0, $numElements, []);
for ($row = 0; $row < $treeRowCount; $row++) {
$col = $i = 0;
while ($i < $numElements) {
$val = $labelValues[$row][$col];
$map[$i] = array_merge($map[$i], array($val));
if (++$i % ($treeInfo[$row]['numInTree'] / $treeInfo[$row]['numInRow']) == 0) {
$col = ++$col % $treeInfo[$row]['numInRow'];
}
}
}
return $map;
}
/**
* @return MetricFamilySamples[]
*/
private function collectCounters(): array
{
$counters = [];
foreach ($this->getMetas('counter') as $counter) {
$metaData = json_decode($counter['value'], true);
$data = [
'name' => $metaData['name'],
'help' => $metaData['help'],
'type' => $metaData['type'],
'labelNames' => $metaData['labelNames'],
'samples' => [],
];
foreach ($this->getValues('counter', $metaData) as $value) {
$parts = explode(':', $value['key']);
$labelValues = $parts[3];
$data['samples'][] = [
'name' => $metaData['name'],
'labelNames' => [],
'labelValues' => $this->decodeLabelValues($labelValues),
'value' => $this->fromBinaryRepresentationAsInteger($value['value']),
];
}
$this->sortSamples($data['samples']);
$counters[] = new MetricFamilySamples($data);
}
return $counters;
}
/**
* When given a type ('histogram', 'gauge', or 'counter'), return an iterable array of matching records retrieved from APCu
*
* @param string $type
* @return array<array>
*/
private function getMetas(string $type): array
{
$arr = [];
$metaCache = apcu_fetch($this->metainfoCacheKey);
if (!is_array($metaCache)) {
$metaCache = $this->scanAndBuildMetainfoCache($this->metainfoCacheTTL);
}
foreach ($metaCache as $metaKey) {
if ((1 === preg_match('/' . $this->prometheusPrefix . ':' . $type . ':.*:meta/', $metaKey)) && false !== ($gauge = apcu_fetch($metaKey))) {
$arr[] = [ 'key' => $metaKey, 'value' => $gauge ];
}
}
return $arr;
}
/**
* When given a type ('histogram', 'gauge', or 'counter') and metaData array, return an iterable array of matching records retrieved from APCu
*
* @param string $type
* @param array<mixed> $metaData
* @return array<array>
*/
private function getValues(string $type, array $metaData): array
{
$labels = $arr = [];
foreach (array_values($metaData['labelNames']) as $label) {
$labelKey = $this->assembleLabelKey($metaData, $label);
if (is_array($tmp = apcu_fetch($labelKey))) {
$labels[] = array_map([$this, 'decodeLabelKey'], array_keys($tmp));
}
}
// Append the histogram bucket-list and the histogram-specific label 'sum' to labels[] then generate the permutations
if (isset($metaData['buckets'])) {
$metaData['buckets'][] = 'sum';
$labels[] = $metaData['buckets'];
$metaData['labelNames'][] = '__histogram_buckets';
}
$labelValuesList = $this->buildPermutationTree($metaData['labelNames'], $labels);
unset($labels);
$histogramBucket = '';
foreach ($labelValuesList as $labelValues) {
// Extract bucket value from permuted element, if present, then construct the key and retrieve
if (isset($metaData['buckets'])) {
$histogramBucket = ':' . array_pop($labelValues);
}
$key = $this->prometheusPrefix . ":{$type}:{$metaData['name']}:" . $this->encodeLabelValues($labelValues) . $histogramBucket . ':value';
if (false !== ($value = apcu_fetch($key))) {
$arr[] = [ 'key' => $key, 'value' => $value ];
}
}
return $arr;
}
/**
* @return MetricFamilySamples[]
*/
private function collectGauges(): array
{
$gauges = [];
foreach ($this->getMetas('gauge') as $gauge) {
$metaData = json_decode($gauge['value'], true);
$data = [
'name' => $metaData['name'],
'help' => $metaData['help'],
'type' => $metaData['type'],
'labelNames' => $metaData['labelNames'],
'samples' => [],
];
foreach ($this->getValues('gauge', $metaData) as $value) {
$parts = explode(':', $value['key']);
$labelValues = $parts[3];
$data['samples'][] = [
'name' => $metaData['name'],
'labelNames' => [],
'labelValues' => $this->decodeLabelValues($labelValues),
'value' => $this->fromBinaryRepresentationAsInteger($value['value']),
];
}
$this->sortSamples($data['samples']);
$gauges[] = new MetricFamilySamples($data);
}
return $gauges;
}
/**
* @return MetricFamilySamples[]
*/
private function collectHistograms(): array
{
$histograms = [];
foreach ($this->getMetas('histogram') as $histogram) {
$metaData = json_decode($histogram['value'], true);
// Add the Inf bucket so we can compute it later on
$metaData['buckets'][] = '+Inf';
$data = [
'name' => $metaData['name'],
'help' => $metaData['help'],
'type' => $metaData['type'],
'labelNames' => $metaData['labelNames'],
'buckets' => $metaData['buckets'],
];
$histogramBuckets = [];
foreach ($this->getValues('histogram', $metaData) as $value) {
$parts = explode(':', $value['key']);
$labelValues = $parts[3];
$bucket = $parts[4];
// Key by labelValues
$histogramBuckets[$labelValues][$bucket] = $value['value'];
}
// Compute all buckets
$labels = array_keys($histogramBuckets);
sort($labels);
foreach ($labels as $labelValues) {
$acc = 0;
$decodedLabelValues = $this->decodeLabelValues($labelValues);
foreach ($data['buckets'] as $bucket) {
$bucket = (string)$bucket;
if (!isset($histogramBuckets[$labelValues][$bucket])) {
$data['samples'][] = [
'name' => $metaData['name'] . '_bucket',
'labelNames' => ['le'],
'labelValues' => array_merge($decodedLabelValues, [$bucket]),
'value' => $acc,
];
} else {
$acc += $histogramBuckets[$labelValues][$bucket];
$data['samples'][] = [
'name' => $metaData['name'] . '_' . 'bucket',
'labelNames' => ['le'],
'labelValues' => array_merge($decodedLabelValues, [$bucket]),
'value' => $acc,
];
}
}
// Add the count
$data['samples'][] = [
'name' => $metaData['name'] . '_count',
'labelNames' => [],
'labelValues' => $decodedLabelValues,
'value' => $acc,
];
// Add the sum
$data['samples'][] = [
'name' => $metaData['name'] . '_sum',
'labelNames' => [],
'labelValues' => $decodedLabelValues,
'value' => $this->fromBinaryRepresentationAsInteger($histogramBuckets[$labelValues]['sum']),
];
}
$histograms[] = new MetricFamilySamples($data);
}
return $histograms;
}
/**
* @return MetricFamilySamples[]
*/
private function collectSummaries(): array
{
$math = new Math();
$summaries = [];
foreach ($this->getMetas('summary') as $summary) {
$metaData = $summary['value'];
$data = [
'name' => $metaData['name'],
'help' => $metaData['help'],
'type' => $metaData['type'],
'labelNames' => $metaData['labelNames'],
'maxAgeSeconds' => $metaData['maxAgeSeconds'],
'quantiles' => $metaData['quantiles'],
'samples' => [],
];
foreach ($this->getValues('summary', $metaData) as $value) {
$encodedLabelValues = $value['value'];
$decodedLabelValues = $this->decodeLabelValues($encodedLabelValues);
$samples = [];
// Deterministically generate keys for all the sample observations, and retrieve them. Pass arrays to apcu_fetch to reduce calls to APCu.
$end = time();
$begin = $end - $metaData['maxAgeSeconds'];
$valueKeyPrefix = $this->valueKey(array_merge($metaData, ['labelValues' => $decodedLabelValues]));
$sampleCountKeysToRetrieve = [];
for ($ts = $begin; $ts <= $end; $ts++) {
$sampleCountKeysToRetrieve[] = $valueKeyPrefix . ':' . $ts . ':observations';
}
$sampleCounts = apcu_fetch($sampleCountKeysToRetrieve);
unset($sampleCountKeysToRetrieve);
if (is_array($sampleCounts)) {
foreach ($sampleCounts as $k => $sampleCountThisSecond) {
$tstamp = explode(':', $k)[5];
$sampleKeysToRetrieve = [];
for ($i = 0; $i < $sampleCountThisSecond; $i++) {
$sampleKeysToRetrieve[] = $valueKeyPrefix . ':' . $tstamp . '.' . $i;
}
$newSamples = apcu_fetch($sampleKeysToRetrieve);
unset($sampleKeysToRetrieve);
if (is_array($newSamples)) {
$samples = array_merge($samples, $newSamples);
}
}
}
unset($sampleCounts);
if (count($samples) === 0) {
apcu_delete($value['key']);
continue;
}
// Compute quantiles
sort($samples);
foreach ($data['quantiles'] as $quantile) {
$data['samples'][] = [
'name' => $metaData['name'],
'labelNames' => ['quantile'],
'labelValues' => array_merge($decodedLabelValues, [$quantile]),
'value' => $math->quantile($samples, $quantile),
];
}
// Add the count
$data['samples'][] = [
'name' => $metaData['name'] . '_count',
'labelNames' => [],
'labelValues' => $decodedLabelValues,
'value' => count($samples),
];
// Add the sum
$data['samples'][] = [
'name' => $metaData['name'] . '_sum',
'labelNames' => [],
'labelValues' => $decodedLabelValues,
'value' => array_sum($samples),
];
}
if (count($data['samples']) > 0) {
$summaries[] = new MetricFamilySamples($data);
} else {
apcu_delete($summary['key']);
}
}
return $summaries;
}
/**
* @param mixed $val
* @return int
* @throws RuntimeException
*/
private function toBinaryRepresentationAsInteger($val): int
{
$packedDouble = pack('d', $val);
if ((bool)$packedDouble !== false) {
$unpackedData = unpack("Q", $packedDouble);
if (is_array($unpackedData)) {
return $unpackedData[1];
}
}
throw new RuntimeException("Formatting from binary representation to integer did not work");
}
/**
* @param mixed $val
* @return float
* @throws RuntimeException
*/
private function fromBinaryRepresentationAsInteger($val): float
{
$packedBinary = pack('Q', $val);
if ((bool)$packedBinary !== false) {
$unpackedData = unpack("d", $packedBinary);
if (is_array($unpackedData)) {
return $unpackedData[1];
}
}
throw new RuntimeException("Formatting from integer to binary representation did not work");
}
/**
* @param mixed[] $samples
*/
private function sortSamples(array &$samples): void
{
usort($samples, function ($a, $b): int {
return strcmp(implode("", $a['labelValues']), implode("", $b['labelValues']));
});
}
/**
* @param mixed[] $values
* @return string
* @throws RuntimeException
*/
private function encodeLabelValues(array $values): string
{
$json = json_encode($values);
if (false === $json) {
throw new RuntimeException(json_last_error_msg());
}
return base64_encode($json);
}
/**
* @param string $values
* @return mixed[]
* @throws RuntimeException
*/
private function decodeLabelValues(string $values): array
{
$json = base64_decode($values, true);
if (false === $json) {
throw new RuntimeException('Cannot base64 decode label values');
}
$decodedValues = json_decode($json, true);
if (false === $decodedValues) {
throw new RuntimeException(json_last_error_msg());
}
return $decodedValues;
}
/**
* @param string $keyString
* @return string
*/
private function encodeLabelKey(string $keyString): string
{
return base64_encode($keyString);
}
/**
* @param string $str
* @return string
* @throws RuntimeException
*/
private function decodeLabelKey(string $str): string
{
$decodedKey = base64_decode($str, true);
if (false === $decodedKey) {
throw new RuntimeException('Cannot base64 decode label key');
}
return $decodedKey;
}
}