-
Notifications
You must be signed in to change notification settings - Fork 40
/
health.go
108 lines (85 loc) · 2.48 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
108
package util
import (
"context"
"fmt"
"log"
"net/http"
"strconv"
"sync"
"time"
"github.com/heptiolabs/healthcheck"
)
const defaultHealthCheckPort = 5335
type healthWatcher struct {
handler healthcheck.Handler
isAppReady bool
isAppLive bool
serverInstance *http.Server
}
var _healthWatcher *healthWatcher
var _healthWatcherSyncOnce = sync.Once{}
func (healthWatcher *healthWatcher) registerLivelinessCheck() {
checkFunc := func() error {
if healthWatcher.isAppLive {
return nil
}
// If we are not ready, we return a failed liveliness check
return fmt.Errorf("secretless is not listening")
}
healthWatcher.handler.AddLivenessCheck("listening", checkFunc)
}
func (healthWatcher *healthWatcher) registerReadinessCheck() {
checkFunc := func() error {
if healthWatcher.isAppReady {
return nil
}
// If we are not ready, we return a failed readiness check
return fmt.Errorf("secretless is not ready")
}
healthWatcher.handler.AddReadinessCheck("ready", checkFunc)
}
func (healthWatcher *healthWatcher) enable(port int) {
log.Printf("Initializing health check on :%d...", port)
healthWatcher.handler = healthcheck.NewHandler()
healthWatcher.registerLivelinessCheck()
healthWatcher.registerReadinessCheck()
healthWatcher.serverInstance = &http.Server{
Addr: ":" + strconv.Itoa(port),
Handler: healthWatcher.handler,
ReadTimeout: 5 * time.Second,
WriteTimeout: 5 * time.Second,
MaxHeaderBytes: 1 << 20,
}
go healthWatcher.serverInstance.ListenAndServe()
log.Printf("Initialization of health check done. " +
"You can access the endpoint at `/live` and `/ready`.")
}
func enableHealthCheck() {
_healthWatcherSyncOnce.Do(func() {
_healthWatcher = &healthWatcher{}
_healthWatcher.enable(defaultHealthCheckPort)
})
}
func disableHealthCheck() {
if _healthWatcher == nil || _healthWatcher.serverInstance == nil {
return
}
// Clean up everything as best we can to ensure prompt GC
if err := _healthWatcher.serverInstance.Shutdown(context.Background()); err != nil {
panic(err)
}
_healthWatcher.serverInstance = nil
_healthWatcher.handler = nil
_healthWatcher = nil
_healthWatcherSyncOnce = sync.Once{}
}
// SetAppInitializedFlag enables health check and sets the ready flag.
func SetAppInitializedFlag() {
enableHealthCheck()
_healthWatcher.isAppReady = true
}
// SetAppIsLive enables health check and marks the app as live.
func SetAppIsLive(isLive bool) {
enableHealthCheck()
_healthWatcher.isAppLive = isLive
}