-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
219 lines (177 loc) · 4.89 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
package main
import (
"fmt"
"log/slog"
"net/http"
"net/http/pprof"
"os"
"os/signal"
"syscall"
"time"
_ "time/tzdata"
"github.com/alecthomas/kingpin/v2"
"github.com/hairyhenderson/hitron_coda_exporter/internal/version"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var (
sc = &safeConfig{
C: &config{},
}
reloadCh chan chan error
)
func handler(w http.ResponseWriter, r *http.Request) {
slog.DebugContext(r.Context(), "Starting scrape")
start := time.Now()
sc.RLock()
conf := *sc.C
sc.RUnlock()
registry := prometheus.NewRegistry()
collector := newCollector(r.Context(), conf)
registry.MustRegister(collector)
// Delegate http serving to Prometheus client library, which will call collector.Collect.
h := promhttp.HandlerFor(registry, promhttp.HandlerOpts{})
h.ServeHTTP(w, r)
duration := time.Since(start).Seconds()
exporterDurationSummary.Observe(duration)
exporterDuration.Observe(duration)
slog.DebugContext(r.Context(), "Finished scrape", slog.Float64("duration_seconds", duration))
}
func handleHUP(configFile string) {
hup := make(chan os.Signal, 1)
signal.Notify(hup, syscall.SIGHUP)
reloadCh = make(chan chan error)
go func() {
for {
select {
case <-hup:
if err := sc.ReloadConfig(configFile); err != nil {
slog.Error("Error reloading config", "err", err)
} else {
slog.Info("Loaded config file")
}
case rc := <-reloadCh:
if err := sc.ReloadConfig(configFile); err != nil {
slog.Error("Error reloading config", "err", err)
rc <- err
} else {
slog.Info("Loaded config file")
rc <- nil
}
}
}
}()
}
func initRoutes() http.Handler {
mux := http.NewServeMux()
mux.Handle("/metrics", promhttp.Handler())
// Endpoint to do scrapes.
mux.HandleFunc("/scrape", func(w http.ResponseWriter, r *http.Request) {
handler(w, r)
})
mux.HandleFunc("/-/reload", func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "POST":
slog.DebugContext(r.Context(), "Reloading config from HTTP endpoint")
rc := make(chan error)
reloadCh <- rc
if err := <-rc; err != nil {
http.Error(w, fmt.Sprintf("failed to reload config: %s", err), http.StatusInternalServerError)
}
default:
http.Error(w, "POST method expected", http.StatusMethodNotAllowed)
}
})
mux.HandleFunc("/", func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(`<html>
<head>
<title>Hitron CODA Cable Modem Exporter</title>
<style>
label{
display:inline-block;
width:75px;
}
form label {
margin: 10px;
}
form input {
margin: 10px;
}
</style>
</head>
<body>
<h1>Hitron CODA Cable Modem Exporter</h1>
<form action="/scrape">
<input type="submit" value="/scrape">
</form>
</body>
</html>`))
})
mux.HandleFunc("/debug/pprof/", pprof.Index)
mux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
mux.HandleFunc("/debug/pprof/trace", pprof.Trace)
return mux
}
func main() {
exitCode := 0
defer func() { os.Exit(exitCode) }()
level := "info"
format := "logfmt"
configFile := "hitron_coda.yml"
listenAddress := ":9780"
kingpin.HelpFlag.Short('h')
kingpin.Version(version.Version)
kingpin.CommandLine.VersionFlag.Short('v')
kingpin.Flag("log.level", "log level (debug, info, warn, error)").Default("info").StringVar(&level)
kingpin.Flag("log.format", "log format (logfmt, json)").Default("logfmt").StringVar(&format)
kingpin.Flag("config.file", "Path to configuration file.").Default("hitron_coda.yml").StringVar(&configFile)
kingpin.Flag("web.listen-address", "Address to listen on for web interface and telemetry.").Default(":9780").StringVar(&listenAddress)
kingpin.Parse()
initExporterMetrics()
initLogger(level, format)
slog.Info("Starting hitron_coda_exporter", "version", version.Version, "commit", version.GitCommit)
// Bail early if the config is bad.
err := sc.ReloadConfig(configFile)
if err != nil {
slog.Error("Error parsing config file", "err", err)
exitCode = 1
return
}
handleHUP(configFile)
mux := initRoutes()
slog.Info("Listening on", "address", listenAddress)
srv := &http.Server{
Addr: listenAddress,
Handler: mux,
//nolint:gomnd
ReadHeaderTimeout: 2 * time.Second,
}
if err := srv.ListenAndServe(); err != nil {
slog.Error("Error starting HTTP server", "err", err)
exitCode = 1
}
}
func initLogger(level, format string) {
lvl := slog.LevelInfo
switch level {
case "debug":
lvl = slog.LevelDebug
case "info":
lvl = slog.LevelInfo
case "warn":
lvl = slog.LevelWarn
case "error":
lvl = slog.LevelError
}
opts := &slog.HandlerOptions{Level: lvl}
var handler slog.Handler
switch format {
case "json":
handler = slog.NewJSONHandler(os.Stderr, opts)
default:
handler = slog.NewTextHandler(os.Stderr, opts)
}
slog.SetDefault(slog.New(handler))
}