/
loadbalancer.go
345 lines (280 loc) · 10.6 KB
/
loadbalancer.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
/*
Copyright 2018 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 elb
import (
"fmt"
"reflect"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/elb"
"github.com/pkg/errors"
"sigs.k8s.io/cluster-api-provider-aws/pkg/apis/awsprovider/v1alpha1"
"sigs.k8s.io/cluster-api-provider-aws/pkg/cloud/aws/converters"
"sigs.k8s.io/cluster-api-provider-aws/pkg/cloud/aws/services/awserrors"
"sigs.k8s.io/cluster-api-provider-aws/pkg/cloud/aws/services/wait"
)
// ReconcileLoadbalancers reconciles the load balancers for the given cluster.
func (s *Service) ReconcileLoadbalancers() error {
s.scope.V(2).Info("Reconciling load balancers")
// Get default api server spec.
spec := s.getAPIServerClassicELBSpec()
// Describe or create.
apiELB, err := s.describeClassicELB(spec.Name)
if IsNotFound(err) {
apiELB, err = s.createClassicELB(spec)
if err != nil {
return err
}
s.scope.V(2).Info("Created new classic load balancer for apiserver", "api-server-elb-name", apiELB.Name)
} else if err != nil {
return err
}
if !reflect.DeepEqual(spec.Attributes, apiELB.Attributes) {
err := s.configureAttributes(apiELB.Name, spec.Attributes)
if err != nil {
return err
}
}
// TODO(vincepri): check if anything has changed and reconcile as necessary.
apiELB.DeepCopyInto(&s.scope.Network().APIServerELB)
s.scope.V(4).Info("Control plane load balancer", "api-server-elb", apiELB)
s.scope.V(2).Info("Reconcile load balancers completed successfully")
return nil
}
// GetAPIServerDNSName returns the DNS name endpoint for the API server
func (s *Service) GetAPIServerDNSName() (string, error) {
apiELB, err := s.describeClassicELB(GenerateELBName(s.scope.Name(), v1alpha1.APIServerRoleTagValue))
if err != nil {
return "", err
}
return apiELB.DNSName, nil
}
// DeleteLoadbalancers deletes the load balancers for the given cluster.
func (s *Service) DeleteLoadbalancers() error {
s.scope.V(2).Info("Deleting load balancers")
// Get default api server name.
elbName := GenerateELBName(s.scope.Name(), v1alpha1.APIServerRoleTagValue)
// Describe and delete if exists.
if _, err := s.describeClassicELB(elbName); err != nil {
if IsNotFound(err) {
return nil
}
return err
}
if err := s.deleteClassicELBAndWait(elbName); err != nil {
return err
}
s.scope.V(2).Info("Deleting load balancers completed successfully")
return nil
}
// RegisterInstanceWithClassicELB registers an instance with a classic ELB
func (s *Service) RegisterInstanceWithClassicELB(instanceID string, loadBalancer string) error {
input := &elb.RegisterInstancesWithLoadBalancerInput{
Instances: []*elb.Instance{{InstanceId: aws.String(instanceID)}},
LoadBalancerName: aws.String(loadBalancer),
}
_, err := s.scope.ELB.RegisterInstancesWithLoadBalancer(input)
if err != nil {
return err
}
return nil
}
// RegisterInstanceWithAPIServerELB registers an instance with a classic ELB
func (s *Service) RegisterInstanceWithAPIServerELB(instanceID string) error {
input := &elb.RegisterInstancesWithLoadBalancerInput{
Instances: []*elb.Instance{{InstanceId: aws.String(instanceID)}},
LoadBalancerName: aws.String(GenerateELBName(s.scope.Name(), v1alpha1.APIServerRoleTagValue)),
}
_, err := s.scope.ELB.RegisterInstancesWithLoadBalancer(input)
if err != nil {
return err
}
return nil
}
// GenerateELBName generates a formatted ELB name
func GenerateELBName(clusterName string, elbName string) string {
return fmt.Sprintf("%s-%s", clusterName, elbName)
}
func (s *Service) getAPIServerClassicELBSpec() *v1alpha1.ClassicELB {
res := &v1alpha1.ClassicELB{
Name: GenerateELBName(s.scope.Name(), v1alpha1.APIServerRoleTagValue),
Scheme: v1alpha1.ClassicELBSchemeInternetFacing,
Listeners: []*v1alpha1.ClassicELBListener{
{
Protocol: v1alpha1.ClassicELBProtocolTCP,
Port: 6443,
InstanceProtocol: v1alpha1.ClassicELBProtocolTCP,
InstancePort: 6443,
},
},
HealthCheck: &v1alpha1.ClassicELBHealthCheck{
Target: fmt.Sprintf("%v:%d", v1alpha1.ClassicELBProtocolTCP, 6443),
Interval: 10 * time.Second,
Timeout: 5 * time.Second,
HealthyThreshold: 5,
UnhealthyThreshold: 3,
},
SecurityGroupIDs: []string{s.scope.SecurityGroups()[v1alpha1.SecurityGroupControlPlane].ID},
Attributes: v1alpha1.ClassicELBAttributes{
IdleTimeout: 10 * time.Minute,
},
}
res.Tags = v1alpha1.Build(v1alpha1.BuildParams{
ClusterName: s.scope.Name(),
Lifecycle: v1alpha1.ResourceLifecycleOwned,
Role: aws.String(v1alpha1.APIServerRoleTagValue),
})
for _, sn := range s.scope.Subnets().FilterPublic() {
res.SubnetIDs = append(res.SubnetIDs, sn.ID)
}
return res
}
func (s *Service) createClassicELB(spec *v1alpha1.ClassicELB) (*v1alpha1.ClassicELB, error) {
input := &elb.CreateLoadBalancerInput{
LoadBalancerName: aws.String(spec.Name),
Subnets: aws.StringSlice(spec.SubnetIDs),
SecurityGroups: aws.StringSlice(spec.SecurityGroupIDs),
Scheme: aws.String(string(spec.Scheme)),
Tags: converters.MapToELBTags(spec.Tags),
}
for _, ln := range spec.Listeners {
input.Listeners = append(input.Listeners, &elb.Listener{
Protocol: aws.String(string(ln.Protocol)),
LoadBalancerPort: aws.Int64(ln.Port),
InstanceProtocol: aws.String(string(ln.InstanceProtocol)),
InstancePort: aws.Int64(ln.InstancePort),
})
}
out, err := s.scope.ELB.CreateLoadBalancer(input)
if err != nil {
return nil, errors.Wrapf(err, "failed to create classic load balancer: %v", spec)
}
if spec.HealthCheck != nil {
hc := &elb.ConfigureHealthCheckInput{
LoadBalancerName: aws.String(spec.Name),
HealthCheck: &elb.HealthCheck{
Target: aws.String(spec.HealthCheck.Target),
Interval: aws.Int64(int64(spec.HealthCheck.Interval.Seconds())),
Timeout: aws.Int64(int64(spec.HealthCheck.Timeout.Seconds())),
HealthyThreshold: aws.Int64(spec.HealthCheck.HealthyThreshold),
UnhealthyThreshold: aws.Int64(spec.HealthCheck.UnhealthyThreshold),
},
}
if _, err := s.scope.ELB.ConfigureHealthCheck(hc); err != nil {
return nil, errors.Wrapf(err, "failed to configure health check for classic load balancer: %v", spec)
}
}
s.scope.V(2).Info("Created classic load balancer", "dns-name", *out.DNSName)
res := spec.DeepCopy()
res.DNSName = *out.DNSName
return res, nil
}
func (s *Service) configureAttributes(name string, attributes v1alpha1.ClassicELBAttributes) error {
attrs := &elb.ModifyLoadBalancerAttributesInput{
LoadBalancerName: aws.String(name),
LoadBalancerAttributes: &elb.LoadBalancerAttributes{},
}
if attributes.IdleTimeout > 0 {
attrs.LoadBalancerAttributes.ConnectionSettings = &elb.ConnectionSettings{
IdleTimeout: aws.Int64(int64(attributes.IdleTimeout.Seconds())),
}
}
if _, err := s.scope.ELB.ModifyLoadBalancerAttributes(attrs); err != nil {
return errors.Wrapf(err, "failed to configure attributes for classic load balancer: %v", name)
}
return nil
}
func (s *Service) deleteClassicELB(name string) error {
input := &elb.DeleteLoadBalancerInput{
LoadBalancerName: aws.String(name),
}
if _, err := s.scope.ELB.DeleteLoadBalancer(input); err != nil {
return err
}
return nil
}
func (s *Service) deleteClassicELBAndWait(name string) error {
if err := s.deleteClassicELB(name); err != nil {
return err
}
input := &elb.DescribeLoadBalancersInput{
LoadBalancerNames: aws.StringSlice([]string{name}),
}
checkForELBDeletion := func() (done bool, err error) {
out, err := s.scope.ELB.DescribeLoadBalancers(input)
// ELB already deleted.
if len(out.LoadBalancerDescriptions) == 0 {
return true, nil
}
if code, _ := awserrors.Code(err); code == "LoadBalancerNotFound" {
return true, nil
}
if err != nil {
return false, err
}
return false, nil
}
if err := wait.WaitForWithRetryable(wait.NewBackoff(), checkForELBDeletion, []string{}); err != nil {
return errors.Wrapf(err, "failed to wait for ELB deletion %q", name)
}
return nil
}
func (s *Service) describeClassicELB(name string) (*v1alpha1.ClassicELB, error) {
input := &elb.DescribeLoadBalancersInput{
LoadBalancerNames: aws.StringSlice([]string{name}),
}
out, err := s.scope.ELB.DescribeLoadBalancers(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case elb.ErrCodeAccessPointNotFoundException:
return nil, errors.Wrapf(err, "no classic load balancer found with name: %q", name)
case elb.ErrCodeDependencyThrottleException:
return nil, errors.Wrap(err, "too many requests made to the ELB service")
default:
return nil, errors.Wrap(err, "unexpected aws error")
}
} else {
return nil, errors.Wrapf(err, "failed to describe classic load balancer: %s", name)
}
}
if out != nil && len(out.LoadBalancerDescriptions) == 0 {
return nil, NewNotFound(fmt.Errorf("no classic load balancer found with name %q", name))
}
if s.scope.VPC().ID != "" && s.scope.VPC().ID != *out.LoadBalancerDescriptions[0].VPCId {
return nil, errors.Errorf(
"ELB names must be unique within a region: %q ELB already exists in this region in VPC %q",
name, *out.LoadBalancerDescriptions[0].VPCId)
}
outAtt, err := s.scope.ELB.DescribeLoadBalancerAttributes(&elb.DescribeLoadBalancerAttributesInput{
LoadBalancerName: aws.String(name),
})
if err != nil {
return nil, errors.Wrapf(err, "failed to describe classic load balancer %q attributes", name)
}
return fromSDKTypeToClassicELB(out.LoadBalancerDescriptions[0], outAtt.LoadBalancerAttributes), nil
}
func fromSDKTypeToClassicELB(v *elb.LoadBalancerDescription, attrs *elb.LoadBalancerAttributes) *v1alpha1.ClassicELB {
res := &v1alpha1.ClassicELB{
Name: aws.StringValue(v.LoadBalancerName),
Scheme: v1alpha1.ClassicELBScheme(*v.Scheme),
SubnetIDs: aws.StringValueSlice(v.Subnets),
SecurityGroupIDs: aws.StringValueSlice(v.SecurityGroups),
DNSName: aws.StringValue(v.DNSName),
}
if attrs.ConnectionSettings != nil && attrs.ConnectionSettings.IdleTimeout != nil {
res.Attributes.IdleTimeout = time.Duration(*attrs.ConnectionSettings.IdleTimeout) * time.Second
}
return res
}