Debian Codegraph @

prometheus/testutil/testutil.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 testutil provides helpers to test code using the prometheus package
15 // of client_golang.
16 //
17 // While writing unit tests to verify correct instrumentation of your code, it's
18 // a common mistake to mostly test the instrumentation library instead of your
19 // own code. Rather than verifying that a prometheus.Counter's value has changed
20 // as expected or that it shows up in the exposition after registration, it is
21 // in general more robust and more faithful to the concept of unit tests to use
22 // mock implementations of the prometheus.Counter and prometheus.Registerer
23 // interfaces that simply assert that the Add or Register methods have been
24 // called with the expected arguments. However, this might be overkill in simple
25 // scenarios. The ToFloat64 function is provided for simple inspection of a
26 // single-value metric, but it has to be used with caution.
27 //
28 // End-to-end tests to verify all or larger parts of the metrics exposition can
29 // be implemented with the CollectAndCompare or GatherAndCompare functions. The
30 // most appropriate use is not so much testing instrumentation of your code, but
31 // testing custom prometheus.Collector implementations and in particular whole
32 // exporters, i.e. programs that retrieve telemetry data from a 3rd party source
33 // and convert it into Prometheus metrics.
34 //
35 // In a similar pattern, CollectAndLint and GatherAndLint can be used to detect
36 // metrics that have issues with their name, type, or metadata without being
37 // necessarily invalid, e.g. a counter with a name missing the “_total” suffix.
38 package testutil
39
40 import (
41 "bytes"
42 "errors"
43 "fmt"
44 "io"
45 "net/http"
46
47 "github.com/kylelemons/godebug/diff"
48 dto "github.com/prometheus/client_model/go"
49 "github.com/prometheus/common/expfmt"
50 "github.com/prometheus/common/model"
51 "google.golang.org/protobuf/proto"
52
53 "github.com/prometheus/client_golang/prometheus"
54 "github.com/prometheus/client_golang/prometheus/internal"
55 )
56
57 // ToFloat64 collects all Metrics from the provided Collector. It expects that
58 // this results in exactly one Metric being collected, which must be a Gauge,
59 // Counter, or Untyped. In all other cases, ToFloat64 panics. ToFloat64 returns
60 // the value of the collected Metric.
61 //
62 // The Collector provided is typically a simple instance of Gauge or Counter, or
63 // – less commonly – a GaugeVec or CounterVec with exactly one element. But any
64 // Collector fulfilling the prerequisites described above will do.
65 //
66 // Use this function with caution. It is computationally very expensive and thus
67 // not suited at all to read values from Metrics in regular code. This is really
68 // only for testing purposes, and even for testing, other approaches are often
69 // more appropriate (see this package's documentation).
70 //
71 // A clear anti-pattern would be to use a metric type from the prometheus
72 // package to track values that are also needed for something else than the
73 // exposition of Prometheus metrics. For example, you would like to track the
74 // number of items in a queue because your code should reject queuing further
75 // items if a certain limit is reached. It is tempting to track the number of
76 // items in a prometheus.Gauge, as it is then easily available as a metric for
77 // exposition, too. However, then you would need to call ToFloat64 in your
78 // regular code, potentially quite often. The recommended way is to track the
79 // number of items conventionally (in the way you would have done it without
80 // considering Prometheus metrics) and then expose the number with a
81 // prometheus.GaugeFunc.
82 func ToFloat64(c prometheus.Collector) float64 {
83 var (
84 m prometheus.Metric
85 mCount int
86 mChan = make(chan prometheus.Metric)
87 done = make(chan struct{})
88 )
89
90 go func() {
91 for m = range mChan {
92 mCount++
93 }
94 close(done)
95 }()
96
97 c.Collect(mChan)
98 close(mChan)
99 <-done
100
101 if mCount != 1 {
102 panic(fmt.Errorf("collected %d metrics instead of exactly 1", mCount))
103 }
104
105 pb := &dto.Metric{}
106 if err := m.Write(pb); err != nil {
107 panic(fmt.Errorf("error happened while collecting metrics: %w", err))
108 }
109 if pb.Gauge != nil {
110 return pb.Gauge.GetValue()
111 }
112 if pb.Counter != nil {
113 return pb.Counter.GetValue()
114 }
115 if pb.Untyped != nil {
116 return pb.Untyped.GetValue()
117 }
118 panic(fmt.Errorf("collected a non-gauge/counter/untyped metric: %s", pb))
119 }
120
121 // CollectAndCount registers the provided Collector with a newly created
122 // pedantic Registry. It then calls GatherAndCount with that Registry and with
123 // the provided metricNames. In the unlikely case that the registration or the
124 // gathering fails, this function panics. (This is inconsistent with the other
125 // CollectAnd… functions in this package and has historical reasons. Changing
126 // the function signature would be a breaking change and will therefore only
127 // happen with the next major version bump.)
128 func CollectAndCount(c prometheus.Collector, metricNames ...string) int {
129 reg := prometheus.NewPedanticRegistry()
130 if err := reg.Register(c); err != nil {
131 panic(fmt.Errorf("registering collector failed: %w", err))
132 }
133 result, err := GatherAndCount(reg, metricNames...)
134 if err != nil {
135 panic(err)
136 }
137 return result
138 }
139
140 // GatherAndCount gathers all metrics from the provided Gatherer and counts
141 // them. It returns the number of metric children in all gathered metric
142 // families together. If any metricNames are provided, only metrics with those
143 // names are counted.
144 func GatherAndCount(g prometheus.Gatherer, metricNames ...string) (int, error) {
145 got, err := g.Gather()
146 if err != nil {
147 return 0, fmt.Errorf("gathering metrics failed: %w", err)
148 }
149 if metricNames != nil {
150 got = filterMetrics(got, metricNames)
151 }
152
153 result := 0
154 for _, mf := range got {
155 result += len(mf.GetMetric())
156 }
157 return result, nil
158 }
159
160 // ScrapeAndCompare calls a remote exporter's endpoint which is expected to return some metrics in
161 // plain text format. Then it compares it with the results that the `expected` would return.
162 // If the `metricNames` is not empty it would filter the comparison only to the given metric names.
163 //
164 // NOTE: Be mindful of accidental discrepancies between expected and metricNames; metricNames filter
165 // both expected and scraped metrics. See https://github.com/prometheus/client_golang/issues/1351.
166 func ScrapeAndCompare(url string, expected io.Reader, metricNames ...string) error {
167 resp, err := http.Get(url)
168 if err != nil {
169 return fmt.Errorf("scraping metrics failed: %w", err)
170 }
171 defer resp.Body.Close()
172
173 if resp.StatusCode != http.StatusOK {
174 return fmt.Errorf("the scraping target returned a status code other than 200: %d",
175 resp.StatusCode)
176 }
177
178 scraped, err := convertReaderToMetricFamily(resp.Body)
179 if err != nil {
180 return err
181 }
182
183 wanted, err := convertReaderToMetricFamily(expected)
184 if err != nil {
185 return err
186 }
187
188 return compareMetricFamilies(scraped, wanted, metricNames...)
189 }
190
191 // CollectAndCompare collects the metrics identified by `metricNames` and compares them in the Prometheus text
192 // exposition format to the data read from expected.
193 //
194 // NOTE: Be mindful of accidental discrepancies between expected and metricNames; metricNames filter
195 // both expected and collected metrics. See https://github.com/prometheus/client_golang/issues/1351.
196 func CollectAndCompare(c prometheus.Collector, expected io.Reader, metricNames ...string) error {
197 reg := prometheus.NewPedanticRegistry()
198 if err := reg.Register(c); err != nil {
199 return fmt.Errorf("registering collector failed: %w", err)
200 }
201 return GatherAndCompare(reg, expected, metricNames...)
202 }
203
204 // GatherAndCompare gathers all metrics from the provided Gatherer and compares
205 // it to an expected output read from the provided Reader in the Prometheus text
206 // exposition format. If any metricNames are provided, only metrics with those
207 // names are compared.
208 //
209 // NOTE: Be mindful of accidental discrepancies between expected and metricNames; metricNames filter
210 // both expected and gathered metrics. See https://github.com/prometheus/client_golang/issues/1351.
211 func GatherAndCompare(g prometheus.Gatherer, expected io.Reader, metricNames ...string) error {
212 return TransactionalGatherAndCompare(prometheus.ToTransactionalGatherer(g), expected, metricNames...)
213 }
214
215 // TransactionalGatherAndCompare gathers all metrics from the provided Gatherer and compares
216 // it to an expected output read from the provided Reader in the Prometheus text
217 // exposition format. If any metricNames are provided, only metrics with those
218 // names are compared.
219 //
220 // NOTE: Be mindful of accidental discrepancies between expected and metricNames; metricNames filter
221 // both expected and gathered metrics. See https://github.com/prometheus/client_golang/issues/1351.
222 func TransactionalGatherAndCompare(g prometheus.TransactionalGatherer, expected io.Reader, metricNames ...string) error {
223 got, done, err := g.Gather()
224 defer done()
225 if err != nil {
226 return fmt.Errorf("gathering metrics failed: %w", err)
227 }
228
229 wanted, err := convertReaderToMetricFamily(expected)
230 if err != nil {
231 return err
232 }
233
234 return compareMetricFamilies(got, wanted, metricNames...)
235 }
236
237 // CollectAndFormat collects the metrics identified by `metricNames` and returns them in the given format.
238 func CollectAndFormat(c prometheus.Collector, format expfmt.FormatType, metricNames ...string) ([]byte, error) {
239 reg := prometheus.NewPedanticRegistry()
240 if err := reg.Register(c); err != nil {
241 return nil, fmt.Errorf("registering collector failed: %w", err)
242 }
243
244 gotFiltered, err := reg.Gather()
245 if err != nil {
246 return nil, fmt.Errorf("gathering metrics failed: %w", err)
247 }
248
249 gotFiltered = filterMetrics(gotFiltered, metricNames)
250
251 var gotFormatted bytes.Buffer
252 enc := expfmt.NewEncoder(&gotFormatted, expfmt.NewFormat(format))
253 for _, mf := range gotFiltered {
254 if err := enc.Encode(mf); err != nil {
255 return nil, fmt.Errorf("encoding gathered metrics failed: %w", err)
256 }
257 }
258
259 return gotFormatted.Bytes(), nil
260 }
261
262 // convertReaderToMetricFamily would read from a io.Reader object and convert it to a slice of
263 // dto.MetricFamily.
264 func convertReaderToMetricFamily(reader io.Reader) ([]*dto.MetricFamily, error) {
265 tp := expfmt.NewTextParser(model.UTF8Validation)
266 notNormalized, err := tp.TextToMetricFamilies(reader)
267 if err != nil {
268 return nil, fmt.Errorf("converting reader to metric families failed: %w", err)
269 }
270
271 // The text protocol handles empty help fields inconsistently. When
272 // encoding, any non-nil value, include the empty string, produces a
273 // "# HELP" line. But when decoding, the help field is only set to a
274 // non-nil value if the "# HELP" line contains a non-empty value.
275 //
276 // Because metrics in a registry always have non-nil help fields, populate
277 // any nil help fields in the parsed metrics with the empty string so that
278 // when we compare text encodings, the results are consistent.
279 for _, metric := range notNormalized {
280 if metric.Help == nil {
281 metric.Help = proto.String("")
282 }
283 }
284
285 return internal.NormalizeMetricFamilies(notNormalized), nil
286 }
287
288 // compareMetricFamilies would compare 2 slices of metric families, and optionally filters both of
289 // them to the `metricNames` provided.
290 func compareMetricFamilies(got, expected []*dto.MetricFamily, metricNames ...string) error {
291 if metricNames != nil {
292 got = filterMetrics(got, metricNames)
293 expected = filterMetrics(expected, metricNames)
294 }
295
296 return compare(got, expected)
297 }
298
299 // compare encodes both provided slices of metric families into the text format,
300 // compares their string message, and returns an error if they do not match.
301 // The error contains the encoded text of both the desired and the actual
302 // result.
303 func compare(got, want []*dto.MetricFamily) error {
304 var gotBuf, wantBuf bytes.Buffer
305 enc := expfmt.NewEncoder(&gotBuf, expfmt.NewFormat(expfmt.TypeTextPlain).WithEscapingScheme(model.NoEscaping))
306 for _, mf := range got {
307 if err := enc.Encode(mf); err != nil {
308 return fmt.Errorf("encoding gathered metrics failed: %w", err)
309 }
310 }
311 enc = expfmt.NewEncoder(&wantBuf, expfmt.NewFormat(expfmt.TypeTextPlain).WithEscapingScheme(model.NoEscaping))
312 for _, mf := range want {
313 if err := enc.Encode(mf); err != nil {
314 return fmt.Errorf("encoding expected metrics failed: %w", err)
315 }
316 }
317 if diffErr := diff.Diff(gotBuf.String(), wantBuf.String()); diffErr != "" {
318 return errors.New(diffErr)
319 }
320 return nil
321 }
322
323 func filterMetrics(metrics []*dto.MetricFamily, names []string) []*dto.MetricFamily {
324 var filtered []*dto.MetricFamily
325 for _, m := range metrics {
326 for _, name := range names {
327 if m.GetName() == name {
328 filtered = append(filtered, m)
329 break
330 }
331 }
332 }
333 return filtered
334 }