-
Notifications
You must be signed in to change notification settings - Fork 9
/
metrics_runtime.go
98 lines (85 loc) · 2.06 KB
/
metrics_runtime.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
90
91
92
93
94
95
96
97
98
package metrics
import (
"bufio"
"bytes"
"fmt"
"io"
"strings"
vm "github.com/VictoriaMetrics/metrics"
"github.com/safing/portbase/api"
"github.com/safing/portbase/config"
"github.com/safing/portbase/log"
)
func registerRuntimeMetric() error {
runtimeBase, err := newMetricBase("_runtime", nil, Options{
Name: "Golang Runtime",
Permission: api.PermitAdmin,
ExpertiseLevel: config.ExpertiseLevelDeveloper,
})
if err != nil {
return err
}
return register(&runtimeMetrics{
metricBase: runtimeBase,
})
}
type runtimeMetrics struct {
*metricBase
}
func (r *runtimeMetrics) WritePrometheus(w io.Writer) {
// If there nothing to change, just write directly to w.
if metricNamespace == "" && len(globalLabels) == 0 {
vm.WriteProcessMetrics(w)
return
}
// Write metrics to buffer.
buf := new(bytes.Buffer)
vm.WriteProcessMetrics(buf)
// Add namespace and label per line.
scanner := bufio.NewScanner(buf)
scanner.Split(bufio.ScanLines)
for scanner.Scan() {
line := scanner.Text()
// Add namespace, if set.
if metricNamespace != "" {
line = metricNamespace + "_" + line
}
// Add global labels, if set.
if len(globalLabels) > 0 {
// Find where to insert.
mergeWithExisting := true
insertAt := strings.Index(line, "{") + 1
if insertAt <= 0 {
mergeWithExisting = false
insertAt = strings.Index(line, " ")
if insertAt < 0 {
continue
}
}
// Write new line directly to w.
fmt.Fprint(w, line[:insertAt])
if !mergeWithExisting {
fmt.Fprint(w, "{")
}
labelsAdded := 0
for labelKey, labelValue := range globalLabels {
fmt.Fprintf(w, "%s=%q", labelKey, labelValue)
// Add separator if not last label.
labelsAdded++
if labelsAdded < len(globalLabels) {
fmt.Fprint(w, ", ")
}
}
if mergeWithExisting {
fmt.Fprint(w, ", ")
} else {
fmt.Fprint(w, "}")
}
fmt.Fprintln(w, line[insertAt:])
}
}
// Check if there was an error in the scanner.
if scanner.Err() != nil {
log.Warningf("metrics: failed to scan go process metrics: %s", scanner.Err())
}
}