Debian Codegraph @

prometheus/promhttp/instrument_client_test.go

raw
1 // Copyright 2017 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 promhttp
15
16 import (
17 "context"
18 "log"
19 "net/http"
20 "net/http/httptest"
21 "reflect"
22 "sort"
23 "strings"
24 "testing"
25 "time"
26
27 "github.com/prometheus/client_golang/prometheus"
28 "github.com/prometheus/client_golang/prometheus/testutil"
29
30 dto "github.com/prometheus/client_model/go"
31 "google.golang.org/protobuf/proto"
32 )
33
34 func makeInstrumentedClient(opts ...Option) (*http.Client, *prometheus.Registry) {
35 client := http.DefaultClient
36 client.Timeout = 1 * time.Second
37
38 reg := prometheus.NewRegistry()
39
40 inFlightGauge := prometheus.NewGauge(prometheus.GaugeOpts{
41 Name: "client_in_flight_requests",
42 Help: "A gauge of in-flight requests for the wrapped client.",
43 })
44
45 counter := prometheus.NewCounterVec(
46 prometheus.CounterOpts{
47 Name: "client_api_requests_total",
48 Help: "A counter for requests from the wrapped client.",
49 },
50 []string{"code", "method"},
51 )
52
53 dnsLatencyVec := prometheus.NewHistogramVec(
54 prometheus.HistogramOpts{
55 Name: "dns_duration_seconds",
56 Help: "Trace dns latency histogram.",
57 Buckets: []float64{.005, .01, .025, .05},
58 },
59 []string{"event"},
60 )
61
62 tlsLatencyVec := prometheus.NewHistogramVec(
63 prometheus.HistogramOpts{
64 Name: "tls_duration_seconds",
65 Help: "Trace tls latency histogram.",
66 Buckets: []float64{.05, .1, .25, .5},
67 },
68 []string{"event"},
69 )
70
71 histVec := prometheus.NewHistogramVec(
72 prometheus.HistogramOpts{
73 Name: "request_duration_seconds",
74 Help: "A histogram of request latencies.",
75 Buckets: prometheus.DefBuckets,
76 },
77 []string{"method"},
78 )
79
80 reg.MustRegister(counter, tlsLatencyVec, dnsLatencyVec, histVec, inFlightGauge)
81
82 trace := &InstrumentTrace{
83 DNSStart: func(t float64) {
84 dnsLatencyVec.WithLabelValues("dns_start").Observe(t)
85 },
86 DNSDone: func(t float64) {
87 dnsLatencyVec.WithLabelValues("dns_done").Observe(t)
88 },
89 TLSHandshakeStart: func(t float64) {
90 tlsLatencyVec.WithLabelValues("tls_handshake_start").Observe(t)
91 },
92 TLSHandshakeDone: func(t float64) {
93 tlsLatencyVec.WithLabelValues("tls_handshake_done").Observe(t)
94 },
95 }
96
97 client.Transport = InstrumentRoundTripperInFlight(inFlightGauge,
98 InstrumentRoundTripperCounter(counter,
99 InstrumentRoundTripperTrace(trace,
100 InstrumentRoundTripperDuration(histVec, http.DefaultTransport, opts...),
101 ),
102 opts...),
103 )
104 return client, reg
105 }
106
107 func labelsToLabelPair(l prometheus.Labels) []*dto.LabelPair {
108 ret := make([]*dto.LabelPair, 0, len(l))
109 for k, v := range l {
110 ret = append(ret, &dto.LabelPair{Name: proto.String(k), Value: proto.String(v)})
111 }
112 sort.Slice(ret, func(i, j int) bool {
113 return *ret[i].Name < *ret[j].Name
114 })
115 return ret
116 }
117
118 func assetMetricAndExemplars(
119 t *testing.T,
120 reg *prometheus.Registry,
121 expectedNumMetrics int,
122 expectedExemplar []*dto.LabelPair,
123 ) {
124 t.Helper()
125
126 mfs, err := reg.Gather()
127 if err != nil {
128 t.Fatal(err)
129 }
130 if want, got := expectedNumMetrics, len(mfs); want != got {
131 t.Fatalf("unexpected number of metric families gathered, want %d, got %d", want, got)
132 }
133
134 for _, mf := range mfs {
135 if len(mf.Metric) == 0 {
136 t.Errorf("metric family %s must not be empty", mf.GetName())
137 }
138 for _, m := range mf.GetMetric() {
139 if c := m.GetCounter(); c != nil {
140 if len(expectedExemplar) == 0 {
141 if c.Exemplar != nil {
142 t.Errorf("expected no exemplar on the counter %v%v, got %v", mf.GetName(), m.Label, c.Exemplar.String())
143 }
144 continue
145 }
146
147 if c.Exemplar == nil {
148 t.Errorf("expected exemplar %v on the counter %v%v, got none", expectedExemplar, mf.GetName(), m.Label)
149 continue
150 }
151 if got := c.Exemplar.Label; !reflect.DeepEqual(expectedExemplar, got) {
152 t.Errorf("expected exemplar %v on the counter %v%v, got %v", expectedExemplar, mf.GetName(), m.Label, got)
153 }
154 continue
155 }
156 if h := m.GetHistogram(); h != nil {
157 found := false
158 for _, b := range h.GetBucket() {
159 if len(expectedExemplar) == 0 {
160 if b.Exemplar != nil {
161 t.Errorf("expected no exemplar on histogram %v%v bkt %v, got %v", mf.GetName(), m.Label, b.GetUpperBound(), b.Exemplar.String())
162 }
163 continue
164 }
165
166 if b.Exemplar == nil {
167 continue
168 }
169 if got := b.Exemplar.Label; !reflect.DeepEqual(expectedExemplar, got) {
170 t.Errorf("expected exemplar %v on the histogram %v%v on bkt %v, got %v", expectedExemplar, mf.GetName(), m.Label, b.GetUpperBound(), got)
171 continue
172 }
173 found = true
174 break
175 }
176
177 if len(expectedExemplar) > 0 && !found {
178 t.Errorf("expected exemplar %v on at least one bucket of the histogram %v%v, got none", expectedExemplar, mf.GetName(), m.Label)
179 }
180 }
181 }
182 }
183 }
184
185 func TestClientMiddlewareAPI(t *testing.T) {
186 client, reg := makeInstrumentedClient()
187 backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
188 w.WriteHeader(http.StatusOK)
189 }))
190 defer backend.Close()
191
192 resp, err := client.Get(backend.URL)
193 if err != nil {
194 t.Fatal(err)
195 }
196 defer resp.Body.Close()
197
198 assetMetricAndExemplars(t, reg, 3, nil)
199 }
200
201 func TestClientMiddlewareAPI_WithExemplars(t *testing.T) {
202 exemplar := prometheus.Labels{"traceID": "example situation observed by this metric"}
203
204 client, reg := makeInstrumentedClient(WithExemplarFromContext(func(_ context.Context) prometheus.Labels { return exemplar }))
205 backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
206 w.WriteHeader(http.StatusOK)
207 }))
208 defer backend.Close()
209
210 resp, err := client.Get(backend.URL)
211 if err != nil {
212 t.Fatal(err)
213 }
214 defer resp.Body.Close()
215
216 assetMetricAndExemplars(t, reg, 3, labelsToLabelPair(exemplar))
217 }
218
219 func TestClientMiddlewareAPI_WithRequestContext(t *testing.T) {
220 client, reg := makeInstrumentedClient()
221 backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
222 w.WriteHeader(http.StatusOK)
223 }))
224 defer backend.Close()
225
226 req, err := http.NewRequest(http.MethodGet, backend.URL, nil)
227 if err != nil {
228 t.Fatalf("%v", err)
229 }
230
231 // Set a context with a long timeout.
232 ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
233 defer cancel()
234 req = req.WithContext(ctx)
235
236 resp, err := client.Do(req)
237 if err != nil {
238 t.Fatal(err)
239 }
240 defer resp.Body.Close()
241
242 mfs, err := reg.Gather()
243 if err != nil {
244 t.Fatal(err)
245 }
246 if want, got := 3, len(mfs); want != got {
247 t.Fatalf("unexpected number of metric families gathered, want %d, got %d", want, got)
248 }
249 for _, mf := range mfs {
250 if len(mf.Metric) == 0 {
251 t.Errorf("metric family %s must not be empty", mf.GetName())
252 }
253 }
254
255 // make sure counters aren't double-incremented (see #1117)
256 expected := `
257 # HELP client_api_requests_total A counter for requests from the wrapped client.
258 # TYPE client_api_requests_total counter
259 client_api_requests_total{code="200",method="get"} 1
260 `
261
262 if err := testutil.GatherAndCompare(reg, strings.NewReader(expected),
263 "client_api_requests_total",
264 ); err != nil {
265 t.Fatal(err)
266 }
267 }
268
269 func TestClientMiddlewareAPIWithRequestContextTimeout(t *testing.T) {
270 client, _ := makeInstrumentedClient()
271
272 // Slow testserver responding in 100ms.
273 backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
274 time.Sleep(100 * time.Millisecond)
275 w.WriteHeader(http.StatusOK)
276 }))
277 defer backend.Close()
278
279 req, err := http.NewRequest(http.MethodGet, backend.URL, nil)
280 if err != nil {
281 t.Fatalf("%v", err)
282 }
283
284 // Set a context with a short timeout.
285 ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
286 defer cancel()
287 req = req.WithContext(ctx)
288
289 _, err = client.Do(req)
290 if err == nil {
291 t.Fatal("did not get timeout error")
292 }
293 expectedMsg := "context deadline exceeded"
294 if !strings.Contains(err.Error(), expectedMsg) {
295 t.Fatalf("unexpected error: %q, expect error: %q", err.Error(), expectedMsg)
296 }
297 }
298
299 func ExampleInstrumentRoundTripperDuration() {
300 client := http.DefaultClient
301 client.Timeout = 1 * time.Second
302
303 inFlightGauge := prometheus.NewGauge(prometheus.GaugeOpts{
304 Name: "client_in_flight_requests",
305 Help: "A gauge of in-flight requests for the wrapped client.",
306 })
307
308 counter := prometheus.NewCounterVec(
309 prometheus.CounterOpts{
310 Name: "client_api_requests_total",
311 Help: "A counter for requests from the wrapped client.",
312 },
313 []string{"code", "method"},
314 )
315
316 // dnsLatencyVec uses custom buckets based on expected dns durations.
317 // It has an instance label "event", which is set in the
318 // DNSStart and DNSDonehook functions defined in the
319 // InstrumentTrace struct below.
320 dnsLatencyVec := prometheus.NewHistogramVec(
321 prometheus.HistogramOpts{
322 Name: "dns_duration_seconds",
323 Help: "Trace dns latency histogram.",
324 Buckets: []float64{.005, .01, .025, .05},
325 },
326 []string{"event"},
327 )
328
329 // tlsLatencyVec uses custom buckets based on expected tls durations.
330 // It has an instance label "event", which is set in the
331 // TLSHandshakeStart and TLSHandshakeDone hook functions defined in the
332 // InstrumentTrace struct below.
333 tlsLatencyVec := prometheus.NewHistogramVec(
334 prometheus.HistogramOpts{
335 Name: "tls_duration_seconds",
336 Help: "Trace tls latency histogram.",
337 Buckets: []float64{.05, .1, .25, .5},
338 },
339 []string{"event"},
340 )
341
342 // histVec has no labels, making it a zero-dimensional ObserverVec.
343 histVec := prometheus.NewHistogramVec(
344 prometheus.HistogramOpts{
345 Name: "request_duration_seconds",
346 Help: "A histogram of request latencies.",
347 Buckets: prometheus.DefBuckets,
348 },
349 []string{},
350 )
351
352 // Register all of the metrics in the standard registry.
353 prometheus.MustRegister(counter, tlsLatencyVec, dnsLatencyVec, histVec, inFlightGauge)
354
355 // Define functions for the available httptrace.ClientTrace hook
356 // functions that we want to instrument.
357 trace := &InstrumentTrace{
358 DNSStart: func(t float64) {
359 dnsLatencyVec.WithLabelValues("dns_start").Observe(t)
360 },
361 DNSDone: func(t float64) {
362 dnsLatencyVec.WithLabelValues("dns_done").Observe(t)
363 },
364 TLSHandshakeStart: func(t float64) {
365 tlsLatencyVec.WithLabelValues("tls_handshake_start").Observe(t)
366 },
367 TLSHandshakeDone: func(t float64) {
368 tlsLatencyVec.WithLabelValues("tls_handshake_done").Observe(t)
369 },
370 }
371
372 // Wrap the default RoundTripper with middleware.
373 roundTripper := InstrumentRoundTripperInFlight(inFlightGauge,
374 InstrumentRoundTripperCounter(counter,
375 InstrumentRoundTripperTrace(trace,
376 InstrumentRoundTripperDuration(histVec, http.DefaultTransport),
377 ),
378 ),
379 )
380
381 // Set the RoundTripper on our client.
382 client.Transport = roundTripper
383
384 resp, err := client.Get("http://google.com")
385 if err != nil {
386 log.Printf("error: %v", err)
387 }
388 defer resp.Body.Close()
389 }