-
Notifications
You must be signed in to change notification settings - Fork 541
/
request.go
1294 lines (1177 loc) · 31.4 KB
/
request.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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2017-2021 Lei Ni (nilei81@gmail.com) and other contributors.
//
// Licensed 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 dragonboat
import (
"crypto/sha512"
"encoding/binary"
"fmt"
"math/rand"
"os"
"sync"
"sync/atomic"
"time"
"github.com/cockroachdb/errors"
"github.com/lni/goutils/random"
"github.com/lni/dragonboat/v4/client"
"github.com/lni/dragonboat/v4/config"
"github.com/lni/dragonboat/v4/internal/fileutil"
"github.com/lni/dragonboat/v4/internal/rsm"
"github.com/lni/dragonboat/v4/internal/settings"
"github.com/lni/dragonboat/v4/logger"
pb "github.com/lni/dragonboat/v4/raftpb"
sm "github.com/lni/dragonboat/v4/statemachine"
)
var (
defaultGCTick uint64 = 2
pendingProposalShards = settings.Soft.PendingProposalShards
)
var (
plog = logger.GetLogger("dragonboat")
)
var (
// ErrInvalidOption indicates that the specified option is invalid.
ErrInvalidOption = errors.New("invalid option")
// ErrInvalidOperation indicates that the requested operation is not allowed.
// e.g. making read or write requests on witness node are not allowed.
ErrInvalidOperation = errors.New("invalid operation")
// ErrInvalidAddress indicates that the specified address is invalid.
ErrInvalidAddress = errors.New("invalid address")
// ErrInvalidSession indicates that the specified client session is invalid.
ErrInvalidSession = errors.New("invalid session")
// ErrTimeoutTooSmall indicates that the specified timeout value is too small.
ErrTimeoutTooSmall = errors.New("specified timeout value is too small")
// ErrPayloadTooBig indicates that the payload is too big.
ErrPayloadTooBig = errors.New("payload is too big")
// ErrSystemBusy indicates that the system is too busy to handle the request.
// This might be caused when the Raft node reached its MaxInMemLogSize limit
// or other system limits. For a requested snapshot, leadership transfer or
// Raft config change operation, ErrSystemBusy means there is already such a
// request waiting to be processed.
ErrSystemBusy = errors.New("system is too busy try again later")
// ErrShardClosed indicates that the requested shard is being shut down.
ErrShardClosed = errors.New("raft shard already closed")
// ErrShardNotInitialized indicates that the requested operation can not be
// completed as the involved raft shard has not been initialized yet.
ErrShardNotInitialized = errors.New("raft shard not initialized yet")
// ErrTimeout indicates that the operation timed out.
ErrTimeout = errors.New("timeout")
// ErrCanceled indicates that the request has been canceled.
ErrCanceled = errors.New("request canceled")
// ErrRejected indicates that the request has been rejected.
ErrRejected = errors.New("request rejected")
// ErrAborted indicates that the request has been aborted, usually by user
// defined behaviours.
ErrAborted = errors.New("request aborted")
// ErrShardNotReady indicates that the request has been dropped as the
// specified raft shard is not ready to handle the request. Unknown leader
// is the most common cause of this Error, trying to use a shard not fully
// initialized is another major cause of ErrShardNotReady.
ErrShardNotReady = errors.New("request dropped as the shard is not ready")
// ErrInvalidTarget indicates that the specified node id invalid.
ErrInvalidTarget = errors.New("invalid target node ID")
)
// IsTempError returns a boolean value indicating whether the specified error
// is a temporary error that worth to be retried later with the exact same
// input, potentially on a more suitable NodeHost instance.
func IsTempError(err error) bool {
return errors.Is(err, ErrSystemBusy) ||
errors.Is(err, ErrShardClosed) ||
errors.Is(err, ErrShardNotInitialized) ||
errors.Is(err, ErrShardNotReady) ||
errors.Is(err, ErrTimeout) ||
errors.Is(err, ErrClosed) ||
errors.Is(err, ErrAborted)
}
// LogRange defines the range [FirstIndex, lastIndex) of the raft log.
type LogRange struct {
FirstIndex uint64
LastIndex uint64
}
// RequestResultCode is the result code returned to the client to indicate the
// outcome of the request.
type RequestResultCode int
// RequestResult is the result struct returned for the request.
type RequestResult struct {
// code is the result state of the request.
code RequestResultCode
// Result is the returned result from the Update method of the state machine
// instance. Result is only available when making a proposal and the Code
// value is RequestCompleted.
result sm.Result
entries []pb.Entry
logRange LogRange
snapshotResult bool
logQueryResult bool
}
// RequestOutOfRange returns a boolean value indicating whether the request
// is out of range.
func (rr *RequestResult) RequestOutOfRange() bool {
return rr.code == requestOutOfRange
}
// Timeout returns a boolean value indicating whether the request timed out.
func (rr *RequestResult) Timeout() bool {
return rr.code == requestTimeout
}
// Committed returns a boolean value indicating whether the request has been
// committed by Raft.
func (rr *RequestResult) Committed() bool {
return rr.code == requestCompleted || rr.code == requestCommitted
}
// Completed returns a boolean value indicating whether the request completed
// successfully. For proposals, it means the proposal has been committed by the
// Raft shard and applied on the local node. For ReadIndex operation, it means
// the shard is now ready for a local read.
func (rr *RequestResult) Completed() bool {
return rr.code == requestCompleted
}
// Terminated returns a boolean value indicating the request terminated due to
// the requested Raft shard is being shut down.
func (rr *RequestResult) Terminated() bool {
return rr.code == requestTerminated
}
// Aborted returns a boolean value indicating the request is aborted.
func (rr *RequestResult) Aborted() bool {
return rr.code == requestAborted
}
// Rejected returns a boolean value indicating the request is rejected. For a
// proposal, it means that the used client session instance is not registered
// or it has been evicted on the server side. When requesting a client session
// to be registered, Rejected means the another client session with the same
// client ID has already been registered. When requesting a client session to
// be unregistered, Rejected means the specified client session is not found
// on the server side. For a membership change request, it means the request
// is out of order and thus not applied.
func (rr *RequestResult) Rejected() bool {
return rr.code == requestRejected
}
// Dropped returns a boolean flag indicating whether the request has been
// dropped as the leader is unavailable or not ready yet. Such dropped requests
// can usually be retried once the leader is ready.
func (rr *RequestResult) Dropped() bool {
return rr.code == requestDropped
}
// SnapshotIndex returns the index of the generated snapshot when the
// RequestResult is from a snapshot related request. Invoking this method on
// RequestResult instances not related to snapshots will cause panic.
func (rr *RequestResult) SnapshotIndex() uint64 {
if !rr.snapshotResult {
plog.Panicf("not a snapshot request result")
}
return rr.result.Value
}
// RaftLogs returns the raft log query result.
func (rr *RequestResult) RaftLogs() ([]pb.Entry, LogRange) {
if !rr.logQueryResult {
panic("not a raft log query result")
}
return rr.entries, rr.logRange
}
// GetResult returns the result value of the request. When making a proposal,
// the returned result is the value returned by the Update method of the
// IStateMachine instance. Returned result is only valid if the RequestResultCode
// value is RequestCompleted.
func (rr *RequestResult) GetResult() sm.Result {
return rr.result
}
const (
requestTimeout RequestResultCode = iota
requestCompleted
requestTerminated
requestRejected
requestDropped
requestAborted
requestCommitted
requestOutOfRange
)
var requestResultCodeName = [...]string{
"RequestTimeout",
"RequestCompleted",
"RequestTerminated",
"RequestRejected",
"RequestDropped",
"RequestAborted",
"RequestCommitted",
"RequestOutOfRange",
}
func (c RequestResultCode) String() string {
return requestResultCodeName[uint64(c)]
}
type logicalClock struct {
ltick uint64
lastGcTime uint64
gcTick uint64
}
func newLogicalClock() logicalClock {
if defaultGCTick == 0 || defaultGCTick > 3 {
plog.Panicf("invalid defaultGCTick %d", defaultGCTick)
}
return logicalClock{gcTick: defaultGCTick}
}
func (p *logicalClock) tick(tick uint64) {
atomic.StoreUint64(&p.ltick, tick)
}
func (p *logicalClock) getTick() uint64 {
return atomic.LoadUint64(&p.ltick)
}
type ready struct {
val uint32
}
func (r *ready) ready() bool {
return atomic.LoadUint32(&r.val) == 1
}
func (r *ready) clear() {
atomic.StoreUint32(&r.val, 0)
}
func (r *ready) set() {
atomic.StoreUint32(&r.val, 1)
}
// SysOpState is the object used to provide system maintenance operation result
// to users.
type SysOpState struct {
completedC <-chan struct{}
}
// CompletedC returns a struct{} chan that is closed when the requested
// operation is completed.
//
// Deprecated: CompletedC() has been deprecated. Use ResultC() instead.
func (o *SysOpState) CompletedC() <-chan struct{} {
return o.completedC
}
// ResultC returns a struct{} chan that is closed when the requested
// operation is completed.
func (o *SysOpState) ResultC() <-chan struct{} {
return o.completedC
}
// RequestState is the object used to provide request result to users.
type RequestState struct {
key uint64
clientID uint64
seriesID uint64
respondedTo uint64
deadline uint64
logRange LogRange
maxSize uint64
readyToRead ready
readyToRelease ready
aggrC chan RequestResult
committedC chan RequestResult
// CompletedC is a channel for delivering request result to users.
//
// Deprecated: CompletedC has been deprecated. Use ResultC() or AppliedC()
// instead.
CompletedC chan RequestResult
node *node
pool *sync.Pool
notifyCommit bool
testErr chan struct{}
}
// AppliedC returns a channel of RequestResult for delivering request result.
// The returned channel reports the final outcomes of proposals and config
// changes, the return value can be of one of the Completed(), Dropped(),
// Timeout(), Rejected(), Terminated() or Aborted() values.
//
// Use ResultC() when the client wants to be notified when proposals or config
// changes are committed.
func (r *RequestState) AppliedC() chan RequestResult {
return r.CompletedC
}
// ResultC returns a channel of RequestResult for delivering request results to
// users. When NotifyCommit is not enabled, the behaviour of the returned
// channel is the same as the one returned by the AppliedC() method. When
// NotifyCommit is enabled, up to two RequestResult values can be received from
// the returned channel. For example, for a successful proposal that is
// eventually committed and applied, the returned chan RequestResult will return
// a RequestResult value to indicate the proposal is committed first, it will be
// followed by another RequestResult value indicating the proposal has been
// applied into the state machine.
//
// Use AppliedC() when your client don't need extra notification when proposals
// and config changes are committed.
func (r *RequestState) ResultC() chan RequestResult {
if !r.notifyCommit {
return r.CompletedC
}
if r.committedC == nil {
plog.Panicf("committedC is nil")
}
if r.aggrC != nil {
return r.aggrC
}
r.aggrC = make(chan RequestResult, 2)
tryBridgeCommittedC := func() {
select {
case cn := <-r.committedC:
if cn.code != requestCommitted {
plog.Panicf("unexpected requestResult, %s", cn.code)
}
r.aggrC <- cn
default:
}
}
go func() {
if r.testErr != nil {
defer func() {
if rr := recover(); rr != nil {
close(r.testErr)
}
}()
}
select {
case cn := <-r.committedC:
if cn.code != requestCommitted {
plog.Panicf("unexpected requestResult, %s", cn.code)
}
r.aggrC <- cn
cc := <-r.CompletedC
if cc.Dropped() {
plog.Panicf("committed entry dropped")
}
if cc.Aborted() {
plog.Panicf("committed entry aborted")
}
if cc.code == requestCommitted {
plog.Panicf("entry committed notified twice")
}
r.aggrC <- cc
case cc := <-r.CompletedC:
if cc.Aborted() {
// this select is to make the test TestResultCCanReceiveRequestResults
// easier to implement for the input
// {true, true, requestAborted, true}
tryBridgeCommittedC()
plog.Panicf("requestAborted sent to CompletedC")
}
if cc.code == requestCommitted {
tryBridgeCommittedC()
plog.Panicf("requestCommitted sent to CompletedC")
}
select {
case ccn := <-r.committedC:
if cc.Dropped() {
r.aggrC <- ccn
plog.Panicf("applied entry dropped")
}
r.aggrC <- ccn
default:
}
r.aggrC <- cc
}
}()
return r.aggrC
}
func (r *RequestState) committed() {
if !r.notifyCommit {
plog.Panicf("notify commit not allowed")
}
if r.committedC == nil {
plog.Panicf("committedC is nil")
}
select {
case r.committedC <- RequestResult{code: requestCommitted}:
default:
plog.Panicf("RequestState.committedC is full")
}
}
func (r *RequestState) timeout() {
r.notify(RequestResult{code: requestTimeout})
}
func (r *RequestState) terminated() {
r.notify(RequestResult{code: requestTerminated})
}
func (r *RequestState) dropped() {
r.notify(RequestResult{code: requestDropped})
}
func (r *RequestState) notify(result RequestResult) {
select {
case r.CompletedC <- result:
r.readyToRelease.set()
default:
plog.Panicf("RequestState.CompletedC is full")
}
}
// Release puts the RequestState instance back to an internal pool so it can be
// reused. Release is normally called after all RequestResult values have been
// received from the ResultC() channel.
func (r *RequestState) Release() {
if r.pool != nil {
if !r.readyToRelease.ready() {
return
}
r.notifyCommit = false
r.logRange = LogRange{}
r.maxSize = 0
r.deadline = 0
r.key = 0
r.seriesID = 0
r.clientID = 0
r.respondedTo = 0
r.node = nil
r.readyToRead.clear()
r.readyToRelease.clear()
r.aggrC = nil
r.pool.Put(r)
}
}
func (r *RequestState) reuse(notifyCommit bool) {
if r.aggrC != nil {
plog.Panicf("aggrC not nil")
}
if len(r.CompletedC) > 0 || r.CompletedC == nil {
r.CompletedC = make(chan RequestResult, 1)
}
if notifyCommit {
if len(r.committedC) > 0 || r.committedC == nil {
r.committedC = make(chan RequestResult, 1)
}
} else {
r.committedC = nil
}
}
func (r *RequestState) mustBeReadyForLocalRead() {
if r.node == nil {
plog.Panicf("invalid rs")
}
if !r.node.initialized() {
plog.Panicf("%s not initialized", r.node.id())
}
if !r.readyToRead.ready() {
plog.Panicf("not ready for local read")
}
}
type proposalShard struct {
mu sync.Mutex
proposals *entryQueue
pending map[uint64]*RequestState
pool *sync.Pool
cfg config.Config
stopped bool
notifyCommit bool
expireNotified uint64
logicalClock
}
type keyGenerator struct {
randMu sync.Mutex
rand *rand.Rand
}
func (k *keyGenerator) nextKey() uint64 {
k.randMu.Lock()
v := k.rand.Uint64()
k.randMu.Unlock()
return v
}
type pendingProposal struct {
shards []*proposalShard
keyg []*keyGenerator
ps uint64
}
type readBatch struct {
index uint64
requests []*RequestState
}
type pendingReadIndex struct {
mu sync.Mutex
batches map[pb.SystemCtx]readBatch
requests *readIndexQueue
stopped bool
pool *sync.Pool
logicalClock
}
type configChangeRequest struct {
data []byte
key uint64
}
type pendingConfigChange struct {
mu sync.Mutex
pending *RequestState
confChangeC chan<- configChangeRequest
notifyCommit bool
logicalClock
}
type pendingSnapshot struct {
mu sync.Mutex
pending *RequestState
snapshotC chan<- rsm.SSRequest
logicalClock
}
type pendingLeaderTransfer struct {
leaderTransferC chan uint64
}
func newPendingLeaderTransfer() pendingLeaderTransfer {
return pendingLeaderTransfer{
leaderTransferC: make(chan uint64, 1),
}
}
func (l *pendingLeaderTransfer) request(target uint64) error {
if target == pb.NoNode {
return ErrInvalidTarget
}
select {
case l.leaderTransferC <- target:
default:
return ErrSystemBusy
}
return nil
}
func (l *pendingLeaderTransfer) get() (uint64, bool) {
select {
case v := <-l.leaderTransferC:
return v, true
default:
}
return 0, false
}
func newPendingSnapshot(snapshotC chan<- rsm.SSRequest) pendingSnapshot {
return pendingSnapshot{
logicalClock: newLogicalClock(),
snapshotC: snapshotC,
}
}
func (p *pendingSnapshot) notify(r RequestResult) {
r.snapshotResult = true
p.pending.notify(r)
}
func (p *pendingSnapshot) close() {
p.mu.Lock()
defer p.mu.Unlock()
p.snapshotC = nil
if p.pending != nil {
p.pending.terminated()
p.pending = nil
}
}
func (p *pendingSnapshot) request(st rsm.SSReqType,
path string, override bool, overhead uint64, index uint64,
timeoutTick uint64) (*RequestState, error) {
if timeoutTick == 0 {
return nil, ErrTimeoutTooSmall
}
p.mu.Lock()
defer p.mu.Unlock()
if p.pending != nil {
return nil, ErrSystemBusy
}
if p.snapshotC == nil {
return nil, ErrShardClosed
}
ssreq := rsm.SSRequest{
Type: st,
Path: path,
Key: random.LockGuardedRand.Uint64(),
OverrideCompaction: override,
CompactionOverhead: overhead,
CompactionIndex: index,
}
req := &RequestState{
key: ssreq.Key,
deadline: p.getTick() + timeoutTick,
CompletedC: make(chan RequestResult, 1),
notifyCommit: false,
}
select {
case p.snapshotC <- ssreq:
p.pending = req
return req, nil
default:
}
return nil, ErrSystemBusy
}
func (p *pendingSnapshot) gc() {
p.mu.Lock()
defer p.mu.Unlock()
if p.pending == nil {
return
}
now := p.getTick()
// FIXME:
// golangci-lint v1.23 complains that lastGcTime is not used unless lastGcTime
// is accessed as a member of the logicalClock. v1.33's typecheck is pretty
// broken, preventing us from upgrading.
if now-p.logicalClock.lastGcTime < p.gcTick {
return
}
p.lastGcTime = now
if p.pending.deadline < now {
p.pending.timeout()
p.pending = nil
}
}
func (p *pendingSnapshot) apply(key uint64,
ignored bool, aborted bool, index uint64) {
if ignored && aborted {
plog.Panicf("ignored && aborted")
}
p.mu.Lock()
defer p.mu.Unlock()
if p.pending == nil {
return
}
if p.pending.key == key {
r := RequestResult{}
if ignored {
r.code = requestRejected
} else if aborted {
r.code = requestAborted
} else {
r.code = requestCompleted
r.result.Value = index
}
p.notify(r)
p.pending = nil
}
}
func newPendingConfigChange(confChangeC chan<- configChangeRequest,
notifyCommit bool) pendingConfigChange {
return pendingConfigChange{
confChangeC: confChangeC,
logicalClock: newLogicalClock(),
notifyCommit: notifyCommit,
}
}
func (p *pendingConfigChange) close() {
p.mu.Lock()
defer p.mu.Unlock()
if p.confChangeC != nil {
if p.pending != nil {
p.pending.terminated()
p.pending = nil
}
close(p.confChangeC)
p.confChangeC = nil
}
}
func (p *pendingConfigChange) request(cc pb.ConfigChange,
timeoutTick uint64) (*RequestState, error) {
if timeoutTick == 0 {
return nil, ErrTimeoutTooSmall
}
p.mu.Lock()
defer p.mu.Unlock()
if p.pending != nil {
return nil, ErrSystemBusy
}
if p.confChangeC == nil {
return nil, ErrShardClosed
}
data := pb.MustMarshal(&cc)
ccreq := configChangeRequest{
key: random.LockGuardedRand.Uint64(),
data: data,
}
req := &RequestState{
key: ccreq.key,
deadline: p.getTick() + timeoutTick,
CompletedC: make(chan RequestResult, 1),
notifyCommit: p.notifyCommit,
}
if p.notifyCommit {
req.committedC = make(chan RequestResult, 1)
}
select {
case p.confChangeC <- ccreq:
p.pending = req
return req, nil
default:
}
return nil, ErrSystemBusy
}
func (p *pendingConfigChange) gc() {
p.mu.Lock()
defer p.mu.Unlock()
if p.pending == nil {
return
}
now := p.getTick()
if now-p.lastGcTime < p.gcTick {
return
}
p.lastGcTime = now
if p.pending.deadline < now {
p.pending.timeout()
p.pending = nil
}
}
func (p *pendingConfigChange) committed(key uint64) {
p.mu.Lock()
defer p.mu.Unlock()
if p.pending == nil {
return
}
if p.pending.key == key {
p.pending.committed()
}
}
func (p *pendingConfigChange) dropped(key uint64) {
p.mu.Lock()
defer p.mu.Unlock()
if p.pending == nil {
return
}
if p.pending.key == key {
p.pending.dropped()
p.pending = nil
}
}
func (p *pendingConfigChange) apply(key uint64, rejected bool) {
p.mu.Lock()
defer p.mu.Unlock()
if p.pending == nil {
return
}
var v RequestResult
if rejected {
v.code = requestRejected
} else {
v.code = requestCompleted
}
if p.pending.key == key {
p.pending.notify(v)
p.pending = nil
}
}
func newPendingReadIndex(pool *sync.Pool, r *readIndexQueue) pendingReadIndex {
return pendingReadIndex{
batches: make(map[pb.SystemCtx]readBatch),
requests: r,
logicalClock: newLogicalClock(),
pool: pool,
}
}
func (p *pendingReadIndex) close() {
p.mu.Lock()
defer p.mu.Unlock()
p.stopped = true
if p.requests != nil {
p.requests.close()
reqs := p.requests.get()
for _, rec := range reqs {
rec.terminated()
}
}
for _, rb := range p.batches {
for _, req := range rb.requests {
if req != nil {
req.terminated()
}
}
}
}
func (p *pendingReadIndex) read(timeoutTick uint64) (*RequestState, error) {
if timeoutTick == 0 {
return nil, ErrTimeoutTooSmall
}
req := p.pool.Get().(*RequestState)
req.reuse(false)
req.notifyCommit = false
req.deadline = p.getTick() + timeoutTick
ok, closed := p.requests.add(req)
if closed {
return nil, ErrShardClosed
}
if !ok {
return nil, ErrSystemBusy
}
return req, nil
}
func (p *pendingReadIndex) genCtx() pb.SystemCtx {
et := p.getTick() + 30
for {
v := pb.SystemCtx{
Low: random.LockGuardedRand.Uint64(),
High: et,
}
if v.Low != 0 {
return v
}
}
}
func (p *pendingReadIndex) nextCtx() pb.SystemCtx {
p.mu.Lock()
defer p.mu.Unlock()
return p.genCtx()
}
func (p *pendingReadIndex) addReady(reads []pb.ReadyToRead) {
if len(reads) == 0 {
return
}
p.mu.Lock()
defer p.mu.Unlock()
for _, v := range reads {
if rb, ok := p.batches[v.SystemCtx]; ok {
rb.index = v.Index
p.batches[v.SystemCtx] = rb
}
}
}
func (p *pendingReadIndex) add(sys pb.SystemCtx, reqs []*RequestState) {
p.mu.Lock()
defer p.mu.Unlock()
if p.stopped {
return
}
if _, ok := p.batches[sys]; ok {
plog.Panicf("same system ctx added again %v", sys)
} else {
rs := make([]*RequestState, len(reqs))
copy(rs, reqs)
p.batches[sys] = readBatch{
requests: rs,
}
}
}
func (p *pendingReadIndex) dropped(system pb.SystemCtx) {
p.mu.Lock()
defer p.mu.Unlock()
if p.stopped {
return
}
if rb, ok := p.batches[system]; ok {
for _, req := range rb.requests {
if req != nil {
req.dropped()
}
}
delete(p.batches, system)
}
}
func (p *pendingReadIndex) applied(applied uint64) {
p.mu.Lock()
defer p.mu.Unlock()
if p.stopped || len(p.batches) == 0 {
return
}
now := p.getTick()
for sys, rb := range p.batches {
if rb.index > 0 && rb.index <= applied {
for _, req := range rb.requests {
if req != nil {
var v RequestResult
if req.deadline > now {
req.readyToRead.set()
v.code = requestCompleted
} else {
v.code = requestTimeout
}
req.notify(v)
}
}
delete(p.batches, sys)
}
}
if now-p.lastGcTime < p.gcTick {
return
}
p.lastGcTime = now
p.gc(now)
}
func (p *pendingReadIndex) gc(now uint64) {
if len(p.batches) == 0 {
return
}
for sys, rb := range p.batches {
for idx, req := range rb.requests {
if req != nil && req.deadline < now {
req.timeout()
rb.requests[idx] = nil
p.batches[sys] = rb
}
}
}
for sys, rb := range p.batches {
if sys.High < now {
empty := true
for _, req := range rb.requests {
if req != nil {
empty = false
break
}
}
if empty {
delete(p.batches, sys)
}
}
}
}
func getRng(shardID uint64, replicaID uint64, shard uint64) *keyGenerator {
pid := os.Getpid()
nano := time.Now().UnixNano()
seedStr := fmt.Sprintf("%d-%d-%d-%d-%d", pid, nano, shardID, replicaID, shard)
m := sha512.New()
fileutil.MustWrite(m, []byte(seedStr))
sum := m.Sum(nil)
seed := binary.LittleEndian.Uint64(sum)
return &keyGenerator{rand: rand.New(rand.NewSource(int64(seed)))}
}