-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
85 lines (69 loc) · 1.71 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
package main
import (
"database/sql"
"fmt"
"log"
"net/http"
"os"
"time"
_ "github.com/mattn/go-sqlite3"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
const (
defaultHost = "0.0.0.0"
defaultPort = 9617
defaultTimeout = 5 * time.Second
metricsEndpoint = "/metrics"
readinessEndpoint = "/readiness"
livenessEndpoint = "/liveness"
sqlite3Driver = "sqlite3"
piholeDSNEnv = "PIHOLE_DSN"
)
var (
lastUpdate int64
piholeDB *sql.DB
)
func init() {
piholeDSN := os.Getenv(piholeDSNEnv)
if piholeDSN == "" {
log.Fatalln(piholeDSNEnv, "must be set")
}
var err error
piholeDB, err = sql.Open(sqlite3Driver, piholeDSN)
if err != nil {
log.Fatalf("open db connection: %s", err)
}
lastUpdate = time.Now().Unix()
}
func main() {
registry := buildMetrics()
handlerOpts := promhttp.HandlerOpts{
Registry: registry,
Timeout: defaultTimeout,
}
promHandler := promhttp.HandlerFor(registry, handlerOpts)
mux := http.NewServeMux()
mux.Handle(metricsEndpoint, metricsHandler(promHandler))
mux.HandleFunc(readinessEndpoint, okHandler)
mux.HandleFunc(livenessEndpoint, okHandler)
srv := &http.Server{
Addr: fmt.Sprintf("%s:%d", defaultHost, defaultPort),
Handler: mux,
}
log.Printf("Listening at %s:%d", defaultHost, defaultPort)
log.Fatal(srv.ListenAndServe())
}
func metricsHandler(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
unchanged := lastUpdate
lastUpdate = updateMetrics(piholeDB, lastUpdate)
if lastUpdate == unchanged {
w.WriteHeader(http.StatusInternalServerError)
return
}
handler.ServeHTTP(w, r)
})
}
func okHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}