/
server.go
126 lines (102 loc) · 2.59 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
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
package action
import (
"context"
"io"
"net/http"
"os"
"os/signal"
"time"
"github.com/go-chi/chi"
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/log/level"
"github.com/kubehippie/database-operator/pkg/config"
"github.com/kubehippie/database-operator/pkg/exporter"
"github.com/kubehippie/database-operator/pkg/version"
"github.com/oklog/run"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
// Server handles the server sub-command.
func Server(cfg *config.Config, logger log.Logger) error {
level.Info(logger).Log(
"msg", "Launching Database Operator",
"version", version.Version,
"revision", version.Revision,
"date", version.BuildDate,
"go", version.GoVersion,
)
var gr run.Group
{
server := &http.Server{
Addr: cfg.Server.Addr,
Handler: handler(cfg, logger),
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
}
gr.Add(func() error {
level.Info(logger).Log(
"msg", "Starting server",
"addr", cfg.Server.Addr,
)
return server.ListenAndServe()
}, func(reason error) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := server.Shutdown(ctx); err != nil {
level.Error(logger).Log(
"msg", "Failed to shutdown server gracefully",
"err", err,
)
return
}
level.Info(logger).Log(
"msg", "Server shutdown gracefully",
"reason", reason,
)
})
}
{
stop := make(chan os.Signal, 1)
gr.Add(func() error {
signal.Notify(stop, os.Interrupt)
<-stop
return nil
}, func(err error) {
close(stop)
})
}
return gr.Run()
}
func handler(cfg *config.Config, logger log.Logger) *chi.Mux {
mux := chi.NewRouter()
r := prometheus.NewRegistry()
r.MustRegister(prometheus.NewProcessCollector(os.Getpid(), ""))
r.MustRegister(prometheus.NewGoCollector())
r.MustRegister(exporter.NewGeneralCollector(
version.Version,
version.Revision,
version.BuildDate,
version.GoVersion,
version.StartTime,
))
mux.Route("/", func(root chi.Router) {
root.Mount(
"/metrics",
promhttp.HandlerFor(
r,
promhttp.HandlerOpts{},
),
)
root.Get("/healthz", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(http.StatusOK)
io.WriteString(w, http.StatusText(http.StatusOK))
})
root.Get("/readyz", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(http.StatusOK)
io.WriteString(w, http.StatusText(http.StatusOK))
})
})
return mux
}