-
Notifications
You must be signed in to change notification settings - Fork 746
/
ipamd.go
2183 lines (1916 loc) · 78.8 KB
/
ipamd.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 Amazon.com Inc. or its affiliates. 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. A copy of the
// License is located at
//
// http://aws.amazon.com/apache2.0/
//
// or in the "license" file accompanying this file. This file 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 ipamd
import (
"context"
"fmt"
"math"
"net"
"os"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/util/retry"
"github.com/aws/amazon-vpc-cni-k8s/pkg/awsutils"
"github.com/aws/amazon-vpc-cni-k8s/pkg/eniconfig"
"github.com/aws/amazon-vpc-cni-k8s/pkg/ipamd/datastore"
"github.com/aws/amazon-vpc-cni-k8s/pkg/networkutils"
"github.com/aws/amazon-vpc-cni-k8s/pkg/utils/logger"
)
// The package ipamd is a long running daemon which manages a warm pool of available IP addresses.
// It also monitors the size of the pool, dynamically allocates more ENIs when the pool size goes below
// the minimum threshold and frees them back when the pool size goes above max threshold.
const (
ipPoolMonitorInterval = 5 * time.Second
maxRetryCheckENI = 5
eniAttachTime = 10 * time.Second
nodeIPPoolReconcileInterval = 60 * time.Second
decreaseIPPoolInterval = 30 * time.Second
// ipReconcileCooldown is the amount of time that an IP address must wait until it can be added to the data store
// during reconciliation after being discovered on the EC2 instance metadata.
ipReconcileCooldown = 60 * time.Second
// This environment variable is used to specify the desired number of free IPs always available in the "warm pool".
// When it is not set, ipamd defaults to use all available IPs per ENI for that instance type.
// For example, for a m4.4xlarge node,
// If WARM-IP-TARGET is set to 1, and there are 9 pods running on the node, ipamd will try
// to make the "warm pool" have 10 IP addresses with 9 being assigned to pods and 1 free IP.
//
// If "WARM-IP-TARGET is not set, it will default to 30 (which the maximum number of IPs per ENI).
// If there are 9 pods running on the node, ipamd will try to make the "warm pool" have 39 IPs with 9 being
// assigned to pods and 30 free IPs.
envWarmIPTarget = "WARM_IP_TARGET"
noWarmIPTarget = 0
// This environment variable is used to specify the desired minimum number of total IPs.
// When it is not set, ipamd defaults to 0.
// For example, for a m4.4xlarge node,
// If WARM_IP_TARGET is set to 1 and MINIMUM_IP_TARGET is set to 12, and there are 9 pods running on the node,
// ipamd will make the "warm pool" have 12 IP addresses with 9 being assigned to pods and 3 free IPs.
//
// If "MINIMUM_IP_TARGET is not set, it will default to 0, which causes WARM_IP_TARGET settings to be the
// only settings considered.
envMinimumIPTarget = "MINIMUM_IP_TARGET"
noMinimumIPTarget = 0
// This environment is used to specify the desired number of free ENIs along with all of its IP addresses
// always available in "warm pool".
// When it is not set, it is default to 1.
//
// when "WARM-IP-TARGET" is defined, ipamd will use behavior defined for "WARM-IP-TARGET".
//
// For example, for a m4.4xlarge node
// If WARM_ENI_TARGET is set to 2, and there are 9 pods running on the node, ipamd will try to
// make the "warm pool" to have 2 extra ENIs and its IP addresses, in other words, 90 IP addresses
// with 9 IPs assigned to pods and 81 free IPs.
//
// If "WARM_ENI_TARGET" is not set, it defaults to 1, so if there are 9 pods running on the node,
// ipamd will try to make the "warm pool" have 1 extra ENI, in other words, 60 IPs with 9 already
// being assigned to pods and 51 free IPs.
envWarmENITarget = "WARM_ENI_TARGET"
defaultWarmENITarget = 1
// This environment variable is used to specify the maximum number of ENIs that will be allocated.
// When it is not set or less than 1, the default is to use the maximum available for the instance type.
//
// The maximum number of ENIs is in any case limited to the amount allowed for the instance type.
envMaxENI = "MAX_ENI"
defaultMaxENI = -1
// This environment is used to specify whether Pods need to use a security group and subnet defined in an ENIConfig CRD.
// When it is NOT set or set to false, ipamd will use primary interface security group and subnet for Pod network.
envCustomNetworkCfg = "AWS_VPC_K8S_CNI_CUSTOM_NETWORK_CFG"
// eniNoManageTagKey is the tag that may be set on an ENI to indicate ipamd
// should not manage it in any form.
eniNoManageTagKey = "node.k8s.amazonaws.com/no_manage"
// disableENIProvisioning is used to specify that ENI doesn't need to be synced during initializing a pod.
envDisableENIProvisioning = "DISABLE_NETWORK_RESOURCE_PROVISIONING"
// Specify where ipam should persist its current IP<->container allocations.
envBackingStorePath = "AWS_VPC_K8S_CNI_BACKING_STORE"
defaultBackingStorePath = "/var/run/aws-node/ipam.json"
// envEnablePodENI is used to attach a Trunk ENI to every node. Required in order to give Branch ENIs to pods.
envEnablePodENI = "ENABLE_POD_ENI"
// envNodeName will be used to store Node name
envNodeName = "MY_NODE_NAME"
// vpcENIConfigLabel is used by the VPC resource controller to pick the right ENI config.
vpcENIConfigLabel = "vpc.amazonaws.com/eniConfig"
//envEnableIpv4PrefixDelegation is used to allocate /28 prefix instead of secondary IP for an ENI.
envEnableIpv4PrefixDelegation = "ENABLE_PREFIX_DELEGATION"
//envWarmPrefixTarget is used to keep a /28 prefix in warm pool.
envWarmPrefixTarget = "WARM_PREFIX_TARGET"
defaultWarmPrefixTarget = 0
//envEnableIPv4 - Env variable to enable/disable IPv4 mode
envEnableIPv4 = "ENABLE_IPv4"
//envEnableIPv6 - Env variable to enable/disable IPv6 mode
envEnableIPv6 = "ENABLE_IPv6"
ipV4AddrFamily = "4"
ipV6AddrFamily = "6"
//insufficientCidrErrorCooldown is the amount of time reconciler will wait before trying to fetch
//more IPs/prefixes for an ENI. With InsufficientCidr we know the subnet doesn't have enough IPs so
//instead of retrying every 5s which would lead to increase in EC2 AllocIPAddress calls, we wait for
//120 seconds for a retry.
insufficientCidrErrorCooldown = 120 * time.Second
// envManageUntaggedENI is used to determine if untagged ENIs should be managed or unmanaged
envManageUntaggedENI = "MANAGE_UNTAGGED_ENI"
eniNodeTagKey = "node.k8s.amazonaws.com/instance_id"
// envAnnotatePodIP is used to annotate[vpc.amazonaws.com/pod-ips] pod's with IPs
// Ref : https://github.com/projectcalico/calico/issues/3530
// not present; in which case we fall back to the k8s podIP
// Present and set to an IP; in which case we use it
// Present and set to the empty string, which we use to mean "CNI DEL had occurred; networking has been removed from this pod"
// The empty string one helps close a trace at pod shutdown where it looks like the pod still has its IP when the IP has been released
envAnnotatePodIP = "ANNOTATE_POD_IP"
)
var log = logger.Get()
var (
ipamdErr = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "awscni_ipamd_error_count",
Help: "The number of errors encountered in ipamd",
},
[]string{"fn"},
)
ipamdActionsInprogress = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "awscni_ipamd_action_inprogress",
Help: "The number of ipamd actions in progress",
},
[]string{"fn"},
)
enisMax = prometheus.NewGauge(
prometheus.GaugeOpts{
Name: "awscni_eni_max",
Help: "The maximum number of ENIs that can be attached to the instance, accounting for unmanaged ENIs",
},
)
ipMax = prometheus.NewGauge(
prometheus.GaugeOpts{
Name: "awscni_ip_max",
Help: "The maximum number of IP addresses that can be allocated to the instance",
},
)
reconcileCnt = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "awscni_reconcile_count",
Help: "The number of times ipamd reconciles on ENIs and IP/Prefix addresses",
},
[]string{"fn"},
)
addIPCnt = prometheus.NewCounter(
prometheus.CounterOpts{
Name: "awscni_add_ip_req_count",
Help: "The number of add IP address requests",
},
)
delIPCnt = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "awscni_del_ip_req_count",
Help: "The number of delete IP address requests",
},
[]string{"reason"},
)
podENIErr = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "awscni_pod_eni_error_count",
Help: "The number of errors encountered for pod ENIs",
},
[]string{"fn"},
)
prometheusRegistered = false
)
// IPAMContext contains node level control information
type IPAMContext struct {
awsClient awsutils.APIs
dataStore *datastore.DataStore
rawK8SClient client.Client
cachedK8SClient client.Client
enableIPv4 bool
enableIPv6 bool
useCustomNetworking bool
networkClient networkutils.NetworkAPIs
maxIPsPerENI int
maxENI int
maxPrefixesPerENI int
unmanagedENI int
warmENITarget int
warmIPTarget int
minimumIPTarget int
warmPrefixTarget int
primaryIP map[string]string // primaryIP is a map from ENI ID to primary IP of that ENI
lastNodeIPPoolAction time.Time
lastDecreaseIPPool time.Time
// reconcileCooldownCache keeps timestamps of the last time an IP address was unassigned from an ENI,
// so that we don't reconcile and add it back too quickly if IMDS lags behind reality.
reconcileCooldownCache ReconcileCooldownCache
terminating int32 // Flag to warn that the pod is about to shut down.
disableENIProvisioning bool
enablePodENI bool
myNodeName string
enablePrefixDelegation bool
lastInsufficientCidrError time.Time
enableManageUntaggedMode bool
enablePodIPAnnotation bool
}
// setUnmanagedENIs will rebuild the set of ENI IDs for ENIs tagged as "no_manage"
func (c *IPAMContext) setUnmanagedENIs(tagMap map[string]awsutils.TagMap) {
if len(tagMap) == 0 {
return
}
var unmanagedENIlist []string
// if "no_manage" tag is present and is true - ENI is unmanaged
// if "no_manage" tag is present and is "not true" - ENI is managed
// if "instance_id" tag is present and is set to instanceID - ENI is managed since this was created by IPAMD
// if "no_manage" tag is not present or not IPAMD created ENI, check if we are in Manage Untagged Mode, default is true.
// if enableManageUntaggedMode is false, then consider all untagged ENIs as unmanaged.
for eniID, tags := range tagMap {
if _, found := tags[eniNoManageTagKey]; found {
if tags[eniNoManageTagKey] != "true" {
continue
}
} else if _, found := tags[eniNodeTagKey]; found && tags[eniNodeTagKey] == c.awsClient.GetInstanceID() {
continue
} else if c.enableManageUntaggedMode {
continue
}
if eniID == c.awsClient.GetPrimaryENI() {
log.Debugf("Ignoring primary ENI %s since it is always managed", eniID)
} else {
log.Debugf("Marking ENI %s as being unmanaged", eniID)
unmanagedENIlist = append(unmanagedENIlist, eniID)
}
}
c.awsClient.SetUnmanagedENIs(unmanagedENIlist)
}
// ReconcileCooldownCache keep track of recently freed CIDRs to avoid reading stale EC2 metadata
type ReconcileCooldownCache struct {
sync.RWMutex
cache map[string]time.Time
}
// Add sets a timestamp for the CIDR added that says how long they are not to be put back in the data store.
func (r *ReconcileCooldownCache) Add(cidr string) {
r.Lock()
defer r.Unlock()
expiry := time.Now().Add(ipReconcileCooldown)
r.cache[cidr] = expiry
}
// Remove removes a CIDR from the cooldown cache.
func (r *ReconcileCooldownCache) Remove(cidr string) {
r.Lock()
defer r.Unlock()
log.Debugf("Removing %s from cooldown cache.", cidr)
delete(r.cache, cidr)
}
// RecentlyFreed checks if this CIDR was recently freed.
func (r *ReconcileCooldownCache) RecentlyFreed(cidr string) (found, recentlyFreed bool) {
r.Lock()
defer r.Unlock()
now := time.Now()
if expiry, ok := r.cache[cidr]; ok {
log.Debugf("Checking if CIDR %s has been recently freed. Cooldown expires at: %s. (Cooldown: %v)", cidr, expiry, now.Sub(expiry) < 0)
return true, now.Sub(expiry) < 0
}
return false, false
}
func prometheusRegister() {
if !prometheusRegistered {
prometheus.MustRegister(ipamdErr)
prometheus.MustRegister(ipamdActionsInprogress)
prometheus.MustRegister(enisMax)
prometheus.MustRegister(ipMax)
prometheus.MustRegister(reconcileCnt)
prometheus.MustRegister(addIPCnt)
prometheus.MustRegister(delIPCnt)
prometheus.MustRegister(podENIErr)
prometheusRegistered = true
}
}
// containsInsufficientCidrBlocksError returns whether exceeds ENI's IP address limit
func containsInsufficientCidrBlocksError(err error) bool {
var awsErr awserr.Error
if errors.As(err, &awsErr) {
return awsErr.Code() == "InsufficientCidrBlocks"
}
return false
}
// inInsufficientCidrCoolingPeriod checks whether IPAMD is in insufficientCidrErrorCooldown
func (c *IPAMContext) inInsufficientCidrCoolingPeriod() bool {
return time.Since(c.lastInsufficientCidrError) <= insufficientCidrErrorCooldown
}
// New retrieves IP address usage information from Instance MetaData service and Kubelet
// then initializes IP address pool data store
func New(rawK8SClient client.Client, cachedK8SClient client.Client) (*IPAMContext, error) {
prometheusRegister()
c := &IPAMContext{}
c.rawK8SClient = rawK8SClient
c.cachedK8SClient = cachedK8SClient
c.networkClient = networkutils.New()
c.useCustomNetworking = UseCustomNetworkCfg()
c.enablePrefixDelegation = usePrefixDelegation()
c.enableIPv4 = isIPv4Enabled()
c.enableIPv6 = isIPv6Enabled()
c.disableENIProvisioning = disablingENIProvisioning()
client, err := awsutils.New(c.useCustomNetworking, c.disableENIProvisioning, c.enableIPv4, c.enableIPv6)
if err != nil {
return nil, errors.Wrap(err, "ipamd: can not initialize with AWS SDK interface")
}
c.awsClient = client
c.primaryIP = make(map[string]string)
c.reconcileCooldownCache.cache = make(map[string]time.Time)
//WARM and Min IP/Prefix targets are ignored in IPv6 mode
c.warmENITarget = getWarmENITarget()
c.warmIPTarget = getWarmIPTarget()
c.minimumIPTarget = getMinimumIPTarget()
c.warmPrefixTarget = getWarmPrefixTarget()
c.enablePodENI = enablePodENI()
c.enableManageUntaggedMode = enableManageUntaggedMode()
c.enablePodIPAnnotation = enablePodIPAnnotation()
err = c.awsClient.FetchInstanceTypeLimits()
if err != nil {
log.Errorf("Failed to get ENI limits from file:vpc_ip_limits or EC2 for %s", c.awsClient.GetInstanceType())
return nil, err
}
//Let's validate if the configured combination of env variables is supported before we
//proceed any further
if !c.isConfigValid() {
return nil, fmt.Errorf("ipamd: failed to validate configuration")
}
c.awsClient.InitCachedPrefixDelegation(c.enablePrefixDelegation)
c.myNodeName = os.Getenv("MY_NODE_NAME")
checkpointer := datastore.NewJSONFile(dsBackingStorePath())
c.dataStore = datastore.NewDataStore(log, checkpointer, c.enablePrefixDelegation)
err = c.nodeInit()
if err != nil {
return nil, err
}
mac := c.awsClient.GetPrimaryENImac()
// retrieve security groups
if c.enableIPv4 || !c.disableENIProvisioning {
err = c.awsClient.RefreshSGIDs(mac)
if err != nil {
return nil, err
}
// Refresh security groups and VPC CIDR blocks in the background
// Ignoring errors since we will retry in 30s
go wait.Forever(func() { _ = c.awsClient.RefreshSGIDs(mac) }, 30*time.Second)
}
return c, nil
}
func (c *IPAMContext) nodeInit() error {
ipamdActionsInprogress.WithLabelValues("nodeInit").Add(float64(1))
defer ipamdActionsInprogress.WithLabelValues("nodeInit").Sub(float64(1))
var err error
var vpcV4CIDRs []string
ctx := context.TODO()
log.Debugf("Start node init")
primaryV4IP := c.awsClient.GetLocalIPv4()
err = c.initENIAndIPLimits()
if c.enableIPv4 {
//Subnets currently will have both v4 and v6 CIDRs. Once EC2 launches v6 only Subnets, that will no longer
//be true and so it is safe (and only required) to get the v4 CIDR info only when IPv4 mode is enabled.
vpcV4CIDRs, err = c.awsClient.GetVPCIPv4CIDRs()
if err != nil {
return err
}
}
err = c.networkClient.SetupHostNetwork(vpcV4CIDRs, c.awsClient.GetPrimaryENImac(), &primaryV4IP, c.enablePodENI, c.enableIPv4,
c.enableIPv6)
if err != nil {
return errors.Wrap(err, "ipamd init: failed to set up host network")
}
metadataResult, err := c.awsClient.DescribeAllENIs()
if err != nil {
return errors.New("ipamd init: failed to retrieve attached ENIs info")
}
log.Debugf("DescribeAllENIs success: ENIs: %d, tagged: %d", len(metadataResult.ENIMetadata), len(metadataResult.TagMap))
c.awsClient.SetCNIUnmanagedENIs(metadataResult.MultiCardENIIDs)
c.setUnmanagedENIs(metadataResult.TagMap)
enis := c.filterUnmanagedENIs(metadataResult.ENIMetadata)
for _, eni := range enis {
log.Debugf("Discovered ENI %s, trying to set it up", eni.ENIID)
isTrunkENI := eni.ENIID == metadataResult.TrunkENI
isEFAENI := metadataResult.EFAENIs[eni.ENIID]
if !isTrunkENI && !c.disableENIProvisioning {
if err := c.awsClient.TagENI(eni.ENIID, metadataResult.TagMap[eni.ENIID]); err != nil {
return errors.Wrapf(err, "ipamd init: failed to tag managed ENI %v", eni.ENIID)
}
}
// Retry ENI sync
retry := 0
for {
retry++
if err = c.setupENI(eni.ENIID, eni, isTrunkENI, isEFAENI); err == nil {
log.Infof("ENI %s set up.", eni.ENIID)
break
}
if retry > maxRetryCheckENI {
log.Warnf("Reached max retry: Unable to discover attached IPs for ENI from metadata service (attempted %d/%d): %v", retry, maxRetryCheckENI, err)
ipamdErrInc("waitENIAttachedMaxRetryExceeded")
break
}
log.Warnf("Error trying to set up ENI %s: %v", eni.ENIID, err)
if strings.Contains(err.Error(), "setupENINetwork: failed to find the link which uses MAC address") {
// If we can't find the matching link for this MAC address, there is no point in retrying for this ENI.
log.Debug("Unable to match link for this ENI, going to the next one.")
break
}
log.Debugf("Unable to discover IPs for this ENI yet (attempt %d/%d)", retry, maxRetryCheckENI)
time.Sleep(eniAttachTime)
}
}
if err := c.dataStore.ReadBackingStore(c.enableIPv6); err != nil {
return err
}
if c.enableIPv6 {
//We will not support upgrading/converting an existing IPv4 cluster to operate in IPv6 mode. So, we will always
//start with a clean slate in IPv6 mode. We also don't have to deal with dynamic update of Prefix Delegation
//feature in IPv6 mode as we don't support (yet) a non-PD v6 option. In addition, we don't support custom
//networking & SGPP in IPv6 mode yet. So, we will skip the corresponding setup. Will save us from checking
//if IPv6 is enabled at multiple places. Once we start supporting these features in IPv6 mode, we can do away
//with this check and not change anything else in the below setup.
return nil
}
if c.enablePrefixDelegation {
//During upgrade or if prefix delgation knob is disabled to enabled then we
//might have secondary IPs attached to ENIs so doing a cleanup if not used before moving on
c.tryUnassignIPsFromENIs()
} else {
//When prefix delegation knob is enabled to disabled then we might
//have unused prefixes attached to the ENIs so need to cleanup
c.tryUnassignPrefixesFromENIs()
}
if err = c.configureIPRulesForPods(); err != nil {
return err
}
// Spawning updateCIDRsRulesOnChange go-routine
go wait.Forever(func() {
vpcV4CIDRs = c.updateCIDRsRulesOnChange(vpcV4CIDRs)
}, 30*time.Second)
eniConfigName, err := eniconfig.GetNodeSpecificENIConfigName(ctx, c.cachedK8SClient)
if err == nil && c.useCustomNetworking && eniConfigName != "default" {
// Signal to VPC Resource Controller that the node is using custom networking
err := c.SetNodeLabel(ctx, vpcENIConfigLabel, eniConfigName)
if err != nil {
log.Errorf("Failed to set eniConfig node label", err)
podENIErrInc("nodeInit")
return err
}
} else {
// Remove the custom networking label
err := c.SetNodeLabel(ctx, vpcENIConfigLabel, "")
if err != nil {
log.Errorf("Failed to delete eniConfig node label", err)
podENIErrInc("nodeInit")
return err
}
}
if metadataResult.TrunkENI != "" {
// Signal to VPC Resource Controller that the node has a trunk already
err := c.SetNodeLabel(ctx, "vpc.amazonaws.com/has-trunk-attached", "true")
if err != nil {
log.Errorf("Failed to set node label", err)
podENIErrInc("nodeInit")
// If this fails, we probably can't talk to the API server. Let the pod restart
return err
}
} else {
// Check if we want to ask for one
c.askForTrunkENIIfNeeded(ctx)
}
if !c.disableENIProvisioning {
// For a new node, attach Cidrs (secondary ips/prefixes)
increasedPool, err := c.tryAssignCidrs()
if err == nil && increasedPool {
c.updateLastNodeIPPoolAction()
} else if err != nil {
if containsInsufficientCidrBlocksError(err) {
log.Errorf("Unable to attach IPs/Prefixes for the ENI, subnet doesn't seem to have enough IPs/Prefixes. Consider using new subnet or carve a reserved range using create-subnet-cidr-reservation")
c.lastInsufficientCidrError = time.Now()
return nil
}
return err
}
}
return nil
}
func (c *IPAMContext) configureIPRulesForPods() error {
rules, err := c.networkClient.GetRuleList()
if err != nil {
log.Errorf("During ipamd init: failed to retrieve IP rule list %v", err)
return nil
}
for _, info := range c.dataStore.AllocatedIPs() {
// TODO(gus): This should really be done via CNI CHECK calls, rather than in ipam (requires upstream k8s changes).
// Update ip rules in case there is a change in VPC CIDRs, AWS_VPC_K8S_CNI_EXTERNALSNAT setting
srcIPNet := net.IPNet{IP: net.ParseIP(info.IP), Mask: net.IPv4Mask(255, 255, 255, 255)}
err = c.networkClient.UpdateRuleListBySrc(rules, srcIPNet)
if err != nil {
log.Warnf("UpdateRuleListBySrc in nodeInit() failed for IP %s: %v", info.IP, err)
}
}
return nil
}
func (c *IPAMContext) updateCIDRsRulesOnChange(oldVPCCIDRs []string) []string {
newVPCCIDRs, err := c.awsClient.GetVPCIPv4CIDRs()
if err != nil {
log.Warnf("skipping periodic update to VPC CIDRs due to error: %v", err)
return oldVPCCIDRs
}
old := sets.NewString(oldVPCCIDRs...)
new := sets.NewString(newVPCCIDRs...)
if !old.Equal(new) {
primaryIP := c.awsClient.GetLocalIPv4()
err = c.networkClient.UpdateHostIptablesRules(newVPCCIDRs, c.awsClient.GetPrimaryENImac(), &primaryIP, c.enableIPv4,
c.enableIPv6)
if err != nil {
log.Warnf("unable to update host iptables rules for VPC CIDRs due to error: %v", err)
}
}
return newVPCCIDRs
}
func (c *IPAMContext) updateIPStats(unmanaged int) {
ipMax.Set(float64(c.maxIPsPerENI * (c.maxENI - unmanaged)))
enisMax.Set(float64(c.maxENI - unmanaged))
}
// StartNodeIPPoolManager monitors the IP pool, add or del them when it is required.
func (c *IPAMContext) StartNodeIPPoolManager() {
if c.enableIPv6 {
//Nothing to do in IPv6 Mode. IPv6 is only supported in Prefix delegation mode
//and VPC CNI will only attach one V6 Prefix.
return
}
sleepDuration := ipPoolMonitorInterval / 2
ctx := context.Background()
for {
if !c.disableENIProvisioning {
time.Sleep(sleepDuration)
c.updateIPPoolIfRequired(ctx)
}
time.Sleep(sleepDuration)
c.nodeIPPoolReconcile(ctx, nodeIPPoolReconcileInterval)
}
}
func (c *IPAMContext) updateIPPoolIfRequired(ctx context.Context) {
c.askForTrunkENIIfNeeded(ctx)
if c.isDatastorePoolTooLow() {
c.increaseDatastorePool(ctx)
} else if c.isDatastorePoolTooHigh() {
c.decreaseDatastorePool(decreaseIPPoolInterval)
}
if c.shouldRemoveExtraENIs() {
c.tryFreeENI()
}
}
// decreaseDatastorePool runs every `interval` and attempts to return unused ENIs and IPs
func (c *IPAMContext) decreaseDatastorePool(interval time.Duration) {
ipamdActionsInprogress.WithLabelValues("decreaseDatastorePool").Add(float64(1))
defer ipamdActionsInprogress.WithLabelValues("decreaseDatastorePool").Sub(float64(1))
now := time.Now()
timeSinceLast := now.Sub(c.lastDecreaseIPPool)
if timeSinceLast <= interval {
log.Debugf("Skipping decrease Datastore pool because time since last %v <= %v", timeSinceLast, interval)
return
}
log.Debugf("Starting to decrease Datastore pool")
c.tryUnassignCidrsFromAll()
c.lastDecreaseIPPool = now
c.lastNodeIPPoolAction = now
log.Debugf("Successfully decreased IP pool")
c.logPoolStats(c.dataStore.GetIPStats(ipV4AddrFamily))
}
// tryFreeENI always tries to free one ENI
func (c *IPAMContext) tryFreeENI() {
if c.isTerminating() {
log.Debug("AWS CNI is terminating, not detaching any ENIs")
return
}
eni := c.dataStore.RemoveUnusedENIFromStore(c.warmIPTarget, c.minimumIPTarget, c.warmPrefixTarget)
if eni == "" {
return
}
log.Debugf("Start freeing ENI %s", eni)
err := c.awsClient.FreeENI(eni)
if err != nil {
ipamdErrInc("decreaseIPPoolFreeENIFailed")
log.Errorf("Failed to free ENI %s, err: %v", eni, err)
return
}
}
// tryUnassignIPsorPrefixesFromAll determines if there are IPs to free when we have extra IPs beyond the target and warmIPTargetDefined
// is enabled, deallocate extra IP addresses
func (c *IPAMContext) tryUnassignCidrsFromAll() {
_, over, warmTargetDefined := c.datastoreTargetState()
//WARM IP targets not defined then check if WARM_PREFIX_TARGET is defined.
if !warmTargetDefined {
over = c.computeExtraPrefixesOverWarmTarget()
}
if over > 0 {
eniInfos := c.dataStore.GetENIInfos()
for eniID := range eniInfos.ENIs {
//Either returns prefixes or IPs [Cidrs]
cidrs := c.dataStore.FindFreeableCidrs(eniID)
if cidrs == nil {
log.Errorf("Error finding unassigned IPs for ENI %s", eniID)
return
}
// Free the number of Cidrs `over` the warm IP target, unless `over` is greater than the number of available Cidrs on
// this ENI. In that case we should only free the number of available Cidrs.
numFreeable := min(over, len(cidrs))
cidrs = cidrs[:numFreeable]
if len(cidrs) == 0 {
continue
}
// Delete IPs from datastore
var deletedCidrs []datastore.CidrInfo
for _, toDelete := range cidrs {
// Don't force the delete, since a freeable Cidrs might have been assigned to a pod
// before we get around to deleting it.
err := c.dataStore.DelIPv4CidrFromStore(eniID, toDelete.Cidr, false /* force */)
if err != nil {
log.Warnf("Failed to delete Cidr %s on ENI %s from datastore: %s", toDelete, eniID, err)
ipamdErrInc("decreaseIPPool")
continue
} else {
deletedCidrs = append(deletedCidrs, toDelete)
}
}
// Deallocate Cidrs from the instance if they aren't used by pods.
c.DeallocCidrs(eniID, deletedCidrs)
}
}
}
func (c *IPAMContext) increaseDatastorePool(ctx context.Context) {
log.Debug("Starting to increase pool size")
ipamdActionsInprogress.WithLabelValues("increaseDatastorePool").Add(float64(1))
defer ipamdActionsInprogress.WithLabelValues("increaseDatastorePool").Sub(float64(1))
short, _, warmIPTargetDefined := c.datastoreTargetState()
if warmIPTargetDefined && short == 0 {
log.Debugf("Skipping increase Datastore pool, warm target reached")
return
}
if !warmIPTargetDefined {
shortPrefix, warmTargetDefined := c.datastorePrefixTargetState()
if warmTargetDefined && shortPrefix == 0 {
log.Debugf("Skipping increase Datastore pool, warm prefix target reached")
return
}
}
if c.isTerminating() {
log.Debug("AWS CNI is terminating, will not try to attach any new IPs or ENIs right now")
return
}
// Try to add more Cidrs to existing ENIs first.
if c.inInsufficientCidrCoolingPeriod() {
log.Debugf("Recently we had InsufficientCidr error hence will wait for %v before retrying", insufficientCidrErrorCooldown)
return
}
increasedPool, err := c.tryAssignCidrs()
if err != nil {
log.Errorf(err.Error())
if containsInsufficientCidrBlocksError(err) {
log.Errorf("Unable to attach IPs/Prefixes for the ENI, subnet doesn't seem to have enough IPs/Prefixes. Consider using new subnet or carve a reserved range using create-subnet-cidr-reservation")
c.lastInsufficientCidrError = time.Now()
return
}
}
if increasedPool {
c.updateLastNodeIPPoolAction()
} else {
// Check if we need to make room for the VPC Resource Controller to attach a trunk ENI
reserveSlotForTrunkENI := 0
if c.enablePodENI && c.dataStore.GetTrunkENI() == "" {
reserveSlotForTrunkENI = 1
}
// If we did not add an IP, try to add an ENI instead.
if c.dataStore.GetENIs() < (c.maxENI - c.unmanagedENI - reserveSlotForTrunkENI) {
if err = c.tryAllocateENI(ctx); err == nil {
c.updateLastNodeIPPoolAction()
}
} else {
log.Debugf("Skipping ENI allocation as the max ENI limit of %d is already reached (accounting for %d unmanaged ENIs and %d trunk ENIs)",
c.maxENI, c.unmanagedENI, reserveSlotForTrunkENI)
}
}
}
func (c *IPAMContext) updateLastNodeIPPoolAction() {
c.lastNodeIPPoolAction = time.Now()
stats := c.dataStore.GetIPStats(ipV4AddrFamily)
if !c.enablePrefixDelegation {
log.Debugf("Successfully increased IP pool: %s", stats)
} else {
log.Debugf("Successfully increased Prefix pool: %s", stats)
}
c.logPoolStats(stats)
}
func (c *IPAMContext) tryAllocateENI(ctx context.Context) error {
var securityGroups []*string
var subnet string
if c.useCustomNetworking {
eniCfg, err := eniconfig.MyENIConfig(ctx, c.cachedK8SClient)
if err != nil {
log.Errorf("Failed to get pod ENI config")
return err
}
log.Infof("ipamd: using custom network config: %v, %s", eniCfg.SecurityGroups, eniCfg.Subnet)
for _, sgID := range eniCfg.SecurityGroups {
log.Debugf("Found security-group id: %s", sgID)
securityGroups = append(securityGroups, aws.String(sgID))
}
subnet = eniCfg.Subnet
}
eni, err := c.awsClient.AllocENI(c.useCustomNetworking, securityGroups, subnet)
if err != nil {
log.Errorf("Failed to increase pool size due to not able to allocate ENI %v", err)
ipamdErrInc("increaseIPPoolAllocENI")
return err
}
resourcesToAllocate := c.GetENIResourcesToAllocate()
err = c.awsClient.AllocIPAddresses(eni, resourcesToAllocate)
if err != nil {
log.Warnf("Failed to allocate %d IP addresses on an ENI: %v", resourcesToAllocate, err)
// Continue to process the allocated IP addresses
ipamdErrInc("increaseIPPoolAllocIPAddressesFailed")
if containsInsufficientCidrBlocksError(err) {
log.Errorf("Unable to attach IPs/Prefixes for the ENI, subnet doesn't seem to have enough IPs/Prefixes. Consider using new subnet or carve a reserved range using create-subnet-cidr-reservation")
c.lastInsufficientCidrError = time.Now()
return err
}
}
eniMetadata, err := c.awsClient.WaitForENIAndIPsAttached(eni, resourcesToAllocate)
if err != nil {
ipamdErrInc("increaseIPPoolwaitENIAttachedFailed")
log.Errorf("Failed to increase pool size: Unable to discover attached ENI from metadata service %v", err)
return err
}
// The CNI does not create trunk or EFA ENIs, so they will always be false here
err = c.setupENI(eni, eniMetadata, false, false)
if err != nil {
ipamdErrInc("increaseIPPoolsetupENIFailed")
log.Errorf("Failed to increase pool size: %v", err)
return err
}
return err
}
// For an ENI, try to fill in missing IPs on an existing ENI with PD disabled
// try to fill in missing Prefixes on an existing ENI with PD enabled
func (c *IPAMContext) tryAssignCidrs() (increasedPool bool, err error) {
short, _, warmIPTargetDefined := c.datastoreTargetState()
if warmIPTargetDefined && short == 0 {
log.Infof("Warm IP target set and short is 0 so not assigning Cidrs (IPs or Prefixes)")
return false, nil
}
if !warmIPTargetDefined {
shortPrefix, warmTargetDefined := c.datastorePrefixTargetState()
if warmTargetDefined && shortPrefix == 0 {
log.Infof("Warm prefix target set and short is 0 so not assigning Cidrs (Prefixes)")
return false, nil
}
}
if !c.enablePrefixDelegation {
return c.tryAssignIPs()
} else {
return c.tryAssignPrefixes()
}
}
// For an ENI, try to fill in missing IPs on an existing ENI
func (c *IPAMContext) tryAssignIPs() (increasedPool bool, err error) {
// If WARM_IP_TARGET is set, only proceed if we are short of target
short, _, warmIPTargetDefined := c.datastoreTargetState()
if warmIPTargetDefined && short == 0 {
return false, nil
}
// If WARM_IP_TARGET is set we only want to allocate up to that target
// to avoid overallocating and releasing
toAllocate := c.maxIPsPerENI
if warmIPTargetDefined {
toAllocate = short
}
// Find an ENI where we can add more IPs
eni := c.dataStore.GetENINeedsIP(c.maxIPsPerENI, c.useCustomNetworking)
if eni != nil && len(eni.AvailableIPv4Cidrs) < c.maxIPsPerENI {
currentNumberOfAllocatedIPs := len(eni.AvailableIPv4Cidrs)
// Try to allocate all available IPs for this ENI
err = c.awsClient.AllocIPAddresses(eni.ID, int(math.Min(float64(c.maxIPsPerENI-currentNumberOfAllocatedIPs), float64(toAllocate))))
if err != nil {
log.Warnf("failed to allocate all available IP addresses on ENI %s, err: %v", eni.ID, err)
// Try to just get one more IP
err = c.awsClient.AllocIPAddresses(eni.ID, 1)
if err != nil {
ipamdErrInc("increaseIPPoolAllocIPAddressesFailed")
return false, errors.Wrap(err, fmt.Sprintf("failed to allocate one IP addresses on ENI %s, err: %v", eni.ID, err))
}
}
// This call to EC2 is needed to verify which IPs got attached to this ENI.
ec2Addrs, err := c.awsClient.GetIPv4sFromEC2(eni.ID)
if err != nil {
ipamdErrInc("increaseIPPoolGetENIaddressesFailed")
return true, errors.Wrap(err, "failed to get ENI IP addresses during IP allocation")
}
c.addENIsecondaryIPsToDataStore(ec2Addrs, eni.ID)
return true, nil
}
return false, nil
}
func (c *IPAMContext) assignIPv6Prefix(eniID string) (err error) {
log.Debugf("Assigning an IPv6Prefix for ENI: %s", eniID)
//Let's make an EC2 API call to get a list of IPv6 prefixes (if any) that are already attached to the
//current ENI. We will make this call only once during boot up/init and doing so will shield us from any
//IMDS out of sync issues. We only need one v6 prefix per ENI/Node.
ec2v6Prefixes, err := c.awsClient.GetIPv6PrefixesFromEC2(eniID)
if err != nil {
log.Errorf("assignIPv6Prefix; err: %s", err)
return err
}
log.Debugf("ENI %s has %v prefixe(s) attached", eniID, len(ec2v6Prefixes))
//Note: If we find more than one v6 prefix attached to the ENI, VPC CNI will not attempt to free it. VPC CNI
//will only attach a single v6 prefix and it will not attempt to free the additional Prefixes.
//We will add all the prefixes to our datastore. TODO - Should we instead pick one of them. If we do, how to track
//that across restarts?
//Check if we already have v6 Prefix(es) attached
if len(ec2v6Prefixes) == 0 {
//Allocate and attach a v6 Prefix to Primary ENI
log.Debugf("No IPv6 Prefix(es) found for ENI: %s", eniID)
strPrefixes, err := c.awsClient.AllocIPv6Prefixes(eniID)
if err != nil {
return err
}
for _, v6Prefix := range strPrefixes {
ec2v6Prefixes = append(ec2v6Prefixes, &ec2.Ipv6PrefixSpecification{Ipv6Prefix: v6Prefix})
}
log.Debugf("Successfully allocated an IPv6Prefix for ENI: %s", eniID)
} else if len(ec2v6Prefixes) > 1 {
//Found more than one v6 prefix attached to the ENI. VPC CNI will only attach a single v6 prefix
//and it will not attempt to free any additional Prefixes that are already attached.
//Will use the first IPv6 Prefix attached for IP address allocation.
ec2v6Prefixes = []*ec2.Ipv6PrefixSpecification{ec2v6Prefixes[0]}
}
c.addENIv6prefixesToDataStore(ec2v6Prefixes, eniID)
return nil
}
func (c *IPAMContext) tryAssignPrefixes() (increasedPool bool, err error) {
toAllocate := c.getPrefixesNeeded()
// Returns an ENI which has space for more prefixes to be attached, but this
// ENI might not suffice the WARM_IP_TARGET/WARM_PREFIX_TARGET
eni := c.dataStore.GetENINeedsIP(c.maxPrefixesPerENI, c.useCustomNetworking)
if eni != nil {
currentNumberOfAllocatedPrefixes := len(eni.AvailableIPv4Cidrs)
err = c.awsClient.AllocIPAddresses(eni.ID, min((c.maxPrefixesPerENI-currentNumberOfAllocatedPrefixes), toAllocate))
if err != nil {
log.Warnf("failed to allocate all available IPv4 Prefixes on ENI %s, err: %v", eni.ID, err)
// Try to just get one more prefix
err = c.awsClient.AllocIPAddresses(eni.ID, 1)