-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathprobe.go
77 lines (62 loc) · 2.01 KB
/
probe.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
package main
import (
"context"
"fmt"
"net/http"
"strconv"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"go.uber.org/zap"
"github.com/webdevops/shelly-plug-exporter/shellyplug"
)
const (
DefaultTimeout = 30
)
func newShellyProber(ctx context.Context, registry *prometheus.Registry, logger *zap.SugaredLogger) *shellyplug.ShellyPlug {
sp := shellyplug.New(ctx, registry, logger)
sp.SetUserAgent(UserAgent + gitTag)
sp.SetTimeout(Opts.Shelly.Request.Timeout)
if len(Opts.Shelly.Auth.Username) >= 1 {
sp.SetHttpAuth(Opts.Shelly.Auth.Username, Opts.Shelly.Auth.Password)
}
return sp
}
func shellyProbeDiscovery(w http.ResponseWriter, r *http.Request) {
var err error
var timeoutSeconds float64
// startTime := time.Now()
contextLogger := buildContextLoggerFromRequest(r)
registry := prometheus.NewRegistry()
// If a timeout is configured via the Prometheus header, add it to the request.
timeoutSeconds, err = getPrometheusTimeout(r, DefaultTimeout)
if err != nil {
contextLogger.Error(err)
http.Error(w, fmt.Sprintf("failed to parse timeout from Prometheus header: %s", err), http.StatusBadRequest)
return
}
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeoutSeconds*float64(time.Second)))
defer cancel()
r = r.WithContext(ctx)
sp := newShellyProber(ctx, registry, contextLogger)
sp.UseDiscovery()
sp.Run()
h := promhttp.HandlerFor(registry, promhttp.HandlerOpts{})
h.ServeHTTP(w, r)
}
func buildContextLoggerFromRequest(r *http.Request) *zap.SugaredLogger {
return logger.With(zap.String("requestPath", r.URL.Path))
}
func getPrometheusTimeout(r *http.Request, defaultTimeout float64) (timeout float64, err error) {
// If a timeout is configured via the Prometheus header, add it to the request.
if v := r.Header.Get("X-Prometheus-Scrape-Timeout-Seconds"); v != "" {
timeout, err = strconv.ParseFloat(v, 64)
if err != nil {
return
}
}
if timeout == 0 {
timeout = defaultTimeout
}
return
}