-
Notifications
You must be signed in to change notification settings - Fork 0
/
health.go
107 lines (81 loc) · 2.19 KB
/
health.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
// Package health contains helpers to enable HTTP health checking.
package health
import (
"context"
"fmt"
"net/http"
"sync"
"time"
"go.uber.org/zap"
"knative.dev/pkg/logging"
)
const healthPath = "/health"
// Use a var instead of a const to allow tests to override this value.
var healthPort uint16 = 8080
const gracefulHandlerShutdown = 3 * time.Second
// handler serves requests to the health endpoint. It returns a success HTTP
// code when its value is true.
type handler struct {
sync.RWMutex
ready bool
}
// Verify that handler implements http.Handler.
var _ http.Handler = (*handler)(nil)
// ServeHTTP implements http.Handler.
func (h *handler) ServeHTTP(w http.ResponseWriter, _ *http.Request) {
if !h.isReady() {
w.WriteHeader(http.StatusServiceUnavailable)
return
}
w.WriteHeader(http.StatusNoContent)
}
func (h *handler) isReady() bool {
h.RLock()
defer h.RUnlock()
return h.ready
}
var defaultHandler handler
// Start runs the default HTTP health handler.
func Start(ctx context.Context) {
mux := &http.ServeMux{}
mux.Handle(healthPath, &defaultHandler)
server := &http.Server{
Addr: fmt.Sprintf(":%d", healthPort),
Handler: mux,
ReadTimeout: 5 * time.Second,
}
errCh := make(chan error)
go func() {
errCh <- server.ListenAndServe()
}()
handleServerError := func(err error) {
if err != http.ErrServerClosed {
logging.FromContext(ctx).Errorw("Error during runtime of health server", zap.Error(err))
}
}
select {
case <-ctx.Done():
ctx, cancel := context.WithTimeout(context.Background(), gracefulHandlerShutdown)
defer cancel()
if err := server.Shutdown(ctx); err != nil {
logging.FromContext(ctx).Errorw("Error during shutdown of health server", zap.Error(err))
}
handleServerError(<-errCh)
case err := <-errCh:
handleServerError(err)
}
}
// MarkReady indicates that the application is ready to operate.
func MarkReady() {
if defaultHandler.isReady() {
return
}
defaultHandler.Lock()
defer defaultHandler.Unlock()
// double-checked lock to ensure we don't write the value of "ready"
// twice if multiple goroutines called MarkReady() simultaneously.
if defaultHandler.ready {
return
}
defaultHandler.ready = true
}