-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmetrics.nim
1319 lines (1158 loc) · 39.9 KB
/
metrics.nim
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
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2019-2023 Status Research & Development GmbH
# Licensed and distributed under either of
# * MIT license: http://opensource.org/licenses/MIT
# * Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0
# at your option. This file may not be copied, modified, or distributed except according to those terms.
# The API is roughly based on the Prometheus client library recommendations:
# https://prometheus.io/docs/instrumenting/writing_clientlibs/
#
# The Prometheus text exposition format is also tightly coupled:
# https://prometheus.io/docs/instrumenting/exposition_formats/#text-based-format
{.push raises: [].}
when defined(metricsTest):
{.pragma: testOnly.}
else:
{.pragma: testOnly, deprecated: "slow helpers used for tests only".}
import std/[locks, monotimes, os, sets, tables, times]
when defined(metrics):
import std/[algorithm, hashes, strutils, sequtils], stew/ptrops, metrics/common
export tables # for custom collectors that need to work with the "Metrics" type
type
LabelKey = object
# Helper type to work around the lack of heterogenous key support in `Table`
data: seq[string]
refs: ptr UncheckedArray[string]
refslen: int
Metric* = object
name*: string
value*: float64
labels*: seq[string]
labelValues*: seq[string]
timestamp*: Time
MetricHandler* =
proc(
name: string,
value: float64,
labels: openArray[string] = [],
labelValues: openArray[string] = [],
timestamp: Time,
) {.gcsafe, raises: [].}
CollecorHandler* = proc(collector: Collector)
Collector* = ref object of RootObj
lock*: Lock
name*: string
help*: string
typ*: string
labels*: seq[string]
timestamp*: bool ## Whether or not we're collecting timestamps for this collector
creationThreadId*: int
sampleRate*: float # only used by StatsD counters
SimpleCollector* = ref object of Collector
metricKeys*: Table[LabelKey, int]
metrics*: seq[seq[Metric]]
IgnoredCollector* = object
Counter* = ref object of SimpleCollector
Gauge* = ref object of SimpleCollector
Summary* = ref object of SimpleCollector
Histogram* = ref object of SimpleCollector # a cumulative histogram, not a regular one
buckets*: seq[float64]
Registry* = ref object of RootObj
lock*: Lock
collectors*: OrderedSet[Collector]
RegistrationError* = object of CatchableError
#########
# utils #
#########
when defined(metrics):
template values(key: LabelKey): openArray[string] =
if key.refslen > 0:
key.refs.toOpenArray(0, key.refslen - 1)
else:
key.data
proc hash(key: LabelKey): Hash =
hash(key.values)
proc `==`(a, b: LabelKey): bool =
a.values == b.values
proc init(T: type LabelKey, values: openArray[string]): T =
LabelKey(data: @values)
proc view(T: type LabelKey, values: openArray[string]): T =
# TODO some day, we might get view types - until then..
LabelKey(refs: baseAddr(values).makeUncheckedArray(), refslen: values.len())
proc toMilliseconds*(time: times.Time): int64 =
convert(Seconds, Milliseconds, time.toUnix()) +
convert(Nanoseconds, Milliseconds, time.nanosecond())
template nameOrIdentifier*(identifier: untyped, name: string): string =
if name.len == 0:
astToStr(identifier)
else:
name
proc processHelp(name, help: string): string =
"# HELP " & name & " " & help.multiReplace([("\\", "\\\\"), ("\n", "\\n")]) & "\n"
proc processType(name, typ: string): string =
"# TYPE " & name & " " & typ & "\n"
template processLabelValue(labelValue: string): string =
labelValue.multiReplace([("\\", "\\\\"), ("\n", "\\n"), ("\"", "\\\"")])
proc addText(
res: var string,
name: string,
value: float64,
labels, labelValues: openArray[string],
timestamp: Time,
) =
# A bit convoluted to mostly avoid pointless memory allocations - there's no
# (trivial) way however to append a float to an existing string
res.add name
if labels.len > 0:
res.add('{')
for i in 0..labels.high:
if i > 0:
res.add ","
res.add labels[i]
res.add "=\""
if labelValues.len > i:
res.add labelValues[i]
res.add "\""
res.add('}')
res.add(" ")
res.add($value)
if toMilliseconds(timestamp) > 0:
res.add(" " & $toMilliseconds(timestamp))
proc addText(res: var string, metric: Metric) =
addText(
res,
metric.name,
metric.value,
metric.labels,
metric.labelValues,
metric.timestamp,
)
proc `$`*(metric: Metric): string =
addText(result, metric)
const
nameRegexStr = r"^[a-zA-Z_:][a-zA-Z0-9_:]*$"
labelRegexStr = r"^[a-zA-Z_][a-zA-Z0-9_]*$"
labelStartChars = {'a'..'z', 'A'..'Z', '_'}
labelChars = labelStartChars + {'0'..'9'}
nameStartChars = labelStartChars + {':'}
nameChars = labelChars + {':'}
template validate(ident: string, startChars, chars: typed): bool =
ident.len > 0 and ident[0] in startChars and ident.allIt(it in chars)
proc validateName(name: string) {.raises: [ValueError].} =
if not validate(name, nameStartChars, nameChars):
raise newException(
ValueError,
"Invalid name: '" & name & "'. It should match the regex: " & nameRegexStr,
)
proc validateLabels(
labels: openArray[string], invalidLabelNames: openArray[string] = []
) {.raises: [ValueError].} =
for label in labels:
if not validate(label, labelStartChars, labelChars):
raise newException(
ValueError,
"Invalid label: '" & label & "'. It should match the regex: '" &
labelRegexStr & "'.",
)
if label.startsWith("__"):
raise newException(
ValueError, "Invalid label: '" & label & "'. It should not start with '__'."
)
if label in invalidLabelNames:
raise newException(
ValueError,
"Invalid label: '" & label & "'. It should not be one of: " &
$invalidLabelNames & ".",
)
######################
# generic collectors #
######################
when defined(metrics):
template withLabelValues(
collector: SimpleCollector,
labelValues: openArray[string],
metricSym, body, construct: untyped,
) =
if labelValues.len > 0 and labelValues.len != collector.labels.len:
printError(
"The number of label values doesn't match the number of labels: " &
collector.name
)
else:
withLock(collector.lock):
collector.metricKeys.withValue(LabelKey.view(labelValues), metricsIdx):
template metricSym(): untyped =
collector.metrics[metricsIdx[]]
body
do:
if collector.creationThreadId != getThreadId():
printError(
"New label values must be added from same thread as the metric was created from - observation dropped: " &
collector.name
)
else:
collector.metrics.add construct
collector.metricKeys[LabelKey.init(labelValues)] = collector.metrics.high
collector.metricKeys.withValue(LabelKey.view(labelValues), metricsIdx):
template metricSym(): untyped =
collector.metrics[metricsIdx[]]
body
method hash*(collector: Collector): Hash {.base.} =
result = result !& collector.name.hash
for label in collector.labels:
result = result !& label.hash
result = !$result
# `hash` and equals must match
method `==`*(x, y: Collector): bool {.base.} =
x.name == y.name and x.labels == y.labels
proc now*(collector: Collector): Time =
if collector.timestamp:
getTime()
else:
Time()
proc call(output: MetricHandler, metric: Metric) =
output(
metric.name, metric.value, metric.labels, metric.labelValues, metric.timestamp
)
method collect*(collector: Collector, output: MetricHandler) {.base.} =
discard
method collect*(collector: SimpleCollector, output: MetricHandler) =
{.warning[LockLevel]: off.}
withLock(collector.lock):
for key, idx in collector.metricKeys:
for metric in collector.metrics[idx]:
call(output, metric)
proc collect*(registry: Registry, output: MetricHandler) =
withLock registry.lock:
for collector in registry.collectors:
collector.collect(output)
proc addText(res: var string, collector: Collector) =
res.add collector.help
res.add collector.typ
let resPtr = addr res
proc addMetric(
name: string,
value: float64,
labels, labelValues: openArray[string],
timestamp: Time,
) =
addText(resPtr[], name, value, labels, labelValues, timestamp)
resPtr[].add "\n"
collect(collector, addMetric)
proc `$`*(collector: Collector): string =
addText(result, collector)
proc `$`*(collector: type IgnoredCollector): string =
""
when defined(metrics):
proc valueImpl*(
collector: Collector,
labelValuesParam: openArray[string] = [],
): float64 {.gcsafe, raises: [KeyError].} =
var res = NaN
# Don't access the "metrics" field directly, so we can support custom
# collectors.
{.gcsafe.}:
let lv = @labelValuesParam.mapIt(it.processLabelValue())
proc findMetric(
name: string,
value: float64,
labels, labelValues: openArray[string],
timestamp: Time) =
if res != res and labelValues == lv:
res = value
collect(collector, findMetric)
if res != res: # NaN
raise newException(
KeyError,
"No such metric for this collector (label values = " & $(@labelValuesParam) &
").",
)
res
template value*(
collector: Collector | type IgnoredCollector,
labelValuesParam: openArray[string] = [],
): float64 {.testOnly.} =
when defined(metrics) and collector is not IgnoredCollector:
{.gcsafe.}:
valueImpl(collector, labelValuesParam)
else:
0.0'f64
proc valueByNameInternal*(
collector: Collector | type IgnoredCollector,
metricName: string,
labelValues: openArray[string] = [],
extraLabelValues: openArray[string] = [],
): float64 {.raises: [ValueError].} =
when defined(metrics) and collector is not IgnoredCollector:
var res = NaN
let allLabelValues = labelValues.mapIt(it.processLabelValue()) & @extraLabelValues
proc findMetric(
name: string,
value: float64,
labels, labelValues: openArray[string],
timestamp: Time,
) =
if res != res and name == metricName and labelValues == allLabelValues:
res = value
collect(collector, findMetric)
if res == res:
return res
raise newException(
KeyError,
"No such metric name for this collector: '" & metricName & "' (label values = " &
$allLabelValues & ").",
)
template valueByName*(
collector: Collector | type IgnoredCollector,
metricName: string,
labelValues: openArray[string] = [],
extraLabelValues: openArray[string] = [],
): float64 {.testOnly.} =
{.gcsafe.}:
valueByNameInternal(collector, metricName, labelValues, extraLabelValues)
############
# registry #
############
proc newRegistry*(): Registry =
when defined(metrics):
new(result)
result.lock.initLock()
# needs to be {.global.} because of the alternative API's usage of {.global.} collector vars
let defaultRegistry* {.global.} = newRegistry()
# We use a generic type here in order to avoid the hidden type casting of
# Collector child types to the parent type.
proc register*[T](
collector: T, registry = defaultRegistry
) {.raises: [RegistrationError].} =
when defined(metrics):
withLock registry.lock:
if collector in registry.collectors:
raise newException(
RegistrationError, "Collector already registered: " & collector.name
)
registry.collectors.incl(collector)
proc unregister*[T](
collector: T, registry = defaultRegistry
) {.raises: [RegistrationError].} =
when defined(metrics) and collector is not IgnoredCollector:
withLock registry.lock:
if collector notin registry.collectors:
raise newException(RegistrationError, "Collector not registered.")
registry.collectors.excl(collector)
proc unregister*(collector: type IgnoredCollector, registry = defaultRegistry) =
discard
proc len(registry: Registry): int =
when defined(metrics):
withLock registry.lock:
return registry.collectors.len()
else:
0
proc addText(res: var string, registry: Registry) =
when defined(metrics):
withLock registry.lock:
for collector in registry.collectors:
res.addText(collector)
res.add("\n")
proc toText*(registry: Registry): string =
result = newStringOfCap(registry.len() * 64)
result.addText(registry)
proc `$`*(registry: Registry): string =
addText(result, registry)
#####################
# custom collectors #
#####################
when defined(metrics):
# Used for custom collectors, to shield the API user from having to deal with
# internal details like lock initialisation.
# Also used internally, for creating standard collectors, to avoid code
# duplication.
proc newCollector*[T](
typ: typedesc[T],
name: string,
help: string,
labels: openArray[string] = [],
registry = defaultRegistry,
standardType = "gauge",
timestamp = false,
): T {.raises: [ValueError, RegistrationError].} =
validateName(name)
validateLabels(labels)
result =
T(
name: name,
help: processHelp(name, help),
typ: processType(name, standardType),
# Prometheus does not support a non-standard value here
labels: @labels,
creationThreadId: getThreadId(),
timestamp: timestamp,
)
result.lock.initLock()
result.register(registry)
#####################
# push metrics hook #
#####################
when defined(metrics):
var
metricsExportHook*:
proc(
name: string,
value: float64,
increment: float64,
metricType: string,
timestamp: Time,
sampleRate: float,
) {.nimcall, gcsafe, raises: [].} = nil
proc updateSystemMetrics*() {.gcsafe.} # defined later in this file
var systemMetricsAutomaticUpdate = true
# whether to piggy-back on changes of user-defined metrics
proc getSystemMetricsAutomaticUpdate*(): bool =
systemMetricsAutomaticUpdate
proc setSystemMetricsAutomaticUpdate*(value: bool) =
systemMetricsAutomaticUpdate = value
proc pushMetrics*(
name: string,
value: float64,
increment = 0.float64,
metricType: string,
timestamp: Time,
sampleRate = 1.float,
doUpdateSystemMetrics = true,
) {.raises: [].} =
# this may run from different threads
if systemMetricsAutomaticUpdate and doUpdateSystemMetrics:
updateSystemMetrics()
if metricsExportHook == nil:
# no backends configured
return
metricsExportHook(name, value, increment, metricType, timestamp, sampleRate)
###########
# counter #
###########
when defined(metrics):
proc newCounterMetrics(
name: string, labels, labelValues: openArray[string]
): seq[Metric] =
let labelValues = labelValues.mapIt(it.processLabelValue())
@[
Metric(name: name & "_total", labels: @labels, labelValues: labelValues),
Metric(
name: name & "_created",
labels: @labels,
labelValues: labelValues,
value: getTime().toUnix().float64,
)
]
# don't document this one, even if we're forced to make it public, because it
# won't work when all (or some) collectors are disabled
proc newCounter*(
name: string,
help: string,
labels: openArray[string] = [],
registry = defaultRegistry,
sampleRate = 1.float,
timestamp = false,
): Counter {.raises: [ValueError, RegistrationError].} =
result = Counter.newCollector(name, help, labels, registry, "counter", timestamp)
result.sampleRate = sampleRate
if labels.len == 0:
result.metrics.add newCounterMetrics(name, labels, labels)
result.metricKeys[LabelKey.init(labels)] = result.metrics.high()
proc incCounter(counter: Counter, amount: float64, labelValues: openArray[string]) =
if amount < 0:
printError(
"Counter.inc() cannot be used with negative amounts: " & $counter.name & "=" &
$amount
)
return
let timestamp = counter.now()
withLabelValues(counter, labelValues, valueSym):
valueSym[0].value += amount
valueSym[0].timestamp = timestamp
pushMetrics(
name = counter.name,
value = valueSym[0].value,
increment = amount,
metricType = "c",
timestamp = timestamp,
sampleRate = counter.sampleRate,
)
do:
newCounterMetrics(counter.name, counter.labels, labelValues)
template declareCounter*(
identifier: untyped,
help: static string,
labels: openArray[string] = [],
registry = defaultRegistry,
sampleRate = 1.float,
name = "",
timestamp = false,
) {.dirty.} =
# fine-grained collector disabling will go in here, turning disabled
# collectors into type aliases for IgnoredCollector
when defined(metrics):
let
identifier =
newCounter(
nameOrIdentifier(identifier, name),
help,
labels,
registry,
sampleRate,
timestamp,
)
else:
type identifier = IgnoredCollector
template declarePublicCounter*(
identifier: untyped,
help: static string,
labels: openArray[string] = [],
registry = defaultRegistry,
sampleRate = 1.float,
name = "",
timestamp = false,
) {.dirty.} =
when defined(metrics):
let
identifier* =
newCounter(
nameOrIdentifier(identifier, name),
help,
labels,
registry,
sampleRate,
timestamp,
)
else:
type identifier* = IgnoredCollector
#- alternative API (without support for custom help strings, labels or custom registries)
#- different collector types with the same names are allowed
#- don't mark this proc as {.inline.} because it's incompatible with {.global.}: https://github.com/status-im/nim-metrics/pull/5#discussion_r304687474
when defined(metrics):
proc counter*(
name: static string
): Counter {.raises: [ValueError, RegistrationError].} =
# This {.global.} var assignment is lifted from the procedure and placed in a
# special module init section that's guaranteed to run only once per program.
# Calls to this proc will just return the globally initialised variable.
var res {.global.} = newCounter(name, "")
return res
else:
template counter*(name: static string): untyped =
IgnoredCollector
template inc*(
counter: Counter | type IgnoredCollector,
amount: int64 | float64 = 1,
labelValues: openArray[string] = [],
) =
when defined(metrics) and counter is not IgnoredCollector:
{.gcsafe.}:
incCounter(counter, amount.float64, labelValues)
template countExceptions*(
counter: Counter | type IgnoredCollector,
typ: typedesc,
labelValues: openArray[string],
body: untyped,
) =
when defined(metrics) and counter is not IgnoredCollector:
try:
body
except typ as exc:
counter.inc(1, labelValues)
raise exc
else:
body
template countExceptions*(
counter: Counter | type IgnoredCollector, typ: typedesc, body: untyped
) =
when defined(metrics) and counter is not IgnoredCollector:
counter.countExceptions(typ, []):
body
else:
body
template countExceptions*(
counter: Counter | type IgnoredCollector,
labelValues: openArray[string],
body: untyped,
) =
countExceptions(counter, Exception, labelValues, body)
template countExceptions*(counter: Counter | type IgnoredCollector, body: untyped) =
when defined(metrics) and counter is not IgnoredCollector:
counter.countExceptions([]):
body
else:
body
#########
# gauge #
#########
when defined(metrics):
proc newGaugeMetrics(
name: string, labels, labelValues: openArray[string]
): seq[Metric] =
let labelValues = labelValues.mapIt(it.processLabelValue())
result =
@[
Metric(name: name, labels: @labels, labelValues: labelValues),
Metric(
name: name & "_created",
labels: @labels,
labelValues: labelValues,
value: getTime().toUnix().float64,
)
]
proc newGauge*(
name: string,
help: string,
labels: openArray[string] = [],
registry = defaultRegistry,
timestamp = false,
): Gauge {.raises: [ValueError, RegistrationError].} =
result = Gauge.newCollector(name, help, labels, registry, "gauge", timestamp)
if labels.len == 0:
result.metrics.add newGaugeMetrics(name, labels, labels)
result.metricKeys[LabelKey.init(labels)] = result.metrics.high()
proc incGauge(gauge: Gauge, amount: float64, labelValues: openArray[string]) =
let timestamp = gauge.now()
withLabelValues(gauge, labelValues, valueSym):
valueSym[0].value += amount
valueSym[0].timestamp = timestamp
pushMetrics(
name = gauge.name,
value = valueSym[0].value,
metricType = "g",
timestamp = timestamp,
)
do:
newGaugeMetrics(gauge.name, gauge.labels, labelValues)
proc setGauge(
gauge: Gauge,
value: float64,
labelValues: openArray[string],
doUpdateSystemMetrics: bool,
) =
let timestamp = gauge.now()
withLabelValues(gauge, labelValues, valueSym):
valueSym[0].value = value.float64
if gauge.timestamp:
valueSym[0].timestamp = getTime()
pushMetrics(
name = gauge.name,
value = value.float64,
metricType = "g",
timestamp = timestamp,
doUpdateSystemMetrics = doUpdateSystemMetrics,
)
do:
newGaugeMetrics(gauge.name, gauge.labels, labelValues)
template declareGauge*(
identifier: untyped,
help: static string,
labels: openArray[string] = [],
registry = defaultRegistry,
name = "",
timestamp = false,
) {.dirty.} =
when defined(metrics):
var
identifier =
newGauge(nameOrIdentifier(identifier, name), help, labels, registry, timestamp)
else:
type identifier = IgnoredCollector
# alternative API
when defined(metrics):
proc gauge*(name: static string): Gauge {.raises: [ValueError, RegistrationError].} =
var res {.global.} = newGauge(name, "") # lifted line
return res
else:
template gauge*(name: static string): untyped =
IgnoredCollector
template declarePublicGauge*(
identifier: untyped,
help: static string,
labels: openArray[string] = [],
registry = defaultRegistry,
name = "",
timestamp = false,
) {.dirty.} =
when defined(metrics):
var
identifier* =
newGauge(nameOrIdentifier(identifier, name), help, labels, registry, timestamp)
else:
type identifier* = IgnoredCollector
# the "type IgnoredCollector" case is covered by Counter.inc()
template inc*(
gauge: Gauge, amount: int64 | float64 = 1, labelValues: openArray[string] = []
) =
when defined(metrics):
{.gcsafe.}:
incGauge(gauge, amount.float64, labelValues)
template dec*(
gauge: Gauge | type IgnoredCollector,
amount: int64 | float64 = 1,
labelValues: openArray[string] = [],
) =
when defined(metrics) and gauge is not IgnoredCollector:
inc(gauge, -amount, labelValues)
template set*(
gauge: Gauge | type IgnoredCollector,
value: int64 | float64,
labelValues: openArray[string] = [],
doUpdateSystemMetrics = true,
) =
when defined(metrics) and gauge is not IgnoredCollector:
{.gcsafe.}:
setGauge(gauge, value.float64, labelValues, doUpdateSystemMetrics)
# in seconds
proc setToCurrentTime*(
gauge: Gauge | type IgnoredCollector, labelValues: openArray[string] = []
) =
when defined(metrics) and gauge is not IgnoredCollector:
gauge.set(getTime().toUnix(), labelValues)
template trackInProgress*(
gauge: Gauge | type IgnoredCollector, labelValues: openArray[string], body: untyped
) =
when defined(metrics) and gauge is not IgnoredCollector:
gauge.inc(1, labelValues)
body
gauge.dec(1, labelValues)
else:
body
template trackInProgress*(gauge: Gauge | type IgnoredCollector, body: untyped) =
when defined(metrics) and gauge is not IgnoredCollector:
gauge.trackInProgress([]):
body
else:
body
# in seconds
template time*(
gauge: Gauge | type IgnoredCollector, labelValues: openArray[string], body: untyped
) =
when defined(metrics) and gauge is not IgnoredCollector:
let start = times.toUnix(getTime())
body
gauge.set(times.toUnix(getTime()) - start, labelValues)
else:
body
template time*(
collector: Gauge | Summary | Histogram | type IgnoredCollector, body: untyped
) =
when defined(metrics) and collector is not IgnoredCollector:
collector.time([]):
body
else:
body
###########
# summary #
###########
when defined(metrics):
proc newSummaryMetrics(
name: string, labels, labelValues: openArray[string]
): seq[Metric] =
let labelValues = labelValues.mapIt(it.processLabelValue())
@[
Metric(name: name & "_sum", labels: @labels, labelValues: labelValues),
Metric(name: name & "_count", labels: @labels, labelValues: labelValues),
Metric(
name: name & "_created",
labels: @labels,
labelValues: labelValues,
value: getTime().toUnix().float64,
)
]
proc newSummary*(
name: string,
help: string,
labels: openArray[string] = [],
registry = defaultRegistry,
timestamp = false,
): Summary {.raises: [ValueError, RegistrationError].} =
validateLabels(labels, invalidLabelNames = ["quantile"])
result = Summary.newCollector(name, help, labels, registry, "summary", timestamp)
if labels.len == 0:
result.metrics.add newSummaryMetrics(name, labels, labels)
result.metricKeys[LabelKey.init(labels)] = result.metrics.high()
proc observeSummary(summary: Summary, amount: float64, labelValues: openArray[string]) =
let timestamp = summary.now()
withLabelValues(summary, labelValues, valueSym):
valueSym[0].value += amount # _sum
valueSym[0].timestamp = timestamp
valueSym[1].value += 1.float64 # _count
valueSym[1].timestamp = timestamp
do:
newSummaryMetrics(summary.name, summary.labels, labelValues)
template declareSummary*(
identifier: untyped,
help: static string,
labels: openArray[string] = [],
registry = defaultRegistry,
name = "",
) {.dirty.} =
when defined(metrics):
let
identifier =
newSummary(nameOrIdentifier(identifier, name), help, labels, registry)
else:
type identifier = IgnoredCollector
template declarePublicSummary*(
identifier: untyped,
help: static string,
labels: openArray[string] = [],
registry = defaultRegistry,
name = "",
) {.dirty.} =
when defined(metrics):
let
identifier* =
newSummary(nameOrIdentifier(identifier, name), help, labels, registry)
else:
type identifier* = IgnoredCollector
when defined(metrics):
proc summary*(
name: static string
): Summary {.raises: [ValueError, RegistrationError].} =
var res {.global.} = newSummary(name, "") # lifted line
return res
else:
template summary*(name: static string): untyped =
IgnoredCollector
template observe*(
summary: Summary | type IgnoredCollector,
amount: int64 | float64 = 1,
labelValues: openArray[string] = [],
) =
when defined(metrics) and summary is not IgnoredCollector:
{.gcsafe.}:
observeSummary(summary, amount.float64, labelValues)
# in seconds
# the "type IgnoredCollector" case and the version without labels are covered by Gauge.time()
template time*(
collector: Summary | Histogram, labelValues: openArray[string], body: untyped
) =
when defined(metrics):
let start = times.toUnix(getTime())
body
collector.observe(times.toUnix(getTime()) - start, labelValues)
else:
body
#############
# histogram #
#############
const
defaultHistogramBuckets* = [
0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1.0, 2.5, 5.0, 7.5, 10.0, Inf
]
when defined(metrics):
proc newHistogramMetrics(
name: string, labels, labelValues: openArray[string], buckets: seq[float64]
): seq[Metric] =
let labelValues = labelValues.mapIt(it.processLabelValue())
result =
@[
Metric(name: name & "_sum", labels: @labels, labelValues: labelValues),
Metric(name: name & "_count", labels: @labels, labelValues: labelValues),
Metric(
name: name & "_created",
labels: @labels,
labelValues: labelValues,
value: getTime().toUnix().float64,
)
]
var bucketLabels = @labels & "le"
for bucket in buckets:
var bucketStr = $bucket
if bucket == Inf:
bucketStr = "+Inf"
result.add(
Metric(
name: name & "_bucket",
labels: bucketLabels,
labelValues: labelValues & bucketStr,
)
)