-
Notifications
You must be signed in to change notification settings - Fork 126
/
controller.go
289 lines (247 loc) · 10.1 KB
/
controller.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
/*
Copyright 2022.
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 keptnappcreationrequest
import (
"context"
"crypto/sha256"
"fmt"
"sort"
"strings"
"time"
"github.com/benbjohnson/clock"
"github.com/go-logr/logr"
lifecycle "github.com/keptn/lifecycle-toolkit/lifecycle-operator/apis/lifecycle/v1alpha3"
"github.com/keptn/lifecycle-toolkit/lifecycle-operator/apis/lifecycle/v1alpha3/common"
"github.com/keptn/lifecycle-toolkit/lifecycle-operator/controllers/common/config"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
)
const (
managedByKLT = "klt"
)
// KeptnAppCreationRequestReconciler reconciles a KeptnAppCreationRequest object
type KeptnAppCreationRequestReconciler struct {
client.Client
Scheme *runtime.Scheme
Log logr.Logger
clock clock.Clock
config config.IConfig
}
func NewReconciler(client client.Client, scheme *runtime.Scheme, log logr.Logger) *KeptnAppCreationRequestReconciler {
return &KeptnAppCreationRequestReconciler{
Client: client,
Scheme: scheme,
Log: log,
config: config.Instance(),
clock: clock.New(),
}
}
// +kubebuilder:rbac:groups=lifecycle.keptn.sh,resources=keptnappcreationrequests,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=lifecycle.keptn.sh,resources=keptnappcreationrequests/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=lifecycle.keptn.sh,resources=keptnappcreationrequests/finalizers,verbs=update
// Reconcile is part of the main kubernetes reconciliation loop which aims to
// move the current state of the cluster closer to the desired state.
// the KeptnAppCreationRequest object against the actual cluster state, and then
// perform operations to make the cluster state reflect the state specified by
// the user.
//
// For more details, check Reconcile and its Result here:
// - https://pkg.go.dev/sigs.k8s.io/[email protected]/pkg/reconcile
//
//nolint:gocyclo
func (r *KeptnAppCreationRequestReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
creationRequest := &lifecycle.KeptnAppCreationRequest{}
if err := r.Get(ctx, req.NamespacedName, creationRequest); err != nil {
if errors.IsNotFound(err) {
return ctrl.Result{}, nil
}
return ctrl.Result{}, fmt.Errorf("could not retrieve KeptnAppCreationRequest: %w", err)
}
// check if we already have an app that has not been created by this controller
appFound := false
keptnApp := &lifecycle.KeptnApp{}
name := req.NamespacedName
name.Name = creationRequest.Spec.AppName
if err := r.Get(ctx, name, keptnApp); err != nil {
if errors.IsNotFound(err) {
r.Log.Info("No KeptnApp found for KeptnAppCreationRequest", "KeptnAppCreationRequest", creationRequest)
} else {
return ctrl.Result{}, fmt.Errorf("could not retrieve KeptnApp %w", err)
}
} else {
appFound = true
}
// if the found app has not been created by this controller, we are done at this point - we don't want to mess with what the user has created
if appFound && keptnApp.Labels[common.K8sRecommendedManagedByAnnotations] != managedByKLT {
r.Log.Info("User defined KeptnApp found for KeptnAppCreationRequest", "KeptnAppCreationRequest", creationRequest)
if err := r.Delete(ctx, creationRequest); err != nil {
r.Log.Error(err, "Could not delete KeptnAppCreationRequest", "KeptnAppCreationRequest", creationRequest)
}
return ctrl.Result{}, nil
}
// check if discovery deadline has expired or if the application is a single service app
if !r.shouldCreateApp(creationRequest) {
r.Log.Info("Discovery deadline not expired yet", "KeptnAppCreationRequest", creationRequest)
return ctrl.Result{RequeueAfter: r.getCreationRequestExpirationDuration(creationRequest)}, nil
}
// look up all the KeptnWorkloads referencing the KeptnApp
workloads, err := r.getWorkloads(ctx, creationRequest)
if err != nil {
return ctrl.Result{}, fmt.Errorf("could not retrieve KeptnWorkloads: %w", err)
}
if !appFound {
err = r.createKeptnApp(ctx, creationRequest, workloads)
} else {
err = r.updateKeptnApp(ctx, keptnApp, workloads)
}
if err != nil {
return ctrl.Result{}, fmt.Errorf("could not update: %w", err)
}
if err := r.Delete(ctx, creationRequest); err != nil {
r.Log.Error(err, "Could not delete", "KeptnAppCreationRequest", creationRequest)
}
return ctrl.Result{}, nil
}
func (r *KeptnAppCreationRequestReconciler) getWorkloads(ctx context.Context, creationRequest *lifecycle.KeptnAppCreationRequest) ([]lifecycle.KeptnWorkload, error) {
workloads := &lifecycle.KeptnWorkloadList{}
if err := r.Client.List(ctx, workloads, client.InNamespace(creationRequest.Namespace), client.MatchingFields{
"spec.app": creationRequest.Spec.AppName,
}); err != nil {
return nil, err
}
sort.Slice(workloads.Items, func(i, j int) bool {
return workloads.Items[i].Name < workloads.Items[j].Name
})
return workloads.Items, nil
}
func (r *KeptnAppCreationRequestReconciler) getCreationRequestExpirationDuration(cr *lifecycle.KeptnAppCreationRequest) time.Duration {
creationRequestTimeout := r.config.GetCreationRequestTimeout()
deadline := cr.CreationTimestamp.Add(creationRequestTimeout)
duration := deadline.Sub(r.clock.Now())
// make sure we return a non-negative duration
if duration >= 0 {
return duration
}
return 0
}
func (r *KeptnAppCreationRequestReconciler) shouldCreateApp(creationRequest *lifecycle.KeptnAppCreationRequest) bool {
discoveryDeadline := r.config.GetCreationRequestTimeout()
return creationRequest.IsSingleService() || r.clock.Now().After(creationRequest.CreationTimestamp.Add(discoveryDeadline))
}
// SetupWithManager sets up the controller with the Manager.
func (r *KeptnAppCreationRequestReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&lifecycle.KeptnAppCreationRequest{}).
Complete(r)
}
func (r *KeptnAppCreationRequestReconciler) updateKeptnApp(ctx context.Context, keptnApp *lifecycle.KeptnApp, workloads []lifecycle.KeptnWorkload) error {
addOrUpdatedWorkload := r.addOrUpdateWorkloads(workloads, keptnApp)
removedWorkload := r.cleanupWorkloads(workloads, keptnApp)
if !addOrUpdatedWorkload && !removedWorkload {
return nil
}
keptnApp.Spec.Version = computeVersionFromWorkloads(workloads)
return r.Update(ctx, keptnApp)
}
func (r *KeptnAppCreationRequestReconciler) addOrUpdateWorkloads(workloads []lifecycle.KeptnWorkload, keptnApp *lifecycle.KeptnApp) bool {
updated := false
for _, workload := range workloads {
foundWorkload := false
workloadName := workload.GetNameWithoutAppPrefix()
for index, appWorkload := range keptnApp.Spec.Workloads {
if appWorkload.Name == workloadName {
// make sure the version matches the current version of the workload
if keptnApp.Spec.Workloads[index].Version != workload.Spec.Version {
keptnApp.Spec.Workloads[index].Version = workload.Spec.Version
// we may also want to increase the version of the app if any version has been changed
updated = true
}
foundWorkload = true
break
}
}
if !foundWorkload {
keptnApp.Spec.Workloads = append(keptnApp.Spec.Workloads, lifecycle.KeptnWorkloadRef{
Name: workloadName,
Version: workload.Spec.Version,
})
updated = true
}
}
return updated
}
func (r *KeptnAppCreationRequestReconciler) cleanupWorkloads(workloads []lifecycle.KeptnWorkload, keptnApp *lifecycle.KeptnApp) bool {
updated := false
updatedWorkloads := []lifecycle.KeptnWorkloadRef{}
for index, appWorkload := range keptnApp.Spec.Workloads {
foundWorkload := false
for _, workload := range workloads {
if appWorkload.Name == workload.GetNameWithoutAppPrefix() {
updatedWorkloads = append(updatedWorkloads, keptnApp.Spec.Workloads[index])
break
}
}
if !foundWorkload {
updated = true
}
}
keptnApp.Spec.Workloads = updatedWorkloads
return updated
}
func (r *KeptnAppCreationRequestReconciler) createKeptnApp(ctx context.Context, creationRequest *lifecycle.KeptnAppCreationRequest, workloads []lifecycle.KeptnWorkload) error {
keptnApp := &lifecycle.KeptnApp{
ObjectMeta: metav1.ObjectMeta{
Name: creationRequest.Spec.AppName,
Namespace: creationRequest.Namespace,
Labels: map[string]string{
common.K8sRecommendedManagedByAnnotations: managedByKLT,
},
// pass through the annotations since those contain the trace context
Annotations: creationRequest.Annotations,
},
Spec: lifecycle.KeptnAppSpec{
Version: computeVersionFromWorkloads(workloads),
PreDeploymentTasks: []string{},
PostDeploymentTasks: []string{},
PreDeploymentEvaluations: []string{},
PostDeploymentEvaluations: []string{},
Workloads: []lifecycle.KeptnWorkloadRef{},
},
}
for _, workload := range workloads {
keptnApp.Spec.Workloads = append(keptnApp.Spec.Workloads, lifecycle.KeptnWorkloadRef{
Name: strings.TrimPrefix(workload.Name, fmt.Sprintf("%s-", creationRequest.Spec.AppName)),
Version: workload.Spec.Version,
})
}
return r.Create(ctx, keptnApp)
}
func computeVersionFromWorkloads(workloads []lifecycle.KeptnWorkload) string {
// for single workload applications, the workload version is the application version
if len(workloads) == 1 {
return workloads[0].Spec.Version
}
versionString := ""
// iterate over all workloads and add their names + version
for _, workload := range workloads {
versionString += workload.Name + "-" + workload.Spec.Version
}
// take the string containing all workloads/versions and compute a hash
hash := sha256.New()
hash.Write([]byte(versionString))
hashValue := fmt.Sprintf("%x", hash.Sum(nil))
return common.TruncateString(hashValue, 10)
}