forked from k3s-io/kine
/
server.go
74 lines (63 loc) · 1.85 KB
/
server.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
package metrics
import (
"context"
"net"
"net/http"
"net/http/pprof"
"github.com/AdamShannag/ora-kine/pkg/tls"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/sirupsen/logrus"
)
type Config struct {
ServerAddress string
ServerTLSConfig tls.Config
EnableProfiling bool
}
const (
defaultBindAddress = ":8080"
metricsPath = "/metrics"
)
func Serve(ctx context.Context, config Config) {
if config.ServerAddress == "" {
config.ServerAddress = defaultBindAddress
}
if config.ServerAddress == "0" {
return
}
logrus.Infof("metrics server is starting to listen at %s", config.ServerAddress)
listener, err := net.Listen("tcp", config.ServerAddress)
if err != nil {
logrus.Fatalf("error creating the metrics listener: %v", err)
}
handler := promhttp.HandlerFor(Registry, promhttp.HandlerOpts{
ErrorHandling: promhttp.HTTPErrorOnError,
})
mux := http.NewServeMux()
mux.Handle(metricsPath, handler)
if config.EnableProfiling {
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)
}
server := http.Server{
Handler: mux,
}
go func() {
logrus.Infof("starting metrics server path %s", metricsPath)
var err error
if config.ServerTLSConfig.CertFile != "" && config.ServerTLSConfig.KeyFile != "" {
err = server.ServeTLS(listener, config.ServerTLSConfig.CertFile, config.ServerTLSConfig.KeyFile)
} else {
err = server.Serve(listener)
}
if err != nil && err != http.ErrServerClosed {
logrus.Fatalf("error starting the metrics server: %v", err)
}
}()
<-ctx.Done()
if err := server.Shutdown(context.Background()); err != nil {
logrus.Fatalf("error shutting down the metrics server: %v", err)
}
}