sigs.k8s.io/kueue@v0.6.2/pkg/util/testing/metrics/metrics.go (about) 1 /* 2 Copyright 2023 The Kubernetes Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package metrics 18 19 import ( 20 "sort" 21 22 "github.com/prometheus/client_golang/prometheus" 23 dto "github.com/prometheus/client_model/go" 24 25 "sigs.k8s.io/kueue/pkg/util/maps" 26 "sigs.k8s.io/kueue/pkg/util/slices" 27 ) 28 29 type GaugeDataPoint struct { 30 Labels map[string]string 31 Value float64 32 } 33 34 func (a *GaugeDataPoint) Less(b *GaugeDataPoint) bool { 35 36 keys := maps.Keys(a.Labels) 37 sort.Strings(keys) 38 for _, k := range keys { 39 vb, found := b.Labels[k] 40 if !found { 41 return false 42 } 43 va := a.Labels[k] 44 if va < vb { 45 return true 46 } 47 if vb < va { 48 return false 49 } 50 } 51 52 la := len(a.Labels) 53 lb := len(b.Labels) 54 if la < lb { 55 return true 56 } 57 if lb < la { 58 return false 59 } 60 return a.Value < b.Value 61 62 } 63 64 func CollectFilteredGaugeVec(v *prometheus.GaugeVec, labels map[string]string) []GaugeDataPoint { 65 if v == nil { 66 return nil 67 } 68 69 ch := make(chan prometheus.Metric) 70 ret := []GaugeDataPoint{} 71 72 go func() { 73 v.Collect(ch) 74 close(ch) 75 }() 76 for m := range ch { 77 // check if matches 78 dtoMetric := dto.Metric{} 79 if m.Write(&dtoMetric) == nil { 80 metricLabelsMap := slices.ToMap(dtoMetric.Label, func(i int) (string, string) { return *dtoMetric.Label[i].Name, *dtoMetric.Label[i].Value }) 81 if maps.Contains(metricLabelsMap, labels) { 82 dp := GaugeDataPoint{ 83 Labels: metricLabelsMap, 84 Value: *dtoMetric.Gauge.Value, 85 } 86 ret = append(ret, dp) 87 } 88 } 89 } 90 return ret 91 }