-
Notifications
You must be signed in to change notification settings - Fork 97
Expand file tree
/
Copy pathsync.go
More file actions
335 lines (289 loc) · 11 KB
/
sync.go
File metadata and controls
335 lines (289 loc) · 11 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
334
335
//
// Copyright (c) 2019-2023 Red Hat, Inc.
// This program and the accompanying materials are made
// available under the terms of the Eclipse Public License 2.0
// which is available at https://www.eclipse.org/legal/epl-2.0/
//
// SPDX-License-Identifier: EPL-2.0
//
// Contributors:
// Red Hat, Inc. - initial API and implementation
//
package deploy
import (
"context"
"fmt"
"reflect"
ctrl "sigs.k8s.io/controller-runtime"
"github.com/eclipse-che/che-operator/pkg/common/chetypes"
"github.com/google/go-cmp/cmp"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
)
var (
syncLog = ctrl.Log.WithName("sync")
)
// Sync syncs the blueprint to the cluster in a generic (as much as Go allows) manner.
// Returns true if object is up-to-date otherwise returns false
func Sync(deployContext *chetypes.DeployContext, blueprint client.Object, diffOpts ...cmp.Option) (bool, error) {
cli := getClientForObject(blueprint.GetNamespace(), deployContext)
return SyncForClient(cli, deployContext, blueprint, diffOpts...)
}
func SyncForClient(cli client.Client, deployContext *chetypes.DeployContext, blueprint client.Object, diffOpts ...cmp.Option) (bool, error) {
runtimeObject, ok := blueprint.(runtime.Object)
if !ok {
return false, fmt.Errorf("object %T is not a runtime.Object. Cannot sync it", runtimeObject)
}
// we will compare this object later with blueprint
// we can't use runtimeObject.DeepCopyObject()
actual, err := deployContext.ClusterAPI.Scheme.New(runtimeObject.GetObjectKind().GroupVersionKind())
if err != nil {
return false, err
}
key := types.NamespacedName{Name: blueprint.GetName(), Namespace: blueprint.GetNamespace()}
exists, err := doGet(context.TODO(), cli, key, actual.(client.Object))
if err != nil {
return false, err
}
// set GroupVersionKind (it might be empty)
actual.GetObjectKind().SetGroupVersionKind(runtimeObject.GetObjectKind().GroupVersionKind())
if !exists {
return doCreate(context.TODO(), cli, deployContext, blueprint, false)
}
return doUpdate(cli, deployContext, actual.(client.Object), blueprint, diffOpts...)
}
// Get gets object.
// Returns true if object exists otherwise returns false.
// Returns error if object cannot be retrieved otherwise returns nil.
func Get(deployContext *chetypes.DeployContext, key client.ObjectKey, actual client.Object) (bool, error) {
cli := getClientForObject(key.Namespace, deployContext)
return doGet(context.TODO(), cli, key, actual)
}
// Get gets object.
// Returns true if object exists otherwise returns false.
// Returns error if object cannot be retrieved otherwise returns nil.
func GetForClient(cli client.Client, key client.ObjectKey, actual client.Object) (bool, error) {
return doGet(context.TODO(), cli, key, actual)
}
// Gets namespaced scope object by name
// Returns true if object exists otherwise returns false.
func GetNamespacedObject(deployContext *chetypes.DeployContext, name string, actual client.Object) (bool, error) {
client := deployContext.ClusterAPI.Client
key := types.NamespacedName{Name: name, Namespace: deployContext.CheCluster.Namespace}
return doGet(context.TODO(), client, key, actual)
}
// Gets cluster scope object by name
// Returns true if object exists otherwise returns false
func GetClusterObject(deployContext *chetypes.DeployContext, name string, actual client.Object) (bool, error) {
client := deployContext.ClusterAPI.NonCachingClient
key := types.NamespacedName{Name: name}
return doGet(context.TODO(), client, key, actual)
}
// CreateIgnoreIfExists creates object.
// Return true if a new object is created or object already exists, otherwise returns false.
// Throws error if object cannot be created otherwise returns nil.
func CreateIgnoreIfExists(deployContext *chetypes.DeployContext, blueprint client.Object) (bool, error) {
cli := getClientForObject(blueprint.GetNamespace(), deployContext)
return doCreate(context.TODO(), cli, deployContext, blueprint, true)
}
// Deletes object.
// Returns true if object deleted or not found otherwise returns false.
func Delete(deployContext *chetypes.DeployContext, key client.ObjectKey, objectMeta client.Object) (bool, error) {
client := getClientForObject(key.Namespace, deployContext)
return DeleteByKeyWithClient(client, key, objectMeta)
}
func DeleteNamespacedObject(deployContext *chetypes.DeployContext, name string, objectMeta client.Object) (bool, error) {
client := deployContext.ClusterAPI.Client
key := types.NamespacedName{Name: name, Namespace: deployContext.CheCluster.Namespace}
return DeleteByKeyWithClient(client, key, objectMeta)
}
func DeleteClusterObject(deployContext *chetypes.DeployContext, name string, objectMeta client.Object) (bool, error) {
client := deployContext.ClusterAPI.NonCachingClient
key := types.NamespacedName{Name: name}
return DeleteByKeyWithClient(client, key, objectMeta)
}
func DeleteByKeyWithClient(cli client.Client, key client.ObjectKey, objectMeta client.Object) (bool, error) {
runtimeObject, ok := objectMeta.(runtime.Object)
if !ok {
return false, fmt.Errorf("object %T is not a runtime.Object. Cannot sync it", runtimeObject)
}
actual := runtimeObject.DeepCopyObject().(client.Object)
exists, err := doGet(context.TODO(), cli, key, actual)
if !exists {
return true, nil
} else if err != nil {
return false, err
}
return doDeleteIgnoreIfNotFound(context.TODO(), cli, actual)
}
func isUpdateUsingDeleteCreate(kind string) bool {
return "Service" == kind || "Ingress" == kind || "Route" == kind || "Job" == kind || "Secret" == kind
}
func setOwnerReferenceIfNeeded(deployContext *chetypes.DeployContext, blueprint metav1.Object) error {
if shouldSetOwnerReferenceForObject(deployContext, blueprint) {
return controllerutil.SetControllerReference(deployContext.CheCluster, blueprint, deployContext.ClusterAPI.Scheme)
}
return nil
}
func shouldSetOwnerReferenceForObject(deployContext *chetypes.DeployContext, blueprint metav1.Object) bool {
// empty workspace (cluster scope object) or object in another namespace
return blueprint.GetNamespace() == deployContext.CheCluster.Namespace
}
func getClientForObject(objectNamespace string, deployContext *chetypes.DeployContext) client.Client {
// empty namespace (cluster scope object) or object in another namespace
if deployContext.CheCluster.Namespace == objectNamespace {
return deployContext.ClusterAPI.Client
}
return deployContext.ClusterAPI.NonCachingClient
}
func GetObjectType(obj interface{}) string {
objType := reflect.TypeOf(obj).String()
if reflect.TypeOf(obj).Kind().String() == "ptr" {
objType = objType[1:]
}
return objType
}
// DeleteIgnoreIfNotFound deletes object.
// Returns nil if object deleted or not found otherwise returns error.
// Return error if object cannot be deleted otherwise returns nil.
func DeleteIgnoreIfNotFound(
context context.Context,
cli client.Client,
key client.ObjectKey,
blueprint client.Object,
) error {
runtimeObj, ok := blueprint.(runtime.Object)
if !ok {
return fmt.Errorf("object %T is not a runtime.Object. Cannot sync it", runtimeObj)
}
actual := runtimeObj.DeepCopyObject().(client.Object)
exists, err := doGet(context, cli, key, actual)
if exists {
_, err := doDeleteIgnoreIfNotFound(context, cli, actual)
return err
}
return err
}
func GetLabelsAndAnnotationsComparator(
ensuredLabels []string,
ensuredAnnotations []string) cmp.Option {
return cmp.Comparer(func(x, y metav1.ObjectMeta) bool {
for _, label := range ensuredLabels {
if x.Labels[label] != y.Labels[label] {
return false
}
}
for _, annotation := range ensuredAnnotations {
if x.Annotations[annotation] != y.Annotations[annotation] {
return false
}
}
return true
})
}
// doCreate creates object.
// Return error if object cannot be created otherwise returns nil.
func doCreate(
context context.Context,
client client.Client,
deployContext *chetypes.DeployContext,
blueprint client.Object,
returnTrueIfAlreadyExists bool,
) (bool, error) {
err := setOwnerReferenceIfNeeded(deployContext, blueprint)
if err != nil {
return false, err
}
err = client.Create(context, blueprint)
if err == nil {
syncLog.Info("Object created", "namespace", blueprint.GetNamespace(), "kind", GetObjectType(blueprint), "name", blueprint.GetName())
return true, nil
} else if errors.IsAlreadyExists(err) {
return returnTrueIfAlreadyExists, nil
} else {
return false, err
}
}
// doDeleteIgnoreIfNotFound deletes object.
// Returns true if object deleted or not found otherwise returns false.
// Returns error if object cannot be deleted otherwise returns nil.
func doDeleteIgnoreIfNotFound(
context context.Context,
cli client.Client,
actual client.Object,
) (bool, error) {
err := cli.Delete(context, actual)
if err == nil {
if errors.IsNotFound(err) {
syncLog.Info("Object not found", "namespace", actual.GetNamespace(), "kind", GetObjectType(actual), "name", actual.GetName())
} else {
syncLog.Info("Object deleted", "namespace", actual.GetNamespace(), "kind", GetObjectType(actual), "name", actual.GetName())
}
return true, nil
} else {
return false, err
}
}
// doGet gets object.
// Returns true if object exists otherwise returns false.
// Returns error if object cannot be retrieved otherwise returns nil.
func doGet(
context context.Context,
cli client.Client,
key client.ObjectKey,
object client.Object,
) (bool, error) {
err := cli.Get(context, key, object)
if err == nil {
return true, nil
} else if errors.IsNotFound(err) {
return false, nil
} else {
return false, err
}
}
// doUpdate updates object.
// Returns true if object is up-to-date otherwise return false
func doUpdate(
cli client.Client,
deployContext *chetypes.DeployContext,
actual client.Object,
blueprint client.Object,
diffOpts ...cmp.Option,
) (bool, error) {
actualMeta, ok := actual.(metav1.Object)
if !ok {
return false, fmt.Errorf("object %T is not a metav1.Object. Cannot sync it", actualMeta)
}
diff := cmp.Diff(actual, blueprint, diffOpts...)
if len(diff) > 0 {
// don't print difference if there are no diffOpts mainly to avoid huge output
if len(diffOpts) != 0 {
fmt.Printf("Difference:\n%s", diff)
}
if isUpdateUsingDeleteCreate(actual.GetObjectKind().GroupVersionKind().Kind) {
done, err := doDeleteIgnoreIfNotFound(context.TODO(), cli, actual)
if !done {
return false, err
}
return doCreate(context.TODO(), cli, deployContext, blueprint, false)
} else {
err := setOwnerReferenceIfNeeded(deployContext, blueprint)
if err != nil {
return false, err
}
// to be able to update, we need to set the resource version of the object that we know of
blueprint.(metav1.Object).SetResourceVersion(actualMeta.GetResourceVersion())
err = cli.Update(context.TODO(), blueprint)
if err == nil {
syncLog.Info("Object updated", "namespace", actual.GetNamespace(), "kind", GetObjectType(actual), "name", actual.GetName())
}
return false, err
}
}
return true, nil
}