-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpeer.go
725 lines (610 loc) · 17.3 KB
/
peer.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
// Copyright 2022 OnMetal authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package metalbond
import (
"errors"
"fmt"
"io"
"math/rand"
"net"
"sync"
"time"
"github.com/sirupsen/logrus"
)
var RetryIntervalMin = 5
var RetryIntervalMax = 5
type metalBondPeer struct {
conn *net.Conn
remoteAddr string
localIP string
localAddr string
direction ConnectionDirection
isServer bool
mtxReset sync.RWMutex
mtxState sync.RWMutex
state ConnectionState
receivedRoutes routeTable
subscribedVNIs map[VNI]bool
mtxSubscribedVNIs sync.RWMutex
metalbond *MetalBond
keepaliveInterval uint32
keepaliveTimer *time.Timer
shutdown chan bool
keepaliveStop chan bool
txChan chan []byte
txChanClose chan bool
rxHello chan msgHello
rxKeepalive chan msgKeepalive
rxSubscribe chan msgSubscribe
rxUnsubscribe chan msgUnsubscribe
rxUpdate chan msgUpdate
wg sync.WaitGroup
}
func newMetalBondPeer(
pconn *net.Conn,
remoteAddr string,
localIP string,
keepaliveInterval uint32,
direction ConnectionDirection,
metalbond *MetalBond) *metalBondPeer {
peer := metalBondPeer{
conn: pconn,
remoteAddr: remoteAddr,
localIP: localIP,
direction: direction,
state: CONNECTING,
receivedRoutes: newRouteTable(),
subscribedVNIs: make(map[VNI]bool),
keepaliveInterval: keepaliveInterval,
metalbond: metalbond,
}
go peer.handle()
return &peer
}
func (p *metalBondPeer) String() string {
return p.remoteAddr
}
func (p *metalBondPeer) GetState() ConnectionState {
p.mtxState.RLock()
state := p.state
p.mtxState.RUnlock()
return state
}
func (p *metalBondPeer) Subscribe(vni VNI) error {
p.log().Debugf("Subscribe to vni %d", vni)
if p.direction == INCOMING {
return fmt.Errorf("Cannot subscribe on incoming connection")
}
if p.GetState() != ESTABLISHED {
return fmt.Errorf("Connection not ESTABLISHED")
}
msg := msgSubscribe{
VNI: vni,
}
return p.sendMessage(msg)
}
func (p *metalBondPeer) Unsubscribe(vni VNI) error {
p.log().Debugf("Unsubscribe from vni %d", vni)
if p.direction == INCOMING {
return fmt.Errorf("Cannot unsubscribe on incoming connection")
}
msg := msgUnsubscribe{
VNI: vni,
}
for dest, nhs := range p.receivedRoutes.GetDestinationsByVNI(vni) {
for _, nh := range nhs {
err, _ := p.receivedRoutes.RemoveNextHop(vni, dest, nh, p)
if err != nil {
p.log().Errorf("Could not remove received route from peer's receivedRoutes Table: %v", err)
}
}
}
return p.sendMessage(msg)
}
func (p *metalBondPeer) SendUpdate(upd msgUpdate) error {
if p.GetState() != ESTABLISHED {
return fmt.Errorf("Connection not ESTABLISHED")
}
if err := p.sendMessage(upd); err != nil {
p.log().Errorf("Cannot send message: %v", err)
return err
}
return nil
}
///////////////////////////////////////////////////////////////////
// PRIVATE METHODS BELOW //
///////////////////////////////////////////////////////////////////
func (p *metalBondPeer) setState(newState ConnectionState) {
oldState := p.state
p.mtxState.Lock()
p.state = newState
p.mtxState.Unlock()
if oldState != newState && newState == ESTABLISHED {
p.metalbond.mtxMySubscriptions.RLock()
for sub := range p.metalbond.mySubscriptions {
if err := p.Subscribe(sub); err != nil {
p.log().Errorf("Cannot subscribe: %v", err)
}
}
p.metalbond.mtxMySubscriptions.RUnlock()
rt := p.metalbond.getMyAnnouncements()
for _, vni := range rt.GetVNIs() {
for dest, hops := range rt.GetDestinationsByVNI(vni) {
for _, hop := range hops {
upd := msgUpdate{
VNI: vni,
Destination: dest,
NextHop: hop,
}
err := p.SendUpdate(upd)
if err != nil {
p.log().Debugf("Could not send update to peer: %v", err)
}
}
}
}
}
// Connection lost
if oldState != newState && newState != ESTABLISHED {
subscribers := make(map[VNI]map[*metalBondPeer]bool)
p.metalbond.mtxSubscribers.RLock()
for vni, peers := range p.metalbond.subscribers {
for peer := range peers {
if p == peer {
if _, ok := subscribers[vni]; !ok {
subscribers[vni] = make(map[*metalBondPeer]bool)
}
subscribers[vni][p] = true
}
}
}
p.metalbond.mtxSubscribers.RUnlock()
for vni, peers := range subscribers {
for peer := range peers {
if p == peer {
if err := p.metalbond.removeSubscriber(p, vni); err != nil {
p.log().Errorf("Cannot remove subscriber: %v", err)
}
}
}
}
}
}
func (p *metalBondPeer) log() *logrus.Entry {
return logrus.WithField("peer", p.remoteAddr).WithField("state", p.GetState().String()).WithField("localAddr", p.localAddr)
}
func (p *metalBondPeer) cleanup() {
p.log().Debugf("cleanup")
// unsubscribe from VNIs
p.mtxSubscribedVNIs.RLock()
defer p.mtxSubscribedVNIs.RUnlock()
for vni := range p.subscribedVNIs {
err := p.metalbond.Unsubscribe(vni)
if err != nil {
p.log().Errorf("Could not unsubscribe from VNI: %v", err)
}
}
// remove received routes from this peer from metalbond database
p.log().Info("Removing all received nexthops from peer")
for _, vni := range p.receivedRoutes.GetVNIs() {
for dest, nhs := range p.receivedRoutes.GetDestinationsByVNI(vni) {
for _, nh := range nhs {
err, _ := p.receivedRoutes.RemoveNextHop(vni, dest, nh, p)
if err != nil {
p.log().Errorf("Could not remove received route from peer's receivedRoutes Table: %v", err)
return
}
if err := p.metalbond.removeReceivedRoute(p, vni, dest, nh); err != nil {
p.log().Errorf("Cannot remove received route from metalbond db: %v", err)
}
}
}
}
}
func (p *metalBondPeer) handle() {
p.wg.Add(1)
defer p.wg.Done()
p.txChan = make(chan []byte, 65536)
p.shutdown = make(chan bool, 5)
p.keepaliveStop = make(chan bool, 5)
p.txChanClose = make(chan bool, 5)
p.rxHello = make(chan msgHello, 5)
p.rxKeepalive = make(chan msgKeepalive, 5)
p.rxSubscribe = make(chan msgSubscribe, 100)
p.rxUnsubscribe = make(chan msgUnsubscribe, 100)
p.rxUpdate = make(chan msgUpdate, 100)
// outgoing connections still need to be established. pconn is nil.
for p.conn == nil {
select {
case <-p.shutdown:
p.cleanup()
// exit handle() thread
return
default:
// proceed
}
var err error
localAddr := &net.TCPAddr{}
if p.localIP != "" {
localAddr, err = net.ResolveTCPAddr("tcp", p.localIP+":0")
if err != nil {
p.log().Errorf("Error resolving local address: %s", err)
return
}
}
remoteAddr, err := net.ResolveTCPAddr("tcp", p.remoteAddr)
if err != nil {
p.log().Errorf("Error resolving remove address: %s", err)
return
}
tcpConn, err := net.DialTCP("tcp", localAddr, remoteAddr)
if err != nil {
retry := time.Duration(rand.Intn(RetryIntervalMax)+RetryIntervalMin) * time.Second
logrus.Infof("Cannot connect to server - %v - retry in %v", err, retry)
time.Sleep(retry)
continue
}
conn := net.Conn(tcpConn)
p.localAddr = conn.LocalAddr().String()
p.conn = &conn
}
go p.rxLoop()
go p.txLoop()
if p.direction == OUTGOING {
helloMsg := msgHello{
KeepaliveInterval: p.keepaliveInterval,
}
if err := p.sendMessage(helloMsg); err != nil {
p.log().Errorf("Failed to send message: %v", err)
}
p.setState(HELLO_SENT)
}
for {
select {
case msg := <-p.rxHello:
p.log().Debugf("Received HELLO message")
p.processRxHello(msg)
case msg := <-p.rxKeepalive:
p.log().Tracef("Received KEEPALIVE message")
p.processRxKeepalive(msg)
case msg := <-p.rxSubscribe:
p.log().Debugf("Received SUBSCRIBE message")
p.processRxSubscribe(msg)
case msg := <-p.rxUnsubscribe:
p.log().Debugf("Received UNSUBSCRIBE message")
p.processRxUnsubscribe(msg)
case msg := <-p.rxUpdate:
p.log().Debugf("Received UPDATE message")
p.processRxUpdate(msg)
case <-p.shutdown:
p.cleanup()
return
}
}
}
func (p *metalBondPeer) rxLoop() {
p.wg.Add(1)
defer p.wg.Done()
buf := make([]byte, 65535)
for {
// TODO: read full packets!!!!
bytesRead, err := (*p.conn).Read(buf)
if p.GetState() == CLOSED || p.GetState() == RETRY {
return
}
if err != nil {
if err == io.EOF {
p.log().Infof("Connection closed by peer")
go p.Reset()
return
}
logrus.Errorf("Error reading from socket: %v", err)
go p.Reset()
return
}
if bytesRead >= len(buf) {
p.log().Warningf("too many messages in inbound queue. Closing connection.")
go p.Reset()
return
}
pktStart := 0
parsePacket:
pktVersion := buf[pktStart]
switch pktVersion {
case 1:
pktLen := uint16(buf[pktStart+1])<<8 + uint16(buf[pktStart+2])
pktType := MESSAGE_TYPE(buf[pktStart+3])
pktBytes := buf[pktStart+4 : pktStart+int(pktLen)+4]
pktStart += 4 + int(pktLen)
switch pktType {
case HELLO:
hello, err := deserializeHelloMsg(pktBytes)
if err != nil {
p.log().Errorf("Cannot deserialize HELLO message: %v", err)
go p.Reset()
return
}
p.rxHello <- *hello
case KEEPALIVE:
p.rxKeepalive <- msgKeepalive{}
case SUBSCRIBE:
sub, err := deserializeSubscribeMsg(pktBytes)
if err != nil {
p.log().Errorf("Cannot deserialize SUBSCRIBE message: %v", err)
go p.Reset()
return
}
p.rxSubscribe <- *sub
case UNSUBSCRIBE:
sub, err := deserializeUnsubscribeMsg(pktBytes)
if err != nil {
p.log().Errorf("Cannot deserialize UNSUBSCRIBE message: %v", err)
go p.Reset()
return
}
p.rxUnsubscribe <- *sub
case UPDATE:
upd, err := deserializeUpdateMsg(pktBytes)
if err != nil {
p.log().Errorf("Cannot deserialize UPDATE message: %v", err)
go p.Reset()
return
}
p.rxUpdate <- *upd
default:
p.log().Errorf("Unknown Packet received. Closing connection.")
return
}
default:
p.log().Errorf("Incompatible Client version. Closing connection.")
go p.Reset()
return
}
if pktStart < bytesRead {
goto parsePacket
}
}
}
func (p *metalBondPeer) processRxHello(msg msgHello) {
if msg.KeepaliveInterval < 1 {
p.log().Errorf("Keepalive Interval too low (%d)", msg.KeepaliveInterval)
p.Reset()
}
// Use lower Keepalive interval of both client and server as peer config
p.isServer = msg.IsServer
keepaliveInterval := p.keepaliveInterval
if msg.KeepaliveInterval < keepaliveInterval {
keepaliveInterval = msg.KeepaliveInterval
}
p.keepaliveInterval = keepaliveInterval
// state transition to HELLO_RECEIVED
p.setState(HELLO_RECEIVED)
p.log().Infof("HELLO message received")
go p.keepaliveLoop()
// if direction incoming, send HELLO response
if p.direction == INCOMING {
helloMsg := msgHello{
KeepaliveInterval: p.keepaliveInterval,
IsServer: p.metalbond.isServer,
}
if err := p.sendMessage(helloMsg); err != nil {
p.log().Errorf("Failed to send message: %v", err)
}
p.setState(HELLO_SENT)
p.log().Infof("HELLO message sent")
}
}
func (p *metalBondPeer) processRxKeepalive(msg msgKeepalive) {
if p.direction == INCOMING && p.GetState() == HELLO_SENT {
p.log().Infof("Connection established")
p.setState(ESTABLISHED)
} else if p.direction == OUTGOING && p.GetState() == HELLO_RECEIVED {
p.log().Infof("Connection established")
p.setState(ESTABLISHED)
} else if p.GetState() == ESTABLISHED {
// all good
} else {
p.log().Errorf("Received KEEPALIVE while in wrong state. Closing connection.")
go p.Reset()
return
}
p.resetKeepaliveTimeout()
// The server must respond incoming KEEPALIVE messages with an own KEEPALIVE message.
if p.direction == INCOMING {
if err := p.sendMessage(msgKeepalive{}); err != nil {
p.log().Errorf("Failed to send message: %v", err)
}
}
}
func (p *metalBondPeer) processRxSubscribe(msg msgSubscribe) {
p.log().Debugf("processRxSubscribe %#v", msg)
p.mtxSubscribedVNIs.Lock()
defer p.mtxSubscribedVNIs.Unlock()
p.subscribedVNIs[msg.VNI] = true
if err := p.metalbond.addSubscriber(p, msg.VNI); err != nil {
p.log().Errorf("Failed to add subscriber: %v", err)
}
}
func (p *metalBondPeer) processRxUnsubscribe(msg msgUnsubscribe) {
p.log().Debugf("processRxUnsubscribe %#v", msg)
if err := p.metalbond.removeSubscriber(p, msg.VNI); err != nil {
p.log().Errorf("Failed to remove subscriber: %v", err)
}
p.mtxSubscribedVNIs.RLock()
delete(p.subscribedVNIs, msg.VNI)
p.mtxSubscribedVNIs.RUnlock()
}
func (p *metalBondPeer) processRxUpdate(msg msgUpdate) {
var err error
switch msg.Action {
case ADD:
err = p.receivedRoutes.AddNextHop(msg.VNI, msg.Destination, msg.NextHop, p)
if err != nil {
p.log().Errorf("Could not add received route (%v -> %v) to peer's receivedRoutes Table: %v", msg.Destination, msg.NextHop, err)
return
}
err = p.metalbond.addReceivedRoute(p, msg.VNI, msg.Destination, msg.NextHop)
if err != nil {
p.log().Errorf("Could not process received route UPDATE ADD: %v", err)
}
case REMOVE:
err, _ = p.receivedRoutes.RemoveNextHop(msg.VNI, msg.Destination, msg.NextHop, p)
if err != nil {
p.log().Errorf("Could not remove received route from peer's receivedRoutes Table: %v", err)
return
}
err = p.metalbond.removeReceivedRoute(p, msg.VNI, msg.Destination, msg.NextHop)
if err != nil {
p.log().Errorf("Could not process received route UPDATE REMOVE: %v", err)
}
default:
p.log().Errorf("Received UPDATE message with invalid action type!")
}
}
func (p *metalBondPeer) Close() {
p.log().Debug("Close")
if p.GetState() != CLOSED {
p.setState(CLOSED)
p.txChanClose <- true
p.shutdown <- true
p.keepaliveStop <- true
}
}
func (p *metalBondPeer) Reset() {
p.log().Debugf("Reset")
p.mtxReset.RLock()
defer p.mtxReset.RUnlock()
if p.GetState() == CLOSED {
p.log().Debug("State is closed")
return
}
switch p.direction {
case INCOMING:
// incoming connections are closed by the server
// in order to avoid stale peer threads
p.Close()
if err := p.metalbond.RemovePeer(p.remoteAddr); err != nil {
p.log().Errorf("Failed to remove peer: %v", err)
}
case OUTGOING:
p.log().Infof("Resetting connection...")
p.setState(RETRY)
p.txChanClose <- true
p.shutdown <- true
p.keepaliveStop <- true
p.wg.Wait()
p.conn = nil
p.localAddr = ""
retry := time.Duration(rand.Intn(RetryIntervalMax)+RetryIntervalMin) * time.Second
p.log().Infof("Closed. Waiting %s...", retry)
time.Sleep(retry)
p.setState(CONNECTING)
p.log().Infof("Reconnecting...")
go p.handle()
}
}
func (p *metalBondPeer) keepaliveLoop() {
p.wg.Add(1)
defer p.wg.Done()
timeout := time.Duration(p.keepaliveInterval) * time.Second * 5 / 2
p.log().Infof("KEEPALIVE timeout: %v", timeout)
p.keepaliveTimer = time.NewTimer(timeout)
interval := time.Duration(p.keepaliveInterval) * time.Second
tckr := time.NewTicker(interval)
// Sending initial KEEPALIVE message
if p.direction == OUTGOING {
if err := p.sendMessage(msgKeepalive{}); err != nil {
p.log().Errorf("Failed to send message: %v", err)
}
}
for {
select {
// Ticker triggers sending KEEPALIVE messages
case <-tckr.C:
if p.direction == OUTGOING {
if err := p.sendMessage(msgKeepalive{}); err != nil {
p.log().Errorf("Failed to send message: %v", err)
}
}
// Timer detects KEEPALIVE timeouts
case <-p.keepaliveTimer.C:
p.log().Infof("Connection timed out. Closing.")
go p.Reset()
// keepaliveStop chan delivers message to stop this routine
case <-p.keepaliveStop:
p.log().Tracef("Stopping keepaliveLoop")
p.keepaliveTimer.Stop()
return
}
}
}
func (p *metalBondPeer) resetKeepaliveTimeout() {
if p.keepaliveTimer != nil {
p.keepaliveTimer.Reset(time.Duration(p.keepaliveInterval) * time.Second * 5 / 2)
}
}
func (p *metalBondPeer) sendMessage(msg message) error {
p.log().Tracef("sendMessage")
if p.GetState() == CLOSED {
err := errors.New("State is closed")
p.log().Debug(err)
return err
}
var msgType MESSAGE_TYPE
switch msg.(type) {
case msgHello:
msgType = HELLO
p.log().Debugf("Sending HELLO message")
case msgKeepalive:
msgType = KEEPALIVE
p.log().Tracef("Sending KEEPALIVE message")
case msgSubscribe:
msgType = SUBSCRIBE
p.log().Debugf("Sending SUBSCRIBE message")
case msgUnsubscribe:
msgType = UNSUBSCRIBE
p.log().Debugf("Sending UNSUBSCRIBE message")
case msgUpdate:
msgType = UPDATE
p.log().Debugf("Sending UPDATE message")
default:
return fmt.Errorf("Unknown message type")
}
msgBytes, err := msg.Serialize()
if err != nil {
return fmt.Errorf("Could not serialize message: %v", err)
}
hdr := []byte{1, byte(len(msgBytes) >> 8), byte(len(msgBytes) % 256), byte(msgType)}
pkt := append(hdr, msgBytes...)
p.txChan <- pkt
return nil
}
func (p *metalBondPeer) txLoop() {
p.wg.Add(1)
defer p.wg.Done()
for {
select {
case msg := <-p.txChan:
n, err := (*p.conn).Write(msg)
if n != len(msg) || err != nil {
p.log().Errorf("Could not transmit message completely: %v", err)
go p.Reset()
}
case <-p.txChanClose:
p.log().Debugf("Closing TCP connection")
(*p.conn).Close()
return
}
}
}