-
Notifications
You must be signed in to change notification settings - Fork 5
/
health_server.go
96 lines (77 loc) · 1.85 KB
/
health_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
package telemetry
import (
"context"
"errors"
"net"
"net/http"
"os"
"sync"
"time"
"github.com/xigxog/kubefox/components/broker/config"
"github.com/xigxog/kubefox/libs/core/logkf"
)
type HealthProvider interface {
Name() string
IsHealthy(ctx context.Context) bool
}
type HealthServer struct {
httpSrv *http.Server
providers []HealthProvider
mutex sync.Mutex
log *logkf.Logger
}
func NewHealthServer() *HealthServer {
return &HealthServer{
providers: make([]HealthProvider, 0),
log: logkf.Global,
}
}
func (srv *HealthServer) Register(provider HealthProvider) {
srv.mutex.Lock()
defer srv.mutex.Unlock()
srv.providers = append(srv.providers, provider)
}
func (srv *HealthServer) Start() error {
srv.log.Debug("health server starting")
srv.httpSrv = &http.Server{
WriteTimeout: time.Second * 30,
ReadTimeout: time.Second * 30,
IdleTimeout: time.Second * 30,
Handler: srv,
}
ln, err := net.Listen("tcp", config.HealthSrvAddr)
if err != nil {
return err
}
go func() {
err := srv.httpSrv.Serve(ln)
if err != nil && !errors.Is(err, http.ErrServerClosed) {
srv.log.Error(err)
os.Exit(1)
}
}()
srv.log.Info("health server started")
return nil
}
func (srv *HealthServer) Shutdown(timeout time.Duration) {
srv.log.Info("health server shutting down")
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
if srv.httpSrv != nil {
if err := srv.httpSrv.Shutdown(ctx); err != nil {
srv.log.Error(err)
}
}
}
func (srv *HealthServer) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
ctx, cancel := context.WithTimeout(req.Context(), time.Second*10)
defer cancel()
status := http.StatusOK
for _, p := range srv.providers {
if !p.IsHealthy(ctx) {
srv.log.Errorf("%s is unhealthy", p.Name())
status = http.StatusServiceUnavailable
}
}
resp.WriteHeader(status)
}