Skip to content

Commit 805fde8

Browse files
authored
Merge pull request #131 from nicolehanjing/nicoleh-instances-v2
instances: initial implementation of instancesV2 interface
2 parents 35aeabd + c71bade commit 805fde8

File tree

6 files changed

+857
-7
lines changed

6 files changed

+857
-7
lines changed

Diff for: go.mod

+6
Original file line numberDiff line numberDiff line change
@@ -28,14 +28,20 @@ replace (
2828

2929
require (
3030
github.com/aws/aws-sdk-go v1.28.2
31+
github.com/golang/mock v1.3.1
32+
github.com/google/go-cmp v0.4.0
33+
github.com/google/uuid v1.1.1
3134
github.com/spf13/cobra v1.0.0
3235
github.com/spf13/pflag v1.0.5
3336
github.com/stretchr/testify v1.4.0
37+
gopkg.in/gcfg.v1 v1.2.0
38+
k8s.io/api v0.0.0
3439
k8s.io/apimachinery v0.0.0
3540
k8s.io/apiserver v0.0.0
3641
k8s.io/cloud-provider v0.0.0
3742
k8s.io/component-base v0.0.0
3843
k8s.io/klog v1.0.0
44+
k8s.io/klog/v2 v2.2.0
3945
k8s.io/kubernetes v1.19.1
4046
k8s.io/legacy-cloud-providers v0.0.0
4147
k8s.io/utils v0.0.0-20200729134348-d5654de09c73

Diff for: go.sum

+3
Original file line numberDiff line numberDiff line change
@@ -262,7 +262,9 @@ github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7 h1:5ZkaAPbicIKTF
262262
github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
263263
github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
264264
github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
265+
github.com/golang/mock v1.3.1 h1:qGJ6qTW+x6xX/my+8YUVl4WNpX9B7+/l2tRsHGZ7f2s=
265266
github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y=
267+
github.com/golang/mock v1.4.4 h1:l75CXGRSwbaYNpl/Z2X1XIIAMSCquvXgpVZDhwEIJsc=
266268
github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM=
267269
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
268270
github.com/golang/protobuf v1.3.1 h1:YF8+flBXS5eO826T4nzqPrxfhQThhXl0YzfuUPu4SBg=
@@ -887,6 +889,7 @@ k8s.io/kube-openapi v0.0.0-20200805222855-6aeccd4b50c6 h1:+WnxoVtG8TMiudHBSEtrVL
887889
k8s.io/kube-openapi v0.0.0-20200805222855-6aeccd4b50c6/go.mod h1:UuqjUnNftUyPE5H64/qeyjQoUZhGpeFDVdxjTeEVN2o=
888890
k8s.io/kubernetes v1.19.1 h1:3Gdl9EtBiV3SYuzml1915nFLVxlx08L6bRz1b07C60k=
889891
k8s.io/kubernetes v1.19.1/go.mod h1:yhT1/ltQajQsha3tnYc9QPFYSumGM45nlZdjf7WqE1A=
892+
k8s.io/kubernetes v1.19.2 h1:sEvBYVM1/H5hqejFR10u8ndreYARV3DiTrqi2AY31ok=
890893
k8s.io/kubernetes/staging/src/k8s.io/api v0.0.0-20200909111720-206bcadf021e h1:mdkfNp9Iu1erEZy/9kefsctTTyey3aAMcCQ5VTzScIE=
891894
k8s.io/kubernetes/staging/src/k8s.io/api v0.0.0-20200909111720-206bcadf021e/go.mod h1:Y4VjjNur38HL6/QxaTVK2yno1zjEQlvcvwbbRQs2DtQ=
892895
k8s.io/kubernetes/staging/src/k8s.io/apiextensions-apiserver v0.0.0-20200909111720-206bcadf021e/go.mod h1:BvtZU215FgO19Oy19K6h8qwajFfjxYqGewgjuYHWGRw=

Diff for: pkg/providers/v2/cloud.go

+35-7
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,8 @@ import (
2828
"github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds"
2929
"github.com/aws/aws-sdk-go/aws/ec2metadata"
3030
"github.com/aws/aws-sdk-go/aws/session"
31+
"github.com/aws/aws-sdk-go/service/ec2"
32+
3133
cloudprovider "k8s.io/cloud-provider"
3234
)
3335

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

4749
// cloud is the AWS v2 implementation of the cloud provider interface
4850
type cloud struct {
49-
creds *credentials.Credentials
50-
region string
51+
creds *credentials.Credentials
52+
instances cloudprovider.InstancesV2
53+
region string
54+
ec2 EC2
55+
metadata EC2Metadata
5156
}
5257

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

110-
return &cloud{
111-
creds: creds,
112-
region: region,
113-
}, nil
115+
instances, err := newInstances(az, creds)
116+
if err != nil {
117+
return nil, err
118+
}
119+
120+
ec2Sess, err := session.NewSession(&aws.Config{
121+
Region: aws.String(region),
122+
Credentials: creds,
123+
})
124+
if err != nil {
125+
return nil, fmt.Errorf("unable to initialize AWS session: %v", err)
126+
}
127+
128+
ec2Service := ec2.New(ec2Sess)
129+
if err != nil {
130+
return nil, fmt.Errorf("error creating AWS ec2 client: %q", err)
131+
}
132+
133+
awsCloud := &cloud{
134+
creds: creds,
135+
instances: instances,
136+
region: region,
137+
metadata: metadataClient,
138+
ec2: ec2Service,
139+
}
140+
141+
return awsCloud, nil
114142
}
115143

116144
// Initialize passes a Kubernetes clientBuilder interface to the cloud provider
@@ -158,5 +186,5 @@ func (c *cloud) HasClusterID() bool {
158186
// Also returns true if the interface is supported, false otherwise.
159187
// WARNING: InstancesV2 is an experimental interface and is subject to change in v1.20.
160188
func (c *cloud) InstancesV2() (cloudprovider.InstancesV2, bool) {
161-
return nil, false
189+
return c.instances, true
162190
}

Diff for: pkg/providers/v2/instances.go

+281
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,281 @@
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, errors.New("getInstance: multiple instances found")
188+
}
189+
190+
state := instances[0].State.Name
191+
if *state == ec2.InstanceStateNameTerminated {
192+
return nil, cloudprovider.InstanceNotFound
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

Comments
 (0)