Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
aos
GitHub Repository: aos/grafana-agent
Path: blob/main/pkg/util/testappender/internal/dtobuilder/sort.go
4099 views
1
package dtobuilder
2
3
import (
4
"sort"
5
6
dto "github.com/prometheus/client_model/go"
7
)
8
9
// sortMetricFamilies sorts metric families, the metrics inside them, and the
10
// summaries and histograms inside the individual metrics.
11
func sortMetricFamilies(mf []*dto.MetricFamily) {
12
sort.Slice(mf, func(i, j int) bool {
13
return mf[i].GetName() < mf[j].GetName()
14
})
15
16
for _, family := range mf {
17
sortMetrics(family.Metric)
18
}
19
}
20
21
// sortMetrics sorts a slice of metrics, followed by the quantiles and
22
// histogram buckets (if present) inside each metric.
23
func sortMetrics(mm []*dto.Metric) {
24
sort.Slice(mm, func(i, j int) bool {
25
return labelsLess(mm[i].GetLabel(), mm[j].GetLabel())
26
})
27
28
for _, m := range mm {
29
if m.Summary != nil {
30
sortQuantiles(m.Summary.GetQuantile())
31
}
32
33
if m.Histogram != nil {
34
sortBuckets(m.Histogram.GetBucket())
35
}
36
}
37
}
38
39
// labelsLess implements the sort.Slice "less" function, returning true if a
40
// should appear before b in a list of sorted labels.
41
func labelsLess(a, b []*dto.LabelPair) bool {
42
for i := 0; i < len(a); i++ {
43
// If all labels have matched but we've gone past the length
44
// of b, that means that a > b.
45
// If we've gone past the length of b, then a has more labels
46
if i >= len(b) {
47
return false
48
}
49
50
switch {
51
case a[i].GetName() != b[i].GetName():
52
return a[i].GetName() < b[i].GetName()
53
case a[i].GetValue() != b[i].GetValue():
54
return a[i].GetValue() < b[i].GetValue()
55
}
56
}
57
58
// Either they're fully equal or a < b, so we return true either way.
59
return true
60
}
61
62
// sortQuantiles sorts a slice of quantiles.
63
func sortQuantiles(qq []*dto.Quantile) {
64
sort.Slice(qq, func(i, j int) bool {
65
return qq[i].GetQuantile() < qq[j].GetQuantile()
66
})
67
}
68
69
// sortBuckets sorts a slice of buckets.
70
func sortBuckets(bb []*dto.Bucket) {
71
sort.Slice(bb, func(i, j int) bool {
72
return bb[i].GetUpperBound() < bb[j].GetUpperBound()
73
})
74
}
75
76