-
Notifications
You must be signed in to change notification settings - Fork 348
/
egressqos.go
1113 lines (957 loc) · 34.2 KB
/
egressqos.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 (
"context"
"fmt"
"net"
"strings"
"sync"
"time"
"github.com/ovn-org/libovsdb/ovsdb"
"github.com/ovn-org/ovn-kubernetes/go-controller/pkg/config"
egressqosapi "github.com/ovn-org/ovn-kubernetes/go-controller/pkg/crd/egressqos/v1"
v1 "github.com/ovn-org/ovn-kubernetes/go-controller/pkg/crd/egressqos/v1"
egressqosapply "github.com/ovn-org/ovn-kubernetes/go-controller/pkg/crd/egressqos/v1/apis/applyconfiguration/egressqos/v1"
egressqosinformer "github.com/ovn-org/ovn-kubernetes/go-controller/pkg/crd/egressqos/v1/apis/informers/externalversions/egressqos/v1"
"github.com/ovn-org/ovn-kubernetes/go-controller/pkg/factory"
libovsdbops "github.com/ovn-org/ovn-kubernetes/go-controller/pkg/libovsdb/ops"
"github.com/ovn-org/ovn-kubernetes/go-controller/pkg/nbdb"
addressset "github.com/ovn-org/ovn-kubernetes/go-controller/pkg/ovn/address_set"
"github.com/ovn-org/ovn-kubernetes/go-controller/pkg/types"
"github.com/ovn-org/ovn-kubernetes/go-controller/pkg/util"
"github.com/pkg/errors"
kapi "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/apimachinery/pkg/util/wait"
v1coreinformers "k8s.io/client-go/informers/core/v1"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/util/workqueue"
"k8s.io/klog/v2"
utilnet "k8s.io/utils/net"
)
const (
defaultEgressQoSName = "default"
EgressQoSFlowStartPriority = 1000
egressQoSAppliedCorrectly = "EgressQoS Rules applied"
egressQoSReadyStatusType = "Ready-In-Zone-"
egressQoSReadyReason = "SetupSucceeded"
egressQoSNotReadyReason = "SetupFailed"
)
var maxEgressQoSRetries = 10
type egressQoS struct {
sync.RWMutex
name string
namespace string
rules []*egressQoSRule
stale bool
}
type egressQoSRule struct {
priority int
dscp int
destination string
addrSet addressset.AddressSet
pods *sync.Map // pods name -> ips in the addrSet
podSelector metav1.LabelSelector
}
func getEgressQosAddrSetDbIDs(namespace, priority, controller string) *libovsdbops.DbObjectIDs {
return libovsdbops.NewDbObjectIDs(libovsdbops.AddressSetEgressQoS, controller, map[libovsdbops.ExternalIDKey]string{
libovsdbops.ObjectNameKey: namespace,
// priority is the unique id for address set within given namespace
libovsdbops.PriorityKey: priority,
})
}
// shallow copies the EgressQoS object provided.
func (oc *DefaultNetworkController) cloneEgressQoS(raw *egressqosapi.EgressQoS) (*egressQoS, error) {
eq := &egressQoS{
name: raw.Name,
namespace: raw.Namespace,
rules: make([]*egressQoSRule, 0),
}
if len(raw.Spec.Egress) > EgressQoSFlowStartPriority {
return nil, fmt.Errorf("cannot create EgressQoS with %d rules - maximum is %d", len(raw.Spec.Egress), EgressQoSFlowStartPriority)
}
addErrors := errors.New("")
for i, rule := range raw.Spec.Egress {
eqr, err := oc.cloneEgressQoSRule(rule, EgressQoSFlowStartPriority-i)
if err != nil {
dst := "any"
if rule.DstCIDR != nil {
dst = *rule.DstCIDR
}
addErrors = errors.Wrapf(addErrors, "error: cannot create egressqos Rule to destination %s for namespace %s - %v",
dst, eq.namespace, err)
continue
}
eq.rules = append(eq.rules, eqr)
}
if addErrors.Error() == "" {
addErrors = nil
}
return eq, addErrors
}
// shallow copies the EgressQoSRule object provided.
func (oc *DefaultNetworkController) cloneEgressQoSRule(raw egressqosapi.EgressQoSRule, priority int) (*egressQoSRule, error) {
dst := ""
if raw.DstCIDR != nil {
_, _, err := net.ParseCIDR(*raw.DstCIDR)
if err != nil {
return nil, err
}
dst = *raw.DstCIDR
}
_, err := metav1.LabelSelectorAsSelector(&raw.PodSelector)
if err != nil {
return nil, err
}
eqr := &egressQoSRule{
priority: priority,
dscp: raw.DSCP,
destination: dst,
podSelector: raw.PodSelector,
}
return eqr, nil
}
func (oc *DefaultNetworkController) createASForEgressQoSRule(podSelector metav1.LabelSelector, namespace string, priority int) (addressset.AddressSet, *sync.Map, error) {
var addrSet addressset.AddressSet
selector, err := metav1.LabelSelectorAsSelector(&podSelector)
if err != nil {
return nil, nil, err
}
if selector.Empty() { // empty selector means that the rule applies to all pods in the namespace
asIndex := getNamespaceAddrSetDbIDs(namespace, oc.controllerName)
addrSet, err := oc.addressSetFactory.EnsureAddressSet(asIndex)
if err != nil {
return nil, nil, fmt.Errorf("cannot ensure that addressSet for namespace %s exists %v", namespace, err)
}
return addrSet, &sync.Map{}, nil
}
podsCache := sync.Map{}
pods, err := oc.watchFactory.GetPodsBySelector(namespace, podSelector)
if err != nil {
return nil, nil, err
}
asIndex := getEgressQosAddrSetDbIDs(namespace, fmt.Sprintf("%d", priority), oc.controllerName)
addrSet, err = oc.addressSetFactory.EnsureAddressSet(asIndex)
if err != nil {
return nil, nil, err
}
podsIps := []net.IP{}
for _, pod := range pods {
// we don't handle HostNetworked or completed pods or not-scheduled pods or remote-zone pods
if !util.PodWantsHostNetwork(pod) && !util.PodCompleted(pod) && util.PodScheduled(pod) && oc.isPodScheduledinLocalZone(pod) {
podIPs, err := util.GetPodIPsOfNetwork(pod, oc.NetInfo)
if err != nil && !errors.Is(err, util.ErrNoPodIPFound) {
return nil, nil, err
}
podsCache.Store(pod.Name, podIPs)
podsIps = append(podsIps, podIPs...)
}
}
err = addrSet.SetAddresses(util.StringSlice(podsIps))
if err != nil {
return nil, nil, err
}
return addrSet, &podsCache, nil
}
// initEgressQoSController initializes the EgressQoS controller.
func (oc *DefaultNetworkController) initEgressQoSController(
eqInformer egressqosinformer.EgressQoSInformer,
podInformer v1coreinformers.PodInformer,
nodeInformer v1coreinformers.NodeInformer) error {
klog.Info("Setting up event handlers for EgressQoS")
oc.egressQoSLister = eqInformer.Lister()
oc.egressQoSSynced = eqInformer.Informer().HasSynced
oc.egressQoSQueue = workqueue.NewNamedRateLimitingQueue(
workqueue.NewItemFastSlowRateLimiter(1*time.Second, 5*time.Second, 5),
"egressqos",
)
_, err := eqInformer.Informer().AddEventHandler(factory.WithUpdateHandlingForObjReplace(cache.ResourceEventHandlerFuncs{
AddFunc: oc.onEgressQoSAdd,
UpdateFunc: oc.onEgressQoSUpdate,
DeleteFunc: oc.onEgressQoSDelete,
}))
if err != nil {
return fmt.Errorf("could not add Event Handler for eqInformer during egressqosController initialization, %w", err)
}
oc.egressQoSPodLister = podInformer.Lister()
oc.egressQoSPodSynced = podInformer.Informer().HasSynced
oc.egressQoSPodQueue = workqueue.NewNamedRateLimitingQueue(
workqueue.NewItemFastSlowRateLimiter(1*time.Second, 5*time.Second, 5),
"egressqospods",
)
_, err = podInformer.Informer().AddEventHandler(factory.WithUpdateHandlingForObjReplace(cache.ResourceEventHandlerFuncs{
AddFunc: oc.onEgressQoSPodAdd,
UpdateFunc: oc.onEgressQoSPodUpdate,
DeleteFunc: oc.onEgressQoSPodDelete,
}))
if err != nil {
return fmt.Errorf("could not add Event Handler for podInformer during egressqosController initialization, %w", err)
}
oc.egressQoSNodeLister = nodeInformer.Lister()
oc.egressQoSNodeSynced = nodeInformer.Informer().HasSynced
oc.egressQoSNodeQueue = workqueue.NewNamedRateLimitingQueue(
workqueue.NewItemFastSlowRateLimiter(1*time.Second, 5*time.Second, 5),
"egressqosnodes",
)
_, err = nodeInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: oc.onEgressQoSNodeAdd, // we only care about new logical switches being added
UpdateFunc: oc.onEgressQoSNodeUpdate, // we care about node's zone changes so that if add event didn't do anything update can take care of it
DeleteFunc: func(obj interface{}) {},
})
if err != nil {
return fmt.Errorf("could not add Event Handler for nodeInformer during egressqosController initialization, %w", err)
}
return nil
}
func (oc *DefaultNetworkController) runEgressQoSController(wg *sync.WaitGroup, threadiness int, stopCh <-chan struct{}) error {
defer utilruntime.HandleCrash()
klog.Infof("Starting EgressQoS Controller")
if !util.WaitForInformerCacheSyncWithTimeout("egressqosnodes", stopCh, oc.egressQoSNodeSynced) {
return fmt.Errorf("timed out waiting for egress QoS node caches to sync")
}
if !util.WaitForInformerCacheSyncWithTimeout("egressqospods", stopCh, oc.egressQoSPodSynced) {
return fmt.Errorf("timed out waiting for egress QoS pods caches to sync")
}
if !util.WaitForInformerCacheSyncWithTimeout("egressqos", stopCh, oc.egressQoSSynced) {
return fmt.Errorf("timed out waiting for egress QoS caches to sync")
}
klog.Infof("Repairing EgressQoSes")
err := oc.repairEgressQoSes()
if err != nil {
return fmt.Errorf("failed to delete stale EgressQoS entries: %v", err)
}
for i := 0; i < threadiness; i++ {
wg.Add(1)
go func() {
defer wg.Done()
wait.Until(func() {
oc.runEgressQoSWorker(wg)
}, time.Second, stopCh)
}()
}
for i := 0; i < threadiness; i++ {
wg.Add(1)
go func() {
defer wg.Done()
wait.Until(func() {
oc.runEgressQoSPodWorker(wg)
}, time.Second, stopCh)
}()
}
for i := 0; i < threadiness; i++ {
wg.Add(1)
go func() {
defer wg.Done()
wait.Until(func() {
oc.runEgressQoSNodeWorker(wg)
}, time.Second, stopCh)
}()
}
// add shutdown goroutine waiting for stopCh
wg.Add(1)
go func() {
defer wg.Done()
// wait until we're told to stop
<-stopCh
klog.Infof("Shutting down EgressQoS controller")
oc.egressQoSQueue.ShutDown()
oc.egressQoSPodQueue.ShutDown()
oc.egressQoSNodeQueue.ShutDown()
}()
return nil
}
// onEgressQoSAdd queues the EgressQoS for processing.
func (oc *DefaultNetworkController) onEgressQoSAdd(obj interface{}) {
key, err := cache.MetaNamespaceKeyFunc(obj)
if err != nil {
utilruntime.HandleError(fmt.Errorf("couldn't get key for object %+v: %v", obj, err))
return
}
oc.egressQoSQueue.Add(key)
}
// onEgressQoSUpdate queues the EgressQoS for processing.
func (oc *DefaultNetworkController) onEgressQoSUpdate(oldObj, newObj interface{}) {
oldEQ := oldObj.(*egressqosapi.EgressQoS)
newEQ := newObj.(*egressqosapi.EgressQoS)
if oldEQ.ResourceVersion == newEQ.ResourceVersion ||
!newEQ.GetDeletionTimestamp().IsZero() {
return
}
key, err := cache.MetaNamespaceKeyFunc(newObj)
if err == nil {
oc.egressQoSQueue.Add(key)
}
}
// onEgressQoSDelete queues the EgressQoS for processing.
func (oc *DefaultNetworkController) onEgressQoSDelete(obj interface{}) {
key, err := cache.MetaNamespaceKeyFunc(obj)
if err != nil {
utilruntime.HandleError(fmt.Errorf("couldn't get key for object %+v: %v", obj, err))
return
}
oc.egressQoSQueue.Add(key)
}
func (oc *DefaultNetworkController) runEgressQoSWorker(wg *sync.WaitGroup) {
for oc.processNextEgressQoSWorkItem(wg) {
}
}
func (oc *DefaultNetworkController) processNextEgressQoSWorkItem(wg *sync.WaitGroup) bool {
wg.Add(1)
defer wg.Done()
key, quit := oc.egressQoSQueue.Get()
if quit {
return false
}
defer oc.egressQoSQueue.Done(key)
eqKey := key.(string)
eq, err := oc.getEgressQoS(eqKey)
if err != nil {
utilruntime.HandleError(fmt.Errorf("failed to retrieve %s qos object: %v", eqKey, err))
oc.egressQoSQueue.Forget(key)
return true
}
err = oc.syncEgressQoS(eqKey, eq)
if err == nil {
oc.egressQoSQueue.Forget(key)
if err = oc.updateEgressQoSZoneStatusToReady(eq); err != nil {
utilruntime.HandleError(fmt.Errorf("failed to update EgressQoS object %s with status: %v", eqKey, err))
}
return true
}
utilruntime.HandleError(fmt.Errorf("%v failed with : %v", key, err))
if oc.egressQoSQueue.NumRequeues(key) < maxEgressQoSRetries {
oc.egressQoSQueue.AddRateLimited(key)
return true
}
if err = oc.updateEgressQoSZoneStatusToNotReady(eq, err); err != nil {
utilruntime.HandleError(fmt.Errorf("failed to update EgressQoS object %s with status: %v", eqKey, err))
}
oc.egressQoSQueue.Forget(key)
return true
}
// This takes care of syncing stale data which we might have in OVN if
// there's no ovnkube-master running for a while.
// It deletes all QoSes and Address Sets from OVN that belong to deleted EgressQoSes.
func (oc *DefaultNetworkController) repairEgressQoSes() error {
startTime := time.Now()
klog.V(4).Infof("Starting repairing loop for egressqos")
defer func() {
klog.V(4).Infof("Finished repairing loop for egressqos: %v", time.Since(startTime))
}()
existing, err := oc.egressQoSLister.List(labels.Everything())
if err != nil {
return err
}
nsWithQoS := map[string]bool{}
for _, q := range existing {
nsWithQoS[q.Namespace] = true
}
p := func(q *nbdb.QoS) bool {
ns, ok := q.ExternalIDs["EgressQoS"]
if !ok {
return false
}
return !nsWithQoS[ns]
}
existingQoSes, err := libovsdbops.FindQoSesWithPredicate(oc.nbClient, p)
if err != nil {
return err
}
if len(existingQoSes) > 0 {
allOps := []ovsdb.Operation{}
logicalSwitches, err := oc.egressQoSSwitches()
if err != nil {
return err
}
for _, sw := range logicalSwitches {
ops, err := libovsdbops.RemoveQoSesFromLogicalSwitchOps(oc.nbClient, nil, sw, existingQoSes...)
if err != nil {
return err
}
allOps = append(allOps, ops...)
}
if _, err := libovsdbops.TransactAndCheck(oc.nbClient, allOps); err != nil {
return fmt.Errorf("unable to remove stale qoses, err: %v", err)
}
}
predicateIDs := libovsdbops.NewDbObjectIDs(libovsdbops.AddressSetEgressQoS, oc.controllerName, nil)
predicateFunc := func(as *nbdb.AddressSet) bool {
// ObjectNameKey is namespace
return !nsWithQoS[as.ExternalIDs[libovsdbops.ObjectNameKey.String()]]
}
asPredicate := libovsdbops.GetPredicate[*nbdb.AddressSet](predicateIDs, predicateFunc)
if err := libovsdbops.DeleteAddressSetsWithPredicate(oc.nbClient, asPredicate); err != nil {
return fmt.Errorf("failed to remove stale egress qos address sets, err: %v", err)
}
return nil
}
func (oc *DefaultNetworkController) syncEgressQoS(key string, eq *v1.EgressQoS) error {
startTime := time.Now()
namespace, name, err := cache.SplitMetaNamespaceKey(key)
if err != nil {
return err
}
klog.Infof("Processing sync for EgressQoS %s/%s", namespace, name)
defer func() {
klog.V(4).Infof("Finished syncing EgressQoS %s on namespace %s : %v", name, namespace, time.Since(startTime))
}()
if name != defaultEgressQoSName {
klog.Errorf("EgressQoS name %s is invalid, must be %s", name, defaultEgressQoSName)
return nil // Return nil to avoid requeues
}
// TODO: we should reconcile better by cleaning and creating in one transaction.
// that should minimize the window of lost DSCP markings on packets.
err = oc.cleanEgressQoSNS(namespace)
if err != nil {
return fmt.Errorf("unable to delete EgressQoS %s/%s, err: %v", namespace, name, err)
}
if eq == nil { // it was deleted no need to process further
return nil
}
klog.V(5).Infof("EgressQoS %s retrieved from lister: %v", eq.Name, eq)
return oc.addEgressQoS(eq)
}
func (oc *DefaultNetworkController) getEgressQoS(key string) (*v1.EgressQoS, error) {
namespace, name, err := cache.SplitMetaNamespaceKey(key)
if err != nil {
return nil, err
}
var eq *v1.EgressQoS
eq, err = oc.egressQoSLister.EgressQoSes(namespace).Get(name)
if err != nil && !apierrors.IsNotFound(err) {
return nil, err
}
return eq, nil
}
func (oc *DefaultNetworkController) cleanEgressQoSNS(namespace string) error {
obj, loaded := oc.egressQoSCache.Load(namespace)
if !loaded {
// the namespace is clean
klog.V(4).Infof("EgressQoS for namespace %s not found in cache", namespace)
return nil
}
eq := obj.(*egressQoS)
eq.Lock()
defer eq.Unlock()
p := func(q *nbdb.QoS) bool {
eqNs, ok := q.ExternalIDs["EgressQoS"]
if !ok { // the QoS is not managed by an EgressQoS
return false
}
return eqNs == eq.namespace
}
existingQoSes, err := libovsdbops.FindQoSesWithPredicate(oc.nbClient, p)
if err != nil {
return err
}
if len(existingQoSes) > 0 {
allOps := []ovsdb.Operation{}
ops, err := libovsdbops.DeleteQoSesOps(oc.nbClient, nil, existingQoSes...)
if err != nil {
return err
}
allOps = append(allOps, ops...)
logicalSwitches, err := oc.egressQoSSwitches()
if err != nil {
return err
}
for _, sw := range logicalSwitches {
ops, err := libovsdbops.RemoveQoSesFromLogicalSwitchOps(oc.nbClient, nil, sw, existingQoSes...)
if err != nil {
return err
}
allOps = append(allOps, ops...)
}
if _, err := libovsdbops.TransactAndCheck(oc.nbClient, allOps); err != nil {
return fmt.Errorf("failed to delete qos, err: %s", err)
}
}
predicateIDs := libovsdbops.NewDbObjectIDs(libovsdbops.AddressSetEgressQoS, oc.controllerName,
map[libovsdbops.ExternalIDKey]string{
libovsdbops.ObjectNameKey: eq.namespace,
})
asPredicate := libovsdbops.GetPredicate[*nbdb.AddressSet](predicateIDs, nil)
if err := libovsdbops.DeleteAddressSetsWithPredicate(oc.nbClient, asPredicate); err != nil {
return fmt.Errorf("failed to remove egress qos address sets, err: %v", err)
}
// we can delete the object from the cache now.
// we also mark it as stale to prevent pod processing if RLock
// acquired after removal from cache.
oc.egressQoSCache.Delete(namespace)
eq.stale = true
return nil
}
func (oc *DefaultNetworkController) addEgressQoS(eqObj *egressqosapi.EgressQoS) error {
eq, err := oc.cloneEgressQoS(eqObj)
if err != nil {
return err
}
eq.Lock()
defer eq.Unlock()
eq.stale = true // until we finish processing successfully
// there should not be an item in the cache for the given namespace
// as we first attempt to delete before create.
if _, loaded := oc.egressQoSCache.LoadOrStore(eq.namespace, eq); loaded {
return fmt.Errorf("error attempting to add egressQoS %s to namespace %s when it already has an EgressQoS",
eq.name, eq.namespace)
}
for _, rule := range eq.rules {
rule.addrSet, rule.pods, err = oc.createASForEgressQoSRule(rule.podSelector, eq.namespace, rule.priority)
if err != nil {
return err
}
}
logicalSwitches, err := oc.egressQoSSwitches()
if err != nil {
return err
}
allOps := []ovsdb.Operation{}
qoses := []*nbdb.QoS{}
for _, r := range eq.rules {
hashedIPv4, hashedIPv6 := r.addrSet.GetASHashNames()
match := generateEgressQoSMatch(r, hashedIPv4, hashedIPv6)
qos := &nbdb.QoS{
Direction: nbdb.QoSDirectionToLport,
Match: match,
Priority: r.priority,
Action: map[string]int{nbdb.QoSActionDSCP: r.dscp},
ExternalIDs: map[string]string{"EgressQoS": eq.namespace},
}
qoses = append(qoses, qos)
}
ops, err := libovsdbops.CreateOrUpdateQoSesOps(oc.nbClient, nil, qoses...)
if err != nil {
return err
}
allOps = append(allOps, ops...)
for _, sw := range logicalSwitches {
ops, err := libovsdbops.AddQoSesToLogicalSwitchOps(oc.nbClient, nil, sw, qoses...)
if err != nil {
return err
}
allOps = append(allOps, ops...)
}
if _, err := libovsdbops.TransactAndCheck(oc.nbClient, allOps); err != nil {
return fmt.Errorf("failed to create qos, err: %s", err)
}
eq.stale = false // we can mark it as "ready" now
return nil
}
func generateEgressQoSMatch(eq *egressQoSRule, hashedAddressSetNameIPv4, hashedAddressSetNameIPv6 string) string {
var src string
var dst string
switch {
case config.IPv4Mode && config.IPv6Mode:
src = fmt.Sprintf("(ip4.src == $%s || ip6.src == $%s)", hashedAddressSetNameIPv4, hashedAddressSetNameIPv6)
case config.IPv4Mode:
src = fmt.Sprintf("ip4.src == $%s", hashedAddressSetNameIPv4)
case config.IPv6Mode:
src = fmt.Sprintf("ip6.src == $%s", hashedAddressSetNameIPv6)
}
dst = "ip4.dst == 0.0.0.0/0 || ip6.dst == ::/0" // if the dstCIDR field was not set we treat it as "any" destination
if eq.destination != "" {
dst = fmt.Sprintf("ip4.dst == %s", eq.destination)
if utilnet.IsIPv6CIDRString(eq.destination) {
dst = fmt.Sprintf("ip6.dst == %s", eq.destination)
}
}
return fmt.Sprintf("(%s) && %s", dst, src)
}
func (oc *DefaultNetworkController) egressQoSSwitches() ([]string, error) {
logicalSwitches := []string{}
// Find all node switches
p := func(item *nbdb.LogicalSwitch) bool {
// Ignore external and Join switches(both legacy and current)
return !(strings.HasPrefix(item.Name, types.JoinSwitchPrefix) || item.Name == types.OVNJoinSwitch || item.Name == types.TransitSwitch || strings.HasPrefix(item.Name, types.ExternalSwitchPrefix))
}
nodeLocalSwitches, err := libovsdbops.FindLogicalSwitchesWithPredicate(oc.nbClient, p)
if err != nil {
return nil, fmt.Errorf("unable to fetch local switches for EgressQoS, err: %v", err)
}
for _, nodeLocalSwitch := range nodeLocalSwitches {
logicalSwitches = append(logicalSwitches, nodeLocalSwitch.Name)
}
return logicalSwitches, nil
}
type mapOp int
const (
mapInsert mapOp = iota
mapDelete
)
type mapAndOp struct {
m *sync.Map
op mapOp
}
func (oc *DefaultNetworkController) syncEgressQoSPod(key string) error {
startTime := time.Now()
namespace, name, err := cache.SplitMetaNamespaceKey(key)
if err != nil {
return err
}
obj, loaded := oc.egressQoSCache.Load(namespace)
if !loaded { // no EgressQoS in the namespace
return nil
}
klog.V(5).Infof("Processing sync for EgressQoS pod %s/%s", namespace, name)
defer func() {
klog.V(4).Infof("Finished syncing EgressQoS pod %s on namespace %s : %v", name, namespace, time.Since(startTime))
}()
eq := obj.(*egressQoS)
eq.RLock() // allow multiple pods to sync
defer eq.RUnlock()
if eq.stale { // was deleted or not created properly
return nil
}
pod, err := oc.egressQoSPodLister.Pods(namespace).Get(name)
if err != nil && !apierrors.IsNotFound(err) {
return err
}
allOps := []ovsdb.Operation{}
// on delete/complete we remove the pod from the relevant address sets
if pod == nil || util.PodCompleted(pod) {
podsCaches := []*sync.Map{}
for _, rule := range eq.rules {
obj, loaded := rule.pods.Load(name)
if !loaded {
continue
}
ips := obj.([]net.IP)
ops, err := rule.addrSet.DeleteAddressesReturnOps(util.StringSlice(ips))
if err != nil {
return err
}
podsCaches = append(podsCaches, rule.pods)
allOps = append(allOps, ops...)
}
_, err = libovsdbops.TransactAndCheck(oc.nbClient, allOps)
if err != nil {
return err
}
for _, pc := range podsCaches {
pc.Delete(name)
}
return nil
}
klog.V(5).Infof("Pod %s retrieved from lister: %v", pod.Name, pod)
if util.PodWantsHostNetwork(pod) || !oc.isPodScheduledinLocalZone(pod) { // we don't handle HostNetworked or remote zone pods
return nil
}
podIPs, err := util.GetPodIPsOfNetwork(pod, oc.NetInfo)
if errors.Is(err, util.ErrNoPodIPFound) {
return nil // reprocess it when it is updated with an IP
}
if err != nil {
return err
}
podLabels := labels.Set(pod.Labels)
podMapOps := []mapAndOp{}
for _, r := range eq.rules {
selector, err := metav1.LabelSelectorAsSelector(&r.podSelector)
if err != nil {
return err
}
if selector.Empty() { // rule applies to all pods in the namespace, no need to modify address set
continue
}
_, loaded := r.pods.Load(pod.Name)
if selector.Matches(podLabels) && !loaded {
ops, err := r.addrSet.AddAddressesReturnOps(util.StringSlice(podIPs))
if err != nil {
return err
}
allOps = append(allOps, ops...)
podMapOps = append(podMapOps, mapAndOp{r.pods, mapInsert})
} else if !selector.Matches(podLabels) && loaded {
ops, err := r.addrSet.DeleteAddressesReturnOps(util.StringSlice(podIPs))
if err != nil {
return err
}
allOps = append(allOps, ops...)
podMapOps = append(podMapOps, mapAndOp{r.pods, mapDelete})
}
}
_, err = libovsdbops.TransactAndCheck(oc.nbClient, allOps)
if err != nil {
return err
}
for _, mapOp := range podMapOps {
switch mapOp.op {
case mapInsert:
mapOp.m.Store(pod.Name, podIPs)
case mapDelete:
mapOp.m.Delete(pod.Name)
}
}
return nil
}
// onEgressQoSPodAdd queues the pod for processing.
func (oc *DefaultNetworkController) onEgressQoSPodAdd(obj interface{}) {
key, err := cache.MetaNamespaceKeyFunc(obj)
if err != nil {
utilruntime.HandleError(fmt.Errorf("couldn't get key for object %+v: %v", obj, err))
return
}
pod := obj.(*kapi.Pod)
// only process this pod if it is local to this zone
if !oc.isPodScheduledinLocalZone(pod) {
// NOTE: This means we don't handle the case where pod goes from
// being local to remote. So far there is no use case for this to happen.
// Also when we think about a pod going from local to remote - what does that mean?
// It means the node on which the pod lived suddenly stopped being local to this zone
// That either means node changed zones - which will involve a full delete and recreate
// the OVN objects in a new zone's DB and/or node is gone etc. All those scenarios don't
// need this controller to take any action.
// NOTE2: During upgrades when the legacy ovnkube-master is still running it will detect
// nodes have gone remote which for this feature means deleting the switches totally and
// based on OVN db schema this will remove all referenced QoS rules created on the switch
return // not local to this zone, nothing to do; no-op
}
oc.egressQoSPodQueue.Add(key)
}
// onEgressQoSPodUpdate queues the pod for processing.
func (oc *DefaultNetworkController) onEgressQoSPodUpdate(oldObj, newObj interface{}) {
oldPod := oldObj.(*kapi.Pod)
newPod := newObj.(*kapi.Pod)
if oldPod.ResourceVersion == newPod.ResourceVersion ||
!newPod.GetDeletionTimestamp().IsZero() {
return
}
oldPodLabels := labels.Set(oldPod.Labels)
newPodLabels := labels.Set(newPod.Labels)
oldPodIPs, _ := util.GetPodIPsOfNetwork(oldPod, oc.NetInfo)
newPodIPs, _ := util.GetPodIPsOfNetwork(newPod, oc.NetInfo)
isOldPodLocal := oc.isPodScheduledinLocalZone(oldPod)
isNewPodLocal := oc.isPodScheduledinLocalZone(newPod)
oldPodCompleted := util.PodCompleted(oldPod)
newPodCompleted := util.PodCompleted(newPod)
if labels.Equals(oldPodLabels, newPodLabels) &&
len(oldPodIPs) == len(newPodIPs) &&
// NOTE: We only expect remote pods to become local when they are scheduled; not vice versa
isOldPodLocal == isNewPodLocal &&
oldPodCompleted == newPodCompleted {
return
}
key, err := cache.MetaNamespaceKeyFunc(newObj)
if err != nil {
utilruntime.HandleError(fmt.Errorf("couldn't get key for object %+v: %v", newObj, err))
return
}
oc.egressQoSPodQueue.Add(key)
}
func (oc *DefaultNetworkController) onEgressQoSPodDelete(obj interface{}) {
key, err := cache.MetaNamespaceKeyFunc(obj)
if err != nil {
utilruntime.HandleError(fmt.Errorf("couldn't get key for object %+v: %v", obj, err))
return
}
pod := obj.(*kapi.Pod)
// only process this pod if it is local to this zone
if !oc.isPodScheduledinLocalZone(pod) {
// NOTE: This means we don't handle the case where pod goes from
// being local to remote. So far there is no use case for this to happen.
// Also when we think about a pod going from local to remote - what does that mean?
// It means the node on which the pod lived suddenly stopped being local to this zone
// That either means node changed zones - which will involve a full delete and recreate
// the OVN objects in a new zone's DB and/or node is gone etc. All those scenarios don't
// need this controller to take any action.
// NOTE2: During upgrades when the legacy ovnkube-master is still running it will detect
// nodes have gone remote which for this feature means deleting the switches totally and
// based on OVN db schema this will remove all referenced QoS rules created on the switch
return // not local to this zone, nothing to do; no-op
}
oc.egressQoSPodQueue.Add(key)
}
func (oc *DefaultNetworkController) runEgressQoSPodWorker(wg *sync.WaitGroup) {
for oc.processNextEgressQoSPodWorkItem(wg) {
}
}
func (oc *DefaultNetworkController) processNextEgressQoSPodWorkItem(wg *sync.WaitGroup) bool {
wg.Add(1)
defer wg.Done()
key, quit := oc.egressQoSPodQueue.Get()
if quit {
return false
}
defer oc.egressQoSPodQueue.Done(key)
err := oc.syncEgressQoSPod(key.(string))
if err == nil {
oc.egressQoSPodQueue.Forget(key)
return true
}
utilruntime.HandleError(fmt.Errorf("%v failed with : %v", key, err))
if oc.egressQoSPodQueue.NumRequeues(key) < maxEgressQoSRetries {
oc.egressQoSPodQueue.AddRateLimited(key)
return true
}
oc.egressQoSPodQueue.Forget(key)
return true
}
// onEgressQoSAdd queues the node for processing.
func (oc *DefaultNetworkController) onEgressQoSNodeAdd(obj interface{}) {
key, err := cache.MetaNamespaceKeyFunc(obj)
if err != nil {
utilruntime.HandleError(fmt.Errorf("couldn't get key for object %+v: %v", obj, err))
return
}
node := obj.(*kapi.Node)
if util.GetNodeZone(node) != oc.zone {
return
}
oc.egressQoSNodeQueue.Add(key)
}
// onEgressQoSNodeUpdate queues the node for processing if it changed zones
func (oc *DefaultNetworkController) onEgressQoSNodeUpdate(oldObj, newObj interface{}) {
oldNode := oldObj.(*kapi.Node)
newNode := newObj.(*kapi.Node)
if oldNode.ResourceVersion == newNode.ResourceVersion ||
!newNode.GetDeletionTimestamp().IsZero() {
return
}
// During a nodeAdd event, the ovnkube-node can take some time to add the zone
// annotation to the node, during that interim time we might consider the node
// as remote and hence the addNode event might not do anything. So we need to
// watch for node updates. We also ensure we only process local node zones by
// comparing to the controller's zone. That will cover the remote->local case.
// The local->remote case is not covered or handled here because in that
// scenario the addUpdateRemoteNodeEvent function which calls the cleanupNodeResources
// will just cleanup the switch resource for the node.
oldNodeZone := util.GetNodeZone(oldNode)
newNodeZone := util.GetNodeZone(newNode)
if oldNodeZone == newNodeZone || newNodeZone != oc.zone {
return
}
key, err := cache.MetaNamespaceKeyFunc(newObj)
if err != nil {
utilruntime.HandleError(fmt.Errorf("couldn't get key for object %+v: %v", newObj, err))
return
}
oc.egressQoSNodeQueue.Add(key)
}
func (oc *DefaultNetworkController) runEgressQoSNodeWorker(wg *sync.WaitGroup) {
for oc.processNextEgressQoSNodeWorkItem(wg) {
}
}
func (oc *DefaultNetworkController) processNextEgressQoSNodeWorkItem(wg *sync.WaitGroup) bool {
wg.Add(1)
defer wg.Done()
key, quit := oc.egressQoSNodeQueue.Get()
if quit {
return false
}
defer oc.egressQoSNodeQueue.Done(key)
err := oc.syncEgressQoSNode(key.(string))
if err == nil {
oc.egressQoSNodeQueue.Forget(key)
return true
}
utilruntime.HandleError(fmt.Errorf("%v failed with: %v", key, err))
if oc.egressQoSNodeQueue.NumRequeues(key) < maxEgressQoSRetries {
oc.egressQoSNodeQueue.AddRateLimited(key)
return true
}
oc.egressQoSNodeQueue.Forget(key)
return true
}