Debian Codegraph @

prometheus/value.go

raw
1 // Copyright 2014 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 "sort"
20 "time"
21 "unicode/utf8"
22
23 "github.com/prometheus/client_golang/prometheus/internal"
24
25 dto "github.com/prometheus/client_model/go"
26 "google.golang.org/protobuf/proto"
27 "google.golang.org/protobuf/types/known/timestamppb"
28 )
29
30 // ValueType is an enumeration of metric types that represent a simple value.
31 type ValueType int
32
33 // Possible values for the ValueType enum. Use UntypedValue to mark a metric
34 // with an unknown type.
35 const (
36 _ ValueType = iota
37 CounterValue
38 GaugeValue
39 UntypedValue
40 )
41
42 var (
43 CounterMetricTypePtr = func() *dto.MetricType { d := dto.MetricType_COUNTER; return &d }()
44 GaugeMetricTypePtr = func() *dto.MetricType { d := dto.MetricType_GAUGE; return &d }()
45 UntypedMetricTypePtr = func() *dto.MetricType { d := dto.MetricType_UNTYPED; return &d }()
46 )
47
48 func (v ValueType) ToDTO() *dto.MetricType {
49 switch v {
50 case CounterValue:
51 return CounterMetricTypePtr
52 case GaugeValue:
53 return GaugeMetricTypePtr
54 default:
55 return UntypedMetricTypePtr
56 }
57 }
58
59 // valueFunc is a generic metric for simple values retrieved on collect time
60 // from a function. It implements Metric and Collector. Its effective type is
61 // determined by ValueType. This is a low-level building block used by the
62 // library to back the implementations of CounterFunc, GaugeFunc, and
63 // UntypedFunc.
64 type valueFunc struct {
65 selfCollector
66
67 desc *Desc
68 valType ValueType
69 function func() float64
70 labelPairs []*dto.LabelPair
71 }
72
73 // newValueFunc returns a newly allocated valueFunc with the given Desc and
74 // ValueType. The value reported is determined by calling the given function
75 // from within the Write method. Take into account that metric collection may
76 // happen concurrently. If that results in concurrent calls to Write, like in
77 // the case where a valueFunc is directly registered with Prometheus, the
78 // provided function must be concurrency-safe.
79 func newValueFunc(desc *Desc, valueType ValueType, function func() float64) *valueFunc {
80 result := &valueFunc{
81 desc: desc,
82 valType: valueType,
83 function: function,
84 labelPairs: MakeLabelPairs(desc, nil),
85 }
86 result.init(result)
87 return result
88 }
89
90 func (v *valueFunc) Desc() *Desc {
91 return v.desc
92 }
93
94 func (v *valueFunc) Write(out *dto.Metric) error {
95 return populateMetric(v.valType, v.function(), v.labelPairs, nil, out, nil)
96 }
97
98 // NewConstMetric returns a metric with one fixed value that cannot be
99 // changed. Users of this package will not have much use for it in regular
100 // operations. However, when implementing custom Collectors, it is useful as a
101 // throw-away metric that is generated on the fly to send it to Prometheus in
102 // the Collect method. NewConstMetric returns an error if the length of
103 // labelValues is not consistent with the variable labels in Desc or if Desc is
104 // invalid.
105 func NewConstMetric(desc *Desc, valueType ValueType, value float64, labelValues ...string) (Metric, error) {
106 if desc.err != nil {
107 return nil, desc.err
108 }
109 if err := validateLabelValues(labelValues, len(desc.variableLabels.names)); err != nil {
110 return nil, err
111 }
112
113 metric := &dto.Metric{}
114 if err := populateMetric(valueType, value, MakeLabelPairs(desc, labelValues), nil, metric, nil); err != nil {
115 return nil, err
116 }
117
118 return &constMetric{
119 desc: desc,
120 metric: metric,
121 }, nil
122 }
123
124 // MustNewConstMetric is a version of NewConstMetric that panics where
125 // NewConstMetric would have returned an error.
126 func MustNewConstMetric(desc *Desc, valueType ValueType, value float64, labelValues ...string) Metric {
127 m, err := NewConstMetric(desc, valueType, value, labelValues...)
128 if err != nil {
129 panic(err)
130 }
131 return m
132 }
133
134 // NewConstMetricWithCreatedTimestamp does the same thing as NewConstMetric, but generates Counters
135 // with created timestamp set and returns an error for other metric types.
136 func NewConstMetricWithCreatedTimestamp(desc *Desc, valueType ValueType, value float64, ct time.Time, labelValues ...string) (Metric, error) {
137 if desc.err != nil {
138 return nil, desc.err
139 }
140 if err := validateLabelValues(labelValues, len(desc.variableLabels.names)); err != nil {
141 return nil, err
142 }
143 switch valueType {
144 case CounterValue:
145 break
146 default:
147 return nil, errors.New("created timestamps are only supported for counters")
148 }
149
150 metric := &dto.Metric{}
151 if err := populateMetric(valueType, value, MakeLabelPairs(desc, labelValues), nil, metric, timestamppb.New(ct)); err != nil {
152 return nil, err
153 }
154
155 return &constMetric{
156 desc: desc,
157 metric: metric,
158 }, nil
159 }
160
161 // MustNewConstMetricWithCreatedTimestamp is a version of NewConstMetricWithCreatedTimestamp that panics where
162 // NewConstMetricWithCreatedTimestamp would have returned an error.
163 func MustNewConstMetricWithCreatedTimestamp(desc *Desc, valueType ValueType, value float64, ct time.Time, labelValues ...string) Metric {
164 m, err := NewConstMetricWithCreatedTimestamp(desc, valueType, value, ct, labelValues...)
165 if err != nil {
166 panic(err)
167 }
168 return m
169 }
170
171 type constMetric struct {
172 desc *Desc
173 metric *dto.Metric
174 }
175
176 func (m *constMetric) Desc() *Desc {
177 return m.desc
178 }
179
180 func (m *constMetric) Write(out *dto.Metric) error {
181 out.Label = m.metric.Label
182 out.Counter = m.metric.Counter
183 out.Gauge = m.metric.Gauge
184 out.Untyped = m.metric.Untyped
185 return nil
186 }
187
188 func populateMetric(
189 t ValueType,
190 v float64,
191 labelPairs []*dto.LabelPair,
192 e *dto.Exemplar,
193 m *dto.Metric,
194 ct *timestamppb.Timestamp,
195 ) error {
196 m.Label = labelPairs
197 switch t {
198 case CounterValue:
199 m.Counter = &dto.Counter{Value: proto.Float64(v), Exemplar: e, CreatedTimestamp: ct}
200 case GaugeValue:
201 m.Gauge = &dto.Gauge{Value: proto.Float64(v)}
202 case UntypedValue:
203 m.Untyped = &dto.Untyped{Value: proto.Float64(v)}
204 default:
205 return fmt.Errorf("encountered unknown type %v", t)
206 }
207 return nil
208 }
209
210 // MakeLabelPairs is a helper function to create protobuf LabelPairs from the
211 // variable and constant labels in the provided Desc. The values for the
212 // variable labels are defined by the labelValues slice, which must be in the
213 // same order as the corresponding variable labels in the Desc.
214 //
215 // This function is only needed for custom Metric implementations. See MetricVec
216 // example.
217 func MakeLabelPairs(desc *Desc, labelValues []string) []*dto.LabelPair {
218 totalLen := len(desc.variableLabels.names) + len(desc.constLabelPairs)
219 if totalLen == 0 {
220 // Super fast path.
221 return nil
222 }
223 if len(desc.variableLabels.names) == 0 {
224 // Moderately fast path.
225 return desc.constLabelPairs
226 }
227 labelPairs := make([]*dto.LabelPair, 0, totalLen)
228 for i, l := range desc.variableLabels.names {
229 labelPairs = append(labelPairs, &dto.LabelPair{
230 Name: proto.String(l),
231 Value: proto.String(labelValues[i]),
232 })
233 }
234 labelPairs = append(labelPairs, desc.constLabelPairs...)
235 sort.Sort(internal.LabelPairSorter(labelPairs))
236 return labelPairs
237 }
238
239 // ExemplarMaxRunes is the max total number of runes allowed in exemplar labels.
240 const ExemplarMaxRunes = 128
241
242 // newExemplar creates a new dto.Exemplar from the provided values. An error is
243 // returned if any of the label names or values are invalid or if the total
244 // number of runes in the label names and values exceeds ExemplarMaxRunes.
245 func newExemplar(value float64, ts time.Time, l Labels) (*dto.Exemplar, error) {
246 e := &dto.Exemplar{}
247 e.Value = proto.Float64(value)
248 tsProto := timestamppb.New(ts)
249 if err := tsProto.CheckValid(); err != nil {
250 return nil, err
251 }
252 e.Timestamp = tsProto
253 labelPairs := make([]*dto.LabelPair, 0, len(l))
254 var runes int
255 for name, value := range l {
256 if !checkLabelName(name) {
257 return nil, fmt.Errorf("exemplar label name %q is invalid", name)
258 }
259 runes += utf8.RuneCountInString(name)
260 if !utf8.ValidString(value) {
261 return nil, fmt.Errorf("exemplar label value %q is not valid UTF-8", value)
262 }
263 runes += utf8.RuneCountInString(value)
264 labelPairs = append(labelPairs, &dto.LabelPair{
265 Name: proto.String(name),
266 Value: proto.String(value),
267 })
268 }
269 if runes > ExemplarMaxRunes {
270 return nil, fmt.Errorf("exemplar labels have %d runes, exceeding the limit of %d", runes, ExemplarMaxRunes)
271 }
272 e.Label = labelPairs
273 return e, nil
274 }