/
metric_export.go
89 lines (74 loc) · 1.81 KB
/
metric_export.go
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
package metrics
import (
"github.com/safing/portbase/api"
)
// UIntMetric is an interface for special functions of uint metrics.
type UIntMetric interface {
CurrentValue() uint64
}
// FloatMetric is an interface for special functions of float metrics.
type FloatMetric interface {
CurrentValue() float64
}
// MetricExport is used to export a metric and its current value.
type MetricExport struct {
Metric
CurrentValue any
}
// ExportMetrics exports all registered metrics.
func ExportMetrics(requestPermission api.Permission) []*MetricExport {
registryLock.RLock()
defer registryLock.RUnlock()
export := make([]*MetricExport, 0, len(registry))
for _, metric := range registry {
// Check permission.
if requestPermission < metric.Opts().Permission {
continue
}
// Add metric with current value.
export = append(export, &MetricExport{
Metric: metric,
CurrentValue: getCurrentValue(metric),
})
}
return export
}
// ExportValues exports the values of all supported metrics.
func ExportValues(requestPermission api.Permission, internalOnly bool) map[string]any {
registryLock.RLock()
defer registryLock.RUnlock()
export := make(map[string]any, len(registry))
for _, metric := range registry {
// Check permission.
if requestPermission < metric.Opts().Permission {
continue
}
// Get Value.
v := getCurrentValue(metric)
if v == nil {
continue
}
// Get ID.
var id string
switch {
case metric.Opts().InternalID != "":
id = metric.Opts().InternalID
case internalOnly:
continue
default:
id = metric.LabeledID()
}
// Add to export
export[id] = v
}
return export
}
func getCurrentValue(metric Metric) any {
if m, ok := metric.(UIntMetric); ok {
return m.CurrentValue()
}
if m, ok := metric.(FloatMetric); ok {
return m.CurrentValue()
}
return nil
}