-
Notifications
You must be signed in to change notification settings - Fork 459
Expand file tree
/
Copy pathapibinding_controller.go
More file actions
574 lines (501 loc) · 23.2 KB
/
Copy pathapibinding_controller.go
File metadata and controls
574 lines (501 loc) · 23.2 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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
/*
Copyright 2022 The kcp 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 apibinding
import (
"context"
"encoding/json"
"fmt"
"time"
"github.com/go-logr/logr"
"k8s.io/apiextensions-apiserver/pkg/apihelpers"
apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/types"
utilerrors "k8s.io/apimachinery/pkg/util/errors"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/util/workqueue"
"k8s.io/klog/v2"
kcpcache "github.com/kcp-dev/apimachinery/v2/pkg/cache"
kcpapiextensionsclientset "github.com/kcp-dev/client-go/apiextensions/client"
kcpapiextensionsv1informers "github.com/kcp-dev/client-go/apiextensions/informers/apiextensions/v1"
"github.com/kcp-dev/logicalcluster/v3"
apisv1alpha1 "github.com/kcp-dev/sdk/apis/apis/v1alpha1"
apisv1alpha2 "github.com/kcp-dev/sdk/apis/apis/v1alpha2"
"github.com/kcp-dev/sdk/apis/core"
corev1alpha1 "github.com/kcp-dev/sdk/apis/core/v1alpha1"
kcpclientset "github.com/kcp-dev/sdk/client/clientset/versioned/cluster"
apisv1alpha2client "github.com/kcp-dev/sdk/client/clientset/versioned/typed/apis/v1alpha2"
apisv1alpha1informers "github.com/kcp-dev/sdk/client/informers/externalversions/apis/v1alpha1"
apisv1alpha2informers "github.com/kcp-dev/sdk/client/informers/externalversions/apis/v1alpha2"
corev1alpha1informers "github.com/kcp-dev/sdk/client/informers/externalversions/core/v1alpha1"
apisv1alpha1listers "github.com/kcp-dev/sdk/client/listers/apis/v1alpha1"
"github.com/kcp-dev/kcp/pkg/indexers"
"github.com/kcp-dev/kcp/pkg/informer"
"github.com/kcp-dev/kcp/pkg/logging"
"github.com/kcp-dev/kcp/pkg/reconciler/committer"
"github.com/kcp-dev/kcp/pkg/reconciler/events"
"github.com/kcp-dev/kcp/pkg/tombstone"
)
const (
ControllerName = "kcp-apibinding"
)
var (
SystemBoundCRDsClusterName = logicalcluster.Name("system:bound-crds")
)
// NewController returns a new controller for APIBindings.
func NewController(
crdClusterClient kcpapiextensionsclientset.ClusterInterface,
kcpClusterClient kcpclientset.ClusterInterface,
apiBindingInformer apisv1alpha2informers.APIBindingClusterInformer,
apiExportInformer apisv1alpha2informers.APIExportClusterInformer,
apiResourceSchemaInformer apisv1alpha1informers.APIResourceSchemaClusterInformer,
apiConversionInformer apisv1alpha1informers.APIConversionClusterInformer,
logicalClusterInformer corev1alpha1informers.LogicalClusterClusterInformer,
globalAPIExportInformer apisv1alpha2informers.APIExportClusterInformer,
globalAPIResourceSchemaInformer apisv1alpha1informers.APIResourceSchemaClusterInformer,
globalAPIConversionInformer apisv1alpha1informers.APIConversionClusterInformer,
crdInformer kcpapiextensionsv1informers.CustomResourceDefinitionClusterInformer,
) (*controller, error) {
c := &controller{
queue: workqueue.NewTypedRateLimitingQueueWithConfig(
workqueue.DefaultTypedControllerRateLimiter[string](),
workqueue.TypedRateLimitingQueueConfig[string]{
Name: ControllerName,
},
),
crdClusterClient: crdClusterClient,
kcpClusterClient: kcpClusterClient,
listAPIBindings: func(clusterName logicalcluster.Name) ([]*apisv1alpha2.APIBinding, error) {
return apiBindingInformer.Lister().Cluster(clusterName).List(labels.Everything())
},
listAPIBindingsByAPIExport: func(export *apisv1alpha2.APIExport) ([]*apisv1alpha2.APIBinding, error) {
// binding keys by full path
keys := sets.New[string]()
if path := logicalcluster.NewPath(export.Annotations[core.LogicalClusterPathAnnotationKey]); !path.Empty() {
pathKeys, err := apiBindingInformer.Informer().GetIndexer().IndexKeys(indexers.APIBindingsByAPIExport, path.Join(export.Name).String())
if err != nil {
return nil, err
}
keys.Insert(pathKeys...)
}
clusterKeys, err := apiBindingInformer.Informer().GetIndexer().IndexKeys(indexers.APIBindingsByAPIExport, logicalcluster.From(export).Path().Join(export.Name).String())
if err != nil {
return nil, err
}
keys.Insert(clusterKeys...)
bindings := make([]*apisv1alpha2.APIBinding, 0, keys.Len())
for _, key := range sets.List[string](keys) {
binding, exists, err := apiBindingInformer.Informer().GetIndexer().GetByKey(key)
if err != nil {
utilruntime.HandleError(err)
continue
} else if !exists {
utilruntime.HandleError(fmt.Errorf("APIBinding %q does not exist", key))
continue
}
bindings = append(bindings, binding.(*apisv1alpha2.APIBinding))
}
return bindings, nil
},
getAPIBinding: func(clusterName logicalcluster.Name, name string) (*apisv1alpha2.APIBinding, error) {
return apiBindingInformer.Lister().Cluster(clusterName).Get(name)
},
getAPIExportByPath: func(path logicalcluster.Path, name string) (*apisv1alpha2.APIExport, error) {
return indexers.ByPathAndNameWithFallback[*apisv1alpha2.APIExport](apisv1alpha2.Resource("apiexports"), apiExportInformer.Informer().GetIndexer(), globalAPIExportInformer.Informer().GetIndexer(), path, name)
},
getAPIExportsBySchema: func(schema *apisv1alpha1.APIResourceSchema) ([]*apisv1alpha2.APIExport, error) {
key, err := kcpcache.DeletionHandlingMetaClusterNamespaceKeyFunc(schema)
if err != nil {
return nil, err
}
return indexers.ByIndexWithFallback[*apisv1alpha2.APIExport](apiExportInformer.Informer().GetIndexer(), globalAPIExportInformer.Informer().GetIndexer(), indexers.APIExportByAPIResourceSchema, key)
},
getAPIExportsByIdentity: func(identityHash string) ([]*apisv1alpha2.APIExport, error) {
return indexers.ByIndexWithFallback[*apisv1alpha2.APIExport](apiExportInformer.Informer().GetIndexer(), globalAPIExportInformer.Informer().GetIndexer(), indexers.APIExportByIdentity, identityHash)
},
getAPIResourceSchema: informer.NewScopedGetterWithFallback[*apisv1alpha1.APIResourceSchema, apisv1alpha1listers.APIResourceSchemaLister](apiResourceSchemaInformer.Lister(), globalAPIResourceSchemaInformer.Lister()),
getAPIConversion: informer.NewScopedGetterWithFallback[*apisv1alpha1.APIConversion, apisv1alpha1listers.APIConversionLister](apiConversionInformer.Lister(), globalAPIConversionInformer.Lister()),
createCRD: func(ctx context.Context, clusterName logicalcluster.Path, crd *apiextensionsv1.CustomResourceDefinition) (*apiextensionsv1.CustomResourceDefinition, error) {
return crdClusterClient.Cluster(clusterName).ApiextensionsV1().CustomResourceDefinitions().Create(ctx, crd, metav1.CreateOptions{})
},
getCRD: func(clusterName logicalcluster.Name, name string) (*apiextensionsv1.CustomResourceDefinition, error) {
return crdInformer.Lister().Cluster(clusterName).Get(name)
},
listCRDs: func(clusterName logicalcluster.Name) ([]*apiextensionsv1.CustomResourceDefinition, error) {
return crdInformer.Lister().Cluster(clusterName).List(labels.Everything())
},
getLogicalCluster: func(name logicalcluster.Name) (*corev1alpha1.LogicalCluster, error) {
return logicalClusterInformer.Lister().Cluster(name).Get(corev1alpha1.LogicalClusterName)
},
updateLogicalCluster: func(ctx context.Context, lc *corev1alpha1.LogicalCluster) error {
patchObj := &corev1alpha1.LogicalCluster{
TypeMeta: metav1.TypeMeta{
APIVersion: corev1alpha1.SchemeGroupVersion.String(),
Kind: "LogicalCluster",
},
ObjectMeta: metav1.ObjectMeta{
Name: lc.Name,
Annotations: map[string]string{
LocksBindingsAnnotationKey: lc.Annotations[LocksBindingsAnnotationKey],
},
},
}
patchBytes, err := json.Marshal(patchObj)
if err != nil {
return err
}
_, err = kcpClusterClient.CoreV1alpha1().LogicalClusters().Cluster(logicalcluster.From(lc).Path()).Patch(
ctx,
lc.Name,
types.ApplyPatchType,
patchBytes,
metav1.PatchOptions{
FieldManager: FieldManagerBindings,
// Force is not needed because each writer uses its own annotation key
},
)
return err
},
deletedCRDTracker: newLockedStringSet(),
commit: committer.NewSSACommitter[*APIBinding, Patcher, *APIBindingSpec, *APIBindingStatus](
kcpClusterClient.ApisV1alpha2().APIBindings(),
ControllerName,
)}
logger := logging.WithReconciler(klog.Background(), ControllerName)
// APIBinding handlers
_, _ = apiBindingInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
c.enqueueAPIBinding(tombstone.Obj[*apisv1alpha2.APIBinding](obj), logger, "")
},
UpdateFunc: func(_, obj interface{}) {
c.enqueueAPIBinding(tombstone.Obj[*apisv1alpha2.APIBinding](obj), logger, "")
},
DeleteFunc: func(obj interface{}) {
c.enqueueAPIBinding(tombstone.Obj[*apisv1alpha2.APIBinding](obj), logger, "")
},
})
// CRD handlers
_, _ = crdInformer.Informer().AddEventHandler(events.WithoutSyncs(cache.FilteringResourceEventHandler{
FilterFunc: func(obj interface{}) bool {
crd := obj.(*apiextensionsv1.CustomResourceDefinition)
return logicalcluster.From(crd) == SystemBoundCRDsClusterName
},
Handler: cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
c.enqueueCRD(tombstone.Obj[*apiextensionsv1.CustomResourceDefinition](obj), logger)
},
UpdateFunc: func(_, obj interface{}) {
c.enqueueCRD(tombstone.Obj[*apiextensionsv1.CustomResourceDefinition](obj), logger)
},
DeleteFunc: func(obj interface{}) {
crd := tombstone.Obj[*apiextensionsv1.CustomResourceDefinition](obj)
// If something deletes one of our bound CRDs, we need to keep track of it so when we're reconciling,
// we know we need to recreate it. This set is there to fight against stale informers still seeing
// the deleted CRD.
c.deletedCRDTracker.Add(crd.Name)
c.enqueueCRD(crd, logger)
},
},
}))
// APIExport handlers
_, _ = apiExportInformer.Informer().AddEventHandler(events.WithoutSyncs(cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
c.enqueueAPIExport(tombstone.Obj[*apisv1alpha2.APIExport](obj), logger, "")
},
UpdateFunc: func(_, obj interface{}) {
c.enqueueAPIExport(tombstone.Obj[*apisv1alpha2.APIExport](obj), logger, "")
},
DeleteFunc: func(obj interface{}) {
c.enqueueAPIExport(tombstone.Obj[*apisv1alpha2.APIExport](obj), logger, "")
},
}))
_, _ = globalAPIExportInformer.Informer().AddEventHandler(events.WithoutSyncs(cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
c.enqueueAPIExport(tombstone.Obj[*apisv1alpha2.APIExport](obj), logger, "")
},
UpdateFunc: func(_, obj interface{}) {
c.enqueueAPIExport(tombstone.Obj[*apisv1alpha2.APIExport](obj), logger, "")
},
DeleteFunc: func(obj interface{}) {
c.enqueueAPIExport(tombstone.Obj[*apisv1alpha2.APIExport](obj), logger, "")
},
}))
// APIResourceSchema handlers
_, _ = apiResourceSchemaInformer.Informer().AddEventHandler(events.WithoutSyncs(cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
c.enqueueAPIResourceSchema(tombstone.Obj[*apisv1alpha1.APIResourceSchema](obj), logger, "")
},
UpdateFunc: func(_, obj interface{}) {
c.enqueueAPIResourceSchema(tombstone.Obj[*apisv1alpha1.APIResourceSchema](obj), logger, "")
},
DeleteFunc: func(obj interface{}) {
c.enqueueAPIResourceSchema(tombstone.Obj[*apisv1alpha1.APIResourceSchema](obj), logger, "")
},
}))
_, _ = globalAPIResourceSchemaInformer.Informer().AddEventHandler(events.WithoutSyncs(cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
c.enqueueAPIResourceSchema(tombstone.Obj[*apisv1alpha1.APIResourceSchema](obj), logger, "")
},
UpdateFunc: func(_, obj interface{}) {
c.enqueueAPIResourceSchema(tombstone.Obj[*apisv1alpha1.APIResourceSchema](obj), logger, "")
},
DeleteFunc: func(obj interface{}) {
c.enqueueAPIResourceSchema(tombstone.Obj[*apisv1alpha1.APIResourceSchema](obj), logger, "")
},
}))
// LogicalCluster handlers
_, _ = logicalClusterInformer.Informer().AddEventHandler(events.WithoutSyncs(cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
c.enqueueLogicalCluster(tombstone.Obj[*corev1alpha1.LogicalCluster](obj), logger, "")
},
UpdateFunc: func(old, obj interface{}) {
oldLC := old.(*corev1alpha1.LogicalCluster)
newLC := obj.(*corev1alpha1.LogicalCluster)
for _, key := range []string{LocksBindingsAnnotationKey, LocksCRDsAnnotationKey, LocksPendingAnnotationKey} {
if oldLC.Annotations[key] != newLC.Annotations[key] {
c.enqueueLogicalCluster(tombstone.Obj[*corev1alpha1.LogicalCluster](obj), logger, "")
return
}
}
},
}))
// APIConversion handlers
_, _ = apiConversionInformer.Informer().AddEventHandler(events.WithoutSyncs(cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
c.enqueueAPIConversion(tombstone.Obj[*apisv1alpha1.APIConversion](obj), logger)
},
UpdateFunc: func(_, obj interface{}) {
c.enqueueAPIConversion(tombstone.Obj[*apisv1alpha1.APIConversion](obj), logger)
},
DeleteFunc: func(obj interface{}) {
c.enqueueAPIConversion(tombstone.Obj[*apisv1alpha1.APIConversion](obj), logger)
},
}))
return c, nil
}
type APIBinding = apisv1alpha2.APIBinding
type APIBindingSpec = apisv1alpha2.APIBindingSpec
type APIBindingStatus = apisv1alpha2.APIBindingStatus
type Patcher = apisv1alpha2client.APIBindingInterface
type Resource = committer.Resource[*APIBindingSpec, *APIBindingStatus]
type CommitFunc = func(context.Context, *Resource, *Resource) error
// controller reconciles APIBindings. It creates and maintains CRDs associated with APIResourceSchemas that are
// referenced from APIBindings. It also watches CRDs, APIResourceSchemas, and APIExports to ensure whenever
// objects related to an APIBinding are updated, the APIBinding is reconciled.
type controller struct {
queue workqueue.TypedRateLimitingInterface[string]
crdClusterClient kcpapiextensionsclientset.ClusterInterface
kcpClusterClient kcpclientset.ClusterInterface
listAPIBindings func(clusterName logicalcluster.Name) ([]*apisv1alpha2.APIBinding, error)
listAPIBindingsByAPIExport func(apiExport *apisv1alpha2.APIExport) ([]*apisv1alpha2.APIBinding, error)
getAPIBinding func(clusterName logicalcluster.Name, name string) (*apisv1alpha2.APIBinding, error)
getAPIExportByPath func(path logicalcluster.Path, name string) (*apisv1alpha2.APIExport, error)
getAPIExportsBySchema func(schema *apisv1alpha1.APIResourceSchema) ([]*apisv1alpha2.APIExport, error)
getAPIExportsByIdentity func(identityHash string) ([]*apisv1alpha2.APIExport, error)
getAPIResourceSchema func(clusterName logicalcluster.Name, name string) (*apisv1alpha1.APIResourceSchema, error)
getAPIConversion func(clusterName logicalcluster.Name, name string) (*apisv1alpha1.APIConversion, error)
createCRD func(ctx context.Context, clusterName logicalcluster.Path, crd *apiextensionsv1.CustomResourceDefinition) (*apiextensionsv1.CustomResourceDefinition, error)
getCRD func(clusterName logicalcluster.Name, name string) (*apiextensionsv1.CustomResourceDefinition, error)
listCRDs func(clusterName logicalcluster.Name) ([]*apiextensionsv1.CustomResourceDefinition, error)
getLogicalCluster func(logicalcluster.Name) (*corev1alpha1.LogicalCluster, error)
updateLogicalCluster func(context.Context, *corev1alpha1.LogicalCluster) error
deletedCRDTracker *lockedStringSet
commit CommitFunc
}
// enqueueAPIBinding enqueues an APIBinding .
func (c *controller) enqueueAPIBinding(apiBinding *apisv1alpha2.APIBinding, logger logr.Logger, logSuffix string) {
key, err := kcpcache.DeletionHandlingMetaClusterNamespaceKeyFunc(apiBinding)
if err != nil {
utilruntime.HandleError(err)
return
}
logging.WithQueueKey(logger, key).V(4).Info(fmt.Sprintf("queueing APIBinding%s", logSuffix))
c.queue.Add(key)
}
// enqueueAPIExport enqueues maps an APIExport to APIBindings for enqueuing.
func (c *controller) enqueueAPIExport(export *apisv1alpha2.APIExport, logger logr.Logger, logSuffix string) {
bindings, err := c.listAPIBindingsByAPIExport(export)
if err != nil {
utilruntime.HandleError(err)
return
}
for _, binding := range bindings {
c.enqueueAPIBinding(binding, logging.WithObject(logger, export), fmt.Sprintf(" because of APIExport%s", logSuffix))
}
}
// enqueueCRD maps a CRD to APIResourceSchema for enqueuing.
func (c *controller) enqueueCRD(crd *apiextensionsv1.CustomResourceDefinition, logger logr.Logger) {
logger = logging.WithObject(logger, crd).WithValues(
"groupResource", fmt.Sprintf("%s.%s", crd.Spec.Names.Plural, crd.Spec.Group),
"established", apihelpers.IsCRDConditionTrue(crd, apiextensionsv1.Established),
)
if crd.Annotations[apisv1alpha1.AnnotationSchemaClusterKey] == "" || crd.Annotations[apisv1alpha1.AnnotationSchemaNameKey] == "" {
logger.V(4).Info("skipping CRD because does not belong to an APIResourceSchema")
return
}
clusterName := logicalcluster.Name(crd.Annotations[apisv1alpha1.AnnotationSchemaClusterKey])
apiResourceSchema, err := c.getAPIResourceSchema(clusterName, crd.Annotations[apisv1alpha1.AnnotationSchemaNameKey])
if err != nil {
utilruntime.HandleError(err)
return
}
// this log here is kind of redundant normally. But we are seeing missing CRD update events
// and hence stale APIBindings. So this might help to understand what's going on.
logger.V(4).Info("queueing APIResourceSchema because of CRD", "key", kcpcache.ToClusterAwareKey(clusterName.String(), "", apiResourceSchema.Name))
c.enqueueAPIResourceSchema(apiResourceSchema, logger, " because of CRD")
}
// enqueueAPIResourceSchema maps an APIResourceSchema to APIExports for enqueuing.
func (c *controller) enqueueAPIResourceSchema(schema *apisv1alpha1.APIResourceSchema, logger logr.Logger, logSuffix string) {
apiExports, err := c.getAPIExportsBySchema(schema)
if err != nil {
utilruntime.HandleError(err)
return
}
for _, export := range apiExports {
c.enqueueAPIExport(export, logging.WithObject(logger, schema), fmt.Sprintf(" because of APIResourceSchema%s", logSuffix))
}
}
// enqueueLogicalCluster maps LogicalClusters to APIBindings for enqueuing.
func (c *controller) enqueueLogicalCluster(lc *corev1alpha1.LogicalCluster, logger logr.Logger, logSuffix string) {
bindings, err := c.listAPIBindings(logicalcluster.From(lc))
if err != nil {
utilruntime.HandleError(err)
return
}
for _, binding := range bindings {
c.enqueueAPIBinding(binding, logging.WithObject(logger, binding), fmt.Sprintf(" because of LogicalCluster%s", logSuffix))
}
}
func (c *controller) enqueueAPIConversion(apiConversion *apisv1alpha1.APIConversion, logger logr.Logger) {
logger = logging.WithObject(logger, apiConversion)
clusterName := logicalcluster.From(apiConversion)
apiResourceSchema, err := c.getAPIResourceSchema(clusterName, apiConversion.Name)
if err != nil {
utilruntime.HandleError(err)
return
}
logger.V(4).Info("queueing APIResourceSchema because of APIConversion", "key", kcpcache.ToClusterAwareKey(clusterName.String(), "", apiConversion.Name))
c.enqueueAPIResourceSchema(apiResourceSchema, logger, "")
}
// Start starts the controller, which stops when ctx.Done() is closed.
func (c *controller) Start(ctx context.Context, numThreads int) {
defer utilruntime.HandleCrash()
defer c.queue.ShutDown()
logger := logging.WithReconciler(klog.FromContext(ctx), ControllerName)
ctx = klog.NewContext(ctx, logger)
logger.Info("Starting controller")
defer logger.Info("Shutting down controller")
for range numThreads {
go wait.UntilWithContext(ctx, c.startWorker, time.Second)
}
<-ctx.Done()
}
func (c *controller) startWorker(ctx context.Context) {
for c.processNextWorkItem(ctx) {
}
}
func (c *controller) processNextWorkItem(ctx context.Context) bool {
// Wait until there is a new item in the working queue
k, quit := c.queue.Get()
if quit {
return false
}
key := k
logger := logging.WithQueueKey(klog.FromContext(ctx), key)
ctx = klog.NewContext(ctx, logger)
logger.V(4).Info("processing key")
// No matter what, tell the queue we're done with this key, to unblock
// other workers.
defer c.queue.Done(key)
if requeue, err := c.process(ctx, key); err != nil {
utilruntime.HandleError(fmt.Errorf("%q controller failed to sync %q, err: %w", ControllerName, key, err))
c.queue.AddRateLimited(key)
return true
} else if requeue {
// only requeue if we didn't error, but we still want to requeue
c.queue.Add(key)
return true
}
c.queue.Forget(key)
return true
}
func (c *controller) process(ctx context.Context, key string) (bool, error) {
logger := klog.FromContext(ctx)
clusterName, _, name, err := kcpcache.SplitMetaClusterNamespaceKey(key)
if err != nil {
utilruntime.HandleError(err)
return false, nil
}
binding, err := c.getAPIBinding(clusterName, name)
if err != nil {
if apierrors.IsNotFound(err) {
logger.Error(err, "failed to get APIBinding from lister", "cluster", clusterName)
}
return false, nil // nothing we can do here
}
old := binding
binding = binding.DeepCopy()
logger = logging.WithObject(logger, binding)
ctx = klog.NewContext(ctx, logger)
var errs []error
requeue, err := c.reconcile(ctx, binding)
if err != nil {
errs = append(errs, err)
}
// If the object being reconciled changed as a result, update it.
oldResource := &Resource{
APIVersion: apisv1alpha2.SchemeGroupVersion.String(),
Kind: "APIBinding",
ObjectMeta: old.ObjectMeta,
Spec: &old.Spec,
Status: &old.Status,
}
newResource := &Resource{
APIVersion: apisv1alpha2.SchemeGroupVersion.String(),
Kind: "APIBinding",
ObjectMeta: binding.ObjectMeta,
Spec: &binding.Spec,
Status: &binding.Status,
}
if err := c.commit(ctx, oldResource, newResource); err != nil {
errs = append(errs, err)
}
return requeue, utilerrors.NewAggregate(errs)
}
// InstallIndexers adds the additional indexers that this controller requires to the informers.
func InstallIndexers(
apiBindingInformer apisv1alpha2informers.APIBindingClusterInformer,
apiExportInformer apisv1alpha2informers.APIExportClusterInformer,
globalAPIExportInformer apisv1alpha2informers.APIExportClusterInformer,
) {
// APIBinding indexers
indexers.AddIfNotPresentOrDie(apiBindingInformer.Informer().GetIndexer(), cache.Indexers{
indexers.APIBindingsByAPIExport: indexers.IndexAPIBindingByAPIExport,
})
// APIExport indexers
indexers.AddIfNotPresentOrDie(apiExportInformer.Informer().GetIndexer(), cache.Indexers{
indexers.ByLogicalClusterPathAndName: indexers.IndexByLogicalClusterPathAndName,
indexers.APIExportByAPIResourceSchema: indexers.IndexAPIExportByAPIResourceSchema,
indexers.APIExportByIdentity: indexers.IndexAPIExportByIdentity,
})
indexers.AddIfNotPresentOrDie(globalAPIExportInformer.Informer().GetIndexer(), cache.Indexers{
indexers.ByLogicalClusterPathAndName: indexers.IndexByLogicalClusterPathAndName,
indexers.APIExportByAPIResourceSchema: indexers.IndexAPIExportByAPIResourceSchema,
indexers.APIExportByIdentity: indexers.IndexAPIExportByIdentity,
})
}