forked from dinstein/fabric
/
synccli.go
390 lines (314 loc) · 9.42 KB
/
synccli.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
package sync
import (
"fmt"
pb "github.com/abchain/fabric/protos"
"golang.org/x/net/context"
"sync"
"time"
)
type ClientFactory interface {
Tag() string
//opts just called at the beginning of ExecuteSyncTask so returned
//object can be created just after being called
Opts() *clientOpts
PreFilter(rledger *pb.LedgerState) bool
//notice this should provide a handling function and factory is
//responsed to schedule tasks between its mutiple handling
//functions
//handling function MUST return nil to incidate current task
//is finished and non-nil to indicate scheduler should retry
//another peer
AssignHandling() func(context.Context, *pb.StreamHandler, *syncCore) error
}
type syncTaskScheduler struct {
sync.Mutex
activedTasks int
conCurrentLimit int
excludeFatalOnly bool
taskEndNotify *sync.Cond
sstub *pb.StreamStub
//the peer which has been handled and finished, so we never
//retry on them when retry another traversing
excluedePeers map[string]bool
}
type NormalEnd struct{}
func (NormalEnd) Error() string { return "Normal finish" }
type FatalEnd struct {
error
}
var retryIntervalLimit = time.Second * 10
//this help us to access the stub object from streamstub
var AccessStubHelper func(*pb.StreamStub, func(*SyncStub)) = func(*pb.StreamStub, func(*SyncStub)) {}
func ExecuteSyncTask(ctx context.Context, cf ClientFactory, sstub *pb.StreamStub) error {
opts := cf.Opts()
rt := &syncTaskScheduler{
conCurrentLimit: opts.ConcurrentLimit,
excluedePeers: make(map[string]bool),
excludeFatalOnly: opts.RetryFail,
}
//checking for correction
if rt.conCurrentLimit == 0 {
clilogger.Warningf("Concurrent limit is not set, suppose to be 1")
rt.conCurrentLimit = 1
}
rt.taskEndNotify = sync.NewCond(rt)
retryTime := time.Duration(opts.RetryInterval) * time.Second
var retryCnt int
AccessStubHelper(sstub, func(s *SyncStub) { s.depressStatusNotify = true })
defer AccessStubHelper(sstub, func(s *SyncStub) { s.depressStatusNotify = false })
for {
clilogger.Infof("start sync task [%s] (%d times)", cf.Tag(), retryCnt)
rt.innerSpawn(ctx, sstub, cf)
if err := rt.waitAll(ctx); err != nil {
return err
}
if rt.conCurrentLimit == 0 {
//all thread has return normally
//when we done, broadcast new ledger status to neighbours
AccessStubHelper(sstub, func(s *SyncStub) { s.BroadcastLedgerStatus(sstub) })
return nil
}
if opts.RetryCount >= 0 && retryCnt >= opts.RetryCount {
return fmt.Errorf("Task [%s] fail: retry count [%d] exceed", cf.Tag(), retryCnt)
} else {
retryCnt++
}
if retryTime < retryIntervalLimit && retryCnt >= 3 {
retryTime = retryIntervalLimit
}
select {
case <-ctx.Done():
return ctx.Err()
case <-time.NewTimer(retryTime).C:
//do retry
}
}
}
func (s *syncTaskScheduler) activeTaskExit(peer *pb.PeerID, err error) {
s.Lock()
defer s.Unlock()
//sanity check
if s.conCurrentLimit == 0 || s.activedTasks == 0 {
panic("Wrong code: error counting")
}
s.activedTasks--
if _, ok := err.(NormalEnd); ok {
err = nil
}
if err == nil {
clilogger.Debugf("A task on peer [%s] has normally exited", peer.GetName())
s.conCurrentLimit--
delete(s.excluedePeers, peer.GetName())
} else if _, ok := err.(FatalEnd); ok {
//exclude this peer
clilogger.Infof("task on peer [%s] is FATAL fail: %s, exclude this peer", peer.GetName(), err)
s.excluedePeers[peer.GetName()] = false
} else if !s.excludeFatalOnly {
clilogger.Infof("task on peer [%s] is fail: %s, exclude this peer", peer.GetName(), err)
s.excluedePeers[peer.GetName()] = false
}
s.taskEndNotify.Signal()
}
func (s *syncTaskScheduler) waitAll(ctx context.Context) error {
s.Lock()
defer s.Unlock()
for s.activedTasks > 0 {
s.taskEndNotify.Wait()
select {
case <-ctx.Done():
return ctx.Err()
default:
}
}
return nil
}
func (s *syncTaskScheduler) waitForNext(ctx context.Context) error {
s.Lock()
defer s.Unlock()
for s.conCurrentLimit > 0 && s.activedTasks >= s.conCurrentLimit {
s.taskEndNotify.Wait()
select {
case <-ctx.Done():
return ctx.Err()
default:
}
}
if s.conCurrentLimit == 0 {
return NormalEnd{}
}
return nil
}
func (s *syncTaskScheduler) preFilter(peer *pb.PeerID) bool {
s.Lock()
defer s.Unlock()
_, existed := s.excluedePeers[peer.GetName()]
if existed {
return false
}
return true
}
func (s *syncTaskScheduler) innerSpawn(ctx context.Context, sstub *pb.StreamStub, cf ClientFactory) {
wctx, endF := context.WithCancel(ctx)
defer endF()
chs := sstub.OverAllHandlers(wctx)
for strm := range chs {
castedh, ok := strm.Impl().(*syncHandler)
if !ok {
panic("Wrong implement, implement is not syncHandler")
}
if !castedh.core.IsIdle() || !s.preFilter(strm.Id) || !cf.PreFilter(castedh.GetRemoteLedgerState()) {
clilogger.Debugf("prefiltering peer %s fail, try next one", strm.Id)
continue
}
s.Lock()
//do prepare works before spawning task
s.activedTasks++
s.excluedePeers[strm.Id.GetName()] = true
s.Unlock()
clilogger.Debugf("start syncing task on peer %s", strm.Id)
//spawn handling routine
go func(f func(context.Context, *pb.StreamHandler, *syncCore) error, strm *pb.PickedStreamHandler, core *syncCore) {
err := f(ctx, strm.StreamHandler, core)
s.activeTaskExit(strm.Id, err)
}(cf.AssignHandling(), strm, castedh.core.syncCore)
if err := s.waitForNext(ctx); err != nil {
clilogger.Debugf("current schedule for task [%s] exit for [%s]", cf.Tag(), err)
return
}
}
}
type ForceAck struct{}
func (ForceAck) Error() string { return "Forced acking" }
type SessionClientImpl interface {
PreFilter(rledger *pb.LedgerState) bool
//assign onconnect and next an id to distinguish the
//different tasks, next can gen a user-custom object
//and it was passed to OnData/Fail
OnConnected(int, *pb.AcceptSession) error
Next(int) (*pb.TransferRequest, interface{})
//can return ForceAck or NormalEnd
//if normalend is returned, Next() will
//be call and the whole session is ended
//if Next() return nil
//Notice 1: if OnData return any error execpt
//for ForceAck, session will end without
//OnFail being called
//Notice 2: we always ack when normal end
OnData(interface{}, *pb.TransferResponse) error
OnFail(interface{}, error)
}
type sessionCliAdapter struct {
tag string
conn *pb.OpenSession
options *clientOpts
taskIdCnt int
SessionClientImpl
}
func newSessionClient(tag string, impl SessionClientImpl) *sessionCliAdapter {
ret := new(sessionCliAdapter)
ret.tag = tag
ret.options = DefaultClientOption()
ret.SessionClientImpl = impl
return ret
}
func (sa *sessionCliAdapter) setConnectMessage(msg *pb.OpenSession) {
sa.conn = msg
}
func (sa *sessionCliAdapter) waitResp(ctx context.Context, c <-chan *pb.SyncMsg_Response) (*pb.SyncMsg_Response, error) {
select {
case <-ctx.Done():
return nil, ctx.Err()
case msg := <-c:
return msg, nil
}
}
func (sa *sessionCliAdapter) handlingFunc(ctx context.Context, tskId int, strm msgSender, c *syncCore) (err error) {
//a task is assigned first so we can fast end handling if no task
req, taskCustom := sa.Next(tskId)
defer func() {
if failobj := recover(); failobj != nil {
err = FatalEnd{fmt.Errorf("Fatal data: %v", failobj)}
}
if _, ok := err.(NormalEnd); err != nil && !ok {
clilogger.Debugf("handling exit for session error: %s", err)
sa.OnFail(taskCustom, err)
}
}()
if req == nil {
return NormalEnd{}
}
respc, err := c.OpenSession(strm, sa.conn)
//opensession fail
if err != nil {
return err
}
accept, err := sa.waitResp(ctx, respc)
if err != nil {
c.CancelRequest(respc)
return err
} else if serr := accept.GetErr(); serr != nil {
return fmt.Errorf("open session fail <%d>: %s", serr.GetErrorCode(), serr.GetErrorDetail())
}
defer c.SessionClose()
if err = sa.OnConnected(tskId, accept.GetHandshake()); err != nil {
return err
} else if err = c.SessionReq(req); err != nil {
return err
}
var ackCounter, ackWindow int
if hs := accept.GetHandshake(); hs != nil {
ackWindow = int(hs.GetTransfer().GetMaxWindowSize() / 2)
}
for {
var msg *pb.SyncMsg_Response
msg, err = sa.waitResp(ctx, respc)
if err != nil {
return err
}
if serr := msg.GetErr(); serr != nil {
err = fmt.Errorf("resp fail <%d>: %s", serr.GetErrorCode(), serr.GetErrorDetail())
return err
} else if pack := msg.GetSession(); pack == nil {
err = fmt.Errorf("mal-formed resp: no package")
return err
} else if err = sa.OnData(taskCustom, pack); err != nil {
switch err.(type) {
case ForceAck:
err = c.SessionAck(pack, nil)
case NormalEnd:
req, taskCustom = sa.Next(tskId)
if req == nil {
clilogger.Debug("handling normal exit")
return err
}
err = c.SessionAck(pack, req)
default:
clilogger.Debugf("handling exit for impl return error: %s", err)
return err
}
ackCounter = 0
} else {
ackCounter++
if ackCounter > ackWindow {
ackCounter = 0
err = c.SessionAck(pack, nil)
}
}
if err != nil {
return err
}
}
return fmt.Errorf("Should not here")
}
func (sa *sessionCliAdapter) Tag() string { return sa.tag }
func (sa *sessionCliAdapter) Opts() *clientOpts { return sa.options }
func (sa *sessionCliAdapter) AssignHandling() func(context.Context, *pb.StreamHandler, *syncCore) error {
if sa.conn == nil {
panic("Connect message is not set")
}
tskId := sa.taskIdCnt
sa.taskIdCnt++
return func(ctx context.Context, strm *pb.StreamHandler, c *syncCore) error {
return sa.handlingFunc(ctx, tskId, strm, c)
}
}