-
Notifications
You must be signed in to change notification settings - Fork 746
/
awsutils.go
2085 lines (1825 loc) · 74.8 KB
/
awsutils.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 awsutils is a utility package for calling EC2 or IMDS
package awsutils
import (
"context"
"encoding/json"
"fmt"
"math/rand"
"net"
"os"
"regexp"
"sort"
"strings"
"sync"
"time"
"github.com/aws/amazon-vpc-cni-k8s/pkg/awsutils/awssession"
"github.com/aws/amazon-vpc-cni-k8s/pkg/ec2wrapper"
"github.com/aws/amazon-vpc-cni-k8s/pkg/utils/eventrecorder"
"github.com/aws/amazon-vpc-cni-k8s/pkg/utils/logger"
"github.com/aws/amazon-vpc-cni-k8s/pkg/utils/retry"
"github.com/aws/amazon-vpc-cni-k8s/pkg/vpc"
"github.com/aws/amazon-vpc-cni-k8s/utils/prometheusmetrics"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/ec2metadata"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/util/wait"
)
const (
maxENIEC2APIRetries = 12
maxENIBackoffDelay = time.Minute
eniDescriptionPrefix = "aws-K8S-"
// AllocENI need to choose a first free device number between 0 and maxENI
// 100 is a hard limit because we use vlanID + 100 for pod networking table names
maxENIs = 100
clusterNameEnvVar = "CLUSTER_NAME"
eniNodeTagKey = "node.k8s.amazonaws.com/instance_id"
eniCreatedAtTagKey = "node.k8s.amazonaws.com/createdAt"
eniClusterTagKey = "cluster.k8s.amazonaws.com/name"
additionalEniTagsEnvVar = "ADDITIONAL_ENI_TAGS"
reservedTagKeyPrefix = "k8s.amazonaws.com"
subnetDiscoveryTagKey = "kubernetes.io/role/cni"
// UnknownInstanceType indicates that the instance type is not yet supported
UnknownInstanceType = "vpc ip resource(eni ip limit): unknown instance type"
// Stagger cleanup start time to avoid calling EC2 too much. Time in seconds.
eniCleanupStartupDelayMax = 300
eniDeleteCooldownTime = 5 * time.Minute
// the default page size when paginating the DescribeNetworkInterfaces call
describeENIPageSize = 1000
)
var (
// ErrENINotFound is an error when ENI is not found.
ErrENINotFound = errors.New("ENI is not found")
// ErrAllSecondaryIPsNotFound is returned when not all secondary IPs on an ENI have been assigned
ErrAllSecondaryIPsNotFound = errors.New("All secondary IPs not found")
// ErrNoSecondaryIPsFound is returned when not all secondary IPs on an ENI have been assigned
ErrNoSecondaryIPsFound = errors.New("No secondary IPs have been assigned to this ENI")
// ErrNoNetworkInterfaces occurs when DescribeNetworkInterfaces(eniID) returns no network interfaces
ErrNoNetworkInterfaces = errors.New("No network interfaces found for ENI")
)
var log = logger.Get()
// APIs defines interfaces calls for adding/getting/deleting ENIs/secondary IPs. The APIs are not thread-safe.
type APIs interface {
// AllocENI creates an ENI and attaches it to the instance
AllocENI(useCustomCfg bool, sg []*string, eniCfgSubnet string, numIPs int) (eni string, err error)
// FreeENI detaches ENI interface and deletes it
FreeENI(eniName string) error
// TagENI Tags ENI with current tags to contain expected tags.
TagENI(eniID string, currentTags map[string]string) error
// GetAttachedENIs retrieves eni information from instance metadata service
GetAttachedENIs() (eniList []ENIMetadata, err error)
// GetIPv4sFromEC2 returns the IPv4 addresses for a given ENI
GetIPv4sFromEC2(eniID string) (addrList []*ec2.NetworkInterfacePrivateIpAddress, err error)
// GetIPv4PrefixesFromEC2 returns the IPv4 prefixes for a given ENI
GetIPv4PrefixesFromEC2(eniID string) (addrList []*ec2.Ipv4PrefixSpecification, err error)
// GetIPv6PrefixesFromEC2 returns the IPv6 prefixes for a given ENI
GetIPv6PrefixesFromEC2(eniID string) (addrList []*ec2.Ipv6PrefixSpecification, err error)
// DescribeAllENIs calls EC2 and returns a fully populated DescribeAllENIsResult struct and an error
DescribeAllENIs() (DescribeAllENIsResult, error)
// AllocIPAddress allocates an IP address for an ENI
AllocIPAddress(eniID string) error
// AllocIPAddresses allocates numIPs IP addresses on a ENI
AllocIPAddresses(eniID string, numIPs int) (*ec2.AssignPrivateIpAddressesOutput, error)
// DeallocIPAddresses deallocates the list of IP addresses from a ENI
DeallocIPAddresses(eniID string, ips []string) error
// DeallocPrefixAddresses deallocates the list of IP addresses from a ENI
DeallocPrefixAddresses(eniID string, ips []string) error
//AllocIPv6Prefixes allocates IPv6 prefixes to the ENI passed in
AllocIPv6Prefixes(eniID string) ([]*string, error)
// GetVPCIPv4CIDRs returns VPC's IPv4 CIDRs from instance metadata
GetVPCIPv4CIDRs() ([]string, error)
// GetLocalIPv4 returns the primary IPv4 address on the primary ENI interface
GetLocalIPv4() net.IP
// GetVPCIPv6CIDRs returns VPC's IPv6 CIDRs from instance metadata
GetVPCIPv6CIDRs() ([]string, error)
// GetPrimaryENI returns the primary ENI
GetPrimaryENI() string
// GetENIIPv4Limit return IP address limit per ENI based on EC2 instance type
GetENIIPv4Limit() int
// GetENILimit returns the number of ENIs that can be attached to an instance
GetENILimit() int
// GetNetworkCards returns the network cards the instance has
GetNetworkCards() []vpc.NetworkCard
// GetPrimaryENImac returns the mac address of the primary ENI
GetPrimaryENImac() string
// SetUnmanagedENIs sets the list of unmanaged ENI IDs
SetUnmanagedENIs(eniIDs []string)
// IsUnmanagedENI checks if an ENI is unmanaged
IsUnmanagedENI(eniID string) bool
// WaitForENIAndIPsAttached waits until the ENI has been attached and the secondary IPs have been added
WaitForENIAndIPsAttached(eni string, wantedSecondaryIPs int) (ENIMetadata, error)
//SetMultiCardENIs ENI
SetMultiCardENIs(eniID []string) error
//IsMultiCardENI
IsMultiCardENI(eniID string) bool
//IsPrimaryENI
IsPrimaryENI(eniID string) bool
//RefreshSGIDs
RefreshSGIDs(mac string) error
//GetInstanceHypervisorFamily returns the hypervisor family for the instance
GetInstanceHypervisorFamily() string
//GetInstanceType returns the EC2 instance type
GetInstanceType() string
//Update cached prefix delegation flag
InitCachedPrefixDelegation(bool)
// GetInstanceID returns the instance ID
GetInstanceID() string
// FetchInstanceTypeLimits Verify if the InstanceNetworkingLimits has the ENI limits else make EC2 call to fill cache.
FetchInstanceTypeLimits() error
IsPrefixDelegationSupported() bool
}
// EC2InstanceMetadataCache caches instance metadata
type EC2InstanceMetadataCache struct {
// metadata info
securityGroups StringSet
subnetID string
localIPv4 net.IP
v4Enabled bool
v6Enabled bool
instanceID string
instanceType string
primaryENI string
primaryENImac string
availabilityZone string
region string
vpcID string
unmanagedENIs StringSet
useCustomNetworking bool
multiCardENIs StringSet
useSubnetDiscovery bool
enablePrefixDelegation bool
clusterName string
additionalENITags map[string]string
imds TypedIMDS
ec2SVC ec2wrapper.EC2
}
// ENIMetadata contains information about an ENI
type ENIMetadata struct {
// ENIID is the id of network interface
ENIID string
// MAC is the mac address of network interface
MAC string
// DeviceNumber is the device number of network interface
DeviceNumber int // 0 means it is primary interface
// SubnetIPv4CIDR is the IPv4 CIDR of network interface
SubnetIPv4CIDR string
// SubnetIPv6CIDR is the IPv6 CIDR of network interface
SubnetIPv6CIDR string
// The ip addresses allocated for the network interface
IPv4Addresses []*ec2.NetworkInterfacePrivateIpAddress
// IPv4 Prefixes allocated for the network interface
IPv4Prefixes []*ec2.Ipv4PrefixSpecification
// IPv6 addresses allocated for the network interface
IPv6Addresses []*ec2.NetworkInterfaceIpv6Address
// IPv6 Prefixes allocated for the network interface
IPv6Prefixes []*ec2.Ipv6PrefixSpecification
}
// PrimaryIPv4Address returns the primary IPv4 address of this node
func (eni ENIMetadata) PrimaryIPv4Address() string {
for _, addr := range eni.IPv4Addresses {
if aws.BoolValue(addr.Primary) {
return aws.StringValue(addr.PrivateIpAddress)
}
}
return ""
}
// PrimaryIPv6Address returns the primary IPv6 address of this node
func (eni ENIMetadata) PrimaryIPv6Address() string {
for _, addr := range eni.IPv6Addresses {
if addr.Ipv6Address != nil {
return aws.StringValue(addr.Ipv6Address)
}
}
return ""
}
// TagMap keeps track of the EC2 tags on each ENI
type TagMap map[string]string
// DescribeAllENIsResult contains the fully
type DescribeAllENIsResult struct {
ENIMetadata []ENIMetadata
TagMap map[string]TagMap
TrunkENI string
EFAENIs map[string]bool
MultiCardENIIDs []string
}
// msSince returns milliseconds since start.
func msSince(start time.Time) float64 {
return float64(time.Since(start) / time.Millisecond)
}
// StringSet is a set of strings
type StringSet struct {
sync.RWMutex
data sets.String
}
// SortedList returns a sorted string slice from this set
func (ss *StringSet) SortedList() []string {
ss.RLock()
defer ss.RUnlock()
// sets.String.List() returns a sorted list
return ss.data.List()
}
// Set sets the string set
func (ss *StringSet) Set(items []string) {
ss.Lock()
defer ss.Unlock()
ss.data = sets.NewString(items...)
}
// Difference compares this StringSet with another
func (ss *StringSet) Difference(other *StringSet) *StringSet {
ss.RLock()
other.RLock()
defer ss.RUnlock()
defer other.RUnlock()
//example: s1 = {a1, a2, a3} s2 = {a1, a2, a4, a5} s1.Difference(s2) = {a3} s2.Difference(s1) = {a4, a5}
return &StringSet{data: ss.data.Difference(other.data)}
}
// Has returns true if the StringSet contains the string
func (ss *StringSet) Has(item string) bool {
ss.RLock()
defer ss.RUnlock()
return ss.data.Has(item)
}
type instrumentedIMDS struct {
EC2MetadataIface
}
func awsReqStatus(err error) string {
if err == nil {
return "200"
}
var aerr awserr.RequestFailure
if errors.As(err, &aerr) {
return fmt.Sprint(aerr.StatusCode())
}
return "" // Unknown HTTP status code
}
func (i instrumentedIMDS) GetMetadataWithContext(ctx context.Context, p string) (string, error) {
start := time.Now()
result, err := i.EC2MetadataIface.GetMetadataWithContext(ctx, p)
duration := msSince(start)
prometheusmetrics.AwsAPILatency.WithLabelValues("GetMetadata", fmt.Sprint(err != nil), awsReqStatus(err)).Observe(duration)
if err != nil {
return "", newIMDSRequestError(p, err)
}
return result, nil
}
// New creates an EC2InstanceMetadataCache
func New(useSubnetDiscovery, useCustomNetworking, disableLeakedENICleanup, v4Enabled, v6Enabled bool) (*EC2InstanceMetadataCache, error) {
// ctx is passed to initWithEC2Metadata func to cancel spawned go-routines when tests are run
ctx := context.Background()
sess := awssession.New()
ec2Metadata := ec2metadata.New(sess)
cache := &EC2InstanceMetadataCache{}
cache.imds = TypedIMDS{instrumentedIMDS{ec2Metadata}}
cache.clusterName = os.Getenv(clusterNameEnvVar)
cache.additionalENITags = loadAdditionalENITags()
region, err := ec2Metadata.Region()
if err != nil {
log.Errorf("Failed to retrieve region data from instance metadata %v", err)
return nil, errors.Wrap(err, "instance metadata: failed to retrieve region data")
}
cache.region = region
log.Debugf("Discovered region: %s", cache.region)
cache.useCustomNetworking = useCustomNetworking
log.Infof("Custom networking enabled %v", cache.useCustomNetworking)
cache.useSubnetDiscovery = useSubnetDiscovery
log.Infof("Subnet discovery enabled %v", cache.useSubnetDiscovery)
cache.v4Enabled = v4Enabled
cache.v6Enabled = v6Enabled
awsCfg := aws.NewConfig().WithRegion(region)
sess = sess.Copy(awsCfg)
ec2SVC := ec2wrapper.New(sess)
cache.ec2SVC = ec2SVC
err = cache.initWithEC2Metadata(ctx)
if err != nil {
return nil, err
}
// Clean up leaked ENIs in the background
if !disableLeakedENICleanup {
go wait.Forever(cache.cleanUpLeakedENIs, time.Hour)
}
return cache, nil
}
func (cache *EC2InstanceMetadataCache) InitCachedPrefixDelegation(enablePrefixDelegation bool) {
cache.enablePrefixDelegation = enablePrefixDelegation
log.Infof("Prefix Delegation enabled %v", cache.enablePrefixDelegation)
}
// InitWithEC2metadata initializes the EC2InstanceMetadataCache with the data retrieved from EC2 metadata service
func (cache *EC2InstanceMetadataCache) initWithEC2Metadata(ctx context.Context) error {
var err error
// retrieve availability-zone
cache.availabilityZone, err = cache.imds.GetAZ(ctx)
if err != nil {
awsAPIErrInc("GetAZ", err)
return err
}
log.Debugf("Found availability zone: %s ", cache.availabilityZone)
// retrieve primary interface local-ipv4
cache.localIPv4, err = cache.imds.GetLocalIPv4(ctx)
if err != nil {
awsAPIErrInc("GetLocalIPv4", err)
return err
}
log.Debugf("Discovered the instance primary IPv4 address: %s", cache.localIPv4)
// retrieve instance-id
cache.instanceID, err = cache.imds.GetInstanceID(ctx)
if err != nil {
awsAPIErrInc("GetInstanceID", err)
return err
}
log.Debugf("Found instance-id: %s ", cache.instanceID)
// retrieve instance-type
cache.instanceType, err = cache.imds.GetInstanceType(ctx)
if err != nil {
awsAPIErrInc("GetInstanceType", err)
return err
}
log.Debugf("Found instance-type: %s ", cache.instanceType)
// retrieve primary interface's mac
mac, err := cache.imds.GetMAC(ctx)
if err != nil {
awsAPIErrInc("GetMAC", err)
return err
}
cache.primaryENImac = mac
log.Debugf("Found primary interface's MAC address: %s", mac)
cache.primaryENI, err = cache.imds.GetInterfaceID(ctx, mac)
if err != nil {
awsAPIErrInc("GetInterfaceID", err)
return errors.Wrap(err, "get instance metadata: failed to find primary ENI")
}
log.Debugf("%s is the primary ENI of this instance", cache.primaryENI)
// retrieve subnet-id
cache.subnetID, err = cache.imds.GetSubnetID(ctx, mac)
if err != nil {
awsAPIErrInc("GetSubnetID", err)
return err
}
log.Debugf("Found subnet-id: %s ", cache.subnetID)
// retrieve vpc-id
cache.vpcID, err = cache.imds.GetVpcID(ctx, mac)
if err != nil {
awsAPIErrInc("GetVpcID", err)
return err
}
log.Debugf("Found vpc-id: %s ", cache.vpcID)
// We use the ctx here for testing, since we spawn go-routines above which will run forever.
select {
case <-ctx.Done():
return nil
default:
}
return nil
}
// RefreshSGIDs retrieves security groups
func (cache *EC2InstanceMetadataCache) RefreshSGIDs(mac string) error {
ctx := context.TODO()
sgIDs, err := cache.imds.GetSecurityGroupIDs(ctx, mac)
if err != nil {
awsAPIErrInc("GetSecurityGroupIDs", err)
return err
}
newSGs := StringSet{}
newSGs.Set(sgIDs)
addedSGs := newSGs.Difference(&cache.securityGroups)
addedSGsCount := 0
deletedSGs := cache.securityGroups.Difference(&newSGs)
deletedSGsCount := 0
for _, sg := range addedSGs.SortedList() {
log.Infof("Found %s, added to ipamd cache", sg)
addedSGsCount++
}
for _, sg := range deletedSGs.SortedList() {
log.Infof("Removed %s from ipamd cache", sg)
deletedSGsCount++
}
cache.securityGroups.Set(sgIDs)
if !cache.useCustomNetworking && (addedSGsCount != 0 || deletedSGsCount != 0) {
allENIs, err := cache.GetAttachedENIs()
if err != nil {
return errors.Wrap(err, "DescribeAllENIs: failed to get local ENI metadata")
}
var eniIDs []string
for _, eni := range allENIs {
eniIDs = append(eniIDs, eni.ENIID)
}
newENIs := StringSet{}
newENIs.Set(eniIDs)
tempfilteredENIs := newENIs.Difference(&cache.multiCardENIs)
filteredENIs := tempfilteredENIs.Difference(&cache.unmanagedENIs)
sgIDsPtrs := aws.StringSlice(sgIDs)
// This will update SG for managed ENIs created by EKS.
for _, eniID := range filteredENIs.SortedList() {
log.Debugf("Update ENI %s", eniID)
attributeInput := &ec2.ModifyNetworkInterfaceAttributeInput{
Groups: sgIDsPtrs,
NetworkInterfaceId: aws.String(eniID),
}
start := time.Now()
_, err = cache.ec2SVC.ModifyNetworkInterfaceAttributeWithContext(context.Background(), attributeInput)
prometheusmetrics.Ec2ApiReq.WithLabelValues("ModifyNetworkInterfaceAttribute").Inc()
prometheusmetrics.AwsAPILatency.WithLabelValues("ModifyNetworkInterfaceAttribute", fmt.Sprint(err != nil), awsReqStatus(err)).Observe(msSince(start))
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
if aerr.Code() == "InvalidNetworkInterfaceID.NotFound" {
awsAPIErrInc("IMDSMetaDataOutOfSync", err)
}
}
checkAPIErrorAndBroadcastEvent(err, "ec2:ModifyNetworkInterfaceAttribute")
awsAPIErrInc("ModifyNetworkInterfaceAttribute", err)
prometheusmetrics.Ec2ApiErr.WithLabelValues("ModifyNetworkInterfaceAttribute").Inc()
//No need to return error here since retry will happen in 30seconds and also
//If update failed due to stale ENI then returning error will prevent updating SG
//for following ENIs since the list is sorted
log.Debugf("refreshSGIDs: unable to update the ENI %s SG - %v", eniID, err)
}
}
}
return nil
}
// GetAttachedENIs retrieves ENI information from meta data service
func (cache *EC2InstanceMetadataCache) GetAttachedENIs() (eniList []ENIMetadata, err error) {
ctx := context.TODO()
// retrieve number of interfaces
macs, err := cache.imds.GetMACs(ctx)
if err != nil {
awsAPIErrInc("GetMACs", err)
return nil, err
}
log.Debugf("Total number of interfaces found: %d ", len(macs))
enis := make([]ENIMetadata, len(macs))
// retrieve the attached ENIs
for i, mac := range macs {
enis[i], err = cache.getENIMetadata(mac)
if err != nil {
return nil, errors.Wrapf(err, "get attached ENIs: failed to retrieve ENI metadata for ENI: %s", mac)
}
}
return enis, nil
}
func (cache *EC2InstanceMetadataCache) getENIMetadata(eniMAC string) (ENIMetadata, error) {
ctx := context.TODO()
log.Debugf("Found ENI MAC address: %s", eniMAC)
var err error
var deviceNum int
eniID, err := cache.imds.GetInterfaceID(ctx, eniMAC)
if err != nil {
awsAPIErrInc("GetInterfaceID", err)
return ENIMetadata{}, err
}
deviceNum, err = cache.imds.GetDeviceNumber(ctx, eniMAC)
if err != nil {
awsAPIErrInc("GetDeviceNumber", err)
return ENIMetadata{}, err
}
primaryMAC, err := cache.imds.GetMAC(ctx)
if err != nil {
awsAPIErrInc("GetMAC", err)
return ENIMetadata{}, err
}
if eniMAC == primaryMAC && deviceNum != 0 {
// Can this even happen? To be backwards compatible, we will always use 0 here and log an error.
log.Errorf("Device number of primary ENI is %d! Forcing it to be 0 as expected", deviceNum)
deviceNum = 0
}
log.Debugf("Found ENI: %s, MAC %s, device %d", eniID, eniMAC, deviceNum)
// Get IPv4 and IPv6 addresses assigned to interface
cidr, err := cache.imds.GetSubnetIPv4CIDRBlock(ctx, eniMAC)
if err != nil {
awsAPIErrInc("GetSubnetIPv4CIDRBlock", err)
return ENIMetadata{}, err
}
imdsIPv4s, err := cache.imds.GetLocalIPv4s(ctx, eniMAC)
if err != nil {
awsAPIErrInc("GetLocalIPv4s", err)
return ENIMetadata{}, err
}
ec2ip4s := make([]*ec2.NetworkInterfacePrivateIpAddress, len(imdsIPv4s))
for i, ip4 := range imdsIPv4s {
ec2ip4s[i] = &ec2.NetworkInterfacePrivateIpAddress{
Primary: aws.Bool(i == 0),
PrivateIpAddress: aws.String(ip4.String()),
}
}
var ec2ip6s []*ec2.NetworkInterfaceIpv6Address
var subnetV6Cidr string
if cache.v6Enabled {
// For IPv6 ENIs, do not error on missing IPv6 information
v6cidr, err := cache.imds.GetSubnetIPv6CIDRBlocks(ctx, eniMAC)
if err != nil {
awsAPIErrInc("GetSubnetIPv6CIDRBlocks", err)
} else {
subnetV6Cidr = v6cidr.String()
}
imdsIPv6s, err := cache.imds.GetIPv6s(ctx, eniMAC)
if err != nil {
awsAPIErrInc("GetIPv6s", err)
} else {
ec2ip6s = make([]*ec2.NetworkInterfaceIpv6Address, len(imdsIPv6s))
for i, ip6 := range imdsIPv6s {
ec2ip6s[i] = &ec2.NetworkInterfaceIpv6Address{
Ipv6Address: aws.String(ip6.String()),
}
}
}
}
var ec2ipv4Prefixes []*ec2.Ipv4PrefixSpecification
var ec2ipv6Prefixes []*ec2.Ipv6PrefixSpecification
// If IPv6 is enabled, get attached v6 prefixes.
if cache.v6Enabled {
imdsIPv6Prefixes, err := cache.imds.GetIPv6Prefixes(ctx, eniMAC)
if err != nil {
awsAPIErrInc("GetIPv6Prefixes", err)
return ENIMetadata{}, err
}
for _, ipv6prefix := range imdsIPv6Prefixes {
ec2ipv6Prefixes = append(ec2ipv6Prefixes, &ec2.Ipv6PrefixSpecification{
Ipv6Prefix: aws.String(ipv6prefix.String()),
})
}
} else if cache.v4Enabled && ((eniMAC == primaryMAC && !cache.useCustomNetworking) || (eniMAC != primaryMAC)) {
// Get prefix on primary ENI when custom networking is enabled is not needed.
// If primary ENI has prefixes attached and then we move to custom networking, we don't need to fetch
// the prefix since recommendation is to terminate the nodes and that would have deleted the prefix on the
// primary ENI.
imdsIPv4Prefixes, err := cache.imds.GetIPv4Prefixes(ctx, eniMAC)
if err != nil {
awsAPIErrInc("GetIPv4Prefixes", err)
return ENIMetadata{}, err
}
for _, ipv4prefix := range imdsIPv4Prefixes {
ec2ipv4Prefixes = append(ec2ipv4Prefixes, &ec2.Ipv4PrefixSpecification{
Ipv4Prefix: aws.String(ipv4prefix.String()),
})
}
}
return ENIMetadata{
ENIID: eniID,
MAC: eniMAC,
DeviceNumber: deviceNum,
SubnetIPv4CIDR: cidr.String(),
IPv4Addresses: ec2ip4s,
IPv4Prefixes: ec2ipv4Prefixes,
SubnetIPv6CIDR: subnetV6Cidr,
IPv6Addresses: ec2ip6s,
IPv6Prefixes: ec2ipv6Prefixes,
}, nil
}
// awsGetFreeDeviceNumber calls EC2 API DescribeInstances to get the next free device index
func (cache *EC2InstanceMetadataCache) awsGetFreeDeviceNumber() (int, error) {
input := &ec2.DescribeInstancesInput{
InstanceIds: []*string{aws.String(cache.instanceID)},
}
start := time.Now()
result, err := cache.ec2SVC.DescribeInstancesWithContext(context.Background(), input)
prometheusmetrics.Ec2ApiReq.WithLabelValues("DescribeInstances").Inc()
prometheusmetrics.AwsAPILatency.WithLabelValues("DescribeInstances", fmt.Sprint(err != nil), awsReqStatus(err)).Observe(msSince(start))
if err != nil {
checkAPIErrorAndBroadcastEvent(err, "ec2:DescribeInstances")
awsAPIErrInc("DescribeInstances", err)
prometheusmetrics.Ec2ApiErr.WithLabelValues("DescribeInstances").Inc()
log.Errorf("awsGetFreeDeviceNumber: Unable to retrieve instance data from EC2 control plane %v", err)
return 0, errors.Wrap(err,
"find a free device number for ENI: not able to retrieve instance data from EC2 control plane")
}
if len(result.Reservations) != 1 {
return 0, errors.Errorf("awsGetFreeDeviceNumber: invalid instance id %s", cache.instanceID)
}
inst := result.Reservations[0].Instances[0]
var device [maxENIs]bool
for _, eni := range inst.NetworkInterfaces {
// We don't support multi-card yet, so only account for network card zero
if aws.Int64Value(eni.Attachment.NetworkCardIndex) == 0 {
if aws.Int64Value(eni.Attachment.DeviceIndex) > maxENIs {
log.Warnf("The Device Index %d of the attached ENI %s > instance max slot %d",
aws.Int64Value(eni.Attachment.DeviceIndex), aws.StringValue(eni.NetworkInterfaceId),
maxENIs)
} else {
log.Debugf("Discovered device number is used: %d", aws.Int64Value(eni.Attachment.DeviceIndex))
device[aws.Int64Value(eni.Attachment.DeviceIndex)] = true
}
}
}
for freeDeviceIndex := 0; freeDeviceIndex < maxENIs; freeDeviceIndex++ {
if !device[freeDeviceIndex] {
log.Debugf("Found a free device number: %d", freeDeviceIndex)
return freeDeviceIndex, nil
}
}
return 0, errors.New("awsGetFreeDeviceNumber: no available device number")
}
// AllocENI creates an ENI and attaches it to the instance
// returns: newly created ENI ID
func (cache *EC2InstanceMetadataCache) AllocENI(useCustomCfg bool, sg []*string, eniCfgSubnet string, numIPs int) (string, error) {
eniID, err := cache.createENI(useCustomCfg, sg, eniCfgSubnet, numIPs)
if err != nil {
return "", errors.Wrap(err, "AllocENI: failed to create ENI")
}
attachmentID, err := cache.attachENI(eniID)
if err != nil {
derr := cache.deleteENI(eniID, maxENIBackoffDelay)
if derr != nil {
awsUtilsErrInc("AllocENIDeleteErr", err)
log.Errorf("Failed to delete newly created untagged ENI! %v", err)
}
return "", errors.Wrap(err, "AllocENI: error attaching ENI")
}
// Also change the ENI's attribute so that the ENI will be deleted when the instance is deleted.
attributeInput := &ec2.ModifyNetworkInterfaceAttributeInput{
Attachment: &ec2.NetworkInterfaceAttachmentChanges{
AttachmentId: aws.String(attachmentID),
DeleteOnTermination: aws.Bool(true),
},
NetworkInterfaceId: aws.String(eniID),
}
start := time.Now()
_, err = cache.ec2SVC.ModifyNetworkInterfaceAttributeWithContext(context.Background(), attributeInput)
prometheusmetrics.Ec2ApiReq.WithLabelValues("ModifyNetworkInterfaceAttribute").Inc()
prometheusmetrics.AwsAPILatency.WithLabelValues("ModifyNetworkInterfaceAttribute", fmt.Sprint(err != nil), awsReqStatus(err)).Observe(msSince(start))
if err != nil {
checkAPIErrorAndBroadcastEvent(err, "ec2:ModifyNetworkInterfaceAttribute")
awsAPIErrInc("ModifyNetworkInterfaceAttribute", err)
prometheusmetrics.Ec2ApiErr.WithLabelValues("ModifyNetworkInterfaceAttribute").Inc()
err := cache.FreeENI(eniID)
if err != nil {
awsUtilsErrInc("ENICleanupUponModifyNetworkErr", err)
}
return "", errors.Wrap(err, "AllocENI: unable to change the ENI's attribute")
}
log.Infof("Successfully created and attached a new ENI %s to instance", eniID)
return eniID, nil
}
// attachENI calls EC2 API to attach the ENI and returns the attachment id
func (cache *EC2InstanceMetadataCache) attachENI(eniID string) (string, error) {
// attach to instance
freeDevice, err := cache.awsGetFreeDeviceNumber()
if err != nil {
return "", errors.Wrap(err, "attachENI: failed to get a free device number")
}
attachInput := &ec2.AttachNetworkInterfaceInput{
DeviceIndex: aws.Int64(int64(freeDevice)),
InstanceId: aws.String(cache.instanceID),
NetworkInterfaceId: aws.String(eniID),
NetworkCardIndex: aws.Int64(0),
}
start := time.Now()
attachOutput, err := cache.ec2SVC.AttachNetworkInterfaceWithContext(context.Background(), attachInput)
prometheusmetrics.Ec2ApiReq.WithLabelValues("AttachNetworkInterface").Inc()
prometheusmetrics.AwsAPILatency.WithLabelValues("AttachNetworkInterface", fmt.Sprint(err != nil), awsReqStatus(err)).Observe(msSince(start))
if err != nil {
checkAPIErrorAndBroadcastEvent(err, "ec2:AttachNetworkInterface")
awsAPIErrInc("AttachNetworkInterface", err)
prometheusmetrics.Ec2ApiErr.WithLabelValues("AttachNetworkInterface").Inc()
log.Errorf("Failed to attach ENI %s: %v", eniID, err)
return "", errors.Wrap(err, "attachENI: failed to attach ENI")
}
return aws.StringValue(attachOutput.AttachmentId), err
}
// return ENI id, error
func (cache *EC2InstanceMetadataCache) createENI(useCustomCfg bool, sg []*string, eniCfgSubnet string, numIPs int) (string, error) {
eniDescription := eniDescriptionPrefix + cache.instanceID
tags := map[string]string{
eniCreatedAtTagKey: time.Now().Format(time.RFC3339),
}
for key, value := range cache.buildENITags() {
tags[key] = value
}
tagSpec := []*ec2.TagSpecification{
{
ResourceType: aws.String(ec2.ResourceTypeNetworkInterface),
Tags: convertTagsToSDKTags(tags),
},
}
var needIPs = numIPs
ipLimit := cache.GetENIIPv4Limit()
if ipLimit < needIPs {
needIPs = ipLimit
}
log.Infof("Trying to allocate %d IP addresses on new ENI", needIPs)
log.Debugf("PD enabled - %t", cache.enablePrefixDelegation)
input := &ec2.CreateNetworkInterfaceInput{}
if cache.enablePrefixDelegation {
input = &ec2.CreateNetworkInterfaceInput{
Description: aws.String(eniDescription),
Groups: aws.StringSlice(cache.securityGroups.SortedList()),
SubnetId: aws.String(cache.subnetID),
TagSpecifications: tagSpec,
Ipv4PrefixCount: aws.Int64(int64(needIPs)),
}
} else {
input = &ec2.CreateNetworkInterfaceInput{
Description: aws.String(eniDescription),
Groups: aws.StringSlice(cache.securityGroups.SortedList()),
SubnetId: aws.String(cache.subnetID),
TagSpecifications: tagSpec,
SecondaryPrivateIpAddressCount: aws.Int64(int64(needIPs)),
}
}
var err error
var networkInterfaceID string
if cache.useCustomNetworking {
input = createENIUsingCustomCfg(sg, eniCfgSubnet, input)
log.Infof("Creating ENI with security groups: %v in subnet: %s", aws.StringValueSlice(input.Groups), aws.StringValue(input.SubnetId))
networkInterfaceID, err = cache.tryCreateNetworkInterface(input)
if err == nil {
return networkInterfaceID, nil
}
} else {
if cache.useSubnetDiscovery {
subnetResult, vpcErr := cache.getVpcSubnets()
if vpcErr != nil {
log.Warnf("Failed to call ec2:DescribeSubnets: %v", vpcErr)
log.Info("Defaulting to same subnet as the primary interface for the new ENI")
networkInterfaceID, err = cache.tryCreateNetworkInterface(input)
if err == nil {
return networkInterfaceID, nil
}
} else {
for _, subnet := range subnetResult {
if *subnet.SubnetId != cache.subnetID {
if !validTag(subnet) {
continue
}
}
log.Infof("Creating ENI with security groups: %v in subnet: %s", aws.StringValueSlice(input.Groups), aws.StringValue(input.SubnetId))
input.SubnetId = subnet.SubnetId
networkInterfaceID, err = cache.tryCreateNetworkInterface(input)
if err == nil {
return networkInterfaceID, nil
}
}
}
} else {
log.Info("Using same security group config as the primary interface for the new ENI")
networkInterfaceID, err = cache.tryCreateNetworkInterface(input)
if err == nil {
return networkInterfaceID, nil
}
}
}
return "", errors.Wrap(err, "failed to create network interface")
}
func (cache *EC2InstanceMetadataCache) getVpcSubnets() ([]*ec2.Subnet, error) {
describeSubnetInput := &ec2.DescribeSubnetsInput{
Filters: []*ec2.Filter{
{
Name: aws.String("vpc-id"),
Values: []*string{aws.String(cache.vpcID)},
},
{
Name: aws.String("availability-zone"),
Values: []*string{aws.String(cache.availabilityZone)},
},
},
}
start := time.Now()
subnetResult, err := cache.ec2SVC.DescribeSubnetsWithContext(context.Background(), describeSubnetInput)
prometheusmetrics.Ec2ApiReq.WithLabelValues("DescribeSubnets").Inc()
prometheusmetrics.AwsAPILatency.WithLabelValues("DescribeSubnets", fmt.Sprint(err != nil), awsReqStatus(err)).Observe(msSince(start))
if err != nil {
checkAPIErrorAndBroadcastEvent(err, "ec2:DescribeSubnets")
awsAPIErrInc("DescribeSubnets", err)
prometheusmetrics.Ec2ApiErr.WithLabelValues("DescribeSubnets").Inc()
return nil, errors.Wrap(err, "AllocENI: unable to describe subnets")
}
// Sort the subnet by available IP address counter (desc order) before determining subnet to use
sort.SliceStable(subnetResult.Subnets, func(i, j int) bool {
return *subnetResult.Subnets[j].AvailableIpAddressCount < *subnetResult.Subnets[i].AvailableIpAddressCount
})
return subnetResult.Subnets, nil
}
func validTag(subnet *ec2.Subnet) bool {
for _, tag := range subnet.Tags {
if *tag.Key == subnetDiscoveryTagKey {
return true
}
}
return false
}
func createENIUsingCustomCfg(sg []*string, eniCfgSubnet string, input *ec2.CreateNetworkInterfaceInput) *ec2.CreateNetworkInterfaceInput {
log.Info("Using a custom network config for the new ENI")
if len(sg) != 0 {
input.Groups = sg
} else {
log.Warnf("No custom networking security group found, will use the node's primary ENI's SG: %v", aws.StringValueSlice(input.Groups))
}
input.SubnetId = aws.String(eniCfgSubnet)
return input
}
func (cache *EC2InstanceMetadataCache) tryCreateNetworkInterface(input *ec2.CreateNetworkInterfaceInput) (string, error) {
start := time.Now()
result, err := cache.ec2SVC.CreateNetworkInterfaceWithContext(context.Background(), input)
prometheusmetrics.Ec2ApiReq.WithLabelValues("CreateNetworkInterface").Inc()
prometheusmetrics.AwsAPILatency.WithLabelValues("CreateNetworkInterface", fmt.Sprint(err != nil), awsReqStatus(err)).Observe(msSince(start))
if err == nil {
log.Infof("Created a new ENI: %s", aws.StringValue(result.NetworkInterface.NetworkInterfaceId))
return aws.StringValue(result.NetworkInterface.NetworkInterfaceId), nil
}
checkAPIErrorAndBroadcastEvent(err, "ec2:CreateNetworkInterface")
awsAPIErrInc("CreateNetworkInterface", err)
prometheusmetrics.Ec2ApiErr.WithLabelValues("CreateNetworkInterface").Inc()
log.Errorf("Failed to CreateNetworkInterface %v for subnet %s", err, *input.SubnetId)
return "", err
}
// buildENITags computes the desired AWS Tags for eni
func (cache *EC2InstanceMetadataCache) buildENITags() map[string]string {
tags := map[string]string{
eniNodeTagKey: cache.instanceID,
}
// If clusterName is provided,
// tag the ENI with "cluster.k8s.amazonaws.com/name=<cluster_name>"
if cache.clusterName != "" {
tags[eniClusterTagKey] = cache.clusterName
}
for key, value := range cache.additionalENITags {
tags[key] = value
}
return tags
}
func (cache *EC2InstanceMetadataCache) TagENI(eniID string, currentTags map[string]string) error {
tagChanges := make(map[string]string)