/
health.go
76 lines (61 loc) · 1.63 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
package main
// This module checks the internal state of the server
// and will set the appropriate health values based on the checking
import (
"context"
"fmt"
"sync"
"google.golang.org/grpc/health"
"google.golang.org/grpc/health/grpc_health_v1"
)
type healthCheck struct {
h *health.Server
sync.Mutex
}
var (
serverHealth = &healthCheck{
h: health.NewServer(),
}
)
func grpcHealth(ctx context.Context, in *grpc_health_v1.HealthCheckRequest) (resp *grpc_health_v1.HealthCheckResponse, err error) {
serverHealth.Lock()
defer serverHealth.Unlock()
return serverHealth.h.Check(ctx, in)
}
func initHealthTracker(ctx context.Context, serviceName string) {
serverHealth.Lock()
serverHealth.h.SetServingStatus(serviceName, grpc_health_v1.HealthCheckResponse_NOT_SERVING)
serverHealth.Unlock()
listenerC := make(chan bool)
modules := &Modules{}
modules.AddListener(listenerC)
go func() {
defer close(listenerC)
defer func() {
serverHealth.Lock()
serverHealth.h.SetServingStatus(serviceName, grpc_health_v1.HealthCheckResponse_NOT_SERVING)
serverHealth.Unlock()
}()
running := false
lastKnown := running
for {
select {
case up := <-listenerC:
running = up
serverHealth.Lock()
if up {
serverHealth.h.SetServingStatus(serviceName, grpc_health_v1.HealthCheckResponse_SERVING)
} else {
serverHealth.h.SetServingStatus(serviceName, grpc_health_v1.HealthCheckResponse_NOT_SERVING)
}
serverHealth.Unlock()
if lastKnown != running {
lastKnown = running
logger.Info(fmt.Sprintf("server running state is %v", running))
}
case <-ctx.Done():
return
}
}
}()
}