1 // 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
6 // http://www.apache.org/licenses/LICENSE-2.0
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.
19 dto "github.com/prometheus/client_model/go"
22 // metricSorter is a sortable slice of *dto.Metric.
23 type metricSorter []*dto.Metric
25 func (s metricSorter) Len() int {
29 func (s metricSorter) Swap(i, j int) {
30 s[i], s[j] = s[j], s[i]
33 func (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)
43 for n, lp := range s[i].Label {
45 vj := s[j].Label[n].GetValue()
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")
57 if s[i].TimestampMs == nil {
60 if s[j].TimestampMs == nil {
63 return s[i].GetTimestampMs() < s[j].GetTimestampMs()
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.
69 func NormalizeMetricFamilies(metricFamiliesByName map[string]*dto.MetricFamily) []*dto.MetricFamily {
70 for _, mf := range metricFamiliesByName {
71 sort.Sort(metricSorter(mf.Metric))
73 names := make([]string, 0, len(metricFamiliesByName))
74 for name, mf := range metricFamiliesByName {
75 if len(mf.Metric) > 0 {
76 names = append(names, name)
80 result := make([]*dto.MetricFamily, 0, len(names))
81 for _, name := range names {
82 result = append(result, metricFamiliesByName[name])