forked from weaveworks/weave
/
fastdp.go
1413 lines (1183 loc) · 36.4 KB
/
fastdp.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 router
import (
"encoding/binary"
"encoding/json"
"fmt"
"net"
"sync"
"syscall"
"time"
"github.com/pkg/errors"
"github.com/vishvananda/netlink"
"github.com/weaveworks/go-odp/odp"
"github.com/weaveworks/mesh"
"github.com/weaveworks/weave/net/ipsec"
)
// The virtual bridge accepts packets from ODP vports and the router
// port (i.e. InjectPacket). We need a map key to index those
// possibilities:
type bridgePortID struct {
vport odp.VportID
router bool
}
// A bridgeSender sends out a packet from the virtual bridge
type bridgeSender func(key PacketKey, lock *fastDatapathLock) FlowOp
// A missHandler handles an ODP miss
type missHandler func(fks odp.FlowKeys, lock *fastDatapathLock) FlowOp
type FastDatapath struct {
lock sync.Mutex // guards state and synchronises use of dpif
iface *net.Interface
dpif *odp.Dpif
dp odp.DatapathHandle
deleteFlowsCount uint64
missCount uint64
missHandlers map[odp.VportID]missHandler
localPeer *mesh.Peer
peers *mesh.Peers
overlayConsumer OverlayConsumer
ipsec *ipsec.IPSec
// Bridge state: How to send to the given bridge port
sendToPort map[bridgePortID]bridgeSender
// How to send to a given destination MAC
sendToMAC map[MAC]bridgeSender
// MACs seen on the bridge recently
seenMACs map[MAC]struct{}
// vxlan vports associated with the given UDP ports
vxlanUDPPorts map[int]odp.VportID
vxlanVportIDs map[odp.VportID]struct{}
mainVxlanVportID odp.VportID
mainVxlanUDPPort int
// A singleton pool for the occasions when we need to decode
// the packet.
dec *EthernetDecoder
// forwarders by remote peer
forwarders map[mesh.PeerName]*fastDatapathForwarder
}
func NewFastDatapath(iface *net.Interface, port int, encryptionEnabled bool) (*FastDatapath, error) {
var ipSec *ipsec.IPSec
dpif, err := odp.NewDpif()
if err != nil {
return nil, err
}
success := false
defer func() {
if !success {
dpif.Close()
}
}()
dp, err := dpif.LookupDatapath(iface.Name)
if err != nil {
return nil, err
}
if encryptionEnabled {
var err error
if ipSec, err = ipsec.New(log); err != nil {
return nil, errors.Wrap(err, "ipsec new")
}
if err := ipSec.Flush(false); err != nil {
return nil, errors.Wrap(err, "ipsec flush")
}
}
fastdp := &FastDatapath{
iface: iface,
dpif: dpif,
dp: dp,
missHandlers: make(map[odp.VportID]missHandler),
ipsec: ipSec,
sendToPort: nil,
sendToMAC: make(map[MAC]bridgeSender),
seenMACs: make(map[MAC]struct{}),
vxlanUDPPorts: make(map[int]odp.VportID),
vxlanVportIDs: make(map[odp.VportID]struct{}),
forwarders: make(map[mesh.PeerName]*fastDatapathForwarder),
}
// This delete happens asynchronously in the kernel, meaning that
// we can sometimes fail to recreate the vxlan vport with EADDRINUSE -
// consequently we retry a small number of times in
// getVxlanVportIDHarder() to compensate.
if err := fastdp.deleteVxlanVports(); err != nil {
return nil, err
}
if err := fastdp.deleteFlows(); err != nil {
return nil, err
}
// We use the weave port number plus 1 for vxlan. Hard-coding
// this relationship may seem dubious, but there is no moral
// difference between this and requiring that the sleeve UDP
// port number is the same as the TCP port number. The hard
// part would be not adding weaver flags to allow the port
// numbers to be independent, but working out how to specify
// them on the connecting side. So we can wait to find out if
// anyone wants that.
fastdp.mainVxlanUDPPort = port + 1
fastdp.mainVxlanVportID, err = fastdp.getVxlanVportIDHarder(fastdp.mainVxlanUDPPort, 5, time.Millisecond*10)
if err != nil {
return nil, err
}
// need to lock before we might receive events
fastdp.lock.Lock()
defer fastdp.lock.Unlock()
if _, err := dp.ConsumeMisses(fastdp); err != nil {
return nil, err
}
if _, err := dp.ConsumeVportEvents(fastdp); err != nil {
return nil, err
}
vports, err := dp.EnumerateVports()
if err != nil {
return nil, err
}
for _, vport := range vports {
fastdp.makeBridgeVport(vport)
}
success = true
go fastdp.run()
return fastdp, nil
}
func (fastdp *FastDatapath) Close() error {
fastdp.lock.Lock()
defer fastdp.lock.Unlock()
err := fastdp.dpif.Close()
fastdp.dpif = nil
return err
}
// While processing a packet, we can potentially acquire and drop the
// FastDatapath lock many times (acquiring it to acceess FastDatapath
// state, and invoke ODP operations; dropping it to invoke callbacks
// that may re-enter the FastDatapath). A fastDatapathLock
// coordinates this process.
type fastDatapathLock struct {
fastdp *FastDatapath
locked bool
// While the lock is dropped, deleteFlows could be called. We
// need to detect when this happens and avoid creating flows,
// because they may be based on stale information.
deleteFlowsCount uint64
}
func (fastdp *FastDatapath) startLock() fastDatapathLock {
fastdp.lock.Lock()
return fastDatapathLock{
fastdp: fastdp,
locked: true,
deleteFlowsCount: fastdp.deleteFlowsCount,
}
}
func (lock *fastDatapathLock) unlock() {
if lock.locked {
lock.fastdp.lock.Unlock()
lock.locked = false
}
}
func (lock *fastDatapathLock) relock() {
if !lock.locked {
lock.fastdp.lock.Lock()
lock.locked = true
}
}
// InjectorConsumer bits
type fastDatapathInjectorConsumer struct {
*FastDatapath
}
func (fastdp *FastDatapath) InjectorConsumer() InjectorConsumer {
return fastDatapathInjectorConsumer{fastdp}
}
func (fastdp fastDatapathInjectorConsumer) Interface() *net.Interface {
return fastdp.iface
}
func (fastdp fastDatapathInjectorConsumer) String() string {
return fmt.Sprint(fastdp.iface.Name, " (via ODP)")
}
func (fastdp fastDatapathInjectorConsumer) Stats() map[string]int {
lock := fastdp.startLock()
defer lock.unlock()
return map[string]int{
"FlowMisses": int(fastdp.missCount),
}
}
var routerBridgePortID = bridgePortID{router: true}
func (fastdp fastDatapathInjectorConsumer) StartConsumingPackets(consumer Consumer) error {
fastdp.lock.Lock()
defer fastdp.lock.Unlock()
if fastdp.sendToPort[routerBridgePortID] != nil {
return fmt.Errorf("FastDatapath already has a Consumer")
}
// set up delivery to the weave router port on the bridge
fastdp.addSendToPort(routerBridgePortID,
func(key PacketKey, lock *fastDatapathLock) FlowOp {
// drop the FastDatapath lock in order to call
// the consumer
lock.unlock()
return consumer(key)
})
return nil
}
func (fastdp fastDatapathInjectorConsumer) InjectPacket(key PacketKey) FlowOp {
lock := fastdp.startLock()
defer lock.unlock()
return fastdp.bridge(routerBridgePortID, key, &lock)
}
// Ethernet bridge implementation
func (fastdp *FastDatapath) bridge(ingress bridgePortID, key PacketKey, lock *fastDatapathLock) FlowOp {
lock.relock()
if fastdp.sendToMAC[key.SrcMAC] == nil {
// Learn the source MAC
fastdp.sendToMAC[key.SrcMAC] = fastdp.sendToPort[ingress]
fastdp.seenMACs[key.SrcMAC] = struct{}{}
}
// If we know about the destination MAC, deliver it to the
// associated port.
if sender := fastdp.sendToMAC[key.DstMAC]; sender != nil {
return NewMultiFlowOp(false, odpEthernetFlowKey(key), sender(key, lock))
}
// Otherwise, it might be a real broadcast, or it might
// be for a MAC we don't know about yet. Either way, we'll
// broadcast it.
mfop := NewMultiFlowOp(false)
if (key.DstMAC[0] & 1) == 0 {
// Not a real broadcast, so don't create a flow rule.
// If we did, we'd need to delete the flows every time
// we learned a new MAC address, or have a more
// complicated selective invalidation scheme.
log.Debug("fastdp: unknown dst", ingress, key)
mfop.Add(vetoFlowCreationFlowOp{})
} else {
// A real broadcast
log.Debug("fastdp: broadcast", ingress, key)
mfop.Add(odpEthernetFlowKey(key))
}
// Send to all ports except the one it came in on. The
// sendToPort map is immutable, so it is safe to iterate over
// it even though the sender functions can drop the
// fastDatapathLock
for id, sender := range fastdp.sendToPort {
if id != ingress {
mfop.Add(sender(key, lock))
}
}
return mfop
}
// Overlay bits
type fastDatapathOverlay struct {
*FastDatapath
}
func (fastdp *FastDatapath) Overlay() NetworkOverlay {
return fastDatapathOverlay{fastdp}
}
func (fastdp fastDatapathOverlay) InvalidateRoutes() {
log.Debug("InvalidateRoutes")
fastdp.lock.Lock()
defer fastdp.lock.Unlock()
checkWarn(fastdp.deleteFlows())
}
func (fastdp fastDatapathOverlay) InvalidateShortIDs() {
log.Debug("InvalidateShortIDs")
fastdp.lock.Lock()
defer fastdp.lock.Unlock()
checkWarn(fastdp.deleteFlows())
}
func (fastdp fastDatapathOverlay) Stop() {
if fastdp.ipsec != nil {
if err := fastdp.ipsec.Flush(true); err != nil {
log.Errorf("ipsec flush failed: %s", err)
}
}
}
func (fastDatapathOverlay) AddFeaturesTo(features map[string]string) {
// Nothing needed. Fast datapath support is indicated through
// OverlaySwitch.
}
type FastDPStatus struct {
Vports []VportStatus
Flows []FlowStatus
}
type FlowStatus odp.FlowInfo
func (flowStatus *FlowStatus) MarshalJSON() ([]byte, error) {
type jsonFlowStatus struct {
FlowKeys []string
Actions []string
Packets uint64
Bytes uint64
Used uint64
}
flowKeys := make([]string, 0, len(flowStatus.FlowKeys))
for _, flowKey := range flowStatus.FlowKeys {
if !flowKey.Ignored() {
flowKeys = append(flowKeys, fmt.Sprint(flowKey))
}
}
actions := make([]string, 0, len(flowStatus.Actions))
for _, action := range flowStatus.Actions {
actions = append(actions, fmt.Sprint(action))
}
return json.Marshal(&jsonFlowStatus{flowKeys, actions, flowStatus.Packets, flowStatus.Bytes, flowStatus.Used})
}
type VportStatus odp.Vport
func (vport *VportStatus) MarshalJSON() ([]byte, error) {
type jsonVportStatus struct {
ID odp.VportID
Name string
TypeName string
}
return json.Marshal(&jsonVportStatus{vport.ID, vport.Spec.Name(), vport.Spec.TypeName()})
}
func (fastdp fastDatapathOverlay) Diagnostics() interface{} {
lock := fastdp.startLock()
defer lock.unlock()
vports, err := fastdp.dp.EnumerateVports()
checkWarn(err)
vportStatuses := make([]VportStatus, 0, len(vports))
for _, vport := range vports {
vportStatuses = append(vportStatuses, VportStatus(vport))
}
flows, err := fastdp.dp.EnumerateFlows()
checkWarn(err)
flowStatuses := make([]FlowStatus, 0, len(flows))
for _, flow := range flows {
flowStatuses = append(flowStatuses, FlowStatus(flow))
}
return FastDPStatus{
vportStatuses,
flowStatuses,
}
}
type FastDPMetrics struct {
Flows int
TotalPackets uint64
TotalBytes uint64
}
func (s FastDPStatus) Metrics() interface{} {
var m FastDPMetrics
m.Flows = len(s.Flows)
for _, flow := range s.Flows {
m.TotalPackets += flow.Packets
m.TotalBytes += flow.Bytes
}
return &m
}
func (fastdp fastDatapathOverlay) StartConsumingPackets(localPeer *mesh.Peer, peers *mesh.Peers, consumer OverlayConsumer) error {
fastdp.lock.Lock()
defer fastdp.lock.Unlock()
if fastdp.overlayConsumer != nil {
return fmt.Errorf("FastDatapath already has an OverlayConsumer")
}
fastdp.localPeer = localPeer
fastdp.peers = peers
fastdp.overlayConsumer = consumer
return nil
}
func (fastdp *FastDatapath) getVxlanVportIDHarder(udpPort int, retries int, duration time.Duration) (odp.VportID, error) {
var vxlanVportID odp.VportID
var err error
for try := 0; try < retries; try++ {
vxlanVportID, err = fastdp.getVxlanVportID(udpPort)
if err == nil || err != odp.NetlinkError(syscall.EADDRINUSE) {
return vxlanVportID, err
}
log.Warning("Address already in use creating vxlan vport ", udpPort, " - retrying")
time.Sleep(duration)
}
return 0, err
}
func (fastdp *FastDatapath) getVxlanVportID(udpPort int) (odp.VportID, error) {
fastdp.lock.Lock()
defer fastdp.lock.Unlock()
if vxlanVportID, present := fastdp.vxlanUDPPorts[udpPort]; present {
return vxlanVportID, nil
}
name := fmt.Sprintf("vxlan-%d", udpPort)
vxlanVportID, err := fastdp.dp.CreateVport(
odp.NewVxlanVportSpec(name, uint16(udpPort)))
if err != nil {
return 0, err
}
// If a netdev for the vxlan vport exists, we need to do an extra check
// to bypass the kernel bug which makes the vxlan creation to complete
// successfully regardless whether there were any errors when binding
// to the given UDP port.
if link, err := netlink.LinkByName(name); err == nil {
if link.Attrs().Flags&net.FlagUp == 0 {
// The netdev interface is down, so most likely bringing it up
// has failed due to the UDP port being in use.
if err := fastdp.dp.DeleteVport(vxlanVportID); err != nil {
log.Warningf("Unable to remove vxlan vport %d: %s", vxlanVportID, err)
}
return 0, odp.NetlinkError(syscall.EADDRINUSE)
}
}
fastdp.vxlanUDPPorts[udpPort] = vxlanVportID
fastdp.vxlanVportIDs[vxlanVportID] = struct{}{}
fastdp.missHandlers[vxlanVportID] = func(fks odp.FlowKeys, lock *fastDatapathLock) FlowOp {
log.Debug("ODP miss: ", fks, " on port ", vxlanVportID)
tunnel := fks[odp.OVS_KEY_ATTR_TUNNEL].(odp.TunnelFlowKey)
tunKey := tunnel.Key()
lock.relock()
consumer := fastdp.overlayConsumer
if consumer == nil {
return vetoFlowCreationFlowOp{}
}
srcPeer, dstPeer := fastdp.extractPeers(tunKey.TunnelId)
if srcPeer == nil || dstPeer == nil {
return vetoFlowCreationFlowOp{}
}
lock.unlock()
pk := flowKeysToPacketKey(fks)
var zeroMAC MAC
if pk.SrcMAC == zeroMAC && pk.DstMAC == zeroMAC {
return vxlanSpecialPacketFlowOp{
fastdp: fastdp,
srcPeer: srcPeer,
sender: &net.UDPAddr{
IP: net.IP(tunKey.Ipv4Src[:]),
Port: udpPort,
},
}
}
key := ForwardPacketKey{
SrcPeer: srcPeer,
DstPeer: dstPeer,
PacketKey: pk,
}
var tunnelFlowKey odp.TunnelFlowKey
tunnelFlowKey.SetTunnelId(tunKey.TunnelId)
tunnelFlowKey.SetIpv4Src(tunKey.Ipv4Src)
tunnelFlowKey.SetIpv4Dst(tunKey.Ipv4Dst)
return NewMultiFlowOp(false, odpFlowKey(tunnelFlowKey), consumer(key))
}
return vxlanVportID, nil
}
func (fastdp *FastDatapath) extractPeers(tunnelID [8]byte) (*mesh.Peer, *mesh.Peer) {
vni := binary.BigEndian.Uint64(tunnelID[:])
srcPeer := fastdp.peers.FetchByShortID(mesh.PeerShortID(vni & 0xfff))
dstPeer := fastdp.peers.FetchByShortID(mesh.PeerShortID((vni >> 12) & 0xfff))
return srcPeer, dstPeer
}
type vxlanSpecialPacketFlowOp struct {
NonDiscardingFlowOp
fastdp *FastDatapath
srcPeer *mesh.Peer
sender *net.UDPAddr
}
func (op vxlanSpecialPacketFlowOp) Process(frame []byte, dec *EthernetDecoder, broadcast bool) {
op.fastdp.lock.Lock()
fwd := op.fastdp.forwarders[op.srcPeer.Name]
op.fastdp.lock.Unlock()
if fwd != nil && dec.IsSpecial() {
fwd.handleVxlanSpecialPacket(frame, op.sender)
}
}
type fastDatapathForwarder struct {
fastdp *FastDatapath
remotePeer *mesh.Peer
localIP [4]byte
sendControlMsg func(byte, []byte) error
connUID uint64
vxlanVportID odp.VportID
sessionKey *[32]byte
isEncrypted bool
isOutboundIPSecEstablished bool
lock sync.RWMutex
confirmed bool
remoteAddr *net.UDPAddr
heartbeatInterval time.Duration
heartbeatTimer *time.Timer // for sending
heartbeatTimeout *time.Timer // for receiving
ackedHeartbeat bool
stopChan chan struct{}
stopped bool
healthy bool
established bool
establishedChan chan struct{}
errorChan chan error
healthChan chan bool
}
func (fastdp fastDatapathOverlay) PrepareConnection(params mesh.OverlayConnectionParams) (mesh.OverlayConnection, error) {
vxlanVportID := fastdp.mainVxlanVportID
vxlanUDPPort := fastdp.mainVxlanUDPPort
remoteAddr := makeUDPAddr(params.RemoteAddr)
if params.Outbound {
var err error
// The provided address contains the main weave port
// number to connect to. We need to derive the vxlan
// port number from that.
vxlanRemoteAddr := *remoteAddr
vxlanRemoteAddr.Port++
remoteAddr = &vxlanRemoteAddr
vxlanUDPPort = remoteAddr.Port
vxlanVportID, err = fastdp.getVxlanVportID(vxlanUDPPort)
if err != nil {
return nil, err
}
} else {
remoteAddr.Port = vxlanUDPPort
}
localIP, err := ipv4Bytes(params.LocalAddr.IP)
if err != nil {
return nil, err
}
fwd := &fastDatapathForwarder{
fastdp: fastdp.FastDatapath,
remotePeer: params.RemotePeer,
localIP: localIP,
sendControlMsg: params.SendControlMessage,
connUID: params.ConnUID,
vxlanVportID: vxlanVportID,
sessionKey: params.SessionKey,
healthy: true,
remoteAddr: remoteAddr,
heartbeatInterval: FastHeartbeat,
stopChan: make(chan struct{}),
establishedChan: make(chan struct{}),
errorChan: make(chan error, 1),
healthChan: make(chan bool),
}
return fwd, nil
}
func ipv4Bytes(ip net.IP) (res [4]byte, err error) {
ipv4 := ip.To4()
if ipv4 != nil {
copy(res[:], ipv4)
} else {
err = fmt.Errorf("IP address %s is not IPv4", ip)
}
return
}
func (fwd *fastDatapathForwarder) logPrefix() string {
return fmt.Sprintf("fastdp ->[%s|%s]: ", fwd.remoteAddr, fwd.remotePeer)
}
func (fwd *fastDatapathForwarder) Confirm() {
fwd.lock.Lock()
if fwd.confirmed {
log.Fatal(fwd.logPrefix(), "already confirmed")
}
var controlMsg []byte
if fwd.fastdp.ipsec != nil && fwd.sessionKey != nil {
fwd.isEncrypted = true
log.Info("Setting up IPsec between ", fwd.fastdp.localPeer, " and ", fwd.remotePeer)
var err error
controlMsg, err = fwd.fastdp.ipsec.InitSALocal(
fwd.fastdp.localPeer.Name, fwd.remotePeer.Name, fwd.connUID,
net.IP(fwd.localIP[:]), fwd.remoteAddr.IP,
fwd.remoteAddr.Port,
fwd.sessionKey,
)
if err != nil {
log.Error(fwd.logPrefix(), "ipsec init SA local failed: ", err)
fwd.handleError(err)
fwd.lock.Unlock()
return
}
}
log.Debug(fwd.logPrefix(), "confirmed")
fwd.fastdp.addForwarder(fwd.remotePeer.Name, fwd)
fwd.confirmed = true
if fwd.remoteAddr != nil && (!fwd.isEncrypted || fwd.isOutboundIPSecEstablished) {
// have the goroutine send a heartbeat straight away
fwd.heartbeatTimer = time.NewTimer(0)
} else {
// we'll reset the timer when we learn the remote ip
fwd.heartbeatTimer = time.NewTimer(MaxDuration)
}
fwd.heartbeatTimeout = time.NewTimer(HeartbeatTimeout)
fwd.lock.Unlock() // unlock before calling send() which may block
if len(controlMsg) > 0 {
if err := fwd.sendControlMsg(FastDatapathCryptoInitSARemote, controlMsg); err != nil {
log.Error(fwd.logPrefix(), "ipsec send InitSARemote failed: ", err)
fwd.handleError(err)
return
}
}
go fwd.doHeartbeats()
}
func (fwd *fastDatapathForwarder) EstablishedChannel() <-chan struct{} {
return fwd.establishedChan
}
func (fwd *fastDatapathForwarder) ErrorChannel() <-chan error {
return fwd.errorChan
}
func (fwd *fastDatapathForwarder) HealthChannel() <-chan bool {
return fwd.healthChan
}
func (fwd *fastDatapathForwarder) doHeartbeats() {
var err error
for err == nil {
select {
case <-fwd.heartbeatTimer.C:
if fwd.confirmed {
log.Debug(fwd.logPrefix(), "sending Heartbeat to peer")
fwd.sendHeartbeat()
}
fwd.heartbeatTimer.Reset(fwd.heartbeatInterval)
case <-fwd.heartbeatTimeout.C:
log.Debug(fwd.logPrefix(), "missed Heartbeat from peer, marking fastdp forwarder as un-healthy")
// treat missed heartbeat as transient error. Indicate to overlay forwarder
// that Forwarder is un-healthy so it can pick next best forwarder
fwd.healthChan <- false
// switch from fast-heartbeat to slow-heartbeat to avoid aggressive heartbeats
// when there is no estbalished session with peer yet
if fwd.heartbeatInterval != SlowHeartbeat {
fwd.heartbeatInterval = SlowHeartbeat
if fwd.heartbeatTimer != nil {
fwd.heartbeatTimer.Reset(fwd.heartbeatInterval)
}
}
if fwd.healthy {
fwd.healthy = false
}
case <-fwd.stopChan:
return
}
}
fwd.lock.Lock()
defer fwd.lock.Unlock()
fwd.handleError(err)
}
// Handle an error which leads to notifying the listener and
// termination of the forwarder
func (fwd *fastDatapathForwarder) handleError(err error) {
if err == nil {
return
}
select {
case fwd.errorChan <- err:
default:
}
// stop the heartbeat goroutine
if !fwd.stopped {
fwd.stopped = true
close(fwd.stopChan)
}
}
func (fwd *fastDatapathForwarder) sendHeartbeat() {
fwd.lock.RLock()
// the heartbeat payload consists of the 64-bit connection uid
// followed by the 16-bit packet size.
buf := make([]byte, EthernetOverhead+fwd.fastdp.iface.MTU)
binary.BigEndian.PutUint64(buf[EthernetOverhead:], fwd.connUID)
binary.BigEndian.PutUint16(buf[EthernetOverhead+8:], uint16(len(buf)))
dec := NewEthernetDecoder()
dec.DecodeLayers(buf)
pk := ForwardPacketKey{
PacketKey: dec.PacketKey(),
SrcPeer: fwd.fastdp.localPeer,
DstPeer: fwd.remotePeer,
}
fwd.lock.RUnlock()
if fop := fwd.Forward(pk); fop != nil {
fop.Process(buf, dec, false)
}
}
const (
FastDatapathHeartbeatAck = iota
FastDatapathCryptoInitSARemote
)
func (fwd *fastDatapathForwarder) handleVxlanSpecialPacket(frame []byte, sender *net.UDPAddr) {
fwd.lock.Lock()
defer fwd.lock.Unlock()
log.Debug(fwd.logPrefix(), "handleVxlanSpecialPacket")
// the only special packet type is a heartbeat
if len(frame) < EthernetOverhead+10 {
log.Warning(fwd.logPrefix(), "short vxlan special packet: ", len(frame), " bytes")
return
}
if binary.BigEndian.Uint64(frame[EthernetOverhead:]) != fwd.connUID ||
uint16(len(frame)) != binary.BigEndian.Uint16(frame[EthernetOverhead+8:]) {
return
}
if fwd.remoteAddr == nil {
fwd.remoteAddr = sender
if fwd.confirmed {
fwd.heartbeatTimer.Reset(0)
}
} else if !udpAddrsEqual(fwd.remoteAddr, sender) {
log.Info(fwd.logPrefix(), "Peer IP address changed to ", sender)
fwd.remoteAddr = sender
}
if !fwd.ackedHeartbeat {
fwd.ackedHeartbeat = true
log.Debug(fwd.logPrefix(), "Ack Heartbeat from peer")
fwd.handleError(fwd.sendControlMsg(FastDatapathHeartbeatAck, nil))
} else {
log.Debug(fwd.logPrefix(), "Got Heartbeat Ack from peer")
}
// we can receive a heartbeat before Confirm() has set up
// heartbeatTimeout
if fwd.heartbeatTimeout != nil {
fwd.heartbeatTimeout.Reset(HeartbeatTimeout)
if !fwd.healthy {
// If fastdp was marked as unhealthy earlier due to missed heartbeat then indicate to
// overlay forwarder that Forwarder is healthy now so it can pick next best forwarder
log.Debug(fwd.logPrefix(), "got Heartbeat from peer, marking fastdp forwarder as healthy")
fwd.healthy = true
fwd.healthChan <- true
}
}
}
func (fwd *fastDatapathForwarder) ControlMessage(tag byte, msg []byte) {
fwd.lock.Lock()
defer fwd.lock.Unlock()
switch tag {
case FastDatapathHeartbeatAck:
fwd.handleHeartbeatAck()
case FastDatapathCryptoInitSARemote:
fwd.handleCryptoInitSARemote(msg)
default:
log.Info(fwd.logPrefix(), "Ignoring unknown control message: ", tag)
}
}
func (fwd *fastDatapathForwarder) Attrs() map[string]interface{} {
return map[string]interface{}{"name": "fastdp", "mtu": fwd.fastdp.iface.MTU}
}
func (fwd *fastDatapathForwarder) handleHeartbeatAck() {
log.Debug(fwd.logPrefix(), "handleHeartbeatAck")
if !fwd.established {
close(fwd.establishedChan)
fwd.established = true
}
if fwd.heartbeatInterval != SlowHeartbeat {
fwd.heartbeatInterval = SlowHeartbeat
if fwd.heartbeatTimer != nil {
fwd.heartbeatTimer.Reset(fwd.heartbeatInterval)
}
}
}
func (fwd *fastDatapathForwarder) handleCryptoInitSARemote(msg []byte) {
if fwd.stopped {
log.Info(fwd.logPrefix(), "IPSec init SA remote failed: forwarder has already been stopped")
return
}
log.Info(fwd.logPrefix(), "IPSec init SA remote")
err := fwd.fastdp.ipsec.InitSARemote(
msg,
fwd.fastdp.localPeer.Name, fwd.remotePeer.Name, fwd.connUID,
net.IP(fwd.localIP[:]), fwd.remoteAddr.IP, fwd.remoteAddr.Port,
fwd.sessionKey,
)
if err != nil {
log.Warning(fwd.logPrefix(), "IPSec init SA remote failed: ", err)
fwd.handleError(err)
return
}
// FastDatapathCryptoInitSARemote can be received before Confirm'ing
// connection, thus before InitSALocal.
if fwd.confirmed && !fwd.isOutboundIPSecEstablished {
fwd.isOutboundIPSecEstablished = true
fwd.heartbeatTimer.Reset(0)
}
}
func (fwd *fastDatapathForwarder) Forward(key ForwardPacketKey) FlowOp {
if !key.SrcPeer.HasShortID || !key.DstPeer.HasShortID {
return nil
}
fwd.lock.RLock()
defer fwd.lock.RUnlock()
if fwd.remoteAddr == nil {
// Returning a DiscardingFlowOp would discard the
// packet, but also result in a flow rule, which we
// would have to invalidate when we learn the remote
// IP. So for now, just prevent flows.
return vetoFlowCreationFlowOp{}
}
remoteIP, err := ipv4Bytes(fwd.remoteAddr.IP)
if err != nil {
log.Error(err)
return DiscardingFlowOp{}
}
var sta odp.SetTunnelAction
sta.SetTunnelId(tunnelIDFor(key))
sta.SetIpv4Src(fwd.localIP)
sta.SetIpv4Dst(remoteIP)
sta.SetTos(0)
sta.SetTtl(64)
sta.SetDf(true)
sta.SetCsum(false)
return fwd.fastdp.odpActions(sta, odp.NewOutputAction(fwd.vxlanVportID))
}
func tunnelIDFor(key ForwardPacketKey) (tunnelID [8]byte) {
src := uint64(key.SrcPeer.ShortID)
dst := uint64(key.DstPeer.ShortID)
binary.BigEndian.PutUint64(tunnelID[:], src|dst<<12)
return
}
func (fwd *fastDatapathForwarder) Stop() {
// Might be nice to delete all the relevant flows here, but we
// can just let them expire.
fwd.fastdp.removeForwarder(fwd.remotePeer.Name, fwd)
fwd.lock.Lock()
defer fwd.lock.Unlock()
fwd.sendControlMsg = func(byte, []byte) error { return nil }
if fwd.isEncrypted {
localIP := net.IP(fwd.localIP[:])
log.Info("Destroying IPsec between ", fwd.fastdp.localPeer, " and ", fwd.remotePeer)
err := fwd.fastdp.ipsec.Destroy(
fwd.fastdp.localPeer.Name, fwd.remotePeer.Name, fwd.connUID,
localIP, fwd.remoteAddr.IP, fwd.remoteAddr.Port,
)
if err != nil {
log.Errorf("ipsec destroy failed: %s", err)
}
}
// stop the heartbeat goroutine
if !fwd.stopped {
fwd.stopped = true
close(fwd.stopChan)
}
}
func (fastdp *FastDatapath) addForwarder(peer mesh.PeerName, fwd *fastDatapathForwarder) {
fastdp.lock.Lock()
defer fastdp.lock.Unlock()
// We shouldn't have two confirmed forwarders to the same
// remotePeer, due to the checks in LocalPeer AddConnection.
fastdp.forwarders[peer] = fwd
}
func (fastdp *FastDatapath) removeForwarder(peer mesh.PeerName, fwd *fastDatapathForwarder) {
fastdp.lock.Lock()
defer fastdp.lock.Unlock()
if fastdp.forwarders[peer] == fwd {