/
reconciler.go
268 lines (248 loc) · 10.1 KB
/
reconciler.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
/*
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 launchtemplate
import (
"context"
"encoding/base64"
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-sdk-go/service/ssm"
cpv1alpha1 "github.com/awslabs/kubernetes-iteration-toolkit/operator/pkg/apis/controlplane/v1alpha1"
"github.com/awslabs/kubernetes-iteration-toolkit/operator/pkg/apis/dataplane/v1alpha1"
"github.com/awslabs/kubernetes-iteration-toolkit/operator/pkg/awsprovider"
"github.com/awslabs/kubernetes-iteration-toolkit/operator/pkg/awsprovider/iam"
"github.com/awslabs/kubernetes-iteration-toolkit/operator/pkg/awsprovider/securitygroup"
"github.com/awslabs/kubernetes-iteration-toolkit/operator/pkg/controllers/master"
"github.com/awslabs/kubernetes-iteration-toolkit/operator/pkg/errors"
"github.com/awslabs/kubernetes-iteration-toolkit/operator/pkg/kubeprovider"
"github.com/awslabs/kubernetes-iteration-toolkit/operator/pkg/utils/keypairs"
"github.com/awslabs/kubernetes-iteration-toolkit/operator/pkg/utils/object"
"github.com/awslabs/kubernetes-iteration-toolkit/operator/pkg/utils/secrets"
"go.uber.org/zap"
"k8s.io/apimachinery/pkg/types"
"knative.dev/pkg/ptr"
)
const (
TagKeyNameForAWSResources = "kit.k8s.sh/cluster-name"
)
type Controller struct {
ec2api *awsprovider.EC2
ssm *awsprovider.SSM
kubeclient *kubeprovider.Client
}
// NewController returns a controller for managing LaunchTemplates in AWS
func NewController(ec2api *awsprovider.EC2, ssm *awsprovider.SSM, client *kubeprovider.Client) *Controller {
return &Controller{ec2api: ec2api, ssm: ssm, kubeclient: client}
}
func (c *Controller) Reconcile(ctx context.Context, dataplane *v1alpha1.DataPlane) error {
// get launch template
templates, err := c.getLaunchTemplates(ctx, dataplane.Spec.ClusterName)
if err != nil && !errors.IsLaunchTemplateDoNotExist(err) {
return fmt.Errorf("getting launch template, %w", err)
}
if !existingTemplateMatchesDesired(templates, dataplane.Spec.ClusterName) { // TODO check if existing LT is same as desired LT
// create launch template
if err := c.createLaunchTemplate(ctx, dataplane); err != nil {
return fmt.Errorf("creating launch template, %w", err)
}
zap.S().Infof("[%s] Created launch template", dataplane.Spec.ClusterName)
return nil
}
return nil
}
func (c *Controller) Finalize(ctx context.Context, dataplane *v1alpha1.DataPlane) error {
return c.deleteLaunchTemplate(ctx, TemplateName(dataplane.Spec.ClusterName))
}
func (c *Controller) deleteLaunchTemplate(ctx context.Context, templateName string) error {
if _, err := c.ec2api.DeleteLaunchTemplateWithContext(ctx, &ec2.DeleteLaunchTemplateInput{
LaunchTemplateName: ptr.String(templateName),
}); err != nil {
if errors.IsLaunchTemplateDoNotExist(err) {
return nil
}
return fmt.Errorf("deleting launch template, %w", err)
}
return nil
}
func (c *Controller) createLaunchTemplate(ctx context.Context, dataplane *v1alpha1.DataPlane) error {
var (
securityGroupID string
err error
)
if len(dataplane.Spec.SecurityGroupSelector) != 0 {
securityGroupID, err = c.securityGroupForSelector(ctx, dataplane.Spec.SecurityGroupSelector)
if err != nil {
return fmt.Errorf("getting security groups by selector, %w", err)
}
} else {
// Currently, we get the same security group assigned to control plane instances
// At some point, we will be creating dataplane specific security groups
securityGroupID, err = securitygroup.New(c.ec2api, c.kubeclient).For(ctx, dataplane.Spec.ClusterName)
if err != nil {
return fmt.Errorf("getting security group for control plane nodes, %w", err)
}
}
apiServerEndpoint := dataplane.Spec.APIServerEndpoint
if apiServerEndpoint == "" {
apiServerEndpoint, err = master.GetClusterEndpoint(ctx, c.kubeclient, types.NamespacedName{Namespace: dataplane.Namespace, Name: dataplane.Spec.ClusterName})
if err != nil {
return fmt.Errorf("getting cluster endpoint, %w", err)
}
}
amiID := dataplane.Spec.AmiID
if amiID == "" {
amiID, err = c.amiID(ctx, dataplane)
if err != nil {
return fmt.Errorf("getting ami id for worker nodes, %w", err)
}
}
instanceProfile := dataplane.Spec.InstanceProfileName
if len(instanceProfile) == 0 {
instanceProfile = iam.KitNodeInstanceProfileNameFor(dataplane.Spec.ClusterName)
}
clusterCA := dataplane.Spec.ClusterCA
if len(clusterCA) == 0 {
caSecret, err := keypairs.Reconciler(c.kubeclient).GetSecretFromServer(ctx,
object.NamespacedName(master.RootCASecretNameFor(dataplane.Spec.ClusterName), dataplane.Namespace))
if err != nil {
return fmt.Errorf("getting control plane ca certificate, %w", err)
}
_, clusterCA = secrets.Parse(caSecret)
}
input := &ec2.CreateLaunchTemplateInput{
LaunchTemplateData: &ec2.RequestLaunchTemplateData{
BlockDeviceMappings: []*ec2.LaunchTemplateBlockDeviceMappingRequest{{
DeviceName: ptr.String("/dev/xvda"),
Ebs: &ec2.LaunchTemplateEbsBlockDeviceRequest{
DeleteOnTermination: ptr.Bool(true),
Iops: ptr.Int64(3000),
VolumeSize: ptr.Int64(20),
VolumeType: ptr.String("gp3"),
}},
},
InstanceType: ptr.String("t2.xlarge"), // TODO get this from dataplane spec
ImageId: ptr.String(amiID),
IamInstanceProfile: &ec2.LaunchTemplateIamInstanceProfileSpecificationRequest{
Name: aws.String(instanceProfile),
},
MetadataOptions: &ec2.LaunchTemplateInstanceMetadataOptionsRequest{
HttpTokens: aws.String(ec2.LaunchTemplateHttpTokensStateRequired),
HttpPutResponseHopLimit: aws.Int64(2),
},
Monitoring: &ec2.LaunchTemplatesMonitoringRequest{Enabled: ptr.Bool(true)},
SecurityGroupIds: []*string{ptr.String(securityGroupID)},
UserData: ptr.String(base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf(userData,
dataplane.Spec.ClusterName, dataplane.Spec.DNSClusterIP,
base64.StdEncoding.EncodeToString(clusterCA), apiServerEndpoint)))),
},
LaunchTemplateName: ptr.String(TemplateName(dataplane.Spec.ClusterName)),
TagSpecifications: generateEC2Tags("launch-template", dataplane.Spec.ClusterName),
}
if _, err := c.ec2api.CreateLaunchTemplateWithContext(ctx, input); err != nil {
return fmt.Errorf("creating launch template, %w", err)
}
return nil
}
func (c *Controller) securityGroupForSelector(ctx context.Context, selector map[string]string) (string, error) {
filters := []*ec2.Filter{}
// Filter by selector
for key, value := range selector {
if value == "*" {
filters = append(filters, &ec2.Filter{
Name: aws.String("tag-key"),
Values: []*string{aws.String(key)},
})
} else {
filters = append(filters, &ec2.Filter{
Name: aws.String(fmt.Sprintf("tag:%s", key)),
Values: []*string{aws.String(value)},
})
}
}
output, err := c.ec2api.DescribeSecurityGroupsWithContext(ctx, &ec2.DescribeSecurityGroupsInput{Filters: filters})
if err != nil {
return "", fmt.Errorf("describing security groups %+v, %w", filters, err)
}
if len(output.SecurityGroups) != 1 {
return "", fmt.Errorf("wrong number of security groups by selector, %d", len(output.SecurityGroups))
}
return aws.StringValue(output.SecurityGroups[0].GroupId), nil
}
func (c *Controller) amiID(ctx context.Context, dataplane *v1alpha1.DataPlane) (string, error) {
kubeVersion, err := c.desiredKubernetesVersion(ctx, dataplane)
if err != nil {
return "", fmt.Errorf("getting kubernetes version, %w", err)
}
paramOutput, err := c.ssm.GetParameterWithContext(ctx, &ssm.GetParameterInput{
Name: ptr.String(fmt.Sprintf("/aws/service/eks/optimized-ami/%s/amazon-linux-2/recommended/image_id", kubeVersion)),
})
if err != nil {
return "", fmt.Errorf("getting ssm parameter, %w", err)
}
return *paramOutput.Parameter.Value, nil
}
func (c *Controller) desiredKubernetesVersion(ctx context.Context, dataplane *v1alpha1.DataPlane) (string, error) {
cp := &cpv1alpha1.ControlPlane{}
if err := c.kubeclient.Get(ctx, types.NamespacedName{Namespace: dataplane.GetNamespace(), Name: dataplane.Spec.ClusterName}, cp); err != nil {
return "", fmt.Errorf("getting control plane object, %w", err)
}
return cp.Spec.KubernetesVersion, nil
}
func (c *Controller) getLaunchTemplates(ctx context.Context, clusterName string) ([]*ec2.LaunchTemplate, error) {
output, err := c.ec2api.DescribeLaunchTemplatesWithContext(ctx, &ec2.DescribeLaunchTemplatesInput{
LaunchTemplateNames: []*string{ptr.String(TemplateName(clusterName))},
})
if err != nil {
return nil, fmt.Errorf("describing launch template, %w", err)
}
if len(output.LaunchTemplates) == 0 {
return nil, nil
}
return output.LaunchTemplates, nil
}
func existingTemplateMatchesDesired(templates []*ec2.LaunchTemplate, clusterName string) bool {
for _, template := range templates {
if aws.StringValue(template.LaunchTemplateName) == TemplateName(clusterName) {
return true
}
}
return false
}
func generateEC2Tags(svcName, clusterName string) []*ec2.TagSpecification {
return []*ec2.TagSpecification{{
ResourceType: ptr.String(svcName),
Tags: []*ec2.Tag{{
Key: ptr.String(TagKeyNameForAWSResources),
Value: ptr.String(clusterName),
}, {
Key: ptr.String("Name"),
Value: ptr.String(TemplateName(clusterName)),
}, {
Key: ptr.String(fmt.Sprintf("kubernetes.io/cluster/%s", clusterName)),
Value: ptr.String("owned"),
}},
}}
}
func TemplateName(clusterName string) string {
return fmt.Sprintf("kit-%s-cluster-nodes", clusterName)
}
var (
userData = `
#!/bin/bash
yum install -y https://s3.amazonaws.com/ec2-downloads-windows/SSMAgent/latest/linux_amd64/amazon-ssm-agent.rpm
/etc/eks/bootstrap.sh %s \
--dns-cluster-ip %s \
--kubelet-extra-args '--node-labels=kit.sh/provisioned=true' \
--b64-cluster-ca %s \
--apiserver-endpoint https://%s`
)