/
ovn.go
1426 lines (1285 loc) · 50.8 KB
/
ovn.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 ovn
import (
"bytes"
"context"
"encoding/json"
"fmt"
"math"
"net"
"reflect"
"strconv"
"sync"
"time"
nettypes "github.com/k8snetworkplumbingwg/network-attachment-definition-client/pkg/apis/k8s.cni.cncf.io/v1"
ocpcloudnetworkapi "github.com/openshift/api/cloudnetwork/v1"
libovsdbclient "github.com/ovn-org/libovsdb/client"
hocontroller "github.com/ovn-org/ovn-kubernetes/go-controller/hybrid-overlay/pkg/controller"
"github.com/ovn-org/ovn-kubernetes/go-controller/pkg/config"
egressipv1 "github.com/ovn-org/ovn-kubernetes/go-controller/pkg/crd/egressip/v1"
"github.com/ovn-org/ovn-kubernetes/go-controller/pkg/factory"
"github.com/ovn-org/ovn-kubernetes/go-controller/pkg/kube"
"github.com/ovn-org/ovn-kubernetes/go-controller/pkg/libovsdbops"
"github.com/ovn-org/ovn-kubernetes/go-controller/pkg/metrics"
"github.com/ovn-org/ovn-kubernetes/go-controller/pkg/nbdb"
addressset "github.com/ovn-org/ovn-kubernetes/go-controller/pkg/ovn/address_set"
svccontroller "github.com/ovn-org/ovn-kubernetes/go-controller/pkg/ovn/controller/services"
"github.com/ovn-org/ovn-kubernetes/go-controller/pkg/ovn/controller/unidling"
lsm "github.com/ovn-org/ovn-kubernetes/go-controller/pkg/ovn/logical_switch_manager"
"github.com/ovn-org/ovn-kubernetes/go-controller/pkg/ovn/subnetallocator"
ovntypes "github.com/ovn-org/ovn-kubernetes/go-controller/pkg/types"
"github.com/ovn-org/ovn-kubernetes/go-controller/pkg/util"
egressfirewall "github.com/ovn-org/ovn-kubernetes/go-controller/pkg/crd/egressfirewall/v1"
utilnet "k8s.io/utils/net"
kapi "k8s.io/api/core/v1"
kapisnetworking "k8s.io/api/networking/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/selection"
ktypes "k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/client-go/informers"
clientset "k8s.io/client-go/kubernetes"
"k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/tools/record"
ref "k8s.io/client-go/tools/reference"
"k8s.io/klog/v2"
)
const (
egressFirewallDNSDefaultDuration time.Duration = 30 * time.Minute
)
// ACL logging severity levels
type ACLLoggingLevels struct {
Allow string `json:"allow,omitempty"`
Deny string `json:"deny,omitempty"`
}
// namespaceInfo contains information related to a Namespace. Use oc.getNamespaceLocked()
// or oc.waitForNamespaceLocked() to get a locked namespaceInfo for a Namespace, and call
// nsInfo.Unlock() on it when you are done with it. (No code outside of the code that
// manages the oc.namespaces map is ever allowed to hold an unlocked namespaceInfo.)
type namespaceInfo struct {
sync.RWMutex
// addressSet is an address set object that holds the IP addresses
// of all pods in the namespace.
addressSet addressset.AddressSet
// map from NetworkPolicy name to networkPolicy. You must hold the
// namespaceInfo's mutex to add/delete/lookup policies, but must hold the
// networkPolicy's mutex (and not necessarily the namespaceInfo's) to work with
// the policy itself.
networkPolicies map[string]*networkPolicy
hybridOverlayExternalGW net.IP
hybridOverlayVTEP net.IP
// routingExternalGWs is a slice of net.IP containing the values parsed from
// annotation k8s.ovn.org/routing-external-gws
routingExternalGWs gatewayInfo
// routingExternalPodGWs contains a map of all pods serving as exgws as well as their
// exgw IPs
// key is <namespace>_<pod name>
routingExternalPodGWs map[string]gatewayInfo
multicastEnabled bool
// If not empty, then it has to be set to a logging a severity level, e.g. "notice", "alert", etc
aclLogging ACLLoggingLevels
// Per-namespace port group default deny UUIDs
portGroupIngressDenyName string // Port group Name for ingress deny rule
portGroupEgressDenyName string // Port group Name for egress deny rule
}
// Controller structure is the object which holds the controls for starting
// and reacting upon the watched resources (e.g. pods, endpoints)
type Controller struct {
client clientset.Interface
kube kube.Interface
watchFactory *factory.WatchFactory
egressFirewallHandler *factory.Handler
stopChan <-chan struct{}
// FIXME DUAL-STACK - Make IP Allocators more dual-stack friendly
masterSubnetAllocator *subnetallocator.SubnetAllocator
hoMaster *hocontroller.MasterController
SCTPSupport bool
// For TCP, UDP, and SCTP type traffic, cache OVN load-balancers used for the
// cluster's east-west traffic.
loadbalancerClusterCache map[kapi.Protocol]string
// A cache of all logical switches seen by the watcher and their subnets
lsManager *lsm.LogicalSwitchManager
// A cache of all logical ports known to the controller
logicalPortCache *portCache
// Info about known namespaces. You must use oc.getNamespaceLocked() or
// oc.waitForNamespaceLocked() to read this map, and oc.createNamespaceLocked()
// or oc.deleteNamespaceLocked() to modify it. namespacesMutex is only held
// from inside those functions.
namespaces map[string]*namespaceInfo
namespacesMutex sync.Mutex
externalGWCache map[ktypes.NamespacedName]*externalRouteInfo
exGWCacheMutex sync.RWMutex
// egressFirewalls is a map of namespaces and the egressFirewall attached to it
egressFirewalls sync.Map
// An address set factory that creates address sets
addressSetFactory addressset.AddressSetFactory
// For each logical port, the number of network policies that want
// to add a ingress deny rule.
lspIngressDenyCache map[string]int
// For each logical port, the number of network policies that want
// to add a egress deny rule.
lspEgressDenyCache map[string]int
// A mutex for lspIngressDenyCache and lspEgressDenyCache
lspMutex *sync.Mutex
// Supports multicast?
multicastSupport bool
// Cluster wide Load_Balancer_Group UUID.
loadBalancerGroupUUID string
// Controller used for programming OVN for egress IP
eIPC egressIPController
// Controller used to handle services
svcController *svccontroller.Controller
// svcFactory used to handle service related events
svcFactory informers.SharedInformerFactory
egressFirewallDNS *EgressDNS
// Is ACL logging enabled while configuring meters?
aclLoggingEnabled bool
joinSwIPManager *lsm.JoinSwitchIPManager
// event recorder used to post events to k8s
recorder record.EventRecorder
// libovsdb northbound client interface
nbClient libovsdbclient.Client
// libovsdb southbound client interface
sbClient libovsdbclient.Client
modelClient libovsdbops.ModelClient
// v4HostSubnetsUsed keeps track of number of v4 subnets currently assigned to nodes
v4HostSubnetsUsed float64
// v6HostSubnetsUsed keeps track of number of v6 subnets currently assigned to nodes
v6HostSubnetsUsed float64
// Map of pods that need to be retried, and the timestamp of when they last failed
// The key is a string which holds "namespace_podName"
retryPods map[string]*retryEntry
retryPodsLock sync.Mutex
// channel to indicate we need to retry pods immediately
retryPodsChan chan struct{}
// Map of network policies that need to be retried, and the timestamp of when they last failed
// keyed by namespace/name
retryNetPolices map[string]*retryNetPolEntry
retryNetPolLock sync.Mutex
// channel to indicate we need to retry policy immediately
retryPolicyChan chan struct{}
metricsRecorder *metrics.ControlPlaneRecorder
}
type retryEntry struct {
pod *kapi.Pod
timeStamp time.Time
backoffSec time.Duration
// whether to include this pod in retry iterations
ignore bool
// used to indicate if add events need to be retried
needsAdd bool
// used to indicate if delete event needs to be retried;
// this will hold a copy of its value from the oc.logicalSwitchPort cache
needsDel *lpInfo
}
type retryNetPolEntry struct {
newPolicy *kapisnetworking.NetworkPolicy
oldPolicy *kapisnetworking.NetworkPolicy
np *networkPolicy
timeStamp time.Time
backoffSec time.Duration
// whether to include this NP in retry iterations
ignore bool
}
const (
// TCP is the constant string for the string "TCP"
TCP = "TCP"
// UDP is the constant string for the string "UDP"
UDP = "UDP"
// SCTP is the constant string for the string "SCTP"
SCTP = "SCTP"
)
func GetIPFullMask(ip string) string {
const (
// IPv4FullMask is the maximum prefix mask for an IPv4 address
IPv4FullMask = "/32"
// IPv6FullMask is the maxiumum prefix mask for an IPv6 address
IPv6FullMask = "/128"
)
if utilnet.IsIPv6(net.ParseIP(ip)) {
return IPv6FullMask
}
return IPv4FullMask
}
// NewOvnController creates a new OVN controller for creating logical network
// infrastructure and policy
func NewOvnController(ovnClient *util.OVNClientset, wf *factory.WatchFactory, stopChan <-chan struct{}, addressSetFactory addressset.AddressSetFactory,
libovsdbOvnNBClient libovsdbclient.Client, libovsdbOvnSBClient libovsdbclient.Client,
recorder record.EventRecorder) *Controller {
if addressSetFactory == nil {
addressSetFactory = addressset.NewOvnAddressSetFactory(libovsdbOvnNBClient)
}
modelClient := libovsdbops.NewModelClient(libovsdbOvnNBClient)
svcController, svcFactory := newServiceController(ovnClient.KubeClient, libovsdbOvnNBClient)
return &Controller{
client: ovnClient.KubeClient,
kube: &kube.Kube{
KClient: ovnClient.KubeClient,
EIPClient: ovnClient.EgressIPClient,
EgressFirewallClient: ovnClient.EgressFirewallClient,
CloudNetworkClient: ovnClient.CloudNetworkClient,
},
watchFactory: wf,
stopChan: stopChan,
masterSubnetAllocator: subnetallocator.NewSubnetAllocator(),
lsManager: lsm.NewLogicalSwitchManager(),
logicalPortCache: newPortCache(stopChan),
namespaces: make(map[string]*namespaceInfo),
namespacesMutex: sync.Mutex{},
externalGWCache: make(map[ktypes.NamespacedName]*externalRouteInfo),
exGWCacheMutex: sync.RWMutex{},
addressSetFactory: addressSetFactory,
lspIngressDenyCache: make(map[string]int),
lspEgressDenyCache: make(map[string]int),
lspMutex: &sync.Mutex{},
eIPC: egressIPController{
egressIPAssignmentMutex: &sync.Mutex{},
podAssignmentMutex: &sync.Mutex{},
podAssignment: make(map[string]*podAssignmentState),
allocator: allocator{&sync.Mutex{}, make(map[string]*egressNode)},
nbClient: libovsdbOvnNBClient,
modelClient: modelClient,
watchFactory: wf,
},
loadbalancerClusterCache: make(map[kapi.Protocol]string),
multicastSupport: config.EnableMulticast,
loadBalancerGroupUUID: "",
aclLoggingEnabled: true,
joinSwIPManager: nil,
retryPods: make(map[string]*retryEntry),
retryPodsChan: make(chan struct{}, 1),
retryNetPolices: make(map[string]*retryNetPolEntry),
retryPolicyChan: make(chan struct{}, 1),
recorder: recorder,
nbClient: libovsdbOvnNBClient,
sbClient: libovsdbOvnSBClient,
svcController: svcController,
svcFactory: svcFactory,
modelClient: modelClient,
metricsRecorder: metrics.NewControlPlaneRecorder(),
}
}
// Run starts the actual watching.
func (oc *Controller) Run(wg *sync.WaitGroup, nodeName string) error {
// Start and sync the watch factory to begin listening for events
if err := oc.watchFactory.Start(); err != nil {
return err
}
oc.syncPeriodic()
klog.Infof("Starting all the Watchers...")
start := time.Now()
// Sync external gateway routes. External gateway may be set in namespaces
// or via pods. So execute an individual sync method at startup
oc.cleanExGwECMPRoutes()
// WatchNamespaces() should be started first because it has no other
// dependencies, and WatchNodes() depends on it
oc.WatchNamespaces()
// WatchNodes must be started next because it creates the node switch
// which most other watches depend on.
// https://github.com/ovn-org/ovn-kubernetes/pull/859
oc.WatchNodes()
// Start service watch factory and sync services
oc.svcFactory.Start(oc.stopChan)
// Services should be started after nodes to prevent LB churn
if err := oc.StartServiceController(wg, true); err != nil {
return err
}
oc.WatchPods()
// WatchNetworkPolicy depends on WatchPods and WatchNamespaces
oc.WatchNetworkPolicy()
if config.OVNKubernetesFeature.EnableEgressIP {
// This is probably the best starting order for all egress IP handlers.
// WatchEgressIPNamespaces and WatchEgressIPPods only use the informer
// cache to retrieve the egress IPs when determining if namespace/pods
// match. It is thus better if we initialize them first and allow
// WatchEgressNodes / WatchEgressIP to initialize after. Those handlers
// might change the assignments of the existing objects. If we do the
// inverse and start WatchEgressIPNamespaces / WatchEgressIPPod last, we
// risk performing a bunch of modifications on the EgressIP objects when
// we restart and then have these handlers act on stale data when they
// sync.
oc.WatchEgressIPNamespaces()
oc.WatchEgressIPPods()
oc.WatchEgressNodes()
oc.WatchEgressIP()
if util.PlatformTypeIsEgressIPCloudProvider() {
oc.WatchCloudPrivateIPConfig()
}
}
if config.OVNKubernetesFeature.EnableEgressFirewall {
var err error
oc.egressFirewallDNS, err = NewEgressDNS(oc.addressSetFactory, oc.stopChan)
if err != nil {
return err
}
oc.egressFirewallDNS.Run(egressFirewallDNSDefaultDuration)
oc.egressFirewallHandler = oc.WatchEgressFirewall()
}
klog.Infof("Completing all the Watchers took %v", time.Since(start))
if config.Kubernetes.OVNEmptyLbEvents {
klog.Infof("Starting unidling controller")
unidlingController, err := unidling.NewController(
oc.recorder,
oc.watchFactory.ServiceInformer(),
oc.sbClient,
)
if err != nil {
return err
}
wg.Add(1)
go func() {
defer wg.Done()
unidlingController.Run(oc.stopChan)
}()
}
if oc.hoMaster != nil {
wg.Add(1)
go func() {
defer wg.Done()
oc.hoMaster.Run(oc.stopChan)
}()
}
// Final step to cleanup after resource handlers have synced
err := oc.ovnTopologyCleanup()
if err != nil {
klog.Errorf("Failed to cleanup OVN topology to version %d: %v", ovntypes.OvnCurrentTopologyVersion, err)
return err
}
// Master is fully running and resource handlers have synced, update Topology version in OVN
currentTopologyVersion := strconv.Itoa(ovntypes.OvnCurrentTopologyVersion)
logicalRouterRes := []nbdb.LogicalRouter{}
ctx, cancel := context.WithTimeout(context.Background(), ovntypes.OVSDBTimeout)
defer cancel()
if err := oc.nbClient.WhereCache(func(lr *nbdb.LogicalRouter) bool {
return lr.Name == ovntypes.OVNClusterRouter
}).List(ctx, &logicalRouterRes); err != nil {
return fmt.Errorf("failed in retrieving %s, error: %v", ovntypes.OVNClusterRouter, err)
}
// Update topology version on distributed cluster router
logicalRouterRes[0].ExternalIDs["k8s-ovn-topo-version"] = currentTopologyVersion
logicalRouter := nbdb.LogicalRouter{
Name: ovntypes.OVNClusterRouter,
ExternalIDs: logicalRouterRes[0].ExternalIDs,
}
opModel := libovsdbops.OperationModel{
Name: logicalRouter.Name,
Model: &logicalRouter,
ModelPredicate: func(lr *nbdb.LogicalRouter) bool { return lr.Name == ovntypes.OVNClusterRouter },
OnModelUpdates: []interface{}{
&logicalRouter.ExternalIDs,
},
ErrNotFound: true,
}
if _, err := oc.modelClient.CreateOrUpdate(opModel); err != nil {
return fmt.Errorf("failed to generate set topology version in OVN, err: %v", err)
}
// Update topology version on node
node, err := oc.kube.GetNode(nodeName)
if err != nil {
return fmt.Errorf("unable to get node: %s", nodeName)
}
err = oc.kube.SetAnnotationsOnNode(node.Name, map[string]interface{}{ovntypes.OvnK8sTopoAnno: strconv.Itoa(ovntypes.OvnCurrentTopologyVersion)})
if err != nil {
return fmt.Errorf("failed to set topology annotation for node %s", node.Name)
}
return nil
}
func (oc *Controller) ovnTopologyCleanup() error {
ver, err := oc.determineOVNTopoVersionFromOVN()
if err != nil {
return err
}
// Cleanup address sets in non dual stack formats in all versions known to possibly exist.
if ver <= ovntypes.OvnPortBindingTopoVersion {
err = addressset.NonDualStackAddressSetCleanup(oc.nbClient)
}
return err
}
// determineOVNTopoVersionFromOVN determines what OVN Topology version is being used
// If "k8s-ovn-topo-version" key in external_ids column does not exist, it is prior to OVN topology versioning
// and therefore set version number to OvnCurrentTopologyVersion
func (oc *Controller) determineOVNTopoVersionFromOVN() (int, error) {
ver := 0
logicalRouterRes := []nbdb.LogicalRouter{}
ctx, cancel := context.WithTimeout(context.Background(), ovntypes.OVSDBTimeout)
defer cancel()
if err := oc.nbClient.WhereCache(func(lr *nbdb.LogicalRouter) bool {
return lr.Name == ovntypes.OVNClusterRouter
}).List(ctx, &logicalRouterRes); err != nil {
return ver, fmt.Errorf("failed in retrieving %s to determine the current version of OVN logical topology: "+
"error: %v", ovntypes.OVNClusterRouter, err)
}
if len(logicalRouterRes) == 0 {
// no OVNClusterRouter exists, DB is empty, nothing to upgrade
return math.MaxInt32, nil
}
v, exists := logicalRouterRes[0].ExternalIDs["k8s-ovn-topo-version"]
if !exists {
klog.Infof("No version string found. The OVN topology is before versioning is introduced. Upgrade needed")
return ver, nil
}
ver, err := strconv.Atoi(v)
if err != nil {
return 0, fmt.Errorf("invalid OVN topology version string for the cluster, err: %v", err)
}
return ver, nil
}
// syncPeriodic adds a goroutine that periodically does some work
// right now there is only one ticker registered
// for syncNodesPeriodic which deletes chassis records from the sbdb
// every 5 minutes
func (oc *Controller) syncPeriodic() {
go func() {
nodeSyncTicker := time.NewTicker(5 * time.Minute)
for {
select {
case <-nodeSyncTicker.C:
oc.syncNodesPeriodic()
case <-oc.stopChan:
return
}
}
}()
}
func (oc *Controller) recordPodEvent(addErr error, pod *kapi.Pod) {
podRef, err := ref.GetReference(scheme.Scheme, pod)
if err != nil {
klog.Errorf("Couldn't get a reference to pod %s/%s to post an event: '%v'",
pod.Namespace, pod.Name, err)
} else {
klog.V(5).Infof("Posting a %s event for Pod %s/%s", kapi.EventTypeWarning, pod.Namespace, pod.Name)
oc.recorder.Eventf(podRef, kapi.EventTypeWarning, "ErrorAddingLogicalPort", addErr.Error())
}
}
func exGatewayAnnotationsChanged(oldPod, newPod *kapi.Pod) bool {
return oldPod.Annotations[routingNamespaceAnnotation] != newPod.Annotations[routingNamespaceAnnotation] ||
oldPod.Annotations[routingNetworkAnnotation] != newPod.Annotations[routingNetworkAnnotation] ||
oldPod.Annotations[bfdAnnotation] != newPod.Annotations[bfdAnnotation]
}
func networkStatusAnnotationsChanged(oldPod, newPod *kapi.Pod) bool {
return oldPod.Annotations[nettypes.NetworkStatusAnnot] != newPod.Annotations[nettypes.NetworkStatusAnnot]
}
// ensurePod tries to set up a pod. It returns nil on success and error on failure; failure
// indicates the pod set up should be retried later.
func (oc *Controller) ensurePod(oldPod, pod *kapi.Pod, addPort bool) error {
// Try unscheduled pods later
if !util.PodScheduled(pod) {
return fmt.Errorf("failed to ensurePod %s/%s since it is not yet scheduled", pod.Namespace, pod.Name)
}
if oldPod != nil && (exGatewayAnnotationsChanged(oldPod, pod) || networkStatusAnnotationsChanged(oldPod, pod)) {
// No matter if a pod is ovn networked, or host networked, we still need to check for exgw
// annotations. If the pod is ovn networked and is in update reschedule, addLogicalPort will take
// care of updating the exgw updates
if err := oc.deletePodExternalGW(oldPod); err != nil {
return fmt.Errorf("ensurePod failed %s/%s: %w", pod.Namespace, pod.Name, err)
}
}
if util.PodWantsNetwork(pod) && addPort {
if err := oc.addLogicalPort(pod); err != nil {
return fmt.Errorf("addLogicalPort failed for %s/%s: %w", pod.Namespace, pod.Name, err)
}
} else {
// either pod is host-networked or its an update for a normal pod (addPort=false case)
if oldPod == nil || exGatewayAnnotationsChanged(oldPod, pod) || networkStatusAnnotationsChanged(oldPod, pod) {
if err := oc.addPodExternalGW(pod); err != nil {
return fmt.Errorf("addPodExternalGW failed for %s/%s: %w", pod.Namespace, pod.Name, err)
}
}
}
return nil
}
// removePod tried to tear down a pod. It returns nil on success and error on failure;
// failure indicates the pod tear down should be retried later.
func (oc *Controller) removePod(pod *kapi.Pod, portInfo *lpInfo) error {
if !util.PodWantsNetwork(pod) {
if err := oc.deletePodExternalGW(pod); err != nil {
return fmt.Errorf("unable to delete external gateway routes for pod %s: %w",
getPodNamespacedName(pod), err)
}
return nil
}
if err := oc.deleteLogicalPort(pod, portInfo); err != nil {
return fmt.Errorf("deleteLogicalPort failed for pod %s: %w",
getPodNamespacedName(pod), err)
}
return nil
}
// WatchPods starts the watching of Pod resource and calls back the appropriate handler logic
func (oc *Controller) WatchPods() {
go func() {
// track the retryPods map and every 30 seconds check if any pods need to be retried
for {
select {
case <-time.After(30 * time.Second):
oc.iterateRetryPods(false)
case <-oc.retryPodsChan:
oc.iterateRetryPods(true)
case <-oc.stopChan:
return
}
}
}()
start := time.Now()
oc.watchFactory.AddPodHandler(cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
pod := obj.(*kapi.Pod)
oc.metricsRecorder.AddPod(pod.UID)
oc.initRetryAddPod(pod)
oc.checkAndSkipRetryPod(pod)
if retryEntry := oc.getPodRetryEntry(pod); retryEntry != nil && retryEntry.needsDel != nil {
klog.Infof("Detected leftover old pod during new pod add with the same name: %s. "+
"Attempting deletion of leftover old...", getPodNamespacedName(pod))
if err := oc.removePod(pod, retryEntry.needsDel); err != nil {
oc.recordPodEvent(err, pod)
klog.Errorf("Failed to delete pod %s, error: %v",
getPodNamespacedName(pod), err)
oc.unSkipRetryPod(pod)
return
}
// deletion was a success; remove delete retry entry
oc.removeDeleteRetry(pod)
}
if err := oc.ensurePod(nil, pod, true); err != nil {
oc.recordPodEvent(err, pod)
klog.Errorf("Failed to add pod %s, error: %v",
getPodNamespacedName(pod), err)
oc.unSkipRetryPod(pod)
return
}
oc.checkAndDeleteRetryPod(pod)
},
UpdateFunc: func(old, newer interface{}) {
oldPod := old.(*kapi.Pod)
pod := newer.(*kapi.Pod)
// there may be a situation where this update event is not the latest
// and we rely on annotations to determine the pod mac/ifaddr
// this would create a situation where
// 1. addLogicalPort is executing with an older pod annotation, skips setting a new annotation
// 2. creates OVN logical port with old pod annotation value
// 3. CNI flows check fails and pod annotation does not match what is in OVN
// Therefore we need to get the latest version of this pod to attempt to addLogicalPort with
podName := pod.Name
podNs := pod.Namespace
pod, err := oc.watchFactory.GetPod(podNs, podName)
if err != nil {
klog.Warningf("Unable to get pod %s/%s for pod update, most likely it was already deleted",
podNs, podName)
return
}
oc.checkAndSkipRetryPod(pod)
if retryEntry := oc.getPodRetryEntry(pod); retryEntry != nil && retryEntry.needsDel != nil {
klog.Infof("Detected leftover old pod during new pod add with the same name: %s. "+
"Attempting deletion of leftover old...", getPodNamespacedName(pod))
if err := oc.removePod(pod, retryEntry.needsDel); err != nil {
oc.recordPodEvent(err, pod)
klog.Errorf("Failed to delete pod %s, error: %v",
getPodNamespacedName(pod), err)
oc.unSkipRetryPod(pod)
return
}
// deletion was a success; remove delete retry entry
oc.removeDeleteRetry(pod)
}
if err := oc.ensurePod(oldPod, pod, oc.checkAndSkipRetryPod(pod)); err != nil {
oc.recordPodEvent(err, pod)
klog.Errorf("Failed to update pod %s, error: %v",
getPodNamespacedName(pod), err)
oc.initRetryAddPod(pod)
// unskip failed pod for next retry iteration
oc.unSkipRetryPod(pod)
return
}
oc.checkAndDeleteRetryPod(pod)
},
DeleteFunc: func(obj interface{}) {
pod := obj.(*kapi.Pod)
oc.metricsRecorder.CleanPod(pod.UID)
oc.initRetryDelPod(pod)
// we have a copy of portInfo in the retry cache now, we can remove it from
// logicalPortCache so that we don't race with a new add pod that comes with
// the same name.
oc.logicalPortCache.remove(util.GetLogicalPortName(pod.Namespace, pod.Name))
retryEntry := oc.getPodRetryEntry(pod)
var portInfo *lpInfo
if retryEntry != nil {
// retryEntry shouldn't be nil since we usually add the pod to retryCache above
portInfo = retryEntry.needsDel
}
if err := oc.removePod(pod, portInfo); err != nil {
oc.recordPodEvent(err, pod)
klog.Errorf("Failed to delete pod %s, error: %v",
getPodNamespacedName(pod), err)
oc.unSkipRetryPod(pod)
return
}
oc.checkAndDeleteRetryPod(pod)
},
}, oc.syncPods)
klog.Infof("Bootstrapping existing pods and cleaning stale pods took %v", time.Since(start))
}
// WatchNetworkPolicy starts the watching of network policy resource and calls
// back the appropriate handler logic
func (oc *Controller) WatchNetworkPolicy() {
go func() {
// track the retryNetworkPolicies map and every 30 seconds check if any pods need to be retried
for {
select {
case <-time.After(30 * time.Second):
oc.iterateRetryNetworkPolicies(false)
case <-oc.retryPolicyChan:
oc.iterateRetryNetworkPolicies(true)
case <-oc.stopChan:
return
}
}
}()
start := time.Now()
oc.watchFactory.AddPolicyHandler(cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
policy := obj.(*kapisnetworking.NetworkPolicy)
oc.initRetryPolicy(policy)
oc.checkAndSkipRetryPolicy(policy)
// If there is a delete entry this is a network policy being added
// with the same name as a previous network policy that failed deletion.
// Destroy it first before we add the new policy.
if retryEntry := oc.getPolicyRetryEntry(policy); retryEntry != nil && retryEntry.oldPolicy != nil {
klog.Infof("Detected stale policy during new policy add with the same name: %s/%s",
policy.Namespace, policy.Name)
if err := oc.deleteNetworkPolicy(retryEntry.oldPolicy, nil); err != nil {
oc.unSkipRetryPolicy(policy)
klog.Errorf("Failed to delete stale network policy %s, during add: %v",
getPolicyNamespacedName(policy), err)
return
}
oc.removeDeleteFromRetryPolicy(policy)
}
start := time.Now()
if err := oc.addNetworkPolicy(policy); err != nil {
klog.Errorf("Failed to create network policy %s, error: %v",
getPolicyNamespacedName(policy), err)
oc.unSkipRetryPolicy(policy)
return
}
klog.Infof("Created Network Policy: %s took: %v", getPolicyNamespacedName(policy), time.Since(start))
oc.checkAndDeleteRetryPolicy(policy)
},
UpdateFunc: func(old, newer interface{}) {
oldPolicy := old.(*kapisnetworking.NetworkPolicy)
newPolicy := newer.(*kapisnetworking.NetworkPolicy)
if !reflect.DeepEqual(oldPolicy, newPolicy) {
oc.checkAndSkipRetryPolicy(oldPolicy)
// check if there was already a retry entry with an old policy
// else just look to delete the old policy in the update
if retryEntry := oc.getPolicyRetryEntry(oldPolicy); retryEntry != nil && retryEntry.oldPolicy != nil {
if err := oc.deleteNetworkPolicy(retryEntry.oldPolicy, nil); err != nil {
oc.initRetryPolicy(newPolicy)
oc.unSkipRetryPolicy(oldPolicy)
klog.Errorf("Failed to delete stale network policy %s, during update: %v",
getPolicyNamespacedName(oldPolicy), err)
return
}
} else if err := oc.deleteNetworkPolicy(oldPolicy, nil); err != nil {
oc.initRetryPolicyWithDelete(oldPolicy, nil)
oc.initRetryPolicy(newPolicy)
oc.unSkipRetryPolicy(oldPolicy)
klog.Errorf("Failed to delete network policy %s, during update: %v",
getPolicyNamespacedName(oldPolicy), err)
return
}
// remove the old policy from retry entry since it was correctly deleted
oc.removeDeleteFromRetryPolicy(oldPolicy)
if err := oc.addNetworkPolicy(newPolicy); err != nil {
oc.initRetryPolicy(newPolicy)
oc.unSkipRetryPolicy(newPolicy)
klog.Errorf("Failed to create network policy %s, during update: %v",
getPolicyNamespacedName(newPolicy), err)
return
}
oc.checkAndDeleteRetryPolicy(newPolicy)
}
},
DeleteFunc: func(obj interface{}) {
policy := obj.(*kapisnetworking.NetworkPolicy)
oc.checkAndSkipRetryPolicy(policy)
oc.initRetryPolicyWithDelete(policy, nil)
if err := oc.deleteNetworkPolicy(policy, nil); err != nil {
oc.unSkipRetryPolicy(policy)
klog.Errorf("Failed to delete network policy %s, error: %v", getPolicyNamespacedName(policy), err)
return
}
oc.checkAndDeleteRetryPolicy(policy)
},
}, oc.syncNetworkPolicies)
klog.Infof("Bootstrapping existing policies and cleaning stale policies took %v", time.Since(start))
}
// WatchEgressFirewall starts the watching of egressfirewall resource and calls
// back the appropriate handler logic
func (oc *Controller) WatchEgressFirewall() *factory.Handler {
return oc.watchFactory.AddEgressFirewallHandler(cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
egressFirewall := obj.(*egressfirewall.EgressFirewall).DeepCopy()
addErrors := oc.addEgressFirewall(egressFirewall)
if addErrors != nil {
klog.Error(addErrors)
egressFirewall.Status.Status = egressFirewallAddError
} else {
egressFirewall.Status.Status = egressFirewallAppliedCorrectly
}
err := oc.updateEgressFirewallWithRetry(egressFirewall)
if err != nil {
klog.Error(err)
}
metrics.UpdateEgressFirewallRuleCount(float64(len(egressFirewall.Spec.Egress)))
metrics.IncrementEgressFirewallCount()
},
UpdateFunc: func(old, newer interface{}) {
newEgressFirewall := newer.(*egressfirewall.EgressFirewall).DeepCopy()
oldEgressFirewall := old.(*egressfirewall.EgressFirewall)
if !reflect.DeepEqual(oldEgressFirewall.Spec, newEgressFirewall.Spec) {
errList := oc.updateEgressFirewall(oldEgressFirewall, newEgressFirewall)
if errList != nil {
newEgressFirewall.Status.Status = egressFirewallUpdateError
klog.Error(errList)
} else {
newEgressFirewall.Status.Status = egressFirewallAppliedCorrectly
}
err := oc.updateEgressFirewallWithRetry(newEgressFirewall)
if err != nil {
klog.Error(err)
}
metrics.UpdateEgressFirewallRuleCount(float64(len(newEgressFirewall.Spec.Egress) - len(oldEgressFirewall.Spec.Egress)))
}
},
DeleteFunc: func(obj interface{}) {
egressFirewall := obj.(*egressfirewall.EgressFirewall)
deleteErrors := oc.deleteEgressFirewall(egressFirewall)
if deleteErrors != nil {
klog.Error(deleteErrors)
return
}
metrics.UpdateEgressFirewallRuleCount(float64(-len(egressFirewall.Spec.Egress)))
metrics.DecrementEgressFirewallCount()
},
}, oc.syncEgressFirewall)
}
// WatchEgressNodes starts the watching of egress assignable nodes and calls
// back the appropriate handler logic.
func (oc *Controller) WatchEgressNodes() {
nodeEgressLabel := util.GetNodeEgressLabel()
oc.watchFactory.AddNodeHandler(cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
node := obj.(*kapi.Node)
if err := oc.addNodeForEgress(node); err != nil {
klog.Error(err)
}
nodeLabels := node.GetLabels()
_, hasEgressLabel := nodeLabels[nodeEgressLabel]
if hasEgressLabel {
oc.setNodeEgressAssignable(node.Name, true)
}
isReady := oc.isEgressNodeReady(node)
if isReady {
oc.setNodeEgressReady(node.Name, true)
}
isReachable := oc.isEgressNodeReachable(node)
if isReachable {
oc.setNodeEgressReachable(node.Name, true)
}
if hasEgressLabel && isReachable && isReady {
if err := oc.addEgressNode(node); err != nil {
klog.Error(err)
}
}
},
UpdateFunc: func(old, new interface{}) {
oldNode := old.(*kapi.Node)
newNode := new.(*kapi.Node)
// Initialize the allocator on every update,
// ovnkube-node/cloud-network-config-controller will make sure to
// annotate the node with the egressIPConfig, but that might have
// happened after we processed the ADD for that object, hence keep
// retrying for all UPDATEs.
if err := oc.initEgressIPAllocator(newNode); err != nil {
klog.V(5).Infof("Egress node initialization error: %v", err)
}
oldLabels := oldNode.GetLabels()
newLabels := newNode.GetLabels()
_, oldHadEgressLabel := oldLabels[nodeEgressLabel]
_, newHasEgressLabel := newLabels[nodeEgressLabel]
// If the node is not labelled for egress assignment, just return
// directly, we don't really need to set the ready / reachable
// status on this node if the user doesn't care about using it.
if !oldHadEgressLabel && !newHasEgressLabel {
return
}
if oldHadEgressLabel && !newHasEgressLabel {
klog.Infof("Node: %s has been un-labelled, deleting it from egress assignment", newNode.Name)
oc.setNodeEgressAssignable(oldNode.Name, false)
if err := oc.deleteEgressNode(oldNode); err != nil {
klog.Error(err)
}
return
}
isOldReady := oc.isEgressNodeReady(oldNode)
isNewReady := oc.isEgressNodeReady(newNode)
isNewReachable := oc.isEgressNodeReachable(newNode)
oc.setNodeEgressReady(newNode.Name, isNewReady)
oc.setNodeEgressReachable(newNode.Name, isNewReachable)
if !oldHadEgressLabel && newHasEgressLabel {
klog.Infof("Node: %s has been labelled, adding it for egress assignment", newNode.Name)
oc.setNodeEgressAssignable(newNode.Name, true)
if isNewReady && isNewReachable {
if err := oc.addEgressNode(newNode); err != nil {
klog.Error(err)
}
} else {
klog.Warningf("Node: %s has been labelled, but node is not ready and reachable, cannot use it for egress assignment", newNode.Name)
}
return
}
if isOldReady == isNewReady {
return
}
if !isNewReady {
klog.Warningf("Node: %s is not ready, deleting it from egress assignment", newNode.Name)
if err := oc.deleteEgressNode(newNode); err != nil {
klog.Error(err)
}
} else if isNewReady && isNewReachable {
klog.Infof("Node: %s is ready and reachable, adding it for egress assignment", newNode.Name)
if err := oc.addEgressNode(newNode); err != nil {
klog.Error(err)
}
}
},
DeleteFunc: func(obj interface{}) {
node := obj.(*kapi.Node)
if err := oc.deleteNodeForEgress(node); err != nil {
klog.Error(err)
}
nodeLabels := node.GetLabels()
if _, hasEgressLabel := nodeLabels[nodeEgressLabel]; hasEgressLabel {
if err := oc.deleteEgressNode(node); err != nil {
klog.Error(err)
}
}
},
}, oc.initClusterEgressPolicies)
}
// WatchCloudPrivateIPConfig starts the watching of cloudprivateipconfigs
// resource and calls back the appropriate handler logic.
func (oc *Controller) WatchCloudPrivateIPConfig() {
oc.watchFactory.AddCloudPrivateIPConfigHandler(cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
cloudPrivateIPConfig := obj.(*ocpcloudnetworkapi.CloudPrivateIPConfig)
if err := oc.reconcileCloudPrivateIPConfig(nil, cloudPrivateIPConfig); err != nil {
klog.Errorf("Unable to add CloudPrivateIPConfig: %s, err: %v", cloudPrivateIPConfig.Name, err)
}
},
UpdateFunc: func(old, new interface{}) {
oldCloudPrivateIPConfig := old.(*ocpcloudnetworkapi.CloudPrivateIPConfig)
newCloudPrivateIPConfig := new.(*ocpcloudnetworkapi.CloudPrivateIPConfig)
if err := oc.reconcileCloudPrivateIPConfig(oldCloudPrivateIPConfig, newCloudPrivateIPConfig); err != nil {
klog.Errorf("Unable to update CloudPrivateIPConfig: %s, err: %v", newCloudPrivateIPConfig.Name, err)
}
},
DeleteFunc: func(obj interface{}) {
cloudPrivateIPConfig := obj.(*ocpcloudnetworkapi.CloudPrivateIPConfig)
if err := oc.reconcileCloudPrivateIPConfig(cloudPrivateIPConfig, nil); err != nil {
klog.Errorf("Unable to delete CloudPrivateIPConfig: %s, err: %v", cloudPrivateIPConfig.Name, err)
}
},
}, nil)
}
// WatchEgressIP starts the watching of egressip resource and calls back the
// appropriate handler logic. It also initiates the other dedicated resource
// handlers for egress IP setup: namespaces, pods.
func (oc *Controller) WatchEgressIP() {
oc.watchFactory.AddEgressIPHandler(cache.ResourceEventHandlerFuncs{