forked from kubernetes/autoscaler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
aws_cloud_provider.go
360 lines (315 loc) · 11.1 KB
/
aws_cloud_provider.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
/*
Copyright 2016 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 aws
import (
"fmt"
"regexp"
"strings"
apiv1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
"k8s.io/autoscaler/cluster-autoscaler/cloudprovider"
"k8s.io/autoscaler/cluster-autoscaler/config/dynamic"
"k8s.io/autoscaler/cluster-autoscaler/utils/errors"
"k8s.io/kubernetes/plugin/pkg/scheduler/schedulercache"
)
// awsCloudProvider implements CloudProvider interface.
type awsCloudProvider struct {
awsManager *AwsManager
asgs []*Asg
}
// BuildAwsCloudProvider builds CloudProvider implementation for AWS.
func BuildAwsCloudProvider(awsManager *AwsManager, discoveryOpts cloudprovider.NodeGroupDiscoveryOptions) (cloudprovider.CloudProvider, error) {
if err := discoveryOpts.Validate(); err != nil {
return nil, fmt.Errorf("Failed to build an aws cloud provider: %v", err)
}
if discoveryOpts.StaticDiscoverySpecified() {
return buildStaticallyDiscoveringProvider(awsManager, discoveryOpts.NodeGroupSpecs)
}
if discoveryOpts.AutoDiscoverySpecified() {
return buildAutoDiscoveringProvider(awsManager, discoveryOpts.NodeGroupAutoDiscoverySpec)
}
return nil, fmt.Errorf("Failed to build an aws cloud provider: Either node group specs or node group auto discovery spec must be specified")
}
func buildAutoDiscoveringProvider(awsManager *AwsManager, spec string) (*awsCloudProvider, error) {
tokens := strings.Split(spec, ":")
if len(tokens) != 2 {
return nil, fmt.Errorf("Invalid node group auto discovery spec specified via --node-group-auto-discovery: %s", spec)
}
discoverer := tokens[0]
if discoverer != "asg" {
return nil, fmt.Errorf("Unsupported discoverer specified: %s", discoverer)
}
param := tokens[1]
paramTokens := strings.Split(param, "=")
parameterKey := paramTokens[0]
if parameterKey != "tag" {
return nil, fmt.Errorf("Unsupported parameter key \"%s\" is specified for discoverer \"%s\". The only supported key is \"tag\"", parameterKey, discoverer)
}
tag := paramTokens[1]
if tag == "" {
return nil, fmt.Errorf("Invalid ASG tag for auto discovery specified: ASG tag must not be empty")
}
// Use the k8s cluster name tag to only discover asgs of the cluster denoted by clusterName
// See https://github.com/kubernetes/kubernetes/blob/9ef85a7/pkg/cloudprovider/providers/aws/tags.go#L30-L34
// for more information about the tag
tags := strings.Split(tag, ",")
asgs, err := awsManager.getAutoscalingGroupsByTags(tags)
if err != nil {
return nil, fmt.Errorf("Failed to get ASGs: %v", err)
}
aws := &awsCloudProvider{
awsManager: awsManager,
asgs: make([]*Asg, 0),
}
for _, asg := range asgs {
aws.addAsg(buildAsg(aws.awsManager, int(*asg.MinSize), int(*asg.MaxSize), *asg.AutoScalingGroupName))
}
return aws, nil
}
func buildStaticallyDiscoveringProvider(awsManager *AwsManager, specs []string) (*awsCloudProvider, error) {
aws := &awsCloudProvider{
awsManager: awsManager,
asgs: make([]*Asg, 0),
}
for _, spec := range specs {
if err := aws.addNodeGroup(spec); err != nil {
return nil, err
}
}
return aws, nil
}
// addNodeGroup adds node group defined in string spec. Format:
// minNodes:maxNodes:asgName
func (aws *awsCloudProvider) addNodeGroup(spec string) error {
asg, err := buildAsgFromSpec(spec, aws.awsManager)
if err != nil {
return err
}
aws.addAsg(asg)
return nil
}
// addAsg adds and registers an asg to this cloud provider
func (aws *awsCloudProvider) addAsg(asg *Asg) {
aws.asgs = append(aws.asgs, asg)
aws.awsManager.RegisterAsg(asg)
}
// Name returns name of the cloud provider.
func (aws *awsCloudProvider) Name() string {
return "aws"
}
// NodeGroups returns all node groups configured for this cloud provider.
func (aws *awsCloudProvider) NodeGroups() []cloudprovider.NodeGroup {
result := make([]cloudprovider.NodeGroup, 0, len(aws.asgs))
for _, asg := range aws.asgs {
result = append(result, asg)
}
return result
}
// NodeGroupForNode returns the node group for the given node.
func (aws *awsCloudProvider) NodeGroupForNode(node *apiv1.Node) (cloudprovider.NodeGroup, error) {
ref, err := AwsRefFromProviderId(node.Spec.ProviderID)
if err != nil {
return nil, err
}
asg, err := aws.awsManager.GetAsgForInstance(ref)
return asg, err
}
// Pricing returns pricing model for this cloud provider or error if not available.
func (aws *awsCloudProvider) Pricing() (cloudprovider.PricingModel, errors.AutoscalerError) {
return nil, cloudprovider.ErrNotImplemented
}
// GetAvilableMachineTypes get all machine types that can be requested from the cloud provider.
func (aws *awsCloudProvider) GetAvilableMachineTypes() ([]string, error) {
return []string{}, nil
}
// NewNodeGroup builds a theoretical node group based on the node definition provided. The node group is not automatically
// created on the cloud provider side. The node group is not returned by NodeGroups() until it is created.
func (aws *awsCloudProvider) NewNodeGroup(name string, machineType string, labels map[string]string, extraResources map[string]resource.Quantity) (cloudprovider.NodeGroup, error) {
return nil, cloudprovider.ErrNotImplemented
}
// AwsRef contains a reference to some entity in AWS/GKE world.
type AwsRef struct {
Name string
}
// AwsRefFromProviderId creates InstanceConfig object from provider id which
// must be in format: aws:///zone/name
func AwsRefFromProviderId(id string) (*AwsRef, error) {
validIdRegex := regexp.MustCompile(`^aws\:\/\/\/[-0-9a-z]*\/[-0-9a-z]*$`)
if validIdRegex.FindStringSubmatch(id) == nil {
return nil, fmt.Errorf("Wrong id: expected format aws:///<zone>/<name>, got %v", id)
}
splitted := strings.Split(id[7:], "/")
return &AwsRef{
Name: splitted[1],
}, nil
}
// Asg implements NodeGroup interface.
type Asg struct {
AwsRef
awsManager *AwsManager
minSize int
maxSize int
}
// MaxSize returns maximum size of the node group.
func (asg *Asg) MaxSize() int {
return asg.maxSize
}
// MinSize returns minimum size of the node group.
func (asg *Asg) MinSize() int {
return asg.minSize
}
// TargetSize returns the current TARGET size of the node group. It is possible that the
// number is different from the number of nodes registered in Kubernetes.
func (asg *Asg) TargetSize() (int, error) {
size, err := asg.awsManager.GetAsgSize(asg)
return int(size), err
}
// Exist checks if the node group really exists on the cloud provider side. Allows to tell the
// theoretical node group from the real one.
func (asg *Asg) Exist() (bool, error) {
return true, nil
}
// Create creates the node group on the cloud provider side.
func (asg *Asg) Create() error {
return cloudprovider.ErrAlreadyExist
}
// Delete deletes the node group on the cloud provider side.
// This will be executed only for autoprovisioned node groups, once their size drops to 0.
func (asg *Asg) Delete() error {
return cloudprovider.ErrNotImplemented
}
// IncreaseSize increases Asg size
func (asg *Asg) IncreaseSize(delta int) error {
if delta <= 0 {
return fmt.Errorf("size increase must be positive")
}
size, err := asg.awsManager.GetAsgSize(asg)
if err != nil {
return err
}
if int(size)+delta > asg.MaxSize() {
return fmt.Errorf("size increase too large - desired:%d max:%d", int(size)+delta, asg.MaxSize())
}
return asg.awsManager.SetAsgSize(asg, size+int64(delta))
}
// DecreaseTargetSize decreases the target size of the node group. This function
// doesn't permit to delete any existing node and can be used only to reduce the
// request for new nodes that have not been yet fulfilled. Delta should be negative.
// It is assumed that cloud provider will not delete the existing nodes if the size
// when there is an option to just decrease the target.
func (asg *Asg) DecreaseTargetSize(delta int) error {
if delta >= 0 {
return fmt.Errorf("size decrease size must be negative")
}
size, err := asg.awsManager.GetAsgSize(asg)
if err != nil {
return err
}
nodes, err := asg.awsManager.GetAsgNodes(asg)
if err != nil {
return err
}
if int(size)+delta < len(nodes) {
return fmt.Errorf("attempt to delete existing nodes targetSize:%d delta:%d existingNodes: %d",
size, delta, len(nodes))
}
return asg.awsManager.SetAsgSize(asg, size+int64(delta))
}
// Belongs returns true if the given node belongs to the NodeGroup.
func (asg *Asg) Belongs(node *apiv1.Node) (bool, error) {
ref, err := AwsRefFromProviderId(node.Spec.ProviderID)
if err != nil {
return false, err
}
targetAsg, err := asg.awsManager.GetAsgForInstance(ref)
if err != nil {
return false, err
}
if targetAsg == nil {
return false, fmt.Errorf("%s doesn't belong to a known asg", node.Name)
}
if targetAsg.Id() != asg.Id() {
return false, nil
}
return true, nil
}
// DeleteNodes deletes the nodes from the group.
func (asg *Asg) DeleteNodes(nodes []*apiv1.Node) error {
size, err := asg.awsManager.GetAsgSize(asg)
if err != nil {
return err
}
if int(size) <= asg.MinSize() {
return fmt.Errorf("min size reached, nodes will not be deleted")
}
refs := make([]*AwsRef, 0, len(nodes))
for _, node := range nodes {
belongs, err := asg.Belongs(node)
if err != nil {
return err
}
if belongs != true {
return fmt.Errorf("%s belongs to a different asg than %s", node.Name, asg.Id())
}
awsref, err := AwsRefFromProviderId(node.Spec.ProviderID)
if err != nil {
return err
}
refs = append(refs, awsref)
}
return asg.awsManager.DeleteInstances(refs)
}
// Id returns asg id.
func (asg *Asg) Id() string {
return asg.Name
}
// Debug returns a debug string for the Asg.
func (asg *Asg) Debug() string {
return fmt.Sprintf("%s (%d:%d)", asg.Id(), asg.MinSize(), asg.MaxSize())
}
// Nodes returns a list of all nodes that belong to this node group.
func (asg *Asg) Nodes() ([]string, error) {
return asg.awsManager.GetAsgNodes(asg)
}
// TemplateNodeInfo returns a node template for this node group.
func (asg *Asg) TemplateNodeInfo() (*schedulercache.NodeInfo, error) {
template, err := asg.awsManager.getAsgTemplate(asg.Name)
if err != nil {
return nil, err
}
node, err := asg.awsManager.buildNodeFromTemplate(asg, template)
if err != nil {
return nil, err
}
nodeInfo := schedulercache.NewNodeInfo(cloudprovider.BuildKubeProxy(asg.Name))
nodeInfo.SetNode(node)
return nodeInfo, nil
}
func buildAsgFromSpec(value string, awsManager *AwsManager) (*Asg, error) {
spec, err := dynamic.SpecFromString(value, true)
if err != nil {
return nil, fmt.Errorf("failed to parse node group spec: %v", err)
}
asg := buildAsg(awsManager, spec.MinSize, spec.MaxSize, spec.Name)
return asg, nil
}
func buildAsg(awsManager *AwsManager, minSize int, maxSize int, name string) *Asg {
return &Asg{
awsManager: awsManager,
minSize: minSize,
maxSize: maxSize,
AwsRef: AwsRef{
Name: name,
},
}
}