forked from aliyun/aliyun-tablestore-go-sdk
/
channel.go
477 lines (435 loc) · 12.9 KB
/
channel.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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
package tunnel
import (
"github.com/zhangzhongjing/aliyun-tablestore-go-sdk/tunnel/protocol"
"github.com/cenkalti/backoff"
"go.uber.org/zap"
"strings"
"sync"
"sync/atomic"
"time"
)
var (
// PipeChannelSize is channelDialer's data pipeline channel size
PipeChannelSize = 1
rpoBar = 500
rpoSizeBar = 900 * 1024 //900K bytes
)
type ChannelStatus struct {
ChannelId string
Version int64
Status protocol.ChannelStatus
}
func ToChannelStatus(c *protocol.Channel) *ChannelStatus {
return &ChannelStatus{
ChannelId: c.GetChannelId(),
Version: c.GetVersion(),
Status: c.GetStatus(),
}
}
func (c *ChannelStatus) ToPbChannel() *protocol.Channel {
clone := c
return &protocol.Channel{
ChannelId: &clone.ChannelId,
Version: &clone.Version,
Status: clone.Status.Enum(),
}
}
type ChannelConn interface {
NotifyStatus(channel *ChannelStatus)
Closed() bool
Close()
}
// failConn do nothing but turn channel state to close
type failConn struct {
mu sync.Mutex
state *TunnelStateMachine
currentState *ChannelStatus
}
func (c *failConn) NotifyStatus(channel *ChannelStatus) {
c.mu.Lock()
defer c.mu.Unlock()
if c.currentState != nil && c.currentState.Version > channel.Version {
return
}
c.currentState = channel
switch c.currentState.Status {
case protocol.ChannelStatus_CLOSE:
case protocol.ChannelStatus_CLOSING:
c.currentState.Version += 1
c.currentState.Status = protocol.ChannelStatus_CLOSE
c.state.UpdateStatus(c.currentState)
case protocol.ChannelStatus_OPEN:
c.currentState.Version += 1
c.currentState.Status = protocol.ChannelStatus_CLOSE
c.state.UpdateStatus(c.currentState)
case protocol.ChannelStatus_TERMINATED:
default:
}
}
func (c *failConn) Closed() bool {
c.mu.Lock()
defer c.mu.Unlock()
if c.currentState == nil {
return false
}
return c.currentState.Status == protocol.ChannelStatus_CLOSE ||
c.currentState.Status == protocol.ChannelStatus_TERMINATED
}
func (c *failConn) Close() {}
type ChannelDialer interface {
ChannelDial(tunnelId, clientId, channelId, token string, p ChannelProcessor, state *TunnelStateMachine) ChannelConn
}
type channelDialer struct {
api tunnelDataApi
lg *zap.Logger
bc *ChannelBackoffConfig
channelParallelChan chan bool
needManualRelease bool
syncReadRecords bool
}
func (d *channelDialer) ChannelDial(tunnelId, clientId, channelId, token string, p ChannelProcessor, state *TunnelStateMachine) ChannelConn {
isStream, err := streamToken(token)
if err != nil {
/*
There are two situations where errors will occur, one is base channel finished, the other is parent stream channel finished.
we judge the channel to be Base depend on base channelId always begin with "BaseData_"
*/
if strings.HasPrefix(channelId, "BaseData_") {
isStream = false
}
isStream = true //treat as stream token with flow control
}
conn := &channelConn{
tunnelId: tunnelId,
clientId: clientId,
channelId: channelId,
token: token,
api: d.api,
p: p,
state: state,
lg: d.lg,
bc: d.bc,
streamChannel: isStream,
}
if d.channelParallelChan != nil {
conn.parallelReleaseManager = &defaultParallelReleaseManager{
mu: new(sync.Mutex),
quotaAcquired: false,
channelParallelChan: d.channelParallelChan,
}
conn.needManualRelease = d.needManualRelease
}
if d.syncReadRecords {
conn.syncReadRecordChan = make(chan bool)
}
return conn
}
var (
waitStatus = int32(0)
runningStatus = int32(1)
closingStatus = int32(2)
closedStatus = int32(3)
)
type tunnelDataApi interface {
ReadRecords(req *ReadRecordRequest) (*ReadRecordResponse, error)
}
type channelConn struct {
mu sync.Mutex
tunnelId string
clientId string
channelId string
token string
api tunnelDataApi
p ChannelProcessor
currentState *ChannelStatus
state *TunnelStateMachine
lg *zap.Logger
bc *ChannelBackoffConfig
status int32
ticker *backoff.Ticker
streamChannel bool
parallelReleaseManager *defaultParallelReleaseManager
needManualRelease bool
syncReadRecordChan chan bool
}
func (c *channelConn) NotifyStatus(channel *ChannelStatus) {
c.mu.Lock()
defer c.mu.Unlock()
if c.currentState != nil && c.currentState.Version > channel.Version {
return
}
c.currentState = channel
switch channel.Status {
case protocol.ChannelStatus_CLOSE:
c.lg.Info("closed channel status", zap.String("tunnelId", c.tunnelId),
zap.String("clientId", c.clientId), zap.String("channelId", c.channelId), zap.Int64("version", channel.Version))
c.close()
case protocol.ChannelStatus_CLOSING: //draw closing action and check closed/finish status
if atomic.LoadInt32(&c.status) == waitStatus {
atomic.StoreInt32(&c.status, closedStatus)
} else {
atomic.CompareAndSwapInt32(&c.status, runningStatus, closingStatus)
}
c.checkUpdateStatus()
case protocol.ChannelStatus_OPEN: //draw processing action or check closed/finish status
if atomic.CompareAndSwapInt32(&c.status, waitStatus, runningStatus) {
if d, ok := c.p.(*defaultProcessor); ok && d.asyncProcessFlag && d.channelOpenFunc != nil {
c.lg.Info("open channel", zap.String("tunnelId", c.tunnelId),
zap.String("clientId", c.clientId), zap.String("channelId", c.channelId), zap.Int64("version", channel.Version))
d.channelOpenFunc(d.ctx)
}
go c.workLoop()
} else {
c.checkUpdateStatus()
}
case protocol.ChannelStatus_TERMINATED:
c.lg.Info("terminated channel status", zap.String("tunnelId", c.tunnelId),
zap.String("clientId", c.clientId), zap.String("channelId", c.channelId), zap.Int64("version", channel.Version))
c.close()
default:
c.lg.Error("Unexpected channel status", zap.String("tunnelId", c.tunnelId),
zap.String("clientId", c.clientId), zap.String("channelId", c.channelId),
zap.Int32("Status", int32(c.currentState.Status)), zap.Int64("version", channel.Version))
}
}
func (c *channelConn) Closed() bool {
return atomic.LoadInt32(&c.status) == closedStatus
}
func (c *channelConn) Close() {
c.close()
}
func (c *channelConn) close() {
c.p.Shutdown()
atomic.StoreInt32(&c.status, closedStatus)
}
func (c *channelConn) checkUpdateStatus() {
if c.p.Finished() {
c.closeAndUpdate(protocol.ChannelStatus_TERMINATED)
return
}
if c.p.Error() {
c.closeAndUpdate(protocol.ChannelStatus_CLOSE)
return
}
if atomic.LoadInt32(&c.status) == closedStatus {
if c.currentState.Status != protocol.ChannelStatus_TERMINATED {
if c.p.Finished() {
c.closeAndUpdate(protocol.ChannelStatus_TERMINATED)
} else {
c.closeAndUpdate(protocol.ChannelStatus_CLOSE)
}
}
}
}
func (c *channelConn) closeAndUpdate(status protocol.ChannelStatus) {
c.close()
c.currentState.Version += 1
c.currentState.Status = status
c.state.UpdateStatus(c.currentState)
}
type pipeResult struct {
finished bool
records []*Record
binaryRecords []byte
traceId string
nextToken string
recordCount int
error error
}
func (c *channelConn) workLoop() {
var pipeSize int
if p, ok := c.p.(*defaultProcessor); ok {
pipeSize = p.recordPipePerChannel
} else {
//for data delivery
pipeSize = PipeChannelSize
}
pipeCh := make(chan *pipeResult, pipeSize)
c.lg.Info("run channel workLoop", zap.Int("PipeChannelSize", pipeSize),
zap.String("cid", c.channelId))
closeCh := make(chan struct{})
//clean channel channelParallelChan when processRecords exit or processRecords is not executed
if c.parallelReleaseManager != nil {
defer c.parallelReleaseManager.Release()
}
defer close(closeCh)
go c.readRecordsPipe(pipeCh, closeCh)
for atomic.LoadInt32(&c.status) == runningStatus {
drained, err := c.processRecords(pipeCh)
if err != nil {
c.lg.Info("channel shutdown with error", zap.String("cid", c.channelId), zap.Error(err))
break
}
if drained {
c.lg.Info("channel read finished", zap.String("cid", c.channelId))
return
}
}
c.lg.Info("channel shutdown", zap.String("cid", c.channelId))
c.close()
}
func (c *channelConn) readRecordsPipe(outCh chan *pipeResult, closeCh chan struct{}) {
//channelParallelChan must be released when readRecords exist
if c.parallelReleaseManager != nil {
defer c.parallelReleaseManager.Release()
}
var bkoff *backoff.ExponentialBackOff
if c.streamChannel {
bkoff = ExponentialBackoff(c.bc.baseDelay, c.bc.MaxDelay, 0, c.bc.factor, c.bc.jitter)
}
var needBinaryRecords bool
if processor, ok := c.p.(*defaultProcessor); ok {
needBinaryRecords = processor.needBinaryRecords
}
for {
ret := new(pipeResult)
select {
case <-closeCh:
return
default:
}
if c.token == FinishTag {
ret.finished = true
} else {
channelWaitChan := time.Now()
//whether there is a limit on the concurrent number of channel
if c.parallelReleaseManager != nil {
if !c.parallelReleaseManager.checkQuotaAcquired() {
//there can only be one goroutine acquire token at a time
c.parallelReleaseManager.mu.Lock()
select {
case c.parallelReleaseManager.channelParallelChan <- true:
c.parallelReleaseManager.quotaAcquired = true
c.parallelReleaseManager.mu.Unlock()
if c.needManualRelease {
c.lg.Info("channel get lock", zap.String("channelId: ", c.channelId), zap.String("tunnelId", c.tunnelId), zap.String("clientId", c.clientId))
}
case <-closeCh:
c.parallelReleaseManager.mu.Unlock()
return
}
}
}
s := time.Now()
request := &ReadRecordRequest{
TunnelId: c.tunnelId,
ChannelId: c.channelId,
ClientId: c.clientId,
Token: c.token,
NeedBinaryRecord: needBinaryRecords,
}
resp, err := c.api.ReadRecords(request)
if err != nil {
ret.error = err
} else {
if needBinaryRecords {
ret.binaryRecords = resp.BinaryRecords
} else {
ret.records = resp.Records
}
ret.recordCount = resp.RecordCount
ret.nextToken = resp.NextToken
ret.traceId = resp.RequestId
if bkoff != nil {
if streamFullData(resp.RecordCount, resp.Size) {
bkoff.Reset()
}
}
c.token = resp.NextToken
}
if ret.recordCount != 0 {
c.lg.Info("Metric info", zap.String("tunnelId", c.tunnelId), zap.String("clientId", c.clientId),
zap.String("channelId", c.channelId), zap.String("token", c.token), zap.String("channelWaitChanLatency", s.Sub(channelWaitChan).String()),
zap.String("GetTunnelRecordLatency", time.Now().Sub(s).String()), zap.Int("recordCount", ret.recordCount), zap.Bool("needBinaryRecords", needBinaryRecords))
}
}
select {
case outCh <- ret:
if c.syncReadRecordChan != nil {
select {
case c.syncReadRecordChan <- true:
case <-closeCh:
return
}
}
case <-closeCh:
return
}
if bkoff != nil {
time.Sleep(bkoff.NextBackOff())
}
}
}
func (c *channelConn) processRecords(inCh chan *pipeResult) (bool, error) {
var manager ParallelReleaseManager
if c.parallelReleaseManager != nil {
manager = c.parallelReleaseManager
//channel switch control by sdk
if !c.needManualRelease {
manager = nil
}
}
if c.syncReadRecordChan != nil {
defer func() {
<-c.syncReadRecordChan
}()
}
ret := <-inCh
if ret.error != nil {
c.lg.Error("Channel read records failed",
zap.String("tunnelId", c.tunnelId), zap.String("clientId", c.clientId),
zap.String("channelId", c.channelId), zap.Error(ret.error))
return false, ret.error
}
if ret.finished {
return true, nil
}
s := time.Now()
if err := c.p.Process(ret.records, ret.binaryRecords, ret.recordCount, ret.nextToken, ret.traceId, c.streamChannel, manager); err != nil {
c.lg.Error("Processor process records failed",
zap.String("tunnelId", c.tunnelId), zap.String("clientId", c.clientId),
zap.String("channelId", c.channelId), zap.Error(err))
return false, err
}
if ret.recordCount != 0 {
c.lg.Info("Metric info", zap.String("tunnelId", c.tunnelId), zap.String("clientId", c.clientId),
zap.String("channelId", c.channelId), zap.String("token", ret.nextToken),
zap.String("ClientProcessLatency", time.Now().Sub(s).String()))
}
//channel switch control by sdk
if c.parallelReleaseManager != nil && !c.needManualRelease {
c.parallelReleaseManager.Release()
}
return false, nil
}
func streamFullData(numRec int, size int) bool {
return numRec > rpoBar || size > rpoSizeBar
}
type ParallelReleaseManager interface {
Release() bool
}
type defaultParallelReleaseManager struct {
mu *sync.Mutex
quotaAcquired bool
channelParallelChan chan bool
}
/*
Manually release the quota occupied by this channel, after release, Other channels can preempt this channel.
Only the channel that occupies quota can read and process data.
*/
func (c *defaultParallelReleaseManager) Release() bool {
c.mu.Lock()
defer c.mu.Unlock()
if c.quotaAcquired {
<-c.channelParallelChan
c.quotaAcquired = false
return true
} else {
return false
}
}
func (c *defaultParallelReleaseManager) checkQuotaAcquired() bool {
c.mu.Lock()
defer c.mu.Unlock()
return c.quotaAcquired
}