/
register.pb.go
1745 lines (1552 loc) · 40.4 KB
/
register.pb.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
// Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: register.proto
/*
Package rwregister is a generated protocol buffer package.
It is generated from these files:
register.proto
It has these top-level messages:
Content
Value
WriteResponse
ReadRequest
*/
package rwregister
import proto "github.com/gogo/protobuf/proto"
import fmt "fmt"
import math "math"
import _ "github.com/relab/gorums"
import bytes "bytes"
import binary "encoding/binary"
import trace "golang.org/x/net/trace"
import grpc "google.golang.org/grpc"
import codes "google.golang.org/grpc/codes"
import status "google.golang.org/grpc/status"
import fnv "hash/fnv"
import io "io"
import log "log"
import net "net"
import sort "sort"
import strings "strings"
import sync "sync"
import time "time"
import context "golang.org/x/net/context"
import reflect "reflect"
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package
type Content struct {
Value string `protobuf:"bytes,1,opt,name=value,proto3" json:"value,omitempty"`
Timestamp int64 `protobuf:"varint,2,opt,name=timestamp,proto3" json:"timestamp,omitempty"`
}
func (m *Content) Reset() { *m = Content{} }
func (*Content) ProtoMessage() {}
func (*Content) Descriptor() ([]byte, []int) { return fileDescriptorRegister, []int{0} }
func (m *Content) GetValue() string {
if m != nil {
return m.Value
}
return ""
}
func (m *Content) GetTimestamp() int64 {
if m != nil {
return m.Timestamp
}
return 0
}
type Value struct {
C *Content `protobuf:"bytes,1,opt,name=c" json:"c,omitempty"`
}
func (m *Value) Reset() { *m = Value{} }
func (*Value) ProtoMessage() {}
func (*Value) Descriptor() ([]byte, []int) { return fileDescriptorRegister, []int{1} }
func (m *Value) GetC() *Content {
if m != nil {
return m.C
}
return nil
}
// [Ack]
type WriteResponse struct {
Ack bool `protobuf:"varint,1,opt,name=ack,proto3" json:"ack,omitempty"`
}
func (m *WriteResponse) Reset() { *m = WriteResponse{} }
func (*WriteResponse) ProtoMessage() {}
func (*WriteResponse) Descriptor() ([]byte, []int) { return fileDescriptorRegister, []int{2} }
func (m *WriteResponse) GetAck() bool {
if m != nil {
return m.Ack
}
return false
}
type ReadRequest struct {
}
func (m *ReadRequest) Reset() { *m = ReadRequest{} }
func (*ReadRequest) ProtoMessage() {}
func (*ReadRequest) Descriptor() ([]byte, []int) { return fileDescriptorRegister, []int{3} }
func init() {
proto.RegisterType((*Content)(nil), "rwregister.Content")
proto.RegisterType((*Value)(nil), "rwregister.Value")
proto.RegisterType((*WriteResponse)(nil), "rwregister.WriteResponse")
proto.RegisterType((*ReadRequest)(nil), "rwregister.ReadRequest")
}
// Reference Gorums specific imports to suppress errors if they are not otherwise used.
var _ = codes.OK
var _ = bytes.MinRead
/* Code generated by protoc-gen-gorums - template source file: calltype_datatypes.tmpl */
type internalValue struct {
nid uint32
reply *Value
err error
}
type internalWriteResponse struct {
nid uint32
reply *WriteResponse
err error
}
/* Code generated by protoc-gen-gorums - template source file: calltype_quorumcall.tmpl */
/* Exported types and methods for quorum call method Read */
// Read is invoked as a quorum call on all nodes in configuration c,
// using the same argument arg, and returns the result.
func (c *Configuration) Read(ctx context.Context, arg *ReadRequest) (*Value, error) {
return c.read(ctx, arg)
}
/* Unexported quorum call method Read */
func (c *Configuration) read(ctx context.Context, a *ReadRequest) (resp *Value, err error) {
var ti traceInfo
if c.mgr.opts.trace {
ti.Trace = trace.New("gorums."+c.tstring()+".Sent", "Read")
defer ti.Finish()
ti.firstLine.cid = c.id
if deadline, ok := ctx.Deadline(); ok {
ti.firstLine.deadline = deadline.Sub(time.Now())
}
ti.LazyLog(&ti.firstLine, false)
ti.LazyLog(&payload{sent: true, msg: a}, false)
defer func() {
ti.LazyLog(&qcresult{
reply: resp,
err: err,
}, false)
if err != nil {
ti.SetError()
}
}()
}
expected := c.n
replyChan := make(chan internalValue, expected)
for _, n := range c.nodes {
go callGRPCRead(ctx, n, a, replyChan)
}
var (
replyValues = make([]*Value, 0, expected)
errCount int
quorum bool
)
for {
select {
case r := <-replyChan:
if r.err != nil {
errCount++
break
}
if c.mgr.opts.trace {
ti.LazyLog(&payload{sent: false, id: r.nid, msg: r.reply}, false)
}
replyValues = append(replyValues, r.reply)
if resp, quorum = c.qspec.ReadQF(replyValues); quorum {
return resp, nil
}
case <-ctx.Done():
return resp, QuorumCallError{ctx.Err().Error(), errCount, len(replyValues)}
}
if errCount+len(replyValues) == expected {
return resp, QuorumCallError{"incomplete call", errCount, len(replyValues)}
}
}
}
func callGRPCRead(ctx context.Context, node *Node, arg *ReadRequest, replyChan chan<- internalValue) {
reply := new(Value)
start := time.Now()
err := grpc.Invoke(
ctx,
"/rwregister.Register/Read",
arg,
reply,
node.conn,
)
s, ok := status.FromError(err)
if ok && (s.Code() == codes.OK || s.Code() == codes.Canceled) {
node.setLatency(time.Since(start))
} else {
node.setLastErr(err)
}
replyChan <- internalValue{node.id, reply, err}
}
/* Exported types and methods for quorum call method Write */
// Write is invoked as a quorum call on all nodes in configuration c,
// using the same argument arg, and returns the result.
func (c *Configuration) Write(ctx context.Context, arg *Value) (*WriteResponse, error) {
return c.write(ctx, arg)
}
/* Unexported quorum call method Write */
func (c *Configuration) write(ctx context.Context, a *Value) (resp *WriteResponse, err error) {
var ti traceInfo
if c.mgr.opts.trace {
ti.Trace = trace.New("gorums."+c.tstring()+".Sent", "Write")
defer ti.Finish()
ti.firstLine.cid = c.id
if deadline, ok := ctx.Deadline(); ok {
ti.firstLine.deadline = deadline.Sub(time.Now())
}
ti.LazyLog(&ti.firstLine, false)
ti.LazyLog(&payload{sent: true, msg: a}, false)
defer func() {
ti.LazyLog(&qcresult{
reply: resp,
err: err,
}, false)
if err != nil {
ti.SetError()
}
}()
}
expected := c.n
replyChan := make(chan internalWriteResponse, expected)
for _, n := range c.nodes {
go callGRPCWrite(ctx, n, a, replyChan)
}
var (
replyValues = make([]*WriteResponse, 0, expected)
errCount int
quorum bool
)
for {
select {
case r := <-replyChan:
if r.err != nil {
errCount++
break
}
if c.mgr.opts.trace {
ti.LazyLog(&payload{sent: false, id: r.nid, msg: r.reply}, false)
}
replyValues = append(replyValues, r.reply)
if resp, quorum = c.qspec.WriteQF(replyValues); quorum {
return resp, nil
}
case <-ctx.Done():
return resp, QuorumCallError{ctx.Err().Error(), errCount, len(replyValues)}
}
if errCount+len(replyValues) == expected {
return resp, QuorumCallError{"incomplete call", errCount, len(replyValues)}
}
}
}
func callGRPCWrite(ctx context.Context, node *Node, arg *Value, replyChan chan<- internalWriteResponse) {
reply := new(WriteResponse)
start := time.Now()
err := grpc.Invoke(
ctx,
"/rwregister.Register/Write",
arg,
reply,
node.conn,
)
s, ok := status.FromError(err)
if ok && (s.Code() == codes.OK || s.Code() == codes.Canceled) {
node.setLatency(time.Since(start))
} else {
node.setLastErr(err)
}
replyChan <- internalWriteResponse{node.id, reply, err}
}
/* Code generated by protoc-gen-gorums - template source file: node.tmpl */
// Node encapsulates the state of a node on which a remote procedure call
// can be made.
type Node struct {
// Only assigned at creation.
id uint32
addr string
conn *grpc.ClientConn
logger *log.Logger
RegisterClient RegisterClient
mu sync.Mutex
lastErr error
latency time.Duration
}
func (n *Node) connect(opts ...grpc.DialOption) error {
var err error
n.conn, err = grpc.Dial(n.addr, opts...)
if err != nil {
return fmt.Errorf("dialing node failed: %v", err)
}
n.RegisterClient = NewRegisterClient(n.conn)
return nil
}
func (n *Node) close() error {
if err := n.conn.Close(); err != nil {
if n.logger != nil {
n.logger.Printf("%d: conn close error: %v", n.id, err)
}
return fmt.Errorf("%d: conn close error: %v", n.id, err)
}
return nil
}
/* Code generated by protoc-gen-gorums - template source file: qspec.tmpl */
// QuorumSpec is the interface that wraps every quorum function.
type QuorumSpec interface {
// ReadQF is the quorum function for the Read
// quorum call method.
ReadQF(replies []*Value) (*Value, bool)
// WriteQF is the quorum function for the Write
// quorum call method.
WriteQF(replies []*WriteResponse) (*WriteResponse, bool)
}
/* Static resources */
/* config.go */
// A Configuration represents a static set of nodes on which quorum remote
// procedure calls may be invoked.
type Configuration struct {
id uint32
nodes []*Node
n int
mgr *Manager
qspec QuorumSpec
}
// ID reports the identifier for the configuration.
func (c *Configuration) ID() uint32 {
return c.id
}
// NodeIDs returns a slice containing the local ids of all the nodes in the
// configuration. IDs are returned in the same order as they were provided in
// the creation of the Configuration.
func (c *Configuration) NodeIDs() []uint32 {
ids := make([]uint32, len(c.nodes))
for i, node := range c.nodes {
ids[i] = node.ID()
}
return ids
}
// Nodes returns a slice of each available node. IDs are returned in the same
// order as they were provided in the creation of the Configuration.
func (c *Configuration) Nodes() []*Node {
return c.nodes
}
// Size returns the number of nodes in the configuration.
func (c *Configuration) Size() int {
return c.n
}
func (c *Configuration) String() string {
return fmt.Sprintf("configuration %d", c.id)
}
func (c *Configuration) tstring() string {
return fmt.Sprintf("config-%d", c.id)
}
// Equal returns a boolean reporting whether a and b represents the same
// configuration.
func Equal(a, b *Configuration) bool { return a.id == b.id }
/* errors.go */
// A NodeNotFoundError reports that a specified node could not be found.
type NodeNotFoundError uint32
func (e NodeNotFoundError) Error() string {
return fmt.Sprintf("node not found: %d", e)
}
// A ConfigNotFoundError reports that a specified configuration could not be
// found.
type ConfigNotFoundError uint32
func (e ConfigNotFoundError) Error() string {
return fmt.Sprintf("configuration not found: %d", e)
}
// An IllegalConfigError reports that a specified configuration could not be
// created.
type IllegalConfigError string
func (e IllegalConfigError) Error() string {
return "illegal configuration: " + string(e)
}
// ManagerCreationError returns an error reporting that a Manager could not be
// created due to err.
func ManagerCreationError(err error) error {
return fmt.Errorf("could not create manager: %s", err.Error())
}
// A QuorumCallError is used to report that a quorum call failed.
type QuorumCallError struct {
Reason string
ErrCount, ReplyCount int
}
func (e QuorumCallError) Error() string {
return fmt.Sprintf(
"quorum call error: %s (errors: %d, replies: %d)",
e.Reason, e.ErrCount, e.ReplyCount,
)
}
/* level.go */
// LevelNotSet is the zero value level used to indicate that no level (and
// thereby no reply) has been set for a correctable quorum call.
const LevelNotSet = -1
/* mgr.go */
// Manager manages a pool of node configurations on which quorum remote
// procedure calls can be made.
type Manager struct {
mu sync.Mutex
nodes []*Node
lookup map[uint32]*Node
configs map[uint32]*Configuration
eventLog trace.EventLog
closeOnce sync.Once
logger *log.Logger
opts managerOptions
}
// NewManager attempts to connect to the given set of node addresses and if
// successful returns a new Manager containing connections to those nodes.
func NewManager(nodeAddrs []string, opts ...ManagerOption) (*Manager, error) {
if len(nodeAddrs) == 0 {
return nil, fmt.Errorf("could not create manager: no nodes provided")
}
m := &Manager{
lookup: make(map[uint32]*Node),
configs: make(map[uint32]*Configuration),
}
for _, opt := range opts {
opt(&m.opts)
}
for _, naddr := range nodeAddrs {
node, err2 := m.createNode(naddr)
if err2 != nil {
return nil, ManagerCreationError(err2)
}
m.lookup[node.id] = node
m.nodes = append(m.nodes, node)
}
if m.opts.trace {
title := strings.Join(nodeAddrs, ",")
m.eventLog = trace.NewEventLog("gorums.Manager", title)
}
err := m.connectAll()
if err != nil {
return nil, ManagerCreationError(err)
}
if m.opts.logger != nil {
m.logger = m.opts.logger
}
if m.eventLog != nil {
m.eventLog.Printf("ready")
}
return m, nil
}
func (m *Manager) createNode(addr string) (*Node, error) {
m.mu.Lock()
defer m.mu.Unlock()
tcpAddr, err := net.ResolveTCPAddr("tcp", addr)
if err != nil {
return nil, fmt.Errorf("create node %s error: %v", addr, err)
}
h := fnv.New32a()
_, _ = h.Write([]byte(tcpAddr.String()))
id := h.Sum32()
if _, found := m.lookup[id]; found {
return nil, fmt.Errorf("create node %s error: node already exists", addr)
}
node := &Node{
id: id,
addr: tcpAddr.String(),
latency: -1 * time.Second,
logger: m.logger,
}
return node, nil
}
func (m *Manager) connectAll() error {
if m.opts.noConnect {
return nil
}
if m.eventLog != nil {
m.eventLog.Printf("connecting")
}
for _, node := range m.nodes {
err := node.connect(m.opts.grpcDialOpts...)
if err != nil {
if m.eventLog != nil {
m.eventLog.Errorf("connect failed, error connecting to node %s, error: %v", node.addr, err)
}
return fmt.Errorf("connect node %s error: %v", node.addr, err)
}
}
return nil
}
func (m *Manager) closeNodeConns() {
for _, node := range m.nodes {
err := node.close()
if err == nil {
continue
}
if m.logger != nil {
m.logger.Printf("node %d: error closing: %v", node.id, err)
}
}
}
// Close closes all node connections and any client streams.
func (m *Manager) Close() {
m.closeOnce.Do(func() {
if m.eventLog != nil {
m.eventLog.Printf("closing")
}
m.closeNodeConns()
})
}
// NodeIDs returns the identifier of each available node. IDs are returned in
// the same order as they were provided in the creation of the Manager.
func (m *Manager) NodeIDs() []uint32 {
m.mu.Lock()
defer m.mu.Unlock()
ids := make([]uint32, 0, len(m.nodes))
for _, node := range m.nodes {
ids = append(ids, node.ID())
}
return ids
}
// Node returns the node with the given identifier if present.
func (m *Manager) Node(id uint32) (node *Node, found bool) {
m.mu.Lock()
defer m.mu.Unlock()
node, found = m.lookup[id]
return node, found
}
// Nodes returns a slice of each available node. IDs are returned in the same
// order as they were provided in the creation of the Manager.
func (m *Manager) Nodes() []*Node {
m.mu.Lock()
defer m.mu.Unlock()
return m.nodes
}
// ConfigurationIDs returns the identifier of each available
// configuration.
func (m *Manager) ConfigurationIDs() []uint32 {
m.mu.Lock()
defer m.mu.Unlock()
ids := make([]uint32, 0, len(m.configs))
for id := range m.configs {
ids = append(ids, id)
}
return ids
}
// Configuration returns the configuration with the given global
// identifier if present.
func (m *Manager) Configuration(id uint32) (config *Configuration, found bool) {
m.mu.Lock()
defer m.mu.Unlock()
config, found = m.configs[id]
return config, found
}
// Configurations returns a slice of each available configuration.
func (m *Manager) Configurations() []*Configuration {
m.mu.Lock()
defer m.mu.Unlock()
configs := make([]*Configuration, 0, len(m.configs))
for _, conf := range m.configs {
configs = append(configs, conf)
}
return configs
}
// Size returns the number of nodes and configurations in the Manager.
func (m *Manager) Size() (nodes, configs int) {
m.mu.Lock()
defer m.mu.Unlock()
return len(m.nodes), len(m.configs)
}
// AddNode attempts to dial to the provide node address. The node is
// added to the Manager's pool of nodes if a connection was established.
func (m *Manager) AddNode(addr string) error {
panic("not implemented")
}
// NewConfiguration returns a new configuration given quorum specification and
// a timeout.
func (m *Manager) NewConfiguration(ids []uint32, qspec QuorumSpec) (*Configuration, error) {
m.mu.Lock()
defer m.mu.Unlock()
if len(ids) == 0 {
return nil, IllegalConfigError("need at least one node")
}
var cnodes []*Node
unique := make(map[uint32]struct{})
var deduped []uint32
for _, nid := range ids {
// Ensure that identical ids are only counted once.
if _, duplicate := unique[nid]; duplicate {
continue
}
unique[nid] = struct{}{}
deduped = append(deduped, nid)
node, found := m.lookup[nid]
if !found {
return nil, NodeNotFoundError(nid)
}
cnodes = append(cnodes, node)
}
// Node ids are sorted ensure a globally consistent configuration id.
sort.Sort(idSlice(deduped))
h := fnv.New32a()
for _, id := range deduped {
binary.Write(h, binary.LittleEndian, id)
}
cid := h.Sum32()
conf, found := m.configs[cid]
if found {
return conf, nil
}
c := &Configuration{
id: cid,
nodes: cnodes,
n: len(cnodes),
mgr: m,
qspec: qspec,
}
m.configs[cid] = c
return c, nil
}
type idSlice []uint32
func (p idSlice) Len() int { return len(p) }
func (p idSlice) Less(i, j int) bool { return p[i] < p[j] }
func (p idSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
/* node_func.go */
// ID returns the ID of m.
func (n *Node) ID() uint32 {
return n.id
}
// Address returns network address of m.
func (n *Node) Address() string {
return n.addr
}
func (n *Node) String() string {
n.mu.Lock()
defer n.mu.Unlock()
return fmt.Sprintf(
"node %d | addr: %s | latency: %v",
n.id, n.addr, n.latency,
)
}
func (n *Node) setLastErr(err error) {
n.mu.Lock()
defer n.mu.Unlock()
n.lastErr = err
}
// LastErr returns the last error encountered (if any) when invoking a remote
// procedure call on this node.
func (n *Node) LastErr() error {
n.mu.Lock()
defer n.mu.Unlock()
return n.lastErr
}
func (n *Node) setLatency(lat time.Duration) {
n.mu.Lock()
defer n.mu.Unlock()
n.latency = lat
}
// Latency returns the latency of the last successful remote procedure call
// made to this node.
func (n *Node) Latency() time.Duration {
n.mu.Lock()
defer n.mu.Unlock()
return n.latency
}
type lessFunc func(n1, n2 *Node) bool
// MultiSorter implements the Sort interface, sorting the nodes within.
type MultiSorter struct {
nodes []*Node
less []lessFunc
}
// Sort sorts the argument slice according to the less functions passed to
// OrderedBy.
func (ms *MultiSorter) Sort(nodes []*Node) {
ms.nodes = nodes
sort.Sort(ms)
}
// OrderedBy returns a Sorter that sorts using the less functions, in order.
// Call its Sort method to sort the data.
func OrderedBy(less ...lessFunc) *MultiSorter {
return &MultiSorter{
less: less,
}
}
// Len is part of sort.Interface.
func (ms *MultiSorter) Len() int {
return len(ms.nodes)
}
// Swap is part of sort.Interface.
func (ms *MultiSorter) Swap(i, j int) {
ms.nodes[i], ms.nodes[j] = ms.nodes[j], ms.nodes[i]
}
// Less is part of sort.Interface. It is implemented by looping along the
// less functions until it finds a comparison that is either Less or
// !Less. Note that it can call the less functions twice per call. We
// could change the functions to return -1, 0, 1 and reduce the
// number of calls for greater efficiency: an exercise for the reader.
func (ms *MultiSorter) Less(i, j int) bool {
p, q := ms.nodes[i], ms.nodes[j]
// Try all but the last comparison.
var k int
for k = 0; k < len(ms.less)-1; k++ {
less := ms.less[k]
switch {
case less(p, q):
// p < q, so we have a decision.
return true
case less(q, p):
// p > q, so we have a decision.
return false
}
// p == q; try the next comparison.
}
// All comparisons to here said "equal", so just return whatever
// the final comparison reports.
return ms.less[k](p, q)
}
// ID sorts nodes by their identifier in increasing order.
var ID = func(n1, n2 *Node) bool {
return n1.id < n2.id
}
// Latency sorts nodes by latency in increasing order. Latencies less then
// zero (sentinel value) are considered greater than any positive latency.
var Latency = func(n1, n2 *Node) bool {
if n1.latency < 0 {
return false
}
return n1.latency < n2.latency
}
// Error sorts nodes by their LastErr() status in increasing order. A
// node with LastErr() != nil is larger than a node with LastErr() == nil.
var Error = func(n1, n2 *Node) bool {
if n1.lastErr != nil && n2.lastErr == nil {
return false
}
return true
}
/* opts.go */
type managerOptions struct {
grpcDialOpts []grpc.DialOption
logger *log.Logger
noConnect bool
trace bool
}
// ManagerOption provides a way to set different options on a new Manager.
type ManagerOption func(*managerOptions)
// WithGrpcDialOptions returns a ManagerOption which sets any gRPC dial options
// the Manager should use when initially connecting to each node in its
// pool.
func WithGrpcDialOptions(opts ...grpc.DialOption) ManagerOption {
return func(o *managerOptions) {
o.grpcDialOpts = opts
}
}
// WithLogger returns a ManagerOption which sets an optional error logger for
// the Manager.
func WithLogger(logger *log.Logger) ManagerOption {
return func(o *managerOptions) {
o.logger = logger
}
}
// WithNoConnect returns a ManagerOption which instructs the Manager not to
// connect to any of its nodes. Mainly used for testing purposes.
func WithNoConnect() ManagerOption {
return func(o *managerOptions) {
o.noConnect = true
}
}
// WithTracing controls whether to trace qourum calls for this Manager instance
// using the golang.org/x/net/trace package. Tracing is currently only supported
// for regular quorum calls.
func WithTracing() ManagerOption {
return func(o *managerOptions) {
o.trace = true
}
}
/* trace.go */
type traceInfo struct {
trace.Trace
firstLine firstLine
}
type firstLine struct {
deadline time.Duration
cid uint32
}
func (f *firstLine) String() string {
var line bytes.Buffer
io.WriteString(&line, "QC: to config")
fmt.Fprintf(&line, "%v deadline:", f.cid)
if f.deadline != 0 {
fmt.Fprint(&line, f.deadline)
} else {
io.WriteString(&line, "none")
}
return line.String()
}
type payload struct {
sent bool
id uint32
msg interface{}
}
func (p payload) String() string {
if p.sent {
return fmt.Sprintf("sent: %v", p.msg)
}
return fmt.Sprintf("recv from %d: %v", p.id, p.msg)
}
type qcresult struct {
ids []uint32
reply interface{}
err error
}
func (q qcresult) String() string {
var out bytes.Buffer
io.WriteString(&out, "recv QC reply: ")
fmt.Fprintf(&out, "ids: %v, ", q.ids)
fmt.Fprintf(&out, "reply: %v ", q.reply)
if q.err != nil {
fmt.Fprintf(&out, ", error: %v", q.err)
}
return out.String()
}
/* util.go */
func appendIfNotPresent(set []uint32, x uint32) []uint32 {
for _, y := range set {
if y == x {
return set
}
}
return append(set, x)
}
// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConn
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
const _ = grpc.SupportPackageIsVersion4
// Client API for Register service
type RegisterClient interface {
Read(ctx context.Context, in *ReadRequest, opts ...grpc.CallOption) (*Value, error)
Write(ctx context.Context, in *Value, opts ...grpc.CallOption) (*WriteResponse, error)
}
type registerClient struct {
cc *grpc.ClientConn
}