Skip to content

instances: initial implementation of instancesV2 interface #131

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 21, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,20 @@ replace (

require (
github.com/aws/aws-sdk-go v1.28.2
github.com/golang/mock v1.3.1
github.com/google/go-cmp v0.4.0
github.com/google/uuid v1.1.1
github.com/spf13/cobra v1.0.0
github.com/spf13/pflag v1.0.5
github.com/stretchr/testify v1.4.0
gopkg.in/gcfg.v1 v1.2.0
k8s.io/api v0.0.0
k8s.io/apimachinery v0.0.0
k8s.io/apiserver v0.0.0
k8s.io/cloud-provider v0.0.0
k8s.io/component-base v0.0.0
k8s.io/klog v1.0.0
k8s.io/klog/v2 v2.2.0
k8s.io/kubernetes v1.19.1
k8s.io/legacy-cloud-providers v0.0.0
k8s.io/utils v0.0.0-20200729134348-d5654de09c73
Expand Down
3 changes: 3 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,9 @@ github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7 h1:5ZkaAPbicIKTF
github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
github.com/golang/mock v1.3.1 h1:qGJ6qTW+x6xX/my+8YUVl4WNpX9B7+/l2tRsHGZ7f2s=
github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y=
github.com/golang/mock v1.4.4 h1:l75CXGRSwbaYNpl/Z2X1XIIAMSCquvXgpVZDhwEIJsc=
github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.1 h1:YF8+flBXS5eO826T4nzqPrxfhQThhXl0YzfuUPu4SBg=
Expand Down Expand Up @@ -887,6 +889,7 @@ k8s.io/kube-openapi v0.0.0-20200805222855-6aeccd4b50c6 h1:+WnxoVtG8TMiudHBSEtrVL
k8s.io/kube-openapi v0.0.0-20200805222855-6aeccd4b50c6/go.mod h1:UuqjUnNftUyPE5H64/qeyjQoUZhGpeFDVdxjTeEVN2o=
k8s.io/kubernetes v1.19.1 h1:3Gdl9EtBiV3SYuzml1915nFLVxlx08L6bRz1b07C60k=
k8s.io/kubernetes v1.19.1/go.mod h1:yhT1/ltQajQsha3tnYc9QPFYSumGM45nlZdjf7WqE1A=
k8s.io/kubernetes v1.19.2 h1:sEvBYVM1/H5hqejFR10u8ndreYARV3DiTrqi2AY31ok=
k8s.io/kubernetes/staging/src/k8s.io/api v0.0.0-20200909111720-206bcadf021e h1:mdkfNp9Iu1erEZy/9kefsctTTyey3aAMcCQ5VTzScIE=
k8s.io/kubernetes/staging/src/k8s.io/api v0.0.0-20200909111720-206bcadf021e/go.mod h1:Y4VjjNur38HL6/QxaTVK2yno1zjEQlvcvwbbRQs2DtQ=
k8s.io/kubernetes/staging/src/k8s.io/apiextensions-apiserver v0.0.0-20200909111720-206bcadf021e/go.mod h1:BvtZU215FgO19Oy19K6h8qwajFfjxYqGewgjuYHWGRw=
Expand Down
42 changes: 35 additions & 7 deletions pkg/providers/v2/cloud.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ import (
"github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds"
"github.com/aws/aws-sdk-go/aws/ec2metadata"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"

cloudprovider "k8s.io/cloud-provider"
)

Expand All @@ -46,8 +48,11 @@ var _ cloudprovider.Interface = (*cloud)(nil)

// cloud is the AWS v2 implementation of the cloud provider interface
type cloud struct {
creds *credentials.Credentials
region string
creds *credentials.Credentials
instances cloudprovider.InstancesV2
region string
ec2 EC2
metadata EC2Metadata
}

// EC2Metadata is an abstraction over the AWS metadata service.
Expand Down Expand Up @@ -107,10 +112,33 @@ func newCloud() (cloudprovider.Interface, error) {
return nil, err
}

return &cloud{
creds: creds,
region: region,
}, nil
instances, err := newInstances(az, creds)
if err != nil {
return nil, err
}

ec2Sess, err := session.NewSession(&aws.Config{
Region: aws.String(region),
Credentials: creds,
})
if err != nil {
return nil, fmt.Errorf("unable to initialize AWS session: %v", err)
}

ec2Service := ec2.New(ec2Sess)
if err != nil {
return nil, fmt.Errorf("error creating AWS ec2 client: %q", err)
}

awsCloud := &cloud{
creds: creds,
instances: instances,
region: region,
metadata: metadataClient,
ec2: ec2Service,
}

return awsCloud, nil
}

// Initialize passes a Kubernetes clientBuilder interface to the cloud provider
Expand Down Expand Up @@ -158,5 +186,5 @@ func (c *cloud) HasClusterID() bool {
// Also returns true if the interface is supported, false otherwise.
// WARNING: InstancesV2 is an experimental interface and is subject to change in v1.20.
func (c *cloud) InstancesV2() (cloudprovider.InstancesV2, bool) {
return nil, false
return c.instances, true
}
281 changes: 281 additions & 0 deletions pkg/providers/v2/instances.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,281 @@
/*
Copyright 2020 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

// Package v2 is an out-of-tree only implementation of the AWS cloud provider.
// It is not compatible with v1 and should only be used on new clusters.
package v2

import (
"context"
"errors"
"fmt"
"net"
"strings"

"k8s.io/klog/v2"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"

v1 "k8s.io/api/core/v1"
cloudprovider "k8s.io/cloud-provider"
)

// newInstances returns an implementation of cloudprovider.InstancesV2
func newInstances(az string, creds *credentials.Credentials) (cloudprovider.InstancesV2, error) {
region, err := azToRegion(az)
if err != nil {
return nil, err
}

awsConfig := &aws.Config{
Region: aws.String(region),
Credentials: creds,
}
awsConfig = awsConfig.WithCredentialsChainVerboseErrors(true)

sess, err := session.NewSession(awsConfig)
if err != nil {
return nil, fmt.Errorf("error creating new session: %v", err)
}
ec2Service := ec2.New(sess)

return &instances{
availabilityZone: az,
ec2: ec2Service,
region: region,
}, nil
}

// EC2 is an interface defining only the methods we call from the AWS EC2 SDK.
type EC2 interface {
DescribeInstances(request *ec2.DescribeInstancesInput) (*ec2.DescribeInstancesOutput, error)
}

// instances is an implementation of cloudprovider.InstancesV2
type instances struct {
availabilityZone string
ec2 EC2
region string
}

// InstanceExists indicates whether a given node exists according to the cloud provider
func (i *instances) InstanceExists(ctx context.Context, node *v1.Node) (bool, error) {
_, err := i.getInstance(ctx, node)

if err == cloudprovider.InstanceNotFound {
klog.V(6).Infof("instance not found for node: %s", node.Name)
return false, nil
}

if err != nil {
return false, err
}

return true, nil
}

// InstanceShutdown returns true if the instance is shutdown according to the cloud provider.
func (i *instances) InstanceShutdown(ctx context.Context, node *v1.Node) (bool, error) {
ec2Instance, err := i.getInstance(ctx, node)
if err != nil {
return false, err
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@andrewsykim Updated the shutdown checks, PTAL!
Let me know if you have any other suggestions :)

}

if ec2Instance.State != nil {
state := aws.StringValue(ec2Instance.State.Name)
// valid state for detaching volumes
if state == ec2.InstanceStateNameStopped {
return true, nil
}
}

return false, nil
}

// InstanceMetadata returns the instance's metadata.
func (i *instances) InstanceMetadata(ctx context.Context, node *v1.Node) (*cloudprovider.InstanceMetadata, error) {
var err error
var ec2Instance *ec2.Instance

// TODO: support node name policy other than private DNS names
ec2Instance, err = i.getInstance(ctx, node)
if err != nil {
return nil, err
}

nodeAddresses, err := nodeAddressesForInstance(ec2Instance)
if err != nil {
return nil, err
}

providerID, err := getInstanceProviderID(ec2Instance)
if err != nil {
return nil, err
}

metadata := &cloudprovider.InstanceMetadata{
ProviderID: providerID,
InstanceType: aws.StringValue(ec2Instance.InstanceType),
NodeAddresses: nodeAddresses,
}

return metadata, nil
}

// getInstance returns the instance if the instance with the given node info still exists.
// If false an error will be returned, the instance will be immediately deleted by the cloud controller manager.
func (i *instances) getInstance(ctx context.Context, node *v1.Node) (*ec2.Instance, error) {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@nckturner Updated!

  • added the logs
  • unified two functions getInstanceByProviderID and getInstanceByPrivateDNSName into getInstance and the only difference is the ec2 request input
  • likely unified two functions InstanceShutdownByProviderID and InstanceShutdownByPrivateDNSName into InstanceShutdown
    PTAL! :)

var request *ec2.DescribeInstancesInput
if node.Spec.ProviderID == "" {
// get Instance by private DNS name
request = &ec2.DescribeInstancesInput{
Filters: []*ec2.Filter{
newEc2Filter("private-dns-name", node.Name),
},
}
klog.V(4).Infof("looking for node by private DNS name %v", node.Name)
} else {
// get Instance by provider ID
instanceID, err := parseInstanceIDFromProviderID(node.Spec.ProviderID)
if err != nil {
return nil, err
}

request = &ec2.DescribeInstancesInput{
InstanceIds: []*string{aws.String(instanceID)},
}
klog.V(4).Infof("looking for node by provider ID %v", node.Spec.ProviderID)
}

instances := []*ec2.Instance{}
var nextToken *string
for {
response, err := i.ec2.DescribeInstances(request)
if err != nil {
return nil, fmt.Errorf("error describing ec2 instances: %v", err)
}

for _, reservation := range response.Reservations {
instances = append(instances, reservation.Instances...)
}

nextToken = response.NextToken
if aws.StringValue(nextToken) == "" {
break
}
request.NextToken = nextToken
}

if len(instances) == 0 {
return nil, cloudprovider.InstanceNotFound
}

if len(instances) > 1 {
return nil, errors.New("getInstance: multiple instances found")
}

state := instances[0].State.Name
if *state == ec2.InstanceStateNameTerminated {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If DescribeInstances returns only 1 instance and that instance has state InstanceStateNameTerminated, then I think we should treat it similar to the case of len(instances) == 0 and here return nil, cloudprovider.InstanceNotFound.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

gotcha, updated!
I was thinking to have a different log for terminated instances, but as "terminated" is just an intermediate state I agree that we should treat it the same as 'not exist'

return nil, cloudprovider.InstanceNotFound
}

return instances[0], nil
}

// nodeAddresses for Instance returns a list of v1.NodeAddress for the give instance.
// TODO: should we support ExternalIP by default?
func nodeAddressesForInstance(instance *ec2.Instance) ([]v1.NodeAddress, error) {
if instance == nil {
return nil, errors.New("provided instances is nil")
}

addresses := []v1.NodeAddress{}
for _, networkInterface := range instance.NetworkInterfaces {
// skip network interfaces that are not currently in use
if aws.StringValue(networkInterface.Status) != ec2.NetworkInterfaceStatusInUse {
continue
}

for _, privateIP := range networkInterface.PrivateIpAddresses {
if ipAddress := aws.StringValue(privateIP.PrivateIpAddress); ipAddress != "" {
ip := net.ParseIP(ipAddress)
if ip == nil {
return nil, fmt.Errorf("invalid IP address %q from instance %q", ipAddress, aws.StringValue(instance.InstanceId))
}

addresses = append(addresses, v1.NodeAddress{
Type: v1.NodeInternalIP,
Address: ip.String(),
})
}
}
}

return addresses, nil
}

// getInstanceProviderID returns the provider ID of an instance which is ultimately set in the node.Spec.ProviderID field.
// The well-known format for a node's providerID is:
// * aws:///<availability-zone>/<instance-id>
Copy link
Member Author

@nicolehanjing nicolehanjing Oct 8, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@andrewsykim I checked the master node's providerID and it's of this form:
aws:///<availability-zone>/<instance-id>
instead of aws://<availability-zone>/<instance-id>
I'm wondering if I need to handle both cases or only the one with three "/"s

func getInstanceProviderID(instance *ec2.Instance) (string, error) {
if aws.StringValue(instance.Placement.AvailabilityZone) == "" {
return "", errors.New("instance availability zone was not set")
}

if aws.StringValue(instance.InstanceId) == "" {
return "", errors.New("instance ID was not set")
}

return "aws:///" + aws.StringValue(instance.Placement.AvailabilityZone) + "/" + aws.StringValue(instance.InstanceId), nil
}

// parseInstanceIDFromProviderID parses the node's instance ID based on the following formats:
// * aws://<availability-zone>/<instance-id>
// * aws:///<instance-id>
// * <instance-id>
// This function always assumes a valid providerID format was provided.
func parseInstanceIDFromProviderID(providerID string) (string, error) {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@andrewsykim is that intended to only parse well-formatted providerID? Should I take care of invalid cases?

// trim the provider name prefix 'aws://', renaming providerID should contain metadata in one of the following formats:
// * <availability-zone>/<instance-id>
// * /<availability-zone>/<instance-id>
// * <instance-id>
instanceID := ""
metadata := strings.Split(strings.TrimPrefix(providerID, "aws://"), "/")
if len(metadata) == 1 {
// instance-id
instanceID = metadata[0]
} else if len(metadata) == 2 {
// az/instance-id
instanceID = metadata[1]
} else if len(metadata) == 3 {
// /az/instance-id
instanceID = metadata[2]
}

return instanceID, nil
}

func newEc2Filter(name string, values ...string) *ec2.Filter {
filter := &ec2.Filter{
Name: aws.String(name),
}

for _, value := range values {
filter.Values = append(filter.Values, aws.String(value))
}

return filter
}
Loading