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

kubeovn / kube-ovn / 20331782627

18 Dec 2025 09:10AM UTC coverage: 22.603% (-0.06%) from 22.661%
20331782627

push

github

web-flow
Add tests for VIP finalizer handling and subnet status updates (#6068)

* Add tests for VIP finalizer handling and subnet status updates

- Introduced a new test to verify that the subnet status is correctly updated when a VIP is created and deleted, ensuring that finalizers are properly handled.
- Added checks for both IPv4 and IPv6 protocols, including dual stack scenarios, to confirm that available and using IP counts and ranges are updated as expected.
- Enhanced the existing VIP creation test to wait for the finalizer to be added before proceeding with subnet status verification.
- Updated sleep durations to ensure sufficient time for status updates after VIP operations.

Signed-off-by: zbb88888 <jmdxjsjgcxy@gmail.com>

* fix after review

Signed-off-by: zbb88888 <jmdxjsjgcxy@gmail.com>

---------

Signed-off-by: zbb88888 <jmdxjsjgcxy@gmail.com>

0 of 312 new or added lines in 10 files covered. (0.0%)

21 existing lines in 6 files now uncovered.

12052 of 53320 relevant lines covered (22.6%)

0.26 hits per line

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

5.66
/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
                c.updateCnpsByLabelsMatch(podNs.Labels, p.Labels)
×
278
        }
×
279

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

443
func (c *Controller) getPodKubeovnNets(pod *v1.Pod) ([]*kubeovnNet, error) {
1✔
444
        attachmentNets, err := c.getPodAttachmentNet(pod)
1✔
445
        if err != nil {
1✔
446
                klog.Error(err)
×
447
                return nil, err
×
448
        }
×
449

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

457
        defaultSubnet, err := c.getPodDefaultSubnet(pod)
1✔
458
        if err != nil {
1✔
459
                klog.Error(err)
×
460
                return nil, err
×
461
        }
×
462

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

469
        if _, hasOtherDefaultNet := pod.Annotations[util.DefaultNetworkAnnotation]; !hasOtherDefaultNet {
2✔
470
                podNets = append(attachmentNets, &kubeovnNet{
1✔
471
                        Type:         providerTypeOriginal,
1✔
472
                        ProviderName: util.OvnProvider,
1✔
473
                        Subnet:       defaultSubnet,
1✔
474
                        IsDefault:    true,
1✔
475
                })
1✔
476
        }
1✔
477

478
        return podNets, nil
1✔
479
}
480

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

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

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

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

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

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

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

547
        // check if route subnet is need.
548
        return c.reconcileRouteSubnets(pod, needRouteSubnets(pod, podNets))
×
549
}
550

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

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

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

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

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

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

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

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

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

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

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

670
                        if isVMPod {
×
671
                                if _, ok := pod.Labels["kubevirt.io/migrationJobUID"]; ok {
×
672
                                        if sourceNode, ok := pod.Labels["kubevirt.io/nodeName"]; ok && sourceNode != pod.Spec.NodeName {
×
673
                                                klog.Infof("VM pod %s/%s is migrating from %s to %s",
×
674
                                                        pod.Namespace, pod.Name, sourceNode, pod.Spec.NodeName)
×
675
                                                if err := c.OVNNbClient.SetLogicalSwitchPortMigrateOptions(portName, sourceNode, pod.Spec.NodeName); err != nil {
×
676
                                                        klog.Errorf("failed to set migrate options for VM pod lsp %s: %v", portName, err)
×
677
                                                        return nil, err
×
678
                                                }
×
679
                                        }
680
                                }
681
                        }
682

683
                        if securityGroupAnnotation != "" || oldSgList != nil {
×
684
                                securityGroups := strings.ReplaceAll(securityGroupAnnotation, " ", "")
×
685
                                newSgList := strings.Split(securityGroups, ",")
×
686
                                sgNames := util.UnionStringSlice(oldSgList, newSgList)
×
687
                                for _, sgName := range sgNames {
×
688
                                        if sgName != "" {
×
689
                                                c.syncSgPortsQueue.Add(sgName)
×
690
                                        }
×
691
                                }
692
                        }
693

694
                        if vips != "" {
×
695
                                c.syncVirtualPortsQueue.Add(podNet.Subnet.Name)
×
696
                        }
×
697
                }
698
                // CreatePort may fail, so put ip CR creation after CreatePort
699
                ipCRName := ovs.PodNameToPortName(podName, pod.Namespace, podNet.ProviderName)
×
700
                if err := c.createOrUpdateIPCR(ipCRName, podName, ipStr, mac, subnet.Name, pod.Namespace, pod.Spec.NodeName, podType); err != nil {
×
701
                        err = fmt.Errorf("failed to create ips CR %s.%s: %w", podName, pod.Namespace, err)
×
702
                        klog.Error(err)
×
703
                        return nil, err
×
704
                }
×
705
        }
706
        if err = util.PatchAnnotations(c.config.KubeClient.CoreV1().Pods(namespace), name, patch); err != nil {
×
707
                if k8serrors.IsNotFound(err) {
×
708
                        // Sometimes pod is deleted between kube-ovn configure ovn-nb and patch pod.
×
709
                        // Then we need to recycle the resource again.
×
710
                        key := strings.Join([]string{namespace, name}, "/")
×
711
                        c.deletingPodObjMap.Store(key, pod)
×
712
                        c.deletePodQueue.AddRateLimited(key)
×
713
                        return nil, nil
×
714
                }
×
715
                klog.Errorf("failed to patch pod %s/%s: %v", namespace, name, err)
×
716
                return nil, err
×
717
        }
718

719
        if pod, err = c.config.KubeClient.CoreV1().Pods(namespace).Get(context.TODO(), name, metav1.GetOptions{}); err != nil {
×
720
                if k8serrors.IsNotFound(err) {
×
721
                        key := strings.Join([]string{namespace, name}, "/")
×
722
                        c.deletingPodObjMap.Store(key, pod)
×
723
                        c.deletePodQueue.AddRateLimited(key)
×
724
                        return nil, nil
×
725
                }
×
726
                klog.Errorf("failed to get pod %s/%s: %v", namespace, name, err)
×
727
                return nil, err
×
728
        }
729

730
        // Check if pod is a vpc nat gateway. Annotation set will have subnet provider name as prefix
731
        isVpcNatGw, vpcGwName := c.checkIsPodVpcNatGw(pod)
×
732
        if isVpcNatGw {
×
733
                klog.Infof("init vpc nat gateway pod %s/%s with name %s", namespace, name, vpcGwName)
×
734
                c.initVpcNatGatewayQueue.Add(vpcGwName)
×
735
        }
×
736

737
        return pod, nil
×
738
}
739

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

747
        if len(needRoutePodNets) == 0 {
×
748
                return nil
×
749
        }
×
750

751
        namespace := pod.Namespace
×
752
        name := pod.Name
×
753
        podName := c.getNameByPod(pod)
×
754

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

×
757
        node, err := c.nodesLister.Get(pod.Spec.NodeName)
×
758
        if err != nil {
×
759
                klog.Errorf("failed to get node %s: %v", pod.Spec.NodeName, err)
×
760
                return err
×
761
        }
×
762

763
        portGroups, err := c.OVNNbClient.ListPortGroups(map[string]string{"node": "", networkPolicyKey: ""})
×
764
        if err != nil {
×
765
                klog.Errorf("failed to list port groups: %v", err)
×
766
                return err
×
767
        }
×
768

769
        var nodePortGroups []string
×
770
        nodePortGroup := strings.ReplaceAll(node.Annotations[util.PortNameAnnotation], "-", ".")
×
771
        for _, pg := range portGroups {
×
772
                if pg.Name != nodePortGroup && pg.ExternalIDs["subnet"] == "" {
×
773
                        nodePortGroups = append(nodePortGroups, pg.Name)
×
774
                }
×
775
        }
776

777
        var podIP string
×
778
        var subnet *kubeovnv1.Subnet
×
779
        patch := util.KVPatch{}
×
780
        for _, podNet := range needRoutePodNets {
×
781
                // in case update handler overlap the annotation when cache is not in sync
×
782
                if pod.Annotations[fmt.Sprintf(util.AllocatedAnnotationTemplate, podNet.ProviderName)] == "" {
×
783
                        return fmt.Errorf("no address has been allocated to %s/%s", namespace, name)
×
784
                }
×
785

786
                podIP = pod.Annotations[fmt.Sprintf(util.IPAddressAnnotationTemplate, podNet.ProviderName)]
×
787
                subnet = podNet.Subnet
×
788

×
789
                // Check if pod uses nodeSwitch subnet
×
790
                if subnet.Name == c.config.NodeSwitch {
×
791
                        return fmt.Errorf("NodeSwitch subnet %s is unavailable for pod", subnet.Name)
×
792
                }
×
793

794
                if portGroups, err = c.OVNNbClient.ListPortGroups(map[string]string{"subnet": subnet.Name, "node": "", networkPolicyKey: ""}); err != nil {
×
795
                        klog.Errorf("failed to list port groups: %v", err)
×
796
                        return err
×
797
                }
×
798

799
                pgName := getOverlaySubnetsPortGroupName(subnet.Name, pod.Spec.NodeName)
×
800
                portName := ovs.PodNameToPortName(podName, pod.Namespace, podNet.ProviderName)
×
801
                subnetPortGroups := make([]string, 0, len(portGroups))
×
802
                for _, pg := range portGroups {
×
803
                        if pg.Name != pgName {
×
804
                                subnetPortGroups = append(subnetPortGroups, pg.Name)
×
805
                        }
×
806
                }
807

808
                if (!c.config.EnableLb || (subnet.Spec.EnableLb == nil || !*subnet.Spec.EnableLb)) &&
×
809
                        subnet.Spec.Vpc == c.config.ClusterRouter &&
×
810
                        subnet.Spec.U2OInterconnection &&
×
811
                        subnet.Spec.Vlan != "" &&
×
812
                        !subnet.Spec.LogicalGateway {
×
813
                        // remove lsp from other port groups
×
814
                        // we need to do this because the pod, e.g. a sts/vm, can be rescheduled to another node
×
815
                        if err = c.OVNNbClient.RemovePortFromPortGroups(portName, subnetPortGroups...); err != nil {
×
816
                                klog.Errorf("failed to remove port %s from port groups %v: %v", portName, subnetPortGroups, err)
×
817
                                return err
×
818
                        }
×
819
                        // add lsp to the port group
820
                        if err := c.OVNNbClient.PortGroupAddPorts(pgName, portName); err != nil {
×
821
                                klog.Errorf("failed to add port to u2o port group %s: %v", pgName, err)
×
822
                                return err
×
823
                        }
×
824
                }
825

826
                if podIP != "" && (subnet.Spec.Vlan == "" || subnet.Spec.LogicalGateway) && subnet.Spec.Vpc == c.config.ClusterRouter {
×
827
                        node, err := c.nodesLister.Get(pod.Spec.NodeName)
×
828
                        if err != nil {
×
829
                                klog.Errorf("failed to get node %s: %v", pod.Spec.NodeName, err)
×
830
                                return err
×
831
                        }
×
832

833
                        // remove lsp from other port groups
834
                        // we need to do this because the pod, e.g. a sts/vm, can be rescheduled to another node
835
                        if err = c.OVNNbClient.RemovePortFromPortGroups(portName, nodePortGroups...); err != nil {
×
836
                                klog.Errorf("failed to remove port %s from port groups %v: %v", portName, nodePortGroups, err)
×
837
                                return err
×
838
                        }
×
839
                        // add lsp to the port group
840
                        if err = c.OVNNbClient.PortGroupAddPorts(nodePortGroup, portName); err != nil {
×
841
                                klog.Errorf("failed to add port %s to port group %s: %v", portName, nodePortGroup, err)
×
842
                                return err
×
843
                        }
×
844

845
                        if c.config.EnableEipSnat && (pod.Annotations[util.EipAnnotation] != "" || pod.Annotations[util.SnatAnnotation] != "") {
×
846
                                cm, err := c.configMapsLister.ConfigMaps(c.config.ExternalGatewayConfigNS).Get(util.ExternalGatewayConfig)
×
847
                                if err != nil {
×
848
                                        klog.Errorf("failed to get ex-gateway config, %v", err)
×
849
                                        return err
×
850
                                }
×
851
                                nextHop := cm.Data["external-gw-addr"]
×
852
                                if nextHop == "" {
×
853
                                        externalSubnet, err := c.subnetsLister.Get(c.config.ExternalGatewaySwitch)
×
854
                                        if err != nil {
×
855
                                                klog.Errorf("failed to get subnet %s, %v", c.config.ExternalGatewaySwitch, err)
×
856
                                                return err
×
857
                                        }
×
858
                                        nextHop = externalSubnet.Spec.Gateway
×
859
                                        if nextHop == "" {
×
860
                                                klog.Errorf("no available gateway address")
×
861
                                                return errors.New("no available gateway address")
×
862
                                        }
×
863
                                }
864
                                if strings.Contains(nextHop, "/") {
×
865
                                        nextHop = strings.Split(nextHop, "/")[0]
×
866
                                }
×
867

868
                                if err := c.addPolicyRouteToVpc(
×
869
                                        subnet.Spec.Vpc,
×
870
                                        &kubeovnv1.PolicyRoute{
×
871
                                                Priority:  util.NorthGatewayRoutePolicyPriority,
×
872
                                                Match:     "ip4.src == " + podIP,
×
873
                                                Action:    kubeovnv1.PolicyRouteActionReroute,
×
874
                                                NextHopIP: nextHop,
×
875
                                        },
×
876
                                        map[string]string{
×
877
                                                "vendor": util.CniTypeName,
×
878
                                                "subnet": subnet.Name,
×
879
                                        },
×
880
                                ); err != nil {
×
881
                                        klog.Errorf("failed to add policy route, %v", err)
×
882
                                        return err
×
883
                                }
×
884

885
                                // remove lsp from port group to make EIP/SNAT work
886
                                if err = c.OVNNbClient.PortGroupRemovePorts(pgName, portName); err != nil {
×
887
                                        klog.Error(err)
×
888
                                        return err
×
889
                                }
×
890
                        } else {
×
891
                                if subnet.Spec.GatewayType == kubeovnv1.GWDistributedType && pod.Annotations[util.NorthGatewayAnnotation] == "" {
×
892
                                        nodeTunlIPAddr, err := getNodeTunlIP(node)
×
893
                                        if err != nil {
×
894
                                                klog.Error(err)
×
895
                                                return err
×
896
                                        }
×
897

898
                                        var added bool
×
899
                                        for _, nodeAddr := range nodeTunlIPAddr {
×
900
                                                for podAddr := range strings.SplitSeq(podIP, ",") {
×
901
                                                        if util.CheckProtocol(nodeAddr.String()) != util.CheckProtocol(podAddr) {
×
902
                                                                continue
×
903
                                                        }
904

905
                                                        // remove lsp from other port groups
906
                                                        // we need to do this because the pod, e.g. a sts/vm, can be rescheduled to another node
907
                                                        if err = c.OVNNbClient.RemovePortFromPortGroups(portName, subnetPortGroups...); err != nil {
×
908
                                                                klog.Errorf("failed to remove port %s from port groups %v: %v", portName, subnetPortGroups, err)
×
909
                                                                return err
×
910
                                                        }
×
911
                                                        if err := c.OVNNbClient.PortGroupAddPorts(pgName, portName); err != nil {
×
912
                                                                klog.Errorf("failed to add port %s to port group %s: %v", portName, pgName, err)
×
913
                                                                return err
×
914
                                                        }
×
915

916
                                                        added = true
×
917
                                                        break
×
918
                                                }
919
                                                if added {
×
920
                                                        break
×
921
                                                }
922
                                        }
923
                                }
924

925
                                if pod.Annotations[util.NorthGatewayAnnotation] != "" && pod.Annotations[util.IPAddressAnnotation] != "" {
×
926
                                        for podAddr := range strings.SplitSeq(pod.Annotations[util.IPAddressAnnotation], ",") {
×
927
                                                if util.CheckProtocol(podAddr) != util.CheckProtocol(pod.Annotations[util.NorthGatewayAnnotation]) {
×
928
                                                        continue
×
929
                                                }
930
                                                ipSuffix := "ip4"
×
931
                                                if util.CheckProtocol(podAddr) == kubeovnv1.ProtocolIPv6 {
×
932
                                                        ipSuffix = "ip6"
×
933
                                                }
×
934

935
                                                if err := c.addPolicyRouteToVpc(
×
936
                                                        subnet.Spec.Vpc,
×
937
                                                        &kubeovnv1.PolicyRoute{
×
938
                                                                Priority:  util.NorthGatewayRoutePolicyPriority,
×
939
                                                                Match:     fmt.Sprintf("%s.src == %s", ipSuffix, podAddr),
×
940
                                                                Action:    kubeovnv1.PolicyRouteActionReroute,
×
941
                                                                NextHopIP: pod.Annotations[util.NorthGatewayAnnotation],
×
942
                                                        },
×
943
                                                        map[string]string{
×
944
                                                                "vendor": util.CniTypeName,
×
945
                                                                "subnet": subnet.Name,
×
946
                                                        },
×
947
                                                ); err != nil {
×
948
                                                        klog.Errorf("failed to add policy route, %v", err)
×
949
                                                        return err
×
950
                                                }
×
951
                                        }
952
                                } else if c.config.EnableEipSnat {
×
953
                                        if err = c.deleteStaticRouteFromVpc(
×
954
                                                c.config.ClusterRouter,
×
955
                                                subnet.Spec.RouteTable,
×
956
                                                podIP,
×
957
                                                "",
×
958
                                                kubeovnv1.PolicyDst,
×
959
                                        ); err != nil {
×
960
                                                klog.Error(err)
×
961
                                                return err
×
962
                                        }
×
963
                                }
964
                        }
965

966
                        if c.config.EnableEipSnat {
×
967
                                for ipStr := range strings.SplitSeq(podIP, ",") {
×
968
                                        if eip := pod.Annotations[util.EipAnnotation]; eip == "" {
×
969
                                                if err = c.OVNNbClient.DeleteNats(c.config.ClusterRouter, ovnnb.NATTypeDNATAndSNAT, ipStr); err != nil {
×
970
                                                        klog.Errorf("failed to delete nat rules: %v", err)
×
971
                                                }
×
972
                                        } else if util.CheckProtocol(eip) == util.CheckProtocol(ipStr) {
×
973
                                                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 {
×
974
                                                        klog.Errorf("failed to add nat rules, %v", err)
×
975
                                                        return err
×
976
                                                }
×
977
                                        }
978
                                        if eip := pod.Annotations[util.SnatAnnotation]; eip == "" {
×
979
                                                if err = c.OVNNbClient.DeleteNats(c.config.ClusterRouter, ovnnb.NATTypeSNAT, ipStr); err != nil {
×
980
                                                        klog.Errorf("failed to delete nat rules: %v", err)
×
981
                                                }
×
982
                                        } else if util.CheckProtocol(eip) == util.CheckProtocol(ipStr) {
×
983
                                                if err = c.OVNNbClient.UpdateSnat(c.config.ClusterRouter, eip, ipStr); err != nil {
×
984
                                                        klog.Errorf("failed to add nat rules, %v", err)
×
985
                                                        return err
×
986
                                                }
×
987
                                        }
988
                                }
989
                        }
990
                }
991

992
                if pod.Annotations[fmt.Sprintf(util.ActivationStrategyTemplate, podNet.ProviderName)] != "" {
×
993
                        if err := c.OVNNbClient.SetLogicalSwitchPortActivationStrategy(portName, pod.Spec.NodeName); err != nil {
×
994
                                klog.Errorf("failed to set activation strategy for lsp %s: %v", portName, err)
×
995
                                return err
×
996
                        }
×
997
                }
998

999
                patch[fmt.Sprintf(util.RoutedAnnotationTemplate, podNet.ProviderName)] = "true"
×
1000
        }
1001
        if err := util.PatchAnnotations(c.config.KubeClient.CoreV1().Pods(namespace), name, patch); err != nil {
×
1002
                if k8serrors.IsNotFound(err) {
×
1003
                        // Sometimes pod is deleted between kube-ovn configure ovn-nb and patch pod.
×
1004
                        // Then we need to recycle the resource again.
×
1005
                        key := strings.Join([]string{namespace, name}, "/")
×
1006
                        c.deletingPodObjMap.Store(key, pod)
×
1007
                        c.deletePodQueue.AddRateLimited(key)
×
1008
                        return nil
×
1009
                }
×
1010
                klog.Errorf("failed to patch pod %s/%s: %v", namespace, name, err)
×
1011
                return err
×
1012
        }
1013
        return nil
×
1014
}
1015

1016
func (c *Controller) handleDeletePod(key string) (err error) {
×
1017
        pod, ok := c.deletingPodObjMap.Load(key)
×
1018
        if !ok {
×
1019
                return nil
×
1020
        }
×
1021
        now := time.Now()
×
1022
        klog.Infof("handle delete pod %s", key)
×
1023
        podName := c.getNameByPod(pod)
×
1024
        c.podKeyMutex.LockKey(key)
×
1025
        defer func() {
×
1026
                _ = c.podKeyMutex.UnlockKey(key)
×
1027
                if err == nil {
×
1028
                        c.deletingPodObjMap.Delete(key)
×
1029
                }
×
1030
                last := time.Since(now)
×
1031
                klog.Infof("take %d ms to handle delete pod %s", last.Milliseconds(), key)
×
1032
        }()
1033

1034
        p, _ := c.podsLister.Pods(pod.Namespace).Get(pod.Name)
×
1035
        if p != nil && p.UID != pod.UID {
×
1036
                // Pod with same name exists, just return here
×
1037
                return nil
×
1038
        }
×
1039

1040
        if aaps := pod.Annotations[util.AAPsAnnotation]; aaps != "" {
×
1041
                for vipName := range strings.SplitSeq(aaps, ",") {
×
1042
                        if vip, err := c.virtualIpsLister.Get(vipName); err == nil {
×
1043
                                if vip.Spec.Namespace != pod.Namespace {
×
1044
                                        continue
×
1045
                                }
1046
                                klog.Infof("enqueue update virtual parents for %s", vipName)
×
1047
                                c.updateVirtualParentsQueue.Add(vipName)
×
1048
                        }
1049
                }
1050
        }
1051

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

×
1054
        var keepIPCR bool
×
1055
        if ok, stsName, stsUID := isStatefulSetPod(pod); ok {
×
1056
                if !pod.DeletionTimestamp.IsZero() {
×
1057
                        klog.Infof("handle deletion of sts pod %s", podKey)
×
1058
                        toDel := isStatefulSetPodToDel(c.config.KubeClient, pod, stsName, stsUID)
×
1059
                        if !toDel {
×
1060
                                klog.Infof("try keep ip for sts pod %s", podKey)
×
1061
                                keepIPCR = true
×
1062
                        }
×
1063
                }
1064
                if keepIPCR {
×
1065
                        isDelete, err := appendCheckPodNonMultusNetToDel(c, pod, stsName, util.StatefulSet)
×
1066
                        if err != nil {
×
1067
                                klog.Error(err)
×
1068
                                return err
×
1069
                        }
×
1070
                        if isDelete {
×
1071
                                klog.Infof("not keep ip for sts pod %s", podKey)
×
1072
                                keepIPCR = false
×
1073
                        }
×
1074
                }
1075
        }
1076
        isVMPod, vmName := isVMPod(pod)
×
1077
        if isVMPod && c.config.EnableKeepVMIP {
×
1078
                ports, err := c.OVNNbClient.ListNormalLogicalSwitchPorts(true, map[string]string{"pod": podKey})
×
1079
                if err != nil {
×
1080
                        klog.Errorf("failed to list lsps of pod %s: %v", podKey, err)
×
1081
                        return err
×
1082
                }
×
1083
                for _, port := range ports {
×
1084
                        if err := c.OVNNbClient.CleanLogicalSwitchPortMigrateOptions(port.Name); err != nil {
×
1085
                                err = fmt.Errorf("failed to clean migrate options for vm lsp %s, %w", port.Name, err)
×
1086
                                klog.Error(err)
×
1087
                                return err
×
1088
                        }
×
1089
                }
1090
                if pod.DeletionTimestamp != nil {
×
1091
                        klog.Infof("handle deletion of vm pod %s", podKey)
×
1092
                        vmToBeDel := c.isVMToDel(pod, vmName)
×
1093
                        if !vmToBeDel {
×
1094
                                klog.Infof("try keep ip for vm pod %s", podKey)
×
1095
                                keepIPCR = true
×
1096
                        }
×
1097
                }
1098
                if keepIPCR {
×
1099
                        isDelete, err := appendCheckPodNonMultusNetToDel(c, pod, vmName, util.VMInstance)
×
1100
                        if err != nil {
×
1101
                                klog.Error(err)
×
1102
                                return err
×
1103
                        }
×
1104
                        if isDelete {
×
1105
                                klog.Infof("not keep ip for vm pod %s", podKey)
×
1106
                                keepIPCR = false
×
1107
                        }
×
1108
                }
1109
        }
1110

1111
        podNets, err := c.getPodKubeovnNets(pod)
×
1112
        if err != nil {
×
1113
                klog.Errorf("failed to get kube-ovn nets of pod %s: %v", podKey, err)
×
1114
        }
×
1115
        ports, err := c.OVNNbClient.ListNormalLogicalSwitchPorts(true, map[string]string{"pod": podKey})
×
1116
        if err != nil {
×
1117
                klog.Errorf("failed to list lsps of pod %s: %v", podKey, err)
×
1118
                return err
×
1119
        }
×
1120
        if keepIPCR {
×
1121
                // always remove lsp from port groups
×
1122
                for _, port := range ports {
×
1123
                        klog.Infof("remove lsp %s from all port groups", port.Name)
×
1124
                        if err = c.OVNNbClient.RemovePortFromPortGroups(port.Name); err != nil {
×
1125
                                klog.Errorf("failed to remove lsp %s from all port groups: %v", port.Name, err)
×
1126
                                return err
×
1127
                        }
×
1128
                }
1129
        } else {
×
1130
                if len(ports) != 0 {
×
1131
                        addresses := c.ipam.GetPodAddress(podKey)
×
1132
                        for _, address := range addresses {
×
1133
                                if strings.TrimSpace(address.IP) == "" {
×
1134
                                        continue
×
1135
                                }
1136
                                subnet, err := c.subnetsLister.Get(address.Subnet.Name)
×
1137
                                if k8serrors.IsNotFound(err) {
×
1138
                                        continue
×
1139
                                } else if err != nil {
×
1140
                                        klog.Error(err)
×
1141
                                        return err
×
1142
                                }
×
1143
                                vpc, err := c.vpcsLister.Get(subnet.Spec.Vpc)
×
1144
                                if k8serrors.IsNotFound(err) {
×
1145
                                        continue
×
1146
                                } else if err != nil {
×
1147
                                        klog.Error(err)
×
1148
                                        return err
×
1149
                                }
×
1150

1151
                                ipSuffix := "ip4"
×
1152
                                if util.CheckProtocol(address.IP) == kubeovnv1.ProtocolIPv6 {
×
1153
                                        ipSuffix = "ip6"
×
1154
                                }
×
1155
                                if err = c.deletePolicyRouteFromVpc(
×
1156
                                        vpc.Name,
×
1157
                                        util.NorthGatewayRoutePolicyPriority,
×
1158
                                        fmt.Sprintf("%s.src == %s", ipSuffix, address.IP),
×
1159
                                ); err != nil {
×
1160
                                        klog.Errorf("failed to delete static route, %v", err)
×
1161
                                        return err
×
1162
                                }
×
1163

1164
                                if c.config.EnableEipSnat {
×
1165
                                        if pod.Annotations[util.EipAnnotation] != "" {
×
1166
                                                if err = c.OVNNbClient.DeleteNat(c.config.ClusterRouter, ovnnb.NATTypeDNATAndSNAT, pod.Annotations[util.EipAnnotation], address.IP); err != nil {
×
1167
                                                        klog.Errorf("failed to delete nat rules: %v", err)
×
1168
                                                }
×
1169
                                        }
1170
                                        if pod.Annotations[util.SnatAnnotation] != "" {
×
1171
                                                if err = c.OVNNbClient.DeleteNat(c.config.ClusterRouter, ovnnb.NATTypeSNAT, "", address.IP); err != nil {
×
1172
                                                        klog.Errorf("failed to delete nat rules: %v", err)
×
1173
                                                }
×
1174
                                        }
1175
                                }
1176
                        }
1177
                }
1178
                for _, port := range ports {
×
1179
                        // when lsp is deleted, the port of pod is deleted from any port-group automatically.
×
1180
                        klog.Infof("delete logical switch port %s", port.Name)
×
1181
                        if err := c.OVNNbClient.DeleteLogicalSwitchPort(port.Name); err != nil {
×
1182
                                klog.Errorf("failed to delete lsp %s, %v", port.Name, err)
×
1183
                                return err
×
1184
                        }
×
1185
                }
1186
                klog.Infof("try release all ip address for deleting pod %s", podKey)
×
1187
                for _, podNet := range podNets {
×
1188
                        portName := ovs.PodNameToPortName(podName, pod.Namespace, podNet.ProviderName)
×
1189
                        ipCR, err := c.ipsLister.Get(portName)
×
1190
                        if err != nil {
×
1191
                                if k8serrors.IsNotFound(err) {
×
1192
                                        continue
×
1193
                                }
1194
                                klog.Errorf("failed to get ip %s, %v", portName, err)
×
1195
                                return err
×
1196
                        }
1197
                        if ipCR.Labels[util.IPReservedLabel] != "true" {
×
1198
                                klog.Infof("delete ip CR %s", ipCR.Name)
×
1199
                                if err := c.config.KubeOvnClient.KubeovnV1().IPs().Delete(context.Background(), ipCR.Name, metav1.DeleteOptions{}); err != nil {
×
1200
                                        if !k8serrors.IsNotFound(err) {
×
1201
                                                klog.Errorf("failed to delete ip %s, %v", ipCR.Name, err)
×
1202
                                                return err
×
1203
                                        }
×
1204
                                }
1205
                                // release ipam address after delete ip CR
1206
                                c.ipam.ReleaseAddressByNic(podKey, portName, podNet.Subnet.Name)
×
NEW
1207
                                // Trigger subnet status update after IPAM release
×
NEW
1208
                                // This is needed when IP CR is deleted without finalizer (race condition)
×
NEW
1209
                                c.updateSubnetStatusQueue.Add(podNet.Subnet.Name)
×
1210
                        }
1211
                }
1212
                if pod.Annotations[util.VipAnnotation] != "" {
×
1213
                        if err = c.releaseVip(pod.Annotations[util.VipAnnotation]); err != nil {
×
1214
                                klog.Errorf("failed to clean label from vip %s, %v", pod.Annotations[util.VipAnnotation], err)
×
1215
                                return err
×
1216
                        }
×
1217
                }
1218
        }
1219
        for _, podNet := range podNets {
×
1220
                // Skip non-OVN subnets for security group synchronization
×
1221
                if !isOvnSubnet(podNet.Subnet) {
×
1222
                        continue
×
1223
                }
1224

1225
                c.syncVirtualPortsQueue.Add(podNet.Subnet.Name)
×
1226
                securityGroupAnnotation := pod.Annotations[fmt.Sprintf(util.SecurityGroupAnnotationTemplate, podNet.ProviderName)]
×
1227
                if securityGroupAnnotation != "" {
×
1228
                        securityGroups := strings.ReplaceAll(securityGroupAnnotation, " ", "")
×
1229
                        for sgName := range strings.SplitSeq(securityGroups, ",") {
×
1230
                                if sgName != "" {
×
1231
                                        c.syncSgPortsQueue.Add(sgName)
×
1232
                                }
×
1233
                        }
1234
                }
1235
        }
1236
        return nil
×
1237
}
1238

1239
func (c *Controller) handleUpdatePodSecurity(key string) error {
×
1240
        now := time.Now()
×
1241
        klog.Infof("handle add/update pod security group %s", key)
×
1242

×
1243
        namespace, name, err := cache.SplitMetaNamespaceKey(key)
×
1244
        if err != nil {
×
1245
                utilruntime.HandleError(fmt.Errorf("invalid resource key: %s", key))
×
1246
                return nil
×
1247
        }
×
1248

1249
        c.podKeyMutex.LockKey(key)
×
1250
        defer func() {
×
1251
                _ = c.podKeyMutex.UnlockKey(key)
×
1252
                last := time.Since(now)
×
1253
                klog.Infof("take %d ms to handle sg for pod %s", last.Milliseconds(), key)
×
1254
        }()
×
1255

1256
        pod, err := c.podsLister.Pods(namespace).Get(name)
×
1257
        if err != nil {
×
1258
                if k8serrors.IsNotFound(err) {
×
1259
                        return nil
×
1260
                }
×
1261
                klog.Error(err)
×
1262
                return err
×
1263
        }
1264
        podName := c.getNameByPod(pod)
×
1265

×
1266
        podNets, err := c.getPodKubeovnNets(pod)
×
1267
        if err != nil {
×
1268
                klog.Errorf("failed to pod nets %v", err)
×
1269
                return err
×
1270
        }
×
1271

1272
        vipsMap := c.getVirtualIPs(pod, podNets)
×
1273

×
1274
        // associated with security group
×
1275
        for _, podNet := range podNets {
×
1276
                // Skip non-OVN subnets (e.g., macvlan) that don't create OVN logical switch ports
×
1277
                if !isOvnSubnet(podNet.Subnet) {
×
1278
                        continue
×
1279
                }
1280

1281
                portSecurity := false
×
1282
                if pod.Annotations[fmt.Sprintf(util.PortSecurityAnnotationTemplate, podNet.ProviderName)] == "true" {
×
1283
                        portSecurity = true
×
1284
                }
×
1285

1286
                mac := pod.Annotations[fmt.Sprintf(util.MacAddressAnnotationTemplate, podNet.ProviderName)]
×
1287
                ipStr := pod.Annotations[fmt.Sprintf(util.IPAddressAnnotationTemplate, podNet.ProviderName)]
×
1288
                vips := vipsMap[fmt.Sprintf("%s.%s", podNet.Subnet.Name, podNet.ProviderName)]
×
1289
                portName := ovs.PodNameToPortName(podName, namespace, podNet.ProviderName)
×
1290
                if err = c.OVNNbClient.SetLogicalSwitchPortSecurity(portSecurity, portName, mac, ipStr, vips); err != nil {
×
1291
                        klog.Errorf("failed to set security for logical switch port %s: %v", portName, err)
×
1292
                        return err
×
1293
                }
×
1294

1295
                c.syncVirtualPortsQueue.Add(podNet.Subnet.Name)
×
1296
                securityGroupAnnotation := pod.Annotations[fmt.Sprintf(util.SecurityGroupAnnotationTemplate, podNet.ProviderName)]
×
1297
                var securityGroups string
×
1298
                if securityGroupAnnotation != "" {
×
1299
                        securityGroups = strings.ReplaceAll(securityGroupAnnotation, " ", "")
×
1300
                        for sgName := range strings.SplitSeq(securityGroups, ",") {
×
1301
                                if sgName != "" {
×
1302
                                        c.syncSgPortsQueue.Add(sgName)
×
1303
                                }
×
1304
                        }
1305
                }
1306
                if err = c.reconcilePortSg(portName, securityGroups); err != nil {
×
1307
                        klog.Errorf("reconcilePortSg failed. %v", err)
×
1308
                        return err
×
1309
                }
×
1310
        }
1311
        return nil
×
1312
}
1313

1314
func (c *Controller) syncKubeOvnNet(pod *v1.Pod, podNets []*kubeovnNet) (*v1.Pod, error) {
×
1315
        podName := c.getNameByPod(pod)
×
1316
        key := fmt.Sprintf("%s/%s", pod.Namespace, podName)
×
1317
        targetPortNameList := strset.NewWithSize(len(podNets))
×
1318
        portsNeedToDel := []string{}
×
1319
        annotationsNeedToDel := []string{}
×
1320
        annotationsNeedToAdd := make(map[string]string)
×
1321
        subnetUsedByPort := make(map[string]string)
×
1322

×
1323
        for _, podNet := range podNets {
×
1324
                portName := ovs.PodNameToPortName(podName, pod.Namespace, podNet.ProviderName)
×
1325
                targetPortNameList.Add(portName)
×
1326
                if podNet.IPRequest != "" {
×
1327
                        klog.Infof("pod %s/%s use custom IP %s for provider %s", pod.Namespace, pod.Name, podNet.IPRequest, podNet.ProviderName)
×
1328
                        annotationsNeedToAdd[fmt.Sprintf(util.IPAddressAnnotationTemplate, podNet.ProviderName)] = podNet.IPRequest
×
1329
                }
×
1330

1331
                if podNet.MacRequest != "" {
×
1332
                        klog.Infof("pod %s/%s use custom MAC %s for provider %s", pod.Namespace, pod.Name, podNet.MacRequest, podNet.ProviderName)
×
1333
                        annotationsNeedToAdd[fmt.Sprintf(util.MacAddressAnnotationTemplate, podNet.ProviderName)] = podNet.MacRequest
×
1334
                }
×
1335
        }
1336

1337
        ports, err := c.OVNNbClient.ListNormalLogicalSwitchPorts(true, map[string]string{"pod": key})
×
1338
        if err != nil {
×
1339
                klog.Errorf("failed to list lsps of pod '%s', %v", pod.Name, err)
×
1340
                return nil, err
×
1341
        }
×
1342

1343
        for _, port := range ports {
×
1344
                if !targetPortNameList.Has(port.Name) {
×
1345
                        portsNeedToDel = append(portsNeedToDel, port.Name)
×
1346
                        subnetUsedByPort[port.Name] = port.ExternalIDs["ls"]
×
1347
                        portNameSlice := strings.Split(port.Name, ".")
×
1348
                        providerName := strings.Join(portNameSlice[2:], ".")
×
1349
                        if providerName == util.OvnProvider {
×
1350
                                continue
×
1351
                        }
1352
                        annotationsNeedToDel = append(annotationsNeedToDel, providerName)
×
1353
                }
1354
        }
1355

1356
        if len(portsNeedToDel) == 0 && len(annotationsNeedToAdd) == 0 {
×
1357
                return pod, nil
×
1358
        }
×
1359

1360
        for _, portNeedDel := range portsNeedToDel {
×
1361
                klog.Infof("release port %s for pod %s", portNeedDel, podName)
×
1362
                if subnet, ok := c.ipam.Subnets[subnetUsedByPort[portNeedDel]]; ok {
×
1363
                        subnet.ReleaseAddressWithNicName(podName, portNeedDel)
×
1364
                }
×
1365
                if err := c.OVNNbClient.DeleteLogicalSwitchPort(portNeedDel); err != nil {
×
1366
                        klog.Errorf("failed to delete lsp %s, %v", portNeedDel, err)
×
1367
                        return nil, err
×
1368
                }
×
1369
                if err := c.config.KubeOvnClient.KubeovnV1().IPs().Delete(context.Background(), portNeedDel, metav1.DeleteOptions{}); err != nil {
×
1370
                        if !k8serrors.IsNotFound(err) {
×
1371
                                klog.Errorf("failed to delete ip %s, %v", portNeedDel, err)
×
1372
                                return nil, err
×
1373
                        }
×
1374
                }
1375
        }
1376

1377
        patch := util.KVPatch{}
×
1378
        for _, providerName := range annotationsNeedToDel {
×
1379
                for key := range pod.Annotations {
×
1380
                        if strings.HasPrefix(key, providerName) {
×
1381
                                patch[key] = nil
×
1382
                        }
×
1383
                }
1384
        }
1385

1386
        for key, value := range annotationsNeedToAdd {
×
1387
                patch[key] = value
×
1388
        }
×
1389

1390
        if len(patch) == 0 {
×
1391
                return pod, nil
×
1392
        }
×
1393

1394
        if err = util.PatchAnnotations(c.config.KubeClient.CoreV1().Pods(pod.Namespace), pod.Name, patch); err != nil {
×
1395
                if k8serrors.IsNotFound(err) {
×
1396
                        return nil, nil
×
1397
                }
×
1398
                klog.Errorf("failed to clean annotations for pod %s/%s: %v", pod.Namespace, pod.Name, err)
×
1399
                return nil, err
×
1400
        }
1401

1402
        if pod, err = c.config.KubeClient.CoreV1().Pods(pod.Namespace).Get(context.TODO(), pod.Name, metav1.GetOptions{}); err != nil {
×
1403
                if k8serrors.IsNotFound(err) {
×
1404
                        return nil, nil
×
1405
                }
×
1406
                klog.Errorf("failed to get pod %s/%s: %v", pod.Namespace, pod.Name, err)
×
1407
                return nil, err
×
1408
        }
1409

1410
        return pod, nil
×
1411
}
1412

1413
func isStatefulSetPod(pod *v1.Pod) (bool, string, types.UID) {
×
1414
        for _, owner := range pod.OwnerReferences {
×
1415
                if owner.Kind == util.StatefulSet && strings.HasPrefix(owner.APIVersion, "apps/") {
×
1416
                        if strings.HasPrefix(pod.Name, owner.Name) {
×
1417
                                return true, owner.Name, owner.UID
×
1418
                        }
×
1419
                }
1420
        }
1421
        return false, "", ""
×
1422
}
1423

1424
func isStatefulSetPodToDel(c kubernetes.Interface, pod *v1.Pod, statefulSetName string, statefulSetUID types.UID) bool {
×
1425
        // only delete statefulset pod lsp when statefulset deleted or down scaled
×
1426
        sts, err := c.AppsV1().StatefulSets(pod.Namespace).Get(context.Background(), statefulSetName, metav1.GetOptions{})
×
1427
        if err != nil {
×
1428
                // statefulset is deleted
×
1429
                if k8serrors.IsNotFound(err) {
×
1430
                        klog.Infof("statefulset %s/%s has been deleted", pod.Namespace, statefulSetName)
×
1431
                        return true
×
1432
                }
×
1433
                klog.Errorf("failed to get statefulset %s/%s: %v", pod.Namespace, statefulSetName, err)
×
1434
                return false
×
1435
        }
1436

1437
        // statefulset is being deleted, or it's a newly created one
1438
        if !sts.DeletionTimestamp.IsZero() {
×
1439
                klog.Infof("statefulset %s/%s is being deleted", pod.Namespace, statefulSetName)
×
1440
                return true
×
1441
        }
×
1442
        if sts.UID != statefulSetUID {
×
1443
                klog.Infof("statefulset %s/%s is a newly created one", pod.Namespace, statefulSetName)
×
1444
                return true
×
1445
        }
×
1446

1447
        // down scale statefulset
1448
        tempStrs := strings.Split(pod.Name, "-")
×
1449
        numStr := tempStrs[len(tempStrs)-1]
×
1450
        index, err := strconv.ParseInt(numStr, 10, 0)
×
1451
        if err != nil {
×
1452
                klog.Errorf("failed to parse %s to int", numStr)
×
1453
                return false
×
1454
        }
×
1455
        // down scaled
1456
        var startOrdinal int64
×
1457
        if sts.Spec.Ordinals != nil {
×
1458
                startOrdinal = int64(sts.Spec.Ordinals.Start)
×
1459
        }
×
1460
        if index >= startOrdinal+int64(*sts.Spec.Replicas) {
×
1461
                klog.Infof("statefulset %s/%s is down scaled", pod.Namespace, statefulSetName)
×
1462
                return true
×
1463
        }
×
1464
        return false
×
1465
}
1466

1467
// only gc statefulset pod lsp when:
1468
// 1. the statefulset has been deleted or is being deleted
1469
// 2. the statefulset has been deleted and recreated
1470
// 3. the statefulset is down scaled and the pod is not alive
1471
func isStatefulSetPodToGC(c kubernetes.Interface, pod *v1.Pod, statefulSetName string, statefulSetUID types.UID) bool {
×
1472
        sts, err := c.AppsV1().StatefulSets(pod.Namespace).Get(context.Background(), statefulSetName, metav1.GetOptions{})
×
1473
        if err != nil {
×
1474
                // the statefulset has been deleted
×
1475
                if k8serrors.IsNotFound(err) {
×
1476
                        klog.Infof("statefulset %s/%s has been deleted", pod.Namespace, statefulSetName)
×
1477
                        return true
×
1478
                }
×
1479
                klog.Errorf("failed to get statefulset %s/%s: %v", pod.Namespace, statefulSetName, err)
×
1480
                return false
×
1481
        }
1482

1483
        // statefulset is being deleted
1484
        if !sts.DeletionTimestamp.IsZero() {
×
1485
                klog.Infof("statefulset %s/%s is being deleted", pod.Namespace, statefulSetName)
×
1486
                return true
×
1487
        }
×
1488
        // the statefulset has been deleted and recreated
1489
        if sts.UID != statefulSetUID {
×
1490
                klog.Infof("statefulset %s/%s is a newly created one", pod.Namespace, statefulSetName)
×
1491
                return true
×
1492
        }
×
1493

1494
        // the statefulset is down scaled and the pod is not alive
1495

1496
        tempStrs := strings.Split(pod.Name, "-")
×
1497
        numStr := tempStrs[len(tempStrs)-1]
×
1498
        index, err := strconv.ParseInt(numStr, 10, 0)
×
1499
        if err != nil {
×
1500
                klog.Errorf("failed to parse %s to int", numStr)
×
1501
                return false
×
1502
        }
×
1503
        // down scaled
1504
        var startOrdinal int64
×
1505
        if sts.Spec.Ordinals != nil {
×
1506
                startOrdinal = int64(sts.Spec.Ordinals.Start)
×
1507
        }
×
1508
        if index >= startOrdinal+int64(*sts.Spec.Replicas) {
×
1509
                klog.Infof("statefulset %s/%s is down scaled", pod.Namespace, statefulSetName)
×
1510
                if !isPodAlive(pod) {
×
1511
                        // we must check whether the pod is alive because we have to consider the following case:
×
1512
                        // 1. the statefulset is down scaled to zero
×
1513
                        // 2. the lsp gc is triggered
×
1514
                        // 3. gc interval, e.g. 90s, is passed and the second gc is triggered
×
1515
                        // 4. the sts is up scaled to the original replicas
×
1516
                        // 5. the pod is still running and it will not be recreated
×
1517
                        return true
×
1518
                }
×
1519
        }
1520

1521
        return false
×
1522
}
1523

1524
func getNodeTunlIP(node *v1.Node) ([]net.IP, error) {
×
1525
        var nodeTunlIPAddr []net.IP
×
1526
        nodeTunlIP := node.Annotations[util.IPAddressAnnotation]
×
1527
        if nodeTunlIP == "" {
×
1528
                return nil, errors.New("node has no tunnel ip annotation")
×
1529
        }
×
1530

1531
        for ip := range strings.SplitSeq(nodeTunlIP, ",") {
×
1532
                nodeTunlIPAddr = append(nodeTunlIPAddr, net.ParseIP(ip))
×
1533
        }
×
1534
        return nodeTunlIPAddr, nil
×
1535
}
1536

1537
func getNextHopByTunnelIP(gw []net.IP) string {
×
1538
        // validation check by caller
×
1539
        nextHop := gw[0].String()
×
1540
        if len(gw) == 2 {
×
1541
                nextHop = gw[0].String() + "," + gw[1].String()
×
1542
        }
×
1543
        return nextHop
×
1544
}
1545

1546
func needAllocateSubnets(pod *v1.Pod, nets []*kubeovnNet) []*kubeovnNet {
×
1547
        // check if allocate from subnet is need.
×
1548
        // allocate subnet when change subnet to hotplug nic
×
1549
        // allocate subnet when migrate vm
×
1550
        if !isPodAlive(pod) {
×
1551
                return nil
×
1552
        }
×
1553

1554
        if pod.Annotations == nil {
×
1555
                return nets
×
1556
        }
×
1557

1558
        migrate := false
×
1559
        if job, ok := pod.Annotations[util.MigrationJobAnnotation]; ok {
×
1560
                klog.Infof("pod %s/%s is in the migration job %s", pod.Namespace, pod.Name, job)
×
1561
                migrate = true
×
1562
        }
×
1563

1564
        result := make([]*kubeovnNet, 0, len(nets))
×
1565
        for _, n := range nets {
×
1566
                if migrate || pod.Annotations[fmt.Sprintf(util.AllocatedAnnotationTemplate, n.ProviderName)] != "true" {
×
1567
                        result = append(result, n)
×
1568
                }
×
1569
        }
1570
        return result
×
1571
}
1572

1573
func needRestartNatGatewayPod(pod *v1.Pod) bool {
×
1574
        for _, psc := range pod.Status.ContainerStatuses {
×
1575
                if psc.Name != "vpc-nat-gw" {
×
1576
                        continue
×
1577
                }
1578
                if psc.RestartCount > 0 {
×
1579
                        return true
×
1580
                }
×
1581
        }
1582
        return false
×
1583
}
1584

1585
func (c *Controller) podNeedSync(pod *v1.Pod) (bool, error) {
×
1586
        // 1. check annotations
×
1587
        if pod.Annotations == nil {
×
1588
                return true, nil
×
1589
        }
×
1590
        // 2. check annotation ovn subnet
1591
        if pod.Annotations[util.RoutedAnnotation] != "true" {
×
1592
                return true, nil
×
1593
        }
×
1594
        // 3. check multus subnet
1595
        attachmentNets, err := c.getPodAttachmentNet(pod)
×
1596
        if err != nil {
×
1597
                klog.Error(err)
×
1598
                return false, err
×
1599
        }
×
1600

1601
        podName := c.getNameByPod(pod)
×
1602
        for _, n := range attachmentNets {
×
1603
                if pod.Annotations[fmt.Sprintf(util.RoutedAnnotationTemplate, n.ProviderName)] != "true" {
×
1604
                        return true, nil
×
1605
                }
×
1606
                ipName := ovs.PodNameToPortName(podName, pod.Namespace, n.ProviderName)
×
1607
                if _, err = c.ipsLister.Get(ipName); err != nil {
×
1608
                        if !k8serrors.IsNotFound(err) {
×
1609
                                err = fmt.Errorf("failed to get ip %s: %w", ipName, err)
×
1610
                                klog.Error(err)
×
1611
                                return false, err
×
1612
                        }
×
1613
                        klog.Infof("ip %s not found", ipName)
×
1614
                        // need to sync to create ip
×
1615
                        return true, nil
×
1616
                }
1617
        }
1618
        return false, nil
×
1619
}
1620

1621
func needRouteSubnets(pod *v1.Pod, nets []*kubeovnNet) []*kubeovnNet {
×
1622
        if !isPodAlive(pod) {
×
1623
                return nil
×
1624
        }
×
1625

1626
        if pod.Annotations == nil {
×
1627
                return nets
×
1628
        }
×
1629

1630
        result := make([]*kubeovnNet, 0, len(nets))
×
1631
        for _, n := range nets {
×
1632
                if !isOvnSubnet(n.Subnet) {
×
1633
                        continue
×
1634
                }
1635

1636
                if pod.Annotations[fmt.Sprintf(util.AllocatedAnnotationTemplate, n.ProviderName)] == "true" && pod.Spec.NodeName != "" {
×
1637
                        if pod.Annotations[fmt.Sprintf(util.RoutedAnnotationTemplate, n.ProviderName)] != "true" {
×
1638
                                result = append(result, n)
×
1639
                        }
×
1640
                }
1641
        }
1642
        return result
×
1643
}
1644

1645
func (c *Controller) getPodDefaultSubnet(pod *v1.Pod) (*kubeovnv1.Subnet, error) {
1✔
1646
        // ignore to clean its ip crd in existing subnets
1✔
1647
        ignoreSubnetNotExist := !pod.DeletionTimestamp.IsZero()
1✔
1648

1✔
1649
        // check pod annotations
1✔
1650
        if lsName := pod.Annotations[util.LogicalSwitchAnnotation]; lsName != "" {
2✔
1651
                // annotations only has one default subnet
1✔
1652
                subnet, err := c.subnetsLister.Get(lsName)
1✔
1653
                if err != nil {
1✔
1654
                        klog.Errorf("failed to get subnet %s: %v", lsName, err)
×
1655
                        if k8serrors.IsNotFound(err) {
×
1656
                                if ignoreSubnetNotExist {
×
1657
                                        klog.Errorf("deleting pod %s/%s default subnet %s already not exist, gc will clean its ip cr", pod.Namespace, pod.Name, lsName)
×
1658
                                        return nil, nil
×
1659
                                }
×
1660
                        }
1661
                        return nil, err
×
1662
                }
1663
                return subnet, nil
1✔
1664
        }
1665

1666
        ns, err := c.namespacesLister.Get(pod.Namespace)
1✔
1667
        if err != nil {
1✔
1668
                klog.Errorf("failed to get namespace %s: %v", pod.Namespace, err)
×
1669
                return nil, err
×
1670
        }
×
1671
        if len(ns.Annotations) == 0 {
1✔
1672
                err = fmt.Errorf("namespace %s network annotations is empty", ns.Name)
×
1673
                klog.Error(err)
×
1674
                return nil, err
×
1675
        }
×
1676

1677
        subnetNames := ns.Annotations[util.LogicalSwitchAnnotation]
1✔
1678
        for subnetName := range strings.SplitSeq(subnetNames, ",") {
2✔
1679
                if subnetName == "" {
1✔
1680
                        err = fmt.Errorf("namespace %s default logical switch is not found", ns.Name)
×
1681
                        klog.Error(err)
×
1682
                        return nil, err
×
1683
                }
×
1684
                subnet, err := c.subnetsLister.Get(subnetName)
1✔
1685
                if err != nil {
1✔
1686
                        klog.Errorf("failed to get subnet %s: %v", subnetName, err)
×
1687
                        if k8serrors.IsNotFound(err) {
×
1688
                                if ignoreSubnetNotExist {
×
1689
                                        klog.Errorf("deleting pod %s/%s namespace subnet %s already not exist, gc will clean its ip cr", pod.Namespace, pod.Name, subnetName)
×
1690
                                        // ip name is unique, it is ok if any subnet release it
×
1691
                                        // gc will handle their ip cr, if all subnets are not exist
×
1692
                                        continue
×
1693
                                }
1694
                        }
1695
                        return nil, err
×
1696
                }
1697

1698
                switch subnet.Spec.Protocol {
1✔
1699
                case kubeovnv1.ProtocolDual:
×
1700
                        if subnet.Status.V6AvailableIPs == 0 && !c.podCanUseExcludeIPs(pod, subnet) {
×
1701
                                klog.Infof("there's no available ipv6 address in subnet %s, try next one", subnet.Name)
×
1702
                                continue
×
1703
                        }
1704
                        fallthrough
×
1705
                case kubeovnv1.ProtocolIPv4:
×
1706
                        if subnet.Status.V4AvailableIPs == 0 && !c.podCanUseExcludeIPs(pod, subnet) {
×
1707
                                klog.Infof("there's no available ipv4 address in subnet %s, try next one", subnet.Name)
×
1708
                                continue
×
1709
                        }
1710
                case kubeovnv1.ProtocolIPv6:
×
1711
                        if subnet.Status.V6AvailableIPs == 0 && !c.podCanUseExcludeIPs(pod, subnet) {
×
1712
                                klog.Infof("there's no available ipv6 address in subnet %s, try next one", subnet.Name)
×
1713
                                continue
×
1714
                        }
1715
                }
1716
                return subnet, nil
1✔
1717
        }
1718
        return nil, ipam.ErrNoAvailable
×
1719
}
1720

1721
func (c *Controller) podCanUseExcludeIPs(pod *v1.Pod, subnet *kubeovnv1.Subnet) bool {
×
1722
        if ipAddr := pod.Annotations[util.IPAddressAnnotation]; ipAddr != "" {
×
1723
                return c.checkIPsInExcludeList(ipAddr, subnet.Spec.ExcludeIps, subnet.Spec.CIDRBlock)
×
1724
        }
×
1725
        if ipPool := pod.Annotations[util.IPPoolAnnotation]; ipPool != "" {
×
1726
                return c.checkIPsInExcludeList(ipPool, subnet.Spec.ExcludeIps, subnet.Spec.CIDRBlock)
×
1727
        }
×
1728

1729
        return false
×
1730
}
1731

1732
func (c *Controller) checkIPsInExcludeList(ips string, excludeIPs []string, cidr string) bool {
×
1733
        expandedExcludeIPs := util.ExpandExcludeIPs(excludeIPs, cidr)
×
1734

×
1735
        for ipAddr := range strings.SplitSeq(strings.TrimSpace(ips), ",") {
×
1736
                ipAddr = strings.TrimSpace(ipAddr)
×
1737
                if ipAddr == "" {
×
1738
                        continue
×
1739
                }
1740

1741
                for _, excludeIP := range expandedExcludeIPs {
×
1742
                        if util.ContainsIPs(excludeIP, ipAddr) {
×
1743
                                klog.V(3).Infof("IP %s is found in exclude IP %s, allowing allocation", ipAddr, excludeIP)
×
1744
                                return true
×
1745
                        }
×
1746
                }
1747
        }
1748
        return false
×
1749
}
1750

1751
type providerType int
1752

1753
const (
1754
        providerTypeIPAM providerType = iota
1755
        providerTypeOriginal
1756
)
1757

1758
type kubeovnNet struct {
1759
        Type               providerType
1760
        ProviderName       string
1761
        Subnet             *kubeovnv1.Subnet
1762
        IsDefault          bool
1763
        AllowLiveMigration bool
1764
        IPRequest          string
1765
        MacRequest         string
1766
}
1767

1768
func (c *Controller) getPodAttachmentNet(pod *v1.Pod) ([]*kubeovnNet, error) {
1✔
1769
        var multusNets []*nadv1.NetworkSelectionElement
1✔
1770
        defaultAttachNetworks := pod.Annotations[util.DefaultNetworkAnnotation]
1✔
1771
        if defaultAttachNetworks != "" {
1✔
1772
                attachments, err := nadutils.ParseNetworkAnnotation(defaultAttachNetworks, pod.Namespace)
×
1773
                if err != nil {
×
1774
                        klog.Errorf("failed to parse default attach net for pod '%s', %v", pod.Name, err)
×
1775
                        return nil, err
×
1776
                }
×
1777
                multusNets = attachments
×
1778
        }
1779

1780
        attachNetworks := pod.Annotations[nadv1.NetworkAttachmentAnnot]
1✔
1781
        if attachNetworks != "" {
2✔
1782
                attachments, err := nadutils.ParseNetworkAnnotation(attachNetworks, pod.Namespace)
1✔
1783
                if err != nil {
1✔
1784
                        klog.Errorf("failed to parse attach net for pod '%s', %v", pod.Name, err)
×
1785
                        return nil, err
×
1786
                }
×
1787
                multusNets = append(multusNets, attachments...)
1✔
1788
        }
1789
        subnets, err := c.subnetsLister.List(labels.Everything())
1✔
1790
        if err != nil {
1✔
1791
                klog.Errorf("failed to list subnets: %v", err)
×
1792
                return nil, err
×
1793
        }
×
1794

1795
        // ignore to return all existing subnets to clean its ip crd
1796
        ignoreSubnetNotExist := !pod.DeletionTimestamp.IsZero()
1✔
1797

1✔
1798
        result := make([]*kubeovnNet, 0, len(multusNets))
1✔
1799
        for _, attach := range multusNets {
2✔
1800
                network, err := c.netAttachLister.NetworkAttachmentDefinitions(attach.Namespace).Get(attach.Name)
1✔
1801
                if err != nil {
1✔
1802
                        klog.Errorf("failed to get net-attach-def %s, %v", attach.Name, err)
×
1803
                        if k8serrors.IsNotFound(err) && ignoreSubnetNotExist {
×
1804
                                // NAD deleted before pod, find subnet for cleanup
×
1805
                                providerName := fmt.Sprintf("%s.%s.%s", attach.Name, attach.Namespace, util.OvnProvider)
×
1806
                                subnetName := pod.Annotations[fmt.Sprintf(util.LogicalSwitchAnnotationTemplate, providerName)]
×
1807
                                if subnetName == "" {
×
1808
                                        for _, subnet := range subnets {
×
1809
                                                if subnet.Spec.Provider == providerName {
×
1810
                                                        subnetName = subnet.Name
×
1811
                                                        break
×
1812
                                                }
1813
                                        }
1814
                                }
1815

1816
                                if subnetName == "" {
×
1817
                                        klog.Errorf("deleting pod %s/%s net-attach-def %s not found and cannot determine subnet, gc will clean its ip cr", pod.Namespace, pod.Name, attach.Name)
×
1818
                                        continue
×
1819
                                }
1820

1821
                                subnet, err := c.subnetsLister.Get(subnetName)
×
1822
                                if err != nil {
×
1823
                                        klog.Errorf("failed to get subnet %s, %v", subnetName, err)
×
1824
                                        if k8serrors.IsNotFound(err) {
×
1825
                                                klog.Errorf("deleting pod %s/%s attach subnet %s already not exist, gc will clean its ip cr", pod.Namespace, pod.Name, subnetName)
×
1826
                                                continue
×
1827
                                        }
1828
                                        return nil, err
×
1829
                                }
1830

1831
                                klog.Infof("pod %s/%s net-attach-def %s not found, using subnet %s for cleanup", pod.Namespace, pod.Name, attach.Name, subnetName)
×
1832
                                result = append(result, &kubeovnNet{
×
1833
                                        Type:         providerTypeIPAM,
×
1834
                                        ProviderName: providerName,
×
1835
                                        Subnet:       subnet,
×
1836
                                        IsDefault:    util.IsDefaultNet(pod.Annotations[util.DefaultNetworkAnnotation], attach),
×
1837
                                })
×
1838
                                continue
×
1839
                        }
1840
                        return nil, err
×
1841
                }
1842

1843
                if network.Spec.Config == "" {
1✔
1844
                        continue
×
1845
                }
1846

1847
                netCfg, err := loadNetConf([]byte(network.Spec.Config))
1✔
1848
                if err != nil {
1✔
1849
                        klog.Errorf("failed to load config of net-attach-def %s, %v", attach.Name, err)
×
1850
                        return nil, err
×
1851
                }
×
1852

1853
                // allocate kubeovn network
1854
                var providerName string
1✔
1855
                if util.IsOvnNetwork(netCfg) {
2✔
1856
                        allowLiveMigration := false
1✔
1857
                        isDefault := util.IsDefaultNet(pod.Annotations[util.DefaultNetworkAnnotation], attach)
1✔
1858

1✔
1859
                        providerName = fmt.Sprintf("%s.%s.%s", attach.Name, attach.Namespace, util.OvnProvider)
1✔
1860
                        if pod.Annotations[util.MigrationJobAnnotation] != "" {
1✔
1861
                                allowLiveMigration = true
×
1862
                        }
×
1863

1864
                        subnetName := pod.Annotations[fmt.Sprintf(util.LogicalSwitchAnnotationTemplate, providerName)]
1✔
1865
                        if subnetName == "" {
1✔
1866
                                for _, subnet := range subnets {
×
1867
                                        if subnet.Spec.Provider == providerName {
×
1868
                                                subnetName = subnet.Name
×
1869
                                                break
×
1870
                                        }
1871
                                }
1872
                        }
1873
                        var subnet *kubeovnv1.Subnet
1✔
1874
                        if subnetName == "" {
1✔
1875
                                // attachment network not specify subnet, use pod default subnet or namespace subnet
×
1876
                                subnet, err = c.getPodDefaultSubnet(pod)
×
1877
                                if err != nil {
×
1878
                                        klog.Errorf("failed to pod default subnet, %v", err)
×
1879
                                        if k8serrors.IsNotFound(err) {
×
1880
                                                if ignoreSubnetNotExist {
×
1881
                                                        klog.Errorf("deleting pod %s/%s attach subnet %s already not exist, gc will clean its ip cr", pod.Namespace, pod.Name, subnetName)
×
1882
                                                        continue
×
1883
                                                }
1884
                                        }
1885
                                        return nil, err
×
1886
                                }
1887
                                // default subnet may change after pod restart
1888
                                klog.Infof("pod %s/%s attachment network %s use default subnet %s", pod.Namespace, pod.Name, attach.Name, subnet.Name)
×
1889
                        } else {
1✔
1890
                                subnet, err = c.subnetsLister.Get(subnetName)
1✔
1891
                                if err != nil {
1✔
1892
                                        klog.Errorf("failed to get subnet %s, %v", subnetName, err)
×
1893
                                        if k8serrors.IsNotFound(err) {
×
1894
                                                if ignoreSubnetNotExist {
×
1895
                                                        klog.Errorf("deleting pod %s/%s attach subnet %s already not exist, gc will clean its ip cr", pod.Namespace, pod.Name, subnetName)
×
1896
                                                        // just continue to next attach subnet
×
1897
                                                        // ip name is unique, so it is ok if the other subnet release it
×
1898
                                                        continue
×
1899
                                                }
1900
                                        }
1901
                                        return nil, err
×
1902
                                }
1903
                        }
1904

1905
                        ret := &kubeovnNet{
1✔
1906
                                Type:               providerTypeOriginal,
1✔
1907
                                ProviderName:       providerName,
1✔
1908
                                Subnet:             subnet,
1✔
1909
                                IsDefault:          isDefault,
1✔
1910
                                AllowLiveMigration: allowLiveMigration,
1✔
1911
                                MacRequest:         attach.MacRequest,
1✔
1912
                                IPRequest:          strings.Join(attach.IPRequest, ","),
1✔
1913
                        }
1✔
1914
                        result = append(result, ret)
1✔
1915
                } else {
×
1916
                        providerName = fmt.Sprintf("%s.%s", attach.Name, attach.Namespace)
×
1917
                        for _, subnet := range subnets {
×
1918
                                if subnet.Spec.Provider == providerName {
×
1919
                                        result = append(result, &kubeovnNet{
×
1920
                                                Type:         providerTypeIPAM,
×
1921
                                                ProviderName: providerName,
×
1922
                                                Subnet:       subnet,
×
1923
                                                MacRequest:   attach.MacRequest,
×
1924
                                                IPRequest:    strings.Join(attach.IPRequest, ","),
×
1925
                                        })
×
1926
                                        break
×
1927
                                }
1928
                        }
1929
                }
1930
        }
1931
        return result, nil
1✔
1932
}
1933

1934
func (c *Controller) validatePodIP(podName, subnetName, ipv4, ipv6 string) (bool, bool, error) {
×
1935
        subnet, err := c.subnetsLister.Get(subnetName)
×
1936
        if err != nil {
×
1937
                klog.Errorf("failed to get subnet %s: %v", subnetName, err)
×
1938
                return false, false, err
×
1939
        }
×
1940

1941
        if subnet.Spec.Vlan == "" && subnet.Spec.Vpc == c.config.ClusterRouter {
×
1942
                nodes, err := c.nodesLister.List(labels.Everything())
×
1943
                if err != nil {
×
1944
                        klog.Errorf("failed to list nodes: %v", err)
×
1945
                        return false, false, err
×
1946
                }
×
1947

1948
                for _, node := range nodes {
×
1949
                        nodeIPv4, nodeIPv6 := util.GetNodeInternalIP(*node)
×
1950
                        if ipv4 != "" && ipv4 == nodeIPv4 {
×
1951
                                klog.Errorf("IP address (%s) assigned to pod %s is the same with internal IP address of node %s, reallocating...", ipv4, podName, node.Name)
×
1952
                                return false, true, nil
×
1953
                        }
×
1954
                        if ipv6 != "" && ipv6 == nodeIPv6 {
×
1955
                                klog.Errorf("IP address (%s) assigned to pod %s is the same with internal IP address of node %s, reallocating...", ipv6, podName, node.Name)
×
1956
                                return true, false, nil
×
1957
                        }
×
1958
                }
1959
        }
1960

1961
        return true, true, nil
×
1962
}
1963

1964
func (c *Controller) acquireAddress(pod *v1.Pod, podNet *kubeovnNet) (string, string, string, *kubeovnv1.Subnet, error) {
×
1965
        podName := c.getNameByPod(pod)
×
1966
        key := fmt.Sprintf("%s/%s", pod.Namespace, podName)
×
1967
        portName := ovs.PodNameToPortName(podName, pod.Namespace, podNet.ProviderName)
×
1968

×
1969
        var checkVMPod bool
×
1970
        isStsPod, _, _ := isStatefulSetPod(pod)
×
1971
        // if pod has static vip
×
1972
        vipName := pod.Annotations[util.VipAnnotation]
×
1973
        if vipName != "" {
×
1974
                vip, err := c.virtualIpsLister.Get(vipName)
×
1975
                if err != nil {
×
1976
                        klog.Errorf("failed to get static vip '%s', %v", vipName, err)
×
1977
                        return "", "", "", podNet.Subnet, err
×
1978
                }
×
1979
                if c.config.EnableKeepVMIP {
×
1980
                        checkVMPod, _ = isVMPod(pod)
×
1981
                }
×
1982
                if err = c.podReuseVip(vipName, portName, isStsPod || checkVMPod); err != nil {
×
1983
                        return "", "", "", podNet.Subnet, err
×
1984
                }
×
1985
                return vip.Status.V4ip, vip.Status.V6ip, vip.Status.Mac, podNet.Subnet, nil
×
1986
        }
1987

1988
        var macPointer *string
×
1989
        if isOvnSubnet(podNet.Subnet) {
×
1990
                annoMAC := pod.Annotations[fmt.Sprintf(util.MacAddressAnnotationTemplate, podNet.ProviderName)]
×
1991
                if annoMAC != "" {
×
1992
                        if _, err := net.ParseMAC(annoMAC); err != nil {
×
1993
                                return "", "", "", podNet.Subnet, err
×
1994
                        }
×
1995
                        macPointer = &annoMAC
×
1996
                }
1997
        } else {
×
1998
                macPointer = ptr.To("")
×
1999
        }
×
2000

2001
        var err error
×
2002
        var nsNets []*kubeovnNet
×
2003
        ippoolStr := pod.Annotations[fmt.Sprintf(util.IPPoolAnnotationTemplate, podNet.ProviderName)]
×
2004
        subnetStr := pod.Annotations[fmt.Sprintf(util.LogicalSwitchAnnotationTemplate, podNet.ProviderName)]
×
2005
        if ippoolStr == "" && podNet.IsDefault {
×
2006
                // no ippool specified by pod annotation, use namespace ippools or ippools in the subnet specified by pod annotation
×
2007
                ns, err := c.namespacesLister.Get(pod.Namespace)
×
2008
                if err != nil {
×
2009
                        klog.Errorf("failed to get namespace %s: %v", pod.Namespace, err)
×
2010
                        return "", "", "", podNet.Subnet, err
×
2011
                }
×
2012
                if nsNets, err = c.getNsAvailableSubnets(pod, podNet); err != nil {
×
2013
                        klog.Errorf("failed to get available subnets for pod %s/%s, %v", pod.Namespace, pod.Name, err)
×
2014
                        return "", "", "", podNet.Subnet, err
×
2015
                }
×
2016
                subnetNames := make([]string, 0, len(nsNets))
×
2017
                for _, net := range nsNets {
×
2018
                        if net.Subnet.Name == subnetStr {
×
2019
                                // allocate from ippools in the subnet specified by pod annotation
×
2020
                                podNet.Subnet = net.Subnet
×
2021
                                subnetNames = []string{net.Subnet.Name}
×
2022
                                break
×
2023
                        }
2024
                        subnetNames = append(subnetNames, net.Subnet.Name)
×
2025
                }
2026

2027
                if subnetStr == "" || slices.Contains(subnetNames, subnetStr) {
×
2028
                        // no subnet specified by pod annotation or specified subnet is in namespace subnets
×
2029
                        if ipPoolList, ok := ns.Annotations[util.IPPoolAnnotation]; ok {
×
2030
                                for ipPoolName := range strings.SplitSeq(ipPoolList, ",") {
×
2031
                                        ippool, err := c.ippoolLister.Get(ipPoolName)
×
2032
                                        if err != nil {
×
2033
                                                klog.Errorf("failed to get ippool %s: %v", ipPoolName, err)
×
2034
                                                return "", "", "", podNet.Subnet, err
×
2035
                                        }
×
2036

2037
                                        switch podNet.Subnet.Spec.Protocol {
×
2038
                                        case kubeovnv1.ProtocolDual:
×
2039
                                                if ippool.Status.V4AvailableIPs.Int64() == 0 || ippool.Status.V6AvailableIPs.Int64() == 0 {
×
2040
                                                        continue
×
2041
                                                }
2042
                                        case kubeovnv1.ProtocolIPv4:
×
2043
                                                if ippool.Status.V4AvailableIPs.Int64() == 0 {
×
2044
                                                        continue
×
2045
                                                }
2046

2047
                                        default:
×
2048
                                                if ippool.Status.V6AvailableIPs.Int64() == 0 {
×
2049
                                                        continue
×
2050
                                                }
2051
                                        }
2052

2053
                                        for _, net := range nsNets {
×
2054
                                                if net.Subnet.Name == ippool.Spec.Subnet && slices.Contains(subnetNames, net.Subnet.Name) {
×
2055
                                                        ippoolStr = ippool.Name
×
2056
                                                        podNet.Subnet = net.Subnet
×
2057
                                                        break
×
2058
                                                }
2059
                                        }
2060
                                        if ippoolStr != "" {
×
2061
                                                break
×
2062
                                        }
2063
                                }
2064
                                if ippoolStr == "" {
×
2065
                                        klog.Infof("no available ippool in subnet(s) %s for pod %s/%s", strings.Join(subnetNames, ","), pod.Namespace, pod.Name)
×
2066
                                        return "", "", "", podNet.Subnet, ipam.ErrNoAvailable
×
2067
                                }
×
2068
                        }
2069
                }
2070
        }
2071

2072
        // Random allocate
2073
        if pod.Annotations[fmt.Sprintf(util.IPAddressAnnotationTemplate, podNet.ProviderName)] == "" &&
×
2074
                ippoolStr == "" {
×
2075
                var skippedAddrs []string
×
2076
                for {
×
2077
                        ipv4, ipv6, mac, err := c.ipam.GetRandomAddress(key, portName, macPointer, podNet.Subnet.Name, "", skippedAddrs, !podNet.AllowLiveMigration)
×
2078
                        if err != nil {
×
2079
                                klog.Error(err)
×
2080
                                return "", "", "", podNet.Subnet, err
×
2081
                        }
×
2082
                        ipv4OK, ipv6OK, err := c.validatePodIP(pod.Name, podNet.Subnet.Name, ipv4, ipv6)
×
2083
                        if err != nil {
×
2084
                                klog.Error(err)
×
2085
                                return "", "", "", podNet.Subnet, err
×
2086
                        }
×
2087
                        if ipv4OK && ipv6OK {
×
2088
                                return ipv4, ipv6, mac, podNet.Subnet, nil
×
2089
                        }
×
2090

2091
                        if !ipv4OK {
×
2092
                                skippedAddrs = append(skippedAddrs, ipv4)
×
2093
                        }
×
2094
                        if !ipv6OK {
×
2095
                                skippedAddrs = append(skippedAddrs, ipv6)
×
2096
                        }
×
2097
                }
2098
        }
2099

2100
        // The static ip can be assigned from any subnet after ns supports multi subnets
2101
        if nsNets == nil {
×
2102
                if nsNets, err = c.getNsAvailableSubnets(pod, podNet); err != nil {
×
2103
                        klog.Errorf("failed to get available subnets for pod %s/%s, %v", pod.Namespace, pod.Name, err)
×
2104
                        return "", "", "", podNet.Subnet, err
×
2105
                }
×
2106
        }
2107

2108
        var v4IP, v6IP, mac string
×
2109

×
2110
        // Static allocate
×
2111
        if ipStr := pod.Annotations[fmt.Sprintf(util.IPAddressAnnotationTemplate, podNet.ProviderName)]; ipStr != "" {
×
2112
                for _, net := range nsNets {
×
2113
                        v4IP, v6IP, mac, err = c.acquireStaticAddress(key, portName, ipStr, macPointer, net.Subnet.Name, net.AllowLiveMigration)
×
2114
                        if err == nil {
×
2115
                                return v4IP, v6IP, mac, net.Subnet, nil
×
2116
                        }
×
2117
                }
2118
                return v4IP, v6IP, mac, podNet.Subnet, err
×
2119
        }
2120

2121
        // IPPool allocate
2122
        if ippoolStr != "" {
×
2123
                var ipPool []string
×
2124
                if strings.ContainsRune(ippoolStr, ';') {
×
2125
                        ipPool = strings.Split(ippoolStr, ";")
×
2126
                } else {
×
2127
                        ipPool = strings.Split(ippoolStr, ",")
×
2128
                        if len(ipPool) == 2 && util.CheckProtocol(ipPool[0]) != util.CheckProtocol(ipPool[1]) {
×
2129
                                ipPool = []string{ippoolStr}
×
2130
                        }
×
2131
                }
2132
                for i, ip := range ipPool {
×
2133
                        ipPool[i] = strings.TrimSpace(ip)
×
2134
                }
×
2135

2136
                if len(ipPool) == 1 && (!strings.ContainsRune(ipPool[0], ',') && net.ParseIP(ipPool[0]) == nil) {
×
2137
                        var skippedAddrs []string
×
2138
                        pool, err := c.ippoolLister.Get(ipPool[0])
×
2139
                        if err != nil {
×
2140
                                klog.Errorf("failed to get ippool %s: %v", ipPool[0], err)
×
2141
                                return "", "", "", podNet.Subnet, err
×
2142
                        }
×
2143
                        for {
×
2144
                                ipv4, ipv6, mac, err := c.ipam.GetRandomAddress(key, portName, macPointer, pool.Spec.Subnet, ipPool[0], skippedAddrs, !podNet.AllowLiveMigration)
×
2145
                                if err != nil {
×
2146
                                        klog.Error(err)
×
2147
                                        return "", "", "", podNet.Subnet, err
×
2148
                                }
×
2149
                                ipv4OK, ipv6OK, err := c.validatePodIP(pod.Name, podNet.Subnet.Name, ipv4, ipv6)
×
2150
                                if err != nil {
×
2151
                                        klog.Error(err)
×
2152
                                        return "", "", "", podNet.Subnet, err
×
2153
                                }
×
2154
                                if ipv4OK && ipv6OK {
×
2155
                                        return ipv4, ipv6, mac, podNet.Subnet, nil
×
2156
                                }
×
2157

2158
                                if !ipv4OK {
×
2159
                                        skippedAddrs = append(skippedAddrs, ipv4)
×
2160
                                }
×
2161
                                if !ipv6OK {
×
2162
                                        skippedAddrs = append(skippedAddrs, ipv6)
×
2163
                                }
×
2164
                        }
2165
                }
2166

2167
                if !isStsPod {
×
2168
                        for _, net := range nsNets {
×
2169
                                for _, staticIP := range ipPool {
×
2170
                                        var checkIP string
×
2171
                                        ipProtocol := util.CheckProtocol(staticIP)
×
2172
                                        if ipProtocol == kubeovnv1.ProtocolDual {
×
2173
                                                checkIP = strings.Split(staticIP, ",")[0]
×
2174
                                        } else {
×
2175
                                                checkIP = staticIP
×
2176
                                        }
×
2177

2178
                                        if assignedPod, ok := c.ipam.IsIPAssignedToOtherPod(checkIP, net.Subnet.Name, key); ok {
×
2179
                                                klog.Errorf("static address %s for %s has been assigned to %s", staticIP, key, assignedPod)
×
2180
                                                continue
×
2181
                                        }
2182

2183
                                        v4IP, v6IP, mac, err = c.acquireStaticAddress(key, portName, staticIP, macPointer, net.Subnet.Name, net.AllowLiveMigration)
×
2184
                                        if err == nil {
×
2185
                                                return v4IP, v6IP, mac, net.Subnet, nil
×
2186
                                        }
×
2187
                                }
2188
                        }
2189
                        klog.Errorf("acquire address from ippool %s for %s failed, %v", ippoolStr, key, err)
×
2190
                } else {
×
2191
                        tempStrs := strings.Split(pod.Name, "-")
×
2192
                        numStr := tempStrs[len(tempStrs)-1]
×
2193
                        index, _ := strconv.Atoi(numStr)
×
2194

×
2195
                        if index < len(ipPool) {
×
2196
                                for _, net := range nsNets {
×
2197
                                        v4IP, v6IP, mac, err = c.acquireStaticAddress(key, portName, ipPool[index], macPointer, net.Subnet.Name, net.AllowLiveMigration)
×
2198
                                        if err == nil {
×
2199
                                                return v4IP, v6IP, mac, net.Subnet, nil
×
2200
                                        }
×
2201
                                }
2202
                                klog.Errorf("acquire address %s for %s failed, %v", ipPool[index], key, err)
×
2203
                        }
2204
                }
2205
        }
2206
        klog.Errorf("allocate address for %s failed, return NoAvailableAddress", key)
×
2207
        return "", "", "", podNet.Subnet, ipam.ErrNoAvailable
×
2208
}
2209

2210
func (c *Controller) acquireStaticAddress(key, nicName, ip string, mac *string, subnet string, liveMigration bool) (string, string, string, error) {
×
2211
        var v4IP, v6IP, macStr string
×
2212
        var err error
×
2213
        for ipStr := range strings.SplitSeq(ip, ",") {
×
2214
                if net.ParseIP(ipStr) == nil {
×
2215
                        return "", "", "", fmt.Errorf("failed to parse IP %s", ipStr)
×
2216
                }
×
2217
        }
2218

2219
        if v4IP, v6IP, macStr, err = c.ipam.GetStaticAddress(key, nicName, ip, mac, subnet, !liveMigration); err != nil {
×
2220
                klog.Errorf("failed to get static ip %v, mac %v, subnet %v, err %v", ip, mac, subnet, err)
×
2221
                return "", "", "", err
×
2222
        }
×
2223
        return v4IP, v6IP, macStr, nil
×
2224
}
2225

2226
func appendCheckPodNonMultusNetToDel(c *Controller, pod *v1.Pod, ownerRefName, ownerRefKind string) (bool, error) {
×
2227
        // subnet for ns has been changed, and statefulset pod's ip is not in the range of subnet's cidr anymore
×
2228
        podNs, err := c.namespacesLister.Get(pod.Namespace)
×
2229
        if err != nil {
×
2230
                klog.Errorf("failed to get namespace %s, %v", pod.Namespace, err)
×
2231
                return false, err
×
2232
        }
×
2233

2234
        // check if subnet exist in OwnerReference
2235
        var ownerRefSubnetExist bool
×
2236
        var ownerRefSubnet string
×
2237
        switch ownerRefKind {
×
2238
        case util.StatefulSet:
×
2239
                ss, err := c.config.KubeClient.AppsV1().StatefulSets(pod.Namespace).Get(context.Background(), ownerRefName, metav1.GetOptions{})
×
2240
                if err != nil {
×
2241
                        if k8serrors.IsNotFound(err) {
×
2242
                                klog.Infof("Statefulset %s is not found", ownerRefName)
×
2243
                                return true, nil
×
2244
                        }
×
2245
                        klog.Errorf("failed to get StatefulSet %s, %v", ownerRefName, err)
×
2246
                }
2247
                if ss.Spec.Template.Annotations[util.LogicalSwitchAnnotation] != "" {
×
2248
                        ownerRefSubnetExist = true
×
2249
                        ownerRefSubnet = ss.Spec.Template.Annotations[util.LogicalSwitchAnnotation]
×
2250
                }
×
2251

2252
        case util.VMInstance:
×
2253
                vm, err := c.config.KubevirtClient.VirtualMachine(pod.Namespace).Get(context.Background(), ownerRefName, metav1.GetOptions{})
×
2254
                if err != nil {
×
2255
                        if k8serrors.IsNotFound(err) {
×
2256
                                klog.Infof("VirtualMachine %s is not found", ownerRefName)
×
2257
                                return true, nil
×
2258
                        }
×
2259
                        klog.Errorf("failed to get VirtualMachine %s, %v", ownerRefName, err)
×
2260
                }
2261
                if vm != nil &&
×
2262
                        vm.Spec.Template != nil &&
×
2263
                        vm.Spec.Template.ObjectMeta.Annotations != nil &&
×
2264
                        vm.Spec.Template.ObjectMeta.Annotations[util.LogicalSwitchAnnotation] != "" {
×
2265
                        ownerRefSubnetExist = true
×
2266
                        ownerRefSubnet = vm.Spec.Template.ObjectMeta.Annotations[util.LogicalSwitchAnnotation]
×
2267
                }
×
2268
        }
2269
        podSwitch := strings.TrimSpace(pod.Annotations[util.LogicalSwitchAnnotation])
×
2270
        if podSwitch == "" {
×
2271
                // pod has no default ovn logical switch annotation, only use multus specs, nothing to clean
×
2272
                klog.Infof("pod %s/%s has no  default ovn logical switch annotation, not auto clean ip", pod.Namespace, pod.Name)
×
2273
                return false, nil
×
2274
        }
×
2275
        if !ownerRefSubnetExist {
×
2276
                nsSubnetNames := podNs.Annotations[util.LogicalSwitchAnnotation]
×
2277
                // check if pod use the subnet of its ns
×
2278
                if nsSubnetNames != "" && !slices.Contains(strings.Split(nsSubnetNames, ","), podSwitch) {
×
2279
                        klog.Infof("ns %s annotation subnet is %s, which is inconstant with subnet for pod %s, delete pod", pod.Namespace, nsSubnetNames, pod.Name)
×
2280
                        return true, nil
×
2281
                }
×
2282
        }
2283

2284
        // subnet cidr has been changed, and statefulset pod's ip is not in the range of subnet's cidr anymore
2285
        podSubnet, err := c.subnetsLister.Get(podSwitch)
×
2286
        if err != nil {
×
2287
                if k8serrors.IsNotFound(err) {
×
2288
                        klog.Infof("subnet %s not found for pod %s/%s, not auto clean ip", podSwitch, pod.Namespace, pod.Name)
×
2289
                        return false, nil
×
2290
                }
×
2291
                klog.Errorf("failed to get subnet %s, %v, not auto clean ip", podSwitch, err)
×
2292
                return false, err
×
2293
        }
2294
        if podSubnet == nil {
×
2295
                // TODO: remove: CRD get interface will retrun a nil subnet ?
×
2296
                klog.Errorf("pod %s/%s subnet %s is nil, not auto clean ip", pod.Namespace, pod.Name, podSwitch)
×
2297
                return false, nil
×
2298
        }
×
2299
        podIP := pod.Annotations[util.IPAddressAnnotation]
×
2300
        if podIP == "" {
×
2301
                // delete pod just after it created < 1ms
×
2302
                klog.Infof("pod %s/%s annotaions has no ip address, not auto clean ip", pod.Namespace, pod.Name)
×
2303
                return false, nil
×
2304
        }
×
2305
        podSubnetCidr := podSubnet.Spec.CIDRBlock
×
2306
        if podSubnetCidr == "" {
×
2307
                // subnet spec cidr changed by user
×
2308
                klog.Errorf("invalid pod subnet %s empty cidr %s, not auto clean ip", podSwitch, podSubnetCidr)
×
2309
                return false, nil
×
2310
        }
×
2311
        if !util.CIDRContainIP(podSubnetCidr, podIP) {
×
2312
                klog.Infof("pod's ip %s is not in the range of subnet %s, delete pod", pod.Annotations[util.IPAddressAnnotation], podSubnet.Name)
×
2313
                return true, nil
×
2314
        }
×
2315
        // subnet of ownerReference(sts/vm) has been changed, it needs to handle delete pod and create port on the new logical switch
2316
        if ownerRefSubnet != "" && podSubnet.Name != ownerRefSubnet {
×
2317
                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)
×
2318
                return true, nil
×
2319
        }
×
2320

2321
        return false, nil
×
2322
}
2323

2324
func isVMPod(pod *v1.Pod) (bool, string) {
×
2325
        for _, owner := range pod.OwnerReferences {
×
2326
                // The name of vmi is consistent with vm's name.
×
2327
                if owner.Kind == util.VMInstance && strings.HasPrefix(owner.APIVersion, "kubevirt.io") {
×
2328
                        return true, owner.Name
×
2329
                }
×
2330
        }
2331
        return false, ""
×
2332
}
2333

2334
func isOwnsByTheVM(vmi metav1.Object) (bool, string) {
×
2335
        for _, owner := range vmi.GetOwnerReferences() {
×
2336
                if owner.Kind == util.VM && strings.HasPrefix(owner.APIVersion, "kubevirt.io") {
×
2337
                        return true, owner.Name
×
2338
                }
×
2339
        }
2340
        return false, ""
×
2341
}
2342

2343
func (c *Controller) isVMToDel(pod *v1.Pod, vmiName string) bool {
×
2344
        var (
×
2345
                vmiAlive bool
×
2346
                vmName   string
×
2347
        )
×
2348
        // The vmi is also deleted when pod is deleted, only left vm exists.
×
2349
        vmi, err := c.config.KubevirtClient.VirtualMachineInstance(pod.Namespace).Get(context.Background(), vmiName, metav1.GetOptions{})
×
2350
        if err != nil {
×
2351
                if k8serrors.IsNotFound(err) {
×
2352
                        vmiAlive = false
×
2353
                        // The name of vmi is consistent with vm's name.
×
2354
                        vmName = vmiName
×
2355
                        klog.ErrorS(err, "failed to get vmi, will try to get the vm directly", "name", vmiName)
×
2356
                } else {
×
2357
                        klog.ErrorS(err, "failed to get vmi", "name", vmiName)
×
2358
                        return false
×
2359
                }
×
2360
        } else {
×
2361
                var ownsByVM bool
×
2362
                ownsByVM, vmName = isOwnsByTheVM(vmi)
×
2363
                if !ownsByVM && !vmi.DeletionTimestamp.IsZero() {
×
2364
                        klog.Infof("ephemeral vmi %s is deleting", vmiName)
×
2365
                        return true
×
2366
                }
×
2367
                vmiAlive = vmi.DeletionTimestamp.IsZero()
×
2368
        }
2369

2370
        if vmiAlive {
×
2371
                return false
×
2372
        }
×
2373

2374
        vm, err := c.config.KubevirtClient.VirtualMachine(pod.Namespace).Get(context.Background(), vmName, metav1.GetOptions{})
×
2375
        if err != nil {
×
2376
                // the vm has gone
×
2377
                if k8serrors.IsNotFound(err) {
×
2378
                        klog.ErrorS(err, "failed to get vm", "name", vmName)
×
2379
                        return true
×
2380
                }
×
2381
                klog.ErrorS(err, "failed to get vm", "name", vmName)
×
2382
                return false
×
2383
        }
2384

2385
        if !vm.DeletionTimestamp.IsZero() {
×
2386
                klog.Infof("vm %s is deleting", vmName)
×
2387
                return true
×
2388
        }
×
2389
        return false
×
2390
}
2391

2392
func (c *Controller) getNameByPod(pod *v1.Pod) string {
×
2393
        if c.config.EnableKeepVMIP {
×
2394
                if isVMPod, vmName := isVMPod(pod); isVMPod {
×
2395
                        return vmName
×
2396
                }
×
2397
        }
2398
        return pod.Name
×
2399
}
2400

2401
// 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.
2402
func (c *Controller) getNsAvailableSubnets(pod *v1.Pod, podNet *kubeovnNet) ([]*kubeovnNet, error) {
×
2403
        // keep the annotation subnet of the pod in first position
×
2404
        result := []*kubeovnNet{podNet}
×
2405

×
2406
        ns, err := c.namespacesLister.Get(pod.Namespace)
×
2407
        if err != nil {
×
2408
                klog.Errorf("failed to get namespace %s, %v", pod.Namespace, err)
×
2409
                return nil, err
×
2410
        }
×
2411
        if ns.Annotations == nil {
×
2412
                return []*kubeovnNet{}, nil
×
2413
        }
×
2414

2415
        subnetNames := ns.Annotations[util.LogicalSwitchAnnotation]
×
2416
        for subnetName := range strings.SplitSeq(subnetNames, ",") {
×
2417
                if subnetName == "" || subnetName == podNet.Subnet.Name {
×
2418
                        continue
×
2419
                }
2420
                subnet, err := c.subnetsLister.Get(subnetName)
×
2421
                if err != nil {
×
2422
                        klog.Errorf("failed to get subnet %v", err)
×
2423
                        return nil, err
×
2424
                }
×
2425

2426
                result = append(result, &kubeovnNet{
×
2427
                        Type:         providerTypeOriginal,
×
2428
                        ProviderName: subnet.Spec.Provider,
×
2429
                        Subnet:       subnet,
×
2430
                })
×
2431
        }
2432

2433
        return result, nil
×
2434
}
2435

2436
func getPodType(pod *v1.Pod) string {
×
2437
        if ok, _, _ := isStatefulSetPod(pod); ok {
×
2438
                return util.StatefulSet
×
2439
        }
×
2440

2441
        if isVMPod, _ := isVMPod(pod); isVMPod {
×
2442
                return util.VM
×
2443
        }
×
2444
        return ""
×
2445
}
2446

2447
func (c *Controller) getVirtualIPs(pod *v1.Pod, podNets []*kubeovnNet) map[string]string {
×
2448
        vipsListMap := make(map[string][]string)
×
2449
        var vipNamesList []string
×
2450
        for vipName := range strings.SplitSeq(strings.TrimSpace(pod.Annotations[util.AAPsAnnotation]), ",") {
×
2451
                if vipName = strings.TrimSpace(vipName); vipName == "" {
×
2452
                        continue
×
2453
                }
2454
                if !slices.Contains(vipNamesList, vipName) {
×
2455
                        vipNamesList = append(vipNamesList, vipName)
×
2456
                } else {
×
2457
                        continue
×
2458
                }
2459
                vip, err := c.virtualIpsLister.Get(vipName)
×
2460
                if err != nil {
×
2461
                        klog.Errorf("failed to get vip %s, %v", vipName, err)
×
2462
                        continue
×
2463
                }
2464
                if vip.Spec.Namespace != pod.Namespace || (vip.Status.V4ip == "" && vip.Status.V6ip == "") {
×
2465
                        continue
×
2466
                }
2467
                for _, podNet := range podNets {
×
2468
                        if podNet.Subnet.Name == vip.Spec.Subnet {
×
2469
                                key := fmt.Sprintf("%s.%s", podNet.Subnet.Name, podNet.ProviderName)
×
2470
                                vipsList := vipsListMap[key]
×
2471
                                if vipsList == nil {
×
2472
                                        vipsList = []string{}
×
2473
                                }
×
2474
                                // ipam will ensure the uniqueness of VIP
2475
                                if util.IsValidIP(vip.Status.V4ip) {
×
2476
                                        vipsList = append(vipsList, vip.Status.V4ip)
×
2477
                                }
×
2478
                                if util.IsValidIP(vip.Status.V6ip) {
×
2479
                                        vipsList = append(vipsList, vip.Status.V6ip)
×
2480
                                }
×
2481

2482
                                vipsListMap[key] = vipsList
×
2483
                        }
2484
                }
2485
        }
2486

2487
        for _, podNet := range podNets {
×
2488
                vipStr := pod.Annotations[fmt.Sprintf(util.PortVipAnnotationTemplate, podNet.ProviderName)]
×
2489
                if vipStr == "" {
×
2490
                        continue
×
2491
                }
2492
                key := fmt.Sprintf("%s.%s", podNet.Subnet.Name, podNet.ProviderName)
×
2493
                vipsList := vipsListMap[key]
×
2494
                if vipsList == nil {
×
2495
                        vipsList = []string{}
×
2496
                }
×
2497

2498
                for vip := range strings.SplitSeq(vipStr, ",") {
×
2499
                        if util.IsValidIP(vip) && !slices.Contains(vipsList, vip) {
×
2500
                                vipsList = append(vipsList, vip)
×
2501
                        }
×
2502
                }
2503

2504
                vipsListMap[key] = vipsList
×
2505
        }
2506

2507
        vipsMap := make(map[string]string)
×
2508
        for key, vipsList := range vipsListMap {
×
2509
                vipsMap[key] = strings.Join(vipsList, ",")
×
2510
        }
×
2511
        return vipsMap
×
2512
}
2513

2514
func setPodRoutesAnnotation(annotations map[string]string, provider string, routes []request.Route) error {
×
2515
        key := fmt.Sprintf(util.RoutesAnnotationTemplate, provider)
×
2516
        if len(routes) == 0 {
×
2517
                delete(annotations, key)
×
2518
                return nil
×
2519
        }
×
2520

2521
        buf, err := json.Marshal(routes)
×
2522
        if err != nil {
×
2523
                err = fmt.Errorf("failed to marshal routes %+v: %w", routes, err)
×
2524
                klog.Error(err)
×
2525
                return err
×
2526
        }
×
2527
        annotations[key] = string(buf)
×
2528

×
2529
        return nil
×
2530
}
2531

2532
// Check if pod is a VPC NAT gateway using pod annotations
2533
func (c *Controller) checkIsPodVpcNatGw(pod *v1.Pod) (bool, string) {
1✔
2534
        if pod == nil {
2✔
2535
                return false, ""
1✔
2536
        }
1✔
2537
        if pod.Annotations == nil {
2✔
2538
                return false, ""
1✔
2539
        }
1✔
2540
        // default provider
2541
        providerName := util.OvnProvider
1✔
2542
        // In non-primary CNI mode, we get the providers from the pod annotations
1✔
2543
        // We get the vpc nat gw name using the provider name
1✔
2544
        if c.config.EnableNonPrimaryCNI {
2✔
2545
                // get providers
1✔
2546
                providers, err := c.getPodProviders(pod)
1✔
2547
                if err != nil {
1✔
2548
                        klog.Errorf("failed to get pod %s/%s providers, %v", pod.Namespace, pod.Name, err)
×
2549
                        return false, ""
×
2550
                }
×
2551
                if len(providers) > 0 {
2✔
2552
                        // use the first provider
1✔
2553
                        providerName = providers[0]
1✔
2554
                }
1✔
2555
        }
2556
        vpcGwName, isVpcNatGw := pod.Annotations[fmt.Sprintf(util.VpcNatGatewayAnnotationTemplate, providerName)]
1✔
2557
        if isVpcNatGw {
2✔
2558
                if vpcGwName == "" {
2✔
2559
                        klog.Errorf("pod %s is vpc nat gateway but name is empty", pod.Name)
1✔
2560
                        return false, ""
1✔
2561
                }
1✔
2562
                klog.Infof("pod %s is vpc nat gateway %s", pod.Name, vpcGwName)
1✔
2563
        }
2564
        return isVpcNatGw, vpcGwName
1✔
2565
}
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