-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathchangeset.go
More file actions
333 lines (302 loc) · 9.05 KB
/
changeset.go
File metadata and controls
333 lines (302 loc) · 9.05 KB
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
package openshift
import (
"fmt"
"sort"
"strings"
"github.com/opendevstack/tailor/pkg/utils"
"github.com/xeipuuv/gojsonpointer"
)
var (
// Resources with no dependencies go first
kindOrder = map[string]string{
"Template": "a",
"ServiceAccount": "b",
"RoleBinding": "c",
"ConfigMap": "d",
"Secret": "e",
"LimitRange": "f",
"ResourceQuota": "g",
"PersistentVolumeClaim": "h",
"CronJob": "i",
"Job": "j",
"ImageStream": "k",
"BuildConfig": "l",
"StatefulSet": "m",
"DeploymentConfig": "n",
"Deployment": "o",
"HorizontalPodAutoscaler": "p",
"Service": "q",
"Route": "r",
}
)
type Changeset struct {
Create []*Change
Update []*Change
Delete []*Change
Noop []*Change
}
func NewChangeset(platformBasedList, templateBasedList *ResourceList, allowDeletion bool, allowRecreate bool, preservePaths []string) (*Changeset, error) {
changeset := &Changeset{
Create: []*Change{},
Delete: []*Change{},
Update: []*Change{},
Noop: []*Change{},
}
// items to delete
if allowDeletion {
for _, item := range platformBasedList.Items {
if _, err := templateBasedList.getItem(item.Kind, item.Name); err != nil {
change := &Change{
Action: "Delete",
Kind: item.Kind,
Name: item.Name,
CurrentState: item.YamlConfig(),
DesiredState: "",
}
changeset.Add(change)
}
}
}
// items to create
for _, item := range templateBasedList.Items {
if _, err := platformBasedList.getItem(item.Kind, item.Name); err != nil {
desiredState, err := item.DesiredConfig()
if err != nil {
return changeset, err
}
change := &Change{
Action: "Create",
Kind: item.Kind,
Name: item.Name,
CurrentState: "",
DesiredState: desiredState,
}
changeset.Add(change)
}
}
// items to update
for _, templateItem := range templateBasedList.Items {
platformItem, err := platformBasedList.getItem(
templateItem.Kind,
templateItem.Name,
)
if err == nil {
actualReservePaths := []string{}
for _, path := range preservePaths {
pathParts := strings.Split(path, ":")
if len(pathParts) > 3 {
return changeset, fmt.Errorf(
"%s is not a valid preserve argument",
path,
)
}
// Preserved paths can be either:
// - globally (e.g. /spec/name)
// - per-kind (e.g. bc:/spec/name)
// - per-resource (e.g. bc:foo:/spec/name)
if len(pathParts) == 1 ||
(len(pathParts) == 2 &&
templateItem.Kind == KindMapping[strings.ToLower(pathParts[0])]) ||
(len(pathParts) == 3 &&
templateItem.Kind == KindMapping[strings.ToLower(pathParts[0])] &&
templateItem.Name == strings.ToLower(pathParts[1])) {
// We only care about the last part (the JSON path) as we
// are already "inside" the item
actualReservePaths = append(actualReservePaths, pathParts[len(pathParts)-1])
}
}
changes, err := calculateChanges(templateItem, platformItem, actualReservePaths, allowRecreate)
if err != nil {
return changeset, err
}
changeset.Add(changes...)
}
}
return changeset, nil
}
func calculateChanges(templateItem *ResourceItem, platformItem *ResourceItem, preservePaths []string, allowRecreate bool) ([]*Change, error) {
err := templateItem.prepareForComparisonWithPlatformItem(platformItem, preservePaths)
if err != nil {
return nil, err
}
err = platformItem.prepareForComparisonWithTemplateItem(templateItem)
if err != nil {
return nil, err
}
comparedPaths := map[string]bool{}
addedPaths := []string{}
for _, path := range templateItem.Paths {
// Skip subpaths of already added paths
if utils.IncludesPrefix(addedPaths, path) {
continue
}
// Paths that should be preserved are no-ops
if utils.IncludesPrefix(preservePaths, path) {
comparedPaths[path] = true
continue
}
pathPointer, _ := gojsonpointer.NewJsonPointer(path)
templateItemVal, _, _ := pathPointer.Get(templateItem.Config)
platformItemVal, _, err := pathPointer.Get(platformItem.Config)
if err != nil {
// Pointer does not exist in platformItem
if templateItem.isImmutableField(path) {
if allowRecreate {
return recreateChanges(templateItem, platformItem), nil
} else {
return nil, recreateProtectionError(path, platformItem.ShortName())
}
}
comparedPaths[path] = true
// OpenShift sometimes removes the whole field when the value is an
// empty string. Therefore, we do not want to add the path in that
// case, otherwise we would cause endless drift. See
// https://github.com/opendevstack/tailor/issues/157.
if v, ok := templateItemVal.(string); ok && len(v) == 0 {
_, err := pathPointer.Delete(templateItem.Config)
if err != nil {
return nil, err
}
} else {
addedPaths = append(addedPaths, path)
}
} else {
// Pointer exists in both items
switch templateItemVal.(type) {
case []interface{}:
// slice content changed, continue ...
comparedPaths[path] = true
case []string:
// slice content changed, continue ...
comparedPaths[path] = true
case map[string]interface{}:
// map content changed, continue
comparedPaths[path] = true
default:
if templateItemVal == platformItemVal {
comparedPaths[path] = true
} else {
if templateItem.isImmutableField(path) {
if allowRecreate {
return recreateChanges(templateItem, platformItem), nil
} else {
return nil, recreateProtectionError(path, platformItem.ShortName())
}
}
comparedPaths[path] = true
}
}
}
}
deletedPaths := []string{}
for _, path := range platformItem.Paths {
if _, ok := comparedPaths[path]; !ok {
// Do not delete subpaths of already deleted paths
if utils.IncludesPrefix(deletedPaths, path) {
continue
}
pp, _ := gojsonpointer.NewJsonPointer(path)
val, _, err := pp.Get(platformItem.Config)
if err != nil {
return nil, err
}
if val == nil {
continue
}
// Skip annotations
if path == annotationsPath {
if x, ok := val.(map[string]interface{}); ok {
if len(x) == 0 {
_, err := pp.Set(templateItem.Config, map[string]interface{}{})
if err != nil {
return nil, err
}
}
}
continue
}
// If the value is an "empty value", there is no need to detect
// drift for it. This allows template authors to reduce boilerplate
// by omitting fields that have an "empty value".
if x, ok := val.(map[string]interface{}); ok {
if len(x) == 0 {
_, err := pp.Set(templateItem.Config, map[string]interface{}{})
if err != nil {
return nil, err
}
continue
}
}
if x, ok := val.([]interface{}); ok {
if len(x) == 0 {
_, err := pp.Set(templateItem.Config, []interface{}{})
if err != nil {
return nil, err
}
continue
}
}
if x, ok := val.([]string); ok {
if len(x) == 0 {
_, err := pp.Set(templateItem.Config, []string{})
if err != nil {
return nil, err
}
continue
}
}
// Pointer exist only in platformItem
comparedPaths[path] = true
deletedPaths = append(deletedPaths, path)
}
}
c := NewChange(templateItem, platformItem)
return []*Change{c}, nil
}
// Blank is true when there is no change across Create, Update, Delete.
func (c *Changeset) Blank() bool {
return len(c.Create) == 0 && len(c.Update) == 0 && len(c.Delete) == 0
}
// ExactlyOne is true when there is just a single change across Create, Update, Delete.
func (c *Changeset) ExactlyOne() bool {
return len(c.Create)+len(c.Update)+len(c.Delete) == 1
}
// Add adds given changes to the changeset.
func (c *Changeset) Add(changes ...*Change) {
for _, change := range changes {
switch change.Action {
case "Create":
c.Create = append(c.Create, change)
sort.Slice(c.Create, func(i, j int) bool {
return kindOrder[c.Create[i].Kind] < kindOrder[c.Create[j].Kind]
})
case "Update":
c.Update = append(c.Update, change)
sort.Slice(c.Update, func(i, j int) bool {
return kindOrder[c.Update[i].Kind] < kindOrder[c.Update[j].Kind]
})
case "Delete":
c.Delete = append(c.Delete, change)
sort.Slice(c.Delete, func(i, j int) bool {
return kindOrder[c.Delete[i].Kind] > kindOrder[c.Delete[j].Kind]
})
case "Noop":
c.Noop = append(c.Noop, change)
}
}
}
func recreateProtectionError(path string, itemName string) error {
return fmt.Errorf(
"Path '%s' of '%s' is immutable.\n"+
"Changing its value would require to delete "+
"and re-create the whole resource, which Tailor prevents by default.\n\n"+
"You may pick one of the following options to resolve this:\n\n"+
"* pass --allow-recreate to give permission to recreate the resource\n"+
"* use --preserve-immutable-fields to keep the cluster state for all immutable paths\n"+
"* change the template to be in sync with the cluster state\n"+
"* exclude the resource from comparison via --exclude %s",
path,
itemName,
itemName,
)
}