-
Notifications
You must be signed in to change notification settings - Fork 4
/
ipam.go
1156 lines (1006 loc) · 35.6 KB
/
ipam.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 (c) 2021 Baidu, Inc. All Rights Reserved.
*
* 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 bcc
import (
"context"
"fmt"
"net"
"sort"
"sync"
"time"
enisdk "github.com/baidubce/bce-sdk-go/services/eni"
"github.com/juju/ratelimit"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/selection"
"k8s.io/apimachinery/pkg/util/clock"
utilerrors "k8s.io/apimachinery/pkg/util/errors"
"k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/informers"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/kubernetes/scheme"
v1core "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"
"github.com/baidubce/baiducloud-cce-cni-driver/pkg/apis/networking/v1alpha1"
networkingv1alpha1 "github.com/baidubce/baiducloud-cce-cni-driver/pkg/apis/networking/v1alpha1"
"github.com/baidubce/baiducloud-cce-cni-driver/pkg/bce/cloud"
"github.com/baidubce/baiducloud-cce-cni-driver/pkg/bce/metadata"
"github.com/baidubce/baiducloud-cce-cni-driver/pkg/config/types"
"github.com/baidubce/baiducloud-cce-cni-driver/pkg/controller/subnet"
"github.com/baidubce/baiducloud-cce-cni-driver/pkg/controller/topology_spread"
datastorev1 "github.com/baidubce/baiducloud-cce-cni-driver/pkg/eniipam/datastore/v1"
ipamgeneric "github.com/baidubce/baiducloud-cce-cni-driver/pkg/eniipam/ipam"
"github.com/baidubce/baiducloud-cce-cni-driver/pkg/eniipam/ipam/ipcache"
"github.com/baidubce/baiducloud-cce-cni-driver/pkg/eniipam/util"
"github.com/baidubce/baiducloud-cce-cni-driver/pkg/generated/clientset/versioned"
crdinformers "github.com/baidubce/baiducloud-cce-cni-driver/pkg/generated/informers/externalversions"
"github.com/baidubce/baiducloud-cce-cni-driver/pkg/metric"
utileni "github.com/baidubce/baiducloud-cce-cni-driver/pkg/nodeagent/util/eni"
utilippool "github.com/baidubce/baiducloud-cce-cni-driver/pkg/nodeagent/util/ippool"
k8sutil "github.com/baidubce/baiducloud-cce-cni-driver/pkg/util/k8s"
log "github.com/baidubce/baiducloud-cce-cni-driver/pkg/util/logger"
)
const (
// minPrivateIPLifeTime is the lifetime of a private ip (from allocation to release), aim to trade off db slave delay
minPrivateIPLifeTime = 5 * time.Second
minIdleIPPoolSize = 1
rateLimitErrorSleepPeriod = time.Millisecond * 200
rateLimitErrorJitterFactor = 5
increasePoolSizePerNode = 10
)
func (ipam *IPAM) Ready(_ context.Context) bool {
return ipam.cacheHasSynced
}
func NewIPAM(
kubeClient kubernetes.Interface,
crdClient versioned.Interface,
kubeInformer informers.SharedInformerFactory,
crdInformer crdinformers.SharedInformerFactory,
bceClient cloud.Interface,
cniMode types.ContainerNetworkMode,
vpcID string,
clusterID string,
subnetSelectionPolicy SubnetSelectionPolicy,
ipMutatingRate float64,
ipMutatingBurst int64,
idleIPPoolMinSize int,
idleIPPoolMaxSize int,
batchAddIPNum int,
eniSyncPeriod time.Duration,
gcPeriod time.Duration,
_ bool,
) (ipamgeneric.Interface, error) {
eventBroadcaster := record.NewBroadcaster()
eventBroadcaster.StartRecordingToSink(&v1core.EventSinkImpl{
Interface: kubeClient.CoreV1().Events(""),
})
recorder := eventBroadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: "cce-ipam"})
// build subsystem controller
sbnController := subnet.NewSubnetController(crdInformer, crdClient, bceClient, eventBroadcaster)
pstsController := topology_spread.NewTopologySpreadController(kubeInformer, crdInformer, crdClient, eventBroadcaster, sbnController)
// min size of idle ip pool must >= 1
if idleIPPoolMinSize < minIdleIPPoolSize {
idleIPPoolMinSize = minIdleIPPoolSize
}
ipam := &IPAM{
eventBroadcaster: eventBroadcaster,
eventRecorder: recorder,
kubeInformer: kubeInformer,
kubeClient: kubeClient,
crdInformer: crdInformer,
crdClient: crdClient,
cloud: bceClient,
clock: clock.RealClock{},
cniMode: cniMode,
vpcID: vpcID,
clusterID: clusterID,
subnetSelectionPolicy: subnetSelectionPolicy,
eniSyncPeriod: eniSyncPeriod,
gcPeriod: gcPeriod,
eniCache: ipcache.NewCacheMapArray[*enisdk.Eni](),
privateIPNumCache: make(map[string]int),
possibleLeakedIPCache: make(map[eniAndIPAddrKey]time.Time),
addIPBackoffCache: ipcache.NewCacheMap[*wait.Backoff](),
allocated: ipcache.NewCacheMap[*networkingv1alpha1.WorkloadEndpoint](),
reusedIPs: ipcache.NewReuseIPAndWepPool(),
datastore: datastorev1.NewDataStore(),
bucket: ratelimit.NewBucketWithRate(ipMutatingRate, ipMutatingBurst),
idleIPPoolMinSize: idleIPPoolMinSize,
idleIPPoolMaxSize: idleIPPoolMaxSize,
batchAddIPNum: batchAddIPNum,
buildDataStoreEventChan: make(map[string]chan *event),
increasePoolEventChan: make(map[string]chan *event),
cacheHasSynced: false,
// subsystem
sbnCtl: sbnController,
tsCtl: pstsController,
}
ipam.exclusiveSubnetCond = sync.NewCond(&ipam.lock)
ipam.exclusiveSubnetFlag = make(map[string]bool)
return ipam, nil
}
func (ipam *IPAM) Run(ctx context.Context, stopCh <-chan struct{}) error {
defer func() {
runtime.HandleCrash()
}()
log.Info(ctx, "Starting cce ipam controller for BCC")
defer log.Info(ctx, "Shutting down cce ipam controller for BCC")
log.Infof(ctx, "limit ip mutating rate to %v, burst to %v", ipam.bucket.Rate(), ipam.bucket.Capacity())
nodeInformer := ipam.kubeInformer.Core().V1().Nodes().Informer()
podInformer := ipam.kubeInformer.Core().V1().Pods().Informer()
stsInformer := ipam.kubeInformer.Apps().V1().StatefulSets().Informer()
wepInformer := ipam.crdInformer.Cce().V1alpha1().WorkloadEndpoints().Informer()
ippoolInformer := ipam.crdInformer.Cce().V1alpha1().IPPools().Informer()
subnetInformer := ipam.crdInformer.Cce().V1alpha1().Subnets().Informer()
pstsInformer := ipam.crdInformer.Cce().V1alpha1().PodSubnetTopologySpreads().Informer()
wepInformer.AddEventHandler(ipam.reusedIPs)
ipam.kubeInformer.Start(stopCh)
ipam.crdInformer.Start(stopCh)
if !cache.WaitForNamedCacheSync(
"cce-ipam",
stopCh,
nodeInformer.HasSynced,
podInformer.HasSynced,
stsInformer.HasSynced,
wepInformer.HasSynced,
ippoolInformer.HasSynced,
subnetInformer.HasSynced,
pstsInformer.HasSynced,
) {
log.Warning(ctx, "failed WaitForCacheSync, timeout")
return nil
} else {
log.Info(ctx, "WaitForCacheSync done")
}
// rebuild allocated cache
err := ipam.buildAllocatedCache(ctx)
if err != nil {
return err
}
// rebuild datastore cache
err = ipam.buildAllocatedNodeCache(ctx)
if err != nil {
return err
}
group := &wait.Group{}
group.Start(func() {
if err := ipam.syncENI(stopCh); err != nil {
log.Errorf(ctx, "failed to sync eni info: %v", err)
}
})
group.Start(func() {
if err := ipam.gc(stopCh); err != nil {
log.Errorf(ctx, "failed to start ipam gc: %v", err)
}
})
group.Start(func() {
if err := ipam.checkIdleIPPoolPeriodically(); err != nil {
log.Errorf(ctx, "failed to start checkIdleIPPoolPeriodically: %v", err)
}
})
subsystemRun := func(sc subsystemController) {
sc.Run(stopCh)
}
// run subsystem controller
group.Start(func() {
subsystemRun(ipam.sbnCtl.(subsystemController))
})
group.Start(func() {
subsystemRun(ipam.tsCtl.(subsystemController))
})
group.Start(func() {
if err := ipam.reconcileRelationOfWepEni(stopCh); err != nil {
log.Errorf(ctx, "failed to start reconcileRelationOfWepEni: %v", err)
}
})
// k8s resource and ip cache are synced
ipam.cacheHasSynced = true
group.Wait()
<-stopCh
return nil
}
func (ipam *IPAM) buildAllocatedCache(ctx context.Context) error {
selector, err := wepListerSelector()
if err != nil {
log.Errorf(ctx, "error parsing requirement: %v", err)
return err
}
wepList, err := ipam.crdInformer.Cce().V1alpha1().WorkloadEndpoints().Lister().List(selector)
if err != nil {
return err
}
for _, wep := range wepList {
nwep := wep.DeepCopy()
ipam.allocated.Add(wep.Spec.IP, nwep)
log.Infof(ctx, "build allocated pod cache: found IP %v assigned to pod (%v %v)", wep.Spec.IP, wep.Namespace, wep.Name)
}
return nil
}
func (ipam *IPAM) allocateIPForFixedIPPod(ctx context.Context, node *v1.Node, pod *v1.Pod, containerID string,
enis []*enisdk.Eni, wep *v1alpha1.WorkloadEndpoint, deadline time.Time) (*v1alpha1.WorkloadEndpoint, error) {
var allocatedIP string
var allocatedEni *enisdk.Eni
var allocatedErr error
// 1.1 try to allocate fixed ip
allocatedIP, allocatedEni, allocatedErr = ipam.allocateFixedIPFromCloud(ctx, node, enis, wep, deadline)
if allocatedErr != nil {
log.Warningf(ctx, "allocate fixed ip %s for pod (%s %s) failed: %s",
wep.Spec.IP, wep.Namespace, wep.Name, allocatedErr)
// 1.2. if 1.1 failed, try to allocate new ip for sts pod
if timeoutErr := assertDeadline(deadline); timeoutErr != nil {
return nil, timeoutErr
}
log.Infof(ctx, "try to allocate new ip for pod (%s %s)", wep.Namespace, wep.Name)
allocatedIP, allocatedEni, allocatedErr = ipam.tryToAllocateIPFromCache(ctx, node, enis, deadline)
if allocatedErr != nil {
log.Errorf(ctx, "allocate ip for pod (%s %s) failed: %s", wep.Namespace, wep.Name, allocatedErr)
return nil, allocatedErr
}
}
// 2. update wep
newWep := ipam.fillFieldsToWep(wep, pod, containerID, allocatedIP, allocatedEni)
_, updateErr := ipam.crdClient.CceV1alpha1().WorkloadEndpoints(newWep.Namespace).Update(ctx, newWep, metav1.UpdateOptions{})
if updateErr != nil {
log.Errorf(ctx, "failed to update wep for pod (%s %s): %s", pod.Namespace, pod.Name, updateErr)
time.Sleep(minPrivateIPLifeTime)
if rollbackErr := ipam.tryDeleteSubnetIPRetainAllocateCache(ctx, newWep); rollbackErr != nil {
log.Errorf(ctx, "rollback wep for pod (%s %s) failed: %s", pod.Namespace, pod.Name, rollbackErr)
}
return nil, updateErr
}
log.Infof(ctx, "update wep with spec %+v for pod (%v %v) successfully", newWep.Spec, newWep.Namespace, newWep.Name)
// 3. update cache ip and wep
ipam.allocated.Add(allocatedIP, newWep)
return newWep, nil
}
func (ipam *IPAM) allocateFixedIPFromCloud(ctx context.Context, node *v1.Node, enis []*enisdk.Eni,
wep *v1alpha1.WorkloadEndpoint, deadline time.Time) (string, *enisdk.Eni, error) {
var namespace, name = wep.Namespace, wep.Name
// Note: here DeletePrivateIP and AddPrivateIP should be atomic. we leverage a lock to do this
// Ensures private ip not attached to other eni
deleteErr := ipam.__tryDeleteIPByIPAndENI(ctx, wep.Spec.Node, wep.Spec.IP, wep.Spec.ENIID, true)
if deleteErr != nil && !cloud.IsErrorENIPrivateIPNotFound(deleteErr) {
log.Errorf(ctx, "error delete private IP %v for pod (%v %v): %v", wep.Spec.IP, namespace, name, deleteErr)
if cloud.IsErrorRateLimit(deleteErr) {
time.Sleep(wait.Jitter(rateLimitErrorSleepPeriod, rateLimitErrorJitterFactor))
}
}
// try to allocate fixed ip
var ipToAllocate = wep.Spec.IP
var backoff = ipamgeneric.CCECniTimeout / time.Duration(len(enis))
var addIPErrors []error
var successEni *enisdk.Eni
var successIP string
for _, oneEni := range enis {
if timeoutErr := assertDeadline(deadline); timeoutErr != nil {
return "", nil, timeoutErr
}
log.Infof(ctx, "try to add IP %v to %v", ipToAllocate, oneEni.EniId)
ipResult, addErr := ipam.batchAddPrivateIP(ctx, []string{ipToAllocate}, 0, oneEni.EniId)
if addErr != nil {
addIPErrors = append(addIPErrors, addErr)
ipam.handleAllocateError(ctx, addErr, oneEni, backoff)
if cloud.IsErrorPrivateIPInUse(addErr) {
break
}
// failed: continue to try other eni
if cloud.IsErrorRateLimit(addErr) {
time.Sleep(wait.Jitter(rateLimitErrorSleepPeriod, rateLimitErrorJitterFactor))
}
} else {
// success
successEni = oneEni
successIP = ipResult[0]
break
}
}
if successEni == nil {
return "", nil, fmt.Errorf("all %d enis binded cannot add IP %s: %v",
len(enis), wep.Spec.IP, utilerrors.NewAggregate(addIPErrors))
}
log.Infof(ctx, "add private IP %s for pod (%s %s) successfully", successIP, namespace, name)
ipam.incPrivateIPNumCache(successEni.EniId, false)
storeErr := ipam.datastore.AddPrivateIPToStore(node.Name, successEni.EniId, successIP, true)
if storeErr != nil {
log.Warningf(ctx, "add private IP %s to store failed: %s", successIP, storeErr)
}
metric.MultiEniMultiIPEniIPCount.WithLabelValues(metric.MetaInfo.ClusterID, metric.MetaInfo.VPCID,
successEni.SubnetId).Inc()
return successIP, successEni, nil
}
func (ipam *IPAM) allocateIPForOrdinaryPod(ctx context.Context, node *v1.Node, pod *v1.Pod, containerID string,
enis []*enisdk.Eni, wep *v1alpha1.WorkloadEndpoint, deadline time.Time) (*v1alpha1.WorkloadEndpoint, error) {
// 1. allocate ip from cache
allocatedIP, allocatedEni, allocatedErr := ipam.tryToAllocateIPFromCache(ctx, node, enis, deadline)
if allocatedErr != nil {
log.Errorf(ctx, "allocate ip for pod (%s %s) failed: %s", pod.Namespace, pod.Name, allocatedErr)
return nil, allocatedErr
}
// 2. update or create wep
newWep := ipam.fillFieldsToWep(wep, pod, containerID, allocatedIP, allocatedEni)
if wep == nil {
// create wep
_, createErr := ipam.crdClient.CceV1alpha1().WorkloadEndpoints(newWep.Namespace).
Create(ctx, newWep, metav1.CreateOptions{})
if createErr != nil {
if rollbackErr := ipam.tryDeleteIPByWep(ctx, newWep); rollbackErr != nil {
log.Errorf(ctx, "rollback wep for pod (%s %s) failed: %s", pod.Namespace, pod.Name, rollbackErr)
}
return nil, createErr
}
} else {
// update wep
_, updateErr := ipam.crdClient.CceV1alpha1().WorkloadEndpoints(newWep.Namespace).
Update(ctx, newWep, metav1.UpdateOptions{})
if updateErr != nil {
time.Sleep(minPrivateIPLifeTime)
if rollbackErr := ipam.tryDeleteSubnetIPRetainAllocateCache(ctx, newWep); rollbackErr != nil {
log.Errorf(ctx, "rollback wep for pod (%s %s) failed: %s", pod.Namespace, pod.Name, rollbackErr)
}
return nil, updateErr
}
}
log.Infof(ctx, "update or create wep with spec %+v for pod (%v %v) successfully",
newWep.Spec, newWep.Namespace, newWep.Name)
// 3. update cache ip and wep
ipam.allocated.Add(allocatedIP, newWep)
return newWep, nil
}
// tryToAllocateIPFromCache get ip from local cache
// increasing the pool if datastore has no available ip
func (ipam *IPAM) tryToAllocateIPFromCache(ctx context.Context, node *v1.Node, enis []*enisdk.Eni, deadline time.Time) (
ipResult string, eni *enisdk.Eni, err error) {
firstEvent := true
// it takes 1s to allocate ip from cloud, retry 5 and wait 200ms+ per times
backoff := wait.Backoff{
Steps: 5,
Duration: 200 * time.Millisecond,
Factor: 1.0,
Jitter: 0.1,
}
err = wait.ExponentialBackoff(backoff, func() (done bool, err error) {
if timeoutErr := assertDeadline(deadline); timeoutErr != nil {
return false, timeoutErr
}
if ipam.canAllocateIP(ctx, node.Name, enis) {
return true, nil
}
if err := ipam.assertNodeCanIncreasePool(ctx, node, enis); err != nil {
return true, err
}
// only send one increase pool event for one ctx
if firstEvent {
ipam.sendIncreasePoolEvent(ctx, node, enis, true)
firstEvent = false
}
return false, nil
})
if err == wait.ErrWaitTimeout {
return "", nil, fmt.Errorf("allocate ip for node %v error", node.Name)
}
if err != nil {
return "", nil, err
}
return ipam.allocateIPFromCache(ctx, node.Name, enis)
}
func (ipam *IPAM) canAllocateIP(_ context.Context, nodeName string, enis []*enisdk.Eni) bool {
var (
total = 0
used = 0
)
for _, eni := range enis {
t, u, err := ipam.datastore.GetENIStats(nodeName, eni.EniId)
if err == nil {
total += t
used += u
}
}
return total > used
}
func (ipam *IPAM) allocateIPFromCache(ctx context.Context, node string, enis []*enisdk.Eni) (string, *enisdk.Eni, error) {
var (
failedEniList []string
)
ipam.sortENIByDatastoreStats(node, enis, false)
// iterate each subnet, try to allocate
for _, eni := range enis {
ipResult, err := ipam.datastore.AllocatePodPrivateIPByENI(node, eni.EniId)
if err == nil {
// allocate one successfully
return ipResult, eni, nil
}
log.Warningf(ctx, "datastore try allocate ip for node %v in eni %v failed: %v", node, eni.EniId, err)
failedEniList = append(failedEniList, eni.EniId)
}
return "", nil, fmt.Errorf("no available ip address in datastore for node %v in enis: %v", node, failedEniList)
}
func (ipam *IPAM) batchAllocateIPFromCloud(
ctx context.Context,
eni *enisdk.Eni,
node *v1.Node,
batchAddNum int,
backoffCap time.Duration,
) ([]string, error) {
var ipResult []string
var err error
for batchAddNum > 0 {
if err = ipam.assertEniCanIncreasePool(ctx, node, eni); err != nil {
break
}
ipResult, err = ipam.batchAllocateIPWithBackoff(ctx, batchAddNum, eni)
if err == nil {
log.Infof(ctx, "batch add %d private ip(s) for %s on eni %s successfully, %v",
batchAddNum, node.Name, eni.EniId, ipResult)
break
}
if err != nil {
// retry condition: batchAddNum > 1 && isErrorNeedExponentialBackoff
log.Warningf(ctx, "batch add %d private ip(s) for node %s failed: %s", batchAddNum, node.Name, err)
if batchAddNum == 1 {
ipam.handleAllocateError(ctx, err, eni, backoffCap)
}
if isErrorNeedExponentialBackoff(err) {
// decrease batchAddNum then retry
batchAddNum = batchAddNum >> 1
continue
}
// don't retry for other errors
break
}
}
if err != nil {
return nil, err
}
for _, allocatedIP := range ipResult {
ipam.incPrivateIPNumCache(eni.EniId, false)
err := ipam.datastore.AddPrivateIPToStore(node.Name, eni.EniId, allocatedIP, false)
if err != nil {
log.Errorf(ctx, "add private ip %s to datastore failed: %v", allocatedIP, err)
}
metric.MultiEniMultiIPEniIPCount.WithLabelValues(metric.MetaInfo.ClusterID, metric.MetaInfo.VPCID, eni.SubnetId).Inc()
}
return ipResult, nil
}
// handleAllocateError
//
// isErrorSubnetHasNoMoreIP: declare subnet = no more ip
// isErrorNeedExponentialBackoff: add backoff to addIPBackoffCache
func (ipam *IPAM) handleAllocateError(ctx context.Context, allocateErr error, eni *enisdk.Eni, backoffCap time.Duration) {
if cloud.IsErrorSubnetHasNoMoreIP(allocateErr) {
if e := ipam.sbnCtl.DeclareSubnetHasNoMoreIP(ctx, eni.SubnetId, true); e != nil {
log.Errorf(ctx, "failed to patch subnet %v that has no more ip: %v", eni.SubnetId, e)
}
}
if isErrorNeedExponentialBackoff(allocateErr) {
if _, ok := ipam.addIPBackoffCache.Get(eni.EniId); !ok {
ipam.addIPBackoffCache.Add(eni.EniId, util.NewBackoffWithCap(backoffCap))
log.Infof(ctx, "add backoff with cap %s for eni %s due to error: %v",
backoffCap, eni.EniId, allocateErr)
}
}
}
func (ipam *IPAM) handleIncreasePoolEvent(ctx context.Context, nodeName string, ch chan *event) {
log.Infof(ctx, "start increase pool goroutine for node %v", nodeName)
for e := range ch {
var (
enis = e.enis
node = e.node
ctx = e.ctx
err error
)
if len(enis) == 0 {
log.Warningf(ctx, "no eni in node %s, skip increase pool", nodeName)
continue
}
if ipam.canIgnoreIncreasingEvent(ctx, e) {
continue
}
ipam.sortENIByDatastoreStats(node.Name, enis, true)
backoff := ipamgeneric.CCECniTimeout / time.Duration(len(enis))
for _, eni := range enis {
_, err = ipam.batchAllocateIPFromCloud(ctx, eni, node, ipam.batchAddIPNum, backoff)
if err == nil {
break
}
if cloud.IsErrorRateLimit(err) {
// wait to try other eni
time.Sleep(wait.Jitter(rateLimitErrorSleepPeriod, rateLimitErrorJitterFactor))
}
log.Warningf(ctx, "failed to batch add ip on eni %s: %s", eni.EniId, err)
}
}
log.Infof(ctx, "closed channel for node %s, exit...", nodeName)
}
func (ipam *IPAM) canIgnoreIncreasingEvent(ctx context.Context, evt *event) bool {
if evt.passive && ipam.canAllocateIP(ctx, evt.node.Name, evt.enis) {
return true
}
if !evt.passive && ipam.idleIPNum(evt.node.Name) >= ipam.idleIPPoolMinSize {
return true
}
return false
}
func (ipam *IPAM) buildAllocatedNodeCache(ctx context.Context) error {
var (
wg sync.WaitGroup
ch = make(chan struct{}, 10)
)
bccNodeSelector, _ := bccNodeListerSelector()
nodes, err := ipam.kubeInformer.Core().V1().Nodes().Lister().List(bccNodeSelector)
if err != nil {
log.Errorf(ctx, "failed to list bcc nodes: %v", err)
return err
}
for _, node := range nodes {
ch <- struct{}{}
wg.Add(1)
go func(node *v1.Node) {
defer func() {
wg.Done()
<-ch
}()
ctx := log.NewContext()
instanceID, err := util.GetInstanceIDFromNode(node)
if err != nil {
return
}
err = ipam.rebuildNodeDataStoreCache(ctx, node, instanceID)
if err != nil {
log.Errorf(ctx, "rebuild cache for node %v error: %v", node.Name, err)
}
}(node)
}
wg.Wait()
return nil
}
func (ipam *IPAM) rebuildNodeDataStoreCache(ctx context.Context, node *v1.Node, instanceID string) error {
listArgs := enisdk.ListEniArgs{
VpcId: ipam.vpcID,
InstanceId: instanceID,
Name: fmt.Sprintf("%s/", ipam.clusterID),
}
var enis []enisdk.Eni
// list eni with backoff
err := wait.ExponentialBackoff(retry.DefaultBackoff, func() (bool, error) {
var err error
enis, err = ipam.cloud.ListENIs(ctx, listArgs)
if err != nil {
log.Errorf(ctx, "failed to list enis attached to instance %s: %v", instanceID, err)
return false, nil
}
return true, nil
})
if err != nil {
log.Errorf(ctx, "failed to backoff list enis attached to instance %s: %v", instanceID, err)
return err
}
err = ipam.datastore.AddNodeToStore(node.Name, instanceID)
if err != nil {
log.Errorf(ctx, "failed to add node to datastore: %v", err)
return err
}
ipam.lock.Lock()
defer ipam.lock.Unlock()
// add ip to store
for _, eni := range enis {
ipam.removeAddIPBackoffCache(eni.EniId, true)
if err := ipam.datastore.AddENIToStore(node.Name, eni.EniId); err == nil {
log.Infof(ctx, "add eni %v from node %v to datastore successfully", eni.EniId, node.Name)
}
sbn, err := ipam.sbnCtl.Get(eni.SubnetId)
if err != nil {
log.Errorf(ctx, "get subnet %s by eni %s on node %s error %v", eni.SubnetId, eni.EniId, node.Name, err)
continue
}
// validate ipv4 in CIDR
_, ipNet, err := net.ParseCIDR(sbn.Spec.CIDR)
if err != nil {
log.Errorf(ctx, "parse subnet %s CIDR error by eni %s on node %s error %v", eni.SubnetId, eni.EniId, node.Name, err)
continue
}
for _, ip := range eni.PrivateIpSet {
if !ip.Primary {
// ipam will sync all weps to build allocated cache when it starts
assigned := ipam.allocated.Exists(ip.PrivateIpAddress)
// If the private IP is not in the CIDR of Eni, it means that it is a cross subnet IP
crossSubnet := !ipNet.Contains(net.ParseIP(ip.PrivateIpAddress))
if crossSubnet {
assigned = true
}
syncErr := ipam.datastore.Synchronized(func() error {
err := ipam.datastore.AddPrivateIPToStoreUnsafe(node.Name, eni.EniId, ip.PrivateIpAddress, assigned, crossSubnet)
if err != nil {
msg := fmt.Sprintf("add private ip %v to datastore failed: %v", ip.PrivateIpAddress, err)
log.Error(ctx, msg)
} else {
log.Infof(ctx, "add private ip %v(assigned: %v) from eni %v to node %v datastore successfully", ip.PrivateIpAddress, assigned, eni.EniId, node.Name)
}
return err
})
if syncErr != nil {
log.Warningf(ctx, "datastore Synchronized failed: %s", syncErr)
}
}
}
}
total, assigned, err := ipam.datastore.GetNodeStats(node.Name)
if err == nil {
log.Infof(ctx, "total, used at initialization for node %v: %v %v", node.Name, total, assigned)
}
return nil
}
func (ipam *IPAM) handleRebuildNodeDatastoreEvent(ctx context.Context, node *v1.Node, ch chan *event) error {
var (
nodeName = node.Name
)
for {
select {
case e, ok := <-ch:
if !ok {
ctx := log.NewContext()
log.Infof(ctx, "closed channel for node %v, exit...", nodeName)
return nil
}
log.Infof(ctx, "start rebuilding datastore for node %v", e.node.Name)
instanceID, err := util.GetInstanceIDFromNode(e.node)
if err != nil {
return err
}
ctx = e.ctx
if !ipam.datastore.NodeExistsInStore(nodeName) {
err := ipam.rebuildNodeDataStoreCache(ctx, e.node, instanceID)
if err != nil {
log.Errorf(ctx, "rebuild cache for node %v error: %v", nodeName, err)
} else {
log.Infof(ctx, "rebuild cache for node %v done", nodeName)
}
}
default:
ctx = log.NewContext()
if ipam.datastore.NodeExistsInStore(nodeName) {
log.Infof(ctx, "node %v already in datastore", nodeName)
return nil
}
}
}
}
func (ipam *IPAM) addIPBackoff(eniID string, cap time.Duration) {
ipam.addIPBackoffCache.AddIfNotExists(eniID, util.NewBackoffWithCap(cap))
}
func (ipam *IPAM) removeAddIPBackoffCache(eniID string, _ bool) bool {
return ipam.addIPBackoffCache.Delete(eniID)
}
func (ipam *IPAM) updateIPPoolStatus(ctx context.Context, node *v1.Node, instanceID string, enis []enisdk.Eni) error {
var (
eniStatus = map[string]v1alpha1.ENI{}
ippoolName = utilippool.GetNodeIPPoolName(node.Name)
)
for _, eni := range enis {
if eni.Status != utileni.ENIStatusInuse || !utileni.ENIOwnedByNode(&eni, ipam.clusterID, instanceID) {
continue
}
ippool, err := ipam.crdInformer.Cce().V1alpha1().IPPools().Lister().IPPools(v1.NamespaceDefault).Get(ippoolName)
if err != nil {
log.Errorf(ctx, "failed to get ippool %v: %v", ippoolName, err)
return err
}
// interfaceIndex cannot be fetched by eni-ipam, node-agent will update it
// we get it from origin crd and store it
var linkIndex int
if _, ok := ippool.Status.ENI.ENIs[eni.EniId]; ok {
linkIndex = ippool.Status.ENI.ENIs[eni.EniId].InterfaceIndex
} else {
linkIndex = -1
}
eniStatus[eni.EniId] = v1alpha1.ENI{
ID: eni.EniId,
MAC: eni.MacAddress,
AvailabilityZone: eni.ZoneName,
Description: eni.Description,
InterfaceIndex: linkIndex,
Subnet: eni.SubnetId,
PrivateIPSet: utileni.GetPrivateIPSet(&eni),
VPC: eni.VpcId,
}
}
retryErr := retry.RetryOnConflict(retry.DefaultRetry, func() error {
result, err := ipam.crdInformer.Cce().V1alpha1().IPPools().Lister().IPPools(v1.NamespaceDefault).Get(ippoolName)
if err != nil {
log.Errorf(ctx, "failed to get ippool %v: %v", ippoolName, err)
return err
}
result.Status.ENI.ENIs = eniStatus
_, updateErr := ipam.crdClient.CceV1alpha1().IPPools(v1.NamespaceDefault).Update(ctx, result, metav1.UpdateOptions{})
if updateErr != nil {
log.Errorf(ctx, "error updating ippool %v status: %v", ippoolName, updateErr)
return updateErr
}
return nil
})
if retryErr != nil {
log.Errorf(ctx, "retry: error updating ippool %v status: %v", ippoolName, retryErr)
return retryErr
}
return nil
}
func (ipam *IPAM) checkIdleIPPool() (bool, error) {
var (
ctx = log.NewContext()
wg sync.WaitGroup
ch = make(chan struct{}, 10)
)
bccNodeSelector, _ := bccNodeListerSelector()
nodes, err := ipam.kubeInformer.Core().V1().Nodes().Lister().List(bccNodeSelector)
if err != nil {
log.Errorf(ctx, "failed to list bbc nodes: %v", err)
return false, nil
}
for _, node := range nodes {
ch <- struct{}{}
wg.Add(1)
go func(node *v1.Node) {
defer func() {
wg.Done()
<-ch
}()
ctx = log.NewContext()
if !ipam.datastore.NodeExistsInStore(node.Name) {
return
}
idle := ipam.idleIPNum(node.Name)
if idle < ipam.idleIPPoolMinSize {
log.Infof(ctx, "ipam will increase pool due to idle ip num %v less than --idle-ip-pool-min-size %v", idle, ipam.idleIPPoolMinSize)
enis, ok := ipam.eniCache.Get(node.Name)
if !ok {
log.Warningf(ctx, "no eni in node %s", node.Name)
return
}
ipam.sendIncreasePoolEvent(ctx, node, enis, false)
}
}(node)
}
wg.Wait()
return false, nil
}
// sendIncreasePoolEvent send increase poll event to cache chan
// create chan if not exists
func (ipam *IPAM) sendIncreasePoolEvent(ctx context.Context, node *v1.Node, enis []*enisdk.Eni, passive bool) {
var (
evt = &event{
node: node,
enis: enis,
passive: passive,
ctx: ctx,
}
ch chan *event
ok bool
)
ipam.lock.Lock()
ch, ok = ipam.increasePoolEventChan[evt.node.Name]
if !ok {
ch = make(chan *event, increasePoolSizePerNode)
ipam.increasePoolEventChan[node.Name] = ch
go ipam.handleIncreasePoolEvent(ctx, node.Name, ch)
}
ipam.lock.Unlock()
select {
case ch <- evt:
return
default:
log.Warningf(ctx, "node %s increase pool is full", node.Name)
return
}
}
func (ipam *IPAM) checkIdleIPPoolPeriodically() error {
return wait.PollImmediateInfinite(30*time.Second, ipam.checkIdleIPPool)
}
func (ipam *IPAM) batchAddPrivateIP(ctx context.Context, privateIPs []string, batchAddNum int, eniID string) ([]string, error) {
ipam.bucket.Wait(1)
return ipam.cloud.BatchAddPrivateIP(ctx, privateIPs, batchAddNum, eniID)
}
// batchAllocateIPWithBackoff allocate ip by eni from cloud with backoff if exists
func (ipam *IPAM) batchAllocateIPWithBackoff(ctx context.Context, batchAddNum int, eni *enisdk.Eni) ([]string, error) {
var backoffWaitPeriod time.Duration
var backoff *wait.Backoff
var ok bool
const waitPeriodNum = 10
ipam.lock.Lock()
backoff, ok = ipam.addIPBackoffCache.Get(eni.EniId)
if backoff != nil && backoff.Steps >= 0 {
backoffWaitPeriod = backoff.Step()
}
ipam.lock.Unlock()
// backoff wait
if backoffWaitPeriod != 0 {
log.Infof(ctx, "backoff: wait %v to allocate private ip on %v", backoffWaitPeriod, eni.EniId)
// instead of sleep a large amount of time, we divide sleep time into small parts to check backoff cache.
for i := 0; i < waitPeriodNum; i++ {
time.Sleep(backoffWaitPeriod / waitPeriodNum)
ipam.lock.RLock()
backoff, ok = ipam.addIPBackoffCache.Get(eni.EniId)
ipam.lock.RUnlock()
if !ok {
log.Warningf(ctx, "found backoff on eni %v removed", eni.EniId)
break
}
}
}
ipResults, batchErr := ipam.batchAddPrivateIP(ctx, []string{}, batchAddNum, eni.EniId)
if batchErr == nil {
ipam.removeAddIPBackoffCache(eni.EniId, false)
}
return ipResults, batchErr
}
func (ipam *IPAM) sortENIByDatastoreStats(node string, enis []*enisdk.Eni, byTotal bool) {
sort.Slice(enis, func(i, j int) bool {
total1, assigned1, _ := ipam.datastore.GetENIStats(node, enis[i].EniId)
total2, assigned2, _ := ipam.datastore.GetENIStats(node, enis[j].EniId)
if !byTotal {
idle1, idle2 := total1-assigned1, total2-assigned2
return idle1 >= idle2
}
return total1 < total2
})
}
func (ipam *IPAM) incPrivateIPNumCache(eniID string, lockless bool) {
if !lockless {
ipam.lock.Lock()
defer ipam.lock.Unlock()
}