-
Notifications
You must be signed in to change notification settings - Fork 71
/
save.go
208 lines (188 loc) · 6.13 KB
/
save.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
package spindeploy
import (
"context"
"encoding/json"
"fmt"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/jsonmergepatch"
"github.com/armory/spinnaker-operator/pkg/generated"
"github.com/go-logr/logr"
kerrors "k8s.io/apimachinery/pkg/api/errors"
apimeta "k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/rest"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
)
// TransformManifests adjusts settings to the configuration
func (d *Deployer) deployConfig(ctx context.Context, scheme *runtime.Scheme, gen *generated.SpinnakerGeneratedConfig, logger logr.Logger) error {
// Set SpinnakerService instance as the owner and controller
count := 0
for _, v := range gen.Config {
count += len(v.Resources)
if v.Deployment != nil {
count += 1
}
if v.Service != nil {
count += 1
}
}
// Give users a few pointers if we end up running into an error halfway
// In theory, we're idempotent and if we need to run again, it should be reflected in
// the status. But things happen.
d.log.Info(fmt.Sprintf("saving %d manifests across %d services", count, len(gen.Config)))
for k := range gen.Config {
s := gen.Config[k]
if s.Deployment != nil {
logger.Info(fmt.Sprintf("saving deployment manifest for %s", k))
if err := d.saveObject(ctx, s.Deployment, logger); err != nil {
return err
}
}
if s.Service != nil {
logger.Info(fmt.Sprintf("saving service manifest for %s", k))
if err := d.saveObject(ctx, s.Service, logger); err != nil {
return err
}
}
for i := range s.Resources {
o, ok := s.Resources[i].(metav1.Object)
if ok {
logger.Info(fmt.Sprintf("saving resource manifest %s for %s", o.GetName(), k))
// Set SpinnakerService instance as the owner and controller
if s.Deployment != nil {
if err := controllerutil.SetControllerReference(s.Deployment, o, scheme); err != nil {
return err
}
}
}
if err := d.saveObject(ctx, s.Resources[i], logger); err != nil {
return err
}
}
for _, o := range s.ToDelete {
logger.Info(fmt.Sprintf("deleting resource manifest for %s", k))
if err := d.deleteObject(ctx, o); err != nil {
return err
}
}
}
return nil
}
func (d *Deployer) saveObject(ctx context.Context, obj client.Object, logger logr.Logger) error {
// Check if it exists
if err := d.patch(ctx, obj); err != nil {
logger.Error(err, fmt.Sprintf("Unable to save object: %v", obj))
return err
}
return nil
}
func (d *Deployer) deleteObject(ctx context.Context, obj client.Object) error {
return d.client.Delete(ctx, obj)
}
func (d *Deployer) checkPatchErrors(patch []byte) error {
// CreateThreeWayJSONMergePatch sometimes produces patch with all fields as null
// Tring to apply this patch causes errors so we need to filter it out
var patchMap map[string]map[string]interface{}
err := json.Unmarshal(patch, &patchMap)
if err != nil {
return err
}
nonNilFieldsPresent := false
patchSpec := patchMap["spec"]
for _, value := range patchSpec {
if value != nil {
nonNilFieldsPresent = true
break
}
}
if !nonNilFieldsPresent {
return fmt.Errorf("all fields of patch object are nil")
}
return nil
}
func (d *Deployer) patch(ctx context.Context, modifiedRaw client.Object) error {
modified, ok := modifiedRaw.(metav1.Object)
if !ok {
return fmt.Errorf("unable to save object %s because is not a metav1.Object", modifiedRaw.GetObjectKind().GroupVersionKind().String())
}
gvk := modifiedRaw.GetObjectKind().GroupVersionKind()
modifiedJson, err := json.Marshal(modifiedRaw)
if err != nil {
return err
}
var i rest.Interface
switch gvk.GroupVersion().String() {
case "core/v1", "v1":
i = d.rawClient.CoreV1().RESTClient()
case "apps/v1beta2":
i = d.rawClient.AppsV1beta2().RESTClient()
case "apps/v1":
i = d.rawClient.AppsV1().RESTClient()
case "apps/v1beta1":
i = d.rawClient.AppsV1beta1().RESTClient()
case "networking.k8s.io/v1":
i = d.rawClient.NetworkingV1().RESTClient()
case "storage.k8s.io/v1":
i = d.rawClient.StorageV1().RESTClient()
case "authorization.k8s.io/v":
i = d.rawClient.AuthorizationV1().RESTClient()
case "authentication.k8s.io/v1":
i = d.rawClient.AuthenticationV1().RESTClient()
default:
return fmt.Errorf("Unable to find a REST interface for %s", gvk.String())
}
rsc, _ := apimeta.UnsafeGuessKindToResource(gvk)
originalRaw := modifiedRaw
// avoid reading from cache
err = d.client.Get(ctx, types.NamespacedName{Namespace: modified.GetNamespace(), Name: modified.GetName()}, originalRaw)
if err != nil {
if kerrors.IsNotFound(err) {
return d.client.Create(ctx, modifiedRaw)
}
return err
}
originalJson, err := json.Marshal(originalRaw)
if err != nil {
return err
}
deleteJson, err := d.createDeleteJson(modifiedRaw, originalRaw)
if err != nil {
return err
}
patch, err := jsonmergepatch.CreateThreeWayJSONMergePatch(deleteJson, modifiedJson, originalJson)
if err != nil {
return err
}
patchErrors := d.checkPatchErrors(patch)
if patchErrors == nil {
err = i.Patch(types.MergePatchType).
Namespace(modified.GetNamespace()).
Resource(rsc.Resource).
Name(modified.GetName()).
Body(patch).
Do(ctx).
Into(modifiedRaw)
return err
} else {
d.log.Info(fmt.Sprintf("Patch %s not applied because of errors: %s", string(patch), patchErrors))
}
return nil
}
// createDeleteJson creates a json with potential fields to be removed from the original object
func (d *Deployer) createDeleteJson(modifiedRaw runtime.Object, originalRaw runtime.Object) ([]byte, error) {
original, ok := originalRaw.(metav1.Object)
if !ok {
return nil, fmt.Errorf("unable to cast %s to metav1.Object", originalRaw.GetObjectKind().GroupVersionKind().String())
}
deleteObjectRaw := modifiedRaw.DeepCopyObject()
deleteObject, ok := deleteObjectRaw.(metav1.Object)
if !ok {
return nil, fmt.Errorf("unable to cast %s to metav1.Object", deleteObjectRaw.GetObjectKind().GroupVersionKind().String())
}
// "removable" fields
deleteObject.SetAnnotations(original.GetAnnotations())
deleteObject.SetLabels(original.GetLabels())
return json.Marshal(deleteObject)
}