This repository has been archived by the owner on Mar 16, 2024. It is now read-only.
/
healthz.go
90 lines (79 loc) · 1.89 KB
/
healthz.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
package router
import (
"context"
"fmt"
"net/http"
"os/signal"
"sync"
"syscall"
"github.com/acorn-io/baaah/pkg/log"
)
var healthz struct {
healths map[string]bool
started bool
lock *sync.RWMutex
port int
}
func init() {
healthz.lock = &sync.RWMutex{}
healthz.healths = make(map[string]bool)
}
func setPort(port int) {
healthz.lock.Lock()
defer healthz.lock.Unlock()
if healthz.port > 0 {
log.Warnf("healthz port cannot be changed")
return
}
healthz.port = port
}
func setHealthy(name string, healthy bool) {
healthz.lock.Lock()
defer healthz.lock.Unlock()
healthz.healths[name] = healthy
}
func getHealthy() bool {
healthz.lock.RLock()
defer healthz.lock.RUnlock()
for _, healthy := range healthz.healths {
if !healthy {
return false
}
}
return true
}
// startHealthz starts a healthz server on the healthzPort. If the server is already running, then this is a no-op.
// Similarly, if the healthzPort is <= 0, then this is a no-op.
func startHealthz(ctx context.Context) {
healthz.lock.Lock()
defer healthz.lock.Unlock()
if healthz.started || healthz.port <= 0 {
return
}
healthz.started = true
// Catch these signals to ensure a graceful shutdown of the server.
sigCtx, cancel := signal.NotifyContext(ctx, syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGKILL)
mux := http.NewServeMux()
mux.HandleFunc("/healthz", func(w http.ResponseWriter, req *http.Request) {
if getHealthy() {
w.WriteHeader(http.StatusOK)
return
}
w.WriteHeader(http.StatusServiceUnavailable)
})
srv := &http.Server{
Addr: fmt.Sprintf(":%d", healthz.port),
Handler: mux,
}
go func() {
<-sigCtx.Done()
// Must cancel so that the registered signals are no longer caught.
cancel()
if err := srv.Shutdown(ctx); err != nil {
log.Warnf("error shutting down healthz server: %v", err)
}
}()
go func() {
log.Infof("healthz server stopped: %v", srv.ListenAndServe())
}()
}