Skip to content

Commit f82b19d

Browse files
committed
instances: initial implementation
1 parent 211d51d commit f82b19d

File tree

4 files changed

+524
-4
lines changed

4 files changed

+524
-4
lines changed

Diff for: go.mod

+2
Original file line numberDiff line numberDiff line change
@@ -28,9 +28,11 @@ replace (
2828

2929
require (
3030
github.com/aws/aws-sdk-go v1.28.2
31+
github.com/google/uuid v1.1.1
3132
github.com/spf13/cobra v1.0.0
3233
github.com/spf13/pflag v1.0.5
3334
github.com/stretchr/testify v1.4.0
35+
k8s.io/api v0.0.0
3436
k8s.io/apimachinery v0.0.0
3537
k8s.io/apiserver v0.0.0
3638
k8s.io/cloud-provider v0.0.0

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

+11-4
Original file line numberDiff line numberDiff line change
@@ -46,8 +46,9 @@ var _ cloudprovider.Interface = (*cloud)(nil)
4646

4747
// cloud is the AWS v2 implementation of the cloud provider interface
4848
type cloud struct {
49-
creds *credentials.Credentials
50-
region string
49+
creds *credentials.Credentials
50+
instances cloudprovider.InstancesV2
51+
region string
5152
}
5253

5354
// EC2Metadata is an abstraction over the AWS metadata service.
@@ -107,9 +108,15 @@ func newCloud() (cloudprovider.Interface, error) {
107108
return nil, err
108109
}
109110

111+
instances, err := newInstances(region, creds)
112+
if err != nil {
113+
return nil, err
114+
}
115+
110116
return &cloud{
111-
creds: creds,
112-
region: region,
117+
creds: creds,
118+
instances: instances,
119+
region: region,
113120
}, nil
114121
}
115122

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

+334
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,334 @@
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+
"github.com/aws/aws-sdk-go/aws"
26+
"github.com/aws/aws-sdk-go/aws/credentials"
27+
"github.com/aws/aws-sdk-go/aws/session"
28+
"github.com/aws/aws-sdk-go/service/ec2"
29+
30+
v1 "k8s.io/api/core/v1"
31+
cloudprovider "k8s.io/cloud-provider"
32+
"k8s.io/klog"
33+
)
34+
35+
// newInstances returns an implementation of cloudprovider.InstancesV2
36+
func newInstances(region string, creds *credentials.Credentials) (cloudprovider.InstancesV2, error) {
37+
awsConfig := &aws.Config{
38+
Region: aws.String(region),
39+
Credentials: creds,
40+
}
41+
awsConfig = awsConfig.WithCredentialsChainVerboseErrors(true)
42+
43+
sess, err := session.NewSession(awsConfig)
44+
if err != nil {
45+
return nil, err
46+
}
47+
ec2Service := ec2.New(sess)
48+
49+
return &instances{
50+
ec2: ec2Service,
51+
}, nil
52+
}
53+
54+
// EC2 is an interface defining only the methods we call from the AWS EC2 SDK.
55+
type EC2 interface {
56+
DescribeInstances(request *ec2.DescribeInstancesInput) (*ec2.DescribeInstancesOutput, error)
57+
}
58+
59+
// instances is an implementation of cloudprovider.InstancesV2
60+
type instances struct {
61+
ec2 EC2
62+
}
63+
64+
// InstanceExists indicates whether a given node exists according to the cloud provider
65+
func (i *instances) InstanceExists(ctx context.Context, node *v1.Node) (bool, error) {
66+
var err error
67+
if node.Spec.ProviderID == "" {
68+
_, err = i.getInstanceByPrivateDNSName(ctx, node.Name)
69+
if err == cloudprovider.InstanceNotFound {
70+
return false, nil
71+
}
72+
73+
if err != nil {
74+
return false, err
75+
}
76+
} else {
77+
_, err = i.getInstanceByProviderID(ctx, node.Spec.ProviderID)
78+
if err == cloudprovider.InstanceNotFound {
79+
return false, nil
80+
}
81+
82+
if err != nil {
83+
return false, err
84+
}
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+
var err error
93+
var ret bool
94+
if node.Spec.ProviderID == "" {
95+
ret, err = i.instanceShutdownByPrivateDNSName(ctx, node.Name)
96+
} else {
97+
ret, err = i.instanceShutdownByProviderID(ctx, node.Spec.ProviderID)
98+
}
99+
100+
return ret, err
101+
}
102+
103+
func (i *instances) InstanceMetadata(ctx context.Context, node *v1.Node) (*cloudprovider.InstanceMetadata, error) {
104+
var err error
105+
var ec2Instance *ec2.Instance
106+
if node.Spec.ProviderID == "" {
107+
ec2Instance, err = i.getInstanceByPrivateDNSName(ctx, node.Name)
108+
if err != nil {
109+
return nil, err
110+
}
111+
} else {
112+
ec2Instance, err = i.getInstanceByProviderID(ctx, node.Spec.ProviderID)
113+
if err != nil {
114+
return nil, err
115+
}
116+
}
117+
118+
nodeAddresses, err := nodeAddressesForInstance(ec2Instance)
119+
if err != nil {
120+
return nil, err
121+
}
122+
123+
providerID, err := getInstanceProviderID(ec2Instance)
124+
if err != nil {
125+
return nil, err
126+
}
127+
128+
metadata := &cloudprovider.InstanceMetadata{
129+
ProviderID: providerID,
130+
InstanceType: aws.StringValue(ec2Instance.InstanceType),
131+
NodeAddresses: nodeAddresses,
132+
}
133+
134+
return metadata, nil
135+
}
136+
137+
// InstanceExistsByProviderID returns the instance if the instance with the given provider id still exists.
138+
// If false an error will be returned, the instance will be immediately deleted by the cloud controller manager.
139+
func (i *instances) getInstanceByProviderID(ctx context.Context, providerID string) (*ec2.Instance, error) {
140+
instanceID, err := parseInstanceIDFromProviderID(providerID)
141+
if err != nil {
142+
return nil, err
143+
}
144+
145+
request := &ec2.DescribeInstancesInput{
146+
InstanceIds: []*string{aws.String(instanceID)},
147+
}
148+
149+
instances := []*ec2.Instance{}
150+
var nextToken *string
151+
for {
152+
response, err := i.ec2.DescribeInstances(request)
153+
if err != nil {
154+
return nil, fmt.Errorf("error describing ec2 instances: %v", err)
155+
}
156+
157+
for _, reservation := range response.Reservations {
158+
instances = append(instances, reservation.Instances...)
159+
}
160+
161+
nextToken = response.NextToken
162+
if aws.StringValue(nextToken) == "" {
163+
break
164+
}
165+
request.NextToken = nextToken
166+
}
167+
168+
if len(instances) == 0 {
169+
return nil, cloudprovider.InstanceNotFound
170+
}
171+
172+
if len(instances) > 1 {
173+
return nil, fmt.Errorf("multiple instances found with provider ID: %s", instanceID)
174+
}
175+
176+
state := instances[0].State.Name
177+
if *state == ec2.InstanceStateNameTerminated {
178+
klog.Warningf("the instance %s is terminated", instanceID)
179+
return nil, nil
180+
}
181+
182+
return instances[0], nil
183+
}
184+
185+
// InstanceExistsByPrivateDNSName returns the instance if the instance with the given provider id still exists.
186+
// If false an error will be returned, the instance will be immediately deleted by the cloud controller manager.
187+
func (i *instances) getInstanceByPrivateDNSName(ctx context.Context, nodeName string) (*ec2.Instance, error) {
188+
request := &ec2.DescribeInstancesInput{
189+
Filters: []*ec2.Filter{
190+
newEc2Filter("private-dns-name", nodeName),
191+
newEc2Filter("instance-state-name", aliveFilter...),
192+
},
193+
}
194+
195+
instances := []*ec2.Instance{}
196+
var nextToken *string
197+
for {
198+
response, err := i.ec2.DescribeInstances(request)
199+
if err != nil {
200+
return nil, fmt.Errorf("error describing ec2 instances: %v", err)
201+
}
202+
203+
for _, reservation := range response.Reservations {
204+
instances = append(instances, reservation.Instances...)
205+
}
206+
207+
nextToken = response.NextToken
208+
if aws.StringValue(nextToken) == "" {
209+
break
210+
}
211+
request.NextToken = nextToken
212+
}
213+
214+
if len(instances) == 0 {
215+
return nil, cloudprovider.InstanceNotFound
216+
}
217+
218+
if len(instances) > 1 {
219+
return nil, fmt.Errorf("multiple instances found with private DNS name: %s", nodeName)
220+
}
221+
222+
return instances[0], nil
223+
}
224+
225+
// instanceShutdownByProviderID returns true if the instance is shutdown according to the cloud provider.
226+
func (i *instances) instanceShutdownByProviderID(ctx context.Context, providerID string) (bool, error) {
227+
ec2Instance, err := i.getInstanceByProviderID(ctx, providerID)
228+
if err != nil {
229+
return false, err
230+
}
231+
232+
if ec2Instance.State != nil {
233+
state := aws.StringValue(ec2Instance.State.Name)
234+
if state == ec2.InstanceStateNameTerminated || state == ec2.InstanceStateNameStopping || state == ec2.InstanceStateNameStopped {
235+
return true, nil
236+
}
237+
}
238+
239+
return false, nil
240+
}
241+
242+
// instanceShutdownByPrivateDNSName returns true if the instance is shutdown according to the cloud provider.
243+
func (i *instances) instanceShutdownByPrivateDNSName(ctx context.Context, nodeName string) (bool, error) {
244+
ec2Instance, err := i.getInstanceByPrivateDNSName(ctx, nodeName)
245+
if err != nil {
246+
return false, err
247+
}
248+
249+
if ec2Instance.State != nil {
250+
state := aws.StringValue(ec2Instance.State.Name)
251+
if state == ec2.InstanceStateNameTerminated || state == ec2.InstanceStateNameStopping || state == ec2.InstanceStateNameStopped {
252+
return true, nil
253+
}
254+
}
255+
256+
return false, nil
257+
}
258+
259+
// nodeAddresses for Instance returns a list of v1.NodeAddress for the give instance.
260+
// TODO: should we support ExternalIP by default?
261+
func nodeAddressesForInstance(instance *ec2.Instance) ([]v1.NodeAddress, error) {
262+
if instance == nil {
263+
return nil, errors.New("provided instances is nil")
264+
}
265+
266+
addresses := []v1.NodeAddress{}
267+
for _, networkInterface := range instance.NetworkInterfaces {
268+
// skip network interfaces that are not currently in use
269+
if aws.StringValue(networkInterface.Status) != ec2.NetworkInterfaceStatusInUse {
270+
continue
271+
}
272+
273+
for _, privateIP := range networkInterface.PrivateIpAddresses {
274+
if ipAddress := aws.StringValue(privateIP.PrivateIpAddress); ipAddress != "" {
275+
ip := net.ParseIP(ipAddress)
276+
if ip == nil {
277+
return nil, fmt.Errorf("invalid IP address %q from instance %q", ipAddress, aws.StringValue(instance.InstanceId))
278+
}
279+
280+
addresses = append(addresses, v1.NodeAddress{
281+
Type: v1.NodeInternalIP,
282+
Address: ip.String(),
283+
})
284+
}
285+
}
286+
}
287+
288+
return addresses, nil
289+
}
290+
291+
// getInstanceProviderID returns the provider ID of an instance which is ultimately set in the node.Spec.ProviderID field.
292+
// The well-known format for a node's providerID is:
293+
// * aws://<availability-zone>/<instance-id>
294+
func getInstanceProviderID(instance *ec2.Instance) (string, error) {
295+
if aws.StringValue(instance.Placement.AvailabilityZone) == "" {
296+
return "", errors.New("instance availability zone was not set")
297+
}
298+
299+
if aws.StringValue(instance.InstanceId) == "" {
300+
return "", errors.New("instance ID was not set")
301+
}
302+
303+
return "aws://" + aws.StringValue(instance.Placement.AvailabilityZone) + "/" + aws.StringValue(instance.InstanceId), nil
304+
}
305+
306+
// parseInstanceIDFromProviderID parses the node's instance ID based on the well-known provider ID format:
307+
// * aws://<availability-zone>/<instance-id>
308+
// This function always assumes a valid providerID format was provided.
309+
func parseInstanceIDFromProviderID(providerID string) (string, error) {
310+
// trim the provider name prefix 'aws://', renaming providerID should contain metadata in the format:
311+
// <availability-zone>/<instance-id>
312+
metadata := strings.Split(strings.TrimPrefix(providerID, "aws://"), "/")
313+
return metadata[1], nil
314+
}
315+
316+
var aliveFilter = []string{
317+
ec2.InstanceStateNamePending,
318+
ec2.InstanceStateNameRunning,
319+
ec2.InstanceStateNameShuttingDown,
320+
ec2.InstanceStateNameStopping,
321+
ec2.InstanceStateNameStopped,
322+
}
323+
324+
func newEc2Filter(name string, values ...string) *ec2.Filter {
325+
filter := &ec2.Filter{
326+
Name: aws.String(name),
327+
}
328+
329+
for _, value := range values {
330+
filter.Values = append(filter.Values, aws.String(value))
331+
}
332+
333+
return filter
334+
}

0 commit comments

Comments
 (0)