-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcoverage.html
More file actions
3765 lines (3255 loc) · 165 KB
/
coverage.html
File metadata and controls
3765 lines (3255 loc) · 165 KB
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
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>pkg: Go Coverage Report</title>
<style>
body {
background: black;
color: rgb(80, 80, 80);
}
body, pre, #legend span {
font-family: Menlo, monospace;
font-weight: bold;
}
#topbar {
background: black;
position: fixed;
top: 0; left: 0; right: 0;
height: 42px;
border-bottom: 1px solid rgb(80, 80, 80);
}
#content {
margin-top: 50px;
}
#nav, #legend {
float: left;
margin-left: 10px;
}
#legend {
margin-top: 12px;
}
#nav {
margin-top: 10px;
}
#legend span {
margin: 0 5px;
}
.cov0 { color: rgb(192, 0, 0) }
.cov1 { color: rgb(128, 128, 128) }
.cov2 { color: rgb(116, 140, 131) }
.cov3 { color: rgb(104, 152, 134) }
.cov4 { color: rgb(92, 164, 137) }
.cov5 { color: rgb(80, 176, 140) }
.cov6 { color: rgb(68, 188, 143) }
.cov7 { color: rgb(56, 200, 146) }
.cov8 { color: rgb(44, 212, 149) }
.cov9 { color: rgb(32, 224, 152) }
.cov10 { color: rgb(20, 236, 155) }
</style>
</head>
<body>
<div id="topbar">
<div id="nav">
<select id="files">
<option value="file0">raft/pkg/bolt_store.go (0.0%)</option>
<option value="file1">raft/pkg/client.go (0.0%)</option>
<option value="file2">raft/pkg/cluster.go (68.9%)</option>
<option value="file3">raft/pkg/config.go (58.3%)</option>
<option value="file4">raft/pkg/logging.go (27.5%)</option>
<option value="file5">raft/pkg/memory_store.go (80.4%)</option>
<option value="file6">raft/pkg/network_policy.go (100.0%)</option>
<option value="file7">raft/pkg/node.go (83.0%)</option>
<option value="file8">raft/pkg/node_candidate_state.go (81.6%)</option>
<option value="file9">raft/pkg/node_follower_state.go (90.3%)</option>
<option value="file10">raft/pkg/node_leader_state.go (68.8%)</option>
<option value="file11">raft/pkg/node_stable_store.go (65.9%)</option>
<option value="file12">raft/pkg/raft_rpc.pb.go (30.1%)</option>
<option value="file13">raft/pkg/raft_rpc_client.go (73.3%)</option>
<option value="file14">raft/pkg/raft_rpc_grpc.pb.go (45.2%)</option>
<option value="file15">raft/pkg/raft_rpc_server.go (90.9%)</option>
<option value="file16">raft/pkg/util.go (80.0%)</option>
</select>
</div>
<div id="legend">
<span>not tracked</span>
<span class="cov0">not covered</span>
<span class="cov8">covered</span>
</div>
</div>
<div id="content">
<pre class="file" id="file0" style="display: none">package pkg
import (
"os"
"time"
bolt "go.etcd.io/bbolt"
)
// BoltStore implements the StableStore interface and serves as a storage option for raft
type BoltStore struct {
db *bolt.DB
path string
}
// NewBoltStore either creates a new store or reopens an existing store.
// Also populates the latest logIndex into memory.
func NewBoltStore(path string) *BoltStore <span class="cov0" title="0">{
db, err := bolt.Open(path, 0666, &bolt.Options{
Timeout: 2 * time.Second,
})
if err != nil </span><span class="cov0" title="0">{
panic(err)</span>
}
<span class="cov0" title="0">db.Update(func(tx *bolt.Tx) error </span><span class="cov0" title="0">{
getBucket(tx, []byte("logs"))
getBucket(tx, []byte("state"))
getBucket(tx, []byte("snapshots"))
return nil
}</span>)
<span class="cov0" title="0">return &BoltStore{db: db, path: path}</span>
}
func getBucket(tx *bolt.Tx, bucket []byte) *bolt.Bucket <span class="cov0" title="0">{
var err error
b := tx.Bucket(bucket)
if b == nil </span><span class="cov0" title="0">{
b, err = tx.CreateBucketIfNotExists(bucket)
if err != nil </span><span class="cov0" title="0">{
panic(err)</span>
}
}
<span class="cov0" title="0">return b</span>
}
// SetBytes sets a key-value pair into Bolt
func (store *BoltStore) SetBytes(key, value []byte) error <span class="cov0" title="0">{
return store.db.Update(func(tx *bolt.Tx) error </span><span class="cov0" title="0">{
b := getBucket(tx, []byte("state"))
return b.Put(key, value)
}</span>)
}
// GetBytes retrives a value for the specified key from Bolt
func (store *BoltStore) GetBytes(key []byte) []byte <span class="cov0" title="0">{
tx, err := store.db.Begin(false)
if err != nil </span><span class="cov0" title="0">{
panic(err)</span>
}
<span class="cov0" title="0">defer tx.Rollback()
b := getBucket(tx, []byte("state"))
return b.Get(key)</span>
}
// SetUint64 sets a key-value pair into Bolt
func (store *BoltStore) SetUint64(key []byte, term uint64) error <span class="cov0" title="0">{
return store.db.Update(func(tx *bolt.Tx) error </span><span class="cov0" title="0">{
b := getBucket(tx, []byte("state"))
return b.Put(key, uint64ToBytes(term))
}</span>)
}
// GetUint64 retrieves a uint64 from Bolt
func (store *BoltStore) GetUint64(key []byte) uint64 <span class="cov0" title="0">{
tx, err := store.db.Begin(false)
if err != nil </span><span class="cov0" title="0">{
panic(err)</span>
}
<span class="cov0" title="0">defer tx.Rollback()
b := getBucket(tx, []byte("state"))
value := b.Get(key)
if value == nil </span><span class="cov0" title="0">{
return 0
}</span>
<span class="cov0" title="0">return bytesToUint64(value)</span>
}
// StoreLog grabs the next log index and stores a LogEntry into Bolt
func (store *BoltStore) StoreLog(log *LogEntry) error <span class="cov0" title="0">{
return store.db.Update(func(tx *bolt.Tx) error </span><span class="cov0" title="0">{
b := getBucket(tx, []byte("logs"))
buf, err := encodeMsgPack(log)
if err != nil </span><span class="cov0" title="0">{
return err
}</span>
<span class="cov0" title="0">return b.Put(uint64ToBytes(log.Index), buf.Bytes())</span>
})
}
// GetLog retrieves a LogEntry at a specific log index from Bolt
func (store *BoltStore) GetLog(index uint64) *LogEntry <span class="cov0" title="0">{
tx, err := store.db.Begin(false)
if err != nil </span><span class="cov0" title="0">{
panic(err)</span>
}
<span class="cov0" title="0">defer tx.Rollback()
b := getBucket(tx, []byte("logs"))
value := b.Get(uint64ToBytes(index))
if value == nil </span><span class="cov0" title="0">{
return nil
}</span>
<span class="cov0" title="0">var log LogEntry
err = decodeMsgPack(value, &log)
if err != nil </span><span class="cov0" title="0">{
panic(err)</span>
}
<span class="cov0" title="0">return &log</span>
}
// LastLogIndex gets the last index inserted into Bolt
func (store *BoltStore) LastLogIndex() uint64 <span class="cov0" title="0">{
tx, err := store.db.Begin(false)
if err != nil </span><span class="cov0" title="0">{
panic(err)</span>
}
<span class="cov0" title="0">defer tx.Rollback()
b := getBucket(tx, []byte("logs"))
cursor := b.Cursor()
key, _ := cursor.Last()
if key == nil </span><span class="cov0" title="0">{
return 0
}</span>
<span class="cov0" title="0">return bytesToUint64(key)</span>
}
// TruncateLog deletes all logs starting from index
func (store *BoltStore) TruncateLog(index uint64) error <span class="cov0" title="0">{
return store.db.Update(func(tx *bolt.Tx) error </span><span class="cov0" title="0">{
b := getBucket(tx, []byte("logs"))
cursor := b.Cursor()
for key, _ := cursor.Seek(uint64ToBytes(index)); key != nil; key, _ = cursor.Next() </span><span class="cov0" title="0">{
err := cursor.Delete()
if err != nil </span><span class="cov0" title="0">{
return err
}</span>
}
<span class="cov0" title="0">return nil</span>
})
}
// AllLogs returns all logs in ascending order. Used for testing purposes.
func (store *BoltStore) AllLogs() []*LogEntry <span class="cov0" title="0">{
tx, err := store.db.Begin(false)
if err != nil </span><span class="cov0" title="0">{
panic(err)</span>
}
<span class="cov0" title="0">defer tx.Rollback()
b := getBucket(tx, []byte("logs"))
cursor := b.Cursor()
var result []*LogEntry
for key, value := cursor.First(); key != nil; key, value = cursor.Next() </span><span class="cov0" title="0">{
var log LogEntry
if err := decodeMsgPack(value, &log); err != nil </span><span class="cov0" title="0">{
panic(err)</span>
}
<span class="cov0" title="0">result = append(result, &log)</span>
}
<span class="cov0" title="0">return result</span>
}
// Close releases the lock on the db file and closes Bolt
func (store *BoltStore) Close() <span class="cov0" title="0">{
err := store.db.Close()
if err != nil && err != bolt.ErrDatabaseNotOpen </span><span class="cov0" title="0">{
panic(err)</span>
}
}
// Remove deletes the db file
func (store *BoltStore) Remove() <span class="cov0" title="0">{
err := os.RemoveAll(store.path)
if err != nil </span><span class="cov0" title="0">{
panic(err)</span>
}
}
// Path returns the db path
func (store *BoltStore) Path() string <span class="cov0" title="0">{
return store.path
}</span>
</pre>
<pre class="file" id="file1" style="display: none">package pkg
import (
"errors"
"fmt"
"time"
)
// Client represents a client that connects to a known node in the Raft cluster
// to issue commands. It can be used by a CLI, web app, or other application to
// interface with Raft.
type Client struct {
ID uint64 // Client ID, determined by the Raft node
Leader *RemoteNode // Raft node we're connected to (also last known leader)
SequenceNum uint64 // Sequence number of the latest request sent by the client
}
// MaxRetries is the maximum times the Client will retry a request after
// receiving a REQ_FAILED reply from the Raft cluster
const MaxRetries = 3
// Connect creates a new Client and registers with the Raft node at the given address.
func Connect(addr string) (cp *Client, err error) <span class="cov0" title="0">{
cp = new(Client)
// Note: we don't yet know the ID of the remoteNode, so just set it to an
// empty string.
remoteNode := &RemoteNode{Id: "", Addr: addr}
var reply *ClientReply
retries := 0
LOOP:
for retries < MaxRetries </span><span class="cov0" title="0">{
reply, err = remoteNode.RegisterClientRPC()
if err != nil </span><span class="cov0" title="0">{
return
}</span>
<span class="cov0" title="0">switch reply.Status </span>{
case ClientStatus_OK:<span class="cov0" title="0">
fmt.Printf("%v is the leader. Client successfully created.\n", remoteNode)
break LOOP</span>
case ClientStatus_REQ_FAILED:<span class="cov0" title="0">
fmt.Printf("Request failed, retrying...\n")
retries++</span>
case ClientStatus_NOT_LEADER:<span class="cov0" title="0">
// The person we've contacted isn't the leader. Use their hint to find
// the leader.
fmt.Printf("%v is not the leader, but thinks that %v is\n", remoteNode, reply.LeaderHint)
remoteNode = reply.LeaderHint</span>
case ClientStatus_ELECTION_IN_PROGRESS:<span class="cov0" title="0">
// An election is in progress. Accept the hint and wait an appropriate
// amount of time, so the election can finish.
fmt.Printf("%v is not the leader, but thinks that %v is\n", remoteNode, reply.LeaderHint)
remoteNode = reply.LeaderHint
time.Sleep(time.Millisecond * 200)</span>
case ClientStatus_CLUSTER_NOT_STARTED:<span class="cov0" title="0">
return nil, errors.New("cluster hasn't started")</span>
default:<span class="cov0" title="0"></span>
}
}
// We've registered with the leader!
<span class="cov0" title="0">cp.ID = reply.ClientId
cp.Leader = remoteNode
return</span>
}
// SendRequest sends a command the associated data to the last known leader of
// the Raft cluster, and handles responses.
func (c *Client) SendRequest(command uint64, data []byte) ([]byte, error) <span class="cov0" title="0">{
request := ClientRequest{
ClientId: c.ID,
SequenceNum: c.SequenceNum,
StateMachineCmd: command,
Data: data,
}
c.SequenceNum++
var reply *ClientReply
var err error
retries := 0
LOOP:
for retries < MaxRetries </span><span class="cov0" title="0">{
reply, err = c.Leader.ClientRequestRPC(&request)
if err != nil </span><span class="cov0" title="0">{
return nil, err
}</span>
<span class="cov0" title="0">switch reply.Status </span>{
case ClientStatus_OK:<span class="cov0" title="0">
fmt.Printf("%v is the leader\n", c.Leader)
fmt.Printf("Request returned \"%v\"\n", reply.Response)
break LOOP</span>
case ClientStatus_REQ_FAILED:<span class="cov0" title="0">
fmt.Printf("Request failed: %v\n", reply.Response)
fmt.Println("Retrying...")
retries++</span>
case ClientStatus_NOT_LEADER:<span class="cov0" title="0">
// The person we've contacted isn't the leader. Use their hint to find
// the leader.
c.Leader = reply.LeaderHint</span>
case ClientStatus_ELECTION_IN_PROGRESS:<span class="cov0" title="0">
// An election is in progress. Accept the hint and wait an appropriate
// amount of time, so the election can finish.
c.Leader = reply.LeaderHint
time.Sleep(time.Millisecond * 200)</span>
case ClientStatus_CLUSTER_NOT_STARTED:<span class="cov0" title="0">
return nil, errors.New("cluster hasn't started")</span>
}
}
<span class="cov0" title="0">return reply.GetResponse(), nil</span>
}
</pre>
<pre class="file" id="file2" style="display: none">package pkg
import (
"fmt"
"math/rand"
"path/filepath"
"raft/pkg/hashmachine"
)
// CreateLocalCluster creates a new Raft cluster with the given config in the
// current process.
func CreateLocalCluster(config Config) (nodes []*Node, err error) <span class="cov8" title="1">{
if err = CheckConfig(config); err != nil </span><span class="cov0" title="0">{
return
}</span>
<span class="cov8" title="1">nodes = make([]*Node, config.ClusterSize)
var stableStore StableStore
if config.InMemory </span><span class="cov8" title="1">{
stableStore = NewMemoryStore()
}</span> else<span class="cov0" title="0"> {
stableStore = NewBoltStore(filepath.Join(config.LogPath, fmt.Sprintf("raft%d", rand.Int())))
}</span>
<span class="cov8" title="1">nodes[0], err = CreateNode(OpenPort(0), config, new(hashmachine.HashMachine), stableStore)
if err != nil </span><span class="cov0" title="0">{
Error.Printf("Error creating first node: %v", err)
return
}</span>
<span class="cov8" title="1">if err = nodes[0].Connect(nil); err != nil </span><span class="cov0" title="0">{
Error.Printf("Error starting first node: %v", err)
return
}</span>
<span class="cov8" title="1">errChan := make(chan error)
for i := 1; i < config.ClusterSize; i++ </span><span class="cov8" title="1">{
var stableStore StableStore
if config.InMemory </span><span class="cov8" title="1">{
stableStore = NewMemoryStore()
}</span> else<span class="cov0" title="0"> {
stableStore = NewBoltStore(filepath.Join(config.LogPath, fmt.Sprintf("raft%d", rand.Int())))
}</span>
<span class="cov8" title="1">nodes[i], err = CreateNode(OpenPort(0), config, new(hashmachine.HashMachine), stableStore)
if err != nil </span><span class="cov0" title="0">{
return
}</span>
<span class="cov8" title="1">go func(node *Node) </span><span class="cov8" title="1">{
errChan <- node.Connect(nodes[0].Self)
}</span>(nodes[i])
}
<span class="cov8" title="1">for i := 1; i < config.ClusterSize; i++ </span><span class="cov8" title="1">{
if err = <-errChan; err != nil </span><span class="cov0" title="0">{
return
}</span>
}
<span class="cov8" title="1">close(errChan)
return nodes, nil</span>
}
// CreateDefinedLocalCluster creates a new Raft cluster with nodes listening at
// the given ports in the current process.
func CreateDefinedLocalCluster(config Config, ports []int) (nodes []*Node, err error) <span class="cov8" title="1">{
if err = CheckConfig(config); err != nil </span><span class="cov0" title="0">{
return
}</span>
<span class="cov8" title="1">nodes = make([]*Node, config.ClusterSize)
var stableStore StableStore
if config.InMemory </span><span class="cov8" title="1">{
stableStore = NewMemoryStore()
}</span> else<span class="cov0" title="0"> {
stableStore = NewBoltStore(filepath.Join(config.LogPath, fmt.Sprintf("raft%d", ports[0])))
}</span>
<span class="cov8" title="1">nodes[0], err = CreateNode(OpenPort(ports[0]), config, new(hashmachine.HashMachine), stableStore)
if err != nil </span><span class="cov0" title="0">{
Error.Printf("Error creating first node: %v", err)
return
}</span>
<span class="cov8" title="1">if err = nodes[0].Connect(nil); err != nil </span><span class="cov0" title="0">{
Error.Printf("Error starting first node: %v", err)
return
}</span>
<span class="cov8" title="1">errChan := make(chan error)
for i := 1; i < config.ClusterSize; i++ </span><span class="cov8" title="1">{
var stableStore StableStore
if config.InMemory </span><span class="cov8" title="1">{
stableStore = NewMemoryStore()
}</span> else<span class="cov0" title="0"> {
stableStore = NewBoltStore(filepath.Join(config.LogPath, fmt.Sprintf("raft%d", ports[i])))
}</span>
<span class="cov8" title="1">nodes[i], err = CreateNode(OpenPort(ports[i]), config, new(hashmachine.HashMachine), stableStore)
if err != nil </span><span class="cov0" title="0">{
Error.Printf("Error creating %v-th node: %v", i, err)
return
}</span>
<span class="cov8" title="1">go func(node *Node) </span><span class="cov8" title="1">{
errChan <- node.Connect(nodes[0].Self)
}</span>(nodes[i])
}
<span class="cov8" title="1">for i := 1; i < config.ClusterSize; i++ </span><span class="cov8" title="1">{
if err = <-errChan; err != nil </span><span class="cov0" title="0">{
return
}</span>
}
<span class="cov8" title="1">close(errChan)
return</span>
}
</pre>
<pre class="file" id="file3" style="display: none">package pkg
import (
"fmt"
"os"
"time"
)
// Config defines the various settings for a Raft cluster.
type Config struct {
ElectionTimeout time.Duration
HeartbeatTimeout time.Duration
ClusterSize int
NodeIDSize int
LogPath string
InMemory bool
}
// DefaultConfig returns the default config for a Raft cluster. By default
// config uses in-memory storage
func DefaultConfig() Config <span class="cov8" title="1">{
return Config{
ClusterSize: 3,
ElectionTimeout: time.Millisecond * 150,
HeartbeatTimeout: time.Millisecond * 50,
NodeIDSize: 2,
LogPath: os.TempDir(),
InMemory: true,
}
}</span>
// CheckConfig checks if a provided Raft config is valid.
func CheckConfig(config Config) error <span class="cov8" title="1">{
if config.HeartbeatTimeout < 5*time.Millisecond </span><span class="cov0" title="0">{
return fmt.Errorf("Heartbeat timeout is too low")
}</span>
<span class="cov8" title="1">if config.ElectionTimeout < 5*time.Millisecond </span><span class="cov0" title="0">{
return fmt.Errorf("Election timeout is too low")
}</span>
<span class="cov8" title="1">if config.ElectionTimeout < config.HeartbeatTimeout </span><span class="cov0" title="0">{
return fmt.Errorf("The election timeout (%v) is less than the heartbeat timeout (%v)", config.ElectionTimeout, config.HeartbeatTimeout)
}</span>
<span class="cov8" title="1">if config.ClusterSize <= 0 </span><span class="cov0" title="0">{
return fmt.Errorf("The cluster size must be positive")
}</span>
<span class="cov8" title="1">if config.NodeIDSize <= 0 </span><span class="cov0" title="0">{
return fmt.Errorf("The node id size must be positive")
}</span>
<span class="cov8" title="1">return nil</span>
}
</pre>
<pre class="file" id="file4" style="display: none">package pkg
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"os"
"github.com/fatih/color"
"google.golang.org/grpc/grpclog"
)
// Debug is medium-risk logger
var Debug *log.Logger
// Out is low-risk logger
var Out *log.Logger
// Error is high-risk logger
var Error *log.Logger
// Initialize the loggers
func init() <span class="cov8" title="1">{
Debug = log.New(ioutil.Discard, "", log.Ltime|log.Lshortfile)
Out = log.New(os.Stdout, "", log.Ltime|log.Lshortfile)
Error = log.New(os.Stderr, "ERROR: ", log.Ltime|log.Lshortfile)
grpclog.SetLogger(log.New(ioutil.Discard, "", 0))
}</span>
// SetDebug turns printing debug strings on or off
func SetDebug(enabled bool) <span class="cov8" title="1">{
if enabled </span><span class="cov0" title="0">{
Debug.SetOutput(os.Stdout)
}</span> else<span class="cov8" title="1"> {
Debug.SetOutput(ioutil.Discard)
}</span>
}
// Out prints to standard output, prefaced with time and filename
func (n *Node) Out(formatString string, args ...interface{}) <span class="cov8" title="1">{
Out.Output(2, fmt.Sprintf("(%v/%v) %v\n", n.Self, n.GetState(), fmt.Sprintf(formatString, args...)))
}</span>
// Debug prints to standard output if SetDebug was called with enabled=true, prefaced with time and filename
func (n *Node) Debug(formatString string, args ...interface{}) <span class="cov8" title="1">{
Debug.Output(2, fmt.Sprintf("(%v/%v) %v\n", n.Self, n.GetState(), fmt.Sprintf(formatString, args...)))
}</span>
// Error prints to standard error, prefaced with "ERROR: ", time, and filename
func (n *Node) Error(formatString string, args ...interface{}) <span class="cov0" title="0">{
color.Set(color.FgRed)
Error.Output(2, fmt.Sprintf("(%v/%v) %v\n", n.Self, n.GetState(), fmt.Sprintf(formatString, args...)))
color.Unset()
}</span>
func (s NodeState) String() string <span class="cov8" title="1">{
switch s </span>{
case FollowerState:<span class="cov8" title="1">
return "follower"</span>
case CandidateState:<span class="cov8" title="1">
return "candidate"</span>
case LeaderState:<span class="cov8" title="1">
return "leader"</span>
case JoinState:<span class="cov8" title="1">
return "joining"</span>
default:<span class="cov8" title="1">
return "unknown"</span>
}
}
func (n *Node) String() string <span class="cov0" title="0">{
return fmt.Sprintf("Node{Self: %v, State: %v}", n.Self, n.GetState())
}</span>
// FormatState returns a string representation of the Raft node's state
func (n *Node) FormatState() string <span class="cov0" title="0">{
var buffer bytes.Buffer
buffer.WriteString(fmt.Sprintf("Current node (%v): state:\n", n.Self))
for i, node := range n.Peers </span><span class="cov0" title="0">{
buffer.WriteString(fmt.Sprintf("%v - %v", i, node))
local := n.Self
if local.Addr == node.Addr </span><span class="cov0" title="0">{
buffer.WriteString(" (local node)")
}</span>
<span class="cov0" title="0">if leader := n.getLeader(); leader != nil && leader.Addr == node.Addr </span><span class="cov0" title="0">{
buffer.WriteString(" (leader node)")
}</span>
<span class="cov0" title="0">buffer.WriteString("\n")</span>
}
<span class="cov0" title="0">buffer.WriteString(fmt.Sprintf("Current term: %v\n", n.GetCurrentTerm()))
buffer.WriteString(fmt.Sprintf("Current state: %v\n", n.GetState()))
buffer.WriteString(fmt.Sprintf("Current commit index: %v\n", n.CommitIndex.Load()))
buffer.WriteString(fmt.Sprintf("Current next index: %v\n", n.nextIndex))
buffer.WriteString(fmt.Sprintf("Current match index: %v\n", n.matchIndex))
return buffer.String()</span>
}
// FormatLogCache returns a string representation of the Raft node's log cache
func (n *Node) FormatLogCache() string <span class="cov0" title="0">{
var buffer bytes.Buffer
buffer.WriteString(fmt.Sprintf("Node %v LogCache:\n", n.Self))
for i := uint64(0); i <= n.LastLogIndex(); i++ </span><span class="cov0" title="0">{
log := n.GetLog(i)
if log != nil </span><span class="cov0" title="0">{
buffer.WriteString(fmt.Sprintf(" idx:%v, term:%v\n", log.Index, log.TermId))
}</span>
}
<span class="cov0" title="0">return buffer.String()</span>
}
// FormatNodeListIds returns a string representation of IDs the list of nodes in the cluster
func (n *Node) FormatNodeListIds(ctx string) string <span class="cov0" title="0">{
var buffer bytes.Buffer
buffer.WriteString(fmt.Sprintf("%v (%v) r.NodeList = [", ctx, n.Self))
nodeList := n.Peers
for i, node := range nodeList </span><span class="cov0" title="0">{
buffer.WriteString(fmt.Sprintf("%v", node.Id))
if i < len(nodeList)-1 </span><span class="cov0" title="0">{
buffer.WriteString(",")
}</span>
}
<span class="cov0" title="0">buffer.WriteString("]\n")
return buffer.String()</span>
}
</pre>
<pre class="file" id="file5" style="display: none">package pkg
import (
"go.uber.org/atomic"
"sort"
"sync"
)
// MemoryStore implements the StableStore interface and serves as a storage option for raft
type MemoryStore struct {
state map[string][]byte
stateMu sync.RWMutex
logs map[uint64]*LogEntry
logsMu sync.RWMutex
lastLogIndex *atomic.Uint64
}
// NewMemoryStore creates a new in-memory store
func NewMemoryStore() *MemoryStore <span class="cov8" title="1">{
return &MemoryStore{
state: make(map[string][]byte),
logs: make(map[uint64]*LogEntry),
//snapshot: nil,
lastLogIndex: atomic.NewUint64(0),
}
}</span>
// SetBytes sets a key-value pair
func (store *MemoryStore) SetBytes(key, value []byte) error <span class="cov8" title="1">{
keyStr := string(key)
store.stateMu.Lock()
defer store.stateMu.Unlock()
store.state[keyStr] = value
return nil
}</span>
// GetBytes retrives a value for the specified key
func (store *MemoryStore) GetBytes(key []byte) []byte <span class="cov8" title="1">{
keyStr := string(key)
store.stateMu.RLock()
defer store.stateMu.RUnlock()
return store.state[keyStr]
}</span>
// SetUint64 sets a key-value pair
func (store *MemoryStore) SetUint64(key []byte, value uint64) error <span class="cov8" title="1">{
keyStr := string(key)
store.stateMu.Lock()
defer store.stateMu.Unlock()
store.state[keyStr] = uint64ToBytes(value)
return nil
}</span>
// GetUint64 retrieves a uint64 from Bolt
func (store *MemoryStore) GetUint64(key []byte) uint64 <span class="cov8" title="1">{
keyStr := string(key)
store.stateMu.RLock()
defer store.stateMu.RUnlock()
if v, ok := store.state[keyStr]; ok </span><span class="cov8" title="1">{
return bytesToUint64(v)
}</span>
<span class="cov8" title="1">return 0</span>
}
// StoreLog grabs the next log index and stores a LogEntry into Bolt
func (store *MemoryStore) StoreLog(log *LogEntry) error <span class="cov8" title="1">{
store.logsMu.Lock()
defer store.logsMu.Unlock()
index := log.GetIndex()
store.logs[index] = log
if index > store.lastLogIndex.Load() </span><span class="cov8" title="1">{
store.lastLogIndex.Store(index)
}</span>
<span class="cov8" title="1">return nil</span>
}
// GetLog retrieves a LogEntry at a specific log index from Bolt
func (store *MemoryStore) GetLog(index uint64) *LogEntry <span class="cov8" title="1">{
store.logsMu.RLock()
defer store.logsMu.RUnlock()
if log := store.logs[index]; log != nil </span><span class="cov8" title="1">{
return log
}</span>
/*store.snapshotsMu.RLock()
defer store.snapshotsMu.RUnlock()
if store.snapshot != nil && store.snapshot.Index == index {
return &LogEntry{
Index: store.snapshot.Index,
TermId: store.snapshot.Term,
}
}*/
<span class="cov0" title="0">return nil</span>
}
// LastLogIndex gets the last index inserted into Bolt
func (store *MemoryStore) LastLogIndex() uint64 <span class="cov8" title="1">{
return store.lastLogIndex.Load()
}</span>
// TruncateLog deletes all logs starting from index
func (store *MemoryStore) TruncateLog(index uint64) error <span class="cov8" title="1">{
store.logsMu.Lock()
defer store.logsMu.Unlock()
for key := range store.logs </span><span class="cov8" title="1">{
if key >= index </span><span class="cov8" title="1">{
delete(store.logs, key)
}</span>
}
<span class="cov8" title="1">if index <= store.lastLogIndex.Load() </span><span class="cov8" title="1">{
store.lastLogIndex.Store(index - 1)
}</span>
<span class="cov8" title="1">return nil</span>
}
// AllLogs returns all logs in ascending order. Used for testing purposes.
func (store *MemoryStore) AllLogs() []*LogEntry <span class="cov0" title="0">{
store.logsMu.Lock()
defer store.logsMu.Unlock()
var res []*LogEntry
for _, log := range store.logs </span><span class="cov0" title="0">{
res = append(res, log)
}</span>
<span class="cov0" title="0">sort.Slice(res, func(i, j int) bool </span><span class="cov0" title="0">{
return res[i].GetIndex() < res[j].GetIndex()
}</span>)
<span class="cov0" title="0">return res</span>
}
// Close closes the db.
func (store *MemoryStore) Close() {<span class="cov8" title="1">
// Noop
}</span>
// Remove deletes the db folder
func (store *MemoryStore) Remove() {<span class="cov8" title="1">
// Noop
}</span>
// Path returns the db path
func (store *MemoryStore) Path() string <span class="cov0" title="0">{
return ""
}</span>
</pre>
<pre class="file" id="file6" style="display: none">package pkg
import (
"errors"
"fmt"
"sync"
)
// NetworkPolicy provides a way to explicitly disallow communication from a node
// to other nodes in the cluster. Each Node has its own network policy that
// can block rpc calls to specific nodes, and/or block communication to all
// other nodes. We encourage you to use this particularly in your test cases.
type NetworkPolicy struct {
pauseWorld bool
rpcPolicy map[string]bool
mutex sync.Mutex
}
// NewNetworkPolicy creates a new network policy and initializes the rpcPolicy map
func NewNetworkPolicy() *NetworkPolicy <span class="cov8" title="1">{
return &NetworkPolicy{
pauseWorld: false,
rpcPolicy: make(map[string]bool, 0),
}
}</span>
// ErrorNetworkPolicyDenied is returned when a request is barred due to the node
var ErrorNetworkPolicyDenied = errors.New("the network policy has forbid this communication")
func getCommID(a, b *RemoteNode) string <span class="cov8" title="1">{
return fmt.Sprintf("%v_%v", a.Id, b.Id)
}</span>
// IsDenied checks our network policy to see if we are allowed to send or
// receive messages with the given remote node.
func (tp *NetworkPolicy) IsDenied(a, b *RemoteNode) bool <span class="cov8" title="1">{
tp.mutex.Lock()
defer tp.mutex.Unlock()
if tp.pauseWorld </span><span class="cov8" title="1">{
return true
}</span>
<span class="cov8" title="1">commStr := getCommID(a, b)
allowed, exists := tp.rpcPolicy[commStr]
return exists && !allowed</span>
}
// RegisterPolicy registers whether or not communication is allowed from a to b.
func (tp *NetworkPolicy) RegisterPolicy(a, b *RemoteNode, allowed bool) <span class="cov8" title="1">{
commStr := getCommID(a, b)
tp.mutex.Lock()
defer tp.mutex.Unlock()
tp.rpcPolicy[commStr] = allowed
}</span>
// PauseWorld temporarily enables / disables all network communication from the current node.
func (tp *NetworkPolicy) PauseWorld(on bool) <span class="cov8" title="1">{
tp.mutex.Lock()
defer tp.mutex.Unlock()
tp.pauseWorld = on
}</span>
</pre>
<pre class="file" id="file7" style="display: none">package pkg
import (
"context"
"errors"
"fmt"
"net"
"os"
"strconv"
"sync"
"go.uber.org/atomic"
"google.golang.org/grpc"
)
// NodeState represents one of five possible states a Raft node can be in.
type NodeState int32
// Enum for potential node states
const (
FollowerState NodeState = iota
CandidateState
LeaderState
JoinState
ExitState
)
// Node defines an individual Raft node.
type Node struct {
UnimplementedRaftRPCServer
// Immutable state on all servers
Self *RemoteNode
Port int
nodeCond *sync.Cond
// gRPC related fields
ctx context.Context
cancel context.CancelFunc
Server *grpc.Server
NetworkPolicy *NetworkPolicy
// Stable store (written to disk, use helper methods)
StableStore StableStore
// Replicated state machine (e.g. hash machine, kv-store etc.)
StateMachine StateMachine
// volatile state on all servers
Leader *RemoteNode
NodeMutex sync.Mutex
lastHeardFromLeader *atomic.Int64