Debian Codegraph @

prometheus/labels.go

raw
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
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
14 package prometheus
15
16 import (
17 "errors"
18 "fmt"
19 "strings"
20 "unicode/utf8"
21
22 "github.com/prometheus/common/model"
23 )
24
25 // Labels represents a collection of label name -> value mappings. This type is
26 // commonly used with the With(Labels) and GetMetricWith(Labels) methods of
27 // metric vector Collectors, e.g.:
28 //
29 // myVec.With(Labels{"code": "404", "method": "GET"}).Add(42)
30 //
31 // The other use-case is the specification of constant label pairs in Opts or to
32 // create a Desc.
33 type Labels map[string]string
34
35 // LabelConstraint normalizes label values.
36 type LabelConstraint func(string) string
37
38 // ConstrainedLabels represents a label name and its constrain function
39 // to normalize label values. This type is commonly used when constructing
40 // metric vector Collectors.
41 type ConstrainedLabel struct {
42 Name string
43 Constraint LabelConstraint
44 }
45
46 // ConstrainableLabels is an interface that allows creating of labels that can
47 // be optionally constrained.
48 //
49 // prometheus.V2().NewCounterVec(CounterVecOpts{
50 // CounterOpts: {...}, // Usual CounterOpts fields
51 // VariableLabels: []ConstrainedLabels{
52 // {Name: "A"},
53 // {Name: "B", Constraint: func(v string) string { ... }},
54 // },
55 // })
56 type ConstrainableLabels interface {
57 compile() *compiledLabels
58 labelNames() []string
59 }
60
61 // ConstrainedLabels represents a collection of label name -> constrain function
62 // to normalize label values. This type is commonly used when constructing
63 // metric vector Collectors.
64 type ConstrainedLabels []ConstrainedLabel
65
66 func (cls ConstrainedLabels) compile() *compiledLabels {
67 compiled := &compiledLabels{
68 names: make([]string, len(cls)),
69 labelConstraints: map[string]LabelConstraint{},
70 }
71
72 for i, label := range cls {
73 compiled.names[i] = label.Name
74 if label.Constraint != nil {
75 compiled.labelConstraints[label.Name] = label.Constraint
76 }
77 }
78
79 return compiled
80 }
81
82 func (cls ConstrainedLabels) labelNames() []string {
83 names := make([]string, len(cls))
84 for i, label := range cls {
85 names[i] = label.Name
86 }
87 return names
88 }
89
90 // UnconstrainedLabels represents collection of label without any constraint on
91 // their value. Thus, it is simply a collection of label names.
92 //
93 // UnconstrainedLabels([]string{ "A", "B" })
94 //
95 // is equivalent to
96 //
97 // ConstrainedLabels {
98 // { Name: "A" },
99 // { Name: "B" },
100 // }
101 type UnconstrainedLabels []string
102
103 func (uls UnconstrainedLabels) compile() *compiledLabels {
104 return &compiledLabels{
105 names: uls,
106 }
107 }
108
109 func (uls UnconstrainedLabels) labelNames() []string {
110 return uls
111 }
112
113 type compiledLabels struct {
114 names []string
115 labelConstraints map[string]LabelConstraint
116 }
117
118 func (cls *compiledLabels) compile() *compiledLabels {
119 return cls
120 }
121
122 func (cls *compiledLabels) labelNames() []string {
123 return cls.names
124 }
125
126 func (cls *compiledLabels) constrain(labelName, value string) string {
127 if fn, ok := cls.labelConstraints[labelName]; ok && fn != nil {
128 return fn(value)
129 }
130 return value
131 }
132
133 // reservedLabelPrefix is a prefix which is not legal in user-supplied
134 // label names.
135 const reservedLabelPrefix = "__"
136
137 var errInconsistentCardinality = errors.New("inconsistent label cardinality")
138
139 func makeInconsistentCardinalityError(fqName string, labels, labelValues []string) error {
140 return fmt.Errorf(
141 "%w: %q has %d variable labels named %q but %d values %q were provided",
142 errInconsistentCardinality, fqName,
143 len(labels), labels,
144 len(labelValues), labelValues,
145 )
146 }
147
148 func validateValuesInLabels(labels Labels, expectedNumberOfValues int) error {
149 if len(labels) != expectedNumberOfValues {
150 return fmt.Errorf(
151 "%w: expected %d label values but got %d in %#v",
152 errInconsistentCardinality, expectedNumberOfValues,
153 len(labels), labels,
154 )
155 }
156
157 for name, val := range labels {
158 if !utf8.ValidString(val) {
159 return fmt.Errorf("label %s: value %q is not valid UTF-8", name, val)
160 }
161 }
162
163 return nil
164 }
165
166 func validateLabelValues(vals []string, expectedNumberOfValues int) error {
167 if len(vals) != expectedNumberOfValues {
168 // The call below makes vals escape, copy them to avoid that.
169 vals := append([]string(nil), vals...)
170 return fmt.Errorf(
171 "%w: expected %d label values but got %d in %#v",
172 errInconsistentCardinality, expectedNumberOfValues,
173 len(vals), vals,
174 )
175 }
176
177 for _, val := range vals {
178 if !utf8.ValidString(val) {
179 return fmt.Errorf("label value %q is not valid UTF-8", val)
180 }
181 }
182
183 return nil
184 }
185
186 func checkLabelName(l string) bool {
187 //nolint:staticcheck // TODO: Don't use deprecated model.NameValidationScheme.
188 return model.NameValidationScheme.IsValidLabelName(l) && !strings.HasPrefix(l, reservedLabelPrefix)
189 }