github.com/muhammadn/cortex@v1.9.1-0.20220510110439-46bb7000d03d/pkg/util/extract/extract.go (about) 1 package extract 2 3 import ( 4 "fmt" 5 6 "github.com/prometheus/common/model" 7 "github.com/prometheus/prometheus/pkg/labels" 8 9 "github.com/cortexproject/cortex/pkg/cortexpb" 10 ) 11 12 var ( 13 errNoMetricNameLabel = fmt.Errorf("No metric name label") 14 ) 15 16 // MetricNameFromLabelAdapters extracts the metric name from a list of LabelPairs. 17 // The returned metric name string is a copy of the label value. 18 func MetricNameFromLabelAdapters(labels []cortexpb.LabelAdapter) (string, error) { 19 unsafeMetricName, err := UnsafeMetricNameFromLabelAdapters(labels) 20 if err != nil { 21 return "", err 22 } 23 24 // Force a string copy since LabelAdapter is often a pointer into 25 // a large gRPC buffer which we don't want to keep alive on the heap. 26 return string([]byte(unsafeMetricName)), nil 27 } 28 29 // UnsafeMetricNameFromLabelAdapters extracts the metric name from a list of LabelPairs. 30 // The returned metric name string is a reference to the label value (no copy). 31 func UnsafeMetricNameFromLabelAdapters(labels []cortexpb.LabelAdapter) (string, error) { 32 for _, label := range labels { 33 if label.Name == model.MetricNameLabel { 34 return label.Value, nil 35 } 36 } 37 return "", errNoMetricNameLabel 38 } 39 40 // MetricNameFromMetric extract the metric name from a model.Metric 41 func MetricNameFromMetric(m model.Metric) (model.LabelValue, error) { 42 if value, found := m[model.MetricNameLabel]; found { 43 return value, nil 44 } 45 return "", fmt.Errorf("no MetricNameLabel for chunk") 46 } 47 48 // MetricNameMatcherFromMatchers extracts the metric name from a set of matchers 49 func MetricNameMatcherFromMatchers(matchers []*labels.Matcher) (*labels.Matcher, []*labels.Matcher, bool) { 50 // Handle the case where there is no metric name and all matchers have been 51 // filtered out e.g. {foo=""}. 52 if len(matchers) == 0 { 53 return nil, matchers, false 54 } 55 56 outMatchers := make([]*labels.Matcher, len(matchers)-1) 57 for i, matcher := range matchers { 58 if matcher.Name != model.MetricNameLabel { 59 continue 60 } 61 62 // Copy other matchers, excluding the found metric name matcher 63 copy(outMatchers, matchers[:i]) 64 copy(outMatchers[i:], matchers[i+1:]) 65 return matcher, outMatchers, true 66 } 67 // Return all matchers if none are metric name matchers 68 return nil, matchers, false 69 } 70 71 // MetricNameFromLabels extracts the metric name from a list of Prometheus Labels. 72 func MetricNameFromLabels(lbls labels.Labels) (metricName string, err error) { 73 metricName = lbls.Get(model.MetricNameLabel) 74 if metricName == "" { 75 err = errNoMetricNameLabel 76 } 77 return 78 }