-
Notifications
You must be signed in to change notification settings - Fork 456
/
Copy pathovs_linux.go
1996 lines (1796 loc) · 61.4 KB
/
ovs_linux.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 daemon
import (
"bytes"
"context"
"errors"
"fmt"
"net"
"os"
"os/exec"
"path"
"path/filepath"
"regexp"
"strconv"
"strings"
"syscall"
"time"
"github.com/containerd/containerd/pkg/netns"
"github.com/containernetworking/plugins/pkg/ns"
"github.com/k8snetworkplumbingwg/sriovnet"
sriovutilfs "github.com/k8snetworkplumbingwg/sriovnet/pkg/utils/filesystem"
"github.com/vishvananda/netlink"
"golang.org/x/sys/unix"
corev1 "k8s.io/api/core/v1"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/kubernetes"
"k8s.io/klog/v2"
kubeovnv1 "github.com/kubeovn/kube-ovn/pkg/apis/kubeovn/v1"
"github.com/kubeovn/kube-ovn/pkg/net/yusur"
"github.com/kubeovn/kube-ovn/pkg/ovs"
"github.com/kubeovn/kube-ovn/pkg/request"
"github.com/kubeovn/kube-ovn/pkg/util"
)
var pciAddrRegexp = regexp.MustCompile(`\b([0-9a-fA-F]{4}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}.\d{1}\S*)`)
func (csh cniServerHandler) configureDpdkNic(podName, podNamespace, provider, netns, containerID, ifName, _ string, _ int, ip, _, ingress, egress, shortSharedDir, socketName, socketConsumption string) error {
sharedDir := filepath.Join("/var", shortSharedDir)
hostNicName, _ := generateNicName(containerID, ifName)
ipStr := util.GetIPWithoutMask(ip)
ifaceID := ovs.PodNameToPortName(podName, podNamespace, provider)
ovs.CleanDuplicatePort(ifaceID, hostNicName)
vhostServerPath := path.Join(sharedDir, socketName)
if socketConsumption == util.ConsumptionKubevirt {
vhostServerPath = path.Join(sharedDir, ifName)
}
// Add vhostuser host end to ovs port
output, err := ovs.Exec(ovs.MayExist, "add-port", "br-int", hostNicName, "--",
"set", "interface", hostNicName,
"type=dpdkvhostuserclient",
fmt.Sprintf("options:vhost-server-path=%s", vhostServerPath),
fmt.Sprintf("external_ids:iface-id=%s", ifaceID),
fmt.Sprintf("external_ids:pod_name=%s", podName),
fmt.Sprintf("external_ids:pod_namespace=%s", podNamespace),
fmt.Sprintf("external_ids:ip=%s", ipStr),
fmt.Sprintf("external_ids:pod_netns=%s", netns))
if err != nil {
return fmt.Errorf("add nic to ovs failed %w: %q", err, output)
}
return ovs.SetInterfaceBandwidth(podName, podNamespace, ifaceID, egress, ingress)
}
func (csh cniServerHandler) configureNic(podName, podNamespace, provider, netns, containerID, vfDriver, ifName, mac string, mtu int, ip, gateway string, isDefaultRoute, vmMigration bool, routes []request.Route, _, _ []string, ingress, egress, deviceID, nicType, latency, limit, loss, jitter string, gwCheckMode int, u2oInterconnectionIP, oldPodName string) ([]request.Route, error) {
var err error
var hostNicName, containerNicName, pfPci string
var vfID int
if deviceID == "" {
hostNicName, containerNicName, err = setupVethPair(containerID, ifName, mtu)
if err != nil {
klog.Errorf("failed to create veth pair %v", err)
return nil, err
}
defer func() {
if err != nil {
if err := rollBackVethPair(hostNicName); err != nil {
klog.Errorf("failed to rollback veth pair %s, %v", hostNicName, err)
return
}
}
}()
} else {
hostNicName, containerNicName, pfPci, vfID, err = setupSriovInterface(containerID, deviceID, vfDriver, ifName, mtu, mac)
if err != nil {
klog.Errorf("failed to create sriov interfaces %v", err)
return nil, err
}
}
ipStr := util.GetIPWithoutMask(ip)
ifaceID := ovs.PodNameToPortName(podName, podNamespace, provider)
ovs.CleanDuplicatePort(ifaceID, hostNicName)
if yusur.IsYusurSmartNic(deviceID) {
klog.Infof("add Yusur smartnic vfr %s to ovs", hostNicName)
// Add yusur ovs port
output, err := ovs.Exec(ovs.MayExist, "add-port", "br-int", hostNicName, "--",
"set", "interface", hostNicName, "type=dpdk",
fmt.Sprintf("options:dpdk-devargs=%s,representor=[%d]", pfPci, vfID),
fmt.Sprintf("mtu_request=%d", mtu),
fmt.Sprintf("external_ids:iface-id=%s", ifaceID),
fmt.Sprintf("external_ids:vendor=%s", util.CniTypeName),
fmt.Sprintf("external_ids:pod_name=%s", podName),
fmt.Sprintf("external_ids:pod_namespace=%s", podNamespace),
fmt.Sprintf("external_ids:ip=%s", ipStr),
fmt.Sprintf("external_ids:pod_netns=%s", netns))
if err != nil {
return nil, fmt.Errorf("add nic to ovs failed %w: %q", err, output)
}
} else {
// Add veth pair host end to ovs port
output, err := ovs.Exec(ovs.MayExist, "add-port", "br-int", hostNicName, "--",
"set", "interface", hostNicName, fmt.Sprintf("external_ids:iface-id=%s", ifaceID),
fmt.Sprintf("external_ids:vendor=%s", util.CniTypeName),
fmt.Sprintf("external_ids:pod_name=%s", podName),
fmt.Sprintf("external_ids:pod_namespace=%s", podNamespace),
fmt.Sprintf("external_ids:ip=%s", ipStr),
fmt.Sprintf("external_ids:pod_netns=%s", netns))
if err != nil {
return nil, fmt.Errorf("add nic to ovs failed %w: %q", err, output)
}
}
defer func() {
if err != nil {
if err := csh.rollbackOvsPort(hostNicName, containerNicName, nicType); err != nil {
klog.Errorf("failed to rollback ovs port %s, %v", hostNicName, err)
return
}
}
}()
// add hostNicName and containerNicName into pod annotations
if deviceID != "" {
var podNameNew string
if podName != oldPodName {
podNameNew = oldPodName
} else {
podNameNew = podName
}
patch := util.KVPatch{
fmt.Sprintf(util.VfRepresentorNameTemplate, provider): hostNicName,
fmt.Sprintf(util.VfNameTemplate, provider): containerNicName,
fmt.Sprintf(util.PodNicAnnotationTemplate, provider): util.SriovNicType,
}
if err = util.PatchAnnotations(csh.Config.KubeClient.CoreV1().Pods(podNamespace), podNameNew, patch); err != nil {
klog.Errorf("failed to patch pod %s/%s: %v", podNamespace, podNameNew, err)
return nil, err
}
}
// lsp and container nic must use same mac address, otherwise ovn will reject these packets by default
macAddr, err := net.ParseMAC(mac)
if err != nil {
return nil, fmt.Errorf("failed to parse mac %s %w", macAddr, err)
}
if !yusur.IsYusurSmartNic(deviceID) {
if err = configureHostNic(hostNicName); err != nil {
klog.Error(err)
return nil, err
}
}
if err = ovs.SetInterfaceBandwidth(podName, podNamespace, ifaceID, egress, ingress); err != nil {
klog.Error(err)
return nil, err
}
if err = ovs.SetNetemQos(podName, podNamespace, ifaceID, latency, limit, loss, jitter); err != nil {
klog.Error(err)
return nil, err
}
if containerNicName == "" {
return nil, nil
}
isUserspaceDP, err := ovs.IsUserspaceDataPath()
if err != nil {
klog.Error(err)
return nil, err
}
if isUserspaceDP {
// turn off tx checksum
if err = TurnOffNicTxChecksum(containerNicName); err != nil {
klog.Error(err)
return nil, err
}
}
podNS, err := ns.GetNS(netns)
if err != nil {
err = fmt.Errorf("failed to open netns %q: %w", netns, err)
klog.Error(err)
return nil, err
}
finalRoutes, err := csh.configureContainerNic(podName, podNamespace, containerNicName, ifName, ip, gateway, isDefaultRoute, vmMigration, routes, macAddr, podNS, mtu, nicType, gwCheckMode, u2oInterconnectionIP)
if err != nil {
klog.Error(err)
return nil, err
}
return finalRoutes, nil
}
func (csh cniServerHandler) releaseVf(podName, podNamespace, podNetns, ifName, nicType, deviceID string) error {
// Only for SRIOV case, we'd need to move the VF from container namespace back to the host namespace
if nicType != util.OffloadType || deviceID == "" {
return nil
}
podDesc := fmt.Sprintf("for pod %s/%s", podNamespace, podName)
klog.Infof("Tear down interface %s", podDesc)
netns, err := ns.GetNS(podNetns)
if err != nil {
return fmt.Errorf("failed to get container namespace %s: %w", podDesc, err)
}
defer netns.Close()
hostNS, err := ns.GetCurrentNS()
if err != nil {
return fmt.Errorf("failed to get host namespace %s: %w", podDesc, err)
}
defer hostNS.Close()
err = netns.Do(func(_ ns.NetNS) error {
// container side interface deletion
link, err := netlink.LinkByName(ifName)
if err != nil {
return fmt.Errorf("failed to get container interface %s %s: %w", ifName, podDesc, err)
}
if err = netlink.LinkSetDown(link); err != nil {
return fmt.Errorf("failed to bring down container interface %s %s: %w", ifName, podDesc, err)
}
// rename VF device back to its original name in the host namespace:
vfName := link.Attrs().Alias
if err = netlink.LinkSetName(link, vfName); err != nil {
return fmt.Errorf("failed to rename container interface %s to %s %s: %w",
ifName, vfName, podDesc, err)
}
// move VF device to host netns
fd := int(netns.Fd()) // #nosec G115
if err = netlink.LinkSetNsFd(link, fd); err != nil {
return fmt.Errorf("failed to move container interface %s back to host namespace %s: %w",
ifName, podDesc, err)
}
return nil
})
if err != nil {
klog.Error(err)
}
return nil
}
func (csh cniServerHandler) deleteNic(podName, podNamespace, containerID, netns, deviceID, ifName, nicType string) error {
if err := csh.releaseVf(podName, podNamespace, netns, ifName, nicType, deviceID); err != nil {
return fmt.Errorf("failed to release VF %s assigned to the Pod %s/%s back to the host network namespace: "+
"%w", ifName, podName, podNamespace, err)
}
var nicName string
if yusur.IsYusurSmartNic(deviceID) {
pfPci, err := yusur.GetYusurNicPfPciFromVfPci(deviceID)
if err != nil {
return fmt.Errorf("failed to get pf pci %w, %s", err, deviceID)
}
pfIndex, err := yusur.GetYusurNicPfIndexByPciAddress(pfPci)
if err != nil {
return fmt.Errorf("failed to get pf index %w, %s", err, deviceID)
}
vfIndex, err := yusur.GetYusurNicVfIndexByPciAddress(deviceID)
if err != nil {
return fmt.Errorf("failed to get vf index %w, %s", err, deviceID)
}
nicName = yusur.GetYusurNicVfRepresentor(pfIndex, vfIndex)
} else {
hostNicName, containerNicName := generateNicName(containerID, ifName)
if nicType == util.InternalType {
nicName = containerNicName
} else {
nicName = hostNicName
}
}
// Remove ovs port
output, err := ovs.Exec(ovs.IfExists, "--with-iface", "del-port", "br-int", nicName)
if err != nil {
return fmt.Errorf("failed to delete ovs port %w, %q", err, output)
}
if err = ovs.ClearPodBandwidth(podName, podNamespace, ""); err != nil {
klog.Error(err)
return err
}
if err = ovs.ClearHtbQosQueue(podName, podNamespace, ""); err != nil {
klog.Error(err)
return err
}
if deviceID == "" {
hostLink, err := netlink.LinkByName(nicName)
if err != nil {
// If link already not exists, return quietly
// E.g. Internal port had been deleted by Remove ovs port previously
if _, ok := err.(netlink.LinkNotFoundError); ok {
return nil
}
return fmt.Errorf("find host link %s failed %w", nicName, err)
}
hostLinkType := hostLink.Type()
// Sometimes no deviceID input for vf nic, avoid delete vf nic.
if hostLinkType == "veth" {
if err = netlink.LinkDel(hostLink); err != nil {
return fmt.Errorf("delete host link %s failed %w", hostLink, err)
}
}
} else if pciAddrRegexp.MatchString(deviceID) && !yusur.IsYusurSmartNic(deviceID) {
// Ret VF index from PCI
vfIndex, err := sriovnet.GetVfIndexByPciAddress(deviceID)
if err != nil {
klog.Errorf("failed to get vf %s index, %v", deviceID, err)
return err
}
if err = setVfMac(deviceID, vfIndex, "00:00:00:00:00:00"); err != nil {
klog.Error(err)
return err
}
}
return nil
}
func (csh cniServerHandler) rollbackOvsPort(hostNicName, containerNicName, nicType string) (err error) {
var nicName string
if nicType == util.InternalType {
nicName = containerNicName
} else {
nicName = hostNicName
}
output, err := ovs.Exec(ovs.IfExists, "--with-iface", "del-port", "br-int", nicName)
if err != nil {
klog.Warningf("failed to delete down ovs port %v, %q", err, output)
}
klog.Infof("rollback ovs port success %s", nicName)
return
}
func generateNicName(containerID, ifname string) (string, string) {
if ifname == "eth0" {
return fmt.Sprintf("%s_h", containerID[0:12]), fmt.Sprintf("%s_c", containerID[0:12])
}
// The nic name is 14 length and have prefix pod in the Kubevirt v1.0.0
if strings.HasPrefix(ifname, "pod") && len(ifname) == 14 {
ifname = ifname[3 : len(ifname)-4]
return fmt.Sprintf("%s_%s_h", containerID[0:12-len(ifname)], ifname), fmt.Sprintf("%s_%s_c", containerID[0:12-len(ifname)], ifname)
}
return fmt.Sprintf("%s_%s_h", containerID[0:12-len(ifname)], ifname), fmt.Sprintf("%s_%s_c", containerID[0:12-len(ifname)], ifname)
}
func configureHostNic(nicName string) error {
hostLink, err := netlink.LinkByName(nicName)
if err != nil {
return fmt.Errorf("can not find host nic %s: %w", nicName, err)
}
if hostLink.Attrs().OperState != netlink.OperUp {
if err = netlink.LinkSetUp(hostLink); err != nil {
return fmt.Errorf("can not set host nic %s up: %w", nicName, err)
}
}
if err = netlink.LinkSetTxQLen(hostLink, 1000); err != nil {
return fmt.Errorf("can not set host nic %s qlen: %w", nicName, err)
}
return nil
}
func (csh cniServerHandler) configureContainerNic(podName, podNamespace, nicName, ifName, ipAddr, gateway string, isDefaultRoute, vmMigration bool, routes []request.Route, macAddr net.HardwareAddr, netns ns.NetNS, mtu int, nicType string, gwCheckMode int, u2oInterconnectionIP string) ([]request.Route, error) {
containerLink, err := netlink.LinkByName(nicName)
if err != nil {
return nil, fmt.Errorf("can not find container nic %s: %w", nicName, err)
}
// Set link alias to its origin link name for fastpath to recognize and bypass netfilter
if err := netlink.LinkSetAlias(containerLink, nicName); err != nil {
klog.Errorf("failed to set link alias for container nic %s: %v", nicName, err)
return nil, err
}
fd := int(netns.Fd()) // #nosec G115
if err = netlink.LinkSetNsFd(containerLink, fd); err != nil {
return nil, fmt.Errorf("failed to move link to netns: %w", err)
}
// do not perform ipv4/ipv6 duplicate address detection during VM live migration
checkIPv6DAD := !vmMigration
detectIPv4Conflict := !vmMigration && csh.Config.EnableArpDetectIPConflict
var finalRoutes []request.Route
err = ns.WithNetNSPath(netns.Path(), func(_ ns.NetNS) error {
interfaceName := nicName
if nicType != util.InternalType {
interfaceName = ifName
if err = netlink.LinkSetName(containerLink, ifName); err != nil {
klog.Error(err)
return err
}
}
if nicType == util.InternalType {
if err = addAdditionalNic(ifName); err != nil {
klog.Error(err)
return err
}
if err = configureAdditionalNic(ifName, ipAddr); err != nil {
klog.Error(err)
return err
}
if err = configureNic(nicName, ipAddr, macAddr, mtu, detectIPv4Conflict, false, false); err != nil {
klog.Error(err)
return err
}
} else {
if err = configureNic(ifName, ipAddr, macAddr, mtu, detectIPv4Conflict, true, false); err != nil {
klog.Error(err)
return err
}
}
if isDefaultRoute {
// Only eth0 requires the default route and gateway
containerGw := gateway
if u2oInterconnectionIP != "" {
containerGw = u2oInterconnectionIP
}
for _, gw := range strings.Split(containerGw, ",") {
if err = netlink.RouteReplace(&netlink.Route{
LinkIndex: containerLink.Attrs().Index,
Scope: netlink.SCOPE_UNIVERSE,
Gw: net.ParseIP(gw),
}); err != nil {
return fmt.Errorf("failed to configure default gateway %s: %w", gw, err)
}
}
}
for _, r := range routes {
var dst *net.IPNet
if r.Destination != "" {
if _, dst, err = net.ParseCIDR(r.Destination); err != nil {
klog.Errorf("invalid route destination %s: %v", r.Destination, err)
continue
}
}
var gw net.IP
if r.Gateway != "" {
if gw = net.ParseIP(r.Gateway); gw == nil {
klog.Errorf("invalid route gateway %s", r.Gateway)
continue
}
}
route := &netlink.Route{
Dst: dst,
Gw: gw,
LinkIndex: containerLink.Attrs().Index,
}
if err = netlink.RouteReplace(route); err != nil {
klog.Errorf("failed to add route %+v: %v", r, err)
}
}
linkRoutes, err := netlink.RouteList(containerLink, netlink.FAMILY_ALL)
if err != nil {
return fmt.Errorf("failed to get routes on interface %s: %w", ifName, err)
}
for _, r := range linkRoutes {
if r.Family != netlink.FAMILY_V4 && r.Family != netlink.FAMILY_V6 {
continue
}
if r.Dst == nil && r.Gw == nil {
continue
}
if r.Dst != nil && r.Dst.IP.IsLinkLocalUnicast() {
if _, bits := r.Dst.Mask.Size(); bits == net.IPv6len*8 {
// skip fe80::/10
continue
}
}
var route request.Route
if r.Dst != nil {
route.Destination = r.Dst.String()
}
if r.Gw != nil {
route.Gateway = r.Gw.String()
}
finalRoutes = append(finalRoutes, route)
}
if gwCheckMode != gatewayCheckModeDisabled {
underlayGateway := gwCheckMode == gatewayCheckModeArping || gwCheckMode == gatewayCheckModeArpingNotConcerned
if u2oInterconnectionIP != "" {
if err = csh.checkGatewayReady(podName, podNamespace, gwCheckMode, interfaceName, ipAddr, u2oInterconnectionIP, false, true); err != nil {
klog.Error(err)
return err
}
}
if err = csh.checkGatewayReady(podName, podNamespace, gwCheckMode, interfaceName, ipAddr, gateway, underlayGateway, true); err != nil {
klog.Error(err)
return err
}
}
if checkIPv6DAD {
// check whether the ipv6 address has a dadfailed flag
addresses, err := netlink.AddrList(containerLink, netlink.FAMILY_V6)
if err != nil {
err = fmt.Errorf("failed to get ipv6 addresses of link %s: %w", interfaceName, err)
klog.Error(err)
return err
}
for _, addr := range addresses {
if addr.Flags&syscall.IFA_F_DADFAILED != 0 {
err = fmt.Errorf("IPv6 address %s has a dadfailed flag, please check whether it has been used by another host", addr.IP.String())
klog.Error(err)
return err
}
}
}
return nil
})
return finalRoutes, err
}
func (csh cniServerHandler) checkGatewayReady(podName, podNamespace string, gwCheckMode int, intr, ipAddr, gateway string, underlayGateway, verbose bool) error {
if gwCheckMode == gatewayCheckModeArpingNotConcerned || gwCheckMode == gatewayCheckModePingNotConcerned {
// ignore error if disableGatewayCheck=true
_ = waitNetworkReady(intr, ipAddr, gateway, underlayGateway, verbose, 1, nil)
return nil
}
done := make(chan struct{}, 1)
go func() {
interval := 5 * time.Second
timer := time.NewTimer(interval)
for {
select {
case <-done:
return
case <-timer.C:
}
pod, err := csh.KubeClient.CoreV1().Pods(podNamespace).Get(context.Background(), podName, metav1.GetOptions{})
if err != nil {
if !k8serrors.IsNotFound(err) {
klog.Errorf("failed to get pod %s/%s: %v", podNamespace, podName, err)
continue
}
pod = nil
}
if pod == nil || !pod.DeletionTimestamp.IsZero() {
// TODO: check pod UID
select {
case <-done:
case done <- struct{}{}:
}
return
}
timer.Reset(interval)
}
}()
return waitNetworkReady(intr, ipAddr, gateway, underlayGateway, verbose, gatewayCheckMaxRetry, done)
}
func waitNetworkReady(nic, ipAddr, gateway string, underlayGateway, verbose bool, maxRetry int, done chan struct{}) error {
ips := strings.Split(ipAddr, ",")
for i, gw := range strings.Split(gateway, ",") {
src := strings.Split(ips[i], "/")[0]
if underlayGateway && util.CheckProtocol(gw) == kubeovnv1.ProtocolIPv4 {
mac, count, err := util.ArpResolve(nic, gw, time.Second, maxRetry, done)
cniConnectivityResult.WithLabelValues(nodeName).Add(float64(count))
if err != nil {
err = fmt.Errorf("network %s with gateway %s is not ready for interface %s after %d checks: %w", ips[i], gw, nic, count, err)
klog.Warning(err)
return err
}
if verbose {
klog.Infof("MAC addresses of gateway %s is %s", gw, mac.String())
klog.Infof("network %s with gateway %s is ready for interface %s after %d checks", ips[i], gw, nic, count)
}
} else {
_, err := pingGateway(gw, src, verbose, maxRetry, done)
if err != nil {
klog.Error(err)
return err
}
}
}
return nil
}
func configureNodeNic(cs kubernetes.Interface, nodeName, portName, ip, gw, joinCIDR string, macAddr net.HardwareAddr, mtu int) error {
ipStr := util.GetIPWithoutMask(ip)
raw, err := ovs.Exec(ovs.MayExist, "add-port", "br-int", util.NodeNic, "--",
"set", "interface", util.NodeNic, "type=internal", "--",
"set", "interface", util.NodeNic, fmt.Sprintf("external_ids:iface-id=%s", portName),
fmt.Sprintf("external_ids:ip=%s", ipStr))
if err != nil {
klog.Errorf("failed to configure node nic %s: %v, %q", portName, err, raw)
return errors.New(raw)
}
if err = configureNic(util.NodeNic, ip, macAddr, mtu, false, false, true); err != nil {
klog.Error(err)
return err
}
hostLink, err := netlink.LinkByName(util.NodeNic)
if err != nil {
return fmt.Errorf("can not find nic %s: %w", util.NodeNic, err)
}
if err = netlink.LinkSetTxQLen(hostLink, 1000); err != nil {
return fmt.Errorf("can not set host nic %s qlen: %w", util.NodeNic, err)
}
// check and add default route for ovn0 in case of can not add automatically
nodeNicRoutes, err := getNicExistRoutes(hostLink, gw)
if err != nil {
klog.Error(err)
return err
}
var toAdd []netlink.Route
for _, c := range strings.Split(joinCIDR, ",") {
found := false
for _, r := range nodeNicRoutes {
if r.Dst.String() == c {
found = true
break
}
}
if !found {
protocol := util.CheckProtocol(c)
var src net.IP
var priority int
if protocol == kubeovnv1.ProtocolIPv4 {
for _, ip := range strings.Split(ipStr, ",") {
if util.CheckProtocol(ip) == protocol {
src = net.ParseIP(ip)
break
}
}
} else {
priority = 256
}
_, cidr, _ := net.ParseCIDR(c)
toAdd = append(toAdd, netlink.Route{
Dst: cidr,
Src: src,
Protocol: netlink.RouteProtocol(unix.RTPROT_KERNEL),
Scope: netlink.SCOPE_LINK,
Priority: priority,
})
}
}
if len(toAdd) > 0 {
klog.Infof("routes to be added on nic %s: %v", util.NodeNic, toAdd)
}
for _, r := range toAdd {
r.LinkIndex = hostLink.Attrs().Index
klog.Infof("adding route %q on %s", r.String(), hostLink.Attrs().Name)
if err = netlink.RouteReplace(&r); err != nil && !errors.Is(err, syscall.EEXIST) {
klog.Errorf("failed to replace route %v: %v", r, err)
}
}
// ping ovn0 gw to activate the flow
klog.Infof("wait ovn0 gw ready")
status := corev1.ConditionFalse
reason := "JoinSubnetGatewayReachable"
message := fmt.Sprintf("ping check to gateway ip %s succeeded", gw)
if err = waitNetworkReady(util.NodeNic, ip, gw, false, true, gatewayCheckMaxRetry, nil); err != nil {
klog.Errorf("failed to init ovn0 check: %v", err)
status = corev1.ConditionTrue
reason = "JoinSubnetGatewayUnreachable"
message = fmt.Sprintf("ping check to gateway ip %s failed", gw)
}
if err := util.SetNodeNetworkUnavailableCondition(cs, nodeName, status, reason, message); err != nil {
klog.Errorf("failed to set node network unavailable condition: %v", err)
}
return err
}
// If OVS restart, the ovn0 port will down and prevent host to pod network,
// Restart the kube-ovn-cni when this happens
func (c *Controller) loopOvn0Check() {
link, err := netlink.LinkByName(util.NodeNic)
if err != nil {
util.LogFatalAndExit(err, "failed to get ovn0 nic")
}
if link.Attrs().OperState == netlink.OperDown {
util.LogFatalAndExit(err, "ovn0 nic is down")
}
node, err := c.nodesLister.Get(c.config.NodeName)
if err != nil {
klog.Errorf("failed to get node %s: %v", c.config.NodeName, err)
return
}
ip := node.Annotations[util.IPAddressAnnotation]
gw := node.Annotations[util.GatewayAnnotation]
status := corev1.ConditionFalse
reason := "JoinSubnetGatewayReachable"
message := fmt.Sprintf("ping check to gateway ip %s succeeded", gw)
if err = waitNetworkReady(util.NodeNic, ip, gw, false, false, 5, nil); err != nil {
klog.Errorf("failed to init ovn0 check: %v", err)
status = corev1.ConditionTrue
reason = "JoinSubnetGatewayUnreachable"
message = fmt.Sprintf("ping check to gateway ip %s failed", gw)
}
var alreadySet bool
for _, condition := range node.Status.Conditions {
if condition.Type == corev1.NodeNetworkUnavailable && condition.Status == corev1.ConditionTrue &&
condition.Reason == reason && condition.Message == message {
alreadySet = true
break
}
}
if !alreadySet {
if err := util.SetNodeNetworkUnavailableCondition(c.config.KubeClient, c.config.NodeName, status, reason, message); err != nil {
klog.Errorf("failed to set node network unavailable condition: %v", err)
}
}
if err != nil {
util.LogFatalAndExit(err, "failed to ping ovn0 gateway %s", gw)
}
}
// This method checks the status of the tunnel interface,
// If the interface is found to be down, it attempts to bring it up
func (c *Controller) loopTunnelCheck() {
tunnelType := c.config.NetworkType
var tunnelNic string
switch tunnelType {
case "vxlan":
tunnelNic = util.VxlanNic
case "geneve":
tunnelNic = util.GeneveNic
case "stt":
// TODO: tunnelNic = "stt tunnel nic name"
return
default:
return
}
link, err := netlink.LinkByName(tunnelNic)
if err != nil || link == nil {
return
}
if link.Attrs().OperState == netlink.OperDown {
klog.Errorf("nic: %s is down, attempting to bring it up", tunnelNic)
if err := netlink.LinkSetUp(link); err != nil {
klog.Errorf("fail to bring up nic: %s, %v", tunnelNic, err)
}
}
}
func (c *Controller) checkNodeGwNicInNs(nodeExtIP, ip, gw string, gwNS ns.NetNS) error {
exists, err := ovs.PortExists(util.NodeGwNic)
if err != nil {
klog.Error(err)
return err
}
filters := labels.Set{util.OvnEipTypeLabel: util.OvnEipTypeLRP}
ovnEips, err := c.ovnEipsLister.List(labels.SelectorFromSet(filters))
if err != nil {
klog.Errorf("failed to list ovn eip, %v", err)
return err
}
if len(ovnEips) == 0 {
klog.Errorf("failed to get type %s ovn eip, %v", util.OvnEipTypeLRP, err)
// node ext gw eip need lrp eip to establish bfd session
return nil
}
if exists {
return ns.WithNetNSPath(gwNS.Path(), func(_ ns.NetNS) error {
err = waitNetworkReady(util.NodeGwNic, ip, gw, true, true, 3, nil)
if err == nil {
if output, err := exec.Command("bfdd-control", "status").CombinedOutput(); err != nil {
err := fmt.Errorf("failed to get bfdd status, %w, %s", err, output)
klog.Error(err)
return err
}
for _, eip := range ovnEips {
if eip.Status.Ready {
// #nosec G204
cmd := exec.Command("bfdd-control", "status", "remote", eip.Spec.V4Ip, "local", nodeExtIP)
var outb bytes.Buffer
cmd.Stdout = &outb
if err := cmd.Run(); err == nil {
out := outb.String()
klog.V(3).Info(out)
if strings.Contains(out, "No session") {
// not exist
cmd = exec.Command("bfdd-control", "allow", eip.Spec.V4Ip) // #nosec G204
if err := cmd.Run(); err != nil {
err := fmt.Errorf("failed to add lrp %s ip %s into bfd listening list, %w", eip.Name, eip.Status.V4Ip, err)
klog.Error(err)
return err
}
}
} else {
err := fmt.Errorf("faild to check bfd status remote %s local %s", eip.Spec.V4Ip, nodeExtIP)
klog.Error(err)
return err
}
}
}
}
return err
})
}
err = errors.New("node external gw not ready")
klog.Error(err)
return err
}
func configureNodeGwNic(portName, ip, gw string, macAddr net.HardwareAddr, mtu int, gwNS ns.NetNS) error {
ipStr := util.GetIPWithoutMask(ip)
output, err := ovs.Exec(ovs.MayExist, "add-port", "br-int", util.NodeGwNic, "--",
"set", "interface", util.NodeGwNic, "type=internal", "--",
"set", "interface", util.NodeGwNic, fmt.Sprintf("external_ids:iface-id=%s", portName),
fmt.Sprintf("external_ids:ip=%s", ipStr),
fmt.Sprintf("external_ids:pod_netns=%s", util.NodeGwNsPath))
if err != nil {
klog.Errorf("failed to configure node external nic %s: %v, %q", portName, err, output)
return errors.New(output)
}
gwLink, err := netlink.LinkByName(util.NodeGwNic)
if err == nil {
fd := int(gwNS.Fd()) // #nosec G115
if err = netlink.LinkSetNsFd(gwLink, fd); err != nil {
klog.Errorf("failed to move link into netns: %v", err)
return err
}
} else {
klog.V(3).Infof("node external nic %q already in ns %s", util.NodeGwNic, util.NodeGwNsPath)
}
return ns.WithNetNSPath(gwNS.Path(), func(_ ns.NetNS) error {
if err = configureNic(util.NodeGwNic, ip, macAddr, mtu, true, false, false); err != nil {
klog.Errorf("failed to configure node gw nic %s, %v", util.NodeGwNic, err)
return err
}
if err = configureLoNic(); err != nil {
klog.Errorf("failed to configure nic %s, %v", util.LoNic, err)
return err
}
gwLink, err = netlink.LinkByName(util.NodeGwNic)
if err != nil {
klog.Errorf("failed to get link %q, %v", util.NodeGwNic, err)
return err
}
switch util.CheckProtocol(ip) {
case kubeovnv1.ProtocolIPv4:
_, defaultNet, _ := net.ParseCIDR("0.0.0.0/0")
err = netlink.RouteReplace(&netlink.Route{
LinkIndex: gwLink.Attrs().Index,
Scope: netlink.SCOPE_UNIVERSE,
Dst: defaultNet,
Gw: net.ParseIP(gw),
})
case kubeovnv1.ProtocolIPv6:
_, defaultNet, _ := net.ParseCIDR("::/0")
err = netlink.RouteReplace(&netlink.Route{
LinkIndex: gwLink.Attrs().Index,
Scope: netlink.SCOPE_UNIVERSE,
Dst: defaultNet,
Gw: net.ParseIP(gw),
})
case kubeovnv1.ProtocolDual:
gws := strings.Split(gw, ",")
_, defaultNet, _ := net.ParseCIDR("0.0.0.0/0")
err = netlink.RouteReplace(&netlink.Route{
LinkIndex: gwLink.Attrs().Index,
Scope: netlink.SCOPE_UNIVERSE,
Dst: defaultNet,
Gw: net.ParseIP(gws[0]),
})
if err != nil {
return fmt.Errorf("config v4 gateway failed: %w", err)
}
_, defaultNet, _ = net.ParseCIDR("::/0")
err = netlink.RouteReplace(&netlink.Route{
LinkIndex: gwLink.Attrs().Index,
Scope: netlink.SCOPE_UNIVERSE,
Dst: defaultNet,
Gw: net.ParseIP(gws[1]),
})
}
if err != nil {
return fmt.Errorf("failed to configure gateway: %w", err)
}
cmd := exec.Command("bfdd-beacon", "--listen=0.0.0.0")
if err := cmd.Run(); err != nil {
err := fmt.Errorf("failed to get start bfd listen, %w", err)
klog.Error(err)
return err
}
return waitNetworkReady(util.NodeGwNic, ip, gw, true, true, 3, nil)
})
}
func removeNodeGwNic() error {
if _, err := ovs.Exec(ovs.IfExists, "del-port", "br-int", util.NodeGwNic); err != nil {
return fmt.Errorf("failed to remove ecmp external port %s from OVS bridge %s: %w", "br-int", util.NodeGwNic, err)
}
klog.Infof("removed node external gw nic %q", util.NodeGwNic)
return nil
}
func removeNodeGwNs() error {
ns := netns.LoadNetNS(util.NodeGwNsPath)
ok, err := ns.Closed()
if err != nil {
return fmt.Errorf("failed to remove node external gw ns %s: %w", util.NodeGwNs, err)
}
if !ok {
if err = ns.Remove(); err != nil {
return fmt.Errorf("failed to remove node external gw ns %s: %w", util.NodeGwNs, err)
}
}
klog.Infof("node external gw ns %s removed", util.NodeGwNs)
return nil
}
func (c *Controller) loopOvnExt0Check() {
node, err := c.nodesLister.Get(c.config.NodeName)
if err != nil {
klog.Errorf("failed to get node %s: %v", c.config.NodeName, err)
return
}
portName := node.Name
needClean := false
cachedEip, err := c.ovnEipsLister.Get(portName)
if err != nil {
if k8serrors.IsNotFound(err) {
val, ok := node.Labels[util.NodeExtGwLabel]
if !ok {
// not gw node before
return
}
if val == "false" {
// already clean
return
}
if val == "true" {
needClean = true
}
} else {
klog.Errorf("failed to get ecmp gateway ovn eip, %v", err)
return
}
}
if needClean {
if err := removeNodeGwNic(); err != nil {
klog.Error(err)
return
}
if err := removeNodeGwNs(); err != nil {
klog.Error(err)
return
}
if err = c.patchNodeExternalGwLabel(false); err != nil {
klog.Errorf("failed to patch labels of node %s: %v", node.Name, err)
return
}