Path: blob/main/pkg/util/testappender/internal/dtobuilder/sort.go
4099 views
package dtobuilder12import (3"sort"45dto "github.com/prometheus/client_model/go"6)78// sortMetricFamilies sorts metric families, the metrics inside them, and the9// summaries and histograms inside the individual metrics.10func sortMetricFamilies(mf []*dto.MetricFamily) {11sort.Slice(mf, func(i, j int) bool {12return mf[i].GetName() < mf[j].GetName()13})1415for _, family := range mf {16sortMetrics(family.Metric)17}18}1920// sortMetrics sorts a slice of metrics, followed by the quantiles and21// histogram buckets (if present) inside each metric.22func sortMetrics(mm []*dto.Metric) {23sort.Slice(mm, func(i, j int) bool {24return labelsLess(mm[i].GetLabel(), mm[j].GetLabel())25})2627for _, m := range mm {28if m.Summary != nil {29sortQuantiles(m.Summary.GetQuantile())30}3132if m.Histogram != nil {33sortBuckets(m.Histogram.GetBucket())34}35}36}3738// labelsLess implements the sort.Slice "less" function, returning true if a39// should appear before b in a list of sorted labels.40func labelsLess(a, b []*dto.LabelPair) bool {41for i := 0; i < len(a); i++ {42// If all labels have matched but we've gone past the length43// of b, that means that a > b.44// If we've gone past the length of b, then a has more labels45if i >= len(b) {46return false47}4849switch {50case a[i].GetName() != b[i].GetName():51return a[i].GetName() < b[i].GetName()52case a[i].GetValue() != b[i].GetValue():53return a[i].GetValue() < b[i].GetValue()54}55}5657// Either they're fully equal or a < b, so we return true either way.58return true59}6061// sortQuantiles sorts a slice of quantiles.62func sortQuantiles(qq []*dto.Quantile) {63sort.Slice(qq, func(i, j int) bool {64return qq[i].GetQuantile() < qq[j].GetQuantile()65})66}6768// sortBuckets sorts a slice of buckets.69func sortBuckets(bb []*dto.Bucket) {70sort.Slice(bb, func(i, j int) bool {71return bb[i].GetUpperBound() < bb[j].GetUpperBound()72})73}747576