forked from armon/go-chord
-
Notifications
You must be signed in to change notification settings - Fork 2
/
net_utp.go
842 lines (738 loc) · 16.9 KB
/
net_utp.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
package chord
import (
"errors"
"fmt"
"io"
"log"
"net"
"sync"
"sync/atomic"
"time"
"github.com/ipkg/go-mux"
"github.com/zeebo/bencode"
)
type UTPTransport struct {
sock mux.ListenerDialer
dialTimeout time.Duration // Dial timeout
rpcTimeout time.Duration
maxIdle time.Duration // Max age of a connection
local map[string]*localRPC
lock sync.RWMutex
inbound map[net.Conn]struct{} // inbound connections
poolLock sync.Mutex
pool map[string][]*utpOutConn // outbound connection pool
shutdown int32
RPCServe func(IEncoder, IDecoder) (interface{}, error)
}
type IEncoder interface {
Encode(interface{}) error
}
type IDecoder interface {
Decode(interface{}) error
}
type utpOutConn struct {
host string
sock net.Conn
header utpHeader
enc IEncoder
dec IDecoder
used time.Time
}
func (u *utpOutConn) Encode(v interface{}) error {
return u.enc.Encode(v)
}
func (u *utpOutConn) Decode(v interface{}) error {
return u.dec.Decode(v)
}
const (
utpPing = iota
utpListReq
utpGetPredReq
utpNotifyReq
utpFindSucReq
utpClearPredReq
utpSkipSucReq
)
type utpHeader struct {
T int
}
// Potential body types
type utpBodyError struct {
//Err error
Err string
}
type utpBodyString struct {
S string
}
type utpBodyVnode struct {
Vn *Vnode
}
type utpBodyTwoVnode struct {
Target *Vnode
Vn *Vnode
}
type utpBodyFindSuc struct {
Target *Vnode
Num int
Key []byte
}
type utpBodyVnodeError struct {
Vnode *Vnode
Err string
//Err error
}
type utpBodyVnodeListError struct {
Vnodes []*Vnode
Err string
//Err error
}
type utpBodyBoolError struct {
B bool
Err string
//Err error
}
// InitUTPTransport creates a new UTP transport on the given listen address with the
// configured timeout duration. A RPC function can be given to implement additional
// rpc's. maxConnIdle is the maximum age of a connection
func InitUTPTransport(layer mux.ListenerDialer, dialTimeout, rpcTimeout, maxConnIdle time.Duration) (*UTPTransport, error) {
// Setup the transport
u := &UTPTransport{
sock: layer,
dialTimeout: dialTimeout,
rpcTimeout: rpcTimeout,
maxIdle: maxConnIdle,
local: make(map[string]*localRPC),
inbound: make(map[net.Conn]struct{}),
pool: make(map[string][]*utpOutConn),
}
// Listen for connections
go u.listen()
// Reap old connections
go u.reapOld()
// Done
return u, nil
}
// Checks for a local vnode
func (t *UTPTransport) get(vn *Vnode) (VnodeRPC, bool) {
key := vn.String()
t.lock.RLock()
defer t.lock.RUnlock()
w, ok := t.local[key]
if ok {
return w.obj, ok
}
return nil, ok
}
// Gets an outbound connection to a host
func (t *UTPTransport) getConn(host string) (*utpOutConn, error) {
// Check if we have a conn cached
var out *utpOutConn
t.poolLock.Lock()
if atomic.LoadInt32(&t.shutdown) == 1 {
t.poolLock.Unlock()
return nil, fmt.Errorf("UTP transport is shutdown")
}
list, ok := t.pool[host]
if ok && len(list) > 0 {
out = list[len(list)-1]
list = list[:len(list)-1]
t.pool[host] = list
}
t.poolLock.Unlock()
if out != nil {
return out, nil
// TODO:=Verify that the socket is valid. Might be closed. THis blocks
// and needs to be revisited.
//if _, err := out.sock.Read(nil); err == nil {
//return out, nil
//}
//out.sock.Close()
}
// Try to establish a connection
conn, err := t.sock.Dial(host, t.dialTimeout)
if err != nil {
return nil, err
}
// Wrap the sock
out = &utpOutConn{
host: host,
sock: conn,
enc: newEncoder(conn),
dec: newDecoder(conn),
used: time.Now(),
}
return out, nil
}
// Returns an outbound TCP connection to the pool
func (t *UTPTransport) returnConn(o *utpOutConn) {
// Update the last used time
o.used = time.Now()
// Push back into the pool
t.poolLock.Lock()
defer t.poolLock.Unlock()
if atomic.LoadInt32(&t.shutdown) == 1 {
o.sock.Close()
return
}
list, _ := t.pool[o.host]
t.pool[o.host] = append(list, o)
}
// ListVnodes gets a list of the vnodes on the box
func (t *UTPTransport) ListVnodes(host string) ([]*Vnode, error) {
// Get a conn
out, err := t.getConn(host)
if err != nil {
return nil, err
}
// Response channels
respChan := make(chan []*Vnode, 1)
errChan := make(chan error, 1)
go func() {
// Send a list command
out.header.T = utpListReq
body := utpBodyString{S: host}
if err := out.enc.Encode(&out.header); err != nil {
errChan <- err
return
}
if err := out.enc.Encode(&body); err != nil {
errChan <- err
return
}
// Read in the response
resp := utpBodyVnodeListError{}
if err := out.dec.Decode(&resp); err != nil {
errChan <- err
return
}
// Return the connection
t.returnConn(out)
if resp.Err == "" {
respChan <- resp.Vnodes
} else {
errChan <- errors.New(resp.Err)
}
}()
select {
case <-time.After(t.rpcTimeout):
return nil, fmt.Errorf("Command timed out!")
case err := <-errChan:
return nil, err
case res := <-respChan:
return res, nil
}
}
// Ping a Vnode, check for liveness
func (t *UTPTransport) Ping(vn *Vnode) (bool, error) {
// Get a conn
out, err := t.getConn(vn.Host)
if err != nil {
return false, err
}
// Response channels
respChan := make(chan bool, 1)
errChan := make(chan error, 1)
go func() {
// Send a list command
out.header.T = utpPing
body := utpBodyVnode{Vn: vn}
if err := out.enc.Encode(&out.header); err != nil {
errChan <- err
return
}
if err := out.enc.Encode(&body); err != nil {
errChan <- err
return
}
// Read in the response
resp := utpBodyBoolError{}
if err := out.dec.Decode(&resp); err != nil {
errChan <- err
return
}
// Return the connection
t.returnConn(out)
if resp.Err == "" {
respChan <- resp.B
} else {
errChan <- errors.New(resp.Err)
}
}()
select {
case <-time.After(t.rpcTimeout):
return false, fmt.Errorf("Command timed out!")
case err := <-errChan:
return false, err
case res := <-respChan:
return res, nil
}
}
// GetPredecessor requests a nodes predecessor
func (t *UTPTransport) GetPredecessor(vn *Vnode) (*Vnode, error) {
// Get a conn
out, err := t.getConn(vn.Host)
if err != nil {
return nil, err
}
respChan := make(chan *Vnode, 1)
errChan := make(chan error, 1)
go func() {
// Send a list command
out.header.T = utpGetPredReq
body := utpBodyVnode{Vn: vn}
if err := out.enc.Encode(&out.header); err != nil {
errChan <- err
return
}
if err := out.enc.Encode(&body); err != nil {
errChan <- err
return
}
// Read in the response
resp := utpBodyVnodeError{}
if err := out.dec.Decode(&resp); err != nil {
errChan <- err
return
}
// Return the connection
t.returnConn(out)
if resp.Err == "" {
respChan <- resp.Vnode
} else {
errChan <- errors.New(resp.Err)
}
}()
select {
case <-time.After(t.rpcTimeout):
return nil, fmt.Errorf("Command timed out!")
case err := <-errChan:
return nil, err
case res := <-respChan:
return res, nil
}
}
// Notify our successor of ourselves
func (t *UTPTransport) Notify(target, self *Vnode) ([]*Vnode, error) {
// Get a conn
out, err := t.getConn(target.Host)
if err != nil {
return nil, err
}
respChan := make(chan []*Vnode, 1)
errChan := make(chan error, 1)
go func() {
// Send a list command
out.header.T = utpNotifyReq
body := utpBodyTwoVnode{Target: target, Vn: self}
if err := out.enc.Encode(&out.header); err != nil {
errChan <- err
return
}
if err := out.enc.Encode(&body); err != nil {
errChan <- err
return
}
// Read in the response
resp := utpBodyVnodeListError{}
if err := out.dec.Decode(&resp); err != nil {
errChan <- err
return
}
// Return the connection
t.returnConn(out)
if resp.Err == "" {
respChan <- resp.Vnodes
} else {
errChan <- errors.New(resp.Err)
}
}()
select {
case <-time.After(t.rpcTimeout):
return nil, fmt.Errorf("Command timed out!")
case err := <-errChan:
return nil, err
case res := <-respChan:
return res, nil
}
}
// FindSuccessors for the given vnode and key upto n successors
func (t *UTPTransport) FindSuccessors(vn *Vnode, n int, k []byte) ([]*Vnode, error) {
// Get a conn
out, err := t.getConn(vn.Host)
if err != nil {
return nil, err
}
respChan := make(chan []*Vnode, 1)
errChan := make(chan error, 1)
go func() {
// Send a list command
out.header.T = utpFindSucReq
body := utpBodyFindSuc{Target: vn, Num: n, Key: k}
if err := out.enc.Encode(&out.header); err != nil {
errChan <- err
return
}
if err := out.enc.Encode(&body); err != nil {
errChan <- err
return
}
// Read in the response
resp := utpBodyVnodeListError{}
if err := out.dec.Decode(&resp); err != nil {
errChan <- err
return
}
// Return the connection
t.returnConn(out)
if resp.Err == "" {
respChan <- resp.Vnodes
} else {
errChan <- errors.New(resp.Err)
}
}()
select {
case <-time.After(t.rpcTimeout):
return nil, fmt.Errorf("Command timed out!")
case err := <-errChan:
return nil, err
case res := <-respChan:
return res, nil
}
}
// ClearPredecessor clears a predecessor if it matches a given vnode. Used to leave.
func (t *UTPTransport) ClearPredecessor(target, self *Vnode) error {
// Get a conn
out, err := t.getConn(target.Host)
if err != nil {
return err
}
respChan := make(chan bool, 1)
errChan := make(chan error, 1)
go func() {
// Send a list command
out.header.T = utpClearPredReq
body := utpBodyTwoVnode{Target: target, Vn: self}
if err := out.enc.Encode(&out.header); err != nil {
errChan <- err
return
}
if err := out.enc.Encode(&body); err != nil {
errChan <- err
return
}
// Read in the response
resp := utpBodyError{}
if err := out.dec.Decode(&resp); err != nil {
errChan <- err
return
}
// Return the connection
t.returnConn(out)
if resp.Err == "" {
respChan <- true
} else {
errChan <- errors.New(resp.Err)
}
}()
select {
case <-time.After(t.rpcTimeout):
return fmt.Errorf("Command timed out!")
case err := <-errChan:
return err
case <-respChan:
return nil
}
}
// SkipSuccessor instructs a node to skip a given successor. Used to leave.
func (t *UTPTransport) SkipSuccessor(target, self *Vnode) error {
// Get a conn
out, err := t.getConn(target.Host)
if err != nil {
return err
}
respChan := make(chan bool, 1)
errChan := make(chan error, 1)
go func() {
// Send a list command
out.header.T = utpSkipSucReq
body := utpBodyTwoVnode{Target: target, Vn: self}
if err := out.enc.Encode(&out.header); err != nil {
errChan <- err
return
}
if err := out.enc.Encode(&body); err != nil {
errChan <- err
return
}
// Read in the response
resp := utpBodyError{}
if err := out.dec.Decode(&resp); err != nil {
errChan <- err
return
}
// Return the connection
t.returnConn(out)
if resp.Err == "" {
respChan <- true
} else {
errChan <- errors.New(resp.Err)
}
}()
select {
case <-time.After(t.rpcTimeout):
return fmt.Errorf("Command timed out!")
case err := <-errChan:
return err
case <-respChan:
return nil
}
}
// Register for an RPC callbacks
func (t *UTPTransport) Register(v *Vnode, o VnodeRPC) {
key := v.String()
t.lock.Lock()
t.local[key] = &localRPC{v, o}
t.lock.Unlock()
}
// Shutdown the TCP transport
func (t *UTPTransport) Shutdown() {
atomic.StoreInt32(&t.shutdown, 1)
t.sock.Close()
// Close all the inbound connections
t.lock.RLock()
for conn := range t.inbound {
conn.Close()
}
t.lock.RUnlock()
// Close all the outbound
t.poolLock.Lock()
for _, conns := range t.pool {
for _, out := range conns {
out.sock.Close()
}
}
t.pool = nil
t.poolLock.Unlock()
}
// Closes old outbound connections
func (t *UTPTransport) reapOld() {
for {
if atomic.LoadInt32(&t.shutdown) == 1 {
return
}
time.Sleep(30 * time.Second)
t.reapOnce()
}
}
func (t *UTPTransport) reapOnce() {
t.poolLock.Lock()
defer t.poolLock.Unlock()
for host, conns := range t.pool {
max := len(conns)
for i := 0; i < max; i++ {
if time.Since(conns[i].used) > t.maxIdle {
conns[i].sock.Close()
conns[i], conns[max-1] = conns[max-1], nil
max--
i--
}
}
// Trim any idle conns
t.pool[host] = conns[:max]
}
}
// Listens for inbound connections
func (t *UTPTransport) listen() {
for {
conn, err := t.sock.Accept()
if err != nil {
if atomic.LoadInt32(&t.shutdown) == 0 {
fmt.Printf("[ERR] Error accepting TCP connection! %s", err)
continue
} else {
return
}
}
// Register the inbound conn
t.lock.Lock()
t.inbound[conn] = struct{}{}
t.lock.Unlock()
// Start handler
go t.handleConn(conn)
}
}
// Handles inbound TCP connections
func (t *UTPTransport) handleConn(conn net.Conn) {
// Defer the cleanup
defer func() {
t.lock.Lock()
delete(t.inbound, conn)
t.lock.Unlock()
conn.Close()
}()
dec := newDecoder(conn)
enc := newEncoder(conn)
header := utpHeader{}
var sendResp interface{}
for {
// Get the header
if err := dec.Decode(&header); err != nil {
if atomic.LoadInt32(&t.shutdown) == 0 && err.Error() != "EOF" {
log.Printf("[ERR] Failed to decode UTP header! Got %s", err)
}
return
}
// Read in the body and process request
switch header.T {
case utpPing:
body := utpBodyVnode{}
if err := dec.Decode(&body); err != nil {
log.Printf("[ERR] Failed to decode UTP body! Got %s", err)
return
}
// Generate a response
_, ok := t.get(body.Vn)
if ok {
sendResp = utpBodyBoolError{B: ok}
} else {
sendResp = utpBodyBoolError{Err: fmt.Sprintf("target VN not found: %s:%s",
body.Vn.Host, body.Vn.String())}
}
case utpListReq:
body := utpBodyString{}
if err := dec.Decode(&body); err != nil {
log.Printf("[ERR] Failed to decode UTP body! Got %s", err)
return
}
// Generate all the local clients
res := make([]*Vnode, 0, len(t.local))
// Build list
t.lock.RLock()
for _, v := range t.local {
res = append(res, v.vnode)
}
t.lock.RUnlock()
sendResp = utpBodyVnodeListError{Vnodes: trimSlice(res)}
case utpGetPredReq:
body := utpBodyVnode{}
if err := dec.Decode(&body); err != nil {
log.Printf("[ERR] Failed to decode UTP body! Got %s", err)
return
}
// Generate a response
obj, ok := t.get(body.Vn)
resp := utpBodyVnodeError{}
sendResp = &resp
if !ok {
resp.Err = fmt.Sprintf("target VN not found: %s:%s",
body.Vn.Host, body.Vn.String())
break
}
node, err := obj.GetPredecessor()
if err == nil {
resp.Vnode = node
} else {
resp.Err = err.Error()
}
case utpNotifyReq:
body := utpBodyTwoVnode{}
if err := dec.Decode(&body); err != nil {
log.Printf("[ERR] Failed to decode UTP body! Got %s", err)
return
}
// invalid request
if body.Target == nil {
return
}
// Generate a response
obj, ok := t.get(body.Target)
resp := utpBodyVnodeListError{}
sendResp = &resp
if !ok {
resp.Err = fmt.Sprintf("target VN not found: %s:%s",
body.Target.Host, body.Target.String())
break
}
nodes, err := obj.Notify(body.Vn)
if err == nil {
resp.Vnodes = trimSlice(nodes)
} else {
resp.Err = err.Error()
}
case utpFindSucReq:
body := utpBodyFindSuc{}
if err := dec.Decode(&body); err != nil {
log.Printf("[ERR] Failed to decode UTP body! Got %s", err)
return
}
// Generate a response
obj, ok := t.get(body.Target)
resp := utpBodyVnodeListError{}
sendResp = &resp
if ok {
nodes, err := obj.FindSuccessors(body.Num, body.Key)
if err == nil {
resp.Vnodes = trimSlice(nodes)
} else {
resp.Err = err.Error()
}
} else {
resp.Err = fmt.Sprintf("target VN not found: %s:%s",
body.Target.Host, body.Target.String())
}
case utpClearPredReq:
body := utpBodyTwoVnode{}
if err := dec.Decode(&body); err != nil {
log.Printf("[ERR] Failed to decode UTP body! Got %s", err)
return
}
// Generate a response
obj, ok := t.get(body.Target)
resp := utpBodyError{}
sendResp = &resp
if ok {
if err := obj.ClearPredecessor(body.Vn); err != nil {
resp.Err = err.Error()
}
} else {
resp.Err = fmt.Sprintf("target VN not found: %s:%s",
body.Target.Host, body.Target.String())
}
case utpSkipSucReq:
body := utpBodyTwoVnode{}
if err := dec.Decode(&body); err != nil {
log.Printf("[ERR] Failed to decode UTP body! Got %s", err)
return
}
// Generate a response
obj, ok := t.get(body.Target)
resp := utpBodyError{}
sendResp = &resp
if ok {
if err := obj.SkipSuccessor(body.Vn); err != nil {
resp.Err = err.Error()
}
} else {
resp.Err = fmt.Sprintf("target VN not found: %s:%s",
body.Target.Host, body.Target.String())
}
default:
log.Printf("[ERR] Unknown request type! Got %d", header.T)
return
}
// Send the response
if err := enc.Encode(sendResp); err != nil {
log.Printf("[ERR] Failed to send UTP body! Got %s", err)
return
}
}
}
//
// abstratct encoder and decoder
//
func newDecoder(r io.Reader) IDecoder {
return bencode.NewDecoder(r)
}
func newEncoder(w io.Writer) IEncoder {
return bencode.NewEncoder(w)
}