-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
82 lines (71 loc) · 1.77 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
// ConnectBox exporter reads metrics from ConnectBox router using HTTP API,
// and returns them in Prometheus format.
package main
import (
"context"
"errors"
"flag"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/tetafro/connectbox"
)
func main() {
ctx, cancel := signal.NotifyContext(
context.Background(),
os.Interrupt,
syscall.SIGTERM,
)
defer cancel()
configFile := flag.String("config", "./config.yml", "path to config file")
flag.Parse()
conf, err := ReadConfig(*configFile)
if err != nil {
log.Fatalf("Failed to read config: %v", err)
}
// Create a client for each target
targets := map[string]ConnectBox{}
for _, t := range conf.Targets {
client, err := connectbox.NewClient(
t.Addr,
t.Username,
t.Password,
)
if err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatalf("Failed to init ConnectBox client: %v", err)
}
targets[t.Addr] = client
}
// Init prometheus metrics collector
collector := NewCollector(conf.Timeout, targets)
// Create HTTP server
mux := http.NewServeMux()
mux.Handle("/metrics", promhttp.Handler())
mux.Handle("/probe", collector)
//nolint:gosec
srv := http.Server{
Addr: conf.ListenAddr,
Handler: mux,
}
// Run HTTP server
go func() {
log.Printf("Listening on %s...", conf.ListenAddr)
err := srv.ListenAndServe()
if err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Printf("HTTP server error: %v", err)
}
}()
// Wait for SIGTERM/SIGINT
<-ctx.Done()
// Shutdown gracefully
ctx, cancel = context.WithTimeout(context.Background(), conf.Timeout)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
log.Printf("HTTP server shutdown error: %v", err)
}
fmt.Println("Shutdown gracefully")
}