This repository has been archived by the owner on Apr 22, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 31
/
executor.go
369 lines (324 loc) · 10.5 KB
/
executor.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
361
362
363
364
365
366
367
368
369
package landscaper
import (
"encoding/json"
"errors"
"reflect"
"github.com/pmezard/go-difflib/difflib"
"github.com/sirupsen/logrus"
"google.golang.org/grpc"
"k8s.io/helm/pkg/helm"
)
// Executor is responsible for applying a desired landscape to the actual landscape
type Executor interface {
Apply(Components, Components) (map[string][]string, error)
CreateComponent(*Component) error
UpdateComponent(*Component) error
DeleteComponent(*Component) error
}
type executor struct {
helmClient helm.Interface
chartLoader ChartLoader
kubeSecrets SecretsWriteDeleter
dryRun bool
wait bool
waitTimeout int64
disabledStages []string
}
// NewExecutor is a factory method to create a new Executor
func NewExecutor(helmClient helm.Interface, chartLoader ChartLoader, kubeSecrets SecretsWriteDeleter, dryRun bool, wait bool, waitTimeout int64, disabledStages []string) Executor {
return &executor{
helmClient: helmClient,
chartLoader: chartLoader,
kubeSecrets: kubeSecrets,
dryRun: dryRun,
wait: wait,
waitTimeout: waitTimeout,
disabledStages: disabledStages,
}
}
// gatherForcedUpdates returns a map that for each to-be-updated component indicates if it needs a forced update.
// there may be several reasons to do so: releases that differ only in secret values are forced so that pods will restart with the new values; releases that differ in namespace cannot be updated
func (e *executor) gatherForcedUpdates(current, update Components) (map[string]bool, error) {
needForcedUpdate := map[string]bool{}
for _, cmp := range update {
// releases that differ only in secret values are forced so that pods will restart with the new values
for _, curCmp := range current {
if curCmp.Name == cmp.Name && isOnlySecretValueDiff(*curCmp, *cmp) {
logrus.Infof("%s differs in secrets values only; don't update but delete + create instead", cmp.Name)
needForcedUpdate[cmp.Name] = true
}
}
if curCmp := current[cmp.Name]; curCmp != nil {
if curCmp.Namespace != cmp.Namespace {
logrus.Infof("%s differs in namespace; don't update but delete + create instead", cmp.Name)
needForcedUpdate[cmp.Name] = true
}
}
}
return needForcedUpdate, nil
}
// Apply transforms the current state into the desired state
func (e *executor) Apply(desired, current Components) (map[string][]string, error) {
result := make(map[string][]string)
result["create"] = []string{}
result["update"] = []string{}
result["delete"] = []string{}
create, update, delete := diff(desired, current)
// some to-be-updated components need a delete + create instead
needForcedUpdate, err := e.gatherForcedUpdates(current, update)
if err != nil {
return result, err
}
// delete+create pairs will never work in dry run since the dry-run "deleted" component will exist in create
if !e.dryRun {
create, update, delete = integrateForcedUpdates(current, create, update, delete, needForcedUpdate)
}
for _, cmp := range delete {
cmpForcedUpdate := needForcedUpdate[cmp.Name]
if e.stageEnabled("delete") || (e.stageEnabled("update") && cmpForcedUpdate) {
logrus.Infof("Delete: %s", cmp.Name)
if err := e.DeleteComponent(cmp); err != nil {
logrus.WithFields(logrus.Fields{"error": err, "component": cmp}).Error("DeleteComponent failed")
return result, err
}
result["delete"] = append(result["delete"], cmp.Name)
}
}
if e.stageEnabled("update") {
for _, cmp := range update {
if err := logDifferences(logrus.Infof, "Update: "+cmp.Name, current[cmp.Name], cmp); err != nil {
return result, err
}
if err := e.UpdateComponent(cmp); err != nil {
logrus.WithFields(logrus.Fields{"error": err, "component": cmp}).Error("UpdateComponent failed")
return result, err
}
result["update"] = append(result["update"], cmp.Name)
}
}
for _, cmp := range create {
cmpForcedUpdate := needForcedUpdate[cmp.Name]
if e.stageEnabled("create") || (e.stageEnabled("update") && cmpForcedUpdate) {
if err := logDifferences(logrus.Infof, "Create: "+cmp.Name, nil, cmp); err != nil {
return result, err
}
if err := e.CreateComponent(cmp); err != nil {
logrus.WithFields(logrus.Fields{"error": err, "component": cmp}).Error("CreateComponent failed")
return result, err
}
result["create"] = append(result["create"], cmp.Name)
}
}
logrus.WithFields(logrus.Fields{"created": len(result["create"]), "updated": len(result["update"]), "deleted": len(result["delete"])}).Info("Applied desired state successfully")
return result, nil
}
func (e *executor) stageEnabled(stage string) bool {
for _, stageDisabled := range e.disabledStages {
if stageDisabled == stage {
return false
}
}
return true
}
// CreateComponent creates the given Component
func (e *executor) CreateComponent(cmp *Component) error {
// We need to ensure the chart is available on the local system. LoadChart will ensure
// this is the case by downloading the chart if it is not there yet
chartRef, err := cmp.FullChartRef()
if err != nil {
return err
}
_, chartPath, err := e.chartLoader.Load(chartRef)
if err != nil {
return err
}
rawValues, err := cmp.Configuration.YAML()
if err != nil {
return err
}
logrus.WithFields(logrus.Fields{
"release": cmp.Name,
"chart": cmp.Release.Chart,
"chartPath": chartPath,
"rawValues": rawValues,
"values": cmp.Configuration,
"dryrun": e.dryRun,
}).Debug("Create component")
if len(cmp.SecretValues) > 0 && !e.dryRun {
err = e.kubeSecrets.Write(cmp.Name, cmp.Namespace, cmp.SecretValues)
if err != nil {
return err
}
}
_, err = e.helmClient.InstallRelease(
chartPath,
cmp.Namespace,
helm.ValueOverrides([]byte(rawValues)),
helm.ReleaseName(cmp.Name),
helm.InstallDryRun(e.dryRun),
helm.InstallReuseName(true),
helm.InstallWait(e.wait),
helm.InstallTimeout(e.waitTimeout),
)
if err != nil {
return errors.New(grpc.ErrorDesc(err))
}
return nil
}
// UpdateComponent updates the given Component
func (e *executor) UpdateComponent(cmp *Component) error {
// We need to ensure the chart is available on the local system. LoadChart will ensure
// this is the case by downloading the chart if it is not there yet
chartRef, err := cmp.FullChartRef()
if err != nil {
return err
}
_, chartPath, err := e.chartLoader.Load(chartRef)
if err != nil {
return err
}
rawValues, err := cmp.Configuration.YAML()
if err != nil {
return err
}
if !e.dryRun {
if e.stageEnabled("deleteSecrets") || len(cmp.SecretValues) > 0 {
err = e.kubeSecrets.Delete(cmp.Name, cmp.Namespace)
}
if len(cmp.SecretValues) > 0 {
err = e.kubeSecrets.Write(cmp.Name, cmp.Namespace, cmp.SecretValues)
if err != nil {
return err
}
}
}
logrus.WithFields(logrus.Fields{
"release": cmp.Name,
"chart": cmp.Release.Chart,
"chartPath": chartPath,
"values": cmp.Configuration,
"dryrun": e.dryRun,
}).Debug("Update component")
_, err = e.helmClient.UpdateRelease(
cmp.Name,
chartPath,
helm.UpdateValueOverrides([]byte(rawValues)),
helm.UpgradeDryRun(e.dryRun),
helm.UpgradeWait(e.wait),
helm.UpgradeTimeout(e.waitTimeout),
)
if err != nil {
return errors.New(grpc.ErrorDesc(err))
}
return nil
}
// DeleteComponent removes the given Component
func (e *executor) DeleteComponent(cmp *Component) error {
logrus.WithFields(logrus.Fields{
"release": cmp.Name,
"values": cmp.Configuration,
"dryrun": e.dryRun,
}).Debug("Delete component")
if len(cmp.SecretValues) > 0 && !e.dryRun {
err := e.kubeSecrets.Delete(cmp.Name, cmp.Namespace)
if err != nil {
return err
}
}
if !e.dryRun {
_, err := e.helmClient.DeleteRelease(
cmp.Name,
helm.DeletePurge(true),
helm.DeleteDryRun(e.dryRun),
)
if err != nil {
return errors.New(grpc.ErrorDesc(err))
}
}
return nil
}
// diff takes desired and current components, and returns the components to create, update and delete to get from current to desired
func diff(desired, current Components) (Components, Components, Components) {
create := Components{}
update := Components{}
delete := Components{}
for name, desiredCmp := range desired {
if currentCmp, ok := current[name]; ok {
if !desiredCmp.Equals(currentCmp) {
update[name] = desiredCmp
}
} else {
create[name] = desiredCmp
}
}
for name, currentCmp := range current {
if _, ok := desired[name]; !ok {
delete[name] = currentCmp
}
}
return create, update, delete
}
// componentDiffText returns a diff as text. current and desired can be nil and indicate non-existence (e.g. current nil and desired non-nil means: create)
func componentDiffText(current, desired *Component) (string, error) {
cText, dText := []string{}, []string{}
cName, dName := "<none>", "<none>"
if current != nil {
cs, err := json.MarshalIndent(current, "", " ")
if err != nil {
return "", err
}
cText = difflib.SplitLines(string(cs))
cName = current.Name
}
if desired != nil {
ds, err := json.MarshalIndent(desired, "", " ")
if err != nil {
return "", err
}
dText = difflib.SplitLines(string(ds))
dName = desired.Name
}
return difflib.GetUnifiedDiffString(difflib.UnifiedDiff{
A: cText,
FromFile: "Current " + cName,
B: dText,
ToFile: "Desired " + dName,
Context: 3,
})
}
func logDifferences(logf func(format string, args ...interface{}), action string, current, desired *Component) error {
diff, err := componentDiffText(current, desired)
if err != nil {
return err
}
logf("%s", action)
if diff != "" {
logf("Diff:\n%s", diff)
}
if current != nil && desired != nil && !reflect.DeepEqual(current.SecretValues, desired.SecretValues) {
logrus.Info("Diff: secrets have changed, not shown here")
}
return nil
}
// integrateForcedUpdates removes forceUpdate from update and inserts it into delete + create
func integrateForcedUpdates(current, create, update, delete Components, forceUpdate map[string]bool) (Components, Components, Components) {
fixUpdate := Components{}
for _, cmp := range update {
if forceUpdate[cmp.Name] {
if currentCmp, ok := current[cmp.Name]; ok {
delete[currentCmp.Name] = currentCmp // delete the current component
}
create[cmp.Name] = cmp // create cmp, by definition a desired component
} else {
fixUpdate[cmp.Name] = cmp
}
}
return create, fixUpdate, delete
}
// isOnlySecretValueDiff tells whether the given Components differ in their .SecretValues fields and are identical otherwise
func isOnlySecretValueDiff(a, b Component) bool {
secValsEqual := reflect.DeepEqual(a.SecretValues, b.SecretValues)
a.SecretValues = SecretValues{}
b.SecretValues = SecretValues{}
return !secValsEqual && reflect.DeepEqual(a, b)
}