-
Notifications
You must be signed in to change notification settings - Fork 75
/
plan_steps.go
177 lines (160 loc) · 4.91 KB
/
plan_steps.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
// SPDX-FileCopyrightText: 2023 The Crossplane Authors <https://crossplane.io>
//
// SPDX-License-Identifier: Apache-2.0
package migration
import (
"fmt"
"sort"
"strconv"
"strings"
"github.com/pkg/errors"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/util/json"
"k8s.io/apimachinery/pkg/util/jsonmergepatch"
"k8s.io/apimachinery/pkg/util/rand"
)
type step int
const (
errMarshalSourceForPatch = "failed to marshal source object for computing JSON merge patch"
errMarshalTargetForPatch = "failed to marshal target object for computing JSON merge patch"
errMergePatch = "failed to compute the JSON merge patch document"
errMergePatchMap = "failed to unmarshal the JSON merge patch document into map"
errInvalidStepFmt = "invalid step ID: %d"
)
func setApplyStep(name string, s *Step) {
s.Name = name
s.Type = StepTypeApply
s.Apply = &ApplyStep{}
}
func setPatchStep(name string, s *Step) {
s.Name = name
s.Type = StepTypePatch
s.Patch = &PatchStep{}
s.Patch.Type = PatchTypeMerge
}
func setDeleteStep(name string, s *Step) {
s.Name = name
s.Type = StepTypeDelete
deletePolicy := FinalizerPolicyRemove
s.Delete = &DeleteStep{
Options: &DeleteOptions{
FinalizerPolicy: &deletePolicy,
},
}
}
func setExecStep(name string, s *Step) {
s.Name = name
s.Type = StepTypeExec
s.Exec = &ExecStep{
Command: "sh",
}
}
func (pg *PlanGenerator) commitSteps() { //nolint: gocyclo
if len(pg.Plan.Spec.stepMap) == 0 {
return
}
pg.Plan.Spec.Steps = make([]Step, 0, len(pg.Plan.Spec.stepMap))
keys := make([]string, 0, len(pg.Plan.Spec.stepMap))
for s := range pg.Plan.Spec.stepMap {
keys = append(keys, s)
}
// keys slice consist of the step keys of enabled migration steps.
// step keys are the string representation of integer or float64 numbers,
// which correspond to the step execution order (greater number executes later)
// therefore needs to be sorted according to their numeric values.
// otherwise, sorting the strings directly causes faulty behavior e.g "1" < "10" < "2"
// sorting will panic if a non-numeric step key is found in keys
sort.SliceStable(keys, func(i, j int) bool {
fi, err := strconv.ParseFloat(keys[i], 64)
if err != nil {
panic(err)
}
fj, err := strconv.ParseFloat(keys[j], 64)
if err != nil {
panic(err)
}
return fi < fj
})
addManualExecution := true
switch t := pg.source.(type) {
case *sources:
for _, source := range t.backends {
if _, ok := source.(*FileSystemSource); ok {
addManualExecution = false
break
}
}
case *FileSystemSource:
addManualExecution = false
}
if addManualExecution {
for _, s := range keys {
AddManualExecution(pg.Plan.Spec.stepMap[s])
pg.Plan.Spec.Steps = append(pg.Plan.Spec.Steps, *pg.Plan.Spec.stepMap[s])
}
} else {
for _, s := range keys {
pg.Plan.Spec.Steps = append(pg.Plan.Spec.Steps, *pg.Plan.Spec.stepMap[s])
}
}
}
// AddManualExecution sets the manual execution hint for
// the specified step.
func AddManualExecution(s *Step) {
switch s.Type {
case StepTypeExec:
s.ManualExecution = []string{fmt.Sprintf("%s %s %q", s.Exec.Command, s.Exec.Args[0], strings.Join(s.Exec.Args[1:], " "))}
case StepTypePatch:
for _, f := range s.Patch.Files {
s.ManualExecution = append(s.ManualExecution, fmt.Sprintf("kubectl patch --type='%s' -f %s --patch-file %s", s.Patch.Type, f, f))
}
case StepTypeApply:
for _, f := range s.Apply.Files {
s.ManualExecution = append(s.ManualExecution, fmt.Sprintf("kubectl apply -f %s", f))
}
case StepTypeDelete:
for _, r := range s.Delete.Resources {
s.ManualExecution = append(s.ManualExecution, fmt.Sprintf("kubectl delete %s %s", strings.Join([]string{r.Kind, r.Group}, "."), r.Name))
}
}
}
func (pg *PlanGenerator) stepEnabled(s step) bool {
for _, i := range pg.enabledSteps {
if i == s {
return true
}
}
return false
}
func computeJSONMergePathDoc(source, target unstructured.Unstructured) (map[string]any, error) {
sourceBuff, err := source.MarshalJSON()
if err != nil {
return nil, errors.Wrap(err, errMarshalSourceForPatch)
}
targetBuff, err := target.MarshalJSON()
if err != nil {
return nil, errors.Wrap(err, errMarshalTargetForPatch)
}
patch, err := jsonmergepatch.CreateThreeWayJSONMergePatch(sourceBuff, targetBuff, sourceBuff)
if err != nil {
return nil, errors.Wrap(err, errMergePatch)
}
var result map[string]any
return result, errors.Wrap(json.Unmarshal(patch, &result), errMergePatchMap)
}
func getQualifiedName(u unstructured.Unstructured) string {
namePrefix := u.GetName()
if len(namePrefix) == 0 {
namePrefix = fmt.Sprintf("%s%s", u.GetGenerateName(), rand.String(5))
}
gvk := u.GroupVersionKind()
return fmt.Sprintf("%s.%ss.%s", namePrefix, strings.ToLower(gvk.Kind), gvk.Group)
}
func getVersionedName(u unstructured.Unstructured) string {
v := u.GroupVersionKind().Version
qName := getQualifiedName(u)
if v == "" {
return qName
}
return fmt.Sprintf("%s_%s", qName, v)
}