forked from prometheus/blackbox_exporter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
264 lines (233 loc) · 7.99 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
// 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/url"
"regexp"
"strconv"
"strings"
"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"
"github.com/prometheus/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.FailIfMatchesRegexp {
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.FailIfNotMatchesRegexp {
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 ProbeHTTP(ctx context.Context, target string, module config.Module, registry *prometheus.Registry, logger log.Logger) (success bool) {
var redirects int
var (
contentLengthGauge = prometheus.NewGauge(prometheus.GaugeOpts{
Name: "content_length",
Help: "Length of http content response",
})
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",
})
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",
})
)
registry.MustRegister(contentLengthGauge)
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, targetPort, err := net.SplitHostPort(targetURL.Host)
// If split fails, assuming it's a hostname without port part.
if err != nil {
targetHost = targetURL.Host
}
ip, err := chooseProtocol(module.HTTP.PreferredIPProtocol, targetHost, registry, logger)
if err != nil {
level.Error(logger).Log("msg", "Error resolving address", "err", err)
return false
}
httpClientConfig := &module.HTTP.HTTPClientConfig
client, err := pconfig.NewHTTPClientFromConfig(httpClientConfig)
if err != nil {
level.Error(logger).Log("msg", "Error generating HTTP client", "err", err)
return false
}
client.CheckRedirect = func(r *http.Request, via []*http.Request) error {
level.Info(logger).Log("msg", "Received redirect", "url", r.URL.String())
redirects = len(via)
if redirects > 10 || httpConfig.NoFollowRedirects {
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 == "" {
targetURL.Host = "[" + ip.String() + "]"
} else {
targetURL.Host = net.JoinHostPort(ip.String(), targetPort)
}
request, err := http.NewRequest(httpConfig.Method, targetURL.String(), nil)
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)
}
// If a body is configured, add it to the request.
if httpConfig.Body != "" {
request.Body = ioutil.NopCloser(strings.NewReader(httpConfig.Body))
}
level.Info(logger).Log("msg", "Making HTTP request", "url", request.URL.String(), "host", request.Host)
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 {
defer resp.Body.Close()
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.FailIfMatchesRegexp) > 0 || len(httpConfig.FailIfNotMatchesRegexp) > 0) {
success = matchRegularExpressions(resp.Body, httpConfig, logger)
if success {
probeFailedDueToRegex.Set(0)
} else {
probeFailedDueToRegex.Set(1)
}
}
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", httpVersionNumber)
success = false
}
}
}
if resp == nil {
resp = &http.Response{}
}
if resp.TLS != nil {
isSSLGauge.Set(float64(1))
registry.MustRegister(probeSSLEarliestCertExpiryGauge)
probeSSLEarliestCertExpiryGauge.Set(float64(getEarliestCertExpiry(resp.TLS).UnixNano() / 1e9))
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))
redirectsGauge.Set(float64(redirects))
return
}