forked from ligato/vpp-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
interface.go
1144 lines (1027 loc) · 38.8 KB
/
interface.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
// Copyright (c) 2018 Cisco and/or its affiliates.
//
// 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 descriptor
import (
"fmt"
"io/ioutil"
"net"
"path/filepath"
"strconv"
"strings"
"github.com/vishvananda/netlink"
"golang.org/x/sys/unix"
"go.ligato.io/vpp-agent/v3/pkg/models"
"github.com/golang/protobuf/proto"
prototypes "github.com/golang/protobuf/ptypes/empty"
"github.com/pkg/errors"
"go.ligato.io/cn-infra/v2/idxmap"
"go.ligato.io/cn-infra/v2/logging"
"go.ligato.io/cn-infra/v2/logging/logrus"
"go.ligato.io/cn-infra/v2/servicelabel"
kvs "go.ligato.io/vpp-agent/v3/plugins/kvscheduler/api"
"go.ligato.io/vpp-agent/v3/plugins/linux/ifplugin/descriptor/adapter"
"go.ligato.io/vpp-agent/v3/plugins/linux/ifplugin/ifaceidx"
iflinuxcalls "go.ligato.io/vpp-agent/v3/plugins/linux/ifplugin/linuxcalls"
"go.ligato.io/vpp-agent/v3/plugins/linux/nsplugin"
nsdescriptor "go.ligato.io/vpp-agent/v3/plugins/linux/nsplugin/descriptor"
nslinuxcalls "go.ligato.io/vpp-agent/v3/plugins/linux/nsplugin/linuxcalls"
"go.ligato.io/vpp-agent/v3/plugins/netalloc"
netalloc_descr "go.ligato.io/vpp-agent/v3/plugins/netalloc/descriptor"
vpp_ifaceidx "go.ligato.io/vpp-agent/v3/plugins/vpp/ifplugin/ifaceidx"
interfaces "go.ligato.io/vpp-agent/v3/proto/ligato/linux/interfaces"
namespace "go.ligato.io/vpp-agent/v3/proto/ligato/linux/namespace"
netalloc_api "go.ligato.io/vpp-agent/v3/proto/ligato/netalloc"
vpp_intf "go.ligato.io/vpp-agent/v3/proto/ligato/vpp/interfaces"
)
const (
// InterfaceDescriptorName is the name of the descriptor for Linux interfaces.
InterfaceDescriptorName = "linux-interface"
// default MTU - expected when MTU is not specified in the config.
defaultEthernetMTU = 1500
defaultLoopbackMTU = 65536
defaultVrfDevMTU = 65536
// dependency labels
existingHostInterfaceDep = "host-interface-exists"
tapInterfaceDep = "vpp-tap-interface-exists"
vethPeerDep = "veth-peer-exists"
microserviceDep = "microservice-available"
// suffix attached to logical names of duplicate VETH interfaces
vethDuplicateSuffix = "-DUPLICATE"
// suffix attached to logical names of VETH interfaces with peers not found by Retrieve
vethMissingPeerSuffix = "-MISSING_PEER"
)
// A list of non-retriable errors:
var (
// ErrUnsupportedLinuxInterfaceType is returned for Linux interfaces of unknown type.
ErrUnsupportedLinuxInterfaceType = errors.New("unsupported Linux interface type")
// ErrInterfaceWithoutName is returned when Linux interface configuration has undefined
// Name attribute.
ErrInterfaceWithoutName = errors.New("Linux interface defined without logical name")
// ErrInterfaceWithoutType is returned when Linux interface configuration has undefined
// Type attribute.
ErrInterfaceWithoutType = errors.New("Linux interface defined without type")
// ErrNamespaceWithoutReference is returned when namespace is missing reference.
ErrInterfaceReferenceMismatch = errors.New("Linux interface reference does not match the interface type")
// ErrVETHWithoutPeer is returned when VETH interface is missing peer interface
// reference.
ErrVETHWithoutPeer = errors.New("VETH interface defined without peer reference")
// ErrTAPWithoutVPPReference is returned when TAP_TO_VPP interface is missing reference to VPP TAP.
ErrTAPWithoutVPPReference = errors.New("TAP_TO_VPP interface defined without reference to VPP TAP")
// ErrTAPRequiresVPPIfPlugin is returned when TAP_TO_VPP is supposed to be configured but VPP ifplugin
// is not loaded.
ErrTAPRequiresVPPIfPlugin = errors.New("TAP_TO_VPP interface requires VPP interface plugin to be loaded")
// ErrNamespaceWithoutReference is returned when namespace is missing reference.
ErrNamespaceWithoutReference = errors.New("namespace defined without name")
// ErrExistingWithNamespace is returned when namespace is specified for
// EXISTING interface.
ErrExistingWithNamespace = errors.New("EXISTING interface defined with namespace")
// ErrExistingIpWithNetalloc is returned when netalloc and EXISTING-IP features are combined,
// which is currently not supported.
ErrExistingIpWithNetalloc = errors.New("it is not supported to reference EXISTING-IP via netalloc")
// ErrInvalidIPWithMask is returned when address is invalid or mask is missing
ErrInvalidIPWithMask = errors.New("IP with mask is not valid")
// ErrLoopbackAlreadyConfigured is returned when multiple logical NB interfaces tries to configure the same loopback
ErrLoopbackAlreadyConfigured = errors.New("loopback already configured")
// ErrLoopbackNotFound is returned if loopback interface can not be found
ErrLoopbackNotFound = errors.New("loopback not found")
// ErrVRFDevWithMACAddr is returned when VRF device is configured with a MAC address.
ErrVRFDevWithMACAddr = errors.New("it is unsupported to set MAC address to a VRF device")
// ErrVRFDevInsideVrf is returned when VRF device is configured to be inside another VRF.
ErrVRFDevInsideVrf = errors.New("VRF device cannot be inside another VRF")
)
// InterfaceDescriptor teaches KVScheduler how to configure Linux interfaces.
type InterfaceDescriptor struct {
log logging.Logger
serviceLabel servicelabel.ReaderAPI
ifHandler iflinuxcalls.NetlinkAPI
nsPlugin nsplugin.API
vppIfPlugin VPPIfPluginAPI
addrAlloc netalloc.AddressAllocator
// runtime
intfIndex ifaceidx.LinuxIfMetadataIndex
}
// VPPIfPluginAPI is defined here to avoid import cycles.
type VPPIfPluginAPI interface {
// GetInterfaceIndex gives read-only access to map with metadata of all configured
// VPP interfaces.
GetInterfaceIndex() vpp_ifaceidx.IfaceMetadataIndex
}
// NewInterfaceDescriptor creates a new instance of the Interface descriptor.
func NewInterfaceDescriptor(
serviceLabel servicelabel.ReaderAPI, nsPlugin nsplugin.API, vppIfPlugin VPPIfPluginAPI,
addrAlloc netalloc.AddressAllocator, log logging.PluginLogger) (descr *kvs.KVDescriptor,
ctx *InterfaceDescriptor) {
// descriptor context
ctx = &InterfaceDescriptor{
nsPlugin: nsPlugin,
vppIfPlugin: vppIfPlugin,
addrAlloc: addrAlloc,
serviceLabel: serviceLabel,
log: log.NewLogger("if-descriptor"),
}
typedDescr := &adapter.InterfaceDescriptor{
Name: InterfaceDescriptorName,
NBKeyPrefix: interfaces.ModelInterface.KeyPrefix(),
ValueTypeName: interfaces.ModelInterface.ProtoName(),
KeySelector: interfaces.ModelInterface.IsKeyValid,
KeyLabel: interfaces.ModelInterface.StripKeyPrefix,
ValueComparator: ctx.EquivalentInterfaces,
WithMetadata: true,
MetadataMapFactory: ctx.MetadataFactory,
Validate: ctx.Validate,
Create: ctx.Create,
Delete: ctx.Delete,
Update: ctx.Update,
UpdateWithRecreate: ctx.UpdateWithRecreate,
Retrieve: ctx.Retrieve,
IsRetriableFailure: ctx.IsRetriableFailure,
DerivedValues: ctx.DerivedValues,
Dependencies: ctx.Dependencies,
RetrieveDependencies: []string{
// refresh the pool of allocated IP addresses first
netalloc_descr.IPAllocDescriptorName,
nsdescriptor.MicroserviceDescriptorName},
}
descr = adapter.NewInterfaceDescriptor(typedDescr)
return
}
// SetInterfaceIndex should be used to provide interface index immediately after
// the descriptor registration.
func (d *InterfaceDescriptor) SetInterfaceIndex(intfIndex ifaceidx.LinuxIfMetadataIndex) {
d.intfIndex = intfIndex
}
// SetInterfaceHandler provides interface handler to the descriptor immediately after
// the registration.
func (d *InterfaceDescriptor) SetInterfaceHandler(ifHandler iflinuxcalls.NetlinkAPI) {
d.ifHandler = ifHandler
}
// EquivalentInterfaces is case-insensitive comparison function for interfaces.LinuxInterface.
func (d *InterfaceDescriptor) EquivalentInterfaces(key string, oldIntf, newIntf *interfaces.Interface) bool {
// attributes compared as usually:
if oldIntf.Name != newIntf.Name ||
oldIntf.Type != newIntf.Type ||
oldIntf.Enabled != newIntf.Enabled ||
oldIntf.LinkOnly != newIntf.LinkOnly ||
getHostIfName(oldIntf) != getHostIfName(newIntf) {
return false
}
switch oldIntf.Type {
case interfaces.Interface_VETH:
if oldIntf.GetVeth().GetPeerIfName() != newIntf.GetVeth().GetPeerIfName() {
return false
}
// handle default config for checksum offloading
if getRxChksmOffloading(oldIntf) != getRxChksmOffloading(newIntf) ||
getTxChksmOffloading(oldIntf) != getTxChksmOffloading(newIntf) {
return false
}
case interfaces.Interface_TAP_TO_VPP:
if oldIntf.GetTap().GetVppTapIfName() != newIntf.GetTap().GetVppTapIfName() {
return false
}
case interfaces.Interface_VRF_DEVICE:
if oldIntf.GetVrfDev().GetRoutingTable() != newIntf.GetVrfDev().GetRoutingTable() {
return false
}
}
if !proto.Equal(oldIntf.Namespace, newIntf.Namespace) {
return false
}
// for existing interfaces all the other parameters are not managed by the agent
if oldIntf.Type == interfaces.Interface_EXISTING {
return true
}
// handle default MTU
if getInterfaceMTU(oldIntf) != getInterfaceMTU(newIntf) {
return false
}
// for link-only everything else is ignored
if oldIntf.LinkOnly {
return true
}
// compare MAC addresses case-insensitively (also handle unspecified MAC address)
if newIntf.PhysAddress != "" &&
strings.ToLower(oldIntf.PhysAddress) != strings.ToLower(newIntf.PhysAddress) {
return false
}
// IP addresses and VRFs are derived out and therefore not compared here
return true
}
// MetadataFactory is a factory for index-map customized for Linux interfaces.
func (d *InterfaceDescriptor) MetadataFactory() idxmap.NamedMappingRW {
return ifaceidx.NewLinuxIfIndex(logrus.DefaultLogger(), "linux-interface-index")
}
// Validate validates Linux interface configuration.
func (d *InterfaceDescriptor) Validate(key string, linuxIf *interfaces.Interface) error {
// validate name (this should never happen, since key is derived from name)
if linuxIf.GetName() == "" {
return kvs.NewInvalidValueError(ErrInterfaceWithoutName, "name")
}
// validate namespace
if ns := linuxIf.GetNamespace(); ns != nil {
if ns.GetType() == namespace.NetNamespace_UNDEFINED || ns.GetReference() == "" {
return kvs.NewInvalidValueError(ErrNamespaceWithoutReference, "namespace")
}
}
// validate type
switch linuxIf.GetType() {
case interfaces.Interface_EXISTING:
if linuxIf.GetLink() != nil {
return kvs.NewInvalidValueError(ErrInterfaceReferenceMismatch, "link")
}
// For now support only the same namespace as the agent.
if linuxIf.GetNamespace() != nil {
return kvs.NewInvalidValueError(ErrExistingWithNamespace, "namespace")
}
// Currently it is not supported to combine netalloc with existing IP.
if linuxIf.GetLinkOnly() {
for i, ipAddr := range linuxIf.GetIpAddresses() {
_, hasAllocDep := d.addrAlloc.GetAddressAllocDep(ipAddr, linuxIf.Name, "")
if hasAllocDep {
return kvs.NewInvalidValueError(ErrExistingIpWithNetalloc,
"type", "link_only", fmt.Sprintf("ip_addresses[%d]", i))
}
}
}
case interfaces.Interface_LOOPBACK:
if linuxIf.GetLink() != nil {
return kvs.NewInvalidValueError(ErrInterfaceReferenceMismatch, "link")
}
case interfaces.Interface_TAP_TO_VPP:
if d.vppIfPlugin == nil {
return ErrTAPRequiresVPPIfPlugin
}
case interfaces.Interface_VRF_DEVICE:
if linuxIf.GetPhysAddress() != "" {
return kvs.NewInvalidValueError(ErrVRFDevWithMACAddr, "type", "phys_address")
}
if linuxIf.GetVrfMasterInterface() != "" {
return kvs.NewInvalidValueError(ErrVRFDevInsideVrf, "type", "vrf")
}
case interfaces.Interface_UNDEFINED:
return kvs.NewInvalidValueError(ErrInterfaceWithoutType, "type")
}
// validate link
switch linuxIf.GetLink().(type) {
case *interfaces.Interface_Tap:
if linuxIf.GetType() != interfaces.Interface_TAP_TO_VPP {
return kvs.NewInvalidValueError(ErrInterfaceReferenceMismatch, "link")
}
if linuxIf.GetTap().GetVppTapIfName() == "" {
return kvs.NewInvalidValueError(ErrTAPWithoutVPPReference, "vpp_tap_if_name")
}
case *interfaces.Interface_Veth:
if linuxIf.GetType() != interfaces.Interface_VETH {
return kvs.NewInvalidValueError(ErrInterfaceReferenceMismatch, "link")
}
if linuxIf.GetVeth().GetPeerIfName() == "" {
return kvs.NewInvalidValueError(ErrVETHWithoutPeer, "peer_if_name")
}
}
return nil
}
// Create creates Linux interface.
func (d *InterfaceDescriptor) Create(key string, linuxIf *interfaces.Interface) (metadata *ifaceidx.LinuxIfMetadata, err error) {
// move to the default namespace
nsCtx := nslinuxcalls.NewNamespaceMgmtCtx()
revert1, err := d.nsPlugin.SwitchToNamespace(nsCtx, nil)
if err != nil {
d.log.Error(err)
return nil, err
}
defer revert1()
// create interface based on its type
switch linuxIf.Type {
case interfaces.Interface_VETH:
metadata, err = d.createVETH(nsCtx, key, linuxIf)
case interfaces.Interface_TAP_TO_VPP:
metadata, err = d.createTAPToVPP(nsCtx, key, linuxIf)
case interfaces.Interface_LOOPBACK:
metadata, err = d.createLoopback(nsCtx, linuxIf)
case interfaces.Interface_EXISTING:
// We expect that the interface already exists, therefore nothing needs to be done.
// We just get the metadata for the interface.
link, err := d.ifHandler.GetLinkByName(getHostIfName(linuxIf))
if err != nil {
d.log.Error(err)
return nil, err
}
metadata = &ifaceidx.LinuxIfMetadata{
Namespace: linuxIf.GetNamespace(),
HostIfName: link.Attrs().Name,
LinuxIfIndex: link.Attrs().Index,
VrfMasterIf: linuxIf.VrfMasterInterface,
}
if vrfDev, isVrf := link.(*netlink.Vrf); isVrf {
metadata.VrfDevRT = vrfDev.Table
}
return metadata, nil
case interfaces.Interface_VRF_DEVICE:
metadata, err = d.createVRF(nsCtx, linuxIf)
case interfaces.Interface_DUMMY:
metadata, err = d.createDummyIf(nsCtx, linuxIf)
default:
return nil, ErrUnsupportedLinuxInterfaceType
}
if err != nil {
d.log.Errorf("creating %v interface failed: %+v", linuxIf.GetType(), err)
return nil, err
}
metadata.HostIfName = getHostIfName(linuxIf)
metadata.VrfMasterIf = linuxIf.VrfMasterInterface
// move to the namespace with the interface
revert2, err := d.nsPlugin.SwitchToNamespace(nsCtx, linuxIf.Namespace)
if err != nil {
d.log.Error(err)
return nil, err
}
defer revert2()
// set interface up
hostName := getHostIfName(linuxIf)
if linuxIf.Enabled {
err = d.ifHandler.SetInterfaceUp(hostName)
if nil != err {
err = errors.Errorf("failed to set linux interface %s up: %v", linuxIf.Name, err)
d.log.Error(err)
return nil, err
}
}
// set checksum offloading
if linuxIf.Type == interfaces.Interface_VETH {
rxOn := getRxChksmOffloading(linuxIf)
txOn := getTxChksmOffloading(linuxIf)
err = d.ifHandler.SetChecksumOffloading(hostName, rxOn, txOn)
if err != nil {
err = errors.Errorf("failed to configure checksum offloading (rx=%t,tx=%t) for linux interface %s: %v",
rxOn, txOn, linuxIf.Name, err)
d.log.Error(err)
return nil, err
}
}
// set interface MTU
if linuxIf.Mtu != 0 {
mtu := int(linuxIf.Mtu)
err = d.ifHandler.SetInterfaceMTU(hostName, mtu)
if err != nil {
err = errors.Errorf("failed to set MTU %d to linux interface %s: %v",
mtu, linuxIf.Name, err)
d.log.Error(err)
return nil, err
}
}
if linuxIf.GetLinkOnly() {
// addresses are configured externally
return metadata, nil
}
// set interface MAC address
if linuxIf.PhysAddress != "" {
err = d.ifHandler.SetInterfaceMac(hostName, linuxIf.PhysAddress)
if err != nil {
err = errors.Errorf("failed to set MAC address %s to linux interface %s: %v",
linuxIf.PhysAddress, linuxIf.Name, err)
d.log.Error(err)
return nil, err
}
}
return metadata, nil
}
// Delete removes Linux interface.
func (d *InterfaceDescriptor) Delete(key string, linuxIf *interfaces.Interface, metadata *ifaceidx.LinuxIfMetadata) error {
// move to the namespace with the interface
nsCtx := nslinuxcalls.NewNamespaceMgmtCtx()
revert, err := d.nsPlugin.SwitchToNamespace(nsCtx, linuxIf.Namespace)
if err != nil {
d.log.Error("switch to namespace failed:", err)
return err
}
defer revert()
switch linuxIf.Type {
case interfaces.Interface_VETH:
return d.deleteVETH(nsCtx, key, linuxIf, metadata)
case interfaces.Interface_TAP_TO_VPP:
return d.deleteAutoTAP(nsCtx, key, linuxIf, metadata)
case interfaces.Interface_LOOPBACK:
return d.deleteLoopback(nsCtx, linuxIf)
case interfaces.Interface_EXISTING:
// We only need to unconfigure the interface.
// Nothing else needs to be done.
return nil
case interfaces.Interface_VRF_DEVICE:
return d.deleteVRF(linuxIf)
case interfaces.Interface_DUMMY:
return d.deleteDummyIf(linuxIf)
}
err = ErrUnsupportedLinuxInterfaceType
d.log.Error(err)
return err
}
// Update is able to change Type-unspecific attributes.
func (d *InterfaceDescriptor) Update(key string, oldLinuxIf, newLinuxIf *interfaces.Interface, oldMetadata *ifaceidx.LinuxIfMetadata) (newMetadata *ifaceidx.LinuxIfMetadata, err error) {
oldHostName := getHostIfName(oldLinuxIf)
newHostName := getHostIfName(newLinuxIf)
if oldLinuxIf.Type == interfaces.Interface_EXISTING {
// with existing interface only metadata needs to be updated
link, err := d.ifHandler.GetLinkByName(newHostName)
if err != nil {
d.log.Error(err)
return nil, err
}
oldMetadata.LinuxIfIndex = link.Attrs().Index
oldMetadata.HostIfName = newHostName
oldMetadata.VrfMasterIf = newLinuxIf.VrfMasterInterface
return oldMetadata, nil
}
// move to the namespace with the interface
nsCtx := nslinuxcalls.NewNamespaceMgmtCtx()
revert, err := d.nsPlugin.SwitchToNamespace(nsCtx, oldLinuxIf.Namespace)
if err != nil {
d.log.Error(err)
return nil, err
}
defer revert()
// update host name
if oldHostName != newHostName {
if err := d.ifHandler.RenameInterface(oldHostName, newHostName); err != nil {
d.log.Error("renaming interface failed:", err)
return nil, err
}
}
// update admin status
if oldLinuxIf.Enabled != newLinuxIf.Enabled {
if newLinuxIf.Enabled {
err = d.ifHandler.SetInterfaceUp(newHostName)
if nil != err {
err = errors.Errorf("failed to set linux interface %s UP: %v", newHostName, err)
d.log.Error(err)
return nil, err
}
} else {
err = d.ifHandler.SetInterfaceDown(newHostName)
if nil != err {
err = errors.Errorf("failed to set linux interface %s DOWN: %v", newHostName, err)
d.log.Error(err)
return nil, err
}
}
}
// update MAC address
if !newLinuxIf.GetLinkOnly() {
if newLinuxIf.PhysAddress != "" && newLinuxIf.PhysAddress != oldLinuxIf.PhysAddress {
err := d.ifHandler.SetInterfaceMac(newHostName, newLinuxIf.PhysAddress)
if err != nil {
err = errors.Errorf("failed to reconfigure MAC address for linux interface %s: %v",
newLinuxIf.Name, err)
d.log.Error(err)
return nil, err
}
}
}
// MTU
if getInterfaceMTU(newLinuxIf) != getInterfaceMTU(oldLinuxIf) {
mtu := getInterfaceMTU(newLinuxIf)
err := d.ifHandler.SetInterfaceMTU(newHostName, mtu)
if nil != err {
err = errors.Errorf("failed to reconfigure MTU for the linux interface %s: %v",
newLinuxIf.Name, err)
d.log.Error(err)
return nil, err
}
}
// update checksum offloading
if newLinuxIf.Type == interfaces.Interface_VETH {
rxOn := getRxChksmOffloading(newLinuxIf)
txOn := getTxChksmOffloading(newLinuxIf)
if rxOn != getRxChksmOffloading(oldLinuxIf) || txOn != getTxChksmOffloading(oldLinuxIf) {
err = d.ifHandler.SetChecksumOffloading(newHostName, rxOn, txOn)
if err != nil {
err = errors.Errorf("failed to reconfigure checksum offloading (rx=%t,tx=%t) for linux interface %s: %v",
rxOn, txOn, newLinuxIf.Name, err)
d.log.Error(err)
return nil, err
}
}
}
// update metadata
oldMetadata.HostIfName = newHostName
oldMetadata.VrfMasterIf = newLinuxIf.VrfMasterInterface
return oldMetadata, nil
}
// UpdateWithRecreate returns true if Type or Type-specific attributes are different.
func (d *InterfaceDescriptor) UpdateWithRecreate(key string, oldLinuxIf, newLinuxIf *interfaces.Interface, metadata *ifaceidx.LinuxIfMetadata) bool {
if oldLinuxIf.Type != newLinuxIf.Type {
return true
}
if oldLinuxIf.LinkOnly != newLinuxIf.LinkOnly {
return true
}
if !proto.Equal(oldLinuxIf.Namespace, newLinuxIf.Namespace) {
// anything attached to the interface (ARPs, routes, ...) will be re-created as well
return true
}
switch oldLinuxIf.Type {
case interfaces.Interface_VETH:
return oldLinuxIf.GetVeth().GetPeerIfName() != newLinuxIf.GetVeth().GetPeerIfName()
case interfaces.Interface_TAP_TO_VPP:
return oldLinuxIf.GetTap().GetVppTapIfName() != newLinuxIf.GetTap().GetVppTapIfName()
case interfaces.Interface_VRF_DEVICE:
return oldLinuxIf.GetVrfDev().GetRoutingTable() != newLinuxIf.GetVrfDev().GetRoutingTable()
}
return false
}
// Dependencies lists dependencies for a Linux interface.
func (d *InterfaceDescriptor) Dependencies(key string, linuxIf *interfaces.Interface) []kvs.Dependency {
var dependencies []kvs.Dependency
// EXISTING depends on a referenced Linux interface in the default namespace
if linuxIf.Type == interfaces.Interface_EXISTING {
dependencies = append(dependencies, kvs.Dependency{
Label: existingHostInterfaceDep,
Key: interfaces.InterfaceHostNameKey(getHostIfName(linuxIf)),
})
}
if linuxIf.Type == interfaces.Interface_TAP_TO_VPP {
// dependency on VPP TAP
dependencies = append(dependencies, kvs.Dependency{
Label: tapInterfaceDep,
Key: vpp_intf.InterfaceKey(linuxIf.GetTap().GetVppTapIfName()),
})
}
// circular dependency between VETH ends
if linuxIf.Type == interfaces.Interface_VETH {
peerName := linuxIf.GetVeth().GetPeerIfName()
if peerName != "" {
dependencies = append(dependencies, kvs.Dependency{
Label: vethPeerDep,
Key: interfaces.InterfaceKey(peerName),
})
}
}
if linuxIf.GetNamespace().GetType() == namespace.NetNamespace_MICROSERVICE {
dependencies = append(dependencies, kvs.Dependency{
Label: microserviceDep,
Key: namespace.MicroserviceKey(linuxIf.Namespace.Reference),
})
}
return dependencies
}
// DerivedValues derives:
// - one empty value to represent interface state
// - one empty value to represent assignment of the interface to a (non-default) VRF
// - one empty value for every IP address assigned to the interface.
func (d *InterfaceDescriptor) DerivedValues(key string, linuxIf *interfaces.Interface) (derValues []kvs.KeyValuePair) {
// interface state
derValues = append(derValues, kvs.KeyValuePair{
Key: interfaces.InterfaceStateKey(linuxIf.Name, linuxIf.Enabled),
Value: &prototypes.Empty{},
})
if linuxIf.GetVrfMasterInterface() != "" {
derValues = append(derValues, kvs.KeyValuePair{
Key: interfaces.InterfaceVrfKey(linuxIf.Name, linuxIf.VrfMasterInterface),
// only fields accessed by VRF descriptor are included in the derived value
// FIXME: we can get rid of this hack once we add Context to descriptor methods
Value: &interfaces.Interface{
Name: linuxIf.Name,
Type: linuxIf.Type,
HostIfName: linuxIf.HostIfName,
VrfMasterInterface: linuxIf.VrfMasterInterface,
},
})
}
if !linuxIf.GetLinkOnly() || linuxIf.GetType() == interfaces.Interface_EXISTING {
var ipSource netalloc_api.IPAddressSource
if linuxIf.GetLinkOnly() { // interface type = EXISTING
ipSource = netalloc_api.IPAddressSource_EXISTING
} else {
ipSource = netalloc_api.IPAddressSource_STATIC
}
// IP addresses
for _, ipAddr := range linuxIf.IpAddresses {
derValues = append(derValues, kvs.KeyValuePair{
Key: interfaces.InterfaceAddressKey(
linuxIf.Name, ipAddr, ipSource),
// only fields accessed by address descriptor are included in the derived value
// FIXME: we can get rid of this hack once we add Context to descriptor methods
Value: &interfaces.Interface{
Name: linuxIf.Name,
Type: linuxIf.Type,
HostIfName: linuxIf.HostIfName,
VrfMasterInterface: linuxIf.VrfMasterInterface,
IpAddresses: []string{ipAddr},
},
})
}
}
return derValues
}
func (d *InterfaceDescriptor) IsRetriableFailure(err error) bool {
if err == ErrLoopbackAlreadyConfigured {
return false
}
return true
}
// Retrieve returns all Linux interfaces managed by this agent, attached to the default namespace
// or to one of the configured non-default namespaces.
func (d *InterfaceDescriptor) Retrieve(correlate []adapter.InterfaceKVWithMetadata) ([]adapter.InterfaceKVWithMetadata, error) {
var retrieved []adapter.InterfaceKVWithMetadata
nsList := []*namespace.NetNamespace{nil} // nil = default namespace, which always should be listed for interfaces
ifCfg := make(map[string]*interfaces.Interface) // interface logical name -> interface config (as expected by correlate)
expExisting := make(map[string]*interfaces.Interface) // EXISTING interface host name -> expected interface config
// process interfaces for correlation to get:
// - the set of namespaces to list for interfaces
// - mapping between interface name and the configuration for correlation
// beware: the same namespace can have multiple different references (e.g. integration of Contiv with SFC)
for _, kv := range correlate {
nsListed := false
for _, ns := range nsList {
if proto.Equal(ns, kv.Value.Namespace) {
nsListed = true
break
}
}
if !nsListed {
nsList = append(nsList, kv.Value.Namespace)
}
ifCfg[kv.Value.Name] = kv.Value
if kv.Value.Type == interfaces.Interface_EXISTING {
expExisting[getHostIfName(kv.Value)] = kv.Value
}
}
// retrieve EXISTING interfaces first
existingIfaces, err := d.retrieveExistingInterfaces(expExisting)
if err != nil {
return nil, err
}
for _, kv := range existingIfaces {
retrieved = append(retrieved, kv)
}
// Obtain interface details - all interfaces with metadata
ifDetails, err := d.ifHandler.DumpInterfacesFromNamespaces(nsList)
if err != nil {
return nil, errors.Errorf("Failed to retrieve linux interfaces: %v", err)
}
// interface logical name -> interface data
ifaces := make(map[string]adapter.InterfaceKVWithMetadata)
// already retrieved interfaces by their Linux indexes
indexes := make(map[int]struct{})
for _, ifDetail := range ifDetails {
// Transform linux interface details to the type-safe value with metadata
var vrfDevRT uint32
if ifDetail.Interface.Type == interfaces.Interface_VRF_DEVICE {
vrfDevRT = ifDetail.Interface.GetVrfDev().GetRoutingTable()
}
// Handle reference to existing (i.e. not managed) VRF from managed interface
if ifDetail.Interface.Namespace == nil {
if vrf, existingVrf := existingIfaces[ifDetail.Meta.MasterIndex]; existingVrf {
ifDetail.Interface.VrfMasterInterface = vrf.Value.Name
}
}
kv := adapter.InterfaceKVWithMetadata{
Origin: kvs.FromNB,
Value: ifDetail.Interface,
Metadata: &ifaceidx.LinuxIfMetadata{
LinuxIfIndex: ifDetail.Meta.LinuxIfIndex,
Namespace: ifDetail.Interface.GetNamespace(),
VPPTapName: ifDetail.Interface.GetTap().GetVppTapIfName(),
HostIfName: ifDetail.Interface.HostIfName,
VrfMasterIf: ifDetail.Interface.VrfMasterInterface,
VrfDevRT: vrfDevRT,
},
Key: interfaces.InterfaceKey(ifDetail.Interface.Name),
}
// skip if this interface was already retrieved and this is not the expected
// namespace from correlation - remember, the same namespace may have
// multiple different references
var rewrite bool
if _, alreadyRetrieved := indexes[kv.Metadata.LinuxIfIndex]; alreadyRetrieved {
if expCfg, hasExpCfg := ifCfg[kv.Value.Name]; hasExpCfg {
if proto.Equal(expCfg.Namespace, kv.Value.Namespace) {
rewrite = true
}
}
if !rewrite {
continue
}
}
indexes[kv.Metadata.LinuxIfIndex] = struct{}{}
// test for duplicity of VETH logical names
if kv.Value.Type == interfaces.Interface_VETH {
if _, duplicate := ifaces[kv.Value.Name]; duplicate && !rewrite {
// add suffix to the duplicate to make its logical name unique
// (and not configured by NB so that it will get removed)
dupIndex := 1
for intf2 := range ifaces {
if strings.HasPrefix(intf2, kv.Value.Name+vethDuplicateSuffix) {
dupIndex++
}
}
kv.Value.Name = kv.Value.Name + vethDuplicateSuffix + strconv.Itoa(dupIndex)
kv.Key = interfaces.InterfaceKey(kv.Value.Name)
}
}
// correlate link_only attribute
if expCfg, hasExpCfg := ifCfg[kv.Value.Name]; hasExpCfg {
kv.Value.LinkOnly = expCfg.GetLinkOnly()
}
ifaces[kv.Value.Name] = kv
}
// collect VETHs with duplicate logical names
for ifName, kv := range ifaces {
if kv.Value.Type == interfaces.Interface_VETH {
isDuplicate := strings.Contains(ifName, vethDuplicateSuffix)
// first interface retrieved from the set of duplicate VETHs still
// does not have the vethDuplicateSuffix appended to the name
_, hasDuplicate := ifaces[ifName+vethDuplicateSuffix+"1"]
if hasDuplicate {
kv.Value.Name = ifName + vethDuplicateSuffix + "0"
kv.Key = interfaces.InterfaceKey(kv.Value.Name)
}
if isDuplicate || hasDuplicate {
// clear peer reference so that Delete removes the VETH-end
// as standalone
kv.Value.Link = &interfaces.Interface_Veth{}
delete(ifaces, ifName)
retrieved = append(retrieved, kv)
}
}
}
// next collect VETHs with missing peer
for ifName, kv := range ifaces {
if kv.Value.Type == interfaces.Interface_VETH {
peer, known := ifaces[kv.Value.GetVeth().GetPeerIfName()]
if !known || peer.Value.GetVeth().GetPeerIfName() != kv.Value.Name {
// append vethMissingPeerSuffix to the logical name so that VETH
// will get removed during resync
kv.Value.Name = ifName + vethMissingPeerSuffix
kv.Key = interfaces.InterfaceKey(kv.Value.Name)
// clear peer reference so that Delete removes the VETH-end
// as standalone
kv.Value.Link = &interfaces.Interface_Veth{}
delete(ifaces, ifName)
retrieved = append(retrieved, kv)
}
}
}
// collect AUTO-TAPs and valid VETHs
for _, kv := range ifaces {
retrieved = append(retrieved, kv)
}
// correlate IP addresses with netalloc references from the expected config
for _, kv := range retrieved {
if expCfg, hasExpCfg := ifCfg[kv.Value.Name]; hasExpCfg {
kv.Value.IpAddresses = d.addrAlloc.CorrelateRetrievedIPs(
expCfg.IpAddresses, kv.Value.IpAddresses,
kv.Value.Name, netalloc_api.IPAddressForm_ADDR_WITH_MASK)
}
}
return retrieved, nil
}
// retrieveExistingInterfaces retrieves already created Linux interface - i.e. not created
// by this agent = type EXISTING.
func (d *InterfaceDescriptor) retrieveExistingInterfaces(expected map[string]*interfaces.Interface) (
existing map[int]adapter.InterfaceKVWithMetadata, err error) {
existing = make(map[int]adapter.InterfaceKVWithMetadata)
// get all links in the default namespace
links, err := d.ifHandler.GetLinkList()
if err != nil {
d.log.Error("Failed to get link list:", err)
return nil, err
}
for _, link := range links {
expCfg, isExp := expected[link.Attrs().Name]
if !isExp {
// do not touch existing interfaces which are not configured by the agent
continue
}
iface := &interfaces.Interface{
Name: expCfg.GetName(),
Type: interfaces.Interface_EXISTING,
HostIfName: link.Attrs().Name,
PhysAddress: link.Attrs().HardwareAddr.String(),
Mtu: uint32(link.Attrs().MTU),
LinkOnly: expCfg.LinkOnly,
}
// retrieve VRF config
var vrfDevRT uint32
if vrfDev, isVrf := link.(*netlink.Vrf); isVrf {
vrfDevRT = vrfDev.Table
}
master := link.Attrs().MasterIndex
if master != 0 {
if masterLink, err := d.ifHandler.GetLinkByIndex(master); err == nil {
if vrfExpCfg, isVrfExp := expected[masterLink.Attrs().Name]; isVrfExp {
iface.VrfMasterInterface = vrfExpCfg.GetName()
}
}
}
// retrieve addresses, MTU, etc.
d.retrieveLinkDetails(link, iface, nil)
// build key-value pair for the retrieved interface
existing[link.Attrs().Index] = adapter.InterfaceKVWithMetadata{
Key: models.Key(iface),
Value: iface,
Origin: kvs.FromNB,
Metadata: &ifaceidx.LinuxIfMetadata{
LinuxIfIndex: link.Attrs().Index,
HostIfName: link.Attrs().Name,
VrfMasterIf: iface.VrfMasterInterface,
VrfDevRT: vrfDevRT,
},
}
}
return existing, nil
}
// retrieveLinkDetails retrieves link details common to all interface types (e.g. addresses).
func (d *InterfaceDescriptor) retrieveLinkDetails(link netlink.Link, iface *interfaces.Interface, nsRef *namespace.NetNamespace) {
var err error
// read interface status
iface.Enabled, err = d.ifHandler.IsInterfaceUp(link.Attrs().Name)
if err != nil {
d.log.WithFields(logging.Fields{
"if-host-name": link.Attrs().Name,
"namespace": nsRef,
}).Warn("Failed to read interface status:", err)
}
// read assigned IP addresses
addressList, err := d.ifHandler.GetAddressList(link.Attrs().Name)
if err != nil {
d.log.WithFields(logging.Fields{
"if-host-name": link.Attrs().Name,
"namespace": nsRef,
}).Warn("Failed to read address list:", err)
}
for _, address := range addressList {
if address.Scope == unix.RT_SCOPE_LINK {
// ignore link-local IPv6 addresses
continue
}
mask, _ := address.Mask.Size()
addrStr := address.IP.String() + "/" + strconv.Itoa(mask)
iface.IpAddresses = append(iface.IpAddresses, addrStr)
}
// read checksum offloading
if iface.Type == interfaces.Interface_VETH {
rxOn, txOn, err := d.ifHandler.GetChecksumOffloading(link.Attrs().Name)
if err != nil {
d.log.WithFields(logging.Fields{
"if-host-name": link.Attrs().Name,
"namespace": nsRef,
}).Warn("Failed to read checksum offloading:", err)
} else {
if !rxOn {
iface.GetVeth().RxChecksumOffloading = interfaces.VethLink_CHKSM_OFFLOAD_DISABLED
}
if !txOn {
iface.GetVeth().TxChecksumOffloading = interfaces.VethLink_CHKSM_OFFLOAD_DISABLED
}
}
}
}
// setInterfaceNamespace moves linux interface from the current to the desired
// namespace.
func (d *InterfaceDescriptor) setInterfaceNamespace(ctx nslinuxcalls.NamespaceMgmtCtx, ifName string, namespace *namespace.NetNamespace) error {
// Get namespace handle.
ns, err := d.nsPlugin.GetNamespaceHandle(ctx, namespace)
if err != nil {
return err
}
defer ns.Close()
// Get the interface link handle.
link, err := d.ifHandler.GetLinkByName(ifName)