|
| 1 | +/* |
| 2 | +Copyright 2020 The Kubernetes Authors. |
| 3 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +you may not use this file except in compliance with the License. |
| 5 | +You may obtain a copy of the License at |
| 6 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 7 | +Unless required by applicable law or agreed to in writing, software |
| 8 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 9 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 10 | +See the License for the specific language governing permissions and |
| 11 | +limitations under the License. |
| 12 | +*/ |
| 13 | + |
| 14 | +// Package v2 is an out-of-tree only implementation of the AWS cloud provider. |
| 15 | +// It is not compatible with v1 and should only be used on new clusters. |
| 16 | +package v2 |
| 17 | + |
| 18 | +import ( |
| 19 | + "context" |
| 20 | + "errors" |
| 21 | + "fmt" |
| 22 | + "net" |
| 23 | + "strings" |
| 24 | + |
| 25 | + "k8s.io/klog/v2" |
| 26 | + |
| 27 | + "github.com/aws/aws-sdk-go/aws" |
| 28 | + "github.com/aws/aws-sdk-go/aws/credentials" |
| 29 | + "github.com/aws/aws-sdk-go/aws/session" |
| 30 | + "github.com/aws/aws-sdk-go/service/ec2" |
| 31 | + |
| 32 | + v1 "k8s.io/api/core/v1" |
| 33 | + cloudprovider "k8s.io/cloud-provider" |
| 34 | +) |
| 35 | + |
| 36 | +// newInstances returns an implementation of cloudprovider.InstancesV2 |
| 37 | +func newInstances(az string, creds *credentials.Credentials) (cloudprovider.InstancesV2, error) { |
| 38 | + region, err := azToRegion(az) |
| 39 | + if err != nil { |
| 40 | + return nil, err |
| 41 | + } |
| 42 | + |
| 43 | + awsConfig := &aws.Config{ |
| 44 | + Region: aws.String(region), |
| 45 | + Credentials: creds, |
| 46 | + } |
| 47 | + awsConfig = awsConfig.WithCredentialsChainVerboseErrors(true) |
| 48 | + |
| 49 | + sess, err := session.NewSession(awsConfig) |
| 50 | + if err != nil { |
| 51 | + return nil, fmt.Errorf("error creating new session: %v", err) |
| 52 | + } |
| 53 | + ec2Service := ec2.New(sess) |
| 54 | + |
| 55 | + return &instances{ |
| 56 | + availabilityZone: az, |
| 57 | + ec2: ec2Service, |
| 58 | + region: region, |
| 59 | + }, nil |
| 60 | +} |
| 61 | + |
| 62 | +// EC2 is an interface defining only the methods we call from the AWS EC2 SDK. |
| 63 | +type EC2 interface { |
| 64 | + DescribeInstances(request *ec2.DescribeInstancesInput) (*ec2.DescribeInstancesOutput, error) |
| 65 | +} |
| 66 | + |
| 67 | +// instances is an implementation of cloudprovider.InstancesV2 |
| 68 | +type instances struct { |
| 69 | + availabilityZone string |
| 70 | + ec2 EC2 |
| 71 | + region string |
| 72 | +} |
| 73 | + |
| 74 | +// InstanceExists indicates whether a given node exists according to the cloud provider |
| 75 | +func (i *instances) InstanceExists(ctx context.Context, node *v1.Node) (bool, error) { |
| 76 | + _, err := i.getInstance(ctx, node) |
| 77 | + |
| 78 | + if err == cloudprovider.InstanceNotFound { |
| 79 | + klog.V(6).Infof("instance not found for node: %s", node.Name) |
| 80 | + return false, nil |
| 81 | + } |
| 82 | + |
| 83 | + if err != nil { |
| 84 | + return false, err |
| 85 | + } |
| 86 | + |
| 87 | + return true, nil |
| 88 | +} |
| 89 | + |
| 90 | +// InstanceShutdown returns true if the instance is shutdown according to the cloud provider. |
| 91 | +func (i *instances) InstanceShutdown(ctx context.Context, node *v1.Node) (bool, error) { |
| 92 | + ec2Instance, err := i.getInstance(ctx, node) |
| 93 | + if err != nil { |
| 94 | + return false, err |
| 95 | + } |
| 96 | + |
| 97 | + if ec2Instance.State != nil { |
| 98 | + state := aws.StringValue(ec2Instance.State.Name) |
| 99 | + // valid state for detaching volumes |
| 100 | + if state == ec2.InstanceStateNameStopped { |
| 101 | + return true, nil |
| 102 | + } |
| 103 | + } |
| 104 | + |
| 105 | + return false, nil |
| 106 | +} |
| 107 | + |
| 108 | +// InstanceMetadata returns the instance's metadata. |
| 109 | +func (i *instances) InstanceMetadata(ctx context.Context, node *v1.Node) (*cloudprovider.InstanceMetadata, error) { |
| 110 | + var err error |
| 111 | + var ec2Instance *ec2.Instance |
| 112 | + |
| 113 | + // TODO: support node name policy other than private DNS names |
| 114 | + ec2Instance, err = i.getInstance(ctx, node) |
| 115 | + if err != nil { |
| 116 | + return nil, err |
| 117 | + } |
| 118 | + |
| 119 | + nodeAddresses, err := nodeAddressesForInstance(ec2Instance) |
| 120 | + if err != nil { |
| 121 | + return nil, err |
| 122 | + } |
| 123 | + |
| 124 | + providerID, err := getInstanceProviderID(ec2Instance) |
| 125 | + if err != nil { |
| 126 | + return nil, err |
| 127 | + } |
| 128 | + |
| 129 | + metadata := &cloudprovider.InstanceMetadata{ |
| 130 | + ProviderID: providerID, |
| 131 | + InstanceType: aws.StringValue(ec2Instance.InstanceType), |
| 132 | + NodeAddresses: nodeAddresses, |
| 133 | + } |
| 134 | + |
| 135 | + return metadata, nil |
| 136 | +} |
| 137 | + |
| 138 | +// getInstance returns the instance if the instance with the given node info still exists. |
| 139 | +// If false an error will be returned, the instance will be immediately deleted by the cloud controller manager. |
| 140 | +func (i *instances) getInstance(ctx context.Context, node *v1.Node) (*ec2.Instance, error) { |
| 141 | + var request *ec2.DescribeInstancesInput |
| 142 | + if node.Spec.ProviderID == "" { |
| 143 | + // get Instance by private DNS name |
| 144 | + request = &ec2.DescribeInstancesInput{ |
| 145 | + Filters: []*ec2.Filter{ |
| 146 | + newEc2Filter("private-dns-name", node.Name), |
| 147 | + }, |
| 148 | + } |
| 149 | + klog.V(4).Infof("looking for node by private DNS name %v", node.Name) |
| 150 | + } else { |
| 151 | + // get Instance by provider ID |
| 152 | + instanceID, err := parseInstanceIDFromProviderID(node.Spec.ProviderID) |
| 153 | + if err != nil { |
| 154 | + return nil, err |
| 155 | + } |
| 156 | + |
| 157 | + request = &ec2.DescribeInstancesInput{ |
| 158 | + InstanceIds: []*string{aws.String(instanceID)}, |
| 159 | + } |
| 160 | + klog.V(4).Infof("looking for node by provider ID %v", node.Spec.ProviderID) |
| 161 | + } |
| 162 | + |
| 163 | + instances := []*ec2.Instance{} |
| 164 | + var nextToken *string |
| 165 | + for { |
| 166 | + response, err := i.ec2.DescribeInstances(request) |
| 167 | + if err != nil { |
| 168 | + return nil, fmt.Errorf("error describing ec2 instances: %v", err) |
| 169 | + } |
| 170 | + |
| 171 | + for _, reservation := range response.Reservations { |
| 172 | + instances = append(instances, reservation.Instances...) |
| 173 | + } |
| 174 | + |
| 175 | + nextToken = response.NextToken |
| 176 | + if aws.StringValue(nextToken) == "" { |
| 177 | + break |
| 178 | + } |
| 179 | + request.NextToken = nextToken |
| 180 | + } |
| 181 | + |
| 182 | + if len(instances) == 0 { |
| 183 | + return nil, cloudprovider.InstanceNotFound |
| 184 | + } |
| 185 | + |
| 186 | + if len(instances) > 1 { |
| 187 | + return nil, fmt.Errorf("getInstance: multiple instances found") |
| 188 | + } |
| 189 | + |
| 190 | + state := instances[0].State.Name |
| 191 | + if *state == ec2.InstanceStateNameTerminated { |
| 192 | + return nil, fmt.Errorf("instance %v is terminated", instances[0].InstanceId) |
| 193 | + } |
| 194 | + |
| 195 | + return instances[0], nil |
| 196 | +} |
| 197 | + |
| 198 | +// nodeAddresses for Instance returns a list of v1.NodeAddress for the give instance. |
| 199 | +// TODO: should we support ExternalIP by default? |
| 200 | +func nodeAddressesForInstance(instance *ec2.Instance) ([]v1.NodeAddress, error) { |
| 201 | + if instance == nil { |
| 202 | + return nil, errors.New("provided instances is nil") |
| 203 | + } |
| 204 | + |
| 205 | + addresses := []v1.NodeAddress{} |
| 206 | + for _, networkInterface := range instance.NetworkInterfaces { |
| 207 | + // skip network interfaces that are not currently in use |
| 208 | + if aws.StringValue(networkInterface.Status) != ec2.NetworkInterfaceStatusInUse { |
| 209 | + continue |
| 210 | + } |
| 211 | + |
| 212 | + for _, privateIP := range networkInterface.PrivateIpAddresses { |
| 213 | + if ipAddress := aws.StringValue(privateIP.PrivateIpAddress); ipAddress != "" { |
| 214 | + ip := net.ParseIP(ipAddress) |
| 215 | + if ip == nil { |
| 216 | + return nil, fmt.Errorf("invalid IP address %q from instance %q", ipAddress, aws.StringValue(instance.InstanceId)) |
| 217 | + } |
| 218 | + |
| 219 | + addresses = append(addresses, v1.NodeAddress{ |
| 220 | + Type: v1.NodeInternalIP, |
| 221 | + Address: ip.String(), |
| 222 | + }) |
| 223 | + } |
| 224 | + } |
| 225 | + } |
| 226 | + |
| 227 | + return addresses, nil |
| 228 | +} |
| 229 | + |
| 230 | +// getInstanceProviderID returns the provider ID of an instance which is ultimately set in the node.Spec.ProviderID field. |
| 231 | +// The well-known format for a node's providerID is: |
| 232 | +// * aws:///<availability-zone>/<instance-id> |
| 233 | +func getInstanceProviderID(instance *ec2.Instance) (string, error) { |
| 234 | + if aws.StringValue(instance.Placement.AvailabilityZone) == "" { |
| 235 | + return "", errors.New("instance availability zone was not set") |
| 236 | + } |
| 237 | + |
| 238 | + if aws.StringValue(instance.InstanceId) == "" { |
| 239 | + return "", errors.New("instance ID was not set") |
| 240 | + } |
| 241 | + |
| 242 | + return "aws:///" + aws.StringValue(instance.Placement.AvailabilityZone) + "/" + aws.StringValue(instance.InstanceId), nil |
| 243 | +} |
| 244 | + |
| 245 | +// parseInstanceIDFromProviderID parses the node's instance ID based on the following formats: |
| 246 | +// * aws://<availability-zone>/<instance-id> |
| 247 | +// * aws:///<instance-id> |
| 248 | +// * <instance-id> |
| 249 | +// This function always assumes a valid providerID format was provided. |
| 250 | +func parseInstanceIDFromProviderID(providerID string) (string, error) { |
| 251 | + // trim the provider name prefix 'aws://', renaming providerID should contain metadata in one of the following formats: |
| 252 | + // * <availability-zone>/<instance-id> |
| 253 | + // * /<availability-zone>/<instance-id> |
| 254 | + // * <instance-id> |
| 255 | + instanceID := "" |
| 256 | + metadata := strings.Split(strings.TrimPrefix(providerID, "aws://"), "/") |
| 257 | + if len(metadata) == 1 { |
| 258 | + // instance-id |
| 259 | + instanceID = metadata[0] |
| 260 | + } else if len(metadata) == 2 { |
| 261 | + // az/instance-id |
| 262 | + instanceID = metadata[1] |
| 263 | + } else if len(metadata) == 3 { |
| 264 | + // /az/instance-id |
| 265 | + instanceID = metadata[2] |
| 266 | + } |
| 267 | + |
| 268 | + return instanceID, nil |
| 269 | +} |
| 270 | + |
| 271 | +func newEc2Filter(name string, values ...string) *ec2.Filter { |
| 272 | + filter := &ec2.Filter{ |
| 273 | + Name: aws.String(name), |
| 274 | + } |
| 275 | + |
| 276 | + for _, value := range values { |
| 277 | + filter.Values = append(filter.Values, aws.String(value)) |
| 278 | + } |
| 279 | + |
| 280 | + return filter |
| 281 | +} |
0 commit comments