• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

kubeovn / kube-ovn / 20688122676

04 Jan 2026 05:18AM UTC coverage: 22.584% (-0.03%) from 22.616%
20688122676

push

github

web-flow
Add open flow sync refer to ovn-k8s (#6117)

* add openflow sync refer to ovn-k8s

Signed-off-by: clyi <clyi@alauda.io>

0 of 180 new or added lines in 5 files covered. (0.0%)

3 existing lines in 2 files now uncovered.

12067 of 53432 relevant lines covered (22.58%)

0.26 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

0.0
/pkg/daemon/controller_linux.go
1
package daemon
2

3
import (
4
        "errors"
5
        "fmt"
6
        "net"
7
        "os"
8
        "os/exec"
9
        "path/filepath"
10
        "reflect"
11
        "slices"
12
        "strings"
13
        "sync"
14
        "syscall"
15

16
        ovsutil "github.com/digitalocean/go-openvswitch/ovs"
17
        nadv1 "github.com/k8snetworkplumbingwg/network-attachment-definition-client/pkg/apis/k8s.cni.cncf.io/v1"
18
        nadutils "github.com/k8snetworkplumbingwg/network-attachment-definition-client/pkg/utils"
19
        "github.com/kubeovn/felix/ipsets"
20
        "github.com/kubeovn/go-iptables/iptables"
21
        "github.com/vishvananda/netlink"
22
        "golang.org/x/sys/unix"
23
        v1 "k8s.io/api/core/v1"
24
        k8serrors "k8s.io/apimachinery/pkg/api/errors"
25
        "k8s.io/apimachinery/pkg/labels"
26
        utilruntime "k8s.io/apimachinery/pkg/util/runtime"
27
        "k8s.io/client-go/tools/cache"
28
        "k8s.io/klog/v2"
29
        k8sipset "k8s.io/kubernetes/pkg/proxy/ipvs/ipset"
30
        k8siptables "k8s.io/kubernetes/pkg/util/iptables"
31

32
        kubeovnv1 "github.com/kubeovn/kube-ovn/pkg/apis/kubeovn/v1"
33
        "github.com/kubeovn/kube-ovn/pkg/ovs"
34
        "github.com/kubeovn/kube-ovn/pkg/util"
35
)
36

37
const (
38
        kernelModuleIPTables  = "ip_tables"
39
        kernelModuleIP6Tables = "ip6_tables"
40
)
41

42
// ControllerRuntime represents runtime specific controller members
43
type ControllerRuntime struct {
44
        iptables         map[string]*iptables.IPTables
45
        iptablesObsolete map[string]*iptables.IPTables
46
        k8siptables      map[string]k8siptables.Interface
47
        k8sipsets        k8sipset.Interface
48
        ipsets           map[string]*ipsets.IPSets
49
        gwCounters       map[string]*util.GwIPtableCounters
50

51
        nmSyncer  *networkManagerSyncer
52
        ovsClient *ovsutil.Client
53

54
        flowCache      map[string]map[string][]string // key: bridgeName -> flowKey -> flow rules
55
        flowCacheMutex sync.RWMutex
56
        flowChan       chan struct{} // channel to trigger immediate flow sync
57
}
58

59
type LbServiceRules struct {
60
        IP          string
61
        Port        uint16
62
        Protocol    string
63
        BridgeName  string
64
        DstMac      string
65
        UnderlayNic string
66
}
67

68
func evalCommandSymlinks(cmd string) (string, error) {
×
69
        path, err := exec.LookPath(cmd)
×
70
        if err != nil {
×
71
                return "", fmt.Errorf("failed to search for command %q: %w", cmd, err)
×
72
        }
×
73
        file, err := filepath.EvalSymlinks(path)
×
74
        if err != nil {
×
75
                return "", fmt.Errorf("failed to read evaluate symbolic links for file %q: %w", path, err)
×
76
        }
×
77

78
        return file, nil
×
79
}
80

81
func isLegacyIptablesMode() (bool, error) {
×
82
        path, err := evalCommandSymlinks("iptables")
×
83
        if err != nil {
×
84
                return false, err
×
85
        }
×
86
        pathLegacy, err := evalCommandSymlinks("iptables-legacy")
×
87
        if err != nil {
×
88
                return false, err
×
89
        }
×
90
        return path == pathLegacy, nil
×
91
}
92

93
func (c *Controller) initRuntime() error {
×
94
        ok, err := isLegacyIptablesMode()
×
95
        if err != nil {
×
96
                klog.Errorf("failed to check iptables mode: %v", err)
×
97
                return err
×
98
        }
×
99
        if !ok {
×
100
                // iptables works in nft mode, we should migrate iptables rules
×
101
                c.iptablesObsolete = make(map[string]*iptables.IPTables, 2)
×
102
        }
×
103

104
        c.iptables = make(map[string]*iptables.IPTables)
×
105
        c.ipsets = make(map[string]*ipsets.IPSets)
×
106
        c.gwCounters = make(map[string]*util.GwIPtableCounters)
×
107
        c.k8siptables = make(map[string]k8siptables.Interface)
×
108
        c.k8sipsets = k8sipset.New()
×
109
        c.ovsClient = ovsutil.New()
×
110

×
NEW
111
        // Initialize OpenFlow flow cache (ovn-kubernetes style)
×
NEW
112
        c.flowCache = make(map[string]map[string][]string)
×
NEW
113
        c.flowChan = make(chan struct{}, 1)
×
NEW
114

×
115
        if c.protocol == kubeovnv1.ProtocolIPv4 || c.protocol == kubeovnv1.ProtocolDual {
×
116
                ipt, err := iptables.NewWithProtocol(iptables.ProtocolIPv4)
×
117
                if err != nil {
×
118
                        klog.Error(err)
×
119
                        return err
×
120
                }
×
121
                c.iptables[kubeovnv1.ProtocolIPv4] = ipt
×
122
                if c.iptablesObsolete != nil {
×
123
                        ok, err := kernelModuleLoaded(kernelModuleIPTables)
×
124
                        if err != nil {
×
125
                                klog.Errorf("failed to check kernel module %s: %v", kernelModuleIPTables, err)
×
126
                        }
×
127
                        if ok {
×
128
                                if ipt, err = iptables.NewWithProtocolAndMode(iptables.ProtocolIPv4, "legacy"); err != nil {
×
129
                                        klog.Error(err)
×
130
                                        return err
×
131
                                }
×
132
                                c.iptablesObsolete[kubeovnv1.ProtocolIPv4] = ipt
×
133
                        }
134
                }
135
                c.ipsets[kubeovnv1.ProtocolIPv4] = ipsets.NewIPSets(ipsets.NewIPVersionConfig(ipsets.IPFamilyV4, IPSetPrefix, nil, nil))
×
136
                c.k8siptables[kubeovnv1.ProtocolIPv4] = k8siptables.New(k8siptables.ProtocolIPv4)
×
137
        }
138
        if c.protocol == kubeovnv1.ProtocolIPv6 || c.protocol == kubeovnv1.ProtocolDual {
×
139
                ipt, err := iptables.NewWithProtocol(iptables.ProtocolIPv6)
×
140
                if err != nil {
×
141
                        klog.Error(err)
×
142
                        return err
×
143
                }
×
144
                c.iptables[kubeovnv1.ProtocolIPv6] = ipt
×
145
                if c.iptablesObsolete != nil {
×
146
                        ok, err := kernelModuleLoaded(kernelModuleIP6Tables)
×
147
                        if err != nil {
×
148
                                klog.Errorf("failed to check kernel module %s: %v", kernelModuleIP6Tables, err)
×
149
                        }
×
150
                        if ok {
×
151
                                if ipt, err = iptables.NewWithProtocolAndMode(iptables.ProtocolIPv6, "legacy"); err != nil {
×
152
                                        klog.Error(err)
×
153
                                        return err
×
154
                                }
×
155
                                c.iptablesObsolete[kubeovnv1.ProtocolIPv6] = ipt
×
156
                        }
157
                }
158
                c.ipsets[kubeovnv1.ProtocolIPv6] = ipsets.NewIPSets(ipsets.NewIPVersionConfig(ipsets.IPFamilyV6, IPSetPrefix, nil, nil))
×
159
                c.k8siptables[kubeovnv1.ProtocolIPv6] = k8siptables.New(k8siptables.ProtocolIPv6)
×
160
        }
161

162
        if err = ovs.ClearU2OFlows(c.ovsClient); err != nil {
×
163
                util.LogFatalAndExit(err, "failed to clear obsolete u2o flows")
×
164
        }
×
165

166
        c.nmSyncer = newNetworkManagerSyncer()
×
167
        c.nmSyncer.Run(c.transferAddrsAndRoutes)
×
168

×
169
        return nil
×
170
}
171

172
func (c *Controller) handleEnableExternalLBAddressChange(oldSubnet, newSubnet *kubeovnv1.Subnet) error {
×
173
        var subnetName string
×
174
        var action string
×
175

×
176
        switch {
×
177
        case oldSubnet != nil && newSubnet != nil:
×
178
                subnetName = oldSubnet.Name
×
179
                if oldSubnet.Spec.EnableExternalLBAddress != newSubnet.Spec.EnableExternalLBAddress {
×
180
                        klog.Infof("EnableExternalLBAddress changed for subnet %s", newSubnet.Name)
×
181
                        if newSubnet.Spec.EnableExternalLBAddress {
×
182
                                action = "add"
×
183
                        } else {
×
184
                                action = "remove"
×
185
                        }
×
186
                }
187
        case oldSubnet != nil:
×
188
                subnetName = oldSubnet.Name
×
189
                if oldSubnet.Spec.EnableExternalLBAddress {
×
190
                        klog.Infof("EnableExternalLBAddress removed for subnet %s", oldSubnet.Name)
×
191
                        action = "remove"
×
192
                }
×
193
        case newSubnet != nil:
×
194
                subnetName = newSubnet.Name
×
195
                if newSubnet.Spec.EnableExternalLBAddress {
×
196
                        klog.Infof("EnableExternalLBAddress added for subnet %s", newSubnet.Name)
×
197
                        action = "add"
×
198
                }
×
199
        }
200

201
        if action != "" {
×
202
                services, err := c.servicesLister.List(labels.Everything())
×
203
                if err != nil {
×
204
                        klog.Errorf("failed to list services: %v", err)
×
205
                        return err
×
206
                }
×
207

208
                for _, svc := range services {
×
209
                        if svc.Annotations[util.ServiceExternalIPFromSubnetAnnotation] == subnetName {
×
210
                                klog.Infof("Service %s/%s has external LB address pool annotation from subnet %s, action: %s", svc.Namespace, svc.Name, subnetName, action)
×
211
                                switch action {
×
212
                                case "add":
×
213
                                        c.serviceQueue.Add(&serviceEvent{newObj: svc})
×
214
                                case "remove":
×
215
                                        c.serviceQueue.Add(&serviceEvent{oldObj: svc})
×
216
                                }
217
                        }
218
                }
219
        }
220
        return nil
×
221
}
222

223
func (c *Controller) reconcileRouters(event *subnetEvent) error {
×
224
        subnets, err := c.subnetsLister.List(labels.Everything())
×
225
        if err != nil {
×
226
                klog.Errorf("failed to list subnets %v", err)
×
227
                return err
×
228
        }
×
229

230
        if event != nil {
×
231
                var ok bool
×
232
                var oldSubnet, newSubnet *kubeovnv1.Subnet
×
233
                if event.oldObj != nil {
×
234
                        if oldSubnet, ok = event.oldObj.(*kubeovnv1.Subnet); !ok {
×
235
                                klog.Errorf("expected old subnet in subnetEvent but got %#v", event.oldObj)
×
236
                                return nil
×
237
                        }
×
238
                }
239
                if event.newObj != nil {
×
240
                        if newSubnet, ok = event.newObj.(*kubeovnv1.Subnet); !ok {
×
241
                                klog.Errorf("expected new subnet in subnetEvent but got %#v", event.newObj)
×
242
                                return nil
×
243
                        }
×
244
                }
245

246
                if err = c.handleEnableExternalLBAddressChange(oldSubnet, newSubnet); err != nil {
×
247
                        klog.Errorf("failed to handle enable external lb address change: %v", err)
×
248
                        return err
×
249
                }
×
250
                // handle policy routing
251
                rulesToAdd, rulesToDel, routesToAdd, routesToDel, err := c.diffPolicyRouting(oldSubnet, newSubnet)
×
252
                if err != nil {
×
253
                        klog.Errorf("failed to get policy routing difference: %v", err)
×
254
                        return err
×
255
                }
×
256
                // add new routes first
257
                for _, r := range routesToAdd {
×
258
                        if err = netlink.RouteReplace(&r); err != nil && !errors.Is(err, syscall.EEXIST) {
×
259
                                klog.Errorf("failed to replace route for subnet %s: %v", newSubnet.Name, err)
×
260
                                return err
×
261
                        }
×
262
                }
263
                // next, add new rules
264
                for _, r := range rulesToAdd {
×
265
                        if err = netlink.RuleAdd(&r); err != nil && !errors.Is(err, syscall.EEXIST) {
×
266
                                klog.Errorf("failed to add network rule for subnet %s: %v", newSubnet.Name, err)
×
267
                                return err
×
268
                        }
×
269
                }
270
                // then delete old network rules
271
                for _, r := range rulesToDel {
×
272
                        // loop to delete all matched rules
×
273
                        for {
×
274
                                if err = netlink.RuleDel(&r); err != nil {
×
275
                                        if !errors.Is(err, syscall.ENOENT) {
×
276
                                                klog.Errorf("failed to delete network rule for subnet %s: %v", oldSubnet.Name, err)
×
277
                                                return err
×
278
                                        }
×
279
                                        break
×
280
                                }
281
                        }
282
                }
283
                // last, delete old network routes
284
                for _, r := range routesToDel {
×
285
                        if err = netlink.RouteDel(&r); err != nil && !errors.Is(err, syscall.ENOENT) {
×
286
                                klog.Errorf("failed to delete route for subnet %s: %v", oldSubnet.Name, err)
×
287
                                return err
×
288
                        }
×
289
                }
290
        }
291

292
        node, err := c.nodesLister.Get(c.config.NodeName)
×
293
        if err != nil {
×
294
                klog.Errorf("failed to get node %s %v", c.config.NodeName, err)
×
295
                return err
×
296
        }
×
297
        nodeIPv4, nodeIPv6 := util.GetNodeInternalIP(*node)
×
298
        var joinIPv4, joinIPv6 string
×
299
        if len(node.Annotations) != 0 {
×
300
                joinIPv4, joinIPv6 = util.SplitStringIP(node.Annotations[util.IPAddressAnnotation])
×
301
        }
×
302

303
        joinCIDR := make([]string, 0, 2)
×
304
        cidrs := make([]string, 0, len(subnets)*2)
×
305
        for _, subnet := range subnets {
×
306
                // The route for overlay subnet cidr via ovn0 should not be deleted even though subnet.Status has changed to not ready
×
307
                if subnet.Spec.Vpc != c.config.ClusterRouter ||
×
308
                        (subnet.Spec.Vlan != "" && !subnet.Spec.LogicalGateway && (!subnet.Spec.U2OInterconnection || (subnet.Spec.EnableLb != nil && *subnet.Spec.EnableLb))) ||
×
309
                        !subnet.Status.IsValidated() {
×
310
                        continue
×
311
                }
312

313
                for cidrBlock := range strings.SplitSeq(subnet.Spec.CIDRBlock, ",") {
×
314
                        if _, ipNet, err := net.ParseCIDR(cidrBlock); err != nil {
×
315
                                klog.Errorf("%s is not a valid cidr block", cidrBlock)
×
316
                        } else {
×
317
                                if nodeIPv4 != "" && util.CIDRContainIP(cidrBlock, nodeIPv4) {
×
318
                                        continue
×
319
                                }
320
                                if nodeIPv6 != "" && util.CIDRContainIP(cidrBlock, nodeIPv6) {
×
321
                                        continue
×
322
                                }
323
                                cidrs = append(cidrs, ipNet.String())
×
324
                                if subnet.Name == c.config.NodeSwitch {
×
325
                                        joinCIDR = append(joinCIDR, ipNet.String())
×
326
                                }
×
327
                        }
328
                }
329
        }
330

331
        gateway, ok := node.Annotations[util.GatewayAnnotation]
×
332
        if !ok {
×
333
                err = fmt.Errorf("gateway annotation for node %s does not exist", node.Name)
×
334
                klog.Error(err)
×
335
                return err
×
336
        }
×
337
        nic, err := netlink.LinkByName(util.NodeNic)
×
338
        if err != nil {
×
339
                klog.Errorf("failed to get nic %s", util.NodeNic)
×
340
                return fmt.Errorf("failed to get nic %s", util.NodeNic)
×
341
        }
×
342

343
        allRoutes, err := getNicExistRoutes(nil, gateway)
×
344
        if err != nil {
×
345
                klog.Error(err)
×
346
                return err
×
347
        }
×
348
        nodeNicRoutes, err := getNicExistRoutes(nic, gateway)
×
349
        if err != nil {
×
350
                klog.Error(err)
×
351
                return err
×
352
        }
×
353
        toAdd, toDel := routeDiff(nodeNicRoutes, allRoutes, cidrs, joinCIDR, joinIPv4, joinIPv6, gateway, net.ParseIP(nodeIPv4), net.ParseIP(nodeIPv6))
×
354
        for _, r := range toDel {
×
355
                if err = netlink.RouteDel(&netlink.Route{Dst: r.Dst}); err != nil {
×
356
                        klog.Errorf("failed to del route %v", err)
×
357
                }
×
358
        }
359

360
        for _, r := range toAdd {
×
361
                r.LinkIndex = nic.Attrs().Index
×
362
                if err = netlink.RouteReplace(&r); err != nil {
×
363
                        klog.Errorf("failed to replace route %v: %v", r, err)
×
364
                }
×
365
        }
366

367
        return nil
×
368
}
369

370
func genLBServiceRules(service *v1.Service, bridgeName, underlayNic string) []LbServiceRules {
×
371
        var lbServiceRules []LbServiceRules
×
372
        for _, ingress := range service.Status.LoadBalancer.Ingress {
×
373
                for _, port := range service.Spec.Ports {
×
374
                        lbServiceRules = append(lbServiceRules, LbServiceRules{
×
375
                                IP:          ingress.IP,
×
376
                                Port:        uint16(port.Port), // #nosec G115
×
377
                                Protocol:    string(port.Protocol),
×
378
                                DstMac:      util.MasqueradeExternalLBAccessMac,
×
379
                                UnderlayNic: underlayNic,
×
380
                                BridgeName:  bridgeName,
×
381
                        })
×
382
                }
×
383
        }
384
        return lbServiceRules
×
385
}
386

387
func (c *Controller) diffExternalLBServiceRules(oldService, newService *v1.Service, isSubnetExternalLBEnabled bool) (lbServiceRulesToAdd, lbServiceRulesToDel []LbServiceRules, err error) {
×
388
        var oldlbServiceRules, newlbServiceRules []LbServiceRules
×
389

×
390
        if oldService != nil && oldService.Annotations[util.ServiceExternalIPFromSubnetAnnotation] != "" {
×
391
                oldBridgeName, underlayNic, err := c.getExtInfoBySubnet(oldService.Annotations[util.ServiceExternalIPFromSubnetAnnotation])
×
392
                if err != nil {
×
393
                        klog.Errorf("failed to get provider network by subnet %s: %v", oldService.Annotations[util.ServiceExternalIPFromSubnetAnnotation], err)
×
394
                        return nil, nil, err
×
395
                }
×
396

397
                oldlbServiceRules = genLBServiceRules(oldService, oldBridgeName, underlayNic)
×
398
        }
399

400
        if isSubnetExternalLBEnabled && newService != nil && newService.Annotations[util.ServiceExternalIPFromSubnetAnnotation] != "" {
×
401
                newBridgeName, underlayNic, err := c.getExtInfoBySubnet(newService.Annotations[util.ServiceExternalIPFromSubnetAnnotation])
×
402
                if err != nil {
×
403
                        klog.Errorf("failed to get provider network by subnet %s: %v", newService.Annotations[util.ServiceExternalIPFromSubnetAnnotation], err)
×
404
                        return nil, nil, err
×
405
                }
×
406
                newlbServiceRules = genLBServiceRules(newService, newBridgeName, underlayNic)
×
407
        }
408

409
        for _, oldRule := range oldlbServiceRules {
×
410
                found := slices.Contains(newlbServiceRules, oldRule)
×
411
                if !found {
×
412
                        lbServiceRulesToDel = append(lbServiceRulesToDel, oldRule)
×
413
                }
×
414
        }
415

416
        for _, newRule := range newlbServiceRules {
×
417
                found := slices.Contains(oldlbServiceRules, newRule)
×
418
                if !found {
×
419
                        lbServiceRulesToAdd = append(lbServiceRulesToAdd, newRule)
×
420
                }
×
421
        }
422

423
        return lbServiceRulesToAdd, lbServiceRulesToDel, nil
×
424
}
425

426
func (c *Controller) getExtInfoBySubnet(subnetName string) (string, string, error) {
×
427
        subnet, err := c.subnetsLister.Get(subnetName)
×
428
        if err != nil {
×
429
                klog.Errorf("failed to get subnet %s: %v", subnetName, err)
×
430
                return "", "", err
×
431
        }
×
432

433
        vlanName := subnet.Spec.Vlan
×
434
        if vlanName == "" {
×
435
                return "", "", errors.New("vlan not specified in subnet")
×
436
        }
×
437

438
        vlan, err := c.vlansLister.Get(vlanName)
×
439
        if err != nil {
×
440
                klog.Errorf("failed to get vlan %s: %v", vlanName, err)
×
441
                return "", "", err
×
442
        }
×
443

444
        providerNetworkName := vlan.Spec.Provider
×
445
        if providerNetworkName == "" {
×
446
                return "", "", errors.New("provider network not specified in vlan")
×
447
        }
×
448

449
        pn, err := c.providerNetworksLister.Get(providerNetworkName)
×
450
        if err != nil {
×
451
                klog.Errorf("failed to get provider network %s: %v", providerNetworkName, err)
×
452
                return "", "", err
×
453
        }
×
454

455
        underlayNic := pn.Spec.DefaultInterface
×
456
        for _, item := range pn.Spec.CustomInterfaces {
×
457
                if slices.Contains(item.Nodes, c.config.NodeName) {
×
458
                        underlayNic = item.Interface
×
459
                        break
×
460
                }
461
        }
462
        klog.Infof("Provider network: %s, Underlay NIC: %s", providerNetworkName, underlayNic)
×
463
        return util.ExternalBridgeName(providerNetworkName), underlayNic, nil
×
464
}
465

466
func (c *Controller) reconcileServices(event *serviceEvent) error {
×
467
        if event == nil {
×
468
                return nil
×
469
        }
×
470
        var ok bool
×
471
        var oldService, newService *v1.Service
×
472
        if event.oldObj != nil {
×
473
                if oldService, ok = event.oldObj.(*v1.Service); !ok {
×
474
                        klog.Errorf("expected old service in serviceEvent but got %#v", event.oldObj)
×
475
                        return nil
×
476
                }
×
477
        }
478

479
        if event.newObj != nil {
×
480
                if newService, ok = event.newObj.(*v1.Service); !ok {
×
481
                        klog.Errorf("expected new service in serviceEvent but got %#v", event.newObj)
×
482
                        return nil
×
483
                }
×
484
        }
485

486
        // check is the lb service IP related subnet's EnableExternalLBAddress
487
        isSubnetExternalLBEnabled := false
×
488
        if newService != nil && newService.Annotations[util.ServiceExternalIPFromSubnetAnnotation] != "" {
×
489
                subnet, err := c.subnetsLister.Get(newService.Annotations[util.ServiceExternalIPFromSubnetAnnotation])
×
490
                if err != nil {
×
491
                        klog.Errorf("failed to get subnet %s: %v", newService.Annotations[util.ServiceExternalIPFromSubnetAnnotation], err)
×
492
                        return err
×
493
                }
×
494
                isSubnetExternalLBEnabled = subnet.Spec.EnableExternalLBAddress
×
495
        }
496

497
        lbServiceRulesToAdd, lbServiceRulesToDel, err := c.diffExternalLBServiceRules(oldService, newService, isSubnetExternalLBEnabled)
×
498
        if err != nil {
×
499
                klog.Errorf("failed to get ip port difference: %v", err)
×
500
                return err
×
501
        }
×
502

503
        if len(lbServiceRulesToAdd) > 0 {
×
504
                for _, rule := range lbServiceRulesToAdd {
×
505
                        klog.Infof("Adding LB service rule: %+v", rule)
×
NEW
506
                        if err := c.AddOrUpdateUnderlaySubnetSvcLocalFlowCache(rule.IP, rule.Port, rule.Protocol, rule.DstMac, rule.UnderlayNic, rule.BridgeName); err != nil {
×
NEW
507
                                klog.Errorf("failed to update underlay subnet svc local openflow cache: %v", err)
×
NEW
508
                                return err
×
UNCOV
509
                        }
×
510
                }
511
        }
512

513
        if len(lbServiceRulesToDel) > 0 {
×
514
                for _, rule := range lbServiceRulesToDel {
×
515
                        klog.Infof("Delete LB service rule: %+v", rule)
×
NEW
516
                        c.deleteUnderlaySubnetSvcLocalFlowCache(rule.BridgeName, rule.IP, rule.Port, rule.Protocol)
×
517
                }
×
518
        }
519

520
        return nil
×
521
}
522

523
func getNicExistRoutes(nic netlink.Link, gateway string) ([]netlink.Route, error) {
×
524
        var routes, existRoutes []netlink.Route
×
525
        var err error
×
526
        for gw := range strings.SplitSeq(gateway, ",") {
×
527
                if util.CheckProtocol(gw) == kubeovnv1.ProtocolIPv4 {
×
528
                        routes, err = netlink.RouteList(nic, netlink.FAMILY_V4)
×
529
                } else {
×
530
                        routes, err = netlink.RouteList(nic, netlink.FAMILY_V6)
×
531
                }
×
532
                if err != nil {
×
533
                        return nil, err
×
534
                }
×
535
                existRoutes = append(existRoutes, routes...)
×
536
        }
537
        return existRoutes, nil
×
538
}
539

540
func routeDiff(nodeNicRoutes, allRoutes []netlink.Route, cidrs, joinCIDR []string, joinIPv4, joinIPv6, gateway string, srcIPv4, srcIPv6 net.IP) (toAdd, toDel []netlink.Route) {
×
541
        // joinIPv6 is not used for now
×
542
        _ = joinIPv6
×
543

×
544
        for _, route := range nodeNicRoutes {
×
545
                if route.Scope == netlink.SCOPE_LINK || route.Dst == nil || route.Dst.IP.IsLinkLocalUnicast() {
×
546
                        continue
×
547
                }
548

549
                found := slices.Contains(cidrs, route.Dst.String())
×
550
                if !found {
×
551
                        toDel = append(toDel, route)
×
552
                }
×
553
                conflict := false
×
554
                for _, ar := range allRoutes {
×
555
                        if ar.Dst != nil && ar.Dst.String() == route.Dst.String() && ar.LinkIndex != route.LinkIndex {
×
556
                                // route conflict
×
557
                                conflict = true
×
558
                                break
×
559
                        }
560
                }
561
                if conflict {
×
562
                        toDel = append(toDel, route)
×
563
                }
×
564
        }
565
        if len(toDel) > 0 {
×
566
                klog.Infof("routes to delete: %v", toDel)
×
567
        }
×
568

569
        ipv4, ipv6 := util.SplitStringIP(gateway)
×
570
        gwV4, gwV6 := net.ParseIP(ipv4), net.ParseIP(ipv6)
×
571
        for _, c := range cidrs {
×
572
                var src, gw net.IP
×
573
                switch util.CheckProtocol(c) {
×
574
                case kubeovnv1.ProtocolIPv4:
×
575
                        src, gw = srcIPv4, gwV4
×
576
                case kubeovnv1.ProtocolIPv6:
×
577
                        src, gw = srcIPv6, gwV6
×
578
                }
579

580
                found := false
×
581
                for _, ar := range allRoutes {
×
582
                        if ar.Dst != nil && ar.Dst.String() == c {
×
583
                                if slices.Contains(joinCIDR, c) {
×
584
                                        // Only compare Dst for join subnets
×
585
                                        found = true
×
586
                                        klog.V(3).Infof("[routeDiff] joinCIDR route already exists in allRoutes: %v", ar)
×
587
                                        break
×
588
                                } else if (ar.Src == nil && src == nil) || (ar.Src != nil && src != nil && ar.Src.Equal(src)) {
×
589
                                        // For non-join subnets, both Dst and Src must be the same
×
590
                                        found = true
×
591
                                        klog.V(3).Infof("[routeDiff] route already exists in allRoutes: %v", ar)
×
592
                                        break
×
593
                                }
594
                        }
595
                }
596
                if found {
×
597
                        continue
×
598
                }
599
                for _, r := range nodeNicRoutes {
×
600
                        if r.Dst == nil || r.Dst.String() != c {
×
601
                                continue
×
602
                        }
603
                        if (src == nil && r.Src == nil) || (src != nil && r.Src != nil && src.Equal(r.Src)) {
×
604
                                found = true
×
605
                                break
×
606
                        }
607
                }
608
                if !found {
×
609
                        var priority int
×
610
                        scope := netlink.SCOPE_UNIVERSE
×
611
                        proto := netlink.RouteProtocol(syscall.RTPROT_STATIC)
×
612
                        if slices.Contains(joinCIDR, c) {
×
613
                                if util.CheckProtocol(c) == kubeovnv1.ProtocolIPv4 {
×
614
                                        src = net.ParseIP(joinIPv4)
×
615
                                } else {
×
616
                                        src, priority = nil, 256
×
617
                                }
×
618
                                gw, scope = nil, netlink.SCOPE_LINK
×
619
                                proto = netlink.RouteProtocol(unix.RTPROT_KERNEL)
×
620
                        }
621
                        _, cidr, _ := net.ParseCIDR(c)
×
622
                        toAdd = append(toAdd, netlink.Route{
×
623
                                Dst:      cidr,
×
624
                                Src:      src,
×
625
                                Gw:       gw,
×
626
                                Protocol: proto,
×
627
                                Scope:    scope,
×
628
                                Priority: priority,
×
629
                        })
×
630
                }
631
        }
632
        if len(toAdd) > 0 {
×
633
                klog.Infof("routes to add: %v", toAdd)
×
634
        }
×
635
        return toAdd, toDel
×
636
}
637

638
func getRulesToAdd(oldRules, newRules []netlink.Rule) []netlink.Rule {
×
639
        var toAdd []netlink.Rule
×
640

×
641
        for _, rule := range newRules {
×
642
                var found bool
×
643
                for _, r := range oldRules {
×
644
                        if r.Family == rule.Family && r.Priority == rule.Priority && r.Table == rule.Table && reflect.DeepEqual(r.Src, rule.Src) {
×
645
                                found = true
×
646
                                break
×
647
                        }
648
                }
649
                if !found {
×
650
                        toAdd = append(toAdd, rule)
×
651
                }
×
652
        }
653

654
        return toAdd
×
655
}
656

657
func getRoutesToAdd(oldRoutes, newRoutes []netlink.Route) []netlink.Route {
×
658
        var toAdd []netlink.Route
×
659

×
660
        for _, route := range newRoutes {
×
661
                var found bool
×
662
                for _, r := range oldRoutes {
×
663
                        if r.Equal(route) {
×
664
                                found = true
×
665
                                break
×
666
                        }
667
                }
668
                if !found {
×
669
                        toAdd = append(toAdd, route)
×
670
                }
×
671
        }
672

673
        return toAdd
×
674
}
675

676
func (c *Controller) diffPolicyRouting(oldSubnet, newSubnet *kubeovnv1.Subnet) (rulesToAdd, rulesToDel []netlink.Rule, routesToAdd, routesToDel []netlink.Route, err error) {
×
677
        oldRules, oldRoutes, err := c.getPolicyRouting(oldSubnet)
×
678
        if err != nil {
×
679
                klog.Error(err)
×
680
                return rulesToAdd, rulesToDel, routesToAdd, routesToDel, err
×
681
        }
×
682
        newRules, newRoutes, err := c.getPolicyRouting(newSubnet)
×
683
        if err != nil {
×
684
                klog.Error(err)
×
685
                return rulesToAdd, rulesToDel, routesToAdd, routesToDel, err
×
686
        }
×
687

688
        rulesToAdd = getRulesToAdd(oldRules, newRules)
×
689
        rulesToDel = getRulesToAdd(newRules, oldRules)
×
690
        routesToAdd = getRoutesToAdd(oldRoutes, newRoutes)
×
691
        routesToDel = getRoutesToAdd(newRoutes, oldRoutes)
×
692

×
693
        return rulesToAdd, rulesToDel, routesToAdd, routesToDel, err
×
694
}
695

696
func (c *Controller) getPolicyRouting(subnet *kubeovnv1.Subnet) ([]netlink.Rule, []netlink.Route, error) {
×
697
        if subnet == nil || subnet.Spec.ExternalEgressGateway == "" || subnet.Spec.Vpc != c.config.ClusterRouter {
×
698
                return nil, nil, nil
×
699
        }
×
700
        if subnet.Spec.GatewayType == kubeovnv1.GWCentralizedType {
×
701
                node, err := c.nodesLister.Get(c.config.NodeName)
×
702
                if err != nil {
×
703
                        klog.Errorf("failed to get node %s: %v", c.config.NodeName, err)
×
704
                        return nil, nil, err
×
705
                }
×
706
                isGatewayNode := util.GatewayContains(subnet.Spec.GatewayNode, c.config.NodeName) ||
×
707
                        (subnet.Spec.GatewayNode == "" && util.MatchLabelSelectors(subnet.Spec.GatewayNodeSelectors, node.Labels))
×
708
                if !isGatewayNode {
×
709
                        return nil, nil, nil
×
710
                }
×
711
        }
712

713
        protocols := make([]string, 1, 2)
×
714
        if protocol := util.CheckProtocol(subnet.Spec.ExternalEgressGateway); protocol == kubeovnv1.ProtocolDual {
×
715
                protocols[0] = kubeovnv1.ProtocolIPv4
×
716
                protocols = append(protocols, kubeovnv1.ProtocolIPv6)
×
717
        } else {
×
718
                protocols[0] = protocol
×
719
        }
×
720

721
        cidr := strings.Split(subnet.Spec.CIDRBlock, ",")
×
722
        egw := strings.Split(subnet.Spec.ExternalEgressGateway, ",")
×
723

×
724
        // rules
×
725
        var rules []netlink.Rule
×
726
        rule := netlink.NewRule()
×
727
        rule.Table = int(subnet.Spec.PolicyRoutingTableID)
×
728
        rule.Priority = int(subnet.Spec.PolicyRoutingPriority)
×
729
        if subnet.Spec.GatewayType == kubeovnv1.GWDistributedType {
×
730
                pods, err := c.podsLister.List(labels.Everything())
×
731
                if err != nil {
×
732
                        klog.Errorf("list pods failed, %+v", err)
×
733
                        return nil, nil, err
×
734
                }
×
735

736
                for _, pod := range pods {
×
737
                        if pod.Status.PodIP == "" ||
×
738
                                pod.Annotations[util.LogicalSwitchAnnotation] != subnet.Name {
×
739
                                continue
×
740
                        }
741

742
                        for i := range protocols {
×
743
                                rule.Family, _ = util.ProtocolToFamily(protocols[i])
×
744

×
745
                                var ip net.IP
×
746
                                var maskBits int
×
747
                                if len(pod.Status.PodIPs) == 2 && protocols[i] == kubeovnv1.ProtocolIPv6 {
×
748
                                        ip = net.ParseIP(pod.Status.PodIPs[1].IP)
×
749
                                        maskBits = 128
×
750
                                } else if util.CheckProtocol(pod.Status.PodIP) == protocols[i] {
×
751
                                        ip = net.ParseIP(pod.Status.PodIP)
×
752
                                        maskBits = 32
×
753
                                        if rule.Family == netlink.FAMILY_V6 {
×
754
                                                maskBits = 128
×
755
                                        }
×
756
                                }
757

758
                                rule.Src = &net.IPNet{IP: ip, Mask: net.CIDRMask(maskBits, maskBits)}
×
759
                                rules = append(rules, *rule)
×
760
                        }
761
                }
762
        } else {
×
763
                for i := range protocols {
×
764
                        rule.Family, _ = util.ProtocolToFamily(protocols[i])
×
765
                        if len(cidr) == len(protocols) {
×
766
                                _, rule.Src, _ = net.ParseCIDR(cidr[i])
×
767
                        }
×
768
                        rules = append(rules, *rule)
×
769
                }
770
        }
771

772
        // routes
773
        var routes []netlink.Route
×
774
        for i := range protocols {
×
775
                routes = append(routes, netlink.Route{
×
776
                        Protocol: netlink.RouteProtocol(syscall.RTPROT_STATIC),
×
777
                        Table:    int(subnet.Spec.PolicyRoutingTableID),
×
778
                        Gw:       net.ParseIP(egw[i]),
×
779
                })
×
780
        }
×
781

782
        return rules, routes, nil
×
783
}
784

785
func (c *Controller) handleUpdatePod(key string) error {
×
786
        namespace, name, err := cache.SplitMetaNamespaceKey(key)
×
787
        if err != nil {
×
788
                utilruntime.HandleError(fmt.Errorf("invalid resource key: %s", key))
×
789
                return nil
×
790
        }
×
791
        klog.Infof("handle qos update for pod %s/%s", namespace, name)
×
792

×
793
        pod, err := c.podsLister.Pods(namespace).Get(name)
×
794
        if err != nil {
×
795
                if k8serrors.IsNotFound(err) {
×
796
                        return nil
×
797
                }
×
798
                klog.Error(err)
×
799
                return err
×
800
        }
801

802
        if err := util.ValidatePodNetwork(pod.Annotations); err != nil {
×
803
                klog.Errorf("validate pod %s/%s failed, %v", namespace, name, err)
×
804
                c.recorder.Eventf(pod, v1.EventTypeWarning, "ValidatePodNetworkFailed", err.Error())
×
805
                return err
×
806
        }
×
807

808
        podName := pod.Name
×
809
        if pod.Annotations[fmt.Sprintf(util.VMAnnotationTemplate, util.OvnProvider)] != "" {
×
810
                podName = pod.Annotations[fmt.Sprintf(util.VMAnnotationTemplate, util.OvnProvider)]
×
811
        }
×
812

813
        // set default nic bandwidth
814
        //  ovsIngress and ovsEgress are derived from the pod's egress and ingress rate annotations respectively, their roles are reversed from the OVS interface perspective.
815
        ifaceID := ovs.PodNameToPortName(podName, pod.Namespace, util.OvnProvider)
×
816
        ovsIngress := pod.Annotations[util.EgressRateAnnotation]
×
817
        ovsEgress := pod.Annotations[util.IngressRateAnnotation]
×
818
        err = ovs.SetInterfaceBandwidth(podName, pod.Namespace, ifaceID, ovsIngress, ovsEgress)
×
819
        if err != nil {
×
820
                klog.Error(err)
×
821
                return err
×
822
        }
×
823
        err = ovs.ConfigInterfaceMirror(c.config.EnableMirror, pod.Annotations[util.MirrorControlAnnotation], ifaceID)
×
824
        if err != nil {
×
825
                klog.Error(err)
×
826
                return err
×
827
        }
×
828
        // set linux-netem qos
829
        err = ovs.SetNetemQos(podName, pod.Namespace, ifaceID, pod.Annotations[util.NetemQosLatencyAnnotation], pod.Annotations[util.NetemQosLimitAnnotation], pod.Annotations[util.NetemQosLossAnnotation], pod.Annotations[util.NetemQosJitterAnnotation])
×
830
        if err != nil {
×
831
                klog.Error(err)
×
832
                return err
×
833
        }
×
834

835
        // set multus-nic bandwidth
836
        attachNets, err := nadutils.ParsePodNetworkAnnotation(pod)
×
837
        if err != nil {
×
838
                if _, ok := err.(*nadv1.NoK8sNetworkError); ok {
×
839
                        return nil
×
840
                }
×
841
                klog.Error(err)
×
842
                return err
×
843
        }
844
        for _, multiNet := range attachNets {
×
845
                provider := fmt.Sprintf("%s.%s.%s", multiNet.Name, multiNet.Namespace, util.OvnProvider)
×
846
                if pod.Annotations[fmt.Sprintf(util.VMAnnotationTemplate, provider)] != "" {
×
847
                        podName = pod.Annotations[fmt.Sprintf(util.VMAnnotationTemplate, provider)]
×
848
                }
×
849
                if pod.Annotations[fmt.Sprintf(util.AllocatedAnnotationTemplate, provider)] == "true" {
×
850
                        ifaceID = ovs.PodNameToPortName(podName, pod.Namespace, provider)
×
851

×
852
                        err = ovs.SetInterfaceBandwidth(podName, pod.Namespace, ifaceID, pod.Annotations[fmt.Sprintf(util.EgressRateAnnotationTemplate, provider)], pod.Annotations[fmt.Sprintf(util.IngressRateAnnotationTemplate, provider)])
×
853
                        if err != nil {
×
854
                                klog.Error(err)
×
855
                                return err
×
856
                        }
×
857
                        err = ovs.ConfigInterfaceMirror(c.config.EnableMirror, pod.Annotations[fmt.Sprintf(util.MirrorControlAnnotationTemplate, provider)], ifaceID)
×
858
                        if err != nil {
×
859
                                klog.Error(err)
×
860
                                return err
×
861
                        }
×
862
                        err = ovs.SetNetemQos(podName, pod.Namespace, ifaceID, pod.Annotations[fmt.Sprintf(util.NetemQosLatencyAnnotationTemplate, provider)], pod.Annotations[fmt.Sprintf(util.NetemQosLimitAnnotationTemplate, provider)], pod.Annotations[fmt.Sprintf(util.NetemQosLossAnnotationTemplate, provider)], pod.Annotations[fmt.Sprintf(util.NetemQosJitterAnnotationTemplate, provider)])
×
863
                        if err != nil {
×
864
                                klog.Error(err)
×
865
                                return err
×
866
                        }
×
867
                }
868
        }
869

870
        return nil
×
871
}
872

873
func (c *Controller) loopEncapIPCheck() {
×
874
        node, err := c.nodesLister.Get(c.config.NodeName)
×
875
        if err != nil {
×
876
                klog.Errorf("failed to get node %s %v", c.config.NodeName, err)
×
877
                return
×
878
        }
×
879

880
        if nodeTunnelName := node.GetAnnotations()[util.TunnelInterfaceAnnotation]; nodeTunnelName != "" {
×
881
                iface, err := findInterface(nodeTunnelName)
×
882
                if err != nil {
×
883
                        klog.Errorf("failed to find iface %s, %v", nodeTunnelName, err)
×
884
                        return
×
885
                }
×
886
                if iface.Flags&net.FlagUp == 0 {
×
887
                        klog.Errorf("iface %v is down", nodeTunnelName)
×
888
                        return
×
889
                }
×
890
                addrs, err := iface.Addrs()
×
891
                if err != nil {
×
892
                        klog.Errorf("failed to get iface addr. %v", err)
×
893
                        return
×
894
                }
×
895
                if len(addrs) == 0 {
×
896
                        klog.Errorf("iface %s has no ip address", nodeTunnelName)
×
897
                        return
×
898
                }
×
899
                if iface.Name != c.config.tunnelIface {
×
900
                        klog.Infof("use %s as tunnel interface", iface.Name)
×
901
                        c.config.tunnelIface = iface.Name
×
902
                }
×
903

904
                // if assigned iface in node annotation is down or with no ip, the error msg should be printed periodically
905
                if c.config.Iface == nodeTunnelName {
×
906
                        klog.V(3).Infof("node tunnel interface %s not changed", nodeTunnelName)
×
907
                        return
×
908
                }
×
909
                c.config.Iface = nodeTunnelName
×
910
                klog.Infof("Update node tunnel interface %v", nodeTunnelName)
×
911

×
912
                c.config.DefaultEncapIP = strings.Split(addrs[0].String(), "/")[0]
×
913
                if err = c.config.setEncapIPs(); err != nil {
×
914
                        klog.Errorf("failed to set encap ip %s for iface %s", c.config.DefaultEncapIP, c.config.Iface)
×
915
                        return
×
916
                }
×
917
        }
918
}
919

920
func (c *Controller) ovnMetricsUpdate() {
×
921
        c.setOvnSubnetGatewayMetric()
×
922

×
923
        resetSysParaMetrics()
×
924
        c.setIPLocalPortRangeMetric()
×
925
        c.setCheckSumErrMetric()
×
926
        c.setDNSSearchMetric()
×
927
        c.setTCPTwRecycleMetric()
×
928
        c.setTCPMtuProbingMetric()
×
929
        c.setConntrackTCPLiberalMetric()
×
930
        c.setBridgeNfCallIptablesMetric()
×
931
        c.setIPv6RouteMaxsizeMetric()
×
932
        c.setTCPMemMetric()
×
933
}
×
934

935
func resetSysParaMetrics() {
×
936
        metricIPLocalPortRange.Reset()
×
937
        metricCheckSumErr.Reset()
×
938
        metricDNSSearch.Reset()
×
939
        metricTCPTwRecycle.Reset()
×
940
        metricTCPMtuProbing.Reset()
×
941
        metricConntrackTCPLiberal.Reset()
×
942
        metricBridgeNfCallIptables.Reset()
×
943
        metricTCPMem.Reset()
×
944
        metricIPv6RouteMaxsize.Reset()
×
945
}
×
946

947
func rotateLog() {
×
948
        output, err := exec.Command("logrotate", "/etc/logrotate.d/openvswitch").CombinedOutput()
×
949
        if err != nil {
×
950
                klog.Errorf("failed to rotate openvswitch log %q", output)
×
951
        }
×
952
        output, err = exec.Command("logrotate", "/etc/logrotate.d/ovn").CombinedOutput()
×
953
        if err != nil {
×
954
                klog.Errorf("failed to rotate ovn log %q", output)
×
955
        }
×
956
        output, err = exec.Command("logrotate", "/etc/logrotate.d/kubeovn").CombinedOutput()
×
957
        if err != nil {
×
958
                klog.Errorf("failed to rotate kube-ovn log %q", output)
×
959
        }
×
960
}
961

962
func kernelModuleLoaded(module string) (bool, error) {
×
963
        data, err := os.ReadFile("/proc/modules")
×
964
        if err != nil {
×
965
                klog.Errorf("failed to read /proc/modules: %v", err)
×
966
                return false, err
×
967
        }
×
968

969
        for line := range strings.SplitSeq(string(data), "\n") {
×
970
                if fields := strings.Fields(line); len(fields) != 0 && fields[0] == module {
×
971
                        return true, nil
×
972
                }
×
973
        }
974

975
        return false, nil
×
976
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc