-
Notifications
You must be signed in to change notification settings - Fork 811
Expand file tree
/
Copy pathawsutils.go
More file actions
2662 lines (2314 loc) · 98.4 KB
/
awsutils.go
File metadata and controls
2662 lines (2314 loc) · 98.4 KB
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"
"io"
"math/rand"
"net"
"os"
"regexp"
"sort"
"strings"
"sync"
"time"
"github.com/aws/amazon-vpc-cni-k8s/utils"
"github.com/aws/aws-sdk-go-v2/aws/middleware"
"github.com/aws/aws-sdk-go-v2/config"
smithymiddleware "github.com/aws/smithy-go/middleware"
"github.com/aws/smithy-go"
"github.com/aws/amazon-vpc-cni-k8s/pkg/ipamd/datastore"
"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"
vpcControllerVpc "github.com/aws/amazon-vpc-resource-controller-k8s/pkg/aws/vpc"
"github.com/aws/aws-sdk-go-v2/aws"
ec2metadata "github.com/aws/aws-sdk-go-v2/feature/ec2/imds"
"github.com/aws/aws-sdk-go-v2/service/ec2"
ec2types "github.com/aws/aws-sdk-go-v2/service/ec2/types"
"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"
// clusterTagKeyPrefix is the prefix for the cluster-specific subnet tags
clusterTagKeyPrefix = "kubernetes.io/cluster/"
eniNodeTagKey = "node.k8s.amazonaws.com/instance_id"
eniCreatedAtTagKey = "node.k8s.amazonaws.com/createdAt"
eniClusterTagKey = "cluster.k8s.amazonaws.com/name"
eniOwnerTagKey = "eks:eni:owner"
eniOwnerTagValue = "amazon-vpc-cni"
additionalEniTagsEnvVar = "ADDITIONAL_ENI_TAGS"
reservedTagKeyPrefix = "k8s.amazonaws.com"
subnetDiscoveryTagKey = "kubernetes.io/role/cni"
subnetDiscoveryTagValueIncluded = "1"
subnetDiscoveryTagValueExcluded = "0"
envVpcCniVersion = "VPC_CNI_VERSION"
// 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 (
awsAPIError smithy.APIError
awsGenericAPIError *smithy.GenericAPIError
// 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")
// ErrUnableToDetachENI is returned when the ENI cannot be detached from the instance
ErrUnableToDetachENI = errors.New("unable to detach ENI from EC2 instance, giving up")
// ErrENIAttachmentIdNotFound is returned when the ENI attachment ID is not found
ErrENIAttachmentIdNotFound = errors.New("ENI attachment ID not found")
)
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(ctx context.Context, sg []*string, eniCfgSubnet string, numIPs int, networkCard int) (eni string, err error)
// FreeENI detaches ENI interface and deletes it
FreeENI(ctx context.Context, eniName string) error
// TagENI Tags ENI with current tags to contain expected tags.
TagENI(ctx context.Context, 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(ctx context.Context, eniID string) (addrList []ec2types.NetworkInterfacePrivateIpAddress, err error)
// GetIPv4PrefixesFromEC2 returns the IPv4 prefixes for a given ENI
GetIPv4PrefixesFromEC2(ctx context.Context, eniID string) (addrList []ec2types.Ipv4PrefixSpecification, err error)
// GetIPv6PrefixesFromEC2 returns the IPv6 prefixes for a given ENI
GetIPv6PrefixesFromEC2(ctx context.Context, eniID string) (addrList []ec2types.Ipv6PrefixSpecification, err error)
// DescribeAllENIs calls EC2 and returns a fully populated DescribeAllENIsResult struct and an error
DescribeAllENIs(ctx context.Context) (DescribeAllENIsResult, error)
// AllocIPAddress allocates an IP address for an ENI
AllocIPAddress(ctx context.Context, eniID string) error
// AllocIPAddresses allocates numIPs IP addresses on a ENI
AllocIPAddresses(ctx context.Context, eniID string, numIPs int) (*ec2.AssignPrivateIpAddressesOutput, error)
// DeallocIPAddresses deallocates the list of IP addresses from a ENI
DeallocIPAddresses(ctx context.Context, eniID string, ips []string) error
// DeallocPrefixAddresses deallocates the list of IP addresses from a ENI
DeallocPrefixAddresses(ctx context.Context, eniID string, ips []string) error
// AllocIPv6Prefixes allocates IPv6 prefixes to the ENI passed in
AllocIPv6Prefixes(ctx context.Context, 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
// GetLocalIPv6 returns the primary IPv6 address on the primary ENI interface
GetLocalIPv6() 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)
// SetUnmanagedNetworkCards sets the list of unmanaged Network Cards
SetUnmanagedNetworkCards(skipNetworkCards []bool)
// Set EFAOnlyENIs
SetEFAOnlyENIs(efaOnlyENIByNetworkCard []string)
// IsUnmanagedENI checks if an ENI is unmanaged
IsUnmanagedENI(eniID string) bool
// IsUnmanagedNIC checks if an Network Card is unmanaged
IsUnmanagedNIC(networkCard int) bool
// IsEfaOnlyENI checks if an ENI is efa-only
IsEfaOnlyENI(networkCard int, eni string) bool
// WaitForENIAndIPsAttached waits until the ENI has been attached and the secondary IPs have been added
WaitForENIAndIPsAttached(eni string, wantedSecondaryIPs int) (ENIMetadata, error)
// IsPrimaryENI
IsPrimaryENI(eniID string) bool
// RefreshSGIDs
RefreshSGIDs(ctx context.Context, mac string, ds *datastore.DataStoreAccess) error
// RefreshCustomSGIDs discovers and refreshes security groups tagged with kubernetes.io/role/cni=1
RefreshCustomSGIDs(ctx context.Context, dsAccess *datastore.DataStoreAccess) 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(ctx context.Context) error
IsPrefixDelegationSupported() bool
IsTrunkingCompatible() bool
// GetENISubnetID gets the subnet ID for an ENI from AWS
GetENISubnetID(ctx context.Context, eniID string) (string, error)
// GetVpcSubnets returns all subnets in the VPC
GetVpcSubnets(ctx context.Context) ([]ec2types.Subnet, error)
// IsSubnetExcluded returns if a subnet is excluded for pod IPs based on its tags
IsSubnetExcluded(ctx context.Context, subnetID string) (bool, error)
}
// EC2InstanceMetadataCache caches instance metadata
type EC2InstanceMetadataCache struct {
// metadata info
securityGroups StringSet
customSecurityGroups 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
unmanagedNICs []bool
efaOnlyENIsByNetworkCard []string
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 []ec2types.NetworkInterfacePrivateIpAddress
// IPv4 Prefixes allocated for the network interface
IPv4Prefixes []ec2types.Ipv4PrefixSpecification
// IPv6 addresses allocated for the network interface
IPv6Addresses []ec2types.NetworkInterfaceIpv6Address
// IPv6 Prefixes allocated for the network interface
IPv6Prefixes []ec2types.Ipv6PrefixSpecification
// Network card the ENI is attached on
NetworkCard int
// SubnetID the ENI is created from
SubnetID string
}
// PrimaryIPv4Address returns the primary IPv4 address of this node
func (eni ENIMetadata) PrimaryIPv4Address() string {
for _, addr := range eni.IPv4Addresses {
if addr.Primary != nil && aws.ToBool(addr.Primary) {
return aws.ToString(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.ToString(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
EFAOnlyENIByNetworkCard []string
ENIsByNetworkCard [][]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"
}
if errors.As(err, &awsGenericAPIError) {
return fmt.Sprint(awsGenericAPIError.ErrorCode())
}
return "" // Unknown HTTP status code
}
func (i instrumentedIMDS) GetMetadataWithContext(ctx context.Context, p string) (string, error) {
start := time.Now()
output, err := i.EC2MetadataIface.GetMetadata(ctx, &ec2metadata.GetMetadataInput{Path: p})
duration := msSince(start)
prometheusmetrics.AwsAPILatency.WithLabelValues("GetMetadata", fmt.Sprint(err != nil), awsReqStatus(err)).Observe(duration)
if err != nil {
return "", newIMDSRequestError(p, err)
}
defer output.Content.Close()
bytes, err := io.ReadAll(output.Content)
if err != nil {
return "", newIMDSRequestError(p, fmt.Errorf("failed to read content: %w", err))
}
return string(bytes), nil
}
// New creates an EC2InstanceMetadataCache
func New(ctx context.Context, useSubnetDiscovery, useCustomNetworking, disableLeakedENICleanup, v4Enabled, v6Enabled bool) (*EC2InstanceMetadataCache, error) {
awsconfig, err := awssession.New(ctx)
if err != nil {
return nil, errors.Wrap(err, "failed to create aws session")
}
ec2Metadata := ec2metadata.NewFromConfig(awsconfig)
cache := &EC2InstanceMetadataCache{}
cache.imds = TypedIMDS{instrumentedIMDS{ec2Metadata}}
cache.clusterName = os.Getenv(clusterNameEnvVar)
cache.additionalENITags = loadAdditionalENITags()
region, err := ec2Metadata.GetRegion(ctx, nil)
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.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
version := utils.GetEnv(envVpcCniVersion, "")
awsCfg, err := config.LoadDefaultConfig(context.TODO(),
config.WithRegion(region.Region),
config.WithHTTPClient(awssession.NewAWSSDKHTTPClient()),
config.WithAPIOptions([]func(*smithymiddleware.Stack) error{
middleware.AddUserAgentKeyValue("amazon-vpc-cni-k8s", version),
}),
)
if err != nil {
return nil, fmt.Errorf("unable to load SDK config, %v", err)
}
ec2SVC := ec2wrapper.New(awsCfg)
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(func() { cache.cleanUpLeakedENIs(ctx) }, 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
}
// discoverCustomSecurityGroups discovers security groups with the cni-role tag
func (cache *EC2InstanceMetadataCache) discoverCustomSecurityGroups(ctx context.Context) ([]string, error) {
describeSGInput := &ec2.DescribeSecurityGroupsInput{
Filters: []ec2types.Filter{
{
Name: aws.String("vpc-id"),
Values: []string{cache.vpcID},
},
{
Name: aws.String("tag:" + subnetDiscoveryTagKey),
Values: []string{subnetDiscoveryTagValueIncluded},
},
},
}
var result *ec2.DescribeSecurityGroupsOutput
err := retry.NWithBackoffCtx(ctx, retry.NewSimpleBackoff(time.Millisecond*100, time.Second*5, 0.15, 2.0), 5, func() error {
var err error
result, err = cache.ec2SVC.DescribeSecurityGroups(ctx, describeSGInput)
return err
})
if err != nil {
return nil, fmt.Errorf("discoverCustomSecurityGroups: unable to describe security groups: %v", err)
}
var sgIDs []string
for _, sg := range result.SecurityGroups {
sgIDs = append(sgIDs, *sg.GroupId)
}
return sgIDs, nil
}
// GetENISubnetID gets the subnet ID for an ENI from AWS
func (cache *EC2InstanceMetadataCache) GetENISubnetID(ctx context.Context, eniID string) (string, error) {
describeInput := &ec2.DescribeNetworkInterfacesInput{
NetworkInterfaceIds: []string{eniID},
}
result, err := cache.ec2SVC.DescribeNetworkInterfaces(ctx, describeInput)
if err != nil {
return "", fmt.Errorf("getENISubnetID: unable to describe network interface: %v", err)
}
if len(result.NetworkInterfaces) == 0 {
return "", fmt.Errorf("getENISubnetID: no interfaces found")
}
return *result.NetworkInterfaces[0].SubnetId, nil
}
// Helper function to get ENIs that match specific criteria
func (cache *EC2InstanceMetadataCache) getFilteredENIs(store *datastore.DataStore, onlySecondarySubnets bool) []string {
eniInfos := store.GetENIInfos()
var eniIDs []string
for eniID := range eniInfos.ENIs {
if eniInfo, ok := eniInfos.ENIs[eniID]; ok {
// Skip primary ENI for secondary subnet operations
if onlySecondarySubnets && eniInfo.IsPrimary {
continue
}
isSecondarySubnet := eniInfo.SubnetID != cache.subnetID
// Filter based on subnet type
if onlySecondarySubnets != isSecondarySubnet {
continue
}
eniIDs = append(eniIDs, eniID)
}
}
// Apply standard filters (unmanaged and multi-card ENIs)
newENIs := StringSet{}
newENIs.Set(eniIDs)
filteredENIs := newENIs.Difference(&cache.unmanagedENIs)
return filteredENIs.SortedList()
}
// Helper function to apply security groups to a list of ENIs
func (cache *EC2InstanceMetadataCache) applySecurityGroupsToENIs(ctx context.Context, eniIDs []string, sgIDs []string, logPrefix string) {
for _, eniID := range eniIDs {
log.Debugf("%s ENI %s with security groups %v", logPrefix, eniID, sgIDs)
attributeInput := &ec2.ModifyNetworkInterfaceAttributeInput{
Groups: sgIDs,
NetworkInterfaceId: aws.String(eniID),
}
start := time.Now()
_, err := cache.ec2SVC.ModifyNetworkInterfaceAttribute(ctx, attributeInput)
prometheusmetrics.Ec2ApiReq.WithLabelValues("ModifyNetworkInterfaceAttribute").Inc()
prometheusmetrics.AwsAPILatency.WithLabelValues("ModifyNetworkInterfaceAttribute", fmt.Sprint(err != nil), awsReqStatus(err)).Observe(msSince(start))
if err != nil {
if errors.As(err, &awsAPIError) {
if awsAPIError.ErrorCode() == "InvalidNetworkInterfaceID.NotFound" {
awsAPIErrInc("IMDSMetaDataOutOfSync", err)
}
}
checkAPIErrorAndBroadcastEvent(err, "ec2:ModifyNetworkInterfaceAttribute")
awsAPIErrInc("ModifyNetworkInterfaceAttribute", err)
prometheusmetrics.Ec2ApiErr.WithLabelValues("ModifyNetworkInterfaceAttribute").Inc()
log.Warnf("%s: unable to update ENI %s security groups: %v", logPrefix, eniID, err)
}
}
}
// Helper function to detect and log security group changes
func (cache *EC2InstanceMetadataCache) detectSecurityGroupChanges(newSGs []string, currentSGs *StringSet, sgType string) (int, int) {
newSGSet := StringSet{}
newSGSet.Set(newSGs)
addedSGs := newSGSet.Difference(currentSGs)
deletedSGs := currentSGs.Difference(&newSGSet)
addedCount := 0
for _, sg := range addedSGs.SortedList() {
log.Infof("Found %s SG %s, added to ipamd cache", sgType, sg)
addedCount++
}
deletedCount := 0
for _, sg := range deletedSGs.SortedList() {
log.Infof("Removed %s SG %s from ipamd cache", sgType, sg)
deletedCount++
}
return addedCount, deletedCount
}
// RefreshCustomSGIDs discovers and refreshes security groups tagged for use with the CNI
func (cache *EC2InstanceMetadataCache) RefreshCustomSGIDs(ctx context.Context, dsAccess *datastore.DataStoreAccess) error {
sgIDs, err := cache.discoverCustomSecurityGroups(ctx)
if err != nil {
awsAPIErrInc("DiscoverCustomSecurityGroups", err)
log.Warnf("Failed to discover custom security groups: %v. Falling back to using primary security groups for ENIs in secondary subnets", err)
if eventRecorder := eventrecorder.Get(); eventRecorder != nil {
eventRecorder.SendPodEvent(v1.EventTypeWarning, "FailedCustomSecurityGroupsDiscovery", "DescribeSecurityGroups",
"aws-node failed calling ec2 api to discover custmized security groups for network interfaces from secondary subnets")
}
return err
}
// Check if no custom security groups were found (empty list)
if len(sgIDs) == 0 {
log.Info("No custom security groups found, using primary security groups for ENIs in secondary subnets")
// Clear custom security groups cache
cache.customSecurityGroups.Set([]string{})
// Apply primary security groups to ENIs in secondary subnets as fallback
cache.applyPrimarySGsToSecondarySubnetENIs(ctx, dsAccess)
return nil
}
addedCount, deletedCount := cache.detectSecurityGroupChanges(sgIDs, &cache.customSecurityGroups, "custom")
cache.customSecurityGroups.Set(sgIDs)
// If there are changes, update ENIs in secondary subnets
if addedCount != 0 || deletedCount != 0 {
var eniIDs []string
for _, ds := range dsAccess.DataStores {
eniIDs = append(eniIDs, cache.getFilteredENIs(ds, true)...) // only secondary subnet ENIs
}
cache.applySecurityGroupsToENIs(ctx, eniIDs, sgIDs, "Update")
}
return nil
}
// applyPrimarySGsToSecondarySubnetENIs applies primary security groups to ENIs in secondary subnets across all datastores
func (cache *EC2InstanceMetadataCache) applyPrimarySGsToSecondarySubnetENIs(ctx context.Context, dsAccess *datastore.DataStoreAccess) {
log.Info("Applying primary security groups as fallback for ENIs in secondary subnets across all datastores")
primarySGs := cache.securityGroups.SortedList()
if len(primarySGs) == 0 {
log.Warn("No primary security groups available for fallback")
}
var eniIDs []string
for _, ds := range dsAccess.DataStores {
eniIDs = append(eniIDs, cache.getFilteredENIs(ds, true)...) // only secondary subnet ENIs
}
cache.applySecurityGroupsToENIs(ctx, eniIDs, primarySGs, "Applying primary security groups to")
}
// RefreshSGIDs retrieves security groups
func (cache *EC2InstanceMetadataCache) RefreshSGIDs(ctx context.Context, mac string, dsAccess *datastore.DataStoreAccess) error {
sgIDs, err := cache.imds.GetSecurityGroupIDs(ctx, mac)
if err != nil {
awsAPIErrInc("GetSecurityGroupIDs", err)
return err
}
addedCount, deletedCount := cache.detectSecurityGroupChanges(sgIDs, &cache.securityGroups, "primary")
cache.securityGroups.Set(sgIDs)
if !cache.useCustomNetworking && (addedCount != 0 || deletedCount != 0) {
var eniIDs []string
// When subnet discovery is enabled, only apply primary SGs to primary subnet ENIs
if cache.useSubnetDiscovery {
for _, ds := range dsAccess.DataStores {
// Get only primary subnet ENIs (onlySecondarySubnets=false)
primarySubnetENIs := cache.getFilteredENIs(ds, false)
for _, eniID := range primarySubnetENIs {
// Filter out unmanaged ENIs
if !cache.unmanagedENIs.Has(eniID) {
eniIDs = append(eniIDs, eniID)
}
}
}
} else {
// Original behavior: apply to all managed ENIs when subnet discovery is disabled
for _, ds := range dsAccess.DataStores {
eniInfos := ds.GetENIInfos()
for eniID := range eniInfos.ENIs {
eniIDs = append(eniIDs, eniID)
}
}
newENIs := StringSet{}
newENIs.Set(eniIDs)
filteredENIs := newENIs.Difference(&cache.unmanagedENIs)
eniIDs = filteredENIs.SortedList()
}
// Apply security groups to the filtered ENIs
cache.applySecurityGroupsToENIs(ctx, eniIDs, sgIDs, "Update")
}
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 IMDS fields for the interface
macImdsFields, err := cache.imds.GetMACImdsFields(ctx, eniMAC)
if err != nil {
awsAPIErrInc("GetMACImdsFields", err)
return ENIMetadata{}, err
}
ipv4Available := false
ipv6Available := false
networkCard := 0
// Efa-only interfaces do not have any ipv4s or ipv6s associated with it. If we don't find any local-ipv4 or ipv6 info in imds we assume it to be efa-only interface and validate this later via ec2 call
for _, field := range macImdsFields {
if field == "local-ipv4s" {
imdsIPv4s, err := cache.imds.GetLocalIPv4s(ctx, eniMAC)
if err != nil {
awsAPIErrInc("GetLocalIPv4s", err)
return ENIMetadata{}, err
}
if len(imdsIPv4s) > 0 {
ipv4Available = true
log.Debugf("Found IPv4 addresses associated with interface. This is not efa-only interface")
}
}
if field == "ipv6s" {
imdsIPv6s, err := cache.imds.GetIPv6s(ctx, eniMAC)
if err != nil {
awsAPIErrInc("GetIPv6s", err)
} else if len(imdsIPv6s) > 0 {
ipv6Available = true
log.Debugf("Found IPv6 addresses associated with interface. This is not efa-only interface")
}
}
if field == "network-card" {
networkCard, err = cache.imds.GetNetworkCard(ctx, eniMAC)
if err != nil {
awsAPIErrInc("GetNetworkCard", err)
log.Errorf("Network Card data not found from %v", networkCard)
return ENIMetadata{}, err
}
}
}
subnetID, err := cache.imds.GetSubnetID(ctx, eniMAC)
if err != nil {
awsAPIErrInc("GetSubnetID", err)
return ENIMetadata{}, err
}
if !ipv4Available && !ipv6Available {
return ENIMetadata{
ENIID: eniID,
MAC: eniMAC,
DeviceNumber: deviceNum,
SubnetIPv4CIDR: "",
IPv4Addresses: make([]ec2types.NetworkInterfacePrivateIpAddress, 0),
IPv4Prefixes: make([]ec2types.Ipv4PrefixSpecification, 0),
SubnetIPv6CIDR: "",
IPv6Addresses: make([]ec2types.NetworkInterfaceIpv6Address, 0),
IPv6Prefixes: make([]ec2types.Ipv6PrefixSpecification, 0),
NetworkCard: networkCard,
SubnetID: subnetID,
}, nil
}
// Get IPv4 and IPv6 addresses assigned to interface
var ec2ip4s []ec2types.NetworkInterfacePrivateIpAddress
var subnetV4Cidr string
if ipv4Available {
cidr, err := cache.imds.GetSubnetIPv4CIDRBlock(ctx, eniMAC)
if err != nil {
awsAPIErrInc("GetSubnetIPv4CIDRBlock", err)
return ENIMetadata{}, err
}
subnetV4Cidr = cidr.String()
imdsIPv4s, err := cache.imds.GetLocalIPv4s(ctx, eniMAC)
if err != nil {
awsAPIErrInc("GetLocalIPv4s", err)
return ENIMetadata{}, err
}
ec2ip4s = make([]ec2types.NetworkInterfacePrivateIpAddress, len(imdsIPv4s))
for i, ip4 := range imdsIPv4s {
ec2ip4s[i] = ec2types.NetworkInterfacePrivateIpAddress{
Primary: aws.Bool(i == 0),
PrivateIpAddress: aws.String(ip4.String()),
}
}
}
var ec2ip6s []ec2types.NetworkInterfaceIpv6Address
var subnetV6Cidr string
if cache.v6Enabled {
// For IPv6 ENIs, we have to return the error if Subnet is not discovered
v6cidr, err := cache.imds.GetSubnetIPv6CIDRBlocks(ctx, eniMAC)
if err != nil {
awsAPIErrInc("GetSubnetIPv6CIDRBlocks", err)
return ENIMetadata{}, err
} else {
// Handle the case where GetSubnetIPv6CIDRBlocks returns empty IPNet for IPv4-only subnets
// IMPORTANT: This scenario includes cross-VPC IPv4 ENIs attached to IPv6 nodes
// where the ENI subnet is IPv4-only but the node is configured for IPv6
if v6cidr != nil && v6cidr.IP != nil && v6cidr.Mask != nil {
subnetV6Cidr = v6cidr.String()
}
}
imdsIPv6s, err := cache.imds.GetIPv6s(ctx, eniMAC)
if err != nil {
awsAPIErrInc("GetIPv6s", err)
} else {
ec2ip6s = make([]ec2types.NetworkInterfaceIpv6Address, len(imdsIPv6s))
for i, ip6 := range imdsIPv6s {
ec2ip6s[i] = ec2types.NetworkInterfaceIpv6Address{
Ipv6Address: aws.String(ip6.String()),
}
}
}
}
var ec2ipv4Prefixes []ec2types.Ipv4PrefixSpecification
var ec2ipv6Prefixes []ec2types.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, ec2types.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, ec2types.Ipv4PrefixSpecification{
Ipv4Prefix: aws.String(ipv4prefix.String()),
})
}
}
return ENIMetadata{
ENIID: eniID,
MAC: eniMAC,
DeviceNumber: deviceNum,
SubnetIPv4CIDR: subnetV4Cidr,
IPv4Addresses: ec2ip4s,
IPv4Prefixes: ec2ipv4Prefixes,
SubnetIPv6CIDR: subnetV6Cidr,