-
Notifications
You must be signed in to change notification settings - Fork 368
/
egress_controller.go
1416 lines (1295 loc) · 48 KB
/
egress_controller.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
// Copyright 2021 Antrea Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package egress
import (
"context"
"fmt"
"net"
"reflect"
"strings"
"sync"
"time"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/apimachinery/pkg/watch"
coreinformers "k8s.io/client-go/informers/core/v1"
"k8s.io/client-go/kubernetes"
v1 "k8s.io/client-go/kubernetes/typed/core/v1"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/tools/record"
"k8s.io/client-go/util/retry"
"k8s.io/client-go/util/workqueue"
"k8s.io/klog/v2"
"antrea.io/antrea/pkg/agent/client"
"antrea.io/antrea/pkg/agent/interfacestore"
"antrea.io/antrea/pkg/agent/ipassigner"
"antrea.io/antrea/pkg/agent/memberlist"
"antrea.io/antrea/pkg/agent/openflow"
"antrea.io/antrea/pkg/agent/route"
"antrea.io/antrea/pkg/agent/servicecidr"
"antrea.io/antrea/pkg/agent/types"
cpv1b2 "antrea.io/antrea/pkg/apis/controlplane/v1beta2"
crdv1b1 "antrea.io/antrea/pkg/apis/crd/v1beta1"
clientsetversioned "antrea.io/antrea/pkg/client/clientset/versioned"
"antrea.io/antrea/pkg/client/clientset/versioned/scheme"
crdinformers "antrea.io/antrea/pkg/client/informers/externalversions/crd/v1beta1"
crdlisters "antrea.io/antrea/pkg/client/listers/crd/v1beta1"
"antrea.io/antrea/pkg/controller/metrics"
"antrea.io/antrea/pkg/util/channel"
"antrea.io/antrea/pkg/util/k8s"
)
const (
controllerName = "AntreaAgentEgressController"
// How long to wait before retrying the processing of an Egress change.
minRetryDelay = 5 * time.Second
maxRetryDelay = 300 * time.Second
// Default number of workers processing an Egress change.
defaultWorkers = 4
// Disable resyncing.
resyncPeriod time.Duration = 0
// minEgressMark is the minimum mark of Egress IPs can be configured on a Node.
minEgressMark = 1
// maxEgressMark is the maximum mark of Egress IPs can be configured on a Node.
maxEgressMark = 255
egressIPIndex = "egressIP"
externalIPPoolIndex = "externalIPPool"
// egressDummyDevice is the dummy device that holds the Egress IPs configured to the system by antrea-agent.
egressDummyDevice = "antrea-egress0"
)
var maxSubnetsPerNodes = types.MaxEgressRouteTable - types.MinEgressRouteTable + 1
var emptyWatch = watch.NewEmptyWatch()
var newIPAssigner = ipassigner.NewIPAssigner
// egressState keeps the actual state of an Egress that has been realized.
type egressState struct {
// The actual egress IP of the Egress. If it's different from the desired IP, there is an update to EgressIP, and we
// need to remove previously installed flows.
egressIP string
// The actual datapath mark of this Egress. Used to check if the mark changes since last process.
mark uint32
// The actual openflow ports for which we have installed SNAT rules. Used to identify stale openflow ports when
// updating or deleting an Egress.
ofPorts sets.Set[int32]
// The actual Pods of the Egress. Used to identify stale Pods when updating or deleting an Egress.
pods sets.Set[string]
// Rate-limit of this Egress.
rateLimitMeter *rateLimitMeter
}
type rateLimitMeter struct {
MeterID uint32
Rate uint32
Burst uint32
}
func (r *rateLimitMeter) Equals(rateLimit *rateLimitMeter) bool {
if r == nil && rateLimit == nil {
return true
}
if r == nil || rateLimit == nil {
return false
}
return r.MeterID == rateLimit.MeterID && r.Rate == rateLimit.Rate && r.Burst == rateLimit.Burst
}
// egressIPState keeps the actual state of an Egress IP. It's maintained separately from egressState because
// multiple Egresses can share an EgressIP.
type egressIPState struct {
egressIP net.IP
// The names of the Egresses that are currently referring to it.
egressNames sets.Set[string]
// The datapath mark of this Egress IP. 0 if this is not a local IP.
mark uint32
// Whether its flows have been installed.
flowsInstalled bool
// Whether its iptables rule has been installed.
ruleInstalled bool
// The subnet the Egress IP is associated with.
subnetInfo *crdv1b1.SubnetInfo
}
// egressRouteTable stores the route table ID created for a subnet and the marks that are referencing it.
type egressRouteTable struct {
// The route table ID.
tableID uint32
// The marks referencing the table. Once it's empty, the route table should be deleted.
marks sets.Set[uint32]
}
// egressBinding keeps the Egresses applying to a Pod.
// There is one effective Egress for a Pod at any given time.
type egressBinding struct {
effectiveEgress string
alternativeEgresses sets.Set[string]
}
type EgressController struct {
ofClient openflow.Client
routeClient route.Interface
k8sClient kubernetes.Interface
crdClient clientsetversioned.Interface
antreaClientProvider client.AntreaClientProvider
egressInformer cache.SharedIndexInformer
egressLister crdlisters.EgressLister
egressListerSynced cache.InformerSynced
queue workqueue.TypedRateLimitingInterface[string]
externalIPPoolLister crdlisters.ExternalIPPoolLister
externalIPPoolListerSynced cache.InformerSynced
// Use an interface for IP detector to enable testing.
localIPDetector ipassigner.LocalIPDetector
ifaceStore interfacestore.InterfaceStore
nodeName string
markAllocator *idAllocator
egressGroups map[string]sets.Set[string]
egressGroupsMutex sync.RWMutex
egressBindings map[string]*egressBinding
egressBindingsMutex sync.RWMutex
egressStates map[string]*egressState
// The mutex is to protect the map, not the egressState items. The workqueue guarantees an Egress will only be
// processed by a single worker at any time. So the returned EgressState has no race condition.
egressStatesMutex sync.RWMutex
egressIPStates map[string]*egressIPState
egressIPStatesMutex sync.Mutex
cluster memberlist.Interface
ipAssigner ipassigner.IPAssigner
egressIPScheduler *egressIPScheduler
serviceCIDRInterface servicecidr.Interface
serviceCIDRUpdateCh chan struct{}
// Declared for testing.
serviceCIDRUpdateRetryDelay time.Duration
trafficShapingEnabled bool
eventBroadcaster record.EventBroadcaster
record record.EventRecorder
// Whether to support non-default subnets.
supportSeparateSubnet bool
// Used to allocate route table ID.
tableAllocator *idAllocator
// Each subnet has its own route table.
egressRouteTables map[crdv1b1.SubnetInfo]*egressRouteTable
}
func NewEgressController(
ofClient openflow.Client,
k8sClient kubernetes.Interface,
antreaClientGetter client.AntreaClientProvider,
crdClient clientsetversioned.Interface,
ifaceStore interfacestore.InterfaceStore,
routeClient route.Interface,
nodeName string,
nodeTransportInterface string,
cluster memberlist.Interface,
egressInformer crdinformers.EgressInformer,
externalIPPoolInformer crdinformers.ExternalIPPoolInformer,
nodeInformers coreinformers.NodeInformer,
podUpdateSubscriber channel.Subscriber,
serviceCIDRInterface servicecidr.Interface,
maxEgressIPsPerNode int,
trafficShapingEnabled bool,
supportSeparateSubnet bool,
) (*EgressController, error) {
if trafficShapingEnabled && !openflow.OVSMetersAreSupported() {
klog.Info("EgressTrafficShaping feature gate is enabled, but it is ignored because OVS meters are not supported.")
}
eventBroadcaster := record.NewBroadcaster()
recorder := eventBroadcaster.NewRecorder(
scheme.Scheme,
corev1.EventSource{Component: controllerName},
)
c := &EgressController{
ofClient: ofClient,
routeClient: routeClient,
k8sClient: k8sClient,
antreaClientProvider: antreaClientGetter,
crdClient: crdClient,
queue: workqueue.NewTypedRateLimitingQueueWithConfig(
workqueue.NewTypedItemExponentialFailureRateLimiter[string](minRetryDelay, maxRetryDelay),
workqueue.TypedRateLimitingQueueConfig[string]{
Name: "egressgroup",
},
),
egressInformer: egressInformer.Informer(),
egressLister: egressInformer.Lister(),
egressListerSynced: egressInformer.Informer().HasSynced,
nodeName: nodeName,
ifaceStore: ifaceStore,
egressGroups: map[string]sets.Set[string]{},
egressStates: map[string]*egressState{},
egressIPStates: map[string]*egressIPState{},
egressBindings: map[string]*egressBinding{},
localIPDetector: ipassigner.NewLocalIPDetector(),
markAllocator: newIDAllocator(minEgressMark, maxEgressMark),
cluster: cluster,
serviceCIDRInterface: serviceCIDRInterface,
// One buffer is enough as we just use it to ensure the target handler is executed once.
serviceCIDRUpdateCh: make(chan struct{}, 1),
serviceCIDRUpdateRetryDelay: 10 * time.Second,
trafficShapingEnabled: openflow.OVSMetersAreSupported() && trafficShapingEnabled,
eventBroadcaster: eventBroadcaster,
record: recorder,
externalIPPoolLister: externalIPPoolInformer.Lister(),
externalIPPoolListerSynced: externalIPPoolInformer.Informer().HasSynced,
supportSeparateSubnet: supportSeparateSubnet,
}
if supportSeparateSubnet {
c.egressRouteTables = map[crdv1b1.SubnetInfo]*egressRouteTable{}
c.tableAllocator = newIDAllocator(types.MinEgressRouteTable, types.MaxEgressRouteTable)
externalIPPoolInformer.Informer().AddEventHandlerWithResyncPeriod(
cache.ResourceEventHandlerFuncs{
AddFunc: c.addExternalIPPool,
UpdateFunc: c.updateExternalIPPool,
},
resyncPeriod,
)
}
ipAssigner, err := newIPAssigner(nodeTransportInterface, egressDummyDevice)
if err != nil {
return nil, fmt.Errorf("initializing egressIP assigner failed: %v", err)
}
c.ipAssigner = ipAssigner
c.egressIPScheduler = NewEgressIPScheduler(cluster, egressInformer, nodeInformers, maxEgressIPsPerNode)
c.egressInformer.AddIndexers(
cache.Indexers{
// egressIPIndex will be used to get all Egresses sharing the same Egress IP.
egressIPIndex: func(obj interface{}) ([]string, error) {
egress, ok := obj.(*crdv1b1.Egress)
if !ok {
return nil, fmt.Errorf("obj is not Egress: %+v", obj)
}
var egressIPs []string
if egress.Spec.EgressIP != "" {
egressIPs = append(egressIPs, egress.Spec.EgressIP)
}
for _, egressIP := range egress.Spec.EgressIPs {
if egressIP != "" {
egressIPs = append(egressIPs, egressIP)
}
}
return egressIPs, nil
},
externalIPPoolIndex: func(obj interface{}) ([]string, error) {
egress, ok := obj.(*crdv1b1.Egress)
if !ok {
return nil, fmt.Errorf("obj is not Egress: %+v", obj)
}
var pools []string
if egress.Spec.ExternalIPPool != "" {
pools = append(pools, egress.Spec.ExternalIPPool)
}
for _, pool := range egress.Spec.ExternalIPPools {
if pool != "" {
pools = append(pools, pool)
}
}
return pools, nil
},
})
c.egressInformer.AddEventHandlerWithResyncPeriod(
cache.ResourceEventHandlerFuncs{
AddFunc: c.addEgress,
UpdateFunc: c.updateEgress,
DeleteFunc: c.deleteEgress,
},
resyncPeriod,
)
// Subscribe Pod update events from CNIServer to enforce Egress earlier, instead of waiting for their IPs are
// reported to kube-apiserver and processed by antrea-controller.
podUpdateSubscriber.Subscribe(c.processPodUpdate)
c.localIPDetector.AddEventHandler(c.onLocalIPUpdate)
c.egressIPScheduler.AddEventHandler(c.onEgressIPSchedule)
c.serviceCIDRInterface.AddEventHandler(c.onServiceCIDRUpdate)
return c, nil
}
// onEgressIPSchedule will be called when EgressIPScheduler reschedules an Egress's IP.
func (c *EgressController) onEgressIPSchedule(egress string) {
c.queue.Add(egress)
}
// onServiceCIDRUpdate will be called when ServiceCIDRs change.
// It ensures updateServiceCIDRs will be executed once after this call.
func (c *EgressController) onServiceCIDRUpdate(_ []*net.IPNet) {
select {
case c.serviceCIDRUpdateCh <- struct{}{}:
default:
// The previous event is not processed yet, discard the new event.
}
}
func (c *EgressController) updateServiceCIDRs(stopCh <-chan struct{}) {
timer := time.NewTimer(0)
defer timer.Stop()
<-timer.C // Consume the first tick.
for {
select {
case <-stopCh:
return
case <-c.serviceCIDRUpdateCh:
klog.V(2).InfoS("Received service CIDR update")
case <-timer.C:
klog.V(2).InfoS("Service CIDR update timer expired")
}
serviceCIDRs, err := c.serviceCIDRInterface.GetServiceCIDRs()
if err != nil {
klog.ErrorS(err, "Failed to get Service CIDRs")
// No need to retry in this case as the Service CIDRs won't be available until it receives a service CIDRs update.
continue
}
err = c.ofClient.InstallSNATBypassServiceFlows(serviceCIDRs)
if err != nil {
klog.ErrorS(err, "Failed to install SNAT bypass flows for Service CIDRs, will retry", "serviceCIDRs", serviceCIDRs)
// Schedule a retry as it should be transient error.
timer.Reset(c.serviceCIDRUpdateRetryDelay)
}
}
}
// processPodUpdate will be called when CNIServer publishes a Pod update event.
// It triggers reconciling the effective Egress of the Pod.
func (c *EgressController) processPodUpdate(e interface{}) {
c.egressBindingsMutex.Lock()
defer c.egressBindingsMutex.Unlock()
podEvent := e.(types.PodUpdate)
pod := k8s.NamespacedName(podEvent.PodNamespace, podEvent.PodName)
binding, exists := c.egressBindings[pod]
if !exists {
return
}
c.queue.Add(binding.effectiveEgress)
}
// addEgress processes Egress ADD events.
func (c *EgressController) addEgress(obj interface{}) {
egress := obj.(*crdv1b1.Egress)
if egress.Spec.EgressIP == "" {
return
}
c.queue.Add(egress.Name)
klog.V(2).InfoS("Processed Egress ADD event", "egress", klog.KObj(egress))
}
// updateEgress processes Egress UPDATE events.
func (c *EgressController) updateEgress(old, cur interface{}) {
oldEgress := old.(*crdv1b1.Egress)
curEgress := cur.(*crdv1b1.Egress)
// Ignore handling the Egress Status change if Egress IP already has been assigned on current node.
if curEgress.Status.EgressNode == c.nodeName && oldEgress.GetGeneration() == curEgress.GetGeneration() {
return
}
c.queue.Add(curEgress.Name)
klog.V(2).InfoS("Processed Egress UPDATE event", "egress", klog.KObj(curEgress))
}
// deleteEgress processes Egress DELETE events.
func (c *EgressController) deleteEgress(obj interface{}) {
egress, ok := obj.(*crdv1b1.Egress)
if !ok {
deletedState, ok := obj.(cache.DeletedFinalStateUnknown)
if !ok {
klog.Errorf("Received unexpected object: %v", obj)
return
}
egress, ok = deletedState.Obj.(*crdv1b1.Egress)
if !ok {
klog.Errorf("DeletedFinalStateUnknown contains non-Egress object: %v", deletedState.Obj)
return
}
}
c.queue.Add(egress.Name)
klog.V(2).InfoS("Processed Egress DELETE event", "egress", klog.KObj(egress))
}
func (c *EgressController) addExternalIPPool(obj interface{}) {
pool := obj.(*crdv1b1.ExternalIPPool)
if pool.Spec.SubnetInfo == nil {
return
}
c.onExternalIPPoolUpdated(pool.Name)
klog.V(2).InfoS("Processed ExternalIPPool ADD event", "externalIPPool", klog.KObj(pool))
}
func (c *EgressController) updateExternalIPPool(old, cur interface{}) {
oldPool := old.(*crdv1b1.ExternalIPPool)
curPool := cur.(*crdv1b1.ExternalIPPool)
// We only care about SubnetInfo here.
if crdv1b1.CompareSubnetInfo(oldPool.Spec.SubnetInfo, curPool.Spec.SubnetInfo, false) {
return
}
c.onExternalIPPoolUpdated(curPool.Name)
klog.V(2).InfoS("Processed ExternalIPPool UPDATE event", "externalIPPool", klog.KObj(curPool))
}
func (c *EgressController) onExternalIPPoolUpdated(pool string) {
egresses, _ := c.egressInformer.GetIndexer().ByIndex(externalIPPoolIndex, pool)
for _, obj := range egresses {
egress := obj.(*crdv1b1.Egress)
c.queue.Add(egress.Name)
}
}
func (c *EgressController) onLocalIPUpdate(ip string, added bool) {
egresses, _ := c.egressInformer.GetIndexer().ByIndex(egressIPIndex, ip)
if len(egresses) == 0 {
return
}
if added {
klog.Infof("Detected Egress IP address %s added to this Node", ip)
} else {
klog.Infof("Detected Egress IP address %s deleted from this Node", ip)
}
for _, obj := range egresses {
egress := obj.(*crdv1b1.Egress)
c.queue.Add(egress.Name)
}
}
// Run will create defaultWorkers workers (go routines) which will process the Egress events from the
// workqueue.
func (c *EgressController) Run(stopCh <-chan struct{}) {
defer c.queue.ShutDown()
klog.Infof("Starting %s", controllerName)
defer klog.Infof("Shutting down %s", controllerName)
c.eventBroadcaster.StartStructuredLogging(0)
c.eventBroadcaster.StartRecordingToSink(&v1.EventSinkImpl{
Interface: c.k8sClient.CoreV1().Events(""),
})
defer c.eventBroadcaster.Shutdown()
go c.localIPDetector.Run(stopCh)
go c.egressIPScheduler.Run(stopCh)
go c.ipAssigner.Run(stopCh)
if !cache.WaitForNamedCacheSync(controllerName, stopCh, c.egressListerSynced, c.externalIPPoolListerSynced, c.localIPDetector.HasSynced, c.egressIPScheduler.HasScheduled) {
return
}
if err := c.replaceEgressIPs(); err != nil {
klog.ErrorS(err, "Failed to replace Egress IPs")
}
if err := c.routeClient.RestoreEgressRoutesAndRules(types.MinEgressRouteTable, types.MaxEgressRouteTable); err != nil {
klog.ErrorS(err, "Failed to restore Egress routes and rules")
}
go wait.NonSlidingUntil(c.watchEgressGroup, 5*time.Second, stopCh)
go c.updateServiceCIDRs(stopCh)
for i := 0; i < defaultWorkers; i++ {
go wait.Until(c.worker, time.Second, stopCh)
}
<-stopCh
}
// replaceEgressIPs unassigns stale Egress IPs that shouldn't be present on this Node and assigns the missing IPs
// on this node. The unassigned IPs are from Egresses that were either deleted from the Kubernetes API or migrated
// to other Nodes when the agent on this Node was not running.
func (c *EgressController) replaceEgressIPs() error {
desiredLocalEgressIPs := map[string]*crdv1b1.SubnetInfo{}
egresses, _ := c.egressLister.List(labels.Everything())
for _, egress := range egresses {
if isEgressSchedulable(egress) && egress.Status.EgressNode == c.nodeName && egress.Status.EgressIP != "" {
pool, err := c.externalIPPoolLister.Get(egress.Spec.ExternalIPPool)
// Ignore the Egress if the ExternalIPPool doesn't exist.
if err != nil {
continue
}
desiredLocalEgressIPs[egress.Status.EgressIP] = pool.Spec.SubnetInfo
// Record the Egress's state as we assign their IPs to this Node in the following call. It makes sure these
// Egress IPs will be unassigned when the Egresses are deleted.
c.newEgressState(egress.Name, egress.Status.EgressIP)
}
}
if err := c.ipAssigner.InitIPs(desiredLocalEgressIPs); err != nil {
return err
}
return nil
}
// worker is a long-running function that will continually call the processNextWorkItem function in
// order to read and process a message on the workqueue.
func (c *EgressController) worker() {
for c.processNextWorkItem() {
}
}
func (c *EgressController) processNextWorkItem() bool {
key, quit := c.queue.Get()
if quit {
return false
}
defer c.queue.Done(key)
if err := c.syncEgress(key); err == nil {
// If no error occurs we Forget this item so it does not get queued again until
// another change happens.
c.queue.Forget(key)
} else {
// Put the item back on the workqueue to handle any transient errors.
c.queue.AddRateLimited(key)
klog.Errorf("Error syncing Egress %s, requeuing. Error: %v", key, err)
}
return true
}
// installPolicyRoute ensures Egress traffic with the given mark access external network via the subnet's gateway, and
// tagged with the subnet's VLAN ID if present.
func (c *EgressController) installPolicyRoute(ipState *egressIPState, subnetInfo *crdv1b1.SubnetInfo) error {
if !c.supportSeparateSubnet {
return nil
}
if crdv1b1.CompareSubnetInfo(ipState.subnetInfo, subnetInfo, false) {
return nil
}
// Deletes stale policy route first.
if err := c.uninstallPolicyRoute(ipState); err != nil {
return err
}
// If the subnetInfo is nil, policy routing is not needed. The Egress IP should just use the main route table.
if subnetInfo == nil {
return nil
}
// Get or create a route table for this subnet.
rt, exists := c.egressRouteTables[*subnetInfo]
if !exists {
tableID, err := c.tableAllocator.allocate()
if err != nil {
return fmt.Errorf("error allocating table for subnet %v due to exceeding max allowed subnets %d: %w", subnetInfo, maxSubnetsPerNodes, err)
}
// Get the index of the network interface to which IPs in the subnet are assigned.
// The network interface will be used as the device via which the Egress traffic leaves.
devID, ok := c.ipAssigner.GetInterfaceID(subnetInfo)
// This should never happen.
if !ok {
return fmt.Errorf("interface for subnet %v not found", subnetInfo)
}
if err := c.routeClient.AddEgressRoutes(tableID, devID, net.ParseIP(subnetInfo.Gateway), int(subnetInfo.PrefixLength)); err != nil {
return fmt.Errorf("error creating route table for subnet %v: %w", subnetInfo, err)
}
rt = &egressRouteTable{tableID: tableID, marks: sets.New[uint32]()}
c.egressRouteTables[*subnetInfo] = rt
}
// Add an IP rule to make the marked Egress traffic look up the table.
if err := c.routeClient.AddEgressRule(rt.tableID, ipState.mark); err != nil {
return fmt.Errorf("error adding ip rule for mark %v: %w", ipState.mark, err)
}
// Track the route table's usage.
rt.marks.Insert(ipState.mark)
// Track the current subnet of the Egress IP.
ipState.subnetInfo = subnetInfo
return nil
}
// uninstallPolicyRoute deletes the policy route of the Egress IP.
func (c *EgressController) uninstallPolicyRoute(ipState *egressIPState) error {
if !c.supportSeparateSubnet {
return nil
}
if ipState.subnetInfo == nil {
return nil
}
rt, exists := c.egressRouteTables[*ipState.subnetInfo]
if !exists {
return nil
}
if err := c.routeClient.DeleteEgressRule(rt.tableID, ipState.mark); err != nil {
return fmt.Errorf("error deleting ip rule for mark %v: %w", ipState.mark, err)
}
rt.marks.Delete(ipState.mark)
// Delete the route table if it is not used by any Egress.
if rt.marks.Len() == 0 {
if err := c.routeClient.DeleteEgressRoutes(rt.tableID); err != nil {
return fmt.Errorf("error deleting route table for subnet %v: %w", ipState.subnetInfo, err)
}
c.tableAllocator.release(rt.tableID)
delete(c.egressRouteTables, *ipState.subnetInfo)
}
ipState.subnetInfo = nil
return nil
}
// realizeEgressIP realizes an Egress IP. Multiple Egresses can share the same Egress IP.
// If it's called the first time for a local Egress IP, it allocates a locally-unique mark for the IP and installs flows
// and iptables rule for this IP and the mark.
// If the Egress IP is changed from local to non local, it uninstalls flows and iptables rule and releases the mark.
// The method returns the mark on success. Non local Egresses use 0 as the mark.
func (c *EgressController) realizeEgressIP(egressName, egressIP string, subnetInfo *crdv1b1.SubnetInfo) (uint32, error) {
isLocalIP := c.localIPDetector.IsLocalIP(egressIP)
c.egressIPStatesMutex.Lock()
defer c.egressIPStatesMutex.Unlock()
ipState, exists := c.egressIPStates[egressIP]
// Create an egressIPState if this is the first Egress using the IP.
if !exists {
ipState = &egressIPState{
egressIP: net.ParseIP(egressIP),
egressNames: sets.New[string](egressName),
}
c.egressIPStates[egressIP] = ipState
} else if !ipState.egressNames.Has(egressName) {
ipState.egressNames.Insert(egressName)
}
var err error
if isLocalIP {
// Ensure the Egress IP has a mark allocated when it's a local IP.
if ipState.mark == 0 {
ipState.mark, err = c.markAllocator.allocate()
if err != nil {
return 0, fmt.Errorf("error allocating mark for IP %s: %v", egressIP, err)
}
}
// Ensure datapath is installed properly.
if !ipState.flowsInstalled {
if err := c.ofClient.InstallSNATMarkFlows(ipState.egressIP, ipState.mark); err != nil {
return 0, fmt.Errorf("error installing SNAT mark flows for IP %s: %v", ipState.egressIP, err)
}
ipState.flowsInstalled = true
}
if !ipState.ruleInstalled {
if err := c.routeClient.AddSNATRule(ipState.egressIP, ipState.mark); err != nil {
return 0, fmt.Errorf("error installing SNAT rule for IP %s: %v", ipState.egressIP, err)
}
ipState.ruleInstalled = true
}
if err := c.installPolicyRoute(ipState, subnetInfo); err != nil {
return 0, fmt.Errorf("error installing policy route for IP %s: %v", ipState.egressIP, err)
}
} else {
// Ensure datapath is uninstalled properly.
if err := c.uninstallPolicyRoute(ipState); err != nil {
return 0, fmt.Errorf("error uninstalling policy routing for IP %s: %v", ipState.egressIP, err)
}
if ipState.ruleInstalled {
if err := c.routeClient.DeleteSNATRule(ipState.mark); err != nil {
return 0, fmt.Errorf("error uninstalling SNAT rule for IP %s: %v", ipState.egressIP, err)
}
ipState.ruleInstalled = false
}
if ipState.flowsInstalled {
if err := c.ofClient.UninstallSNATMarkFlows(ipState.mark); err != nil {
return 0, fmt.Errorf("error uninstalling SNAT mark flows for IP %s: %v", ipState.egressIP, err)
}
ipState.flowsInstalled = false
}
if ipState.mark != 0 {
err := c.markAllocator.release(ipState.mark)
if err != nil {
return 0, fmt.Errorf("error releasing mark for IP %s: %v", egressIP, err)
}
ipState.mark = 0
}
}
return ipState.mark, nil
}
func bandwidthToRateLimitMeter(bandwidth *crdv1b1.Bandwidth, meterID uint32) *rateLimitMeter {
if bandwidth == nil {
return nil
}
rate, err := resource.ParseQuantity(bandwidth.Rate)
if err != nil {
klog.ErrorS(err, "Invalid bandwidth rate configured for Egress", "rate", bandwidth.Rate)
return nil
}
burst, err := resource.ParseQuantity(bandwidth.Burst)
if err != nil {
klog.ErrorS(err, "Invalid bandwidth burst size configured for Egress", "burst", bandwidth.Burst)
return nil
}
return &rateLimitMeter{
MeterID: meterID,
Rate: uint32(rate.Value() / 1000),
Burst: uint32(burst.Value() / 1000),
}
}
func (c *EgressController) realizeEgressQoS(egressName string, eState *egressState, mark uint32, bandwidth *crdv1b1.Bandwidth) error {
if !c.trafficShapingEnabled {
if bandwidth != nil {
klog.InfoS("Bandwidth in the Egress is ignored because OVS meters are not supported or trafficShaping is not enabled in Antrea-agent config.", "EgressName", egressName)
}
return nil
}
var desiredRateLimit *rateLimitMeter
// QoS is desired only if the Egress is configured on this Node.
if mark != 0 {
desiredRateLimit = bandwidthToRateLimitMeter(bandwidth, mark)
}
// Nothing changes.
if eState.rateLimitMeter.Equals(desiredRateLimit) {
return nil
}
// It's desired to have QoS on this Node, install/override it.
if desiredRateLimit != nil {
if err := c.ofClient.InstallEgressQoS(mark, desiredRateLimit.Rate, desiredRateLimit.Burst); err != nil {
return err
}
eState.rateLimitMeter = desiredRateLimit
return nil
}
// It's undesired to have QoS on this Node, uninstall it.
if eState.rateLimitMeter != nil {
if err := c.ofClient.UninstallEgressQoS(eState.rateLimitMeter.MeterID); err != nil {
return err
}
eState.rateLimitMeter = nil
}
return nil
}
// unrealizeEgressIP unrealizes an Egress IP, reverts what realizeEgressIP does.
// For a local Egress IP, only when the last Egress unrealizes the Egress IP, it will releases the IP's mark and
// uninstalls corresponding flows and iptables rule.
func (c *EgressController) unrealizeEgressIP(egressName, egressIP string) error {
c.egressIPStatesMutex.Lock()
defer c.egressIPStatesMutex.Unlock()
ipState, exist := c.egressIPStates[egressIP]
// The Egress IP was not configured before, do nothing.
if !exist {
return nil
}
// Unlink the Egress from the EgressIP. If it's the last Egress referring to it, uninstall its datapath rules and
// release the mark if installed.
ipState.egressNames.Delete(egressName)
if len(ipState.egressNames) > 0 {
return nil
}
if ipState.mark != 0 {
if err := c.uninstallPolicyRoute(ipState); err != nil {
return err
}
if ipState.ruleInstalled {
if err := c.routeClient.DeleteSNATRule(ipState.mark); err != nil {
return err
}
ipState.ruleInstalled = false
}
if ipState.flowsInstalled {
if err := c.ofClient.UninstallSNATMarkFlows(ipState.mark); err != nil {
return err
}
ipState.flowsInstalled = false
}
c.markAllocator.release(ipState.mark)
}
delete(c.egressIPStates, egressIP)
return nil
}
func (c *EgressController) getEgressState(egressName string) (*egressState, bool) {
c.egressStatesMutex.RLock()
defer c.egressStatesMutex.RUnlock()
state, exists := c.egressStates[egressName]
return state, exists
}
func (c *EgressController) deleteEgressState(egressName string) {
c.egressStatesMutex.Lock()
defer c.egressStatesMutex.Unlock()
delete(c.egressStates, egressName)
}
func (c *EgressController) newEgressState(egressName string, egressIP string) *egressState {
c.egressStatesMutex.Lock()
defer c.egressStatesMutex.Unlock()
state := &egressState{
egressIP: egressIP,
ofPorts: sets.New[int32](),
pods: sets.New[string](),
}
c.egressStates[egressName] = state
return state
}
// bindPodEgress binds the Pod with the Egress and returns whether this Egress is the effective one for the Pod.
func (c *EgressController) bindPodEgress(pod, egress string) bool {
c.egressBindingsMutex.Lock()
defer c.egressBindingsMutex.Unlock()
binding, exists := c.egressBindings[pod]
if !exists {
// Promote itself as the effective Egress if there was not one.
c.egressBindings[pod] = &egressBinding{
effectiveEgress: egress,
alternativeEgresses: sets.New[string](),
}
return true
}
if binding.effectiveEgress == egress {
return true
}
if !binding.alternativeEgresses.Has(egress) {
binding.alternativeEgresses.Insert(egress)
}
return false
}
// unbindPodEgress unbinds the Pod with the Egress.
// If the unbound Egress was the effective one for the Pod and there are any alternative ones, it will return the new
// effective Egress and true. Otherwise it return empty string and false.
func (c *EgressController) unbindPodEgress(pod, egress string) (string, bool) {
c.egressBindingsMutex.Lock()
defer c.egressBindingsMutex.Unlock()
// The binding must exist.
binding := c.egressBindings[pod]
if binding.effectiveEgress == egress {
var popped bool
binding.effectiveEgress, popped = binding.alternativeEgresses.PopAny()
if !popped {
// Remove the Pod's binding if there is no alternative.
delete(c.egressBindings, pod)
return "", false
}
return binding.effectiveEgress, true
}
binding.alternativeEgresses.Delete(egress)
return "", false
}
func (c *EgressController) updateEgressStatus(egress *crdv1b1.Egress, egressIP string, scheduleErr error) error {
isLocal := false
if egressIP != "" {
isLocal = c.localIPDetector.IsLocalIP(egressIP)
}
desiredStatus := &crdv1b1.EgressStatus{}
if isLocal {
desiredStatus.EgressNode = c.nodeName
desiredStatus.EgressIP = egressIP
if isEgressSchedulable(egress) {
desiredStatus.Conditions = []crdv1b1.EgressCondition{
{
Type: crdv1b1.IPAssigned,
Status: corev1.ConditionTrue,
LastTransitionTime: metav1.Now(),
Reason: "Assigned",
Message: "EgressIP is successfully assigned to EgressNode",
},
}
}
} else if egressIP == "" {
// Select one Node to update false status among all Nodes.
// We don't care about the value of egress.Spec.EgressIP, just use it to reach a consensus among all agents
// about which one should do the update.
nodeToUpdateStatus, err := c.cluster.SelectNodeForIP(egress.Spec.EgressIP, "")
if err != nil {
return err
}
// Skip if the Node is not the selected one.
if nodeToUpdateStatus != c.nodeName {
return nil
}
desiredStatus.EgressNode = ""
desiredStatus.EgressIP = ""
// If the error is nil, it means the Egress hasn't been processed yet.
// The scheduler will get a result for the Egress very soon regardless of success or failure and trigger the
// controller to process it another time, so we avoid generating a transient state here, which may lead to some
// back-off retries due to updating conflict.
if scheduleErr != nil {
desiredStatus.Conditions = []crdv1b1.EgressCondition{
{
Type: crdv1b1.IPAssigned,
Status: corev1.ConditionFalse,
LastTransitionTime: metav1.Now(),
Reason: "AssignmentError",
Message: fmt.Sprintf("Failed to assign the IP to EgressNode: %v", scheduleErr),
},
}
}
} else {
// The Egress IP is assigned to a Node (egressIP != "") but it's not this Node (isLocal == false), do nothing.
return nil
}
toUpdate := egress.DeepCopy()
var updateErr, getErr error
if err := retry.RetryOnConflict(retry.DefaultRetry, func() error {
if compareEgressStatus(&toUpdate.Status, desiredStatus) {
return nil
}
// Must make a copy here as we will append more conditions. If it's appended to desiredStatus directly, there
// would be duplicate conditions when the function retries.
statusToUpdate := desiredStatus.DeepCopy()
// Copy conditions other than crdv1b1.IPAssigned to statusToUpdate.
for _, c := range toUpdate.Status.Conditions {
if c.Type != crdv1b1.IPAssigned {
statusToUpdate.Conditions = append(statusToUpdate.Conditions, c)
}
}
toUpdate.Status = *statusToUpdate
klog.V(2).InfoS("Updating Egress status", "Egress", egress.Name, "oldNode", egress.Status.EgressNode, "newNode", toUpdate.Status.EgressNode)
_, updateErr = c.crdClient.CrdV1beta1().Egresses().UpdateStatus(context.TODO(), toUpdate, metav1.UpdateOptions{})
if updateErr != nil && errors.IsConflict(updateErr) {
if toUpdate, getErr = c.crdClient.CrdV1beta1().Egresses().Get(context.TODO(), egress.Name, metav1.GetOptions{}); getErr != nil {
return getErr
}
}
// Return the error from UPDATE.
return updateErr
}); err != nil {
return err
}
klog.V(2).InfoS("Updated Egress status", "Egress", egress.Name)
metrics.AntreaEgressStatusUpdates.Inc()
return nil
}
func (c *EgressController) syncEgress(egressName string) error {
startTime := time.Now()
defer func() {
klog.V(4).Infof("Finished syncing Egress for %s. (%v)", egressName, time.Since(startTime))
}()
egress, err := c.egressLister.Get(egressName)
if err != nil {
// The Egress has been removed, clean it up.
if errors.IsNotFound(err) {
eState, exist := c.getEgressState(egressName)
// The Egress hasn't been installed, do nothing.
if !exist {
return nil