/
keepalive.go
266 lines (219 loc) · 6.91 KB
/
keepalive.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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
/*
* 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 xprotocol
import (
"context"
"sync"
"time"
atomicex "go.uber.org/atomic"
"mosn.io/api"
"mosn.io/mosn/pkg/log"
str "mosn.io/mosn/pkg/stream"
"mosn.io/mosn/pkg/types"
"mosn.io/pkg/utils"
)
// StreamReceiver to receive keep alive response
type xprotocolKeepAlive struct {
Codec str.Client
Protocol api.XProtocol
Timeout time.Duration
Callbacks []types.KeepAliveCallback
heartbeatFailCount atomicex.Uint32 // the number of consecutive heartbeat failures, will be reset after hb succ
previousIsSucc atomicex.Bool // the previous heartbeat result
tickCount atomicex.Uint32 // tick intervals after the last heartbeat request sent
idleFree *idleFree
// once protects stop channel
once sync.Once
// stop channel will stop all keep alive action
stop chan struct{}
// mutex protects the request map
mutex sync.Mutex
// requests records all running request
// a request is handled once: response or timeout
requests map[uint64]*keepAliveTimeout
}
func (kp *xprotocolKeepAlive) store(key uint64, val *keepAliveTimeout) {
kp.mutex.Lock()
defer kp.mutex.Unlock()
kp.requests[key] = val
}
func (kp *xprotocolKeepAlive) loadAndDelete(key uint64) (val *keepAliveTimeout, loaded bool) {
kp.mutex.Lock()
defer kp.mutex.Unlock()
v, ok := kp.requests[key]
if ok {
delete(kp.requests, key)
}
return v, ok
}
// NewKeepAlive creates a keepalive object
func NewKeepAlive(codec str.Client, proto api.XProtocol, timeout time.Duration) types.KeepAlive {
kp := &xprotocolKeepAlive{
Codec: codec,
Protocol: proto,
Timeout: timeout,
Callbacks: make([]types.KeepAliveCallback, 0),
stop: make(chan struct{}),
requests: make(map[uint64]*keepAliveTimeout),
}
// initially set previous heartbeat request success
kp.previousIsSucc.Store(true)
// register keepalive to connection event listener
// if connection is closed, keepalive should stop
kp.Codec.AddConnectionEventListener(kp)
return kp
}
// keepalive should stop when connection closed
func (kp *xprotocolKeepAlive) OnEvent(event api.ConnectionEvent) {
if event.IsClose() || event.ConnectFailure() {
kp.Stop()
}
}
// AddCallback add a callback to keepalive
// currently there no use for this function
func (kp *xprotocolKeepAlive) AddCallback(cb types.KeepAliveCallback) {
kp.Callbacks = append(kp.Callbacks, cb)
}
func (kp *xprotocolKeepAlive) runCallback(status types.KeepAliveStatus) {
for _, cb := range kp.Callbacks {
cb(status)
}
}
// SendKeepAlive will make a request to server via codec.
// use channel, do not block
func (kp *xprotocolKeepAlive) SendKeepAlive() {
select {
case <-kp.stop:
return
default:
}
var (
c = xprotoKeepaliveConfig.Load().(KeepaliveConfig)
tickCount = kp.tickCount.Inc()
)
if kp.previousIsSucc.Load() {
// previous hb is success
if tickCount >= c.TickCountIfSucc {
kp.sendKeepAlive()
}
} else {
// previous hb is failure
if tickCount >= c.TickCountIfFail {
kp.sendKeepAlive()
}
}
}
func (kp *xprotocolKeepAlive) StartIdleTimeout() {
kp.idleFree = newIdleFree()
}
// The function will be called when connection in the codec is idle
func (kp *xprotocolKeepAlive) sendKeepAlive() {
ctx := context.Background()
sender := kp.Codec.NewStream(ctx, kp)
id := sender.GetStream().ID()
// check idle free
if kp.idleFree.CheckFree(id) {
kp.Codec.Close()
return
}
// reset the tick count
kp.tickCount.Store(0)
// we send sofa rpc cmd as "header", but it maybe contains "body"
hb := kp.Protocol.Trigger(ctx, id)
kp.store(id, startTimeout(id, kp)) // store request before send, in case receive response too quick but not data in store
sender.AppendHeaders(ctx, hb.GetHeader(), true)
// start a timer for request
if log.DefaultLogger.GetLogLevel() >= log.DEBUG {
log.DefaultLogger.Debugf("[stream] [xprotocol] [keepalive] connection %d send a keepalive request, id = %d", kp.Codec.ConnID(), id)
}
}
func (kp *xprotocolKeepAlive) GetTimeout() time.Duration {
return kp.Timeout
}
func (kp *xprotocolKeepAlive) HandleTimeout(id uint64) {
c := xprotoKeepaliveConfig.Load().(KeepaliveConfig)
select {
case <-kp.stop:
return
default:
}
if _, ok := kp.loadAndDelete(id); !ok {
return
}
if log.DefaultLogger.GetLogLevel() >= log.DEBUG {
log.DefaultLogger.Debugf("[stream] [xprotocol] [keepalive] connection %d receive a request timeout %d", kp.Codec.ConnID(), id)
}
kp.heartbeatFailCount.Inc()
kp.previousIsSucc.Store(false)
// close the connection, stop keep alive
if kp.heartbeatFailCount.Load() >= c.FailCountToClose {
kp.Codec.Close()
}
kp.runCallback(types.KeepAliveTimeout)
}
func (kp *xprotocolKeepAlive) HandleSuccess(id uint64) {
select {
case <-kp.stop:
return
default:
}
timeout, ok := kp.loadAndDelete(id)
if !ok {
return
}
if log.DefaultLogger.GetLogLevel() >= log.DEBUG {
log.DefaultLogger.Debugf("[stream] [xprotocol] [keepalive] connection %d receive a request success %d", kp.Codec.ConnID(), id)
}
timeout.timer.Stop()
// reset the tiemout count
kp.heartbeatFailCount.Store(0)
kp.previousIsSucc.Store(true)
kp.runCallback(types.KeepAliveSuccess)
}
func (kp *xprotocolKeepAlive) Stop() {
kp.once.Do(func() {
log.DefaultLogger.Infof("[stream] [xprotocol] [keepalive] connection %d stopped keepalive", kp.Codec.ConnID())
close(kp.stop)
})
}
// StreamReceiver Implementation
// we just needs to make sure we can receive a response, do not care the data we received
func (kp *xprotocolKeepAlive) OnReceive(ctx context.Context, headers types.HeaderMap, data types.IoBuffer, trailers types.HeaderMap) {
if ack, ok := headers.(api.XFrame); ok {
kp.HandleSuccess(ack.GetRequestId())
}
}
// OnDecodeError does not process decode failure
// the timer will fail this heart beat
func (kp *xprotocolKeepAlive) OnDecodeError(ctx context.Context, err error, headers types.HeaderMap) {
}
type keepAliveTimeout struct {
ID uint64
timer *utils.Timer
KeepAlive types.KeepAlive
}
func startTimeout(id uint64, keep types.KeepAlive) *keepAliveTimeout {
t := &keepAliveTimeout{
ID: id,
KeepAlive: keep,
}
t.timer = utils.NewTimer(keep.GetTimeout(), t.onTimeout)
return t
}
func (t *keepAliveTimeout) onTimeout() {
t.KeepAlive.HandleTimeout(t.ID)
}