-
Notifications
You must be signed in to change notification settings - Fork 20
/
gc.go
346 lines (300 loc) · 12.9 KB
/
gc.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
/*
Copyright 2019 The Multicluster-Controller Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package gc
import (
"context"
"fmt"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/rest"
"sigs.k8s.io/controller-runtime/pkg/client"
"admiralty.io/multicluster-controller/pkg/cluster"
"admiralty.io/multicluster-controller/pkg/controller"
"admiralty.io/multicluster-controller/pkg/patterns"
"admiralty.io/multicluster-controller/pkg/reconcile"
"admiralty.io/multicluster-controller/pkg/reference"
)
var (
LabelParentUID = "multicluster.admiralty.io/parent-uid"
)
func NewController(ctx context.Context, parentClusters []*cluster.Cluster, childClusters []*cluster.Cluster, o Options) (*controller.Controller, error) {
r := &reconciler{Options: o}
parentGVKs, _, err := parentClusters[0].GetScheme().ObjectKinds(r.ParentPrototype)
if err != nil {
return nil, fmt.Errorf("getting GVKs for parent prototype: %v", err)
}
if len(parentGVKs) != 1 {
return nil, fmt.Errorf("parent cluster scheme has %d GVK(s) for parent prototype when 1 is expected")
}
r.parentGVK = parentGVKs[0]
childGVKs, _, err := childClusters[0].GetScheme().ObjectKinds(r.ChildPrototype)
if err != nil {
return nil, fmt.Errorf("getting GVKs for child prototype: %v", err)
}
if len(childGVKs) != 1 {
return nil, fmt.Errorf("child cluster scheme has %d GVK(s) for child prototype when 1 is expected")
}
r.childGVK = childGVKs[0]
co := controller.New(r, controller.Options{})
r.parentClients = make(map[string]client.Client, len(parentClusters))
for _, clu := range parentClusters {
cli, err := clu.GetDelegatingClient()
if err != nil {
return nil, fmt.Errorf("getting delegating client for parent cluster: %v", err)
}
r.parentClients[clu.Name] = cli
if err := co.WatchResourceReconcileObject(ctx, clu, r.ParentPrototype, r.ParentWatchOptions); err != nil {
return nil, fmt.Errorf("setting up watch for %s: %v", r.parentResourceErrorString(clu.Name), err)
}
}
r.childClients = make(map[string]client.Client, len(childClusters))
for _, clu := range childClusters {
cli, err := clu.GetDelegatingClient()
if err != nil {
return nil, fmt.Errorf("getting delegating client for child cluster: %v", err)
}
r.childClients[clu.Name] = cli
if err := co.WatchResourceReconcileController(ctx, clu, r.ChildPrototype, controller.WatchOptions{Namespace: r.ChildNamespace}); err != nil {
return nil, fmt.Errorf("setting up watch for %s: %v", r.childResourceErrorString(clu.Name), err)
}
}
r.childWriters = make(map[string]map[string]client.Client, len(parentClusters))
for _, p := range parentClusters {
r.childWriters[p.Name] = make(map[string]client.Client, len(childClusters))
for _, c := range childClusters {
if o.GetImpersonatorForChildWriter != nil {
cfg := rest.CopyConfig(c.Config)
cfg.Impersonate = rest.ImpersonationConfig{
UserName: r.GetImpersonatorForChildWriter(p.Name),
}
cli, err := client.New(cfg, client.Options{})
if err != nil {
return nil, err
}
r.childWriters[p.Name][c.Name] = cli
} else {
r.childWriters[p.Name][c.Name] = r.childClients[c.Name]
}
}
}
if r.MakeSelector == nil {
r.MakeSelector = r.defaultMakeSelector
}
return co, nil
}
type Options struct {
ParentPrototype runtime.Object
ChildPrototype runtime.Object
ParentWatchOptions controller.WatchOptions
ChildNamespace string // optional, can optimize List operations vs. it only be set in MakeChild
Applier Applier
CopyLabels bool
MakeSelector func(parent interface{}) labels.Set // optional
MakeExpectedChildWhenFound bool
GetImpersonatorForChildWriter func(clusterName string) string
}
type reconciler struct {
parentClients map[string]client.Client
childClients map[string]client.Client
childWriters map[string]map[string]client.Client
parentGVK schema.GroupVersionKind
childGVK schema.GroupVersionKind
Options
}
func (r *reconciler) defaultMakeSelector(parent interface{}) labels.Set {
parentMeta := parent.(metav1.Object)
s := labels.Set{LabelParentUID: string(parentMeta.GetUID())}
return s
}
func (r *reconciler) Reconcile(req reconcile.Request) (reconcile.Result, error) {
// filter out requests enqueued for children whose parents are in a different cluster
// TODO move this upstream to an option or variation of WatchResourceReconcileController
parentClusterName := req.Context
_, ok := r.parentClients[parentClusterName]
if !ok {
return reconcile.Result{}, nil
}
parent := r.ParentPrototype.DeepCopyObject()
child := r.ChildPrototype.DeepCopyObject()
expectedChild := r.ChildPrototype.DeepCopyObject()
parentMeta := parent.(metav1.Object)
childMeta := child.(metav1.Object)
expectedChildMeta := child.(metav1.Object)
if err := r.parentClients[parentClusterName].Get(context.Background(), req.NamespacedName, parent); err != nil {
if !errors.IsNotFound(err) {
return reconcile.Result{}, fmt.Errorf("cannot get %s: %v",
r.parentObjectErrorString(req.Name, req.Namespace, parentClusterName), err)
}
return reconcile.Result{}, nil
}
parentMeta.SetClusterName(parentClusterName) // used by
childClusterName, err := r.Applier.ChildClusterName(parent)
if err != nil {
return reconcile.Result{}, fmt.Errorf("cannot get child cluster name for %s: %v",
r.parentObjectErrorString(req.Name, req.Namespace, parentClusterName), err)
}
childFound := true
if err := r.getChild(parent, child, childClusterName); err != nil {
if !IsChildNotFoundErr(err) {
// TODO? consider ignoring errors, so we remove finalizers if child cluster is disconnected
return reconcile.Result{}, fmt.Errorf("cannot get child object of %s: %v",
r.parentObjectErrorString(req.Name, req.Namespace, parentClusterName), err)
}
childFound = false
}
needUpdate, needStatusUpdate, err := r.Applier.MutateParent(parent, childFound, child)
if err != nil {
return reconcile.Result{}, fmt.Errorf("cannot mutate or determine whether %s needs update: %v",
r.parentObjectErrorString(req.Name, req.Namespace, parentClusterName), err)
}
if needUpdate {
if err := r.parentClients[parentClusterName].Update(context.Background(), parent); err != nil {
if patterns.IsOptimisticLockError(err) {
return reconcile.Result{}, nil
} else {
return reconcile.Result{}, fmt.Errorf("cannot update %s: %v",
r.parentObjectErrorString(parentMeta.GetName(), parentMeta.GetNamespace(), parentClusterName), err)
}
}
}
if needStatusUpdate {
if err := r.parentClients[parentClusterName].Status().Update(context.Background(), parent); err != nil {
if patterns.IsOptimisticLockError(err) {
return reconcile.Result{}, nil
} else {
return reconcile.Result{}, fmt.Errorf("cannot update status of %s: %v",
r.parentObjectErrorString(parentMeta.GetName(), parentMeta.GetNamespace(), parentClusterName), err)
}
}
}
parentTerminating := parentMeta.GetDeletionTimestamp() != nil
finalizers := parentMeta.GetFinalizers()
j := -1
for i, f := range finalizers {
if f == "multicluster.admiralty.io/multiclusterForegroundDeletion" {
j = i
break
}
}
parentHasFinalizer := j > -1
if parentTerminating {
if childFound {
if err := r.childWriters[parentClusterName][childClusterName].Delete(context.Background(), child); err != nil && !errors.IsNotFound(err) {
return reconcile.Result{}, fmt.Errorf("cannot delete %s: %v",
r.childObjectErrorString(childMeta.GetName(), childMeta.GetNamespace(), childClusterName), err)
}
} else if parentHasFinalizer {
// remove finalizer
parentMeta.SetFinalizers(append(finalizers[:j], finalizers[j+1:]...))
if err := r.parentClients[parentClusterName].Update(context.Background(), parent); err != nil && !patterns.IsOptimisticLockError(err) {
return reconcile.Result{}, fmt.Errorf("cannot remove finalizer from %s: %v",
r.parentObjectErrorString(parentMeta.GetName(), parentMeta.GetNamespace(), parentClusterName), err)
}
}
} else {
if !parentHasFinalizer {
parentMeta.SetFinalizers(append(finalizers, "multicluster.admiralty.io/multiclusterForegroundDeletion"))
if err := r.parentClients[parentClusterName].Update(context.Background(), parent); err != nil && !patterns.IsOptimisticLockError(err) {
return reconcile.Result{}, fmt.Errorf("cannot add finalizer to %s: %v",
r.parentObjectErrorString(parentMeta.GetName(), parentMeta.GetNamespace(), parentClusterName), err)
}
} else {
if !childFound || r.MakeExpectedChildWhenFound {
if err := r.makeChildWrapper(parent, expectedChild); err != nil {
return reconcile.Result{}, fmt.Errorf("cannot make child from %s: %v",
r.parentObjectErrorString(parentMeta.GetName(), parentMeta.GetNamespace(), parentClusterName), err)
}
}
if !childFound {
if err := r.childWriters[parentClusterName][childClusterName].Create(context.Background(), expectedChild); err != nil && !errors.IsAlreadyExists(err) {
return reconcile.Result{}, fmt.Errorf("cannot create %s: %v",
r.childObjectErrorString(expectedChildMeta.GetName(), expectedChildMeta.GetNamespace(), childClusterName), err)
}
} else {
needUpdate, err := r.Applier.MutateChild(parent, child, expectedChild)
if err != nil {
return reconcile.Result{}, fmt.Errorf("cannot mutate or determine whether %s needs update: %v",
r.childObjectErrorString(childMeta.GetName(), childMeta.GetNamespace(), childClusterName), err)
}
if needUpdate {
if err := r.childWriters[parentClusterName][childClusterName].Update(context.Background(), child); err != nil && !patterns.IsOptimisticLockError(err) {
return reconcile.Result{}, fmt.Errorf("cannot update %s: %v",
r.childObjectErrorString(childMeta.GetName(), childMeta.GetNamespace(), childClusterName), err)
}
}
}
}
}
return reconcile.Result{}, nil
}
func (r *reconciler) getChild(parent runtime.Object, child runtime.Object, childClusterName string) error {
childList := &unstructured.UnstructuredList{}
childList.SetGroupVersionKind(r.childGVK)
s := labels.SelectorFromValidatedSet(r.MakeSelector(parent))
err := r.childClients[childClusterName].List(context.Background(), childList, client.InNamespace(r.ChildNamespace), client.MatchingLabelsSelector{Selector: s})
if err != nil {
return fmt.Errorf("cannot list %s with label selector %s: %v", r.childResourceErrorString(childClusterName), s, err)
}
if len(childList.Items) == 0 {
return r.ChildNotFoundErr(childClusterName, s)
} else if len(childList.Items) > 1 {
return r.DuplicateChildErr(childClusterName, s)
}
if err := runtime.DefaultUnstructuredConverter.FromUnstructured(childList.Items[0].Object, child); err != nil {
panic(err)
}
childMeta := child.(metav1.Object)
childMeta.SetClusterName(childClusterName)
return nil
}
func (r *reconciler) makeChildWrapper(parent runtime.Object, expectedChild runtime.Object) error {
parentMeta := parent.(metav1.Object)
expectedChildMeta := expectedChild.(metav1.Object)
if err := r.Applier.MakeChild(parent, expectedChild); err != nil {
return err
}
if r.ChildNamespace != "" {
expectedChildMeta.SetNamespace(r.ChildNamespace)
}
// we use generate name instead of clusterName-namespace-name combinations to avoid (unlikely) conflicts such as:
// namespace=foo-bar, name=baz vs. namespace=foo, name=bar-baz
expectedChildMeta.SetGenerateName(parentMeta.GetName() + "-")
l := expectedChildMeta.GetLabels()
if l == nil {
l = make(labels.Set)
}
for k, v := range r.MakeSelector(parent) {
l[k] = v
}
if r.CopyLabels {
for k, v := range parentMeta.GetLabels() {
l[k] = v
}
}
expectedChildMeta.SetLabels(l)
ref := reference.NewMulticlusterOwnerReference(parentMeta, r.parentGVK, parentMeta.GetClusterName())
if err := reference.SetMulticlusterControllerReference(expectedChildMeta, ref); err != nil {
return fmt.Errorf("cannot set multi-cluster controller reference: %v", err)
}
return nil
}
type Applier interface {
ChildClusterName(parent interface{}) (string, error)
MakeChild(parent interface{}, expectedChild interface{}) error
MutateChild(parent interface{}, child interface{}, expectedChild interface{}) (needUpdate bool, err error)
MutateParent(parent interface{}, childFound bool, child interface{}) (needUpdate bool, needStatusUpdate bool, err error)
}