forked from prometheus/blackbox_exporter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
328 lines (293 loc) · 9.79 KB
/
main.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
// 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 main
import (
"bytes"
"context"
"fmt"
"html"
"net/http"
"os"
"os/signal"
"strconv"
"syscall"
"time"
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/log/level"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/prometheus/common/expfmt"
"github.com/prometheus/common/promlog"
"github.com/prometheus/common/promlog/flag"
"github.com/prometheus/common/version"
"gopkg.in/alecthomas/kingpin.v2"
"gopkg.in/yaml.v2"
"github.com/prometheus/blackbox_exporter/config"
"github.com/prometheus/blackbox_exporter/prober"
)
var (
sc = &config.SafeConfig{
C: &config.Config{},
}
configFile = kingpin.Flag("config.file", "Blackbox exporter configuration file.").Default("blackbox.yml").String()
listenAddress = kingpin.Flag("web.listen-address", "The address to listen on for HTTP requests.").Default(":9115").String()
timeoutOffset = kingpin.Flag("timeout-offset", "Offset to subtract from timeout in seconds.").Default("0.5").Float64()
Probers = map[string]prober.ProbeFn{
"http": prober.ProbeHTTP,
"tcp": prober.ProbeTCP,
"icmp": prober.ProbeICMP,
"dns": prober.ProbeDNS,
}
)
func probeHandler(w http.ResponseWriter, r *http.Request, c *config.Config, logger log.Logger, rh *resultHistory) {
moduleName := r.URL.Query().Get("module")
if moduleName == "" {
moduleName = "http_2xx"
}
module, ok := c.Modules[moduleName]
if !ok {
http.Error(w, fmt.Sprintf("Unknown module %q", moduleName), 400)
return
}
// If a timeout is configured via the Prometheus header, add it to the request.
var timeoutSeconds float64
if v := r.Header.Get("X-Prometheus-Scrape-Timeout-Seconds"); v != "" {
var err error
timeoutSeconds, err = strconv.ParseFloat(v, 64)
if err != nil {
http.Error(w, fmt.Sprintf("Failed to parse timeout from Prometheus header: %s", err), http.StatusInternalServerError)
return
}
}
if timeoutSeconds == 0 {
timeoutSeconds = 10
}
if module.Timeout.Seconds() < timeoutSeconds && module.Timeout.Seconds() > 0 {
timeoutSeconds = module.Timeout.Seconds()
}
timeoutSeconds -= *timeoutOffset
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeoutSeconds*1e9))
defer cancel()
r = r.WithContext(ctx)
probeSuccessGauge := prometheus.NewGauge(prometheus.GaugeOpts{
Name: "probe_success",
Help: "Displays whether or not the probe was a success",
})
probeDurationGauge := prometheus.NewGauge(prometheus.GaugeOpts{
Name: "probe_duration_seconds",
Help: "Returns how long the probe took to complete in seconds",
})
params := r.URL.Query()
target := params.Get("target")
if target == "" {
http.Error(w, "Target parameter is missing", 400)
return
}
prober, ok := Probers[module.Prober]
if !ok {
http.Error(w, fmt.Sprintf("Unknown prober %q", module.Prober), 400)
return
}
sl := newScrapeLogger(logger, moduleName, target)
level.Info(sl).Log("msg", "Beginning probe", "probe", module.Prober, "timeout_seconds", timeoutSeconds)
start := time.Now()
registry := prometheus.NewRegistry()
registry.MustRegister(probeSuccessGauge)
registry.MustRegister(probeDurationGauge)
success := prober(ctx, target, module, registry, sl)
duration := time.Since(start).Seconds()
probeDurationGauge.Set(duration)
if success {
probeSuccessGauge.Set(1)
level.Info(sl).Log("msg", "Probe succeeded", "duration_seconds", duration)
} else {
level.Error(sl).Log("msg", "Probe failed", "duration_seconds", duration)
}
debugOutput := DebugOutput(&module, &sl.buffer, registry)
rh.Add(moduleName, target, debugOutput, success)
if r.URL.Query().Get("debug") == "true" {
w.Header().Set("Content-Type", "text/plain")
w.Write([]byte(debugOutput))
return
}
h := promhttp.HandlerFor(registry, promhttp.HandlerOpts{})
h.ServeHTTP(w, r)
}
type scrapeLogger struct {
next log.Logger
module string
target string
buffer bytes.Buffer
bufferLogger log.Logger
}
func newScrapeLogger(logger log.Logger, module string, target string) *scrapeLogger {
logger = log.With(logger, "module", module, "target", target)
sl := &scrapeLogger{
next: logger,
buffer: bytes.Buffer{},
}
bl := log.NewLogfmtLogger(&sl.buffer)
sl.bufferLogger = log.With(bl, "ts", log.DefaultTimestampUTC, "caller", log.Caller(6), "module", module, "target", target)
return sl
}
func (sl scrapeLogger) Log(keyvals ...interface{}) error {
sl.bufferLogger.Log(keyvals...)
kvs := make([]interface{}, len(keyvals))
copy(kvs, keyvals)
// Switch level to debug for application output.
for i := 0; i < len(kvs); i += 2 {
if kvs[i] == level.Key() {
kvs[i+1] = level.DebugValue()
}
}
return sl.next.Log(kvs...)
}
// Returns plaintext debug output for a probe.
func DebugOutput(module *config.Module, logBuffer *bytes.Buffer, registry *prometheus.Registry) string {
buf := &bytes.Buffer{}
fmt.Fprintf(buf, "Logs for the probe:\n")
logBuffer.WriteTo(buf)
fmt.Fprintf(buf, "\n\n\nMetrics that would have been returned:\n")
mfs, err := registry.Gather()
if err != nil {
fmt.Fprintf(buf, "Error gathering metrics: %s\n", err)
}
for _, mf := range mfs {
expfmt.MetricFamilyToText(buf, mf)
}
fmt.Fprintf(buf, "\n\n\nModule configuration:\n")
c, err := yaml.Marshal(module)
if err != nil {
fmt.Fprintf(buf, "Error marshalling config: %s\n", err)
}
buf.Write(c)
return buf.String()
}
func init() {
prometheus.MustRegister(version.NewCollector("blackbox_exporter"))
}
func main() {
allowedLevel := promlog.AllowedLevel{}
flag.AddFlags(kingpin.CommandLine, &allowedLevel)
kingpin.Version(version.Print("blackbox_exporter"))
kingpin.HelpFlag.Short('h')
kingpin.Parse()
logger := promlog.New(allowedLevel)
rh := &resultHistory{}
level.Info(logger).Log("msg", "Starting blackbox_exporter", "version", version.Info())
level.Info(logger).Log("msg", "Build context", version.BuildContext())
if err := sc.ReloadConfig(*configFile); err != nil {
level.Error(logger).Log("msg", "Error loading config", "err", err)
os.Exit(1)
}
level.Info(logger).Log("msg", "Loaded config file")
hup := make(chan os.Signal)
reloadCh := make(chan chan error)
signal.Notify(hup, syscall.SIGHUP)
go func() {
for {
select {
case <-hup:
if err := sc.ReloadConfig(*configFile); err != nil {
level.Error(logger).Log("msg", "Error reloading config", "err", err)
continue
}
level.Info(logger).Log("msg", "Reloaded config file")
case rc := <-reloadCh:
if err := sc.ReloadConfig(*configFile); err != nil {
level.Error(logger).Log("msg", "Error reloading config", "err", err)
rc <- err
} else {
level.Info(logger).Log("msg", "Reloaded config file")
rc <- nil
}
}
}
}()
http.HandleFunc("/-/reload",
func(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
w.WriteHeader(http.StatusMethodNotAllowed)
fmt.Fprintf(w, "This endpoint requires a POST request.\n")
return
}
rc := make(chan error)
reloadCh <- rc
if err := <-rc; err != nil {
http.Error(w, fmt.Sprintf("failed to reload config: %s", err), http.StatusInternalServerError)
}
})
http.Handle("/metrics", promhttp.Handler())
http.HandleFunc("/probe", func(w http.ResponseWriter, r *http.Request) {
sc.Lock()
conf := sc.C
sc.Unlock()
probeHandler(w, r, conf, logger, rh)
})
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
w.Write([]byte(`<html>
<head><title>Blackbox Exporter</title></head>
<body>
<h1>Blackbox Exporter</h1>
<p><a href="/probe?target=prometheus.io&module=http_2xx">Probe prometheus.io for http_2xx</a></p>
<p><a href="/probe?target=prometheus.io&module=http_2xx&debug=true">Debug probe prometheus.io for http_2xx</a></p>
<p><a href="/metrics">Metrics</a></p>
<p><a href="/config">Configuration</a></p>
<h2>Recent Probes</h2>
<table border='1'><tr><th>Module</th><th>Target</th><th>Result</th><th>Debug</th>`))
results := rh.List()
for i := len(results) - 1; i >= 0; i-- {
r := results[i]
success := "Success"
if !r.success {
success = "<strong>Failure</strong>"
}
fmt.Fprintf(w, "<tr><td>%s</td><td>%s</td><td>%s</td><td><a href='logs?id=%d'>Logs</a></td></td>",
html.EscapeString(r.moduleName), html.EscapeString(r.target), success, r.id)
}
w.Write([]byte(`</table></body>
</html>`))
})
http.HandleFunc("/logs", func(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseInt(r.URL.Query().Get("id"), 10, 64)
if err != nil {
http.Error(w, "Invalid probe id", 500)
return
}
result := rh.Get(id)
if result == nil {
http.Error(w, "Probe id not found", 404)
return
}
w.Header().Set("Content-Type", "text/plain")
w.Write([]byte(result.debugOutput))
})
http.HandleFunc("/config", func(w http.ResponseWriter, r *http.Request) {
sc.RLock()
c, err := yaml.Marshal(sc.C)
sc.RUnlock()
if err != nil {
level.Warn(logger).Log("msg", "Error marshalling configuration", "err", err)
http.Error(w, err.Error(), 500)
return
}
w.Header().Set("Content-Type", "text/plain")
w.Write(c)
})
level.Info(logger).Log("msg", "Listening on address", "address", *listenAddress)
if err := http.ListenAndServe(*listenAddress, nil); err != nil {
level.Error(logger).Log("msg", "Error starting HTTP server", "err", err)
os.Exit(1)
}
}