/
http.go
600 lines (528 loc) · 18.6 KB
/
http.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
// Copyright 2016 The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package prober
import (
"context"
"errors"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"net/http/cookiejar"
"net/http/httptrace"
"net/textproto"
"net/url"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/log/level"
"github.com/prometheus/client_golang/prometheus"
pconfig "github.com/prometheus/common/config"
"golang.org/x/net/publicsuffix"
"github.com/sciencemesh/blackbox_exporter/config"
)
func matchRegularExpressions(reader io.Reader, httpConfig config.HTTPProbe, logger log.Logger) bool {
body, err := ioutil.ReadAll(reader)
if err != nil {
level.Error(logger).Log("msg", "Error reading HTTP body", "err", err)
return false
}
for _, expression := range httpConfig.FailIfBodyMatchesRegexp {
re, err := regexp.Compile(expression)
if err != nil {
level.Error(logger).Log("msg", "Could not compile regular expression", "regexp", expression, "err", err)
return false
}
if re.Match(body) {
level.Error(logger).Log("msg", "Body matched regular expression", "regexp", expression)
return false
}
}
for _, expression := range httpConfig.FailIfBodyNotMatchesRegexp {
re, err := regexp.Compile(expression)
if err != nil {
level.Error(logger).Log("msg", "Could not compile regular expression", "regexp", expression, "err", err)
return false
}
if !re.Match(body) {
level.Error(logger).Log("msg", "Body did not match regular expression", "regexp", expression)
return false
}
}
return true
}
func matchRegularExpressionsOnHeaders(header http.Header, httpConfig config.HTTPProbe, logger log.Logger) bool {
for _, headerMatchSpec := range httpConfig.FailIfHeaderMatchesRegexp {
values := header[textproto.CanonicalMIMEHeaderKey(headerMatchSpec.Header)]
if len(values) == 0 {
if !headerMatchSpec.AllowMissing {
level.Error(logger).Log("msg", "Missing required header", "header", headerMatchSpec.Header)
return false
} else {
continue // No need to match any regex on missing headers.
}
}
re, err := regexp.Compile(headerMatchSpec.Regexp)
if err != nil {
level.Error(logger).Log("msg", "Could not compile regular expression", "regexp", headerMatchSpec.Regexp, "err", err)
return false
}
for _, val := range values {
if re.MatchString(val) {
level.Error(logger).Log("msg", "Header matched regular expression", "header", headerMatchSpec.Header,
"regexp", headerMatchSpec.Regexp, "value_count", len(values))
return false
}
}
}
for _, headerMatchSpec := range httpConfig.FailIfHeaderNotMatchesRegexp {
values := header[textproto.CanonicalMIMEHeaderKey(headerMatchSpec.Header)]
if len(values) == 0 {
if !headerMatchSpec.AllowMissing {
level.Error(logger).Log("msg", "Missing required header", "header", headerMatchSpec.Header)
return false
} else {
continue // No need to match any regex on missing headers.
}
}
re, err := regexp.Compile(headerMatchSpec.Regexp)
if err != nil {
level.Error(logger).Log("msg", "Could not compile regular expression", "regexp", headerMatchSpec.Regexp, "err", err)
return false
}
anyHeaderValueMatched := false
for _, val := range values {
if re.MatchString(val) {
anyHeaderValueMatched = true
break
}
}
if !anyHeaderValueMatched {
level.Error(logger).Log("msg", "Header did not match regular expression", "header", headerMatchSpec.Header,
"regexp", headerMatchSpec.Regexp, "value_count", len(values))
return false
}
}
return true
}
// roundTripTrace holds timings for a single HTTP roundtrip.
type roundTripTrace struct {
tls bool
start time.Time
dnsDone time.Time
connectDone time.Time
gotConn time.Time
responseStart time.Time
end time.Time
}
// transport is a custom transport keeping traces for each HTTP roundtrip.
type transport struct {
Transport http.RoundTripper
NoServerNameTransport http.RoundTripper
firstHost string
logger log.Logger
mu sync.Mutex
traces []*roundTripTrace
current *roundTripTrace
}
func newTransport(rt, noServerName http.RoundTripper, logger log.Logger) *transport {
return &transport{
Transport: rt,
NoServerNameTransport: noServerName,
logger: logger,
traces: []*roundTripTrace{},
}
}
// RoundTrip switches to a new trace, then runs embedded RoundTripper.
func (t *transport) RoundTrip(req *http.Request) (*http.Response, error) {
level.Info(t.logger).Log("msg", "Making HTTP request", "url", req.URL.String(), "host", req.Host)
trace := &roundTripTrace{}
if req.URL.Scheme == "https" {
trace.tls = true
}
t.current = trace
t.traces = append(t.traces, trace)
if t.firstHost == "" {
t.firstHost = req.URL.Host
}
if t.firstHost != req.URL.Host {
// This is a redirect to something other than the initial host,
// so TLS ServerName should not be set.
level.Info(t.logger).Log("msg", "Address does not match first address, not sending TLS ServerName", "first", t.firstHost, "address", req.URL.Host)
return t.NoServerNameTransport.RoundTrip(req)
}
return t.Transport.RoundTrip(req)
}
func (t *transport) DNSStart(_ httptrace.DNSStartInfo) {
t.mu.Lock()
defer t.mu.Unlock()
t.current.start = time.Now()
}
func (t *transport) DNSDone(_ httptrace.DNSDoneInfo) {
t.mu.Lock()
defer t.mu.Unlock()
t.current.dnsDone = time.Now()
}
func (ts *transport) ConnectStart(_, _ string) {
ts.mu.Lock()
defer ts.mu.Unlock()
t := ts.current
// No DNS resolution because we connected to IP directly.
if t.dnsDone.IsZero() {
t.start = time.Now()
t.dnsDone = t.start
}
}
func (t *transport) ConnectDone(net, addr string, err error) {
t.mu.Lock()
defer t.mu.Unlock()
t.current.connectDone = time.Now()
}
func (t *transport) GotConn(_ httptrace.GotConnInfo) {
t.mu.Lock()
defer t.mu.Unlock()
t.current.gotConn = time.Now()
}
func (t *transport) GotFirstResponseByte() {
t.mu.Lock()
defer t.mu.Unlock()
t.current.responseStart = time.Now()
}
// byteCounter implements an io.ReadCloser that keeps track of the total
// number of bytes it has read.
type byteCounter struct {
io.ReadCloser
n int64
}
func (bc *byteCounter) Read(p []byte) (int, error) {
n, err := bc.ReadCloser.Read(p)
bc.n += int64(n)
return n, err
}
func ProbeHTTP(ctx context.Context, target string, values url.Values, module config.Module, registry *prometheus.Registry, logger log.Logger) (success bool) {
var redirects int
var (
durationGaugeVec = prometheus.NewGaugeVec(prometheus.GaugeOpts{
Name: "probe_http_duration_seconds",
Help: "Duration of http request by phase, summed over all redirects",
}, []string{"phase"})
contentLengthGauge = prometheus.NewGauge(prometheus.GaugeOpts{
Name: "probe_http_content_length",
Help: "Length of http content response",
})
bodyUncompressedLengthGauge = prometheus.NewGauge(prometheus.GaugeOpts{
Name: "probe_http_uncompressed_body_length",
Help: "Length of uncompressed response body",
})
redirectsGauge = prometheus.NewGauge(prometheus.GaugeOpts{
Name: "probe_http_redirects",
Help: "The number of redirects",
})
isSSLGauge = prometheus.NewGauge(prometheus.GaugeOpts{
Name: "probe_http_ssl",
Help: "Indicates if SSL was used for the final redirect",
})
statusCodeGauge = prometheus.NewGauge(prometheus.GaugeOpts{
Name: "probe_http_status_code",
Help: "Response HTTP status code",
})
probeSSLEarliestCertExpiryGauge = prometheus.NewGauge(prometheus.GaugeOpts{
Name: "probe_ssl_earliest_cert_expiry",
Help: "Returns earliest SSL cert expiry in unixtime",
})
probeSSLLastChainExpiryTimestampSeconds = prometheus.NewGauge(prometheus.GaugeOpts{
Name: "probe_ssl_last_chain_expiry_timestamp_seconds",
Help: "Returns last SSL chain expiry in timestamp seconds",
})
probeSSLLastInformation = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "probe_ssl_last_chain_info",
Help: "Contains SSL leaf certificate information",
},
[]string{"fingerprint_sha256"},
)
probeTLSVersion = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "probe_tls_version_info",
Help: "Contains the TLS version used",
},
[]string{"version"},
)
probeHTTPVersionGauge = prometheus.NewGauge(prometheus.GaugeOpts{
Name: "probe_http_version",
Help: "Returns the version of HTTP of the probe response",
})
probeFailedDueToRegex = prometheus.NewGauge(prometheus.GaugeOpts{
Name: "probe_failed_due_to_regex",
Help: "Indicates if probe failed due to regex",
})
probeHTTPLastModified = prometheus.NewGauge(prometheus.GaugeOpts{
Name: "probe_http_last_modified_timestamp_seconds",
Help: "Returns the Last-Modified HTTP response header in unixtime",
})
)
for _, lv := range []string{"resolve", "connect", "tls", "processing", "transfer"} {
durationGaugeVec.WithLabelValues(lv)
}
registry.MustRegister(durationGaugeVec)
registry.MustRegister(contentLengthGauge)
registry.MustRegister(bodyUncompressedLengthGauge)
registry.MustRegister(redirectsGauge)
registry.MustRegister(isSSLGauge)
registry.MustRegister(statusCodeGauge)
registry.MustRegister(probeHTTPVersionGauge)
registry.MustRegister(probeFailedDueToRegex)
httpConfig := module.HTTP
if !strings.HasPrefix(target, "http://") && !strings.HasPrefix(target, "https://") {
target = "http://" + target
}
targetURL, err := url.Parse(target)
if err != nil {
level.Error(logger).Log("msg", "Could not parse target URL", "err", err)
return false
}
targetHost := targetURL.Hostname()
targetPort := targetURL.Port()
ip, lookupTime, err := chooseProtocol(ctx, module.HTTP.IPProtocol, module.HTTP.IPProtocolFallback, targetHost, registry, logger)
if err != nil {
level.Error(logger).Log("msg", "Error resolving address", "err", err)
return false
}
durationGaugeVec.WithLabelValues("resolve").Add(lookupTime)
httpClientConfig := module.HTTP.HTTPClientConfig
if len(httpClientConfig.TLSConfig.ServerName) == 0 {
// If there is no `server_name` in tls_config, use
// the hostname of the target.
httpClientConfig.TLSConfig.ServerName = targetHost
}
client, err := pconfig.NewClientFromConfig(httpClientConfig, "http_probe", pconfig.WithKeepAlivesDisabled())
if err != nil {
level.Error(logger).Log("msg", "Error generating HTTP client", "err", err)
return false
}
httpClientConfig.TLSConfig.ServerName = ""
noServerName, err := pconfig.NewRoundTripperFromConfig(httpClientConfig, "http_probe", pconfig.WithKeepAlivesDisabled())
if err != nil {
level.Error(logger).Log("msg", "Error generating HTTP client without ServerName", "err", err)
return false
}
jar, err := cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List})
if err != nil {
level.Error(logger).Log("msg", "Error generating cookiejar", "err", err)
return false
}
client.Jar = jar
// Inject transport that tracks traces for each redirect,
// and does not set TLS ServerNames on redirect if needed.
tt := newTransport(client.Transport, noServerName, logger)
client.Transport = tt
client.CheckRedirect = func(r *http.Request, via []*http.Request) error {
level.Info(logger).Log("msg", "Received redirect", "location", r.Response.Header.Get("Location"))
redirects = len(via)
if redirects > 10 || !httpConfig.FollowRedirects {
level.Info(logger).Log("msg", "Not following redirect")
return errors.New("don't follow redirects")
}
return nil
}
if httpConfig.Method == "" {
httpConfig.Method = "GET"
}
// Replace the host field in the URL with the IP we resolved.
origHost := targetURL.Host
if targetPort == "" {
if strings.Contains(ip.String(), ":") {
targetURL.Host = "[" + ip.String() + "]"
} else {
targetURL.Host = ip.String()
}
} else {
targetURL.Host = net.JoinHostPort(ip.String(), targetPort)
}
var body io.Reader
var respBodyBytes int64
// If a body is configured, add it to the request.
if httpConfig.Body != "" {
body = strings.NewReader(httpConfig.Body)
}
request, err := http.NewRequest(httpConfig.Method, targetURL.String(), body)
request.Host = origHost
request = request.WithContext(ctx)
if err != nil {
level.Error(logger).Log("msg", "Error creating request", "err", err)
return
}
for key, value := range httpConfig.Headers {
if strings.Title(key) == "Host" {
request.Host = value
continue
}
request.Header.Set(key, value)
}
trace := &httptrace.ClientTrace{
DNSStart: tt.DNSStart,
DNSDone: tt.DNSDone,
ConnectStart: tt.ConnectStart,
ConnectDone: tt.ConnectDone,
GotConn: tt.GotConn,
GotFirstResponseByte: tt.GotFirstResponseByte,
}
request = request.WithContext(httptrace.WithClientTrace(request.Context(), trace))
resp, err := client.Do(request)
// Err won't be nil if redirects were turned off. See https://github.com/golang/go/issues/3795
if err != nil && resp == nil {
level.Error(logger).Log("msg", "Error for HTTP request", "err", err)
} else {
requestErrored := (err != nil)
level.Info(logger).Log("msg", "Received HTTP response", "status_code", resp.StatusCode)
if len(httpConfig.ValidStatusCodes) != 0 {
for _, code := range httpConfig.ValidStatusCodes {
if resp.StatusCode == code {
success = true
break
}
}
if !success {
level.Info(logger).Log("msg", "Invalid HTTP response status code", "status_code", resp.StatusCode,
"valid_status_codes", fmt.Sprintf("%v", httpConfig.ValidStatusCodes))
}
} else if 200 <= resp.StatusCode && resp.StatusCode < 300 {
success = true
} else {
level.Info(logger).Log("msg", "Invalid HTTP response status code, wanted 2xx", "status_code", resp.StatusCode)
}
if success && (len(httpConfig.FailIfHeaderMatchesRegexp) > 0 || len(httpConfig.FailIfHeaderNotMatchesRegexp) > 0) {
success = matchRegularExpressionsOnHeaders(resp.Header, httpConfig, logger)
if success {
probeFailedDueToRegex.Set(0)
} else {
probeFailedDueToRegex.Set(1)
}
}
byteCounter := &byteCounter{ReadCloser: resp.Body}
if success && (len(httpConfig.FailIfBodyMatchesRegexp) > 0 || len(httpConfig.FailIfBodyNotMatchesRegexp) > 0) {
success = matchRegularExpressions(byteCounter, httpConfig, logger)
if success {
probeFailedDueToRegex.Set(0)
} else {
probeFailedDueToRegex.Set(1)
}
}
if resp != nil && !requestErrored {
_, err = io.Copy(ioutil.Discard, byteCounter)
if err != nil {
level.Info(logger).Log("msg", "Failed to read HTTP response body", "err", err)
success = false
}
respBodyBytes = byteCounter.n
if err := byteCounter.Close(); err != nil {
// We have already read everything we could from the server. The error here might be a
// TCP error. Log it in case it contains useful information as to what's the problem.
level.Info(logger).Log("msg", "Error while closing response from server", "error", err.Error())
}
}
// At this point body is fully read and we can write end time.
tt.current.end = time.Now()
// Check if there is a Last-Modified HTTP response header.
if t, err := http.ParseTime(resp.Header.Get("Last-Modified")); err == nil {
registry.MustRegister(probeHTTPLastModified)
probeHTTPLastModified.Set(float64(t.Unix()))
}
var httpVersionNumber float64
httpVersionNumber, err = strconv.ParseFloat(strings.TrimPrefix(resp.Proto, "HTTP/"), 64)
if err != nil {
level.Error(logger).Log("msg", "Error parsing version number from HTTP version", "err", err)
}
probeHTTPVersionGauge.Set(httpVersionNumber)
if len(httpConfig.ValidHTTPVersions) != 0 {
found := false
for _, version := range httpConfig.ValidHTTPVersions {
if version == resp.Proto {
found = true
break
}
}
if !found {
level.Error(logger).Log("msg", "Invalid HTTP version number", "version", resp.Proto)
success = false
}
}
}
if resp == nil {
resp = &http.Response{}
}
tt.mu.Lock()
defer tt.mu.Unlock()
for i, trace := range tt.traces {
level.Info(logger).Log(
"msg", "Response timings for roundtrip",
"roundtrip", i,
"start", trace.start,
"dnsDone", trace.dnsDone,
"connectDone", trace.connectDone,
"gotConn", trace.gotConn,
"responseStart", trace.responseStart,
"end", trace.end,
)
// We get the duration for the first request from chooseProtocol.
if i != 0 {
durationGaugeVec.WithLabelValues("resolve").Add(trace.dnsDone.Sub(trace.start).Seconds())
}
// Continue here if we never got a connection because a request failed.
if trace.gotConn.IsZero() {
continue
}
if trace.tls {
// dnsDone must be set if gotConn was set.
durationGaugeVec.WithLabelValues("connect").Add(trace.connectDone.Sub(trace.dnsDone).Seconds())
durationGaugeVec.WithLabelValues("tls").Add(trace.gotConn.Sub(trace.dnsDone).Seconds())
} else {
durationGaugeVec.WithLabelValues("connect").Add(trace.gotConn.Sub(trace.dnsDone).Seconds())
}
// Continue here if we never got a response from the server.
if trace.responseStart.IsZero() {
continue
}
durationGaugeVec.WithLabelValues("processing").Add(trace.responseStart.Sub(trace.gotConn).Seconds())
// Continue here if we never read the full response from the server.
// Usually this means that request either failed or was redirected.
if trace.end.IsZero() {
continue
}
durationGaugeVec.WithLabelValues("transfer").Add(trace.end.Sub(trace.responseStart).Seconds())
}
if resp.TLS != nil {
isSSLGauge.Set(float64(1))
registry.MustRegister(probeSSLEarliestCertExpiryGauge, probeTLSVersion, probeSSLLastChainExpiryTimestampSeconds, probeSSLLastInformation)
probeSSLEarliestCertExpiryGauge.Set(float64(getEarliestCertExpiry(resp.TLS).Unix()))
probeTLSVersion.WithLabelValues(getTLSVersion(resp.TLS)).Set(1)
probeSSLLastChainExpiryTimestampSeconds.Set(float64(getLastChainExpiry(resp.TLS).Unix()))
probeSSLLastInformation.WithLabelValues(getFingerprint(resp.TLS)).Set(1)
if httpConfig.FailIfSSL {
level.Error(logger).Log("msg", "Final request was over SSL")
success = false
}
} else if httpConfig.FailIfNotSSL {
level.Error(logger).Log("msg", "Final request was not over SSL")
success = false
}
statusCodeGauge.Set(float64(resp.StatusCode))
contentLengthGauge.Set(float64(resp.ContentLength))
bodyUncompressedLengthGauge.Set(float64(respBodyBytes))
redirectsGauge.Set(float64(redirects))
return
}