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

kubeovn / kube-ovn / 17601237263

10 Sep 2025 02:25AM UTC coverage: 21.232% (-0.1%) from 21.329%
17601237263

push

github

web-flow
Feat: Added non primary cni mode support for Kube-OVN (#5618)

* Add support for secondary CNI configuration

Signed-off-by: Vishal Mohan <vishalmohan@microsoft.com>

* Enhanced VPC NAT gateway to work with secondary interface

Signed-off-by: Vishal Mohan <vishalmohan@microsoft.com>

* Enhance NAT gateway and pod handling for non-primary CNI support

Signed-off-by: Vishal Mohan <vishalmohan@microsoft.com>

* Fixed compile

Signed-off-by: Vishal Mohan <vishalmohan@microsoft.com>

* Fix typo in TODO comment and improve error handling in getNadInterfaceFromNetworkStatusAnnotation

Signed-off-by: Vishal Mohan <vishalmohan@microsoft.com>

* Refactor getNadInterfaceFromNetworkStatusAnnotation to util package and update references in VPC NAT gateway

Signed-off-by: Vishal Mohan <vishalmohan@microsoft.com>

* Add support for non-primary CNI mode and improve VPC NAT gateway handling

- Introduced non-primary CNI configuration in values.yaml.
- Updated controller deployment to include non-primary CNI flag.
- Refactored NAT gateway script to use correct environment file path.
- Enhanced endpoint slice handling to utilize secondary IPs.
- Simplified pod provider extraction logic for VPC NAT gateway.
- Improved annotation management for VPC CIDRs in NAT gateway.

Signed-off-by: Vishal Mohan <vishalmohan@microsoft.com>

* Apply suggestions from code review

Signed-off-by: Vishal Mohan <vishalmohan@microsoft.com>

* Fixed lint
- Refactor variable type from 'interface{}' to 'any' in GetNadInterfaceFromNetworkStatusAnnotation for clarity
- Fixed pod routes annotation to use subnetProvider variable in vpc nat gw genNatGwStatefulSet

Signed-off-by: Vishal Mohan <vishalmohan@microsoft.com>

* fix lint issues

Signed-off-by: Mengxin Liu <liumengxinfly@gmail.com>

* Refactor endpoint slice handling to improve secondary IP address updates and add conditional provider retrieval for VPC NAT gateway support

Signed-off-by: Vishal Mohan <vishalmohan@microsoft.com>

* Updated He... (continued)

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

4 existing lines in 3 files now uncovered.

10659 of 50202 relevant lines covered (21.23%)

0.25 hits per line

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

0.0
/pkg/controller/pod.go
1
package controller
2

3
import (
4
        "context"
5
        "encoding/json"
6
        "errors"
7
        "fmt"
8
        "maps"
9
        "net"
10
        "slices"
11
        "strconv"
12
        "strings"
13
        "sync"
14
        "time"
15

16
        nadv1 "github.com/k8snetworkplumbingwg/network-attachment-definition-client/pkg/apis/k8s.cni.cncf.io/v1"
17
        nadutils "github.com/k8snetworkplumbingwg/network-attachment-definition-client/pkg/utils"
18
        "github.com/scylladb/go-set/strset"
19
        v1 "k8s.io/api/core/v1"
20
        k8serrors "k8s.io/apimachinery/pkg/api/errors"
21
        metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
22
        "k8s.io/apimachinery/pkg/labels"
23
        "k8s.io/apimachinery/pkg/types"
24
        utilruntime "k8s.io/apimachinery/pkg/util/runtime"
25
        "k8s.io/client-go/kubernetes"
26
        "k8s.io/client-go/tools/cache"
27
        "k8s.io/klog/v2"
28
        "k8s.io/utils/ptr"
29

30
        kubeovnv1 "github.com/kubeovn/kube-ovn/pkg/apis/kubeovn/v1"
31
        "github.com/kubeovn/kube-ovn/pkg/ipam"
32
        "github.com/kubeovn/kube-ovn/pkg/ovs"
33
        "github.com/kubeovn/kube-ovn/pkg/ovsdb/ovnnb"
34
        "github.com/kubeovn/kube-ovn/pkg/request"
35
        "github.com/kubeovn/kube-ovn/pkg/util"
36
)
37

38
type NamedPort struct {
39
        mutex sync.RWMutex
40
        // first key is namespace, second key is portName
41
        namedPortMap map[string]map[string]*util.NamedPortInfo
42
}
43

44
func NewNamedPort() *NamedPort {
×
45
        return &NamedPort{
×
46
                mutex:        sync.RWMutex{},
×
47
                namedPortMap: map[string]map[string]*util.NamedPortInfo{},
×
48
        }
×
49
}
×
50

51
func (n *NamedPort) AddNamedPortByPod(pod *v1.Pod) {
×
52
        n.mutex.Lock()
×
53
        defer n.mutex.Unlock()
×
54
        ns := pod.Namespace
×
55
        podName := pod.Name
×
56

×
57
        restartableInitContainers := make([]v1.Container, 0, len(pod.Spec.InitContainers))
×
58
        for i := range pod.Spec.InitContainers {
×
59
                if pod.Spec.InitContainers[i].RestartPolicy != nil &&
×
60
                        *pod.Spec.InitContainers[i].RestartPolicy == v1.ContainerRestartPolicyAlways {
×
61
                        restartableInitContainers = append(restartableInitContainers, pod.Spec.InitContainers[i])
×
62
                }
×
63
        }
64

65
        containers := slices.Concat(restartableInitContainers, pod.Spec.Containers)
×
66
        if len(containers) == 0 {
×
67
                return
×
68
        }
×
69

70
        for _, container := range containers {
×
71
                if len(container.Ports) == 0 {
×
72
                        continue
×
73
                }
74

75
                for _, port := range container.Ports {
×
76
                        if port.Name == "" || port.ContainerPort == 0 {
×
77
                                continue
×
78
                        }
79

80
                        if _, ok := n.namedPortMap[ns]; ok {
×
81
                                if _, ok := n.namedPortMap[ns][port.Name]; ok {
×
82
                                        if n.namedPortMap[ns][port.Name].PortID == port.ContainerPort {
×
83
                                                n.namedPortMap[ns][port.Name].Pods.Add(podName)
×
84
                                        } else {
×
85
                                                klog.Warningf("named port %s has already be defined with portID %d",
×
86
                                                        port.Name, n.namedPortMap[ns][port.Name].PortID)
×
87
                                        }
×
88
                                        continue
×
89
                                }
90
                        } else {
×
91
                                n.namedPortMap[ns] = make(map[string]*util.NamedPortInfo)
×
92
                        }
×
93
                        n.namedPortMap[ns][port.Name] = &util.NamedPortInfo{
×
94
                                PortID: port.ContainerPort,
×
95
                                Pods:   strset.New(podName),
×
96
                        }
×
97
                }
98
        }
99
}
100

101
func (n *NamedPort) DeleteNamedPortByPod(pod *v1.Pod) {
×
102
        n.mutex.Lock()
×
103
        defer n.mutex.Unlock()
×
104

×
105
        ns := pod.Namespace
×
106
        podName := pod.Name
×
107

×
108
        if pod.Spec.Containers == nil {
×
109
                return
×
110
        }
×
111

112
        for _, container := range pod.Spec.Containers {
×
113
                if container.Ports == nil {
×
114
                        continue
×
115
                }
116

117
                for _, port := range container.Ports {
×
118
                        if port.Name == "" {
×
119
                                continue
×
120
                        }
121

122
                        if _, ok := n.namedPortMap[ns]; !ok {
×
123
                                continue
×
124
                        }
125

126
                        if _, ok := n.namedPortMap[ns][port.Name]; !ok {
×
127
                                continue
×
128
                        }
129

130
                        if !n.namedPortMap[ns][port.Name].Pods.Has(podName) {
×
131
                                continue
×
132
                        }
133

134
                        n.namedPortMap[ns][port.Name].Pods.Remove(podName)
×
135
                        if n.namedPortMap[ns][port.Name].Pods.Size() == 0 {
×
136
                                delete(n.namedPortMap[ns], port.Name)
×
137
                                if len(n.namedPortMap[ns]) == 0 {
×
138
                                        delete(n.namedPortMap, ns)
×
139
                                }
×
140
                        }
141
                }
142
        }
143
}
144

145
func (n *NamedPort) GetNamedPortByNs(namespace string) map[string]*util.NamedPortInfo {
×
146
        n.mutex.RLock()
×
147
        defer n.mutex.RUnlock()
×
148

×
149
        if result, ok := n.namedPortMap[namespace]; ok {
×
150
                for portName, info := range result {
×
151
                        klog.Infof("namespace %s's namedPort portname is %s with info %v", namespace, portName, info)
×
152
                }
×
153
                return result
×
154
        }
155
        return nil
×
156
}
157

158
func isPodAlive(p *v1.Pod) bool {
×
159
        if !p.DeletionTimestamp.IsZero() && p.DeletionGracePeriodSeconds != nil {
×
160
                now := time.Now()
×
161
                deletionTime := p.DeletionTimestamp.Time
×
162
                gracePeriod := time.Duration(*p.DeletionGracePeriodSeconds) * time.Second
×
163
                if now.After(deletionTime.Add(gracePeriod)) {
×
164
                        return false
×
165
                }
×
166
        }
167
        return isPodStatusPhaseAlive(p)
×
168
}
169

170
func isPodStatusPhaseAlive(p *v1.Pod) bool {
×
171
        if p.Status.Phase == v1.PodSucceeded && p.Spec.RestartPolicy != v1.RestartPolicyAlways {
×
172
                return false
×
173
        }
×
174

175
        if p.Status.Phase == v1.PodFailed && p.Spec.RestartPolicy == v1.RestartPolicyNever {
×
176
                return false
×
177
        }
×
178

179
        if p.Status.Phase == v1.PodFailed && p.Status.Reason == "Evicted" {
×
180
                return false
×
181
        }
×
182
        return true
×
183
}
184

185
func (c *Controller) enqueueAddPod(obj any) {
×
186
        p := obj.(*v1.Pod)
×
187
        if p.Spec.HostNetwork {
×
188
                return
×
189
        }
×
190

191
        // Pod might be targeted by manual endpoints and we need to recompute its port mappings
192
        c.enqueueStaticEndpointUpdateInNamespace(p.Namespace)
×
193

×
194
        // TODO: we need to find a way to reduce duplicated np added to the queue
×
195
        if c.config.EnableNP {
×
196
                c.namedPort.AddNamedPortByPod(p)
×
197
                if p.Status.PodIP != "" {
×
198
                        for _, np := range c.podMatchNetworkPolicies(p) {
×
199
                                klog.V(3).Infof("enqueue update network policy %s", np)
×
200
                                c.updateNpQueue.Add(np)
×
201
                        }
×
202
                }
203
        }
204

205
        key := cache.MetaObjectToName(p).String()
×
206
        if !isPodAlive(p) {
×
207
                isStateful, statefulSetName, statefulSetUID := isStatefulSetPod(p)
×
208
                isVMPod, vmName := isVMPod(p)
×
209
                if isStateful || (isVMPod && c.config.EnableKeepVMIP) {
×
210
                        if isStateful && isStatefulSetPodToDel(c.config.KubeClient, p, statefulSetName, statefulSetUID) {
×
211
                                klog.V(3).Infof("enqueue delete pod %s", key)
×
212
                                c.deletingPodObjMap.Store(key, p)
×
213
                                c.deletePodQueue.Add(key)
×
214
                        }
×
215
                        if isVMPod && c.isVMToDel(p, vmName) {
×
216
                                klog.V(3).Infof("enqueue delete pod %s", key)
×
217
                                c.deletingPodObjMap.Store(key, p)
×
218
                                c.deletePodQueue.Add(key)
×
219
                        }
×
220
                } else {
×
221
                        klog.V(3).Infof("enqueue delete pod %s", key)
×
222
                        c.deletingPodObjMap.Store(key, p)
×
223
                        c.deletePodQueue.Add(key)
×
224
                }
×
225
                return
×
226
        }
227

228
        need, err := c.podNeedSync(p)
×
229
        if err != nil {
×
230
                klog.Errorf("invalid pod net: %v", err)
×
231
                return
×
232
        }
×
233
        if need {
×
234
                klog.Infof("enqueue add pod %s", key)
×
235
                c.addOrUpdatePodQueue.Add(key)
×
236
        }
×
237

238
        if err = c.handlePodEventForVpcEgressGateway(p); err != nil {
×
239
                klog.Errorf("failed to handle pod event for vpc egress gateway: %v", err)
×
240
        }
×
241
}
242

243
func (c *Controller) enqueueDeletePod(obj any) {
×
244
        var p *v1.Pod
×
245
        switch t := obj.(type) {
×
246
        case *v1.Pod:
×
247
                p = t
×
248
        case cache.DeletedFinalStateUnknown:
×
249
                pod, ok := t.Obj.(*v1.Pod)
×
250
                if !ok {
×
251
                        klog.Warningf("unexpected object type: %T", t.Obj)
×
252
                        return
×
253
                }
×
254
                p = pod
×
255
        default:
×
256
                klog.Warningf("unexpected type: %T", obj)
×
257
                return
×
258
        }
259

260
        if p.Spec.HostNetwork {
×
261
                return
×
262
        }
×
263

264
        // Pod might be targeted by manual endpoints and we need to recompute its port mappings
265
        c.enqueueStaticEndpointUpdateInNamespace(p.Namespace)
×
266

×
267
        if c.config.EnableNP {
×
268
                c.namedPort.DeleteNamedPortByPod(p)
×
269
                for _, np := range c.podMatchNetworkPolicies(p) {
×
270
                        c.updateNpQueue.Add(np)
×
271
                }
×
272
        }
273

274
        if c.config.EnableANP {
×
275
                podNs, _ := c.namespacesLister.Get(p.Namespace)
×
276
                c.updateAnpsByLabelsMatch(podNs.Labels, p.Labels)
×
277
        }
×
278

279
        key := cache.MetaObjectToName(p).String()
×
280
        klog.Infof("enqueue delete pod %s", key)
×
281
        c.deletingPodObjMap.Store(key, p)
×
282
        c.deletePodQueue.Add(key)
×
283
}
284

285
func (c *Controller) enqueueUpdatePod(oldObj, newObj any) {
×
286
        oldPod := oldObj.(*v1.Pod)
×
287
        newPod := newObj.(*v1.Pod)
×
288

×
289
        // Pod might be targeted by manual endpoints and we need to recompute its port mappings
×
290
        c.enqueueStaticEndpointUpdateInNamespace(oldPod.Namespace)
×
291

×
292
        if oldPod.Annotations[util.AAPsAnnotation] != "" || newPod.Annotations[util.AAPsAnnotation] != "" {
×
293
                oldAAPs := strings.Split(oldPod.Annotations[util.AAPsAnnotation], ",")
×
294
                newAAPs := strings.Split(newPod.Annotations[util.AAPsAnnotation], ",")
×
295
                var vipNames []string
×
296
                for _, vipName := range oldAAPs {
×
297
                        vipNames = append(vipNames, strings.TrimSpace(vipName))
×
298
                }
×
299
                for _, vipName := range newAAPs {
×
300
                        vipName = strings.TrimSpace(vipName)
×
301
                        if !slices.Contains(vipNames, vipName) {
×
302
                                vipNames = append(vipNames, vipName)
×
303
                        }
×
304
                }
305
                for _, vipName := range vipNames {
×
306
                        if vip, err := c.virtualIpsLister.Get(vipName); err == nil {
×
307
                                if vip.Spec.Namespace != newPod.Namespace {
×
308
                                        continue
×
309
                                }
310
                                klog.Infof("enqueue update virtual parents for %s", vipName)
×
311
                                c.updateVirtualParentsQueue.Add(vipName)
×
312
                        }
313
                }
314
        }
315

316
        if oldPod.ResourceVersion == newPod.ResourceVersion {
×
317
                return
×
318
        }
×
319
        if newPod.Spec.HostNetwork {
×
320
                return
×
321
        }
×
322

323
        podNets, err := c.getPodKubeovnNets(newPod)
×
324
        if err != nil {
×
325
                klog.Errorf("failed to get newPod nets %v", err)
×
326
                return
×
327
        }
×
328

329
        key := cache.MetaObjectToName(newPod).String()
×
330
        if c.config.EnableNP {
×
331
                c.namedPort.AddNamedPortByPod(newPod)
×
332
                newNp := c.podMatchNetworkPolicies(newPod)
×
333
                if !maps.Equal(oldPod.Labels, newPod.Labels) {
×
334
                        oldNp := c.podMatchNetworkPolicies(oldPod)
×
335
                        for _, np := range util.DiffStringSlice(oldNp, newNp) {
×
336
                                c.updateNpQueue.Add(np)
×
337
                        }
×
338
                }
339

340
                for _, podNet := range podNets {
×
341
                        oldAllocated := oldPod.Annotations[fmt.Sprintf(util.AllocatedAnnotationTemplate, podNet.ProviderName)]
×
342
                        newAllocated := newPod.Annotations[fmt.Sprintf(util.AllocatedAnnotationTemplate, podNet.ProviderName)]
×
343
                        if oldAllocated != newAllocated {
×
344
                                for _, np := range newNp {
×
345
                                        klog.V(3).Infof("enqueue update network policy %s for pod %s", np, key)
×
346
                                        c.updateNpQueue.Add(np)
×
347
                                }
×
348
                                break
×
349
                        }
350
                }
351
        }
352

353
        if c.config.EnableANP {
×
354
                podNs, _ := c.namespacesLister.Get(newPod.Namespace)
×
355
                if !maps.Equal(oldPod.Labels, newPod.Labels) {
×
356
                        c.updateAnpsByLabelsMatch(podNs.Labels, newPod.Labels)
×
357
                }
×
358

359
                for _, podNet := range podNets {
×
360
                        oldAllocated := oldPod.Annotations[fmt.Sprintf(util.AllocatedAnnotationTemplate, podNet.ProviderName)]
×
361
                        newAllocated := newPod.Annotations[fmt.Sprintf(util.AllocatedAnnotationTemplate, podNet.ProviderName)]
×
362
                        if oldAllocated != newAllocated {
×
363
                                c.updateAnpsByLabelsMatch(podNs.Labels, newPod.Labels)
×
364
                                break
×
365
                        }
366
                }
367
        }
368

369
        isStateful, statefulSetName, statefulSetUID := isStatefulSetPod(newPod)
×
370
        isVMPod, vmName := isVMPod(newPod)
×
371
        if !isPodStatusPhaseAlive(newPod) && !isStateful && !isVMPod {
×
372
                klog.V(3).Infof("enqueue delete pod %s", key)
×
373
                c.deletingPodObjMap.Store(key, newPod)
×
374
                c.deletePodQueue.Add(key)
×
375
                return
×
376
        }
×
377

378
        // enqueue delay
379
        var delay time.Duration
×
380
        if newPod.Spec.TerminationGracePeriodSeconds != nil {
×
381
                if !newPod.DeletionTimestamp.IsZero() {
×
382
                        delay = time.Until(newPod.DeletionTimestamp.Add(time.Duration(*newPod.Spec.TerminationGracePeriodSeconds) * time.Second))
×
383
                } else {
×
384
                        delay = time.Duration(*newPod.Spec.TerminationGracePeriodSeconds) * time.Second
×
385
                }
×
386
        }
387

388
        if !newPod.DeletionTimestamp.IsZero() && !isStateful && !isVMPod {
×
389
                go func() {
×
390
                        // In case node get lost and pod can not be deleted,
×
391
                        // the ip address will not be recycled
×
392
                        klog.V(3).Infof("enqueue delete pod %s after %v", key, delay)
×
393
                        c.deletingPodObjMap.Store(key, newPod)
×
394
                        c.deletePodQueue.AddAfter(key, delay)
×
395
                }()
×
396
                return
×
397
        }
398

399
        if err = c.handlePodEventForVpcEgressGateway(newPod); err != nil {
×
400
                klog.Errorf("failed to handle pod event for vpc egress gateway: %v", err)
×
401
        }
×
402

403
        // do not delete statefulset pod unless ownerReferences is deleted
404
        if isStateful && isStatefulSetPodToDel(c.config.KubeClient, newPod, statefulSetName, statefulSetUID) {
×
405
                go func() {
×
406
                        klog.V(3).Infof("enqueue delete pod %s after %v", key, delay)
×
407
                        c.deletingPodObjMap.Store(key, newPod)
×
408
                        c.deletePodQueue.AddAfter(key, delay)
×
409
                }()
×
410
                return
×
411
        }
412
        if isVMPod && c.isVMToDel(newPod, vmName) {
×
413
                go func() {
×
414
                        klog.V(3).Infof("enqueue delete pod %s after %v", key, delay)
×
415
                        c.deletingPodObjMap.Store(key, newPod)
×
416
                        c.deletePodQueue.AddAfter(key, delay)
×
417
                }()
×
418
                return
×
419
        }
420
        klog.Infof("enqueue update pod %s", key)
×
421
        c.addOrUpdatePodQueue.Add(key)
×
422

×
423
        // security policy changed
×
424
        for _, podNet := range podNets {
×
425
                oldSecurity := oldPod.Annotations[fmt.Sprintf(util.PortSecurityAnnotationTemplate, podNet.ProviderName)]
×
426
                newSecurity := newPod.Annotations[fmt.Sprintf(util.PortSecurityAnnotationTemplate, podNet.ProviderName)]
×
427
                oldSg := oldPod.Annotations[fmt.Sprintf(util.SecurityGroupAnnotationTemplate, podNet.ProviderName)]
×
428
                newSg := newPod.Annotations[fmt.Sprintf(util.SecurityGroupAnnotationTemplate, podNet.ProviderName)]
×
429
                oldVips := oldPod.Annotations[fmt.Sprintf(util.PortVipAnnotationTemplate, podNet.ProviderName)]
×
430
                newVips := newPod.Annotations[fmt.Sprintf(util.PortVipAnnotationTemplate, podNet.ProviderName)]
×
431
                oldAAPs := oldPod.Annotations[util.AAPsAnnotation]
×
432
                newAAPs := newPod.Annotations[util.AAPsAnnotation]
×
433
                if oldSecurity != newSecurity || oldSg != newSg || oldVips != newVips || oldAAPs != newAAPs {
×
434
                        c.updatePodSecurityQueue.Add(key)
×
435
                        break
×
436
                }
437
        }
438
}
439

440
func (c *Controller) getPodKubeovnNets(pod *v1.Pod) ([]*kubeovnNet, error) {
×
NEW
441
        attachmentNets, err := c.getPodAttachmentNet(pod)
×
442
        if err != nil {
×
443
                klog.Error(err)
×
444
                return nil, err
×
445
        }
×
446

NEW
447
        podNets := attachmentNets
×
NEW
448
        // When Kube-OVN is run as non-primary CNI, we do not add default network configuration to pod.
×
NEW
449
        // We only add network attachment defined by the user to pod.
×
NEW
450
        if c.config.EnableNonPrimaryCNI {
×
NEW
451
                return podNets, nil
×
NEW
452
        }
×
453

NEW
454
        defaultSubnet, err := c.getPodDefaultSubnet(pod)
×
455
        if err != nil {
×
456
                klog.Error(err)
×
457
                return nil, err
×
458
        }
×
459

460
        // pod annotation default subnet not found
461
        if defaultSubnet == nil {
×
462
                klog.Errorf("pod %s/%s has no default subnet, skip adding default network", pod.Namespace, pod.Name)
×
463
                return attachmentNets, nil
×
464
        }
×
465

466
        if _, hasOtherDefaultNet := pod.Annotations[util.DefaultNetworkAnnotation]; !hasOtherDefaultNet {
×
467
                podNets = append(attachmentNets, &kubeovnNet{
×
468
                        Type:         providerTypeOriginal,
×
469
                        ProviderName: util.OvnProvider,
×
470
                        Subnet:       defaultSubnet,
×
471
                        IsDefault:    true,
×
472
                })
×
473
        }
×
474

475
        return podNets, nil
×
476
}
477

478
func (c *Controller) handleAddOrUpdatePod(key string) (err error) {
×
479
        now := time.Now()
×
480
        klog.Infof("handle add/update pod %s", key)
×
481

×
482
        namespace, name, err := cache.SplitMetaNamespaceKey(key)
×
483
        if err != nil {
×
484
                utilruntime.HandleError(fmt.Errorf("invalid resource key: %s", key))
×
485
                return nil
×
486
        }
×
487

488
        c.podKeyMutex.LockKey(key)
×
489
        defer func() {
×
490
                _ = c.podKeyMutex.UnlockKey(key)
×
491
                last := time.Since(now)
×
492
                klog.Infof("take %d ms to handle add or update pod %s", last.Milliseconds(), key)
×
493
        }()
×
494

495
        pod, err := c.podsLister.Pods(namespace).Get(name)
×
496
        if err != nil {
×
497
                if k8serrors.IsNotFound(err) {
×
498
                        return nil
×
499
                }
×
500
                klog.Error(err)
×
501
                return err
×
502
        }
503
        if err := util.ValidatePodNetwork(pod.Annotations); err != nil {
×
504
                klog.Errorf("validate pod %s/%s failed: %v", namespace, name, err)
×
505
                c.recorder.Eventf(pod, v1.EventTypeWarning, "ValidatePodNetworkFailed", err.Error())
×
506
                return err
×
507
        }
×
508

509
        podNets, err := c.getPodKubeovnNets(pod)
×
510
        if err != nil {
×
511
                klog.Errorf("failed to get pod nets %v", err)
×
512
                return err
×
513
        }
×
514

515
        // check and do hotnoplug nic
516
        if pod, err = c.syncKubeOvnNet(pod, podNets); err != nil {
×
517
                klog.Errorf("failed to sync pod nets %v", err)
×
518
                return err
×
519
        }
×
520
        if pod == nil {
×
521
                // pod has been deleted
×
522
                return nil
×
523
        }
×
524
        needAllocatePodNets := needAllocateSubnets(pod, podNets)
×
525
        if len(needAllocatePodNets) != 0 {
×
526
                if pod, err = c.reconcileAllocateSubnets(pod, needAllocatePodNets); err != nil {
×
527
                        klog.Error(err)
×
528
                        return err
×
529
                }
×
530
                if pod == nil {
×
531
                        // pod has been deleted
×
532
                        return nil
×
533
                }
×
534
        }
535

NEW
536
        isVpcNatGw, vpcGwName := c.checkIsPodVpcNatGw(pod)
×
NEW
537
        if isVpcNatGw {
×
538
                if needRestartNatGatewayPod(pod) {
×
NEW
539
                        klog.Infof("restarting vpc nat gateway %s", vpcGwName)
×
540
                        c.addOrUpdateVpcNatGatewayQueue.Add(vpcGwName)
×
541
                }
×
542
        }
543

544
        // check if route subnet is need.
545
        return c.reconcileRouteSubnets(pod, needRouteSubnets(pod, podNets))
×
546
}
547

548
// do the same thing as add pod
549
func (c *Controller) reconcileAllocateSubnets(pod *v1.Pod, needAllocatePodNets []*kubeovnNet) (*v1.Pod, error) {
×
550
        namespace := pod.Namespace
×
551
        name := pod.Name
×
552
        klog.Infof("sync pod %s/%s allocated", namespace, name)
×
553

×
554
        vipsMap := c.getVirtualIPs(pod, needAllocatePodNets)
×
555
        isVMPod, vmName := isVMPod(pod)
×
556
        podType := getPodType(pod)
×
557
        podName := c.getNameByPod(pod)
×
558
        // todo: isVmPod, getPodType, getNameByPod has duplicated logic
×
559

×
560
        var err error
×
561
        var vmKey string
×
562
        if isVMPod && c.config.EnableKeepVMIP {
×
563
                vmKey = fmt.Sprintf("%s/%s", namespace, vmName)
×
564
        }
×
565
        // Avoid create lsp for already running pod in ovn-nb when controller restart
566
        patch := util.KVPatch{}
×
567
        for _, podNet := range needAllocatePodNets {
×
568
                // the subnet may changed when alloc static ip from the latter subnet after ns supports multi subnets
×
569
                v4IP, v6IP, mac, subnet, err := c.acquireAddress(pod, podNet)
×
570
                if err != nil {
×
571
                        c.recorder.Eventf(pod, v1.EventTypeWarning, "AcquireAddressFailed", err.Error())
×
572
                        klog.Error(err)
×
573
                        return nil, err
×
574
                }
×
575
                ipStr := util.GetStringIP(v4IP, v6IP)
×
576
                patch[fmt.Sprintf(util.IPAddressAnnotationTemplate, podNet.ProviderName)] = ipStr
×
577
                if mac == "" {
×
578
                        patch[fmt.Sprintf(util.MacAddressAnnotationTemplate, podNet.ProviderName)] = nil
×
579
                } else {
×
580
                        patch[fmt.Sprintf(util.MacAddressAnnotationTemplate, podNet.ProviderName)] = mac
×
581
                }
×
582
                patch[fmt.Sprintf(util.CidrAnnotationTemplate, podNet.ProviderName)] = subnet.Spec.CIDRBlock
×
583
                patch[fmt.Sprintf(util.GatewayAnnotationTemplate, podNet.ProviderName)] = subnet.Spec.Gateway
×
584
                if isOvnSubnet(podNet.Subnet) {
×
585
                        patch[fmt.Sprintf(util.LogicalSwitchAnnotationTemplate, podNet.ProviderName)] = subnet.Name
×
586
                        if pod.Annotations[fmt.Sprintf(util.PodNicAnnotationTemplate, podNet.ProviderName)] == "" {
×
587
                                patch[fmt.Sprintf(util.PodNicAnnotationTemplate, podNet.ProviderName)] = c.config.PodNicType
×
588
                        }
×
589
                } else {
×
590
                        patch[fmt.Sprintf(util.LogicalSwitchAnnotationTemplate, podNet.ProviderName)] = nil
×
591
                        patch[fmt.Sprintf(util.PodNicAnnotationTemplate, podNet.ProviderName)] = nil
×
592
                }
×
593
                patch[fmt.Sprintf(util.AllocatedAnnotationTemplate, podNet.ProviderName)] = "true"
×
594
                if vmKey != "" {
×
595
                        patch[fmt.Sprintf(util.VMAnnotationTemplate, podNet.ProviderName)] = vmName
×
596
                }
×
597
                if err := util.ValidateNetworkBroadcast(podNet.Subnet.Spec.CIDRBlock, ipStr); err != nil {
×
598
                        klog.Errorf("validate pod %s/%s failed: %v", namespace, name, err)
×
599
                        c.recorder.Eventf(pod, v1.EventTypeWarning, "ValidatePodNetworkFailed", err.Error())
×
600
                        return nil, err
×
601
                }
×
602

603
                if podNet.Type != providerTypeIPAM {
×
604
                        if (subnet.Spec.Vlan == "" || subnet.Spec.LogicalGateway || subnet.Spec.U2OInterconnection) && subnet.Spec.Vpc != "" {
×
605
                                patch[fmt.Sprintf(util.LogicalRouterAnnotationTemplate, podNet.ProviderName)] = subnet.Spec.Vpc
×
606
                        }
×
607

608
                        if subnet.Spec.Vlan != "" {
×
609
                                vlan, err := c.vlansLister.Get(subnet.Spec.Vlan)
×
610
                                if err != nil {
×
611
                                        klog.Error(err)
×
612
                                        c.recorder.Eventf(pod, v1.EventTypeWarning, "GetVlanInfoFailed", err.Error())
×
613
                                        return nil, err
×
614
                                }
×
615
                                patch[fmt.Sprintf(util.VlanIDAnnotationTemplate, podNet.ProviderName)] = strconv.Itoa(vlan.Spec.ID)
×
616
                                patch[fmt.Sprintf(util.ProviderNetworkTemplate, podNet.ProviderName)] = vlan.Spec.Provider
×
617
                        }
618

619
                        portSecurity := false
×
620
                        if pod.Annotations[fmt.Sprintf(util.PortSecurityAnnotationTemplate, podNet.ProviderName)] == "true" {
×
621
                                portSecurity = true
×
622
                        }
×
623

624
                        vips := vipsMap[fmt.Sprintf("%s.%s", podNet.Subnet.Name, podNet.ProviderName)]
×
625
                        for ip := range strings.SplitSeq(vips, ",") {
×
626
                                if ip != "" && net.ParseIP(ip) == nil {
×
627
                                        klog.Errorf("invalid vip address '%s' for pod %s", ip, name)
×
628
                                        vips = ""
×
629
                                        break
×
630
                                }
631
                        }
632

633
                        portName := ovs.PodNameToPortName(podName, namespace, podNet.ProviderName)
×
634
                        dhcpOptions := &ovs.DHCPOptionsUUIDs{
×
635
                                DHCPv4OptionsUUID: subnet.Status.DHCPv4OptionsUUID,
×
636
                                DHCPv6OptionsUUID: subnet.Status.DHCPv6OptionsUUID,
×
637
                        }
×
638

×
639
                        var oldSgList []string
×
640
                        if vmKey != "" {
×
641
                                existingLsp, err := c.OVNNbClient.GetLogicalSwitchPort(portName, true)
×
642
                                if err != nil {
×
643
                                        klog.Errorf("failed to get logical switch port %s: %v", portName, err)
×
644
                                        return nil, err
×
645
                                }
×
646
                                if existingLsp != nil {
×
647
                                        oldSgList, _ = c.getPortSg(existingLsp)
×
648
                                }
×
649
                        }
650

651
                        securityGroupAnnotation := pod.Annotations[fmt.Sprintf(util.SecurityGroupAnnotationTemplate, podNet.ProviderName)]
×
652
                        if err := c.OVNNbClient.CreateLogicalSwitchPort(subnet.Name, portName, ipStr, mac, podName, pod.Namespace,
×
653
                                portSecurity, securityGroupAnnotation, vips, podNet.Subnet.Spec.EnableDHCP, dhcpOptions, subnet.Spec.Vpc); err != nil {
×
654
                                c.recorder.Eventf(pod, v1.EventTypeWarning, "CreateOVNPortFailed", err.Error())
×
655
                                klog.Errorf("%v", err)
×
656
                                return nil, err
×
657
                        }
×
658

659
                        if pod.Annotations[fmt.Sprintf(util.Layer2ForwardAnnotationTemplate, podNet.ProviderName)] == "true" {
×
660
                                if err := c.OVNNbClient.EnablePortLayer2forward(portName); err != nil {
×
661
                                        c.recorder.Eventf(pod, v1.EventTypeWarning, "SetOVNPortL2ForwardFailed", err.Error())
×
662
                                        klog.Errorf("%v", err)
×
663
                                        return nil, err
×
664
                                }
×
665
                        }
666

667
                        if securityGroupAnnotation != "" || oldSgList != nil {
×
668
                                securityGroups := strings.ReplaceAll(securityGroupAnnotation, " ", "")
×
669
                                newSgList := strings.Split(securityGroups, ",")
×
670
                                sgNames := util.UnionStringSlice(oldSgList, newSgList)
×
671
                                for _, sgName := range sgNames {
×
672
                                        if sgName != "" {
×
673
                                                c.syncSgPortsQueue.Add(sgName)
×
674
                                        }
×
675
                                }
676
                        }
677

678
                        if vips != "" {
×
679
                                c.syncVirtualPortsQueue.Add(podNet.Subnet.Name)
×
680
                        }
×
681
                }
682
                // CreatePort may fail, so put ip CR creation after CreatePort
683
                ipCRName := ovs.PodNameToPortName(podName, pod.Namespace, podNet.ProviderName)
×
684
                if err := c.createOrUpdateIPCR(ipCRName, podName, ipStr, mac, subnet.Name, pod.Namespace, pod.Spec.NodeName, podType); err != nil {
×
685
                        err = fmt.Errorf("failed to create ips CR %s.%s: %w", podName, pod.Namespace, err)
×
686
                        klog.Error(err)
×
687
                        return nil, err
×
688
                }
×
689
        }
690
        if err = util.PatchAnnotations(c.config.KubeClient.CoreV1().Pods(namespace), name, patch); err != nil {
×
691
                if k8serrors.IsNotFound(err) {
×
692
                        // Sometimes pod is deleted between kube-ovn configure ovn-nb and patch pod.
×
693
                        // Then we need to recycle the resource again.
×
694
                        key := strings.Join([]string{namespace, name}, "/")
×
695
                        c.deletingPodObjMap.Store(key, pod)
×
696
                        c.deletePodQueue.AddRateLimited(key)
×
697
                        return nil, nil
×
698
                }
×
699
                klog.Errorf("failed to patch pod %s/%s: %v", namespace, name, err)
×
700
                return nil, err
×
701
        }
702

703
        if pod, err = c.config.KubeClient.CoreV1().Pods(namespace).Get(context.TODO(), name, metav1.GetOptions{}); err != nil {
×
704
                if k8serrors.IsNotFound(err) {
×
705
                        key := strings.Join([]string{namespace, name}, "/")
×
706
                        c.deletingPodObjMap.Store(key, pod)
×
707
                        c.deletePodQueue.AddRateLimited(key)
×
708
                        return nil, nil
×
709
                }
×
710
                klog.Errorf("failed to get pod %s/%s: %v", namespace, name, err)
×
711
                return nil, err
×
712
        }
713

714
        // Check if pod is a vpc nat gateway. Annotation set will have subnet provider name as prefix
NEW
715
        isVpcNatGw, vpcGwName := c.checkIsPodVpcNatGw(pod)
×
NEW
716
        if isVpcNatGw {
×
NEW
717
                klog.Infof("init vpc nat gateway pod %s/%s with name %s", namespace, name, vpcGwName)
×
718
                c.initVpcNatGatewayQueue.Add(vpcGwName)
×
719
        }
×
720

UNCOV
721
        return pod, nil
×
722
}
723

724
// do the same thing as update pod
725
func (c *Controller) reconcileRouteSubnets(pod *v1.Pod, needRoutePodNets []*kubeovnNet) error {
×
726
        // the lb-svc pod has dependencies on Running state, check it when pod state get updated
×
727
        if err := c.checkAndReInitLbSvcPod(pod); err != nil {
×
728
                klog.Errorf("failed to init iptable rules for load-balancer pod %s/%s: %v", pod.Namespace, pod.Name, err)
×
729
        }
×
730

731
        if len(needRoutePodNets) == 0 {
×
732
                return nil
×
733
        }
×
734

735
        namespace := pod.Namespace
×
736
        name := pod.Name
×
737
        podName := c.getNameByPod(pod)
×
738

×
739
        klog.Infof("sync pod %s/%s routed", namespace, name)
×
740

×
741
        node, err := c.nodesLister.Get(pod.Spec.NodeName)
×
742
        if err != nil {
×
743
                klog.Errorf("failed to get node %s: %v", pod.Spec.NodeName, err)
×
744
                return err
×
745
        }
×
746

747
        portGroups, err := c.OVNNbClient.ListPortGroups(map[string]string{"node": "", networkPolicyKey: ""})
×
748
        if err != nil {
×
749
                klog.Errorf("failed to list port groups: %v", err)
×
750
                return err
×
751
        }
×
752

753
        var nodePortGroups []string
×
754
        nodePortGroup := strings.ReplaceAll(node.Annotations[util.PortNameAnnotation], "-", ".")
×
755
        for _, pg := range portGroups {
×
756
                if pg.Name != nodePortGroup && pg.ExternalIDs["subnet"] == "" {
×
757
                        nodePortGroups = append(nodePortGroups, pg.Name)
×
758
                }
×
759
        }
760

761
        var podIP string
×
762
        var subnet *kubeovnv1.Subnet
×
763
        patch := util.KVPatch{}
×
764
        for _, podNet := range needRoutePodNets {
×
765
                // in case update handler overlap the annotation when cache is not in sync
×
766
                if pod.Annotations[fmt.Sprintf(util.AllocatedAnnotationTemplate, podNet.ProviderName)] == "" {
×
767
                        return fmt.Errorf("no address has been allocated to %s/%s", namespace, name)
×
768
                }
×
769

770
                podIP = pod.Annotations[fmt.Sprintf(util.IPAddressAnnotationTemplate, podNet.ProviderName)]
×
771
                subnet = podNet.Subnet
×
772

×
773
                // Check if pod uses nodeSwitch subnet
×
774
                if subnet.Name == c.config.NodeSwitch {
×
775
                        return fmt.Errorf("NodeSwitch subnet %s is unavailable for pod", subnet.Name)
×
776
                }
×
777

778
                if portGroups, err = c.OVNNbClient.ListPortGroups(map[string]string{"subnet": subnet.Name, "node": "", networkPolicyKey: ""}); err != nil {
×
779
                        klog.Errorf("failed to list port groups: %v", err)
×
780
                        return err
×
781
                }
×
782

783
                pgName := getOverlaySubnetsPortGroupName(subnet.Name, pod.Spec.NodeName)
×
784
                portName := ovs.PodNameToPortName(podName, pod.Namespace, podNet.ProviderName)
×
785
                subnetPortGroups := make([]string, 0, len(portGroups))
×
786
                for _, pg := range portGroups {
×
787
                        if pg.Name != pgName {
×
788
                                subnetPortGroups = append(subnetPortGroups, pg.Name)
×
789
                        }
×
790
                }
791

792
                if (!c.config.EnableLb || (subnet.Spec.EnableLb == nil || !*subnet.Spec.EnableLb)) &&
×
793
                        subnet.Spec.Vpc == c.config.ClusterRouter &&
×
794
                        subnet.Spec.U2OInterconnection &&
×
795
                        subnet.Spec.Vlan != "" &&
×
796
                        !subnet.Spec.LogicalGateway {
×
797
                        // remove lsp from other port groups
×
798
                        // we need to do this because the pod, e.g. a sts/vm, can be rescheduled to another node
×
799
                        if err = c.OVNNbClient.RemovePortFromPortGroups(portName, subnetPortGroups...); err != nil {
×
800
                                klog.Errorf("failed to remove port %s from port groups %v: %v", portName, subnetPortGroups, err)
×
801
                                return err
×
802
                        }
×
803
                        // add lsp to the port group
804
                        if err := c.OVNNbClient.PortGroupAddPorts(pgName, portName); err != nil {
×
805
                                klog.Errorf("failed to add port to u2o port group %s: %v", pgName, err)
×
806
                                return err
×
807
                        }
×
808
                }
809

810
                if podIP != "" && (subnet.Spec.Vlan == "" || subnet.Spec.LogicalGateway) && subnet.Spec.Vpc == c.config.ClusterRouter {
×
811
                        node, err := c.nodesLister.Get(pod.Spec.NodeName)
×
812
                        if err != nil {
×
813
                                klog.Errorf("failed to get node %s: %v", pod.Spec.NodeName, err)
×
814
                                return err
×
815
                        }
×
816

817
                        // remove lsp from other port groups
818
                        // we need to do this because the pod, e.g. a sts/vm, can be rescheduled to another node
819
                        if err = c.OVNNbClient.RemovePortFromPortGroups(portName, nodePortGroups...); err != nil {
×
820
                                klog.Errorf("failed to remove port %s from port groups %v: %v", portName, nodePortGroups, err)
×
821
                                return err
×
822
                        }
×
823
                        // add lsp to the port group
824
                        if err = c.OVNNbClient.PortGroupAddPorts(nodePortGroup, portName); err != nil {
×
825
                                klog.Errorf("failed to add port %s to port group %s: %v", portName, nodePortGroup, err)
×
826
                                return err
×
827
                        }
×
828

829
                        if c.config.EnableEipSnat && (pod.Annotations[util.EipAnnotation] != "" || pod.Annotations[util.SnatAnnotation] != "") {
×
830
                                cm, err := c.configMapsLister.ConfigMaps(c.config.ExternalGatewayConfigNS).Get(util.ExternalGatewayConfig)
×
831
                                if err != nil {
×
832
                                        klog.Errorf("failed to get ex-gateway config, %v", err)
×
833
                                        return err
×
834
                                }
×
835
                                nextHop := cm.Data["external-gw-addr"]
×
836
                                if nextHop == "" {
×
837
                                        externalSubnet, err := c.subnetsLister.Get(c.config.ExternalGatewaySwitch)
×
838
                                        if err != nil {
×
839
                                                klog.Errorf("failed to get subnet %s, %v", c.config.ExternalGatewaySwitch, err)
×
840
                                                return err
×
841
                                        }
×
842
                                        nextHop = externalSubnet.Spec.Gateway
×
843
                                        if nextHop == "" {
×
844
                                                klog.Errorf("no available gateway address")
×
845
                                                return errors.New("no available gateway address")
×
846
                                        }
×
847
                                }
848
                                if strings.Contains(nextHop, "/") {
×
849
                                        nextHop = strings.Split(nextHop, "/")[0]
×
850
                                }
×
851

852
                                if err := c.addPolicyRouteToVpc(
×
853
                                        subnet.Spec.Vpc,
×
854
                                        &kubeovnv1.PolicyRoute{
×
855
                                                Priority:  util.NorthGatewayRoutePolicyPriority,
×
856
                                                Match:     "ip4.src == " + podIP,
×
857
                                                Action:    kubeovnv1.PolicyRouteActionReroute,
×
858
                                                NextHopIP: nextHop,
×
859
                                        },
×
860
                                        map[string]string{
×
861
                                                "vendor": util.CniTypeName,
×
862
                                                "subnet": subnet.Name,
×
863
                                        },
×
864
                                ); err != nil {
×
865
                                        klog.Errorf("failed to add policy route, %v", err)
×
866
                                        return err
×
867
                                }
×
868

869
                                // remove lsp from port group to make EIP/SNAT work
870
                                if err = c.OVNNbClient.PortGroupRemovePorts(pgName, portName); err != nil {
×
871
                                        klog.Error(err)
×
872
                                        return err
×
873
                                }
×
874
                        } else {
×
875
                                if subnet.Spec.GatewayType == kubeovnv1.GWDistributedType && pod.Annotations[util.NorthGatewayAnnotation] == "" {
×
876
                                        nodeTunlIPAddr, err := getNodeTunlIP(node)
×
877
                                        if err != nil {
×
878
                                                klog.Error(err)
×
879
                                                return err
×
880
                                        }
×
881

882
                                        var added bool
×
883
                                        for _, nodeAddr := range nodeTunlIPAddr {
×
884
                                                for podAddr := range strings.SplitSeq(podIP, ",") {
×
885
                                                        if util.CheckProtocol(nodeAddr.String()) != util.CheckProtocol(podAddr) {
×
886
                                                                continue
×
887
                                                        }
888

889
                                                        // remove lsp from other port groups
890
                                                        // we need to do this because the pod, e.g. a sts/vm, can be rescheduled to another node
891
                                                        if err = c.OVNNbClient.RemovePortFromPortGroups(portName, subnetPortGroups...); err != nil {
×
892
                                                                klog.Errorf("failed to remove port %s from port groups %v: %v", portName, subnetPortGroups, err)
×
893
                                                                return err
×
894
                                                        }
×
895
                                                        if err := c.OVNNbClient.PortGroupAddPorts(pgName, portName); err != nil {
×
896
                                                                klog.Errorf("failed to add port %s to port group %s: %v", portName, pgName, err)
×
897
                                                                return err
×
898
                                                        }
×
899

900
                                                        added = true
×
901
                                                        break
×
902
                                                }
903
                                                if added {
×
904
                                                        break
×
905
                                                }
906
                                        }
907
                                }
908

909
                                if pod.Annotations[util.NorthGatewayAnnotation] != "" && pod.Annotations[util.IPAddressAnnotation] != "" {
×
910
                                        for podAddr := range strings.SplitSeq(pod.Annotations[util.IPAddressAnnotation], ",") {
×
911
                                                if util.CheckProtocol(podAddr) != util.CheckProtocol(pod.Annotations[util.NorthGatewayAnnotation]) {
×
912
                                                        continue
×
913
                                                }
914
                                                ipSuffix := "ip4"
×
915
                                                if util.CheckProtocol(podAddr) == kubeovnv1.ProtocolIPv6 {
×
916
                                                        ipSuffix = "ip6"
×
917
                                                }
×
918

919
                                                if err := c.addPolicyRouteToVpc(
×
920
                                                        subnet.Spec.Vpc,
×
921
                                                        &kubeovnv1.PolicyRoute{
×
922
                                                                Priority:  util.NorthGatewayRoutePolicyPriority,
×
923
                                                                Match:     fmt.Sprintf("%s.src == %s", ipSuffix, podAddr),
×
924
                                                                Action:    kubeovnv1.PolicyRouteActionReroute,
×
925
                                                                NextHopIP: pod.Annotations[util.NorthGatewayAnnotation],
×
926
                                                        },
×
927
                                                        map[string]string{
×
928
                                                                "vendor": util.CniTypeName,
×
929
                                                                "subnet": subnet.Name,
×
930
                                                        },
×
931
                                                ); err != nil {
×
932
                                                        klog.Errorf("failed to add policy route, %v", err)
×
933
                                                        return err
×
934
                                                }
×
935
                                        }
936
                                } else if c.config.EnableEipSnat {
×
937
                                        if err = c.deleteStaticRouteFromVpc(
×
938
                                                c.config.ClusterRouter,
×
939
                                                subnet.Spec.RouteTable,
×
940
                                                podIP,
×
941
                                                "",
×
942
                                                kubeovnv1.PolicyDst,
×
943
                                        ); err != nil {
×
944
                                                klog.Error(err)
×
945
                                                return err
×
946
                                        }
×
947
                                }
948
                        }
949

950
                        if c.config.EnableEipSnat {
×
951
                                for ipStr := range strings.SplitSeq(podIP, ",") {
×
952
                                        if eip := pod.Annotations[util.EipAnnotation]; eip == "" {
×
953
                                                if err = c.OVNNbClient.DeleteNats(c.config.ClusterRouter, ovnnb.NATTypeDNATAndSNAT, ipStr); err != nil {
×
954
                                                        klog.Errorf("failed to delete nat rules: %v", err)
×
955
                                                }
×
956
                                        } else if util.CheckProtocol(eip) == util.CheckProtocol(ipStr) {
×
957
                                                if err = c.OVNNbClient.UpdateDnatAndSnat(c.config.ClusterRouter, eip, ipStr, fmt.Sprintf("%s.%s", podName, pod.Namespace), pod.Annotations[util.MacAddressAnnotation], c.ExternalGatewayType); err != nil {
×
958
                                                        klog.Errorf("failed to add nat rules, %v", err)
×
959
                                                        return err
×
960
                                                }
×
961
                                        }
962
                                        if eip := pod.Annotations[util.SnatAnnotation]; eip == "" {
×
963
                                                if err = c.OVNNbClient.DeleteNats(c.config.ClusterRouter, ovnnb.NATTypeSNAT, ipStr); err != nil {
×
964
                                                        klog.Errorf("failed to delete nat rules: %v", err)
×
965
                                                }
×
966
                                        } else if util.CheckProtocol(eip) == util.CheckProtocol(ipStr) {
×
967
                                                if err = c.OVNNbClient.UpdateSnat(c.config.ClusterRouter, eip, ipStr); err != nil {
×
968
                                                        klog.Errorf("failed to add nat rules, %v", err)
×
969
                                                        return err
×
970
                                                }
×
971
                                        }
972
                                }
973
                        }
974
                }
975

976
                if pod.Annotations[fmt.Sprintf(util.ActivationStrategyTemplate, podNet.ProviderName)] != "" {
×
977
                        if err := c.OVNNbClient.SetLogicalSwitchPortActivationStrategy(portName, pod.Spec.NodeName); err != nil {
×
978
                                klog.Errorf("failed to set activation strategy for lsp %s: %v", portName, err)
×
979
                                return err
×
980
                        }
×
981
                }
982

983
                patch[fmt.Sprintf(util.RoutedAnnotationTemplate, podNet.ProviderName)] = "true"
×
984
        }
985
        if err := util.PatchAnnotations(c.config.KubeClient.CoreV1().Pods(namespace), name, patch); err != nil {
×
986
                if k8serrors.IsNotFound(err) {
×
987
                        // Sometimes pod is deleted between kube-ovn configure ovn-nb and patch pod.
×
988
                        // Then we need to recycle the resource again.
×
989
                        key := strings.Join([]string{namespace, name}, "/")
×
990
                        c.deletingPodObjMap.Store(key, pod)
×
991
                        c.deletePodQueue.AddRateLimited(key)
×
992
                        return nil
×
993
                }
×
994
                klog.Errorf("failed to patch pod %s/%s: %v", namespace, name, err)
×
995
                return err
×
996
        }
997
        return nil
×
998
}
999

1000
func (c *Controller) handleDeletePod(key string) (err error) {
×
1001
        pod, ok := c.deletingPodObjMap.Load(key)
×
1002
        if !ok {
×
1003
                return nil
×
1004
        }
×
1005
        now := time.Now()
×
1006
        klog.Infof("handle delete pod %s", key)
×
1007
        podName := c.getNameByPod(pod)
×
1008
        c.podKeyMutex.LockKey(key)
×
1009
        defer func() {
×
1010
                _ = c.podKeyMutex.UnlockKey(key)
×
1011
                if err == nil {
×
1012
                        c.deletingPodObjMap.Delete(key)
×
1013
                }
×
1014
                last := time.Since(now)
×
1015
                klog.Infof("take %d ms to handle delete pod %s", last.Milliseconds(), key)
×
1016
        }()
1017

1018
        p, _ := c.podsLister.Pods(pod.Namespace).Get(pod.Name)
×
1019
        if p != nil && p.UID != pod.UID {
×
1020
                // Pod with same name exists, just return here
×
1021
                return nil
×
1022
        }
×
1023

1024
        if aaps := pod.Annotations[util.AAPsAnnotation]; aaps != "" {
×
1025
                for vipName := range strings.SplitSeq(aaps, ",") {
×
1026
                        if vip, err := c.virtualIpsLister.Get(vipName); err == nil {
×
1027
                                if vip.Spec.Namespace != pod.Namespace {
×
1028
                                        continue
×
1029
                                }
1030
                                klog.Infof("enqueue update virtual parents for %s", vipName)
×
1031
                                c.updateVirtualParentsQueue.Add(vipName)
×
1032
                        }
1033
                }
1034
        }
1035

1036
        podKey := fmt.Sprintf("%s/%s", pod.Namespace, podName)
×
1037

×
1038
        var keepIPCR bool
×
1039
        if ok, stsName, stsUID := isStatefulSetPod(pod); ok {
×
1040
                if !pod.DeletionTimestamp.IsZero() {
×
1041
                        klog.Infof("handle deletion of sts pod %s", podKey)
×
1042
                        toDel := isStatefulSetPodToDel(c.config.KubeClient, pod, stsName, stsUID)
×
1043
                        if !toDel {
×
1044
                                klog.Infof("try keep ip for sts pod %s", podKey)
×
1045
                                keepIPCR = true
×
1046
                        }
×
1047
                }
1048
                if keepIPCR {
×
1049
                        isDelete, err := appendCheckPodToDel(c, pod, stsName, util.StatefulSet)
×
1050
                        if err != nil {
×
1051
                                klog.Error(err)
×
1052
                                return err
×
1053
                        }
×
1054
                        if isDelete {
×
1055
                                klog.Infof("not keep ip for sts pod %s", podKey)
×
1056
                                keepIPCR = false
×
1057
                        }
×
1058
                }
1059
        }
1060
        isVMPod, vmName := isVMPod(pod)
×
1061
        if isVMPod && c.config.EnableKeepVMIP {
×
1062
                ports, err := c.OVNNbClient.ListNormalLogicalSwitchPorts(true, map[string]string{"pod": podKey})
×
1063
                if err != nil {
×
1064
                        klog.Errorf("failed to list lsps of pod %s: %v", podKey, err)
×
1065
                        return err
×
1066
                }
×
1067
                for _, port := range ports {
×
1068
                        if err := c.OVNNbClient.CleanLogicalSwitchPortMigrateOptions(port.Name); err != nil {
×
1069
                                err = fmt.Errorf("failed to clean migrate options for vm lsp %s, %w", port.Name, err)
×
1070
                                klog.Error(err)
×
1071
                                return err
×
1072
                        }
×
1073
                }
1074
                if pod.DeletionTimestamp != nil {
×
1075
                        klog.Infof("handle deletion of vm pod %s", podKey)
×
1076
                        vmToBeDel := c.isVMToDel(pod, vmName)
×
1077
                        if !vmToBeDel {
×
1078
                                klog.Infof("try keep ip for vm pod %s", podKey)
×
1079
                                keepIPCR = true
×
1080
                        }
×
1081
                }
1082
                if keepIPCR {
×
1083
                        isDelete, err := appendCheckPodToDel(c, pod, vmName, util.VMInstance)
×
1084
                        if err != nil {
×
1085
                                klog.Error(err)
×
1086
                                return err
×
1087
                        }
×
1088
                        if isDelete {
×
1089
                                klog.Infof("not keep ip for vm pod %s", podKey)
×
1090
                                keepIPCR = false
×
1091
                        }
×
1092
                }
1093
        }
1094

1095
        podNets, err := c.getPodKubeovnNets(pod)
×
1096
        if err != nil {
×
1097
                klog.Errorf("failed to get kube-ovn nets of pod %s: %v", podKey, err)
×
1098
        }
×
1099
        ports, err := c.OVNNbClient.ListNormalLogicalSwitchPorts(true, map[string]string{"pod": podKey})
×
1100
        if err != nil {
×
1101
                klog.Errorf("failed to list lsps of pod %s: %v", podKey, err)
×
1102
                return err
×
1103
        }
×
1104
        if keepIPCR {
×
1105
                // always remove lsp from port groups
×
1106
                for _, port := range ports {
×
1107
                        klog.Infof("remove lsp %s from all port groups", port.Name)
×
1108
                        if err = c.OVNNbClient.RemovePortFromPortGroups(port.Name); err != nil {
×
1109
                                klog.Errorf("failed to remove lsp %s from all port groups: %v", port.Name, err)
×
1110
                                return err
×
1111
                        }
×
1112
                }
1113
        } else {
×
1114
                if len(ports) != 0 {
×
1115
                        addresses := c.ipam.GetPodAddress(podKey)
×
1116
                        for _, address := range addresses {
×
1117
                                if strings.TrimSpace(address.IP) == "" {
×
1118
                                        continue
×
1119
                                }
1120
                                subnet, err := c.subnetsLister.Get(address.Subnet.Name)
×
1121
                                if k8serrors.IsNotFound(err) {
×
1122
                                        continue
×
1123
                                } else if err != nil {
×
1124
                                        klog.Error(err)
×
1125
                                        return err
×
1126
                                }
×
1127
                                vpc, err := c.vpcsLister.Get(subnet.Spec.Vpc)
×
1128
                                if k8serrors.IsNotFound(err) {
×
1129
                                        continue
×
1130
                                } else if err != nil {
×
1131
                                        klog.Error(err)
×
1132
                                        return err
×
1133
                                }
×
1134

1135
                                ipSuffix := "ip4"
×
1136
                                if util.CheckProtocol(address.IP) == kubeovnv1.ProtocolIPv6 {
×
1137
                                        ipSuffix = "ip6"
×
1138
                                }
×
1139
                                if err = c.deletePolicyRouteFromVpc(
×
1140
                                        vpc.Name,
×
1141
                                        util.NorthGatewayRoutePolicyPriority,
×
1142
                                        fmt.Sprintf("%s.src == %s", ipSuffix, address.IP),
×
1143
                                ); err != nil {
×
1144
                                        klog.Errorf("failed to delete static route, %v", err)
×
1145
                                        return err
×
1146
                                }
×
1147

1148
                                if c.config.EnableEipSnat {
×
1149
                                        if pod.Annotations[util.EipAnnotation] != "" {
×
1150
                                                if err = c.OVNNbClient.DeleteNat(c.config.ClusterRouter, ovnnb.NATTypeDNATAndSNAT, pod.Annotations[util.EipAnnotation], address.IP); err != nil {
×
1151
                                                        klog.Errorf("failed to delete nat rules: %v", err)
×
1152
                                                }
×
1153
                                        }
1154
                                        if pod.Annotations[util.SnatAnnotation] != "" {
×
1155
                                                if err = c.OVNNbClient.DeleteNat(c.config.ClusterRouter, ovnnb.NATTypeSNAT, "", address.IP); err != nil {
×
1156
                                                        klog.Errorf("failed to delete nat rules: %v", err)
×
1157
                                                }
×
1158
                                        }
1159
                                }
1160
                        }
1161
                }
1162
                for _, port := range ports {
×
1163
                        // when lsp is deleted, the port of pod is deleted from any port-group automatically.
×
1164
                        klog.Infof("delete logical switch port %s", port.Name)
×
1165
                        if err := c.OVNNbClient.DeleteLogicalSwitchPort(port.Name); err != nil {
×
1166
                                klog.Errorf("failed to delete lsp %s, %v", port.Name, err)
×
1167
                                return err
×
1168
                        }
×
1169
                }
1170
                klog.Infof("try release all ip address for deleting pod %s", podKey)
×
1171
                for _, podNet := range podNets {
×
1172
                        portName := ovs.PodNameToPortName(podName, pod.Namespace, podNet.ProviderName)
×
1173
                        ipCR, err := c.ipsLister.Get(portName)
×
1174
                        if err != nil {
×
1175
                                if k8serrors.IsNotFound(err) {
×
1176
                                        continue
×
1177
                                }
1178
                                klog.Errorf("failed to get ip %s, %v", portName, err)
×
1179
                                return err
×
1180
                        }
1181
                        if ipCR.Labels[util.IPReservedLabel] != "true" {
×
1182
                                klog.Infof("delete ip CR %s", ipCR.Name)
×
1183
                                if err := c.config.KubeOvnClient.KubeovnV1().IPs().Delete(context.Background(), ipCR.Name, metav1.DeleteOptions{}); err != nil {
×
1184
                                        if !k8serrors.IsNotFound(err) {
×
1185
                                                klog.Errorf("failed to delete ip %s, %v", ipCR.Name, err)
×
1186
                                                return err
×
1187
                                        }
×
1188
                                }
1189
                                // release ipam address after delete ip CR
1190
                                c.ipam.ReleaseAddressByNic(podKey, portName, podNet.Subnet.Name)
×
1191
                        }
1192
                }
1193
                if pod.Annotations[util.VipAnnotation] != "" {
×
1194
                        if err = c.releaseVip(pod.Annotations[util.VipAnnotation]); err != nil {
×
1195
                                klog.Errorf("failed to clean label from vip %s, %v", pod.Annotations[util.VipAnnotation], err)
×
1196
                                return err
×
1197
                        }
×
1198
                }
1199
        }
1200
        for _, podNet := range podNets {
×
1201
                c.syncVirtualPortsQueue.Add(podNet.Subnet.Name)
×
1202
                securityGroupAnnotation := pod.Annotations[fmt.Sprintf(util.SecurityGroupAnnotationTemplate, podNet.ProviderName)]
×
1203
                if securityGroupAnnotation != "" {
×
1204
                        securityGroups := strings.ReplaceAll(securityGroupAnnotation, " ", "")
×
1205
                        for sgName := range strings.SplitSeq(securityGroups, ",") {
×
1206
                                if sgName != "" {
×
1207
                                        c.syncSgPortsQueue.Add(sgName)
×
1208
                                }
×
1209
                        }
1210
                }
1211
        }
1212
        return nil
×
1213
}
1214

1215
func (c *Controller) handleUpdatePodSecurity(key string) error {
×
1216
        now := time.Now()
×
1217
        klog.Infof("handle add/update pod security group %s", key)
×
1218

×
1219
        namespace, name, err := cache.SplitMetaNamespaceKey(key)
×
1220
        if err != nil {
×
1221
                utilruntime.HandleError(fmt.Errorf("invalid resource key: %s", key))
×
1222
                return nil
×
1223
        }
×
1224

1225
        c.podKeyMutex.LockKey(key)
×
1226
        defer func() {
×
1227
                _ = c.podKeyMutex.UnlockKey(key)
×
1228
                last := time.Since(now)
×
1229
                klog.Infof("take %d ms to handle sg for pod %s", last.Milliseconds(), key)
×
1230
        }()
×
1231

1232
        pod, err := c.podsLister.Pods(namespace).Get(name)
×
1233
        if err != nil {
×
1234
                if k8serrors.IsNotFound(err) {
×
1235
                        return nil
×
1236
                }
×
1237
                klog.Error(err)
×
1238
                return err
×
1239
        }
1240
        podName := c.getNameByPod(pod)
×
1241

×
1242
        podNets, err := c.getPodKubeovnNets(pod)
×
1243
        if err != nil {
×
1244
                klog.Errorf("failed to pod nets %v", err)
×
1245
                return err
×
1246
        }
×
1247

1248
        vipsMap := c.getVirtualIPs(pod, podNets)
×
1249

×
1250
        // associated with security group
×
1251
        for _, podNet := range podNets {
×
1252
                portSecurity := false
×
1253
                if pod.Annotations[fmt.Sprintf(util.PortSecurityAnnotationTemplate, podNet.ProviderName)] == "true" {
×
1254
                        portSecurity = true
×
1255
                }
×
1256

1257
                mac := pod.Annotations[fmt.Sprintf(util.MacAddressAnnotationTemplate, podNet.ProviderName)]
×
1258
                ipStr := pod.Annotations[fmt.Sprintf(util.IPAddressAnnotationTemplate, podNet.ProviderName)]
×
1259
                vips := vipsMap[fmt.Sprintf("%s.%s", podNet.Subnet.Name, podNet.ProviderName)]
×
1260
                portName := ovs.PodNameToPortName(podName, namespace, podNet.ProviderName)
×
1261
                if err = c.OVNNbClient.SetLogicalSwitchPortSecurity(portSecurity, portName, mac, ipStr, vips); err != nil {
×
1262
                        klog.Errorf("failed to set security for logical switch port %s: %v", portName, err)
×
1263
                        return err
×
1264
                }
×
1265

1266
                c.syncVirtualPortsQueue.Add(podNet.Subnet.Name)
×
1267
                securityGroupAnnotation := pod.Annotations[fmt.Sprintf(util.SecurityGroupAnnotationTemplate, podNet.ProviderName)]
×
1268
                var securityGroups string
×
1269
                if securityGroupAnnotation != "" {
×
1270
                        securityGroups = strings.ReplaceAll(securityGroupAnnotation, " ", "")
×
1271
                        for sgName := range strings.SplitSeq(securityGroups, ",") {
×
1272
                                if sgName != "" {
×
1273
                                        c.syncSgPortsQueue.Add(sgName)
×
1274
                                }
×
1275
                        }
1276
                }
1277
                if err = c.reconcilePortSg(portName, securityGroups); err != nil {
×
1278
                        klog.Errorf("reconcilePortSg failed. %v", err)
×
1279
                        return err
×
1280
                }
×
1281
        }
1282
        return nil
×
1283
}
1284

1285
func (c *Controller) syncKubeOvnNet(pod *v1.Pod, podNets []*kubeovnNet) (*v1.Pod, error) {
×
1286
        podName := c.getNameByPod(pod)
×
1287
        key := fmt.Sprintf("%s/%s", pod.Namespace, podName)
×
1288
        targetPortNameList := strset.NewWithSize(len(podNets))
×
1289
        portsNeedToDel := []string{}
×
1290
        annotationsNeedToDel := []string{}
×
1291
        annotationsNeedToAdd := make(map[string]string)
×
1292
        subnetUsedByPort := make(map[string]string)
×
1293

×
1294
        for _, podNet := range podNets {
×
1295
                portName := ovs.PodNameToPortName(podName, pod.Namespace, podNet.ProviderName)
×
1296
                targetPortNameList.Add(portName)
×
1297
                if podNet.IPRequest != "" {
×
1298
                        klog.Infof("pod %s/%s use custom IP %s for provider %s", pod.Namespace, pod.Name, podNet.IPRequest, podNet.ProviderName)
×
1299
                        annotationsNeedToAdd[fmt.Sprintf(util.IPAddressAnnotationTemplate, podNet.ProviderName)] = podNet.IPRequest
×
1300
                }
×
1301

1302
                if podNet.MacRequest != "" {
×
1303
                        klog.Infof("pod %s/%s use custom MAC %s for provider %s", pod.Namespace, pod.Name, podNet.MacRequest, podNet.ProviderName)
×
1304
                        annotationsNeedToAdd[fmt.Sprintf(util.MacAddressAnnotationTemplate, podNet.ProviderName)] = podNet.MacRequest
×
1305
                }
×
1306
        }
1307

1308
        ports, err := c.OVNNbClient.ListNormalLogicalSwitchPorts(true, map[string]string{"pod": key})
×
1309
        if err != nil {
×
1310
                klog.Errorf("failed to list lsps of pod '%s', %v", pod.Name, err)
×
1311
                return nil, err
×
1312
        }
×
1313

1314
        for _, port := range ports {
×
1315
                if !targetPortNameList.Has(port.Name) {
×
1316
                        portsNeedToDel = append(portsNeedToDel, port.Name)
×
1317
                        subnetUsedByPort[port.Name] = port.ExternalIDs["ls"]
×
1318
                        portNameSlice := strings.Split(port.Name, ".")
×
1319
                        providerName := strings.Join(portNameSlice[2:], ".")
×
1320
                        if providerName == util.OvnProvider {
×
1321
                                continue
×
1322
                        }
1323
                        annotationsNeedToDel = append(annotationsNeedToDel, providerName)
×
1324
                }
1325
        }
1326

1327
        if len(portsNeedToDel) == 0 && len(annotationsNeedToAdd) == 0 {
×
1328
                return pod, nil
×
1329
        }
×
1330

1331
        for _, portNeedDel := range portsNeedToDel {
×
1332
                klog.Infof("release port %s for pod %s", portNeedDel, podName)
×
1333
                if subnet, ok := c.ipam.Subnets[subnetUsedByPort[portNeedDel]]; ok {
×
1334
                        subnet.ReleaseAddressWithNicName(podName, portNeedDel)
×
1335
                }
×
1336
                if err := c.OVNNbClient.DeleteLogicalSwitchPort(portNeedDel); err != nil {
×
1337
                        klog.Errorf("failed to delete lsp %s, %v", portNeedDel, err)
×
1338
                        return nil, err
×
1339
                }
×
1340
                if err := c.config.KubeOvnClient.KubeovnV1().IPs().Delete(context.Background(), portNeedDel, metav1.DeleteOptions{}); err != nil {
×
1341
                        if !k8serrors.IsNotFound(err) {
×
1342
                                klog.Errorf("failed to delete ip %s, %v", portNeedDel, err)
×
1343
                                return nil, err
×
1344
                        }
×
1345
                }
1346
        }
1347

1348
        patch := util.KVPatch{}
×
1349
        for _, providerName := range annotationsNeedToDel {
×
1350
                for key := range pod.Annotations {
×
1351
                        if strings.HasPrefix(key, providerName) {
×
1352
                                patch[key] = nil
×
1353
                        }
×
1354
                }
1355
        }
1356

1357
        for key, value := range annotationsNeedToAdd {
×
1358
                patch[key] = value
×
1359
        }
×
1360

1361
        if len(patch) == 0 {
×
1362
                return pod, nil
×
1363
        }
×
1364

1365
        if err = util.PatchAnnotations(c.config.KubeClient.CoreV1().Pods(pod.Namespace), pod.Name, patch); err != nil {
×
1366
                if k8serrors.IsNotFound(err) {
×
1367
                        return nil, nil
×
1368
                }
×
1369
                klog.Errorf("failed to clean annotations for pod %s/%s: %v", pod.Namespace, pod.Name, err)
×
1370
                return nil, err
×
1371
        }
1372

1373
        if pod, err = c.config.KubeClient.CoreV1().Pods(pod.Namespace).Get(context.TODO(), pod.Name, metav1.GetOptions{}); err != nil {
×
1374
                if k8serrors.IsNotFound(err) {
×
1375
                        return nil, nil
×
1376
                }
×
1377
                klog.Errorf("failed to get pod %s/%s: %v", pod.Namespace, pod.Name, err)
×
1378
                return nil, err
×
1379
        }
1380

1381
        return pod, nil
×
1382
}
1383

1384
func isStatefulSetPod(pod *v1.Pod) (bool, string, types.UID) {
×
1385
        for _, owner := range pod.OwnerReferences {
×
1386
                if owner.Kind == util.StatefulSet && strings.HasPrefix(owner.APIVersion, "apps/") {
×
1387
                        if strings.HasPrefix(pod.Name, owner.Name) {
×
1388
                                return true, owner.Name, owner.UID
×
1389
                        }
×
1390
                }
1391
        }
1392
        return false, "", ""
×
1393
}
1394

1395
func isStatefulSetPodToDel(c kubernetes.Interface, pod *v1.Pod, statefulSetName string, statefulSetUID types.UID) bool {
×
1396
        // only delete statefulset pod lsp when statefulset deleted or down scaled
×
1397
        sts, err := c.AppsV1().StatefulSets(pod.Namespace).Get(context.Background(), statefulSetName, metav1.GetOptions{})
×
1398
        if err != nil {
×
1399
                // statefulset is deleted
×
1400
                if k8serrors.IsNotFound(err) {
×
1401
                        klog.Infof("statefulset %s/%s has been deleted", pod.Namespace, statefulSetName)
×
1402
                        return true
×
1403
                }
×
1404
                klog.Errorf("failed to get statefulset %s/%s: %v", pod.Namespace, statefulSetName, err)
×
1405
                return false
×
1406
        }
1407

1408
        // statefulset is being deleted, or it's a newly created one
1409
        if !sts.DeletionTimestamp.IsZero() {
×
1410
                klog.Infof("statefulset %s/%s is being deleted", pod.Namespace, statefulSetName)
×
1411
                return true
×
1412
        }
×
1413
        if sts.UID != statefulSetUID {
×
1414
                klog.Infof("statefulset %s/%s is a newly created one", pod.Namespace, statefulSetName)
×
1415
                return true
×
1416
        }
×
1417

1418
        // down scale statefulset
1419
        tempStrs := strings.Split(pod.Name, "-")
×
1420
        numStr := tempStrs[len(tempStrs)-1]
×
1421
        index, err := strconv.ParseInt(numStr, 10, 0)
×
1422
        if err != nil {
×
1423
                klog.Errorf("failed to parse %s to int", numStr)
×
1424
                return false
×
1425
        }
×
1426
        // down scaled
1427
        var startOrdinal int64
×
1428
        if sts.Spec.Ordinals != nil {
×
1429
                startOrdinal = int64(sts.Spec.Ordinals.Start)
×
1430
        }
×
1431
        if index >= startOrdinal+int64(*sts.Spec.Replicas) {
×
1432
                klog.Infof("statefulset %s/%s is down scaled", pod.Namespace, statefulSetName)
×
1433
                return true
×
1434
        }
×
1435
        return false
×
1436
}
1437

1438
// only gc statefulset pod lsp when:
1439
// 1. the statefulset has been deleted or is being deleted
1440
// 2. the statefulset has been deleted and recreated
1441
// 3. the statefulset is down scaled and the pod is not alive
1442
func isStatefulSetPodToGC(c kubernetes.Interface, pod *v1.Pod, statefulSetName string, statefulSetUID types.UID) bool {
×
1443
        sts, err := c.AppsV1().StatefulSets(pod.Namespace).Get(context.Background(), statefulSetName, metav1.GetOptions{})
×
1444
        if err != nil {
×
1445
                // the statefulset has been deleted
×
1446
                if k8serrors.IsNotFound(err) {
×
1447
                        klog.Infof("statefulset %s/%s has been deleted", pod.Namespace, statefulSetName)
×
1448
                        return true
×
1449
                }
×
1450
                klog.Errorf("failed to get statefulset %s/%s: %v", pod.Namespace, statefulSetName, err)
×
1451
                return false
×
1452
        }
1453

1454
        // statefulset is being deleted
1455
        if !sts.DeletionTimestamp.IsZero() {
×
1456
                klog.Infof("statefulset %s/%s is being deleted", pod.Namespace, statefulSetName)
×
1457
                return true
×
1458
        }
×
1459
        // the statefulset has been deleted and recreated
1460
        if sts.UID != statefulSetUID {
×
1461
                klog.Infof("statefulset %s/%s is a newly created one", pod.Namespace, statefulSetName)
×
1462
                return true
×
1463
        }
×
1464

1465
        // the statefulset is down scaled and the pod is not alive
1466

1467
        tempStrs := strings.Split(pod.Name, "-")
×
1468
        numStr := tempStrs[len(tempStrs)-1]
×
1469
        index, err := strconv.ParseInt(numStr, 10, 0)
×
1470
        if err != nil {
×
1471
                klog.Errorf("failed to parse %s to int", numStr)
×
1472
                return false
×
1473
        }
×
1474
        // down scaled
1475
        var startOrdinal int64
×
1476
        if sts.Spec.Ordinals != nil {
×
1477
                startOrdinal = int64(sts.Spec.Ordinals.Start)
×
1478
        }
×
1479
        if index >= startOrdinal+int64(*sts.Spec.Replicas) {
×
1480
                klog.Infof("statefulset %s/%s is down scaled", pod.Namespace, statefulSetName)
×
1481
                if !isPodAlive(pod) {
×
1482
                        // we must check whether the pod is alive because we have to consider the following case:
×
1483
                        // 1. the statefulset is down scaled to zero
×
1484
                        // 2. the lsp gc is triggered
×
1485
                        // 3. gc interval, e.g. 90s, is passed and the second gc is triggered
×
1486
                        // 4. the sts is up scaled to the original replicas
×
1487
                        // 5. the pod is still running and it will not be recreated
×
1488
                        return true
×
1489
                }
×
1490
        }
1491

1492
        return false
×
1493
}
1494

1495
func getNodeTunlIP(node *v1.Node) ([]net.IP, error) {
×
1496
        var nodeTunlIPAddr []net.IP
×
1497
        nodeTunlIP := node.Annotations[util.IPAddressAnnotation]
×
1498
        if nodeTunlIP == "" {
×
1499
                return nil, errors.New("node has no tunnel ip annotation")
×
1500
        }
×
1501

1502
        for ip := range strings.SplitSeq(nodeTunlIP, ",") {
×
1503
                nodeTunlIPAddr = append(nodeTunlIPAddr, net.ParseIP(ip))
×
1504
        }
×
1505
        return nodeTunlIPAddr, nil
×
1506
}
1507

1508
func getNextHopByTunnelIP(gw []net.IP) string {
×
1509
        // validation check by caller
×
1510
        nextHop := gw[0].String()
×
1511
        if len(gw) == 2 {
×
1512
                nextHop = gw[0].String() + "," + gw[1].String()
×
1513
        }
×
1514
        return nextHop
×
1515
}
1516

1517
func needAllocateSubnets(pod *v1.Pod, nets []*kubeovnNet) []*kubeovnNet {
×
1518
        // check if allocate from subnet is need.
×
1519
        // allocate subnet when change subnet to hotplug nic
×
1520
        // allocate subnet when migrate vm
×
1521
        if !isPodAlive(pod) {
×
1522
                return nil
×
1523
        }
×
1524

1525
        if pod.Annotations == nil {
×
1526
                return nets
×
1527
        }
×
1528

1529
        migrate := false
×
1530
        if job, ok := pod.Annotations[util.MigrationJobAnnotation]; ok {
×
1531
                klog.Infof("pod %s/%s is in the migration job %s", pod.Namespace, pod.Name, job)
×
1532
                migrate = true
×
1533
        }
×
1534

1535
        result := make([]*kubeovnNet, 0, len(nets))
×
1536
        for _, n := range nets {
×
1537
                if migrate || pod.Annotations[fmt.Sprintf(util.AllocatedAnnotationTemplate, n.ProviderName)] != "true" {
×
1538
                        result = append(result, n)
×
1539
                }
×
1540
        }
1541
        return result
×
1542
}
1543

1544
func needRestartNatGatewayPod(pod *v1.Pod) bool {
×
1545
        for _, psc := range pod.Status.ContainerStatuses {
×
1546
                if psc.Name != "vpc-nat-gw" {
×
1547
                        continue
×
1548
                }
1549
                if psc.RestartCount > 0 {
×
1550
                        return true
×
1551
                }
×
1552
        }
1553
        return false
×
1554
}
1555

1556
func (c *Controller) podNeedSync(pod *v1.Pod) (bool, error) {
×
1557
        // 1. check annotations
×
1558
        if pod.Annotations == nil {
×
1559
                return true, nil
×
1560
        }
×
1561
        // 2. check annotation ovn subnet
1562
        if pod.Annotations[util.RoutedAnnotation] != "true" {
×
1563
                return true, nil
×
1564
        }
×
1565
        // 3. check multus subnet
1566
        attachmentNets, err := c.getPodAttachmentNet(pod)
×
1567
        if err != nil {
×
1568
                klog.Error(err)
×
1569
                return false, err
×
1570
        }
×
1571

1572
        podName := c.getNameByPod(pod)
×
1573
        for _, n := range attachmentNets {
×
1574
                if pod.Annotations[fmt.Sprintf(util.RoutedAnnotationTemplate, n.ProviderName)] != "true" {
×
1575
                        return true, nil
×
1576
                }
×
1577
                ipName := ovs.PodNameToPortName(podName, pod.Namespace, n.ProviderName)
×
1578
                if _, err = c.ipsLister.Get(ipName); err != nil {
×
1579
                        if !k8serrors.IsNotFound(err) {
×
1580
                                err = fmt.Errorf("failed to get ip %s: %w", ipName, err)
×
1581
                                klog.Error(err)
×
1582
                                return false, err
×
1583
                        }
×
1584
                        klog.Infof("ip %s not found", ipName)
×
1585
                        // need to sync to create ip
×
1586
                        return true, nil
×
1587
                }
1588
        }
1589
        return false, nil
×
1590
}
1591

1592
func needRouteSubnets(pod *v1.Pod, nets []*kubeovnNet) []*kubeovnNet {
×
1593
        if !isPodAlive(pod) {
×
1594
                return nil
×
1595
        }
×
1596

1597
        if pod.Annotations == nil {
×
1598
                return nets
×
1599
        }
×
1600

1601
        result := make([]*kubeovnNet, 0, len(nets))
×
1602
        for _, n := range nets {
×
1603
                if !isOvnSubnet(n.Subnet) {
×
1604
                        continue
×
1605
                }
1606

1607
                if pod.Annotations[fmt.Sprintf(util.AllocatedAnnotationTemplate, n.ProviderName)] == "true" && pod.Spec.NodeName != "" {
×
1608
                        if pod.Annotations[fmt.Sprintf(util.RoutedAnnotationTemplate, n.ProviderName)] != "true" {
×
1609
                                result = append(result, n)
×
1610
                        }
×
1611
                }
1612
        }
1613
        return result
×
1614
}
1615

1616
func (c *Controller) getPodDefaultSubnet(pod *v1.Pod) (*kubeovnv1.Subnet, error) {
×
1617
        // ignore to clean its ip crd in existing subnets
×
1618
        ignoreSubnetNotExist := !pod.DeletionTimestamp.IsZero()
×
1619

×
1620
        // check pod annotations
×
1621
        if lsName := pod.Annotations[util.LogicalSwitchAnnotation]; lsName != "" {
×
1622
                // annotations only has one default subnet
×
1623
                subnet, err := c.subnetsLister.Get(lsName)
×
1624
                if err != nil {
×
1625
                        klog.Errorf("failed to get subnet %s: %v", lsName, err)
×
1626
                        if k8serrors.IsNotFound(err) {
×
1627
                                if ignoreSubnetNotExist {
×
1628
                                        klog.Errorf("deletting pod %s/%s default subnet %s already not exist, gc will clean its ip cr", pod.Namespace, pod.Name, lsName)
×
1629
                                        return nil, nil
×
1630
                                }
×
1631
                        }
1632
                        return nil, err
×
1633
                }
1634
                return subnet, nil
×
1635
        }
1636

1637
        ns, err := c.namespacesLister.Get(pod.Namespace)
×
1638
        if err != nil {
×
1639
                klog.Errorf("failed to get namespace %s: %v", pod.Namespace, err)
×
1640
                return nil, err
×
1641
        }
×
1642
        if len(ns.Annotations) == 0 {
×
1643
                err = fmt.Errorf("namespace %s network annotations is empty", ns.Name)
×
1644
                klog.Error(err)
×
1645
                return nil, err
×
1646
        }
×
1647

1648
        subnetNames := ns.Annotations[util.LogicalSwitchAnnotation]
×
1649
        for subnetName := range strings.SplitSeq(subnetNames, ",") {
×
1650
                if subnetName == "" {
×
1651
                        err = fmt.Errorf("namespace %s default logical switch is not found", ns.Name)
×
1652
                        klog.Error(err)
×
1653
                        return nil, err
×
1654
                }
×
1655
                subnet, err := c.subnetsLister.Get(subnetName)
×
1656
                if err != nil {
×
1657
                        klog.Errorf("failed to get subnet %s: %v", subnetName, err)
×
1658
                        if k8serrors.IsNotFound(err) {
×
1659
                                if ignoreSubnetNotExist {
×
1660
                                        klog.Errorf("deletting pod %s/%s namespace subnet %s already not exist, gc will clean its ip cr", pod.Namespace, pod.Name, subnetName)
×
1661
                                        // ip name is unique, it is ok if any subnet release it
×
1662
                                        // gc will handle their ip cr, if all subnets are not exist
×
1663
                                        continue
×
1664
                                }
1665
                        }
1666
                        return nil, err
×
1667
                }
1668

1669
                switch subnet.Spec.Protocol {
×
1670
                case kubeovnv1.ProtocolDual:
×
1671
                        if subnet.Status.V6AvailableIPs == 0 && !c.podCanUseExcludeIPs(pod, subnet) {
×
1672
                                klog.Infof("there's no available ipv6 address in subnet %s, try next one", subnet.Name)
×
1673
                                continue
×
1674
                        }
1675
                        fallthrough
×
1676
                case kubeovnv1.ProtocolIPv4:
×
1677
                        if subnet.Status.V4AvailableIPs == 0 && !c.podCanUseExcludeIPs(pod, subnet) {
×
1678
                                klog.Infof("there's no available ipv4 address in subnet %s, try next one", subnet.Name)
×
1679
                                continue
×
1680
                        }
1681
                case kubeovnv1.ProtocolIPv6:
×
1682
                        if subnet.Status.V6AvailableIPs == 0 && !c.podCanUseExcludeIPs(pod, subnet) {
×
1683
                                klog.Infof("there's no available ipv6 address in subnet %s, try next one", subnet.Name)
×
1684
                                continue
×
1685
                        }
1686
                }
1687
                return subnet, nil
×
1688
        }
1689
        return nil, ipam.ErrNoAvailable
×
1690
}
1691

1692
func (c *Controller) podCanUseExcludeIPs(pod *v1.Pod, subnet *kubeovnv1.Subnet) bool {
×
1693
        if ipAddr := pod.Annotations[util.IPAddressAnnotation]; ipAddr != "" {
×
1694
                return c.checkIPsInExcludeList(ipAddr, subnet.Spec.ExcludeIps, subnet.Spec.CIDRBlock)
×
1695
        }
×
1696
        if ipPool := pod.Annotations[util.IPPoolAnnotation]; ipPool != "" {
×
1697
                return c.checkIPsInExcludeList(ipPool, subnet.Spec.ExcludeIps, subnet.Spec.CIDRBlock)
×
1698
        }
×
1699

1700
        return false
×
1701
}
1702

1703
func (c *Controller) checkIPsInExcludeList(ips string, excludeIPs []string, cidr string) bool {
×
1704
        expandedExcludeIPs := util.ExpandExcludeIPs(excludeIPs, cidr)
×
1705

×
1706
        for ipAddr := range strings.SplitSeq(strings.TrimSpace(ips), ",") {
×
1707
                ipAddr = strings.TrimSpace(ipAddr)
×
1708
                if ipAddr == "" {
×
1709
                        continue
×
1710
                }
1711

1712
                for _, excludeIP := range expandedExcludeIPs {
×
1713
                        if util.ContainsIPs(excludeIP, ipAddr) {
×
1714
                                klog.V(3).Infof("IP %s is found in exclude IP %s, allowing allocation", ipAddr, excludeIP)
×
1715
                                return true
×
1716
                        }
×
1717
                }
1718
        }
1719
        return false
×
1720
}
1721

1722
type providerType int
1723

1724
const (
1725
        providerTypeIPAM providerType = iota
1726
        providerTypeOriginal
1727
)
1728

1729
type kubeovnNet struct {
1730
        Type               providerType
1731
        ProviderName       string
1732
        Subnet             *kubeovnv1.Subnet
1733
        IsDefault          bool
1734
        AllowLiveMigration bool
1735
        IPRequest          string
1736
        MacRequest         string
1737
}
1738

1739
func (c *Controller) getPodAttachmentNet(pod *v1.Pod) ([]*kubeovnNet, error) {
×
1740
        var multusNets []*nadv1.NetworkSelectionElement
×
1741
        defaultAttachNetworks := pod.Annotations[util.DefaultNetworkAnnotation]
×
1742
        if defaultAttachNetworks != "" {
×
1743
                attachments, err := nadutils.ParseNetworkAnnotation(defaultAttachNetworks, pod.Namespace)
×
1744
                if err != nil {
×
1745
                        klog.Errorf("failed to parse default attach net for pod '%s', %v", pod.Name, err)
×
1746
                        return nil, err
×
1747
                }
×
1748
                multusNets = attachments
×
1749
        }
1750

1751
        attachNetworks := pod.Annotations[nadv1.NetworkAttachmentAnnot]
×
1752
        if attachNetworks != "" {
×
1753
                attachments, err := nadutils.ParseNetworkAnnotation(attachNetworks, pod.Namespace)
×
1754
                if err != nil {
×
1755
                        klog.Errorf("failed to parse attach net for pod '%s', %v", pod.Name, err)
×
1756
                        return nil, err
×
1757
                }
×
1758
                multusNets = append(multusNets, attachments...)
×
1759
        }
1760
        subnets, err := c.subnetsLister.List(labels.Everything())
×
1761
        if err != nil {
×
1762
                klog.Errorf("failed to list subnets: %v", err)
×
1763
                return nil, err
×
1764
        }
×
1765

1766
        // ignore to return all existing subnets to clean its ip crd
1767
        ignoreSubnetNotExist := !pod.DeletionTimestamp.IsZero()
×
1768

×
1769
        result := make([]*kubeovnNet, 0, len(multusNets))
×
1770
        for _, attach := range multusNets {
×
1771
                network, err := c.netAttachLister.NetworkAttachmentDefinitions(attach.Namespace).Get(attach.Name)
×
1772
                if err != nil {
×
1773
                        klog.Errorf("failed to get net-attach-def %s, %v", attach.Name, err)
×
1774
                        return nil, err
×
1775
                }
×
1776

1777
                if network.Spec.Config == "" {
×
1778
                        continue
×
1779
                }
1780

1781
                netCfg, err := loadNetConf([]byte(network.Spec.Config))
×
1782
                if err != nil {
×
1783
                        klog.Errorf("failed to load config of net-attach-def %s, %v", attach.Name, err)
×
1784
                        return nil, err
×
1785
                }
×
1786

1787
                // allocate kubeovn network
1788
                var providerName string
×
1789
                if util.IsOvnNetwork(netCfg) {
×
1790
                        allowLiveMigration := false
×
1791
                        isDefault := util.IsDefaultNet(pod.Annotations[util.DefaultNetworkAnnotation], attach)
×
1792

×
1793
                        providerName = fmt.Sprintf("%s.%s.%s", attach.Name, attach.Namespace, util.OvnProvider)
×
1794
                        if pod.Annotations[util.MigrationJobAnnotation] != "" {
×
1795
                                allowLiveMigration = true
×
1796
                        }
×
1797

1798
                        subnetName := pod.Annotations[fmt.Sprintf(util.LogicalSwitchAnnotationTemplate, providerName)]
×
1799
                        if subnetName == "" {
×
1800
                                for _, subnet := range subnets {
×
1801
                                        if subnet.Spec.Provider == providerName {
×
1802
                                                subnetName = subnet.Name
×
1803
                                                break
×
1804
                                        }
1805
                                }
1806
                        }
1807
                        var subnet *kubeovnv1.Subnet
×
1808
                        if subnetName == "" {
×
1809
                                // attachment network not specify subnet, use pod default subnet or namespace subnet
×
1810
                                subnet, err = c.getPodDefaultSubnet(pod)
×
1811
                                if err != nil {
×
1812
                                        klog.Errorf("failed to pod default subnet, %v", err)
×
1813
                                        if k8serrors.IsNotFound(err) {
×
1814
                                                if ignoreSubnetNotExist {
×
1815
                                                        klog.Errorf("deletting pod %s/%s attach subnet %s already not exist, gc will clean its ip cr", pod.Namespace, pod.Name, subnetName)
×
1816
                                                        continue
×
1817
                                                }
1818
                                        }
1819
                                        return nil, err
×
1820
                                }
1821
                                // default subnet may change after pod restart
1822
                                klog.Infof("pod %s/%s attachment network %s use default subnet %s", pod.Namespace, pod.Name, attach.Name, subnet.Name)
×
1823
                        } else {
×
1824
                                subnet, err = c.subnetsLister.Get(subnetName)
×
1825
                                if err != nil {
×
1826
                                        klog.Errorf("failed to get subnet %s, %v", subnetName, err)
×
1827
                                        if k8serrors.IsNotFound(err) {
×
1828
                                                if ignoreSubnetNotExist {
×
1829
                                                        klog.Errorf("deletting pod %s/%s attach subnet %s already not exist, gc will clean its ip cr", pod.Namespace, pod.Name, subnetName)
×
1830
                                                        // just continue to next attach subnet
×
1831
                                                        // ip name is unique, so it is ok if the other subnet release it
×
1832
                                                        continue
×
1833
                                                }
1834
                                        }
1835
                                        return nil, err
×
1836
                                }
1837
                        }
1838

1839
                        ret := &kubeovnNet{
×
1840
                                Type:               providerTypeOriginal,
×
1841
                                ProviderName:       providerName,
×
1842
                                Subnet:             subnet,
×
1843
                                IsDefault:          isDefault,
×
1844
                                AllowLiveMigration: allowLiveMigration,
×
1845
                                MacRequest:         attach.MacRequest,
×
1846
                                IPRequest:          strings.Join(attach.IPRequest, ","),
×
1847
                        }
×
1848
                        result = append(result, ret)
×
1849
                } else {
×
1850
                        providerName = fmt.Sprintf("%s.%s", attach.Name, attach.Namespace)
×
1851
                        for _, subnet := range subnets {
×
1852
                                if subnet.Spec.Provider == providerName {
×
1853
                                        result = append(result, &kubeovnNet{
×
1854
                                                Type:         providerTypeIPAM,
×
1855
                                                ProviderName: providerName,
×
1856
                                                Subnet:       subnet,
×
1857
                                                MacRequest:   attach.MacRequest,
×
1858
                                                IPRequest:    strings.Join(attach.IPRequest, ","),
×
1859
                                        })
×
1860
                                        break
×
1861
                                }
1862
                        }
1863
                }
1864
        }
1865
        return result, nil
×
1866
}
1867

1868
func (c *Controller) validatePodIP(podName, subnetName, ipv4, ipv6 string) (bool, bool, error) {
×
1869
        subnet, err := c.subnetsLister.Get(subnetName)
×
1870
        if err != nil {
×
1871
                klog.Errorf("failed to get subnet %s: %v", subnetName, err)
×
1872
                return false, false, err
×
1873
        }
×
1874

1875
        if subnet.Spec.Vlan == "" && subnet.Spec.Vpc == c.config.ClusterRouter {
×
1876
                nodes, err := c.nodesLister.List(labels.Everything())
×
1877
                if err != nil {
×
1878
                        klog.Errorf("failed to list nodes: %v", err)
×
1879
                        return false, false, err
×
1880
                }
×
1881

1882
                for _, node := range nodes {
×
1883
                        nodeIPv4, nodeIPv6 := util.GetNodeInternalIP(*node)
×
1884
                        if ipv4 != "" && ipv4 == nodeIPv4 {
×
1885
                                klog.Errorf("IP address (%s) assigned to pod %s is the same with internal IP address of node %s, reallocating...", ipv4, podName, node.Name)
×
1886
                                return false, true, nil
×
1887
                        }
×
1888
                        if ipv6 != "" && ipv6 == nodeIPv6 {
×
1889
                                klog.Errorf("IP address (%s) assigned to pod %s is the same with internal IP address of node %s, reallocating...", ipv6, podName, node.Name)
×
1890
                                return true, false, nil
×
1891
                        }
×
1892
                }
1893
        }
1894

1895
        return true, true, nil
×
1896
}
1897

1898
func (c *Controller) acquireAddress(pod *v1.Pod, podNet *kubeovnNet) (string, string, string, *kubeovnv1.Subnet, error) {
×
1899
        podName := c.getNameByPod(pod)
×
1900
        key := fmt.Sprintf("%s/%s", pod.Namespace, podName)
×
1901

×
1902
        var checkVMPod bool
×
1903
        isStsPod, _, _ := isStatefulSetPod(pod)
×
1904
        // if pod has static vip
×
1905
        vipName := pod.Annotations[util.VipAnnotation]
×
1906
        if vipName != "" {
×
1907
                vip, err := c.virtualIpsLister.Get(vipName)
×
1908
                if err != nil {
×
1909
                        klog.Errorf("failed to get static vip '%s', %v", vipName, err)
×
1910
                        return "", "", "", podNet.Subnet, err
×
1911
                }
×
1912
                portName := ovs.PodNameToPortName(podName, pod.Namespace, podNet.ProviderName)
×
1913
                if c.config.EnableKeepVMIP {
×
1914
                        checkVMPod, _ = isVMPod(pod)
×
1915
                }
×
1916
                if err = c.podReuseVip(vipName, portName, isStsPod || checkVMPod); err != nil {
×
1917
                        return "", "", "", podNet.Subnet, err
×
1918
                }
×
1919
                return vip.Status.V4ip, vip.Status.V6ip, vip.Status.Mac, podNet.Subnet, nil
×
1920
        }
1921

1922
        var macPointer *string
×
1923
        if isOvnSubnet(podNet.Subnet) {
×
1924
                annoMAC := pod.Annotations[fmt.Sprintf(util.MacAddressAnnotationTemplate, podNet.ProviderName)]
×
1925
                if annoMAC != "" {
×
1926
                        if _, err := net.ParseMAC(annoMAC); err != nil {
×
1927
                                return "", "", "", podNet.Subnet, err
×
1928
                        }
×
1929
                        macPointer = &annoMAC
×
1930
                }
1931
        } else {
×
1932
                macPointer = ptr.To("")
×
1933
        }
×
1934

1935
        ippoolStr := pod.Annotations[fmt.Sprintf(util.IPPoolAnnotationTemplate, podNet.ProviderName)]
×
1936
        if ippoolStr == "" {
×
1937
                ns, err := c.namespacesLister.Get(pod.Namespace)
×
1938
                if err != nil {
×
1939
                        klog.Errorf("failed to get namespace %s: %v", pod.Namespace, err)
×
1940
                        return "", "", "", podNet.Subnet, err
×
1941
                }
×
1942

1943
                if len(ns.Annotations) != 0 {
×
1944
                        if ipPoolList, ok := ns.Annotations[util.IPPoolAnnotation]; ok {
×
1945
                                for ipPoolName := range strings.SplitSeq(ipPoolList, ",") {
×
1946
                                        ippool, err := c.ippoolLister.Get(ipPoolName)
×
1947
                                        if err != nil {
×
1948
                                                klog.Errorf("failed to get ippool %s: %v", ipPoolName, err)
×
1949
                                                return "", "", "", podNet.Subnet, err
×
1950
                                        }
×
1951

1952
                                        switch podNet.Subnet.Spec.Protocol {
×
1953
                                        case kubeovnv1.ProtocolDual:
×
1954
                                                if ippool.Status.V4AvailableIPs.Int64() == 0 || ippool.Status.V6AvailableIPs.Int64() == 0 {
×
1955
                                                        continue
×
1956
                                                }
1957
                                        case kubeovnv1.ProtocolIPv4:
×
1958
                                                if ippool.Status.V4AvailableIPs.Int64() == 0 {
×
1959
                                                        continue
×
1960
                                                }
1961

1962
                                        default:
×
1963
                                                if ippool.Status.V6AvailableIPs.Int64() == 0 {
×
1964
                                                        continue
×
1965
                                                }
1966
                                        }
1967

1968
                                        if ippool.Spec.Subnet == podNet.Subnet.Name {
×
1969
                                                ippoolStr = ippool.Name
×
1970
                                                break
×
1971
                                        }
1972
                                }
1973
                        }
1974
                }
1975
        }
1976

1977
        // Random allocate
1978
        if pod.Annotations[fmt.Sprintf(util.IPAddressAnnotationTemplate, podNet.ProviderName)] == "" &&
×
1979
                ippoolStr == "" {
×
1980
                var skippedAddrs []string
×
1981
                for {
×
1982
                        portName := ovs.PodNameToPortName(podName, pod.Namespace, podNet.ProviderName)
×
1983

×
1984
                        ipv4, ipv6, mac, err := c.ipam.GetRandomAddress(key, portName, macPointer, podNet.Subnet.Name, "", skippedAddrs, !podNet.AllowLiveMigration)
×
1985
                        if err != nil {
×
1986
                                klog.Error(err)
×
1987
                                return "", "", "", podNet.Subnet, err
×
1988
                        }
×
1989
                        ipv4OK, ipv6OK, err := c.validatePodIP(pod.Name, podNet.Subnet.Name, ipv4, ipv6)
×
1990
                        if err != nil {
×
1991
                                klog.Error(err)
×
1992
                                return "", "", "", podNet.Subnet, err
×
1993
                        }
×
1994
                        if ipv4OK && ipv6OK {
×
1995
                                return ipv4, ipv6, mac, podNet.Subnet, nil
×
1996
                        }
×
1997

1998
                        if !ipv4OK {
×
1999
                                skippedAddrs = append(skippedAddrs, ipv4)
×
2000
                        }
×
2001
                        if !ipv6OK {
×
2002
                                skippedAddrs = append(skippedAddrs, ipv6)
×
2003
                        }
×
2004
                }
2005
        }
2006

2007
        portName := ovs.PodNameToPortName(podName, pod.Namespace, podNet.ProviderName)
×
2008

×
2009
        // The static ip can be assigned from any subnet after ns supports multi subnets
×
2010
        nsNets, _ := c.getNsAvailableSubnets(pod, podNet)
×
2011
        var v4IP, v6IP, mac string
×
2012
        var err error
×
2013

×
2014
        // Static allocate
×
2015
        if pod.Annotations[fmt.Sprintf(util.IPAddressAnnotationTemplate, podNet.ProviderName)] != "" {
×
2016
                ipStr := pod.Annotations[fmt.Sprintf(util.IPAddressAnnotationTemplate, podNet.ProviderName)]
×
2017

×
2018
                for _, net := range nsNets {
×
2019
                        v4IP, v6IP, mac, err = c.acquireStaticAddress(key, portName, ipStr, macPointer, net.Subnet.Name, net.AllowLiveMigration)
×
2020
                        if err == nil {
×
2021
                                return v4IP, v6IP, mac, net.Subnet, nil
×
2022
                        }
×
2023
                }
2024
                return v4IP, v6IP, mac, podNet.Subnet, err
×
2025
        }
2026

2027
        // IPPool allocate
2028
        if ippoolStr != "" {
×
2029
                var ipPool []string
×
2030
                if strings.ContainsRune(ippoolStr, ';') {
×
2031
                        ipPool = strings.Split(ippoolStr, ";")
×
2032
                } else {
×
2033
                        ipPool = strings.Split(ippoolStr, ",")
×
2034
                        if len(ipPool) == 2 && util.CheckProtocol(ipPool[0]) != util.CheckProtocol(ipPool[1]) {
×
2035
                                ipPool = []string{ippoolStr}
×
2036
                        }
×
2037
                }
2038
                for i, ip := range ipPool {
×
2039
                        ipPool[i] = strings.TrimSpace(ip)
×
2040
                }
×
2041

2042
                if len(ipPool) == 1 && (!strings.ContainsRune(ipPool[0], ',') && net.ParseIP(ipPool[0]) == nil) {
×
2043
                        var skippedAddrs []string
×
2044
                        for {
×
2045
                                portName := ovs.PodNameToPortName(podName, pod.Namespace, podNet.ProviderName)
×
2046
                                ipv4, ipv6, mac, err := c.ipam.GetRandomAddress(key, portName, macPointer, podNet.Subnet.Name, ipPool[0], skippedAddrs, !podNet.AllowLiveMigration)
×
2047
                                if err != nil {
×
2048
                                        klog.Error(err)
×
2049
                                        return "", "", "", podNet.Subnet, err
×
2050
                                }
×
2051
                                ipv4OK, ipv6OK, err := c.validatePodIP(pod.Name, podNet.Subnet.Name, ipv4, ipv6)
×
2052
                                if err != nil {
×
2053
                                        klog.Error(err)
×
2054
                                        return "", "", "", podNet.Subnet, err
×
2055
                                }
×
2056
                                if ipv4OK && ipv6OK {
×
2057
                                        return ipv4, ipv6, mac, podNet.Subnet, nil
×
2058
                                }
×
2059

2060
                                if !ipv4OK {
×
2061
                                        skippedAddrs = append(skippedAddrs, ipv4)
×
2062
                                }
×
2063
                                if !ipv6OK {
×
2064
                                        skippedAddrs = append(skippedAddrs, ipv6)
×
2065
                                }
×
2066
                        }
2067
                }
2068

2069
                if !isStsPod {
×
2070
                        for _, net := range nsNets {
×
2071
                                for _, staticIP := range ipPool {
×
2072
                                        var checkIP string
×
2073
                                        ipProtocol := util.CheckProtocol(staticIP)
×
2074
                                        if ipProtocol == kubeovnv1.ProtocolDual {
×
2075
                                                checkIP = strings.Split(staticIP, ",")[0]
×
2076
                                        } else {
×
2077
                                                checkIP = staticIP
×
2078
                                        }
×
2079

2080
                                        if assignedPod, ok := c.ipam.IsIPAssignedToOtherPod(checkIP, net.Subnet.Name, key); ok {
×
2081
                                                klog.Errorf("static address %s for %s has been assigned to %s", staticIP, key, assignedPod)
×
2082
                                                continue
×
2083
                                        }
2084

2085
                                        v4IP, v6IP, mac, err = c.acquireStaticAddress(key, portName, staticIP, macPointer, net.Subnet.Name, net.AllowLiveMigration)
×
2086
                                        if err == nil {
×
2087
                                                return v4IP, v6IP, mac, net.Subnet, nil
×
2088
                                        }
×
2089
                                }
2090
                        }
2091
                        klog.Errorf("acquire address from ippool %s for %s failed, %v", ippoolStr, key, err)
×
2092
                } else {
×
2093
                        tempStrs := strings.Split(pod.Name, "-")
×
2094
                        numStr := tempStrs[len(tempStrs)-1]
×
2095
                        index, _ := strconv.Atoi(numStr)
×
2096

×
2097
                        if index < len(ipPool) {
×
2098
                                for _, net := range nsNets {
×
2099
                                        v4IP, v6IP, mac, err = c.acquireStaticAddress(key, portName, ipPool[index], macPointer, net.Subnet.Name, net.AllowLiveMigration)
×
2100
                                        if err == nil {
×
2101
                                                return v4IP, v6IP, mac, net.Subnet, nil
×
2102
                                        }
×
2103
                                }
2104
                                klog.Errorf("acquire address %s for %s failed, %v", ipPool[index], key, err)
×
2105
                        }
2106
                }
2107
        }
2108
        klog.Errorf("allocate address for %s failed, return NoAvailableAddress", key)
×
2109
        return "", "", "", podNet.Subnet, ipam.ErrNoAvailable
×
2110
}
2111

2112
func (c *Controller) acquireStaticAddress(key, nicName, ip string, mac *string, subnet string, liveMigration bool) (string, string, string, error) {
×
2113
        var v4IP, v6IP, macStr string
×
2114
        var err error
×
2115
        for ipStr := range strings.SplitSeq(ip, ",") {
×
2116
                if net.ParseIP(ipStr) == nil {
×
2117
                        return "", "", "", fmt.Errorf("failed to parse IP %s", ipStr)
×
2118
                }
×
2119
        }
2120

2121
        if v4IP, v6IP, macStr, err = c.ipam.GetStaticAddress(key, nicName, ip, mac, subnet, !liveMigration); err != nil {
×
2122
                klog.Errorf("failed to get static ip %v, mac %v, subnet %v, err %v", ip, mac, subnet, err)
×
2123
                return "", "", "", err
×
2124
        }
×
2125
        return v4IP, v6IP, macStr, nil
×
2126
}
2127

2128
func appendCheckPodToDel(c *Controller, pod *v1.Pod, ownerRefName, ownerRefKind string) (bool, error) {
×
2129
        // subnet for ns has been changed, and statefulset pod's ip is not in the range of subnet's cidr anymore
×
2130
        podNs, err := c.namespacesLister.Get(pod.Namespace)
×
2131
        if err != nil {
×
2132
                klog.Errorf("failed to get namespace %s, %v", pod.Namespace, err)
×
2133
                return false, err
×
2134
        }
×
2135

2136
        // check if subnet exist in OwnerReference
2137
        var ownerRefSubnetExist bool
×
2138
        var ownerRefSubnet string
×
2139
        switch ownerRefKind {
×
2140
        case util.StatefulSet:
×
2141
                ss, err := c.config.KubeClient.AppsV1().StatefulSets(pod.Namespace).Get(context.Background(), ownerRefName, metav1.GetOptions{})
×
2142
                if err != nil {
×
2143
                        if k8serrors.IsNotFound(err) {
×
2144
                                klog.Infof("Statefulset %s is not found", ownerRefName)
×
2145
                                return true, nil
×
2146
                        }
×
2147
                        klog.Errorf("failed to get StatefulSet %s, %v", ownerRefName, err)
×
2148
                }
2149
                if ss.Spec.Template.Annotations[util.LogicalSwitchAnnotation] != "" {
×
2150
                        ownerRefSubnetExist = true
×
2151
                        ownerRefSubnet = ss.Spec.Template.Annotations[util.LogicalSwitchAnnotation]
×
2152
                }
×
2153

2154
        case util.VMInstance:
×
2155
                vm, err := c.config.KubevirtClient.VirtualMachine(pod.Namespace).Get(context.Background(), ownerRefName, metav1.GetOptions{})
×
2156
                if err != nil {
×
2157
                        if k8serrors.IsNotFound(err) {
×
2158
                                klog.Infof("VirtualMachine %s is not found", ownerRefName)
×
2159
                                return true, nil
×
2160
                        }
×
2161
                        klog.Errorf("failed to get VirtualMachine %s, %v", ownerRefName, err)
×
2162
                }
2163
                if vm != nil &&
×
2164
                        vm.Spec.Template != nil &&
×
2165
                        vm.Spec.Template.ObjectMeta.Annotations != nil &&
×
2166
                        vm.Spec.Template.ObjectMeta.Annotations[util.LogicalSwitchAnnotation] != "" {
×
2167
                        ownerRefSubnetExist = true
×
2168
                        ownerRefSubnet = vm.Spec.Template.ObjectMeta.Annotations[util.LogicalSwitchAnnotation]
×
2169
                }
×
2170
        }
2171
        podSwitch := strings.TrimSpace(pod.Annotations[util.LogicalSwitchAnnotation])
×
2172
        if !ownerRefSubnetExist {
×
2173
                nsSubnetNames := podNs.Annotations[util.LogicalSwitchAnnotation]
×
2174
                // check if pod use the subnet of its ns
×
2175
                if nsSubnetNames != "" && podSwitch != "" && !slices.Contains(strings.Split(nsSubnetNames, ","), podSwitch) {
×
2176
                        klog.Infof("ns %s annotation subnet is %s, which is inconstant with subnet for pod %s, delete pod", pod.Namespace, nsSubnetNames, pod.Name)
×
2177
                        return true, nil
×
2178
                }
×
2179
        }
2180

2181
        // subnet cidr has been changed, and statefulset pod's ip is not in the range of subnet's cidr anymore
2182
        podSubnet, err := c.subnetsLister.Get(podSwitch)
×
2183
        if err != nil {
×
2184
                klog.Errorf("failed to get subnet %s, %v, not auto clean ip", podSwitch, err)
×
2185
                return false, err
×
2186
        }
×
2187
        if podSubnet == nil {
×
2188
                // TODO: remove: CRD get interface will retrun a nil subnet ?
×
2189
                klog.Errorf("pod %s/%s subnet %s is nil, not auto clean ip", pod.Namespace, pod.Name, podSwitch)
×
2190
                return false, nil
×
2191
        }
×
2192
        podIP := pod.Annotations[util.IPAddressAnnotation]
×
2193
        if podIP == "" {
×
2194
                // delete pod just after it created < 1ms
×
2195
                klog.Infof("pod %s/%s annotaions has no ip address, not auto clean ip", pod.Namespace, pod.Name)
×
2196
                return false, nil
×
2197
        }
×
2198
        podSubnetCidr := podSubnet.Spec.CIDRBlock
×
2199
        if podSubnetCidr == "" {
×
2200
                // subnet spec cidr changed by user
×
2201
                klog.Errorf("invalid pod subnet %s empty cidr %s, not auto clean ip", podSwitch, podSubnetCidr)
×
2202
                return false, nil
×
2203
        }
×
2204
        if !util.CIDRContainIP(podSubnetCidr, podIP) {
×
2205
                klog.Infof("pod's ip %s is not in the range of subnet %s, delete pod", pod.Annotations[util.IPAddressAnnotation], podSubnet.Name)
×
2206
                return true, nil
×
2207
        }
×
2208
        // subnet of ownerReference(sts/vm) has been changed, it needs to handle delete pod and create port on the new logical switch
2209
        if ownerRefSubnet != "" && podSubnet.Name != ownerRefSubnet {
×
2210
                klog.Infof("Subnet of owner %s has been changed from %s to %s, delete pod %s/%s", ownerRefName, podSubnet.Name, ownerRefSubnet, pod.Namespace, pod.Name)
×
2211
                return true, nil
×
2212
        }
×
2213

2214
        return false, nil
×
2215
}
2216

2217
func isVMPod(pod *v1.Pod) (bool, string) {
×
2218
        for _, owner := range pod.OwnerReferences {
×
2219
                // The name of vmi is consistent with vm's name.
×
2220
                if owner.Kind == util.VMInstance && strings.HasPrefix(owner.APIVersion, "kubevirt.io") {
×
2221
                        return true, owner.Name
×
2222
                }
×
2223
        }
2224
        return false, ""
×
2225
}
2226

2227
func isOwnsByTheVM(vmi metav1.Object) (bool, string) {
×
2228
        for _, owner := range vmi.GetOwnerReferences() {
×
2229
                if owner.Kind == util.VM && strings.HasPrefix(owner.APIVersion, "kubevirt.io") {
×
2230
                        return true, owner.Name
×
2231
                }
×
2232
        }
2233
        return false, ""
×
2234
}
2235

2236
func (c *Controller) isVMToDel(pod *v1.Pod, vmiName string) bool {
×
2237
        var (
×
2238
                vmiAlive bool
×
2239
                vmName   string
×
2240
        )
×
2241
        // The vmi is also deleted when pod is deleted, only left vm exists.
×
2242
        vmi, err := c.config.KubevirtClient.VirtualMachineInstance(pod.Namespace).Get(context.Background(), vmiName, metav1.GetOptions{})
×
2243
        if err != nil {
×
2244
                if k8serrors.IsNotFound(err) {
×
2245
                        vmiAlive = false
×
2246
                        // The name of vmi is consistent with vm's name.
×
2247
                        vmName = vmiName
×
2248
                        klog.ErrorS(err, "failed to get vmi, will try to get the vm directly", "name", vmiName)
×
2249
                } else {
×
2250
                        klog.ErrorS(err, "failed to get vmi", "name", vmiName)
×
2251
                        return false
×
2252
                }
×
2253
        } else {
×
2254
                var ownsByVM bool
×
2255
                ownsByVM, vmName = isOwnsByTheVM(vmi)
×
2256
                if !ownsByVM && !vmi.DeletionTimestamp.IsZero() {
×
2257
                        klog.Infof("ephemeral vmi %s is deleting", vmiName)
×
2258
                        return true
×
2259
                }
×
2260
                vmiAlive = vmi.DeletionTimestamp.IsZero()
×
2261
        }
2262

2263
        if vmiAlive {
×
2264
                return false
×
2265
        }
×
2266

2267
        vm, err := c.config.KubevirtClient.VirtualMachine(pod.Namespace).Get(context.Background(), vmName, metav1.GetOptions{})
×
2268
        if err != nil {
×
2269
                // the vm has gone
×
2270
                if k8serrors.IsNotFound(err) {
×
2271
                        klog.ErrorS(err, "failed to get vm", "name", vmName)
×
2272
                        return true
×
2273
                }
×
2274
                klog.ErrorS(err, "failed to get vm", "name", vmName)
×
2275
                return false
×
2276
        }
2277

2278
        if !vm.DeletionTimestamp.IsZero() {
×
2279
                klog.Infof("vm %s is deleting", vmName)
×
2280
                return true
×
2281
        }
×
2282
        return false
×
2283
}
2284

2285
func (c *Controller) getNameByPod(pod *v1.Pod) string {
×
2286
        if c.config.EnableKeepVMIP {
×
2287
                if isVMPod, vmName := isVMPod(pod); isVMPod {
×
2288
                        return vmName
×
2289
                }
×
2290
        }
2291
        return pod.Name
×
2292
}
2293

2294
// When subnet's v4availableIPs is 0 but still there's available ip in exclude-ips, the static ip in exclude-ips can be allocated normal.
2295
func (c *Controller) getNsAvailableSubnets(pod *v1.Pod, podNet *kubeovnNet) ([]*kubeovnNet, error) {
×
2296
        var result []*kubeovnNet
×
2297
        // keep the annotation subnet of the pod in first position
×
2298
        result = append(result, podNet)
×
2299

×
2300
        ns, err := c.namespacesLister.Get(pod.Namespace)
×
2301
        if err != nil {
×
2302
                klog.Errorf("failed to get namespace %s, %v", pod.Namespace, err)
×
2303
                return nil, err
×
2304
        }
×
2305
        if ns.Annotations == nil {
×
2306
                return nil, nil
×
2307
        }
×
2308

2309
        subnetNames := ns.Annotations[util.LogicalSwitchAnnotation]
×
2310
        for subnetName := range strings.SplitSeq(subnetNames, ",") {
×
2311
                if subnetName == "" || subnetName == podNet.Subnet.Name {
×
2312
                        continue
×
2313
                }
2314
                subnet, err := c.subnetsLister.Get(subnetName)
×
2315
                if err != nil {
×
2316
                        klog.Errorf("failed to get subnet %v", err)
×
2317
                        return nil, err
×
2318
                }
×
2319

2320
                result = append(result, &kubeovnNet{
×
2321
                        Type:         providerTypeOriginal,
×
2322
                        ProviderName: subnet.Spec.Provider,
×
2323
                        Subnet:       subnet,
×
2324
                })
×
2325
        }
2326

2327
        return result, nil
×
2328
}
2329

2330
func getPodType(pod *v1.Pod) string {
×
2331
        if ok, _, _ := isStatefulSetPod(pod); ok {
×
2332
                return util.StatefulSet
×
2333
        }
×
2334

2335
        if isVMPod, _ := isVMPod(pod); isVMPod {
×
2336
                return util.VM
×
2337
        }
×
2338
        return ""
×
2339
}
2340

2341
func (c *Controller) getVirtualIPs(pod *v1.Pod, podNets []*kubeovnNet) map[string]string {
×
2342
        vipsListMap := make(map[string][]string)
×
2343
        var vipNamesList []string
×
2344
        for vipName := range strings.SplitSeq(strings.TrimSpace(pod.Annotations[util.AAPsAnnotation]), ",") {
×
2345
                if vipName = strings.TrimSpace(vipName); vipName == "" {
×
2346
                        continue
×
2347
                }
2348
                if !slices.Contains(vipNamesList, vipName) {
×
2349
                        vipNamesList = append(vipNamesList, vipName)
×
2350
                } else {
×
2351
                        continue
×
2352
                }
2353
                vip, err := c.virtualIpsLister.Get(vipName)
×
2354
                if err != nil {
×
2355
                        klog.Errorf("failed to get vip %s, %v", vipName, err)
×
2356
                        continue
×
2357
                }
2358
                if vip.Spec.Namespace != pod.Namespace || (vip.Status.V4ip == "" && vip.Status.V6ip == "") {
×
2359
                        continue
×
2360
                }
2361
                for _, podNet := range podNets {
×
2362
                        if podNet.Subnet.Name == vip.Spec.Subnet {
×
2363
                                key := fmt.Sprintf("%s.%s", podNet.Subnet.Name, podNet.ProviderName)
×
2364
                                vipsList := vipsListMap[key]
×
2365
                                if vipsList == nil {
×
2366
                                        vipsList = []string{}
×
2367
                                }
×
2368
                                // ipam will ensure the uniqueness of VIP
2369
                                if util.IsValidIP(vip.Status.V4ip) {
×
2370
                                        vipsList = append(vipsList, vip.Status.V4ip)
×
2371
                                }
×
2372
                                if util.IsValidIP(vip.Status.V6ip) {
×
2373
                                        vipsList = append(vipsList, vip.Status.V6ip)
×
2374
                                }
×
2375

2376
                                vipsListMap[key] = vipsList
×
2377
                        }
2378
                }
2379
        }
2380

2381
        for _, podNet := range podNets {
×
2382
                vipStr := pod.Annotations[fmt.Sprintf(util.PortVipAnnotationTemplate, podNet.ProviderName)]
×
2383
                if vipStr == "" {
×
2384
                        continue
×
2385
                }
2386
                key := fmt.Sprintf("%s.%s", podNet.Subnet.Name, podNet.ProviderName)
×
2387
                vipsList := vipsListMap[key]
×
2388
                if vipsList == nil {
×
2389
                        vipsList = []string{}
×
2390
                }
×
2391

2392
                for vip := range strings.SplitSeq(vipStr, ",") {
×
2393
                        if util.IsValidIP(vip) && !slices.Contains(vipsList, vip) {
×
2394
                                vipsList = append(vipsList, vip)
×
2395
                        }
×
2396
                }
2397

2398
                vipsListMap[key] = vipsList
×
2399
        }
2400

2401
        vipsMap := make(map[string]string)
×
2402
        for key, vipsList := range vipsListMap {
×
2403
                vipsMap[key] = strings.Join(vipsList, ",")
×
2404
        }
×
2405
        return vipsMap
×
2406
}
2407

2408
func setPodRoutesAnnotation(annotations map[string]string, provider string, routes []request.Route) error {
×
2409
        key := fmt.Sprintf(util.RoutesAnnotationTemplate, provider)
×
2410
        if len(routes) == 0 {
×
2411
                delete(annotations, key)
×
2412
                return nil
×
2413
        }
×
2414

2415
        buf, err := json.Marshal(routes)
×
2416
        if err != nil {
×
2417
                err = fmt.Errorf("failed to marshal routes %+v: %w", routes, err)
×
2418
                klog.Error(err)
×
2419
                return err
×
2420
        }
×
2421
        annotations[key] = string(buf)
×
2422

×
2423
        return nil
×
2424
}
2425

2426
// Check if pod is a VPC NAT gateway using pod annotations
NEW
2427
func (c *Controller) checkIsPodVpcNatGw(pod *v1.Pod) (bool, string) {
×
NEW
2428
        if pod == nil {
×
NEW
2429
                return false, ""
×
NEW
2430
        }
×
NEW
2431
        if pod.Annotations == nil {
×
NEW
2432
                return false, ""
×
NEW
2433
        }
×
2434
        // default provider
NEW
2435
        providerName := util.OvnProvider
×
NEW
2436
        // In non-primary CNI mode, we get the providers from the pod annotations
×
NEW
2437
        // We get the vpc nat gw name using the provider name
×
NEW
2438
        if c.config.EnableNonPrimaryCNI {
×
NEW
2439
                // get providers
×
NEW
2440
                providers, err := c.getPodProviders(pod)
×
NEW
2441
                if err != nil {
×
NEW
2442
                        klog.Errorf("failed to get pod %s/%s providers, %v", pod.Namespace, pod.Name, err)
×
NEW
2443
                        return false, ""
×
NEW
2444
                }
×
NEW
2445
                if len(providers) > 0 {
×
NEW
2446
                        // use the first provider
×
NEW
2447
                        providerName = providers[0]
×
NEW
2448
                }
×
2449
        }
NEW
2450
        vpcGwName, isVpcNatGw := pod.Annotations[fmt.Sprintf(util.VpcNatGatewayAnnotationTemplate, providerName)]
×
NEW
2451
        if isVpcNatGw {
×
NEW
2452
                if vpcGwName == "" {
×
NEW
2453
                        klog.Errorf("pod %s is vpc nat gateway but name is empty", pod.Name)
×
NEW
2454
                        return false, ""
×
NEW
2455
                }
×
NEW
2456
                klog.Infof("pod %s is vpc nat gateway %s", pod.Name, vpcGwName)
×
2457
        }
NEW
2458
        return isVpcNatGw, vpcGwName
×
2459
}
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