-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathhedge.go
1498 lines (1268 loc) · 37.1 KB
/
hedge.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
package hedge
import (
"bufio"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"log"
"net"
"os"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"cloud.google.com/go/spanner"
pb "github.com/flowerinthenight/hedge/proto/v1"
"github.com/flowerinthenight/spindle/v2"
"github.com/google/uuid"
gaxv2 "github.com/googleapis/gax-go/v2"
"github.com/hashicorp/memberlist"
"google.golang.org/api/iterator"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/reflection"
)
const (
CmdLeader = "LDR" // for leader confirmation, reply="ACK"
CmdWrite = "PUT" // write key/value, fmt="PUT <base64(payload)> [noappend]"
CmdSend = "SND" // member to leader, fmt="SND <base64(payload)>"
CmdPing = "HEY" // heartbeat to indicate availability, fmt="HEY [id]"
CmdMembers = "MEM" // members info from leader to all, fmt="MEM base64(JSON(members))"
CmdBroadcast = "ALL" // broadcast to all, fmt="ALL base64(payload)"
CmdAck = "ACK" // generic reply, fmt="ACK"|"ACK base64(err)"|"ACK base64(JSON(members))"
CmdSemaphore = "SEM" // create semaphore, fmt="SEM {name} {limit} {caller}, reply="ACK"
CmdSemAcquire = "SEA" // acquire semaphore, fmt="SEA {name} {caller}", reply="ACK[ base64([0:|1:]err)]" (0=final,1=retry)
CmdSemRelease = "SER" // release semaphore, fmt="SER {name} {caller}"
FlagNoAppend = "noappend"
)
var (
ErrNotRunning = fmt.Errorf("hedge: not running")
ErrNoLeader = fmt.Errorf("hedge: no leader available")
ErrNoHandler = fmt.Errorf("hedge: no message handler")
ErrNotSupported = fmt.Errorf("hedge: not supported")
ErrInvalidConn = fmt.Errorf("hedge: invalid connection")
cctx = func(ctx context.Context) context.Context {
return context.WithValue(ctx, struct{}{}, nil)
}
)
type FnMsgHandler func(data interface{}, msg []byte) ([]byte, error)
// KeyValue is for Put()/Get() callers.
type KeyValue struct {
Key string `json:"key"`
Value string `json:"value"`
Timestamp time.Time `json:"timestamp"` // read-only, populated when Get()
}
// LogItem represents an item in our log.
type LogItem struct {
Id string
Key string
Value string
Leader string
Timestamp time.Time
}
type Option interface {
Apply(*Op)
}
type withDuration int64
func (w withDuration) Apply(op *Op) { op.lockTimeout = int64(w) }
// WithDuration sets Op's internal spindle object's lease duration in milliseconds.
// Defaults to 30000ms (30s) when not set. Minimum value is 2000ms (2s).
func WithDuration(v int64) Option { return withDuration(v) }
type withGroupSyncInterval time.Duration
func (w withGroupSyncInterval) Apply(op *Op) { op.syncInterval = time.Duration(w) }
// WithGroupSyncInterval sets the internal interval timeout to sync membership
// within the group in seconds. If not set, defaults to 30s. Minimum value is 2s.
func WithGroupSyncInterval(v time.Duration) Option { return withGroupSyncInterval(v) }
type withLeaderCallback struct {
d interface{}
f spindle.FnLeaderCallback
}
func (w withLeaderCallback) Apply(op *Op) {
op.cbLeaderData = w.d
op.cbLeader = w.f
}
// WithLeaderCallback sets the node's callback function when it a leader is
// selected (or deselected). The msg arg for h will be set to either 0 or 1.
func WithLeaderCallback(d interface{}, f spindle.FnLeaderCallback) Option {
return withLeaderCallback{d, f}
}
type withLeaderHandler struct {
d interface{}
h FnMsgHandler
}
func (w withLeaderHandler) Apply(op *Op) {
op.fnLdrData = w.d
op.fnLeader = w.h
}
// WithLeaderHandler sets the node's callback function when it is the current
// leader and when members send messages to it using the Send(...) API. Any
// arbitrary data represented by d will be passed to the callback h every
// time it is called. If d is nil, the default callback data will be the *Op
// object itself. The handler's returning []byte will serve as reply.
//
// Typical flow would be:
// 1. Any node (including the leader) calls the Send(...) API.
// 2. The current leader handles the call by reading the input.
// 3. Leader will then call FnLeaderHandler, passing the arbitrary data
// along with the message.
// 4. FnLeaderHandler will process the data as leader, then returns the
// reply to the calling member.
func WithLeaderHandler(d interface{}, h FnMsgHandler) Option {
return withLeaderHandler{d, h}
}
type withBroadcastHandler struct {
d interface{}
h FnMsgHandler
}
func (w withBroadcastHandler) Apply(op *Op) {
op.fnBcData = w.d
op.fnBroadcast = w.h
}
// WithBroadcastHandler sets the node's callback function for broadcast messages
// from anyone in the group using the Broadcast(...) API. Any arbitrary data
// represented by d will be passed to the callback h every time it is called.
// If d is nil, the default callback data will be the *Op object itself. The
// handler's returning []byte will serve as reply.
//
// A nil broadcast handler disables the internal heartbeat function.
func WithBroadcastHandler(d interface{}, h FnMsgHandler) Option {
return withBroadcastHandler{d, h}
}
type withGrpcHostPort string
func (w withGrpcHostPort) Apply(op *Op) { op.grpcHostPort = string(w) }
// WithGrpcHostPort sets Op's internal grpc host/port address.
// Defaults to the internal TCP host:port+1.
func WithGrpcHostPort(v string) Option { return withGrpcHostPort(v) }
type StreamMessage struct {
Payload *pb.Payload `json:"payload"`
Error error `json:"error"`
}
type withLeaderStreamChannels struct {
in chan *StreamMessage
out chan *StreamMessage
}
func (w withLeaderStreamChannels) Apply(op *Op) {
op.leaderStreamIn = w.in
op.leaderStreamOut = w.out
}
// WithLeaderStreamChannels sets the streaming input and output channels for sending
// streaming messages to the leader. All incoming stream messages to the leader will
// be sent to the `in` channel. A nil message indicates the end of the streaming data.
// After sending all messages to `in`, the handler will then listen to the `out` channel
// for reply messages. A nil message indicates the end of the reply stream.
func WithLeaderStreamChannels(in chan *StreamMessage, out chan *StreamMessage) Option {
return withLeaderStreamChannels{in, out}
}
type withBroadcastStreamChannels struct {
in chan *StreamMessage
out chan *StreamMessage
}
func (w withBroadcastStreamChannels) Apply(op *Op) {
op.broadcastStreamIn = w.in
op.broadcastStreamOut = w.out
}
// WithBroadcastStreamChannels sets the streaming input and output channels for broadcasting
// messages to all nodes. All incoming stream messages will be sent to the `in` channel. A
// nil message indicates the end of the streaming data. After sending all messages to `in`,
// the handler will then listen to the `out` channel for reply messages. A nil message
// indicates the end of the reply stream.
func WithBroadcastStreamChannels(in chan *StreamMessage, out chan *StreamMessage) Option {
return withBroadcastStreamChannels{in, out}
}
type withLogger struct{ l *log.Logger }
func (w withLogger) Apply(op *Op) { op.logger = w.l }
// WithLogger sets Op's logger object. Can be silenced by setting v to:
//
// log.New(ioutil.Discard, "", 0)
func WithLogger(v *log.Logger) Option { return withLogger{v} }
// Op is our main instance for hedge operations.
type Op struct {
hostPort string // this instance's id; address:port
grpcHostPort string // default is host:port+1 (from `hostPort`)
spannerClient *spanner.Client // both for spindle and hedge
lockTable string // spindle lock table
lockName string // spindle lock name
lockTimeout int64 // spindle's lock lease duration in ms
logTable string // append-only log table
cbLeader spindle.FnLeaderCallback
cbLeaderData interface{}
fnLeader FnMsgHandler // leader message handler
fnLdrData interface{} // arbitrary data passed to fnLeader
fnBroadcast FnMsgHandler // broadcast message handler
fnBcData interface{} // arbitrary data passed to fnBroadcast
leaderStreamIn chan *StreamMessage
leaderStreamOut chan *StreamMessage
broadcastStreamIn chan *StreamMessage
broadcastStreamOut chan *StreamMessage
sosLock *sync.Mutex
soss map[string]*SoS // distributed memory
*spindle.Lock // handles our distributed lock
members map[string]struct{} // key=id
syncInterval time.Duration // ensure membership
mtx sync.Mutex // local mutex
mtxSem sync.Mutex // semaphore mutex
ensureOn atomic.Int32 // 1=semaphore checker running
ensureCh chan string // please check this id
ensureCtx context.Context
ensureCancel context.CancelFunc
ensureDone chan struct{}
active atomic.Int32 // 1=running, 0=off
logger *log.Logger // internal logger
}
// String implements the Stringer interface.
func (op *Op) String() string {
return fmt.Sprintf("hostport:%s;spindle:%v;%v;%v",
op.hostPort,
op.spannerClient.DatabaseName(),
op.lockTable,
op.logTable,
)
}
// HostPort returns the host:port (or name) of this instance.
func (op *Op) HostPort() string { return op.hostPort }
// Name is the same as HostPort.
func (op *Op) Name() string { return op.hostPort }
// IsRunning returns true if Op is already running.
func (op *Op) IsRunning() bool { return op.active.Load() == 1 }
// Run starts the main handler. It blocks until ctx is cancelled,
// optionally sending an error message to done when finished.
func (op *Op) Run(ctx context.Context, done ...chan error) error {
var err error
defer func(e *error) {
if len(done) > 0 {
done[0] <- *e
}
}(&err)
// Some housekeeping.
if op.spannerClient == nil {
err = fmt.Errorf("hedge: Spanner client cannot be nil")
return err
}
for _, v := range []struct {
name string
val string
}{
{"SpindleTable", op.lockTable},
{"SpindleLockName", op.lockName},
} {
if v.val == "" {
err = fmt.Errorf("hedge: %v cannot be empty", v.name)
return err
}
}
// Setup our server for our internal protocol.
addr, err := net.ResolveTCPAddr("tcp4", op.hostPort)
if err != nil {
return err
}
var exitedTCP atomic.Int32
doneTCP := make(chan error, 1)
// This connection will be closed upon context termination.
tl, err := net.ListenTCP("tcp", addr)
if err != nil {
return err
}
op.logger.Printf("tcp: listen on %v", op.hostPort)
go func() {
defer func() { doneTCP <- nil }()
for {
conn, err := tl.Accept()
if exitedTCP.Load() == 1 {
return
}
if err != nil {
op.logger.Printf("Accept failed: %v", err)
return
}
if ctx.Err() != nil {
op.logger.Printf("cancelled: %v", ctx.Err())
return
}
go handleMsg(ctx, op, conn)
}
}()
gl, err := net.Listen("tcp", op.grpcHostPort)
if err != nil {
return err
}
defer gl.Close()
op.logger.Printf("grpc: listen on %v", op.grpcHostPort)
gs := grpc.NewServer()
svc := &service{op: op}
pb.RegisterHedgeServer(gs, svc)
reflection.Register(gs) // register reflection service
go gs.Serve(gl)
// Setup and start our internal spindle object.
op.Lock = spindle.New(
op.spannerClient,
op.lockTable,
fmt.Sprintf("hedge/spindle/lockname/%v", op.lockName),
spindle.WithDuration(op.lockTimeout),
spindle.WithId(op.hostPort),
spindle.WithLeaderCallback(op.cbLeaderData, func(data interface{}, msg []byte) {
if op.cbLeader != nil {
m := fmt.Sprintf("%v %v", string(msg), op.Name())
op.cbLeader(data, []byte(m))
}
}),
spindle.WithLogger(op.logger),
)
spindleDone := make(chan error, 1)
ctxSpindle, cancel := context.WithCancel(context.Background())
op.Lock.Run(ctxSpindle, spindleDone)
defer func() {
cancel() // stop spindle;
<-spindleDone // and wait
}()
// Start tracking online members.
op.members[op.hostPort] = struct{}{}
membersDone := make(chan error, 1)
ctxMembers := cctx(ctx)
first := make(chan struct{}, 1)
first <- struct{}{} // immediately the first time
ticker := time.NewTicker(op.syncInterval)
defer func() {
ticker.Stop()
<-membersDone
}()
go func() {
var active atomic.Int32
fnEnsureMembers := func() {
active.Store(1)
defer active.Store(0)
ch := make(chan *string)
emdone := make(chan struct{}, 1)
todel := []string{}
go func() {
for {
m := <-ch
switch {
case m == nil:
emdone <- struct{}{}
return
default:
todel = append(todel, *m)
}
}
}()
var w sync.WaitGroup
allm := op.getMembers()
for k := range allm {
w.Add(1)
go func(id string) {
defer func() { w.Done() }()
timeout := time.Second * 5
conn, err := net.DialTimeout("tcp", id, timeout)
if err != nil {
ch <- &id // delete this
return
}
var sb strings.Builder
fmt.Fprintf(&sb, "%s\n", CmdPing)
r, err := op.send(conn, sb.String())
if err != nil {
ch <- &id // delete this
return
}
if r != CmdAck {
ch <- &id // delete this
}
}(k)
}
w.Wait()
ch <- nil // close;
<-emdone // and wait
for _, rm := range todel {
if rm != "" {
op.logger.Printf("[leader] delete %v", rm)
op.delMember(rm)
}
}
// Broadcast active members to all.
for k := range op.getMembers() {
w.Add(1)
go func(id string) {
defer w.Done()
timeout := time.Second * 5
conn, err := net.DialTimeout("tcp", id, timeout)
if err != nil {
return
}
defer conn.Close()
var sb strings.Builder
fmt.Fprintf(&sb, "%s %s\n", CmdMembers, op.encodeMembers())
op.send(conn, sb.String())
}(k)
}
w.Wait()
}
var hbactive atomic.Int32
fnHeartbeat := func() {
hbactive.Store(1)
defer hbactive.Store(0)
lconn, err := op.getLeaderConn(ctx)
if err != nil {
return
}
if lconn != nil {
defer lconn.Close()
}
var sb strings.Builder
fmt.Fprintf(&sb, "%s %s\n", CmdPing, op.hostPort)
r, err := op.send(lconn, sb.String())
if err != nil {
return
}
b, _ := base64.StdEncoding.DecodeString(r)
var allm map[string]struct{}
json.Unmarshal(b, &allm)
op.setMembers(allm)
}
for {
select {
case <-ctxMembers.Done():
membersDone <- nil
return
case <-first:
case <-ticker.C:
}
if op.fnBroadcast == nil {
op.logger.Println("no broadcast support")
membersDone <- nil
return
}
if hbactive.Load() == 0 {
go fnHeartbeat() // tell leader we're online
}
if hl, _ := op.HasLock(); !hl {
continue
}
if active.Load() == 0 {
go fnEnsureMembers() // leader only
}
}
}()
op.active.Store(1)
defer op.active.Store(0)
<-ctx.Done() // wait for termination
exitedTCP.Store(1) // don't print err in tl.Accept
tl.Close() // will cause tl.Accept to fail
gs.GracefulStop() // stop grpc server
if op.ensureOn.Load() == 1 {
op.ensureCancel() // stop semaphore checker;
<-op.ensureDone // and wait
}
return nil
}
// NewSemaphore returns a distributed semaphore object.
func (op *Op) NewSemaphore(ctx context.Context, name string, limit int) (*Semaphore, error) {
if op.logTable == "" {
return nil, ErrNotSupported
}
if op.active.Load() != 1 {
return nil, ErrNotRunning
}
if strings.Contains(name, " ") {
return nil, fmt.Errorf("name cannot have whitespace(s)")
}
conn, err := op.getLeaderConn(ctx)
if err != nil {
return nil, err
}
if conn != nil {
defer conn.Close()
}
var sb strings.Builder
fmt.Fprintf(&sb, "%s %s %d %s\n", CmdSemaphore, name, limit, op.hostPort)
reply, err := op.send(conn, sb.String())
if err != nil {
return nil, err
}
switch {
case strings.HasPrefix(reply, CmdAck):
ss := strings.Split(reply, " ")
if len(ss) > 1 { // failed
dec, _ := base64.StdEncoding.DecodeString(ss[1])
return nil, fmt.Errorf(string(dec))
}
default:
return nil, ErrNotSupported
}
return &Semaphore{name, limit, op}, nil
}
// NewSoS returns an object for writing data to spill-over
// storage across the cluster. The order of writing is local
// memory, local disk, other pod's memory, other pod's disk,
// and so on.
func (op *Op) NewSoS(name string, opts ...*SoSOptions) *SoS {
op.sosLock.Lock()
defer op.sosLock.Unlock()
if _, ok := op.soss[name]; ok {
return op.soss[name]
}
op.soss[name] = newSoS(name, op, opts...)
return op.soss[name]
}
// Get reads a key (or keys) from Op.
// The values of limit are:
//
// limit = 0 --> (default) latest only
// limit = -1 --> all (latest to oldest, [0]=latest)
// limit = -2 --> oldest version only
// limit > 0 --> items behind latest; 3 means latest + 2 versions behind, [0]=latest
func (op *Op) Get(ctx context.Context, key string, limit ...int64) ([]KeyValue, error) {
if op.logTable == "" {
return nil, ErrNotSupported
}
ret := []KeyValue{}
var q strings.Builder
fmt.Fprintf(&q, "select key, value, timestamp ")
fmt.Fprintf(&q, "from %s ", op.logTable)
fmt.Fprintf(&q, "where key = @key and timestamp is not null ")
fmt.Fprintf(&q, "order by timestamp desc limit 1")
if len(limit) > 0 {
switch {
case limit[0] > 0:
q.Reset()
fmt.Fprintf(&q, "select key, value, timestamp ")
fmt.Fprintf(&q, "from %s ", op.logTable)
fmt.Fprintf(&q, "where key = @key and timestamp is not null ")
fmt.Fprintf(&q, "order by timestamp desc limit %v", limit[0])
case limit[0] == -1:
q.Reset()
fmt.Fprintf(&q, "select key, value, timestamp ")
fmt.Fprintf(&q, "from %s ", op.logTable)
fmt.Fprintf(&q, "where key = @key and timestamp is not null ")
fmt.Fprintf(&q, "order by timestamp desc")
case limit[0] == -2:
q.Reset()
fmt.Fprintf(&q, "select key, value, timestamp ")
fmt.Fprintf(&q, "from %s ", op.logTable)
fmt.Fprintf(&q, "where key = @key and timestamp is not null ")
fmt.Fprintf(&q, "order by timestamp limit 1")
}
}
stmt := spanner.Statement{SQL: q.String(), Params: map[string]interface{}{"key": key}}
iter := op.spannerClient.Single().Query(ctx, stmt)
defer iter.Stop()
for {
row, err := iter.Next()
if err == iterator.Done {
break
}
if err != nil {
return ret, err
}
var li LogItem
err = row.ToStruct(&li)
if err != nil {
return ret, err
}
ret = append(ret, KeyValue{
Key: li.Key,
Value: li.Value,
Timestamp: li.Timestamp,
})
}
return ret, nil
}
type PutOptions struct {
// If true, do a direct write, no need to fwd to leader.
DirectWrite bool
// If true, don't do an append-write; overwrite the latest. Note that even
// if you set this to true, if you do another Put the next time with this
// field set as false (default), the previous write will now be gone, or
// will now be part of the history.
NoAppend bool
}
// Put saves a key/value to Op. This call will try to block, at least roughly
// until spindle's timeout, to wait for the leader's availability to do actual
// writes before returning.
func (op *Op) Put(ctx context.Context, kv KeyValue, po ...PutOptions) error {
if op.logTable == "" {
return ErrNotSupported
}
var err error
var direct, noappend, hl bool
if len(po) > 0 {
direct = po[0].DirectWrite
noappend = po[0].NoAppend
} else {
hl, _ = op.HasLock()
}
id := uuid.NewString()
if noappend {
id = "-"
}
if direct || hl {
b, _ := json.Marshal(kv)
op.logger.Printf("[Put] leader: direct write: %v", string(b))
_, err := op.spannerClient.Apply(ctx, []*spanner.Mutation{
spanner.InsertOrUpdate(op.logTable,
[]string{"id", "key", "value", "leader", "timestamp"},
[]interface{}{id, kv.Key, kv.Value, op.hostPort, spanner.CommitTimestamp},
),
})
return err
}
// For non-leaders, we confirm the leader via spindle, and if so, ask leader to do the
// actual write for us. Let's do a couple retries up to spindle's timeout.
conn, err := op.getLeaderConn(ctx)
if err != nil {
return err
}
if conn != nil {
defer conn.Close()
}
b, _ := json.Marshal(kv)
enc := base64.StdEncoding.EncodeToString(b)
var sb strings.Builder
fmt.Fprintf(&sb, "%s %s\n", CmdWrite, enc)
if noappend {
sb.Reset()
fmt.Fprintf(&sb, "%s %s %s\n", CmdWrite, enc, FlagNoAppend)
}
reply, err := op.send(conn, sb.String())
if err != nil {
return err
}
switch {
case strings.HasPrefix(reply, CmdAck):
ss := strings.Split(reply, " ")
if len(ss) > 1 { // failed
dec, _ := base64.StdEncoding.DecodeString(ss[1])
return fmt.Errorf(string(dec))
}
default:
return ErrNoLeader
}
return nil
}
// Send sends msg to the current leader. Any node can send messages,
// including the leader itself (send to self). It also blocks until
// it receives the reply from the leader's message handler.
func (op *Op) Send(ctx context.Context, msg []byte) ([]byte, error) {
conn, err := op.getLeaderConn(ctx)
if err != nil {
return nil, err
}
if conn != nil {
defer conn.Close()
}
enc := base64.StdEncoding.EncodeToString(msg)
var sb strings.Builder
fmt.Fprintf(&sb, "%s %s\n", CmdSend, enc)
reply, err := op.send(conn, sb.String())
if err != nil {
return nil, err
}
switch {
case strings.HasPrefix(reply, CmdAck): // expect "ACK base64(reply)"
ss := strings.Split(reply, " ")
if len(ss) > 1 {
return base64.StdEncoding.DecodeString(ss[1])
}
}
// If not ACK, then the whole reply is an error string.
b, _ := base64.StdEncoding.DecodeString(reply)
return nil, fmt.Errorf(string(b))
}
type StreamToLeaderOutput struct {
In chan *StreamMessage `json:"in"`
Out chan *StreamMessage `json:"out"`
}
// StreamToLeader returns an input and output channels for streaming to leader.
// To use the channels, send your request message(s) to the input channel, close
// it (i.e. close(input)), then read the replies from the output channel. This
// function will close the output channel when done.
//
// StreamToLeader is sequential in the sense that you need to send all your input
// messages first before getting any response from the leader.
func (op *Op) StreamToLeader(ctx context.Context) (*StreamToLeaderOutput, error) {
if op.leaderStreamIn == nil || op.leaderStreamOut == nil {
return nil, fmt.Errorf("hedge: input/output channel(s) cannot be nil")
}
conn, err := op.getLeaderGrpcConn(ctx)
if err != nil {
return nil, err
}
client := pb.NewHedgeClient(conn)
stream, err := client.Send(ctx)
if err != nil {
return nil, err
}
keyId := "id"
id := uuid.NewString()
reply := make(chan error)
ret := StreamToLeaderOutput{
In: make(chan *StreamMessage),
Out: make(chan *StreamMessage),
}
// Exit only when input channel is closed by the caller.
// We don't wait for this goroutine.
go func() {
var err error
for m := range ret.In {
if m.Payload.Meta == nil {
m.Payload.Meta = map[string]string{keyId: id}
} else {
if _, ok := m.Payload.Meta[keyId]; !ok {
m.Payload.Meta[keyId] = id
}
}
err = stream.Send(m.Payload)
if err != nil {
break
}
}
stream.CloseSend()
reply <- err
}()
// Exit only when streaming response is done.
// We don't wait for this goroutine.
go func() {
defer func() {
close(ret.Out)
conn.Close()
}()
err := <-reply
if err != nil {
ret.Out <- &StreamMessage{Error: err}
return
}
for {
resp, err := stream.Recv()
if err == io.EOF {
return
}
ret.Out <- &StreamMessage{Payload: resp}
}
}()
return &ret, nil
}
type BroadcastOutput struct {
Id string `json:"id,omitempty"`
Reply []byte `json:"reply,omitempty"`
Error error `json:"error,omitempty"`
}
type BroadcastArgs struct {
SkipSelf bool // if true, skip broadcasting to self
Out chan BroadcastOutput
}
// Broadcast sends msg to all nodes (send to all). Any node can broadcast messages, including the
// leader itself. Note that this is best-effort basis only; by the time you call this API, the
// handler might not have all the active members in record yet, as is the usual situation with
// k8s deployments, where pods come and go, and our internal heartbeat protocol hasn't been
// completed yet. This call will also block until it receives all the reply from all nodes'
// broadcast handlers.
//
// If args[].Out is set, the output will be streamed to that channel instead. Useful if you prefer
// a streamed output (as reply comes) instead of waiting for all replies before returning. If set,
// the return value (output slice) will be set to empty []. Also, close() will be called on the
// Out channel to indicate streaming end.
func (op *Op) Broadcast(ctx context.Context, msg []byte, args ...BroadcastArgs) []BroadcastOutput {
if op.active.Load() != 1 || op.fnBroadcast == nil {
return nil // not running or no broadcast support
}
var stream bool
outs := []BroadcastOutput{}
var w sync.WaitGroup
var outch chan BroadcastOutput
members := op.getMembers()
if len(args) > 0 && args[0].SkipSelf {
delete(members, op.Name())
}
switch {
case len(args) > 0 && args[0].Out != nil:
outch = args[0].Out
stream = true
default:
outch = make(chan BroadcastOutput, len(members))
}
for k := range members {
w.Add(1)
go func(id string) {
defer w.Done()
timeout := time.Second * 5
conn, err := net.DialTimeout("tcp", id, timeout)
if err != nil {
outch <- BroadcastOutput{Id: id, Error: err}
return
}
defer conn.Close()
enc := base64.StdEncoding.EncodeToString(msg)
var sb strings.Builder
fmt.Fprintf(&sb, "%s %s\n", CmdBroadcast, enc)
reply, err := op.send(conn, sb.String())
if err != nil {
outch <- BroadcastOutput{Id: id, Error: err}
return
}
switch {
case strings.HasPrefix(reply, CmdAck): // expect "ACK base64(reply)"
ss := strings.Split(reply, " ")
if len(ss) > 1 {
r, e := base64.StdEncoding.DecodeString(ss[1])
outch <- BroadcastOutput{Id: id, Reply: r, Error: e}
return
}
}
// If not ACK, then the whole reply is an error string.
r, _ := base64.StdEncoding.DecodeString(reply)
outch <- BroadcastOutput{Id: id, Error: fmt.Errorf(string(r))}
}(k)
}
w.Wait()
switch {
case stream:
close(args[0].Out)
default:
for range members {
outs = append(outs, <-outch)
}
}
return outs
}
type StreamBroadcastArgs struct {
SkipSelf bool // if true, skip broadcasting to self
}
type StreamBroadcastOutput struct {
In chan *StreamMessage
Outs map[string]chan *StreamMessage
}
// StreamBroadcast returns input and output channels for doing streaming broadcasts. Any node can broadcast messages,
// including the leader itself. Note that this is best-effort basis only; by the time you call this API, the handler
// might not have all the active members in record yet, as is the usual situation with k8s deployments, where pods
// come and go, and our internal heartbeat protocol hasn't been completed yet. This call will also block until it
// receives all the reply from all nodes' broadcast handlers.
//
// To use the channels, send your request message(s) to the input channel, close it (i.e. close(input)), then read
// the replies from the output channels. This function will close all output channels when done.
//
// StreamBroadcast is sequential in the sense that you need to send all your input messages first before getting
// any response from all the nodes.
func (op *Op) StreamBroadcast(ctx context.Context, args ...StreamBroadcastArgs) (*StreamBroadcastOutput, error) {
if op.active.Load() != 1 {
return nil, nil // not running
}
members := op.getMembers()