-
Notifications
You must be signed in to change notification settings - Fork 40
/
crd.go
344 lines (283 loc) · 11.6 KB
/
crd.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
/*
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 kubernetes
import (
"context"
"fmt"
"strings"
"github.com/keikoproj/instance-manager/api/v1alpha1"
"github.com/keikoproj/instance-manager/controllers/common"
"github.com/pkg/errors"
kerr "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/dynamic"
)
const (
CRDStrategyName = "crd"
DefaultUpgradeNamespace = "default"
OwnershipAnnotationKey = "app.kubernetes.io/managed-by"
ScopeAnnotationKey = "instancemgr.keikoproj.io/upgrade-scope"
OwnershipAnnotationValue = "instance-manager"
)
func ProcessCRDStrategy(kube dynamic.Interface, instanceGroup *v1alpha1.InstanceGroup, configName string) (bool, error) {
var (
status = instanceGroup.GetStatus()
strategy = instanceGroup.GetUpgradeStrategy().GetCRDType()
spec = instanceGroup.GetEKSSpec()
instanceGroupNamespacedName = instanceGroup.NamespacedName()
asgName = status.GetActiveScalingGroupName()
statusPath = strategy.GetStatusJSONPath()
successString = strategy.GetStatusSuccessString()
failureString = strategy.GetStatusFailureString()
crdName = strategy.GetCRDName()
policy = strategy.GetConcurrencyPolicy()
)
renderParams := struct {
InstanceGroup *v1alpha1.InstanceGroup
}{
InstanceGroup: instanceGroup,
}
templatedCustomResource, err := RenderCustomResource(strategy.GetSpec(), renderParams)
if err != nil {
return false, errors.Wrap(err, "failed to render custom resource templating")
}
customResource, err := ParseCustomResourceYaml(templatedCustomResource)
if err != nil {
return false, errors.Wrap(err, "failed to parse custom resource yaml")
}
AddAnnotation(customResource, OwnershipAnnotationKey, OwnershipAnnotationValue)
AddAnnotation(customResource, ScopeAnnotationKey, asgName)
GVR := GetGVR(customResource, crdName)
var launchID string
if spec.IsLaunchConfiguration() {
launchID = common.GetLastElementBy(configName, "-")
} else if spec.IsLaunchTemplate() {
templateID := common.GetLastElementBy(configName, "-")
version := status.GetLatestTemplateVersion()
if common.StringEmpty(version) {
version = "0"
}
launchID = strings.Join([]string{templateID, version}, "-")
}
NormalizeName(customResource, launchID)
crdFullName := CRDFullName(GVR.Resource, GVR.Group)
if !CRDExists(kube, crdFullName) {
return false, errors.Errorf("custom resource definition '%v' is missing, could not upgrade", crdFullName)
}
var (
customResourceName = customResource.GetName()
customResourceNamespace = customResource.GetNamespace()
)
status.SetStrategyResourceName(customResourceName)
status.SetStrategyResourceNamespace(customResourceNamespace)
_, activeResources, err := GetResources(kube, instanceGroup, customResource)
if err != nil {
return false, errors.Wrap(err, "failed to discover active custom resources")
}
if len(activeResources) > 0 {
switch strings.ToLower(policy) {
case v1alpha1.ForbidConcurrencyPolicy:
// if any active resource exist for the ASG, it must first complete
log.Info("custom resource/s still active, will requeue", "instancegroup", instanceGroupNamespacedName)
return false, nil
case v1alpha1.ReplaceConcurrencyPolicy:
var isRunning bool
for _, resource := range activeResources {
resourceName := resource.GetName()
resourceNamespace := resource.GetNamespace()
// if active resource exist with same launch id, it's not replaceable
if strings.HasSuffix(resourceName, launchID) {
isRunning = true
continue
}
// if active resource exist with a different launch id, it is replaceable
log.Info("active custom resource/s exists, will replace", "instancegroup", instanceGroupNamespacedName)
err = kube.Resource(GVR).Namespace(resourceNamespace).Delete(context.Background(), resourceName, metav1.DeleteOptions{})
if err != nil {
if !kerr.IsNotFound(err) {
return false, errors.Wrap(err, "failed to delete custom resource")
}
}
}
if isRunning {
// finally, if an active resource is still running, requeue until it's done
return false, nil
}
case v1alpha1.AllowConcurrencyPolicy:
log.Info("concurrency set to allow, will submit new resource", "instancegroup", instanceGroupNamespacedName)
}
}
// create new resource if not exist
_, err = kube.Resource(GVR).Namespace(customResourceNamespace).Create(context.Background(), customResource, metav1.CreateOptions{})
if err != nil {
if !kerr.IsAlreadyExists(err) {
return false, errors.Wrap(err, "failed to submit custom resource")
}
} else {
log.Info("submitted custom resource", "instancegroup", instanceGroupNamespacedName)
status.SetStrategyRetryCount(0)
}
// get created resource
customResource, err = kube.Resource(GVR).Namespace(customResourceNamespace).Get(context.Background(), customResourceName, metav1.GetOptions{})
if kerr.IsNotFound(err) {
log.Info("custom resource did not propagate, will requeue", "instancegroup", instanceGroupNamespacedName)
return false, nil
}
// check if resource completed / failed
resourceStatus, err := GetUnstructuredPath(customResource, statusPath)
if err != nil {
return false, err
}
log.Info("watching custom resource status", "instancegroup", instanceGroupNamespacedName, "resource", customResourceName, "status", resourceStatus)
if strings.EqualFold(resourceStatus, successString) {
log.Info("custom resource succeeded", "instancegroup", instanceGroupNamespacedName, "resource", customResourceName, "status", resourceStatus)
status.SetStrategyRetryCount(0)
return true, nil
}
if strings.EqualFold(resourceStatus, failureString) {
log.Info("custom resource failed", "instancegroup", instanceGroupNamespacedName, "resource", customResourceName, "status", resourceStatus)
maxRetries := *strategy.MaxRetries
if maxRetries > status.GetStrategyRetryCount() {
if maxRetries == -1 {
// if maxRetries is set to -1, retry forever
status.SetStrategyRetryCount(-1)
} else {
// otherwise increment retry counter
status.IncrementStrategyRetryCount()
}
log.Info("max retries not met, will resubmit", "instancegroup", instanceGroupNamespacedName, "maxRetries", maxRetries, "retryNumber", status.StrategyRetryCount)
err = kube.Resource(GVR).Namespace(customResourceNamespace).Delete(context.Background(), customResourceName, metav1.DeleteOptions{})
if err != nil {
if !kerr.IsNotFound(err) {
return false, errors.Wrap(err, "failed to delete custom resource")
}
}
return false, nil
}
return false, errors.Errorf("custom resource failed to converge, %v status is %v", statusPath, resourceStatus)
}
log.Info("custom resource still converging", "instancegroup", instanceGroupNamespacedName, "resource", customResourceName, "status", resourceStatus)
return false, nil
}
func NormalizeName(customResource *unstructured.Unstructured, id string) {
var (
name string
resourceName = customResource.GetName()
resourceNamespace = customResource.GetNamespace()
generatedName = customResource.GetGenerateName()
)
// Add missing id suffix if missing
if !common.StringEmpty(resourceName) && !strings.HasSuffix(resourceName, id) {
name = fmt.Sprintf("%v-%v", resourceName, id)
customResource.SetName(name)
}
// If generatedName provided use instead
if !common.StringEmpty(generatedName) {
name = fmt.Sprintf("%v-%v", generatedName, id)
customResource.SetName(name)
}
// Shorten long name
if len(name) > 63 {
name = fmt.Sprintf("instancemgr-%v", id)
customResource.SetName(name)
}
// Use default namespace if not provided
if common.StringEmpty(resourceNamespace) {
customResource.SetNamespace(DefaultUpgradeNamespace)
}
}
func ResourceGVR(kube dynamic.Interface, instanceGroup *v1alpha1.InstanceGroup) (schema.GroupVersionResource, error) {
var (
strategy = instanceGroup.GetUpgradeStrategy().GetCRDType()
)
renderParams := struct {
InstanceGroup *v1alpha1.InstanceGroup
}{
InstanceGroup: instanceGroup,
}
templatedCustomResource, err := RenderCustomResource(strategy.GetSpec(), renderParams)
if err != nil {
return schema.GroupVersionResource{}, errors.Wrap(err, "failed to render custom resource templating")
}
customResource, err := ParseCustomResourceYaml(templatedCustomResource)
if err != nil {
return schema.GroupVersionResource{}, errors.Wrap(err, "failed to parse custom resource yaml")
}
return GetGVR(customResource, strategy.GetCRDName()), nil
}
func IsResourceActive(kube dynamic.Interface, instanceGroup *v1alpha1.InstanceGroup) bool {
var (
strategy = instanceGroup.GetUpgradeStrategy().GetCRDType()
status = instanceGroup.GetStatus()
)
if strategy == nil {
return false
}
var (
statusJSONPath = strategy.GetStatusJSONPath()
completedStatus = strategy.GetStatusSuccessString()
errorStatus = strategy.GetStatusFailureString()
)
name := status.GetStrategyResourceName()
namespace := status.GetStrategyResourceNamespace()
if common.StringEmpty(name) || common.StringEmpty(namespace) {
return false
}
gvr, err := ResourceGVR(kube, instanceGroup)
if err != nil {
log.Error(err, "failed to get resource gvr")
return false
}
r, err := kube.Resource(gvr).Namespace(namespace).Get(context.Background(), name, metav1.GetOptions{})
if err != nil {
if kerr.IsNotFound(err) {
return false
}
log.Error(err, "failed to get upgrade resource")
return false
}
if IsPathValue(*r, statusJSONPath, completedStatus) || IsPathValue(*r, statusJSONPath, errorStatus) {
return false
}
return true
}
func GetResources(kube dynamic.Interface, instanceGroup *v1alpha1.InstanceGroup, resource *unstructured.Unstructured) ([]unstructured.Unstructured, []unstructured.Unstructured, error) {
var (
status = instanceGroup.GetStatus()
strategy = instanceGroup.GetUpgradeStrategy().GetCRDType()
statusJSONPath = strategy.GetStatusJSONPath()
completedStatus = strategy.GetStatusSuccessString()
errorStatus = strategy.GetStatusFailureString()
activeResources = make([]unstructured.Unstructured, 0)
inactiveResources = make([]unstructured.Unstructured, 0)
GVR = GetGVR(resource, strategy.GetCRDName())
resourceNamespace = resource.GetNamespace()
)
r, err := kube.Resource(GVR).Namespace(resourceNamespace).List(context.Background(), metav1.ListOptions{})
if err != nil {
return inactiveResources, activeResources, err
}
for _, ru := range r.Items {
annotations := ru.GetAnnotations()
if HasAnnotationWithValue(annotations, OwnershipAnnotationKey, OwnershipAnnotationValue) && HasAnnotationWithValue(annotations, ScopeAnnotationKey, status.GetActiveScalingGroupName()) {
if IsPathValue(ru, statusJSONPath, completedStatus) || IsPathValue(ru, statusJSONPath, errorStatus) {
// if resource is not completed and not failed, it must be still active
inactiveResources = append(inactiveResources, ru)
} else {
activeResources = append(activeResources, ru)
}
}
}
return inactiveResources, activeResources, nil
}