forked from hoesler/kafka-connect-exporter
-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
73 lines (64 loc) · 1.67 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
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"time"
"github.com/caarlos0/env"
"github.com/go-kafka/connect"
"github.com/pkg/errors"
prom "github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/snahelou/kafka-connect-exporter/prometheus"
)
type config struct {
KafkaConnectHost string `env:"KAFKA_CONNECT_HOST"`
Port int `env:"PORT" envDefault:"9400"`
}
func graceful(srv *http.Server, timeout time.Duration) error {
stop := make(chan os.Signal)
signal.Notify(stop, os.Interrupt, os.Kill)
errC := make(chan error)
go func() {
defer close(errC)
if err := srv.ListenAndServe(); err != nil {
errC <- err
}
}()
select {
case err := <-errC:
return err
case <-stop:
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
return srv.Shutdown(ctx)
}
}
func main() {
cfg := new(config)
if err := env.Parse(cfg); err != nil {
log.Fatal(err)
}
// set up connect api refresh
client := connect.NewClient(cfg.KafkaConnectHost)
metrics := prometheus.NewMetrics(client)
prom.MustRegister(metrics)
// expose metrics via http
addr := fmt.Sprintf(":%d", cfg.Port)
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if err := metrics.Update(); err != nil {
log.Print(errors.WithStack(errors.WithMessage(err, "calling kafka connect API")))
//w.WriteHeader(500)
//w.Write([]byte(errors.Cause(err).Error()))
return
}
promhttp.Handler().ServeHTTP(w, r)
})
timeout := 10 * time.Second
if err := graceful(&http.Server{Addr: addr, Handler: handler}, timeout); err != nil {
log.Fatal(err)
}
}