Debian Codegraph @

http.go

raw symbols SCIP
1 // Copyright 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 probing
15
16 import (
17 "bytes"
18 "context"
19 "crypto/tls"
20 "io"
21 "net/http"
22 "net/http/httptrace"
23 "sync"
24 "time"
25 )
26
27 const (
28 defaultHTTPCallFrequency = time.Second
29 defaultHTTPMaxConcurrentCalls = 1
30 defaultHTTPMethod = http.MethodGet
31 defaultTimeout = time.Second * 10
32 )
33
34 type httpCallerOptions struct {
35 client *http.Client
36
37 callFrequency time.Duration
38 maxConcurrentCalls int
39
40 host string
41 headers http.Header
42 method string
43 body []byte
44 timeout time.Duration
45
46 isValidResponse func(response *http.Response, body []byte) bool
47
48 onDNSStart func(suite *TraceSuite, info httptrace.DNSStartInfo)
49 onDNSDone func(suite *TraceSuite, info httptrace.DNSDoneInfo)
50 onConnStart func(suite *TraceSuite, network, addr string)
51 onConnDone func(suite *TraceSuite, network, addr string, err error)
52 onTLSStart func(suite *TraceSuite)
53 onTLSDone func(suite *TraceSuite, state tls.ConnectionState, err error)
54 onWroteHeaders func(suite *TraceSuite)
55 onFirstByteReceived func(suite *TraceSuite)
56 onReq func(suite *TraceSuite)
57 onResp func(suite *TraceSuite, info *HTTPCallInfo)
58
59 logger Logger
60 }
61
62 // HTTPCallerOption represents a function type for a functional parameter passed to a NewHTTPCaller constructor.
63 type HTTPCallerOption func(options *httpCallerOptions)
64
65 // WithHTTPCallerClient is a functional parameter for a HTTPCaller which specifies a http.Client.
66 func WithHTTPCallerClient(client *http.Client) HTTPCallerOption {
67 return func(options *httpCallerOptions) {
68 options.client = client
69 }
70 }
71
72 // WithHTTPCallerCallFrequency is a functional parameter for a HTTPCaller which specifies a call frequency.
73 // If this option is not provided the default one will be used. You can check default value in const
74 // defaultHTTPCallFrequency.
75 func WithHTTPCallerCallFrequency(frequency time.Duration) HTTPCallerOption {
76 return func(options *httpCallerOptions) {
77 options.callFrequency = frequency
78 }
79 }
80
81 // WithHTTPCallerMaxConcurrentCalls is a functional parameter for a HTTPCaller which specifies a number of
82 // maximum concurrent calls. If this option is not provided the default one will be used. You can check default value in const
83 // defaultHTTPMaxConcurrentCalls.
84 func WithHTTPCallerMaxConcurrentCalls(maxConcurrent int) HTTPCallerOption {
85 return func(options *httpCallerOptions) {
86 options.maxConcurrentCalls = maxConcurrent
87 }
88 }
89
90 // WithHTTPCallerHeaders is a functional parameter for a HTTPCaller which specifies headers that should be
91 // set in request.
92 // To override a Host header use a WithHTTPCallerHost method.
93 func WithHTTPCallerHeaders(headers http.Header) HTTPCallerOption {
94 return func(options *httpCallerOptions) {
95 options.headers = headers
96 }
97 }
98
99 // WithHTTPCallerMethod is a functional parameter for a HTTPCaller which specifies a method that should be
100 // set in request. If this option is not provided the default one will be used. You can check default value in const
101 // defaultHTTPMethod.
102 func WithHTTPCallerMethod(method string) HTTPCallerOption {
103 return func(options *httpCallerOptions) {
104 options.method = method
105 }
106 }
107
108 // WithHTTPCallerHost is a functional parameter for a HTTPCaller which allowed to override a host header.
109 func WithHTTPCallerHost(host string) HTTPCallerOption {
110 return func(options *httpCallerOptions) {
111 options.host = host
112 }
113 }
114
115 // WithHTTPCallerBody is a functional parameter for a HTTPCaller which specifies a body that should be set
116 // in request.
117 func WithHTTPCallerBody(body []byte) HTTPCallerOption {
118 return func(options *httpCallerOptions) {
119 options.body = body
120 }
121 }
122
123 // WithHTTPCallerTimeout is a functional parameter for a HTTPCaller which specifies request timeout.
124 // If this option is not provided the default one will be used. You can check default value in const defaultTimeout.
125 func WithHTTPCallerTimeout(timeout time.Duration) HTTPCallerOption {
126 return func(options *httpCallerOptions) {
127 options.timeout = timeout
128 }
129 }
130
131 // WithHTTPCallerIsValidResponse is a functional parameter for a HTTPCaller which specifies a function that
132 // will be used to assess whether a response is valid. If not specified, all responses will be treated as valid.
133 // You can read more explanation about this parameter in HTTPCaller annotation.
134 func WithHTTPCallerIsValidResponse(isValid func(response *http.Response, body []byte) bool) HTTPCallerOption {
135 return func(options *httpCallerOptions) {
136 options.isValidResponse = isValid
137 }
138 }
139
140 // WithHTTPCallerOnDNSStart is a functional parameter for a HTTPCaller which specifies a callback that will be
141 // called when dns resolving starts. You can read more explanation about this parameter in HTTPCaller annotation.
142 func WithHTTPCallerOnDNSStart(onDNSStart func(suite *TraceSuite, info httptrace.DNSStartInfo)) HTTPCallerOption {
143 return func(options *httpCallerOptions) {
144 options.onDNSStart = onDNSStart
145 }
146 }
147
148 // WithHTTPCallerOnDNSDone is a functional parameter for a HTTPCaller which specifies a callback that will be
149 // called when dns resolving ended. You can read more explanation about this parameter in HTTPCaller annotation.
150 func WithHTTPCallerOnDNSDone(onDNSDone func(suite *TraceSuite, info httptrace.DNSDoneInfo)) HTTPCallerOption {
151 return func(options *httpCallerOptions) {
152 options.onDNSDone = onDNSDone
153 }
154 }
155
156 // WithHTTPCallerOnConnStart is a functional parameter for a HTTPCaller which specifies a callback that will be
157 // called when connection establishment started. You can read more explanation about this parameter in HTTPCaller
158 // annotation.
159 func WithHTTPCallerOnConnStart(onConnStart func(suite *TraceSuite, network, addr string)) HTTPCallerOption {
160 return func(options *httpCallerOptions) {
161 options.onConnStart = onConnStart
162 }
163 }
164
165 // WithHTTPCallerOnConnDone is a functional parameter for a HTTPCaller which specifies a callback that will be
166 // called when connection establishment finished. You can read more explanation about this parameter in HTTPCaller
167 // annotation.
168 func WithHTTPCallerOnConnDone(conConnDone func(suite *TraceSuite, network, addr string, err error)) HTTPCallerOption {
169 return func(options *httpCallerOptions) {
170 options.onConnDone = conConnDone
171 }
172 }
173
174 // WithHTTPCallerOnTLSStart is a functional parameter for a HTTPCaller which specifies a callback that will be
175 // called when tls handshake started. You can read more explanation about this parameter in HTTPCaller annotation.
176 func WithHTTPCallerOnTLSStart(onTLSStart func(suite *TraceSuite)) HTTPCallerOption {
177 return func(options *httpCallerOptions) {
178 options.onTLSStart = onTLSStart
179 }
180 }
181
182 // WithHTTPCallerOnTLSDone is a functional parameter for a HTTPCaller which specifies a callback that will be
183 // called when tls handshake ended. You can read more explanation about this parameter in HTTPCaller annotation.
184 func WithHTTPCallerOnTLSDone(onTLSDone func(suite *TraceSuite, state tls.ConnectionState, err error)) HTTPCallerOption {
185 return func(options *httpCallerOptions) {
186 options.onTLSDone = onTLSDone
187 }
188 }
189
190 // WithHTTPCallerOnWroteRequest is a functional parameter for a HTTPCaller which specifies a callback that will be
191 // called when request has been written. You can read more explanation about this parameter in HTTPCaller annotation.
192 func WithHTTPCallerOnWroteRequest(onWroteRequest func(suite *TraceSuite)) HTTPCallerOption {
193 return func(options *httpCallerOptions) {
194 options.onWroteHeaders = onWroteRequest
195 }
196 }
197
198 // WithHTTPCallerOnFirstByteReceived is a functional parameter for a HTTPCaller which specifies a callback that will be
199 // called when first response byte has been received. You can read more explanation about this parameter in HTTPCaller
200 // annotation.
201 func WithHTTPCallerOnFirstByteReceived(onGotFirstByte func(suite *TraceSuite)) HTTPCallerOption {
202 return func(options *httpCallerOptions) {
203 options.onFirstByteReceived = onGotFirstByte
204 }
205 }
206
207 // WithHTTPCallerOnReq is a functional parameter for a HTTPCaller which specifies a callback that will be
208 // called before the start of the http call execution. You can read more explanation about this parameter in HTTPCaller
209 // annotation.
210 func WithHTTPCallerOnReq(onReq func(suite *TraceSuite)) HTTPCallerOption {
211 return func(options *httpCallerOptions) {
212 options.onReq = onReq
213 }
214 }
215
216 // WithHTTPCallerOnResp is a functional parameter for a HTTPCaller which specifies a callback that will be
217 // called when response is received. You can read more explanation about this parameter in HTTPCaller annotation.
218 func WithHTTPCallerOnResp(onResp func(suite *TraceSuite, info *HTTPCallInfo)) HTTPCallerOption {
219 return func(options *httpCallerOptions) {
220 options.onResp = onResp
221 }
222 }
223
224 // WithHTTPCallerLogger is a functional parameter for a HTTPCaller which specifies a logger.
225 // If not specified, logs will be omitted.
226 func WithHTTPCallerLogger(logger Logger) HTTPCallerOption {
227 return func(options *httpCallerOptions) {
228 options.logger = logger
229 }
230 }
231
232 // NewHTTPCaller returns a new HTTPCaller. URL parameter is the only required one, other options might be specified via
233 // functional parameters, otherwise default values will be used where applicable.
234 func NewHTTPCaller(url string, options ...HTTPCallerOption) *HTTPCaller {
235 opts := httpCallerOptions{
236 callFrequency: defaultHTTPCallFrequency,
237 maxConcurrentCalls: defaultHTTPMaxConcurrentCalls,
238 method: defaultHTTPMethod,
239 timeout: defaultTimeout,
240 client: &http.Client{},
241 }
242 for _, opt := range options {
243 opt(&opts)
244 }
245
246 return &HTTPCaller{
247 client: opts.client,
248
249 callFrequency: opts.callFrequency,
250 maxConcurrentCalls: opts.maxConcurrentCalls,
251
252 url: url,
253 host: opts.host,
254 headers: opts.headers,
255 method: opts.method,
256 body: opts.body,
257 timeout: opts.timeout,
258
259 isValidResponse: opts.isValidResponse,
260
261 workChan: make(chan struct{}, opts.maxConcurrentCalls),
262 doneChan: make(chan struct{}),
263
264 onDNSStart: opts.onDNSStart,
265 onDNSDone: opts.onDNSDone,
266 onConnStart: opts.onConnStart,
267 onConnDone: opts.onConnDone,
268 onTLSStart: opts.onTLSStart,
269 onTLSDone: opts.onTLSDone,
270 onWroteHeaders: opts.onWroteHeaders,
271 onFirstByteReceived: opts.onFirstByteReceived,
272 onReq: opts.onReq,
273 onResp: opts.onResp,
274
275 logger: opts.logger,
276 }
277 }
278
279 // HTTPCaller represents a prober performing http calls and collecting relevant statistics.
280 type HTTPCaller struct {
281 client *http.Client
282
283 // callFrequency is a parameter which specifies how often to send a new request. You might need to increase
284 // maxConcurrentCalls value to achieve required value.
285 callFrequency time.Duration
286
287 // maxConcurrentCalls is a maximum number of calls that might be performed concurrently. In other words,
288 // a number of "workers" that will try to perform probing concurrently.
289 // Default number is specified in defaultHTTPMaxConcurrentCalls
290 maxConcurrentCalls int
291
292 // url is an url which will be used in all probe requests, mandatory in constructor.
293 url string
294
295 // host allows to override a Host header
296 host string
297
298 // headers are headers that which will be used in all probe requests, default are none.
299 headers http.Header
300
301 // method is a http request method which will be used in all probe requests,
302 // default is specified in defaultHTTPMethod
303 method string
304
305 // body is a http request body which will be used in all probe requests, default is none.
306 body []byte
307
308 // timeout is a http call timeout, default is specified in defaultTimeout.
309 timeout time.Duration
310
311 // isValidResponse is a function that will be used to validate whether a response is valid up to clients choice.
312 // You can think of it as a verification that response contains data that you expected. This information will be
313 // passed back in HTTPCallInfo during an onResp callback and HTTPStatistics during an onFinish callback
314 // or a Statistics call.
315 isValidResponse func(response *http.Response, body []byte) bool
316
317 workChan chan struct{}
318 doneChan chan struct{}
319 doneWg sync.WaitGroup
320
321 // All callbacks except onReq and onResp are based on a httptrace callbacks, meaning they are called at the time
322 // and contain signature same as you would expect in httptrace library. In addition to that each callback has a
323 // TraceSuite as a first argument, which will help you to propagate data between these callbacks. You can read more
324 // about it in TraceSuite annotation.
325
326 // onDNSStart is a callback which is called when a dns lookup starts. It's based on a httptrace.DNSStart callback.
327 onDNSStart func(suite *TraceSuite, info httptrace.DNSStartInfo)
328 // onDNSDone is a callback which is called when a dns lookup ends. It's based on a httptrace.DNSDone callback.
329 onDNSDone func(suite *TraceSuite, info httptrace.DNSDoneInfo)
330 // onConnStart is a callback which is called when a connection dial starts. It's based on a httptrace.ConnectStart
331 // callback.
332 onConnStart func(suite *TraceSuite, network, addr string)
333 // onConnDone is a callback which is called when a connection dial ends. It's based on a httptrace.ConnectDone
334 // callback.
335 onConnDone func(suite *TraceSuite, network, addr string, err error)
336 // onTLSStart is a callback which is called when a tls handshake starts. It's based on a httptrace.TLSHandshakeStart
337 // callback.
338 onTLSStart func(suite *TraceSuite)
339 // onTLSDone is a callback which is called when a tls handshake ends. It's based on a httptrace.TLSHandshakeDone
340 // callback.
341 onTLSDone func(suite *TraceSuite, state tls.ConnectionState, err error)
342 // onWroteHeaders is a callback which is called when request headers where written. It's based on a
343 // httptrace.WroteHeaders callback.
344 onWroteHeaders func(suite *TraceSuite)
345 // onFirstByteReceived is a callback which is called when first response bytes were received. It's based on a
346 // httptrace.GotFirstResponseByte callback.
347 onFirstByteReceived func(suite *TraceSuite)
348
349 // onReq is a custom callback which is called before http client starts request execution.
350 onReq func(suite *TraceSuite)
351 // onResp is a custom callback which is called when a response is received.
352 onResp func(suite *TraceSuite, info *HTTPCallInfo)
353
354 // logger is a logger implementation, default is none.
355 logger Logger
356 }
357
358 // Stop gracefully stops the execution of a HTTPCaller.
359 func (c *HTTPCaller) Stop() {
360 close(c.doneChan)
361 c.doneWg.Wait()
362 }
363
364 // Run starts execution of a probing.
365 func (c *HTTPCaller) Run() {
366 c.run(context.Background())
367 }
368
369 // RunWithContext starts execution of a probing and allows providing a context.
370 func (c *HTTPCaller) RunWithContext(ctx context.Context) {
371 c.run(ctx)
372 }
373
374 func (c *HTTPCaller) run(ctx context.Context) {
375 c.runWorkScheduler(ctx)
376 c.runCallers(ctx)
377 c.doneWg.Wait()
378 }
379
380 func (c *HTTPCaller) runWorkScheduler(ctx context.Context) {
381 c.doneWg.Go(func() {
382
383 ticker := time.NewTicker(c.callFrequency)
384 defer ticker.Stop()
385
386 for {
387 select {
388 case <-ticker.C:
389 c.workChan <- struct{}{}
390 case <-ctx.Done():
391 return
392 case <-c.doneChan:
393 return
394 }
395 }
396 })
397 }
398
399 func (c *HTTPCaller) runCallers(ctx context.Context) {
400 for i := 0; i < c.maxConcurrentCalls; i++ {
401 c.doneWg.Go(func() {
402 for {
403 logger := c.logger
404 if logger == nil {
405 logger = NoopLogger{}
406 }
407 select {
408 case <-c.workChan:
409 if err := c.makeCall(ctx); err != nil {
410 logger.Errorf("failed making a call: %v", err)
411 }
412 case <-ctx.Done():
413 return
414 case <-c.doneChan:
415 return
416 }
417 }
418 })
419 }
420 }
421
422 // TraceSuite is a struct that is passed to each callback. It contains a bunch of time helpers, that you can use with
423 // a corresponding getter. These timers are set before making a corresponding callback, meaning that when an onDNSStart
424 // callback will be called - TraceSuite will already have filled dnsStart field. In addition to that, it contains
425 // an Extra field of type any which you can use in any custom way you might need. Before each callback call, mutex
426 // is used, meaning all operations inside your callback are concurrent-safe.
427 // Keep in mind, that if your http client set up to follow redirects - timers will be overwritten.
428 type TraceSuite struct {
429 mu sync.Mutex
430
431 generalStart time.Time
432 generalEnd time.Time
433 dnsStart time.Time
434 dnsEnd time.Time
435 connStart time.Time
436 connEnd time.Time
437 tlsStart time.Time
438 tlsEnd time.Time
439 wroteHeaders time.Time
440 firstByteReceived time.Time
441
442 Extra any
443 }
444
445 // GetGeneralStart returns a general http request execution start time.
446 func (s *TraceSuite) GetGeneralStart() time.Time {
447 return s.generalStart
448 }
449
450 // GetGeneralEnd returns a general http response time.
451 func (s *TraceSuite) GetGeneralEnd() time.Time {
452 return s.generalEnd
453 }
454
455 // GetDNSStart returns a time of a dns lookup start.
456 func (s *TraceSuite) GetDNSStart() time.Time {
457 return s.dnsStart
458 }
459
460 // GetDNSEnd returns a time of a dns lookup send.
461 func (s *TraceSuite) GetDNSEnd() time.Time {
462 return s.dnsEnd
463 }
464
465 // GetConnStart returns a time of a connection dial start.
466 func (s *TraceSuite) GetConnStart() time.Time {
467 return s.connStart
468 }
469
470 // GetConnEnd returns a time of a connection dial end.
471 func (s *TraceSuite) GetConnEnd() time.Time {
472 return s.connEnd
473 }
474
475 // GetTLSStart returns a time of a tls handshake start.
476 func (s *TraceSuite) GetTLSStart() time.Time {
477 return s.tlsStart
478 }
479
480 // GetTLSEnd returns a time of a tls handshake end.
481 func (s *TraceSuite) GetTLSEnd() time.Time {
482 return s.tlsEnd
483 }
484
485 // GetWroteHeaders returns a time when request headers were written.
486 func (s *TraceSuite) GetWroteHeaders() time.Time {
487 return s.wroteHeaders
488 }
489
490 // GetFirstByteReceived returns a time when first response bytes were received.
491 func (s *TraceSuite) GetFirstByteReceived() time.Time {
492 return s.firstByteReceived
493 }
494
495 func (c *HTTPCaller) getClientTrace(suite *TraceSuite) *httptrace.ClientTrace {
496 return &httptrace.ClientTrace{
497 DNSStart: func(info httptrace.DNSStartInfo) {
498 suite.mu.Lock()
499 defer suite.mu.Unlock()
500
501 suite.dnsStart = time.Now()
502 if c.onDNSStart != nil {
503 c.onDNSStart(suite, info)
504 }
505 },
506 DNSDone: func(info httptrace.DNSDoneInfo) {
507 suite.mu.Lock()
508 defer suite.mu.Unlock()
509
510 suite.dnsEnd = time.Now()
511 if c.onDNSDone != nil {
512 c.onDNSDone(suite, info)
513 }
514 },
515 ConnectStart: func(network, addr string) {
516 suite.mu.Lock()
517 defer suite.mu.Unlock()
518
519 suite.connStart = time.Now()
520 if c.onConnStart != nil {
521 c.onConnStart(suite, network, addr)
522 }
523 },
524 ConnectDone: func(network, addr string, err error) {
525 suite.mu.Lock()
526 defer suite.mu.Unlock()
527
528 suite.connEnd = time.Now()
529 if c.onConnDone != nil {
530 c.onConnDone(suite, network, addr, err)
531 }
532 },
533 TLSHandshakeStart: func() {
534 suite.mu.Lock()
535 defer suite.mu.Unlock()
536
537 suite.tlsStart = time.Now()
538 if c.onTLSStart != nil {
539 c.onTLSStart(suite)
540 }
541 },
542 TLSHandshakeDone: func(state tls.ConnectionState, err error) {
543 suite.mu.Lock()
544 defer suite.mu.Unlock()
545
546 suite.tlsEnd = time.Now()
547 if c.onTLSDone != nil {
548 c.onTLSDone(suite, state, err)
549 }
550 },
551 WroteHeaders: func() {
552 suite.mu.Lock()
553 defer suite.mu.Unlock()
554
555 suite.wroteHeaders = time.Now()
556 if c.onWroteHeaders != nil {
557 c.onWroteHeaders(suite)
558 }
559 },
560 GotFirstResponseByte: func() {
561 suite.mu.Lock()
562 defer suite.mu.Unlock()
563
564 suite.firstByteReceived = time.Now()
565 if c.onFirstByteReceived != nil {
566 c.onFirstByteReceived(suite)
567 }
568 },
569 }
570 }
571
572 func (c *HTTPCaller) makeCall(ctx context.Context) error {
573 ctx, cancel := context.WithTimeout(ctx, c.timeout)
574 defer cancel()
575
576 suite := TraceSuite{
577 generalStart: time.Now(),
578 }
579 traceCtx := httptrace.WithClientTrace(ctx, c.getClientTrace(&suite))
580 req, err := http.NewRequestWithContext(traceCtx, c.method, c.url, bytes.NewReader(c.body))
581 if err != nil {
582 return err
583 }
584 req.Header = c.headers
585 if c.host != "" {
586 req.Host = c.host
587 }
588
589 if c.onReq != nil {
590 suite.mu.Lock()
591 c.onReq(&suite)
592 suite.mu.Unlock()
593 }
594 resp, err := c.client.Do(req)
595 if err != nil {
596 return err
597 }
598 body, err := io.ReadAll(resp.Body)
599 if err != nil {
600 return err
601 }
602 resp.Body.Close()
603 isValidResponse := true
604 if c.isValidResponse != nil {
605 isValidResponse = c.isValidResponse(resp, body)
606 }
607 if c.onResp != nil {
608 suite.mu.Lock()
609 defer suite.mu.Unlock()
610
611 suite.generalEnd = time.Now()
612 c.onResp(&suite, &HTTPCallInfo{
613 StatusCode: resp.StatusCode,
614 IsValidResponse: isValidResponse,
615 })
616 }
617 return nil
618 }
619
620 // HTTPCallInfo represents a data set which passed as a function argument to an onResp callback.
621 type HTTPCallInfo struct {
622 // StatusCode is a response status code
623 StatusCode int
624
625 // IsValidResponse represents a fact of whether a response is treated as valid. You can read more about it in
626 // HTTPCaller annotation.
627 IsValidResponse bool
628 }