Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
aos
GitHub Repository: aos/grafana-agent
Path: blob/main/pkg/agentctl/cardinality.go
4094 views
1
package agentctl
2
3
import (
4
"github.com/prometheus/prometheus/tsdb/record"
5
"github.com/prometheus/prometheus/tsdb/wlog"
6
)
7
8
// Cardinality represents some metric by name and the number of times that metric is used
9
// with a different combination of unique labels.
10
type Cardinality struct {
11
Metric string
12
Instances int
13
}
14
15
// FindCardinality searches the WAL and returns the cardinality of all __name__
16
// series within the WAL for any given series with the label job=<job> and
17
// instance=<instance>. All other series are ignored.
18
func FindCardinality(walDir string, job string, instance string) ([]Cardinality, error) {
19
w, err := wlog.Open(nil, walDir)
20
if err != nil {
21
return nil, err
22
}
23
defer w.Close()
24
25
cardinality := map[string]int{}
26
27
err = walIterate(w, func(r *wlog.Reader) error {
28
return collectCardinality(r, job, instance, cardinality)
29
})
30
if err != nil {
31
return nil, err
32
}
33
34
res := make([]Cardinality, 0, len(cardinality))
35
for k, v := range cardinality {
36
res = append(res, Cardinality{Metric: k, Instances: v})
37
}
38
return res, nil
39
}
40
41
func collectCardinality(r *wlog.Reader, job, instance string, cardinality map[string]int) error {
42
var dec record.Decoder
43
44
for r.Next() {
45
rec := r.Record()
46
47
switch dec.Type(rec) {
48
case record.Series:
49
series, err := dec.Series(rec, nil)
50
if err != nil {
51
return err
52
}
53
for _, s := range series {
54
var (
55
jobLabel = s.Labels.Get("job")
56
instanceLabel = s.Labels.Get("instance")
57
)
58
59
if jobLabel == job && instanceLabel == instance {
60
cardinality[s.Labels.Get("__name__")]++
61
}
62
}
63
}
64
}
65
66
return r.Err()
67
}
68
69