forked from mosn/mosn
/
healthchecker.go
207 lines (187 loc) · 5.98 KB
/
healthchecker.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
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package healthcheck
import (
"math/rand"
"sync"
"sync/atomic"
"time"
v2 "mosn.io/mosn/pkg/api/v2"
"mosn.io/mosn/pkg/log"
"mosn.io/mosn/pkg/types"
"mosn.io/mosn/pkg/utils"
)
const (
DefaultTimeout = time.Second
DefaultInterval = 15 * time.Second
)
// healthChecker is a basic implementation of a health checker.
// we use different implementations of types.Session to implement different health checker
type healthChecker struct {
//
sessionConfig map[string]interface{}
sessionFactory types.HealthCheckSessionFactory
mutex sync.Mutex
checkers map[string]*sessionChecker
localProcessHealthy int64
hosts []types.Host
stats *healthCheckStats
// check config
timeout time.Duration
intervalBase time.Duration
intervalJitter time.Duration
healthyThreshold uint32
unhealthyThreshold uint32
rander *rand.Rand
hostCheckCallbacks []types.HealthCheckCb
}
func newHealthChecker(cfg v2.HealthCheck, f types.HealthCheckSessionFactory) types.HealthChecker {
timeout := DefaultTimeout
if cfg.Timeout != 0 {
timeout = cfg.Timeout
}
interval := DefaultInterval
if cfg.Interval != 0 {
interval = cfg.Interval
}
hc := &healthChecker{
// cfg
sessionConfig: cfg.SessionConfig,
timeout: timeout,
intervalBase: interval,
intervalJitter: cfg.IntervalJitter,
healthyThreshold: cfg.HealthyThreshold,
unhealthyThreshold: cfg.UnhealthyThreshold,
//runtime and stats
rander: rand.New(rand.NewSource(time.Now().UnixNano())),
hostCheckCallbacks: []types.HealthCheckCb{},
sessionFactory: f,
mutex: sync.Mutex{},
checkers: make(map[string]*sessionChecker),
stats: newHealthCheckStats(cfg.ServiceName),
}
// Add common callbacks when create
// common callbacks should be registered and configured
for _, name := range cfg.CommonCallbacks {
if cb, ok := commonCallbacks[name]; ok {
hc.AddHostCheckCompleteCb(cb)
}
}
return hc
}
func (hc *healthChecker) Start() {
hc.mutex.Lock()
defer hc.mutex.Unlock()
hc.start()
}
func (hc *healthChecker) start() {
for _, h := range hc.hosts {
hc.startCheck(h)
}
hc.stats.healthy.Update(atomic.LoadInt64(&hc.localProcessHealthy))
}
func (hc *healthChecker) Stop() {
hc.mutex.Lock()
defer hc.mutex.Unlock()
hc.stop()
}
func (hc *healthChecker) stop() {
for _, h := range hc.hosts {
hc.stopCheck(h)
}
}
func (hc *healthChecker) AddHostCheckCompleteCb(cb types.HealthCheckCb) {
hc.hostCheckCallbacks = append(hc.hostCheckCallbacks, cb)
}
// SetHealthCheckerHostSet reset the healthchecker's hosts
func (hc *healthChecker) SetHealthCheckerHostSet(hostSet types.HostSet) {
hc.mutex.Lock()
defer hc.mutex.Unlock()
hc.stop()
hc.hosts = hostSet.Hosts()
hc.start()
}
func (hc *healthChecker) startCheck(host types.Host) {
addr := host.AddressString()
if _, ok := hc.checkers[addr]; !ok {
s := hc.sessionFactory.NewSession(hc.sessionConfig, host)
if s == nil {
log.DefaultLogger.Errorf("[upstream] [health check] Create Health Check Session Error, Remote Address = %s", addr)
return
}
c := newChecker(s, host, hc)
hc.checkers[addr] = c
utils.GoWithRecover(func() {
c.Start()
}, nil)
atomic.AddInt64(&hc.localProcessHealthy, 1) // default host is healthy
if log.DefaultLogger.GetLogLevel() >= log.INFO {
log.DefaultLogger.Infof("[upstream] [health check] create a health check session for %s", addr)
}
}
}
func (hc *healthChecker) stopCheck(host types.Host) {
addr := host.AddressString()
if c, ok := hc.checkers[addr]; ok {
c.Stop()
delete(hc.checkers, addr)
// hc.localProcessHealthy--
atomic.AddInt64(&hc.localProcessHealthy, ^int64(0)) // deleted check is unhealthy
if log.DefaultLogger.GetLogLevel() >= log.INFO {
log.DefaultLogger.Infof("[upstream] [health check] remove a health check session for %s", addr)
}
}
}
func (hc *healthChecker) runCallbacks(host types.Host, changed bool, isHealthy bool) {
hc.stats.healthy.Update(atomic.LoadInt64(&hc.localProcessHealthy))
for _, cb := range hc.hostCheckCallbacks {
cb(host, changed, isHealthy)
}
}
func (hc *healthChecker) getCheckInterval() time.Duration {
interval := hc.intervalBase
if hc.intervalJitter > 0 {
interval += time.Duration(hc.rander.Int63n(int64(hc.intervalJitter)))
}
// TODO: support jitter percentage
return interval
}
func (hc *healthChecker) incHealthy(host types.Host, changed bool) {
hc.stats.success.Inc(1)
if changed {
log.DefaultLogger.Infof("[upstream] [health check] host %s is healthy", host.AddressString())
atomic.AddInt64(&hc.localProcessHealthy, 1)
}
hc.runCallbacks(host, changed, true)
}
func (hc *healthChecker) decHealthy(host types.Host, reason types.FailureType, changed bool) {
hc.stats.failure.Inc(1)
if changed {
// hc.localProcessHealthy--
log.DefaultLogger.Infof("[upstream] [health check] host %s is unhealthy", host.AddressString())
atomic.AddInt64(&hc.localProcessHealthy, ^int64(0))
}
switch reason {
case types.FailureActive:
hc.stats.activeFailure.Inc(1)
case types.FailureNetwork:
hc.stats.networkFailure.Inc(1)
case types.FailurePassive: //TODO: not support yet
hc.stats.passiveFailure.Inc(1)
}
hc.runCallbacks(host, changed, false)
}