blob: 351c26e1aedb4ad9c0f78200757d8c1e946fc00b [file] [log] [blame]
khenaidooffe076b2019-01-15 16:08:08 -05001// Copyright 2018 The Prometheus Authors
2// Licensed under the Apache License, Version 2.0 (the "License");
3// you may not use this file except in compliance with the License.
4// You may obtain a copy of the License at
5//
6// http://www.apache.org/licenses/LICENSE-2.0
7//
8// Unless required by applicable law or agreed to in writing, software
9// distributed under the License is distributed on an "AS IS" BASIS,
10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11// See the License for the specific language governing permissions and
12// limitations under the License.
13
14package internal
15
16import (
17 "sort"
18
19 dto "github.com/prometheus/client_model/go"
20)
21
22// metricSorter is a sortable slice of *dto.Metric.
23type metricSorter []*dto.Metric
24
25func (s metricSorter) Len() int {
26 return len(s)
27}
28
29func (s metricSorter) Swap(i, j int) {
30 s[i], s[j] = s[j], s[i]
31}
32
33func (s metricSorter) Less(i, j int) bool {
34 if len(s[i].Label) != len(s[j].Label) {
35 // This should not happen. The metrics are
36 // inconsistent. However, we have to deal with the fact, as
37 // people might use custom collectors or metric family injection
38 // to create inconsistent metrics. So let's simply compare the
39 // number of labels in this case. That will still yield
40 // reproducible sorting.
41 return len(s[i].Label) < len(s[j].Label)
42 }
43 for n, lp := range s[i].Label {
44 vi := lp.GetValue()
45 vj := s[j].Label[n].GetValue()
46 if vi != vj {
47 return vi < vj
48 }
49 }
50
51 // We should never arrive here. Multiple metrics with the same
52 // label set in the same scrape will lead to undefined ingestion
53 // behavior. However, as above, we have to provide stable sorting
54 // here, even for inconsistent metrics. So sort equal metrics
55 // by their timestamp, with missing timestamps (implying "now")
56 // coming last.
57 if s[i].TimestampMs == nil {
58 return false
59 }
60 if s[j].TimestampMs == nil {
61 return true
62 }
63 return s[i].GetTimestampMs() < s[j].GetTimestampMs()
64}
65
66// NormalizeMetricFamilies returns a MetricFamily slice with empty
67// MetricFamilies pruned and the remaining MetricFamilies sorted by name within
68// the slice, with the contained Metrics sorted within each MetricFamily.
69func NormalizeMetricFamilies(metricFamiliesByName map[string]*dto.MetricFamily) []*dto.MetricFamily {
70 for _, mf := range metricFamiliesByName {
71 sort.Sort(metricSorter(mf.Metric))
72 }
73 names := make([]string, 0, len(metricFamiliesByName))
74 for name, mf := range metricFamiliesByName {
75 if len(mf.Metric) > 0 {
76 names = append(names, name)
77 }
78 }
79 sort.Strings(names)
80 result := make([]*dto.MetricFamily, 0, len(names))
81 for _, name := range names {
82 result = append(result, metricFamiliesByName[name])
83 }
84 return result
85}