-
Notifications
You must be signed in to change notification settings - Fork 443
/
pod.go
1961 lines (1762 loc) · 59.6 KB
/
pod.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package controller
import (
"context"
"encoding/json"
"fmt"
"net"
"reflect"
"strconv"
"strings"
"sync"
"time"
"github.com/scylladb/go-set/strset"
"gopkg.in/k8snetworkplumbingwg/multus-cni.v4/pkg/logging"
multustypes "gopkg.in/k8snetworkplumbingwg/multus-cni.v4/pkg/types"
v1 "k8s.io/api/core/v1"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/types"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/cache"
"k8s.io/klog/v2"
kubeovnv1 "github.com/kubeovn/kube-ovn/pkg/apis/kubeovn/v1"
"github.com/kubeovn/kube-ovn/pkg/ipam"
"github.com/kubeovn/kube-ovn/pkg/ovs"
"github.com/kubeovn/kube-ovn/pkg/ovsdb/ovnnb"
"github.com/kubeovn/kube-ovn/pkg/util"
)
type NamedPort struct {
mutex sync.RWMutex
// first key is namespace, second key is portName
namedPortMap map[string]map[string]*util.NamedPortInfo
}
func NewNamedPort() *NamedPort {
return &NamedPort{
mutex: sync.RWMutex{},
namedPortMap: map[string]map[string]*util.NamedPortInfo{},
}
}
func (n *NamedPort) AddNamedPortByPod(pod *v1.Pod) {
n.mutex.Lock()
defer n.mutex.Unlock()
ns := pod.Namespace
podName := pod.Name
if pod.Spec.Containers == nil {
return
}
for _, container := range pod.Spec.Containers {
if container.Ports == nil {
continue
}
for _, port := range container.Ports {
if port.Name == "" || port.ContainerPort == 0 {
continue
}
if _, ok := n.namedPortMap[ns]; ok {
if _, ok := n.namedPortMap[ns][port.Name]; ok {
if n.namedPortMap[ns][port.Name].PortID == port.ContainerPort {
n.namedPortMap[ns][port.Name].Pods.Add(podName)
} else {
klog.Warningf("named port %s has already be defined with portID %d",
port.Name, n.namedPortMap[ns][port.Name].PortID)
}
continue
}
} else {
n.namedPortMap[ns] = make(map[string]*util.NamedPortInfo)
}
n.namedPortMap[ns][port.Name] = &util.NamedPortInfo{
PortID: port.ContainerPort,
Pods: strset.New(podName),
}
}
}
}
func (n *NamedPort) DeleteNamedPortByPod(pod *v1.Pod) {
n.mutex.Lock()
defer n.mutex.Unlock()
ns := pod.Namespace
podName := pod.Name
if pod.Spec.Containers == nil {
return
}
for _, container := range pod.Spec.Containers {
if container.Ports == nil {
continue
}
for _, port := range container.Ports {
if port.Name == "" {
continue
}
if _, ok := n.namedPortMap[ns]; !ok {
continue
}
if _, ok := n.namedPortMap[ns][port.Name]; !ok {
continue
}
if !n.namedPortMap[ns][port.Name].Pods.Has(podName) {
continue
}
n.namedPortMap[ns][port.Name].Pods.Remove(podName)
if n.namedPortMap[ns][port.Name].Pods.Size() == 0 {
delete(n.namedPortMap[ns], port.Name)
if len(n.namedPortMap[ns]) == 0 {
delete(n.namedPortMap, ns)
}
}
}
}
}
func (n *NamedPort) GetNamedPortByNs(namespace string) map[string]*util.NamedPortInfo {
n.mutex.RLock()
defer n.mutex.RUnlock()
if result, ok := n.namedPortMap[namespace]; ok {
for portName, info := range result {
klog.Infof("namespace %s's namedPort portname is %s with info %v ", namespace, portName, info)
}
return result
}
return nil
}
func isPodAlive(p *v1.Pod) bool {
if p.DeletionTimestamp != nil && p.DeletionGracePeriodSeconds != nil {
now := time.Now()
deletionTime := p.DeletionTimestamp.Time
gracePeriod := time.Duration(*p.DeletionGracePeriodSeconds) * time.Second
if now.After(deletionTime.Add(gracePeriod)) {
return false
}
}
return isPodStatusPhaseAlive(p)
}
func isPodStatusPhaseAlive(p *v1.Pod) bool {
if p.Status.Phase == v1.PodSucceeded && p.Spec.RestartPolicy != v1.RestartPolicyAlways {
return false
}
if p.Status.Phase == v1.PodFailed && p.Spec.RestartPolicy == v1.RestartPolicyNever {
return false
}
if p.Status.Phase == v1.PodFailed && p.Status.Reason == "Evicted" {
return false
}
return true
}
func (c *Controller) enqueueAddPod(obj interface{}) {
var key string
var err error
if key, err = cache.MetaNamespaceKeyFunc(obj); err != nil {
utilruntime.HandleError(err)
return
}
p := obj.(*v1.Pod)
// TODO: we need to find a way to reduce duplicated np added to the queue
if c.config.EnableNP {
c.namedPort.AddNamedPortByPod(p)
if p.Status.PodIP != "" {
for _, np := range c.podMatchNetworkPolicies(p) {
c.updateNpQueue.Add(np)
}
}
}
if p.Spec.HostNetwork {
return
}
if !isPodAlive(p) {
isStateful, statefulSetName := isStatefulSetPod(p)
isVMPod, vmName := isVMPod(p)
if isStateful || (isVMPod && c.config.EnableKeepVMIP) {
if isStateful && isStatefulSetPodToDel(c.config.KubeClient, p, statefulSetName) {
klog.V(3).Infof("enqueue delete pod %s", key)
c.deletingPodObjMap.Store(key, p)
c.deletePodQueue.Add(key)
}
if isVMPod && c.isVMToDel(p, vmName) {
klog.V(3).Infof("enqueue delete pod %s", key)
c.deletingPodObjMap.Store(key, p)
c.deletePodQueue.Add(key)
}
} else {
klog.V(3).Infof("enqueue delete pod %s", key)
c.deletingPodObjMap.Store(key, p)
c.deletePodQueue.Add(key)
}
return
}
need, err := c.podNeedSync(p)
if err != nil {
klog.Errorf("invalid pod net: %v", err)
return
}
if need {
klog.Infof("enqueue add pod %s", key)
c.addOrUpdatePodQueue.Add(key)
}
}
func (c *Controller) enqueueDeletePod(obj interface{}) {
var key string
var err error
if key, err = cache.MetaNamespaceKeyFunc(obj); err != nil {
utilruntime.HandleError(err)
return
}
p := obj.(*v1.Pod)
if c.config.EnableNP {
c.namedPort.DeleteNamedPortByPod(p)
for _, np := range c.podMatchNetworkPolicies(p) {
c.updateNpQueue.Add(np)
}
}
if p.Spec.HostNetwork {
return
}
klog.Infof("enqueue delete pod %s", key)
c.deletingPodObjMap.Store(key, p)
c.deletePodQueue.Add(key)
}
func (c *Controller) enqueueUpdatePod(oldObj, newObj interface{}) {
oldPod := oldObj.(*v1.Pod)
newPod := newObj.(*v1.Pod)
if oldPod.ResourceVersion == newPod.ResourceVersion {
return
}
key, err := cache.MetaNamespaceKeyFunc(newObj)
if err != nil {
utilruntime.HandleError(err)
return
}
podNets, err := c.getPodKubeovnNets(newPod)
if err != nil {
klog.Errorf("failed to get newPod nets %v", err)
return
}
if c.config.EnableNP {
c.namedPort.AddNamedPortByPod(newPod)
newNp := c.podMatchNetworkPolicies(newPod)
if !reflect.DeepEqual(oldPod.Labels, newPod.Labels) {
oldNp := c.podMatchNetworkPolicies(oldPod)
for _, np := range util.DiffStringSlice(oldNp, newNp) {
c.updateNpQueue.Add(np)
}
}
for _, podNet := range podNets {
oldAllocated := oldPod.Annotations[fmt.Sprintf(util.AllocatedAnnotationTemplate, podNet.ProviderName)]
newAllocated := newPod.Annotations[fmt.Sprintf(util.AllocatedAnnotationTemplate, podNet.ProviderName)]
if oldAllocated != newAllocated {
for _, np := range newNp {
klog.V(3).Infof("enqueue update network policy %s for pod %s", np, key)
c.updateNpQueue.Add(np)
}
break
}
}
}
if newPod.Spec.HostNetwork {
return
}
isStateful, statefulSetName := isStatefulSetPod(newPod)
isVMPod, vmName := isVMPod(newPod)
if !isPodStatusPhaseAlive(newPod) && !isStateful && !isVMPod {
klog.V(3).Infof("enqueue delete pod %s", key)
c.deletingPodObjMap.Store(key, newPod)
c.deletePodQueue.Add(key)
return
}
// enqueue delay
var delay time.Duration
if newPod.Spec.TerminationGracePeriodSeconds != nil {
if newPod.DeletionTimestamp != nil {
delay = time.Until(newPod.DeletionTimestamp.Add(time.Duration(*newPod.Spec.TerminationGracePeriodSeconds) * time.Second))
} else {
delay = time.Duration(*newPod.Spec.TerminationGracePeriodSeconds) * time.Second
}
}
if newPod.DeletionTimestamp != nil && !isStateful && !isVMPod {
go func() {
// In case node get lost and pod can not be deleted,
// the ip address will not be recycled
klog.V(3).Infof("enqueue delete pod %s after %v", key, delay)
c.deletingPodObjMap.Store(key, newPod)
c.deletePodQueue.AddAfter(key, delay)
}()
return
}
// do not delete statefulset pod unless ownerReferences is deleted
if isStateful && isStatefulSetPodToDel(c.config.KubeClient, newPod, statefulSetName) {
go func() {
klog.V(3).Infof("enqueue delete pod %s after %v", key, delay)
c.deletingPodObjMap.Store(key, newPod)
c.deletePodQueue.AddAfter(key, delay)
}()
return
}
if isVMPod && c.isVMToDel(newPod, vmName) {
go func() {
klog.V(3).Infof("enqueue delete pod %s after %v", key, delay)
c.deletingPodObjMap.Store(key, newPod)
c.deletePodQueue.AddAfter(key, delay)
}()
return
}
klog.Infof("enqueue update pod %s", key)
c.addOrUpdatePodQueue.Add(key)
// security policy changed
for _, podNet := range podNets {
oldSecurity := oldPod.Annotations[fmt.Sprintf(util.PortSecurityAnnotationTemplate, podNet.ProviderName)]
newSecurity := newPod.Annotations[fmt.Sprintf(util.PortSecurityAnnotationTemplate, podNet.ProviderName)]
oldSg := oldPod.Annotations[fmt.Sprintf(util.SecurityGroupAnnotationTemplate, podNet.ProviderName)]
newSg := newPod.Annotations[fmt.Sprintf(util.SecurityGroupAnnotationTemplate, podNet.ProviderName)]
oldVips := oldPod.Annotations[fmt.Sprintf(util.PortVipAnnotationTemplate, podNet.ProviderName)]
newVips := newPod.Annotations[fmt.Sprintf(util.PortVipAnnotationTemplate, podNet.ProviderName)]
if oldSecurity != newSecurity || oldSg != newSg || oldVips != newVips {
c.updatePodSecurityQueue.Add(key)
break
}
}
}
func (c *Controller) runAddOrUpdatePodWorker() {
for c.processNextAddOrUpdatePodWorkItem() {
}
}
func (c *Controller) runDeletePodWorker() {
for c.processNextDeletePodWorkItem() {
}
}
func (c *Controller) runUpdatePodSecurityWorker() {
for c.processNextUpdatePodSecurityWorkItem() {
}
}
func (c *Controller) processNextAddOrUpdatePodWorkItem() bool {
obj, shutdown := c.addOrUpdatePodQueue.Get()
if shutdown {
return false
}
now := time.Now()
err := func(obj interface{}) error {
defer c.addOrUpdatePodQueue.Done(obj)
var key string
var ok bool
if key, ok = obj.(string); !ok {
c.addOrUpdatePodQueue.Forget(obj)
utilruntime.HandleError(fmt.Errorf("expected string in workqueue but got %#v", obj))
return nil
}
if err := c.handleAddOrUpdatePod(key); err != nil {
c.addOrUpdatePodQueue.AddRateLimited(key)
return fmt.Errorf("error syncing '%s': %s, requeuing", key, err.Error())
}
last := time.Since(now)
klog.Infof("take %d ms to handle sync pod %s", last.Milliseconds(), key)
c.addOrUpdatePodQueue.Forget(obj)
return nil
}(obj)
if err != nil {
utilruntime.HandleError(err)
return true
}
return true
}
func (c *Controller) processNextDeletePodWorkItem() bool {
obj, shutdown := c.deletePodQueue.Get()
if shutdown {
return false
}
now := time.Now()
err := func(obj interface{}) error {
defer c.deletePodQueue.Done(obj)
var key string
var ok bool
if key, ok = obj.(string); !ok {
c.deletePodQueue.Forget(obj)
utilruntime.HandleError(fmt.Errorf("expected string in workqueue but got %#v", obj))
return nil
}
if _, ok := c.deletingPodObjMap.Load(key); !ok {
return nil
}
if err := c.handleDeletePod(key); err != nil {
c.deletePodQueue.AddRateLimited(key)
return fmt.Errorf("error syncing '%s': %s, requeuing", key, err.Error())
}
c.deletePodQueue.Forget(obj)
last := time.Since(now)
klog.Infof("take %d ms to handle delete pod %s", last.Milliseconds(), key)
// gc pod obj in c.deletingPodObjMap
go func() {
time.Sleep(5 * time.Minute)
c.deletingPodObjMap.Delete(key)
}()
return nil
}(obj)
if err != nil {
utilruntime.HandleError(err)
return true
}
return true
}
func (c *Controller) processNextUpdatePodSecurityWorkItem() bool {
obj, shutdown := c.updatePodSecurityQueue.Get()
if shutdown {
return false
}
err := func(obj interface{}) error {
defer c.updatePodSecurityQueue.Done(obj)
var key string
var ok bool
if key, ok = obj.(string); !ok {
c.updatePodSecurityQueue.Forget(obj)
utilruntime.HandleError(fmt.Errorf("expected string in workqueue but got %#v", obj))
return nil
}
if err := c.handleUpdatePodSecurity(key); err != nil {
c.updatePodSecurityQueue.AddRateLimited(key)
return fmt.Errorf("error syncing '%s': %s, requeuing", key, err.Error())
}
c.updatePodSecurityQueue.Forget(obj)
return nil
}(obj)
if err != nil {
utilruntime.HandleError(err)
return true
}
return true
}
func (c *Controller) getPodKubeovnNets(pod *v1.Pod) ([]*kubeovnNet, error) {
defaultSubnet, err := c.getPodDefaultSubnet(pod)
if err != nil {
klog.Error(err)
return nil, err
}
attachmentNets, err := c.getPodAttachmentNet(pod)
if err != nil {
klog.Error(err)
return nil, err
}
podNets := attachmentNets
if _, hasOtherDefaultNet := pod.Annotations[util.DefaultNetworkAnnotation]; !hasOtherDefaultNet {
podNets = append(attachmentNets, &kubeovnNet{
Type: providerTypeOriginal,
ProviderName: util.OvnProvider,
Subnet: defaultSubnet,
IsDefault: true,
})
}
return podNets, nil
}
func (c *Controller) changeVMSubnet(vmName, namespace, providerName, subnetName string) error {
ipName := ovs.PodNameToPortName(vmName, namespace, providerName)
ipCr, err := c.ipsLister.Get(ipName)
if err != nil {
if k8serrors.IsNotFound(err) {
return nil
}
err := fmt.Errorf("failed to get ip CR %s: %v", ipName, err)
klog.Error(err)
return err
}
if ipCr.Spec.Subnet != subnetName {
key := fmt.Sprintf("%s/%s", namespace, vmName)
klog.Infof("release ipam for vm %s from old subnet %s", key, ipCr.Spec.Subnet)
c.ipam.ReleaseAddressByPod(key, ipCr.Spec.Subnet)
klog.Infof("gc logical switch port %s", key)
if err := c.OVNNbClient.DeleteLogicalSwitchPort(key); err != nil {
klog.Errorf("failed to delete lsp %s, %v", key, err)
return err
}
// old lsp has been deleted, delete old ip cr
if err := c.config.KubeOvnClient.KubeovnV1().IPs().Delete(context.Background(), ipName, metav1.DeleteOptions{}); err != nil {
if !k8serrors.IsNotFound(err) {
klog.Errorf("failed to delete ip %s, %v", ipName, err)
return err
}
}
// handleAddOrUpdatePod will create new lsp and new ip cr
}
return nil
}
func (c *Controller) handleAddOrUpdatePod(key string) (err error) {
namespace, name, err := cache.SplitMetaNamespaceKey(key)
if err != nil {
utilruntime.HandleError(fmt.Errorf("invalid resource key: %s", key))
return nil
}
c.podKeyMutex.LockKey(key)
defer func() { _ = c.podKeyMutex.UnlockKey(key) }()
klog.Infof("handle add/update pod %s", key)
cachedPod, err := c.podsLister.Pods(namespace).Get(name)
if err != nil {
if k8serrors.IsNotFound(err) {
return nil
}
klog.Error(err)
return err
}
pod := cachedPod.DeepCopy()
if err := util.ValidatePodNetwork(pod.Annotations); err != nil {
klog.Errorf("validate pod %s/%s failed: %v", namespace, name, err)
c.recorder.Eventf(pod, v1.EventTypeWarning, "ValidatePodNetworkFailed", err.Error())
return err
}
podNets, err := c.getPodKubeovnNets(pod)
if err != nil {
klog.Errorf("failed to get pod nets %v", err)
return err
}
if len(pod.Annotations) == 0 {
pod.Annotations = map[string]string{}
}
// check and do hotnoplug nic
if cachedPod, err = c.syncKubeOvnNet(cachedPod, pod, podNets); err != nil {
klog.Errorf("failed to sync pod nets %v", err)
return err
}
if cachedPod == nil {
// pod has been deleted
return nil
}
pod = cachedPod.DeepCopy()
// check if allocate subnet is need. also allocate subnet when hotplug nic
needAllocatePodNets := needAllocateSubnets(pod, podNets)
if len(needAllocatePodNets) != 0 {
if cachedPod, err = c.reconcileAllocateSubnets(cachedPod, pod, needAllocatePodNets); err != nil {
return err
}
if cachedPod == nil {
// pod has been deleted
return nil
}
}
// check if route subnet is need.
pod = cachedPod.DeepCopy()
return c.reconcileRouteSubnets(cachedPod, pod, needRouteSubnets(pod, podNets))
}
// do the same thing as add pod
func (c *Controller) reconcileAllocateSubnets(cachedPod, pod *v1.Pod, needAllocatePodNets []*kubeovnNet) (*v1.Pod, error) {
namespace := pod.Namespace
name := pod.Name
klog.Infof("sync pod %s/%s allocated", namespace, name)
isVMPod, vmName := isVMPod(pod)
podType := getPodType(pod)
podName := c.getNameByPod(pod)
// todo: isVmPod, getPodType, getNameByPod has duplicated logic
// Avoid create lsp for already running pod in ovn-nb when controller restart
for _, podNet := range needAllocatePodNets {
// the subnet may changed when alloc static ip from the latter subnet after ns supports multi subnets
v4IP, v6IP, mac, subnet, err := c.acquireAddress(pod, podNet)
if err != nil {
c.recorder.Eventf(pod, v1.EventTypeWarning, "AcquireAddressFailed", err.Error())
klog.Error(err)
return nil, err
}
ipStr := util.GetStringIP(v4IP, v6IP)
pod.Annotations[fmt.Sprintf(util.IPAddressAnnotationTemplate, podNet.ProviderName)] = ipStr
if mac == "" {
delete(pod.Annotations, fmt.Sprintf(util.MacAddressAnnotationTemplate, podNet.ProviderName))
} else {
pod.Annotations[fmt.Sprintf(util.MacAddressAnnotationTemplate, podNet.ProviderName)] = mac
}
pod.Annotations[fmt.Sprintf(util.CidrAnnotationTemplate, podNet.ProviderName)] = subnet.Spec.CIDRBlock
pod.Annotations[fmt.Sprintf(util.GatewayAnnotationTemplate, podNet.ProviderName)] = subnet.Spec.Gateway
if isOvnSubnet(podNet.Subnet) {
pod.Annotations[fmt.Sprintf(util.LogicalSwitchAnnotationTemplate, podNet.ProviderName)] = subnet.Name
if pod.Annotations[fmt.Sprintf(util.PodNicAnnotationTemplate, podNet.ProviderName)] == "" {
pod.Annotations[fmt.Sprintf(util.PodNicAnnotationTemplate, podNet.ProviderName)] = c.config.PodNicType
}
} else {
delete(pod.Annotations, fmt.Sprintf(util.LogicalSwitchAnnotationTemplate, podNet.ProviderName))
delete(pod.Annotations, fmt.Sprintf(util.PodNicAnnotationTemplate, podNet.ProviderName))
}
pod.Annotations[fmt.Sprintf(util.AllocatedAnnotationTemplate, podNet.ProviderName)] = "true"
if isVMPod && c.config.EnableKeepVMIP {
pod.Annotations[fmt.Sprintf(util.VMAnnotationTemplate, podNet.ProviderName)] = vmName
if err := c.changeVMSubnet(vmName, namespace, podNet.ProviderName, subnet.Name); err != nil {
klog.Errorf("change subnet of pod %s/%s to %s failed: %v", namespace, name, subnet.Name, err)
return nil, err
}
}
if err := util.ValidatePodCidr(podNet.Subnet.Spec.CIDRBlock, ipStr); err != nil {
klog.Errorf("validate pod %s/%s failed: %v", namespace, name, err)
c.recorder.Eventf(pod, v1.EventTypeWarning, "ValidatePodNetworkFailed", err.Error())
return nil, err
}
if podNet.Type != providerTypeIPAM {
if (subnet.Spec.Vlan == "" || subnet.Spec.LogicalGateway || subnet.Spec.U2OInterconnection) && subnet.Spec.Vpc != "" {
pod.Annotations[fmt.Sprintf(util.LogicalRouterAnnotationTemplate, podNet.ProviderName)] = subnet.Spec.Vpc
}
if subnet.Spec.Vlan != "" {
vlan, err := c.vlansLister.Get(subnet.Spec.Vlan)
if err != nil {
klog.Error(err)
c.recorder.Eventf(pod, v1.EventTypeWarning, "GetVlanInfoFailed", err.Error())
return nil, err
}
pod.Annotations[fmt.Sprintf(util.VlanIDAnnotationTemplate, podNet.ProviderName)] = strconv.Itoa(vlan.Spec.ID)
pod.Annotations[fmt.Sprintf(util.ProviderNetworkTemplate, podNet.ProviderName)] = vlan.Spec.Provider
}
portSecurity := false
if pod.Annotations[fmt.Sprintf(util.PortSecurityAnnotationTemplate, podNet.ProviderName)] == "true" {
portSecurity = true
}
vips := pod.Annotations[fmt.Sprintf(util.PortVipAnnotationTemplate, podNet.ProviderName)]
for _, ip := range strings.Split(vips, ",") {
if ip != "" && net.ParseIP(ip) == nil {
klog.Errorf("invalid vip address '%s' for pod %s", ip, name)
vips = ""
break
}
}
portName := ovs.PodNameToPortName(podName, namespace, podNet.ProviderName)
dhcpOptions := &ovs.DHCPOptionsUUIDs{
DHCPv4OptionsUUID: subnet.Status.DHCPv4OptionsUUID,
DHCPv6OptionsUUID: subnet.Status.DHCPv6OptionsUUID,
}
securityGroupAnnotation := pod.Annotations[fmt.Sprintf(util.SecurityGroupAnnotationTemplate, podNet.ProviderName)]
securityGroups := strings.ReplaceAll(securityGroupAnnotation, " ", "")
if err := c.OVNNbClient.CreateLogicalSwitchPort(subnet.Name, portName, ipStr, mac, podName, pod.Namespace,
portSecurity, securityGroupAnnotation, vips, podNet.Subnet.Spec.EnableDHCP, dhcpOptions, subnet.Spec.Vpc); err != nil {
c.recorder.Eventf(pod, v1.EventTypeWarning, "CreateOVNPortFailed", err.Error())
klog.Errorf("%v", err)
return nil, err
}
if pod.Annotations[fmt.Sprintf(util.Layer2ForwardAnnotationTemplate, podNet.ProviderName)] == "true" {
if err := c.OVNNbClient.EnablePortLayer2forward(portName); err != nil {
c.recorder.Eventf(pod, v1.EventTypeWarning, "SetOVNPortL2ForwardFailed", err.Error())
klog.Errorf("%v", err)
return nil, err
}
}
if securityGroupAnnotation != "" {
sgNames := strings.Split(securityGroups, ",")
for _, sgName := range sgNames {
if sgName != "" {
c.syncSgPortsQueue.Add(sgName)
}
}
}
if vips != "" {
c.syncVirtualPortsQueue.Add(podNet.Subnet.Name)
}
}
// CreatePort may fail, so put ip cr creation after CreatePort
if err := c.createOrUpdateCrdIPs(podName, ipStr, mac, subnet.Name, pod.Namespace, pod.Spec.NodeName, podNet.ProviderName, podType); err != nil {
err = fmt.Errorf("failed to create ips CR %s.%s: %v", podName, pod.Namespace, err)
klog.Error(err)
return nil, err
}
}
patch, err := util.GenerateMergePatchPayload(cachedPod, pod)
if err != nil {
klog.Errorf("failed to generate patch for pod %s/%s: %v", name, namespace, err)
return nil, err
}
patchedPod, err := c.config.KubeClient.CoreV1().Pods(namespace).Patch(context.Background(), name,
types.MergePatchType, patch, metav1.PatchOptions{}, "")
if err != nil {
if k8serrors.IsNotFound(err) {
// Sometimes pod is deleted between kube-ovn configure ovn-nb and patch pod.
// Then we need to recycle the resource again.
key := strings.Join([]string{namespace, name}, "/")
c.deletingPodObjMap.Store(key, pod)
c.deletePodQueue.AddRateLimited(key)
return nil, nil
}
klog.Errorf("patch pod %s/%s failed: %v", name, namespace, err)
return nil, err
}
if vpcGwName, isVpcNatGw := pod.Annotations[util.VpcNatGatewayAnnotation]; isVpcNatGw {
c.initVpcNatGatewayQueue.Add(vpcGwName)
}
return patchedPod.DeepCopy(), nil
}
// do the same thing as update pod
func (c *Controller) reconcileRouteSubnets(cachedPod, pod *v1.Pod, needRoutePodNets []*kubeovnNet) error {
if len(needRoutePodNets) == 0 {
return nil
}
namespace := pod.Namespace
name := pod.Name
podName := c.getNameByPod(pod)
klog.Infof("sync pod %s/%s routed", namespace, name)
var podIP string
var subnet *kubeovnv1.Subnet
for _, podNet := range needRoutePodNets {
// in case update handler overlap the annotation when cache is not in sync
if pod.Annotations[fmt.Sprintf(util.AllocatedAnnotationTemplate, podNet.ProviderName)] == "" {
return fmt.Errorf("no address has been allocated to %s/%s", namespace, name)
}
podIP = pod.Annotations[fmt.Sprintf(util.IPAddressAnnotationTemplate, podNet.ProviderName)]
subnet = podNet.Subnet
if podIP != "" && (subnet.Spec.Vlan == "" || subnet.Spec.LogicalGateway) && subnet.Spec.Vpc == c.config.ClusterRouter {
node, err := c.nodesLister.Get(pod.Spec.NodeName)
if err != nil {
klog.Errorf("failed to get node %s: %v", pod.Spec.NodeName, err)
return err
}
pgName := getOverlaySubnetsPortGroupName(subnet.Name, node.Name)
if c.config.EnableEipSnat && (pod.Annotations[util.EipAnnotation] != "" || pod.Annotations[util.SnatAnnotation] != "") {
cm, err := c.configMapsLister.ConfigMaps(c.config.ExternalGatewayConfigNS).Get(util.ExternalGatewayConfig)
if err != nil {
klog.Errorf("failed to get ex-gateway config, %v", err)
return err
}
nextHop := cm.Data["external-gw-addr"]
if nextHop == "" {
externalSubnet, err := c.subnetsLister.Get(c.config.ExternalGatewaySwitch)
if err != nil {
klog.Errorf("failed to get subnet %s, %v", c.config.ExternalGatewaySwitch, err)
return err
}
nextHop = externalSubnet.Spec.Gateway
if nextHop == "" {
klog.Errorf("no available gateway address")
return fmt.Errorf("no available gateway address")
}
}
if strings.Contains(nextHop, "/") {
nextHop = strings.Split(nextHop, "/")[0]
}
if err := c.addStaticRouteToVpc(
c.config.ClusterRouter,
&kubeovnv1.StaticRoute{
Policy: kubeovnv1.PolicySrc,
CIDR: podIP,
NextHopIP: nextHop,
RouteTable: subnet.Spec.RouteTable,
},
); err != nil {
klog.Errorf("failed to add static route, %v", err)
return err
}
// remove lsp from port group to make EIP/SNAT work
portName := ovs.PodNameToPortName(podName, pod.Namespace, podNet.ProviderName)
if err = c.OVNNbClient.PortGroupRemovePorts(pgName, portName); err != nil {
return err
}
} else {
if subnet.Spec.GatewayType == kubeovnv1.GWDistributedType && pod.Annotations[util.NorthGatewayAnnotation] == "" {
nodeTunlIPAddr, err := getNodeTunlIP(node)
if err != nil {
klog.Error(err)
return err
}
var added bool
for _, nodeAddr := range nodeTunlIPAddr {
for _, podAddr := range strings.Split(podIP, ",") {
if util.CheckProtocol(nodeAddr.String()) != util.CheckProtocol(podAddr) {
continue
}
portName := ovs.PodNameToPortName(podName, pod.Namespace, podNet.ProviderName)
if err := c.OVNNbClient.PortGroupAddPorts(pgName, portName); err != nil {
klog.Errorf("add port to port group %s: %v", pgName, err)
return err
}
added = true
break
}
if added {
break
}
}
}
if pod.Annotations[util.NorthGatewayAnnotation] != "" {
if err := c.addStaticRouteToVpc(
subnet.Spec.RouteTable,
&kubeovnv1.StaticRoute{
Policy: kubeovnv1.PolicySrc,
CIDR: podIP,
NextHopIP: pod.Annotations[util.NorthGatewayAnnotation],
RouteTable: subnet.Spec.RouteTable,
},
); err != nil {
klog.Errorf("failed to add static route, %v", err)
return err
}
} else if c.config.EnableEipSnat {
if err = c.deleteStaticRouteFromVpc(
c.config.ClusterRouter,
subnet.Spec.RouteTable,
podIP,
"",
kubeovnv1.PolicyDst,
); err != nil {
return err
}
}
}
if c.config.EnableEipSnat {
for _, ipStr := range strings.Split(podIP, ",") {
if eip := pod.Annotations[util.EipAnnotation]; eip == "" {
if err = c.OVNNbClient.DeleteNats(c.config.ClusterRouter, ovnnb.NATTypeDNATAndSNAT, ipStr); err != nil {
klog.Errorf("failed to delete nat rules: %v", err)
}
} else if util.CheckProtocol(eip) == util.CheckProtocol(ipStr) {
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 {
klog.Errorf("failed to add nat rules, %v", err)
return err
}
}
if eip := pod.Annotations[util.SnatAnnotation]; eip == "" {
if err = c.OVNNbClient.DeleteNats(c.config.ClusterRouter, ovnnb.NATTypeSNAT, ipStr); err != nil {
klog.Errorf("failed to delete nat rules: %v", err)
}
} else if util.CheckProtocol(eip) == util.CheckProtocol(ipStr) {
if err = c.OVNNbClient.UpdateSnat(c.config.ClusterRouter, eip, ipStr); err != nil {
klog.Errorf("failed to add nat rules, %v", err)
return err
}
}
}
}
}
pod.Annotations[fmt.Sprintf(util.RoutedAnnotationTemplate, podNet.ProviderName)] = "true"
}
patch, err := util.GenerateMergePatchPayload(cachedPod, pod)
if err != nil {
klog.Errorf("failed to generate patch for pod %s/%s: %v", name, namespace, err)
return err
}
if _, err := c.config.KubeClient.CoreV1().Pods(namespace).Patch(context.Background(), name,
types.MergePatchType, patch, metav1.PatchOptions{}, ""); err != nil {
if k8serrors.IsNotFound(err) {
// Sometimes pod is deleted between kube-ovn configure ovn-nb and patch pod.
// Then we need to recycle the resource again.
key := strings.Join([]string{namespace, name}, "/")
c.deletingPodObjMap.Store(key, pod)
c.deletePodQueue.AddRateLimited(key)
return nil
}
klog.Errorf("patch pod %s/%s failed %v", name, namespace, err)
return err
}
return nil
}
func (c *Controller) handleDeletePod(key string) error {
podObj, ok := c.deletingPodObjMap.Load(key)
if !ok {
return nil
}
pod := podObj.(*v1.Pod)
podName := c.getNameByPod(pod)
c.podKeyMutex.LockKey(key)
defer func() { _ = c.podKeyMutex.UnlockKey(key) }()
klog.Infof("handle delete pod %s", key)
p, _ := c.podsLister.Pods(pod.Namespace).Get(pod.Name)
if p != nil && p.UID != pod.UID {
// Pod with same name exists, just return here
return nil
}
podKey := fmt.Sprintf("%s/%s", pod.Namespace, podName)
var keepIPCR bool
if ok, sts := isStatefulSetPod(pod); ok {
toDel := isStatefulSetPodToDel(c.config.KubeClient, pod, sts)
isDelete, err := appendCheckPodToDel(c, pod, sts, "StatefulSet")
if pod.DeletionTimestamp != nil {
// triggered by delete event
if !(toDel || (isDelete && err == nil)) {
return nil
}
}
keepIPCR = !toDel && !isDelete && err == nil
}
isVMPod, vmName := isVMPod(pod)
if isVMPod && c.config.EnableKeepVMIP {
vmToBeDel := c.isVMToDel(pod, vmName)
isDelete, err := appendCheckPodToDel(c, pod, vmName, util.VMInstance)
if pod.DeletionTimestamp != nil {
// triggered by delete event
if !(vmToBeDel || (isDelete && err == nil)) {
return nil
}
klog.Infof("delete vm pod %s", podName)
}
}
podNets, err := c.getPodKubeovnNets(pod)
if err != nil {
klog.Errorf("failed to get pod nets %v", err)
}
if !keepIPCR {
ports, err := c.OVNNbClient.ListNormalLogicalSwitchPorts(true, map[string]string{"pod": podKey})
if err != nil {
klog.Errorf("failed to list lsps of pod '%s', %v", pod.Name, err)
return err
}
if len(ports) != 0 {
addresses := c.ipam.GetPodAddress(podKey)
for _, address := range addresses {
if strings.TrimSpace(address.IP) == "" {
continue
}
subnet, err := c.subnetsLister.Get(address.Subnet.Name)
if k8serrors.IsNotFound(err) {
continue
} else if err != nil {
klog.Error(err)
return err