-
Notifications
You must be signed in to change notification settings - Fork 469
/
healthz.go
executable file
·223 lines (198 loc) · 5.78 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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
package registry
import (
"context"
"errors"
"fmt"
"time"
"github.com/go-chassis/go-chassis/core/config"
"github.com/go-chassis/go-chassis/core/lager"
"github.com/go-chassis/go-chassis/healthz/client"
)
const (
timeoutToPending = 1 * time.Second
timeoutToPackage = 100 * time.Millisecond
timeoutToHealthCheck = 5 * time.Second
chanCapacity = 1000
)
var defaultHealthChecker = &HealthChecker{}
func init() {
defaultHealthChecker.Run()
}
// WrapInstance is the struct defines an instance object with appID/serviceName/version
type WrapInstance struct {
AppID string
ServiceName string
Version string
Instance *MicroServiceInstance
}
// String is the method returns the string type current instance's key value
func (i *WrapInstance) String() string {
return fmt.Sprintf("%s:%s:%s:%s", i.ServiceName, i.Version, i.AppID, i.Instance.InstanceID)
}
// ServiceKey is the method returns the string type current instance's service key value
func (i *WrapInstance) ServiceKey() string {
return fmt.Sprintf("%s:%s:%s", i.ServiceName, i.Version, i.AppID)
}
// checkResult is the struct defines the result from health check
type checkResult struct {
Item *WrapInstance
Err error
}
// HealthChecker is the struct judges the instance health in the removing cache
type HealthChecker struct {
pendingCh chan *WrapInstance
delCh chan map[string]*WrapInstance
}
// Run is the method initializes and starts the health check process
func (hc *HealthChecker) Run() {
hc.pendingCh = make(chan *WrapInstance, chanCapacity)
hc.delCh = make(chan map[string]*WrapInstance, chanCapacity)
go hc.wait()
go hc.check()
}
// Add is the method adds a key of the instance cache into pending chan
func (hc *HealthChecker) Add(i *WrapInstance) error {
select {
case hc.pendingCh <- i:
case <-time.After(timeoutToPending):
return errors.New("Health checker is too busy")
}
return nil
}
func (hc *HealthChecker) wait() {
pack := make(map[string]*WrapInstance)
for {
select {
case i, ok := <-hc.pendingCh:
if !ok {
// chan closed
return
}
pack[i.String()] = i
case <-time.After(timeoutToPackage):
if len(pack) > 0 {
hc.delCh <- pack
pack = make(map[string]*WrapInstance)
}
}
}
}
func (hc *HealthChecker) check() {
for pack := range hc.delCh {
var rs []<-chan checkResult
for _, v := range pack {
rs = append(rs, hc.doCheck(v))
}
for _, r := range rs {
cr := <-r
if cr.Err != nil {
lager.Logger.Debugf("Health check instance %s failed, %s",
cr.Item.ServiceKey(), cr.Err)
hc.removeFromCache(cr.Item)
continue
}
lager.Logger.Debugf("Health check instance %s %s is still alive, keep it in cache",
cr.Item.ServiceKey(), cr.Item.Instance.EndpointsMap)
}
}
}
func (hc *HealthChecker) doCheck(i *WrapInstance) <-chan checkResult {
cr := make(chan checkResult)
go func() {
ctx, cancel := context.WithTimeout(context.Background(), timeoutToHealthCheck)
r := checkResult{Item: i, Err: nil}
defer func() {
cancel()
cr <- r
}()
req := client.Reply{
AppId: i.AppID,
ServiceName: i.ServiceName,
Version: i.Version,
}
for protocol, ep := range i.Instance.EndpointsMap {
r.Err = client.Test(ctx, protocol, ep, req)
return
}
}()
return cr
}
func (hc *HealthChecker) removeFromCache(i *WrapInstance) {
c, ok := MicroserviceInstanceIndex.Get(i.ServiceName, nil)
if !ok {
return
}
var is []*MicroServiceInstance
for _, inst := range c.([]*MicroServiceInstance) {
if inst.InstanceID == i.Instance.InstanceID {
continue
}
is = append(is, inst)
}
MicroserviceInstanceIndex.Set(i.ServiceName, is)
lager.Logger.Debugf("Health check: cached [%d] Instances of service [%s]", len(is), i.ServiceName)
}
// HealthCheck is the function adds the instance to HealthChecker
func HealthCheck(service, version, appID string, instance *MicroServiceInstance) error {
if !config.GetServiceDiscoveryHealthCheck() {
return fmt.Errorf("Health check is disabled")
}
return defaultHealthChecker.Add(&WrapInstance{
ServiceName: service,
Version: version,
AppID: appID,
Instance: instance,
})
}
// RefreshCache is the function to filter changes between new pulling instances and cache
func RefreshCache(service string, ups []*MicroServiceInstance, downs map[string]struct{}) {
c, ok := MicroserviceInstanceIndex.Get(service, nil)
if !ok || c == nil || c.([]*MicroServiceInstance) == nil {
// if full new instances or at less one instance, then refresh cache immediately
MicroserviceInstanceIndex.Set(service, ups)
return
}
var (
saves []*MicroServiceInstance
lefts []*MicroServiceInstance
exps = c.([]*MicroServiceInstance)
mapUps = make(map[string]*MicroServiceInstance, len(ups))
mapExps = make(map[string]*MicroServiceInstance, len(exps))
)
for _, ins := range ups {
mapUps[ins.InstanceID] = ins
}
for _, instance := range exps {
mapExps[instance.InstanceID] = instance
}
for _, exp := range mapExps {
// case: keep still alive instances
if _, ok := mapUps[exp.InstanceID]; ok {
lefts = append(lefts, exp)
continue
}
// case: remove instances with the non-up status
if _, ok := downs[exp.InstanceID]; ok {
continue
}
// case: keep instances returned HC ok
if err := HealthCheck(service, exp.version(), exp.appID(), exp); err == nil {
lefts = append(lefts, exp)
}
}
for _, up := range ups {
if _, ok := mapExps[up.InstanceID]; ok {
continue
}
// case: add new come in instances
saves = append(saves, up)
}
lefts = append(lefts, saves...)
if len(lefts) == 0 {
//todo remove this when the cache struct can delete the key if the input is an empty slice
MicroserviceInstanceIndex.Delete(service)
} else {
MicroserviceInstanceIndex.Set(service, lefts)
}
lager.Logger.Debugf("Cached [%d] Instances of service [%s]", len(lefts), service)
}