Skip to content

Commit c7dafbc

Browse files
committed
instances: initial implementation of Instances interface
1 parent 35aeabd commit c7dafbc

File tree

6 files changed

+856
-7
lines changed

6 files changed

+856
-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

+284
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,284 @@
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")
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+
if err == cloudprovider.InstanceNotFound {
95+
// We don't have live ec2Instance
96+
return true, nil
97+
}
98+
return false, err
99+
}
100+
101+
if ec2Instance.State != nil {
102+
state := aws.StringValue(ec2Instance.State.Name)
103+
if state == ec2.InstanceStateNameStopping || state == ec2.InstanceStateNameStopped {
104+
return true, nil
105+
}
106+
}
107+
108+
return false, nil
109+
}
110+
111+
// InstanceMetadata returns the instance's metadata.
112+
func (i *instances) InstanceMetadata(ctx context.Context, node *v1.Node) (*cloudprovider.InstanceMetadata, error) {
113+
var err error
114+
var ec2Instance *ec2.Instance
115+
116+
// TODO: support node name policy other than private DNS names
117+
ec2Instance, err = i.getInstance(ctx, node)
118+
if err != nil {
119+
return nil, err
120+
}
121+
122+
nodeAddresses, err := nodeAddressesForInstance(ec2Instance)
123+
if err != nil {
124+
return nil, err
125+
}
126+
127+
providerID, err := getInstanceProviderID(ec2Instance)
128+
if err != nil {
129+
return nil, err
130+
}
131+
132+
metadata := &cloudprovider.InstanceMetadata{
133+
ProviderID: providerID,
134+
InstanceType: aws.StringValue(ec2Instance.InstanceType),
135+
NodeAddresses: nodeAddresses,
136+
}
137+
138+
return metadata, nil
139+
}
140+
141+
// getInstance returns the instance if the instance with the given node info still exists.
142+
// If false an error will be returned, the instance will be immediately deleted by the cloud controller manager.
143+
func (i *instances) getInstance(ctx context.Context, node *v1.Node) (*ec2.Instance, error) {
144+
var request *ec2.DescribeInstancesInput
145+
if node.Spec.ProviderID == "" {
146+
// get Instance by private DNS name
147+
request = &ec2.DescribeInstancesInput{
148+
Filters: []*ec2.Filter{
149+
newEc2Filter("private-dns-name", node.Name),
150+
},
151+
}
152+
klog.V(4).Infof("looking for node by private DNS name %v", node.Name)
153+
} else {
154+
// get Instance by provider ID
155+
instanceID, err := parseInstanceIDFromProviderID(node.Spec.ProviderID)
156+
if err != nil {
157+
return nil, err
158+
}
159+
160+
request = &ec2.DescribeInstancesInput{
161+
InstanceIds: []*string{aws.String(instanceID)},
162+
}
163+
klog.V(4).Infof("looking for node by provider ID %v", node.Spec.ProviderID)
164+
}
165+
166+
instances := []*ec2.Instance{}
167+
var nextToken *string
168+
for {
169+
response, err := i.ec2.DescribeInstances(request)
170+
if err != nil {
171+
return nil, fmt.Errorf("error describing ec2 instances: %v", err)
172+
}
173+
174+
for _, reservation := range response.Reservations {
175+
instances = append(instances, reservation.Instances...)
176+
}
177+
178+
nextToken = response.NextToken
179+
if aws.StringValue(nextToken) == "" {
180+
break
181+
}
182+
request.NextToken = nextToken
183+
}
184+
185+
if len(instances) == 0 {
186+
return nil, cloudprovider.InstanceNotFound
187+
}
188+
189+
if len(instances) > 1 {
190+
return nil, fmt.Errorf("getInstance: multiple instances found")
191+
}
192+
193+
state := instances[0].State.Name
194+
if *state == ec2.InstanceStateNameTerminated {
195+
return nil, fmt.Errorf("the instance %v is terminated", aws.StringValue(instances[0].InstanceId))
196+
}
197+
198+
return instances[0], nil
199+
}
200+
201+
// nodeAddresses for Instance returns a list of v1.NodeAddress for the give instance.
202+
// TODO: should we support ExternalIP by default?
203+
func nodeAddressesForInstance(instance *ec2.Instance) ([]v1.NodeAddress, error) {
204+
if instance == nil {
205+
return nil, errors.New("provided instances is nil")
206+
}
207+
208+
addresses := []v1.NodeAddress{}
209+
for _, networkInterface := range instance.NetworkInterfaces {
210+
// skip network interfaces that are not currently in use
211+
if aws.StringValue(networkInterface.Status) != ec2.NetworkInterfaceStatusInUse {
212+
continue
213+
}
214+
215+
for _, privateIP := range networkInterface.PrivateIpAddresses {
216+
if ipAddress := aws.StringValue(privateIP.PrivateIpAddress); ipAddress != "" {
217+
ip := net.ParseIP(ipAddress)
218+
if ip == nil {
219+
return nil, fmt.Errorf("invalid IP address %q from instance %q", ipAddress, aws.StringValue(instance.InstanceId))
220+
}
221+
222+
addresses = append(addresses, v1.NodeAddress{
223+
Type: v1.NodeInternalIP,
224+
Address: ip.String(),
225+
})
226+
}
227+
}
228+
}
229+
230+
return addresses, nil
231+
}
232+
233+
// getInstanceProviderID returns the provider ID of an instance which is ultimately set in the node.Spec.ProviderID field.
234+
// The well-known format for a node's providerID is:
235+
// * aws:///<availability-zone>/<instance-id>
236+
func getInstanceProviderID(instance *ec2.Instance) (string, error) {
237+
if aws.StringValue(instance.Placement.AvailabilityZone) == "" {
238+
return "", errors.New("instance availability zone was not set")
239+
}
240+
241+
if aws.StringValue(instance.InstanceId) == "" {
242+
return "", errors.New("instance ID was not set")
243+
}
244+
245+
return "aws:///" + aws.StringValue(instance.Placement.AvailabilityZone) + "/" + aws.StringValue(instance.InstanceId), nil
246+
}
247+
248+
// parseInstanceIDFromProviderID parses the node's instance ID based on the following formats:
249+
// * aws://<availability-zone>/<instance-id>
250+
// * aws:///<instance-id>
251+
// * <instance-id>
252+
// This function always assumes a valid providerID format was provided.
253+
func parseInstanceIDFromProviderID(providerID string) (string, error) {
254+
// trim the provider name prefix 'aws://', renaming providerID should contain metadata in one of the following formats:
255+
// * <availability-zone>/<instance-id>
256+
// * /<availability-zone>/<instance-id>
257+
// * <instance-id>
258+
instanceID := ""
259+
metadata := strings.Split(strings.TrimPrefix(providerID, "aws://"), "/")
260+
if len(metadata) == 1 {
261+
// instance-id
262+
instanceID = metadata[0]
263+
} else if len(metadata) == 2 {
264+
// az/instance-id
265+
instanceID = metadata[1]
266+
} else if len(metadata) == 3 {
267+
// /az/instance-id
268+
instanceID = metadata[2]
269+
}
270+
271+
return instanceID, nil
272+
}
273+
274+
func newEc2Filter(name string, values ...string) *ec2.Filter {
275+
filter := &ec2.Filter{
276+
Name: aws.String(name),
277+
}
278+
279+
for _, value := range values {
280+
filter.Values = append(filter.Values, aws.String(value))
281+
}
282+
283+
return filter
284+
}

0 commit comments

Comments
 (0)