/
sfserviceinstance_controller.go
718 lines (640 loc) · 24.7 KB
/
sfserviceinstance_controller.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
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
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
/*
Copyright 2018 The Service Fabrik 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 sfserviceinstance
import (
"context"
"fmt"
"os"
"reflect"
"strconv"
"strings"
osbv1alpha1 "github.com/cloudfoundry-incubator/service-fabrik-broker/interoperator/api/osb/v1alpha1"
"github.com/cloudfoundry-incubator/service-fabrik-broker/interoperator/internal/config"
"github.com/cloudfoundry-incubator/service-fabrik-broker/interoperator/internal/properties"
"github.com/cloudfoundry-incubator/service-fabrik-broker/interoperator/internal/resources"
"github.com/cloudfoundry-incubator/service-fabrik-broker/interoperator/internal/services"
"github.com/cloudfoundry-incubator/service-fabrik-broker/interoperator/pkg/cluster/registry"
"github.com/cloudfoundry-incubator/service-fabrik-broker/interoperator/pkg/constants"
"github.com/cloudfoundry-incubator/service-fabrik-broker/interoperator/pkg/errors"
"github.com/cloudfoundry-incubator/service-fabrik-broker/interoperator/pkg/utils"
"github.com/cloudfoundry-incubator/service-fabrik-broker/interoperator/pkg/watches"
"github.com/go-logr/logr"
apiErrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/types"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller"
"sigs.k8s.io/controller-runtime/pkg/handler"
)
// ReconcileSFServiceInstance reconciles a SFServiceInstance object
type ReconcileSFServiceInstance struct {
client.Client
uncachedClient client.Client
Log logr.Logger
clusterRegistry registry.ClusterRegistry
resourceManager resources.ResourceManager
watchList []osbv1alpha1.APIVersionKind
cfgManager config.Config
}
// Reconcile reads that state of the cluster for a SFServiceInstance object and makes changes based on the state read
// and what is in the SFServiceInstance.Spec
// Automatically generate RBAC rules to allow the Controller to read and write Deployments
// +kubebuilder:rbac:groups=osb.servicefabrik.io,resources=*,verbs=*
// +kubebuilder:rbac:groups=deployment.servicefabrik.io,resources=*,verbs=*
// +kubebuilder:rbac:groups=kubernetes.sapcloud.io,resources=*,verbs=*
// +kubebuilder:rbac:groups=kubedb.com,resources=Postgres,verbs=*
// +kubebuilder:rbac:groups=,resources=configmap,verbs=*
// +kubebuilder:rbac:groups=apps,resources=deployments,verbs=*
// TODO dynamically setup rbac rules
func (r *ReconcileSFServiceInstance) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
log := r.Log.WithValues("sfserviceinstance", req.NamespacedName)
defer r.restartOnWatchUpdate()
// Fetch the ServiceInstance instance
instance := &osbv1alpha1.SFServiceInstance{}
err := r.Get(ctx, req.NamespacedName, instance)
if err != nil {
if apiErrors.IsNotFound(err) {
// Object not found, return. Created objects are automatically garbage collected.
// For additional cleanup logic use finalizers.
log.Info("instance deleted")
return ctrl.Result{}, nil
}
// Error reading the object - requeue the request.
return r.handleError(instance, ctrl.Result{}, err, "", 0)
}
serviceID := instance.Spec.ServiceID
planID := instance.Spec.PlanID
instanceID := instance.GetName()
bindingID := ""
state := instance.GetState()
if state == "succeeded" || state == "failed" {
return ctrl.Result{}, nil
}
// Fetch again using uncachedClient to read the state again
err = r.uncachedClient.Get(ctx, req.NamespacedName, instance)
if err != nil {
if apiErrors.IsNotFound(err) {
// Object not found, return. Created objects are automatically garbage collected.
// For additional cleanup logic use finalizers.
log.Info("instance deleted")
return ctrl.Result{}, nil
}
// Error reading the object - requeue the request.
return r.handleError(instance, ctrl.Result{}, err, state, 0)
}
state = instance.GetState()
clusterID, err := instance.GetClusterID()
if err != nil {
if errors.SFServiceInstanceNotFound(err) || errors.ClusterIDNotSet(err) {
log.Info("clusterID not set. Ignoring")
return ctrl.Result{}, nil
}
log.Error(err, "failed to get clusterID")
return r.handleError(instance, ctrl.Result{}, err, state, 0)
}
if clusterID != constants.OwnClusterID {
return ctrl.Result{}, nil
}
if err := r.reconcileFinalizers(instance, 0); err != nil {
return r.handleError(instance, ctrl.Result{Requeue: true}, nil, "", 0)
}
if state == "delete" && !instance.GetDeletionTimestamp().IsZero() {
// The object is being deleted
// so lets handle our external dependency
remainingResource, err := r.resourceManager.DeleteSubResources(r, instance.Status.Resources)
if err != nil {
log.Error(err, "Delete sub resources failed")
return r.handleError(instance, ctrl.Result{}, err, state, 0)
}
err = r.setInProgress(req.NamespacedName, state, remainingResource, 0)
if err != nil {
return r.handleError(instance, ctrl.Result{}, err, state, 0)
}
} else if state == "in_queue" || state == "update" {
expectedResources, err := r.resourceManager.ComputeExpectedResources(r, instanceID, bindingID, serviceID, planID, osbv1alpha1.ProvisionAction, instance.GetNamespace())
if err != nil {
return r.handleError(instance, ctrl.Result{}, err, state, 0)
}
err = r.resourceManager.SetOwnerReference(instance, expectedResources, r.Scheme())
if err != nil {
return r.handleError(instance, ctrl.Result{}, err, state, 0)
}
resourceRefs, err := r.resourceManager.ReconcileResources(r, expectedResources, instance.Status.Resources, false)
if err != nil {
log.Error(err, "ReconcileResources failed")
return r.handleError(instance, ctrl.Result{}, err, state, 0)
}
err = r.updatePlanHash(req.NamespacedName, 0)
if err != nil {
// Not throwing error
// Annotation is only required if plan.Spec.AutoUpdateInstances is enabled
log.Error(err, "Failed to update hash of sfplan on annotation.")
}
err = r.setInProgress(req.NamespacedName, state, resourceRefs, 0)
if err != nil {
return r.handleError(instance, ctrl.Result{}, err, state, 0)
}
}
err = r.Get(ctx, req.NamespacedName, instance)
if err != nil {
return r.handleError(instance, ctrl.Result{}, err, "", 0)
}
state = instance.GetState()
labels := instance.GetLabels()
lastOperation, ok := labels[constants.LastOperationKey]
if !ok {
lastOperation = "in_queue"
}
if state == "in progress" {
if lastOperation == "delete" {
if err := r.updateDeprovisionStatus(instance, 0); err != nil {
return r.handleError(instance, ctrl.Result{}, err, lastOperation, 0)
}
} else if lastOperation == "in_queue" || lastOperation == "update" {
err = r.updateStatus(instance, 0)
if err != nil {
return r.handleError(instance, ctrl.Result{}, err, lastOperation, 0)
}
}
}
return r.handleError(instance, ctrl.Result{}, nil, lastOperation, 0)
}
func (r *ReconcileSFServiceInstance) reconcileFinalizers(object *osbv1alpha1.SFServiceInstance, retryCount int) error {
ctx := context.Background()
objectID := object.GetName()
namespace := object.GetNamespace()
// Fetch object again before updating
namespacedName := types.NamespacedName{
Name: objectID,
Namespace: namespace,
}
log := r.Log.WithValues("instanceID", objectID)
err := r.Get(ctx, namespacedName, object)
if err != nil {
if retryCount < constants.ErrorThreshold {
log.Info("Retrying", "function", "reconcileFinalizers", "retryCount", retryCount+1)
return r.reconcileFinalizers(object, retryCount+1)
}
log.Error(err, "failed to fetch object")
return err
}
if object.GetDeletionTimestamp().IsZero() {
if !utils.ContainsString(object.GetFinalizers(), constants.FinalizerName) {
// The object is not being deleted, so if it does not have our finalizer,
// then lets add the finalizer and update the object.
object.SetFinalizers(append(object.GetFinalizers(), constants.FinalizerName))
if err := r.Update(ctx, object); err != nil {
if retryCount < constants.ErrorThreshold {
log.Info("Retrying", "function", "reconcileFinalizers", "retryCount", retryCount+1)
return r.reconcileFinalizers(object, retryCount+1)
}
log.Error(err, "failed to add finalizer")
return err
}
log.Info("added finalizer")
}
}
return nil
}
func (r *ReconcileSFServiceInstance) setInProgress(namespacedName types.NamespacedName, state string, resources []osbv1alpha1.Source, retryCount int) error {
ctx := context.Background()
log := r.Log.WithValues("sfserviceinstance", namespacedName, "function", "setInProgress")
if state == "in_queue" || state == "update" || state == "delete" {
instance := &osbv1alpha1.SFServiceInstance{}
err := r.Get(ctx, namespacedName, instance)
if err != nil {
if retryCount < constants.ErrorThreshold {
log.Info("Retrying", "retryCount", retryCount+1, "state", state)
return r.setInProgress(namespacedName, state, resources, retryCount+1)
}
log.Error(err, "Updating status to in progress failed")
return err
}
labels := instance.GetLabels()
if labels == nil {
labels = make(map[string]string)
}
lastOperation, ok := labels[constants.LastOperationKey]
if !ok {
lastOperation = "in_queue"
}
labels[constants.LastOperationKey] = state
// Do not update state if another operation happend in between
if state == instance.GetState() {
instance.SetState("in progress")
instance.SetLabels(labels)
} else {
log.Info("Error while trying to set in progress. state mismatch", "state", state,
"currentState", instance.GetState(), "lastOperation", lastOperation)
}
instance.Status.Resources = resources
newState := instance.GetState()
err = r.Update(ctx, instance)
if err != nil {
if retryCount < constants.ErrorThreshold {
log.Info("Retrying", "retryCount", retryCount+1, "state", state, "newState", newState, "lastOperation", lastOperation)
return r.setInProgress(namespacedName, state, resources, retryCount+1)
}
log.Error(err, "Updating status to in progress failed", "state", state, "newState", newState, "lastOperation", lastOperation)
return err
}
log.Info("Updated status to in progress", "state", state, "newState", newState, "lastOperation", lastOperation)
}
return nil
}
func (r *ReconcileSFServiceInstance) updateDeprovisionStatus(instance *osbv1alpha1.SFServiceInstance, retryCount int) error {
ctx := context.Background()
serviceID := instance.Spec.ServiceID
planID := instance.Spec.PlanID
instanceID := instance.GetName()
bindingID := ""
namespace := instance.GetNamespace()
log := r.Log.WithValues("instanceId", instanceID)
labels := instance.GetLabels()
if labels == nil {
labels = make(map[string]string)
}
lastOperation, ok := labels[constants.LastOperationKey]
if !ok {
lastOperation = "in_queue"
}
state := instance.GetState()
computedStatus, err := r.resourceManager.ComputeStatus(r, instanceID, bindingID, serviceID, planID, osbv1alpha1.ProvisionAction, namespace)
if err != nil && !errors.NotFound(err) {
log.Error(err, "ComputeStatus failed for deprovision", "state", state, "lastOperation", lastOperation)
return err
}
if errors.NotFound(err) && computedStatus == nil {
computedStatus = &properties.Status{}
computedStatus.Deprovision.State = instance.GetState()
computedStatus.Deprovision.Error = err.Error()
}
// Fetch object again before updating status
namespacedName := types.NamespacedName{
Name: instanceID,
Namespace: namespace,
}
err = r.Get(ctx, namespacedName, instance)
if err != nil {
log.Error(err, "Failed to get instance", "state", state, "lastOperation", lastOperation)
return err
}
labels = instance.GetLabels()
if labels == nil {
labels = make(map[string]string)
}
lastOperation, ok = labels[constants.LastOperationKey]
if !ok {
lastOperation = "in_queue"
}
state = instance.GetState()
if state != "in progress" {
err = errors.NewPreconditionError("updateDeprovisionStatus", "state not in progress", nil)
log.Error(err, "state changed while processing instance", "state", state, "lastOperation", lastOperation)
return err
}
updateRequired := false
updatedStatus := instance.Status.DeepCopy()
updatedStatus.State = computedStatus.Deprovision.State
updatedStatus.Error = computedStatus.Deprovision.Error
updatedStatus.Description = computedStatus.Deprovision.Response
updatedStatus.InstanceUsable = computedStatus.Deprovision.InstanceUsable
updatedStatus.UpdateRepeatable = computedStatus.Deprovision.UpdateRepeatable
remainingResource := []osbv1alpha1.Source{}
for _, subResource := range instance.Status.Resources {
resource := &unstructured.Unstructured{}
resource.SetKind(subResource.Kind)
resource.SetAPIVersion(subResource.APIVersion)
resource.SetName(subResource.Name)
resource.SetNamespace(subResource.Namespace)
namespacedName := types.NamespacedName{
Name: resource.GetName(),
Namespace: resource.GetNamespace(),
}
err := r.Get(ctx, namespacedName, resource)
if !apiErrors.IsNotFound(err) {
remainingResource = append(remainingResource, subResource)
}
}
updatedStatus.Resources = remainingResource
if !reflect.DeepEqual(&instance.Status, updatedStatus) {
updatedStatus.DeepCopyInto(&instance.Status)
updateRequired = true
}
if instance.GetState() == "succeeded" || len(remainingResource) == 0 {
// remove our finalizer from the list and update it.
log.Info("Removing finalizer", "state", state, "lastOperation", lastOperation)
instance.SetFinalizers(utils.RemoveString(instance.GetFinalizers(), constants.FinalizerName))
instance.SetState("succeeded")
updateRequired = true
}
if updateRequired {
newState := instance.GetState()
log.Info("Updating deprovision status from template", "state", state, "lastOperation", lastOperation, "newState", newState)
if err := r.Update(ctx, instance); err != nil {
if retryCount < constants.ErrorThreshold {
log.Info("Retrying", "function", "updateDeprovisionStatus", "retryCount", retryCount+1)
return r.updateDeprovisionStatus(instance, retryCount+1)
}
log.Error(err, "failed to update deprovision status", "state", state, "lastOperation", lastOperation, "newState", newState)
return err
}
}
return nil
}
func (r *ReconcileSFServiceInstance) updateStatus(instance *osbv1alpha1.SFServiceInstance, retryCount int) error {
serviceID := instance.Spec.ServiceID
planID := instance.Spec.PlanID
instanceID := instance.GetName()
bindingID := ""
namespace := instance.GetNamespace()
ctx := context.Background()
log := r.Log.WithValues("instanceID", instanceID)
computedStatus, err := r.resourceManager.ComputeStatus(r, instanceID, bindingID, serviceID, planID, osbv1alpha1.ProvisionAction, namespace)
if err != nil {
log.Error(err, "Compute status failed")
return err
}
// Fetch object again before updating status
namespacedName := types.NamespacedName{
Name: instanceID,
Namespace: namespace,
}
err = r.Get(ctx, namespacedName, instance)
if err != nil {
log.Error(err, "failed to fetch instance")
return err
}
labels := instance.GetLabels()
if labels == nil {
labels = make(map[string]string)
}
lastOperation, ok := labels[constants.LastOperationKey]
if !ok {
lastOperation = "in_queue"
}
state := instance.GetState()
if state != "in progress" {
err = errors.NewPreconditionError("updateStatus", "state not in progress", nil)
log.Error(err, "state changed while processing instance", "state", state, "lastOperation", lastOperation)
return err
}
updatedStatus := instance.Status.DeepCopy()
updatedStatus.State = computedStatus.Provision.State
updatedStatus.Error = computedStatus.Provision.Error
updatedStatus.Description = computedStatus.Provision.Response
updatedStatus.DashboardURL = computedStatus.Provision.DashboardURL
updatedStatus.InstanceUsable = computedStatus.Provision.InstanceUsable
updatedStatus.UpdateRepeatable = computedStatus.Provision.UpdateRepeatable
if !reflect.DeepEqual(&instance.Status, updatedStatus) {
updatedStatus.DeepCopyInto(&instance.Status)
newState := instance.GetState()
log.Info("Updating provision status from template", "state", state, "lastOperation", lastOperation, "newState", newState)
err = r.Update(ctx, instance)
if err != nil {
if retryCount < constants.ErrorThreshold {
log.Info("Retrying", "function", "updateStatus", "retryCount", retryCount+1)
return r.updateStatus(instance, retryCount+1)
}
log.Error(err, "failed to update status", "state", state, "lastOperation", lastOperation, "newState", newState)
return err
}
}
return nil
}
func (r *ReconcileSFServiceInstance) handleError(object *osbv1alpha1.SFServiceInstance, result ctrl.Result, inputErr error, lastOperation string, retryCount int) (ctrl.Result, error) {
objectID := object.GetName()
namespace := object.GetNamespace()
// Fetch object again before updating
namespacedName := types.NamespacedName{
Name: objectID,
Namespace: namespace,
}
ctx := context.Background()
log := r.Log.WithValues("objectID", objectID, "function", "handleError")
err := r.Get(ctx, namespacedName, object)
if err != nil {
if apiErrors.IsNotFound(err) {
return result, inputErr
}
if retryCount < constants.ErrorThreshold {
log.Info("Retrying", "retryCount", retryCount+1, "lastOperation", lastOperation, "err", inputErr)
return r.handleError(object, result, inputErr, lastOperation, retryCount+1)
}
log.Error(err, "failed to fetch object")
return result, inputErr
}
labels := object.GetLabels()
var count int64
if labels == nil {
labels = make(map[string]string)
}
countString, ok := labels[constants.ErrorCountKey]
if !ok {
count = 0
} else {
i, err := strconv.ParseInt(countString, 10, 64)
if err != nil {
count = 0
} else {
count = i
}
}
if inputErr != nil {
if statusError, ok := inputErr.(*apiErrors.StatusError); ok {
if statusError.ErrStatus.Code == 422 {
log.Error(inputErr, "Encountered StatusError")
object.Status.State = "failed"
object.Status.Error = fmt.Sprintf("StatusError encountered for %s.\n%s", objectID, inputErr.Error())
causes := statusError.ErrStatus.Details.Causes
if len(causes) > 0 {
messages := make([]string, 0)
for _, v := range causes {
messages = append(messages, v.Message)
}
object.Status.Description = fmt.Sprintf("%s, Error code: 422", strings.Join(messages[:], ", "))
} else if inputErr.Error() != "" {
object.Status.Description = fmt.Sprintf("%s, Error code: 422", inputErr.Error())
} else {
object.Status.Description = "Unprocessable Entity - this is usually caused by invalid request parameters, Error code: 422"
}
if lastOperation != "" {
labels[constants.LastOperationKey] = lastOperation
object.SetLabels(labels)
}
err := r.Update(ctx, object)
if err != nil {
log.Error(err, "Failed to set state to failed", "objectID", objectID)
}
return result, nil
}
}
}
if inputErr == nil {
if count == 0 {
//No change for count
return result, inputErr
}
count = 0
} else {
count++
}
if count > constants.ErrorThreshold {
log.Error(inputErr, "Retry threshold reached. Ignoring error")
object.Status.State = "failed"
object.Status.Error = fmt.Sprintf("Retry threshold reached for %s.\n%s", objectID, inputErr.Error())
if inputErr.Error() != "" {
object.Status.Description = inputErr.Error()
} else {
object.Status.Description = "Service Broker Error, status code: ETIMEDOUT, error code: 10008"
}
if lastOperation != "" {
labels[constants.LastOperationKey] = lastOperation
object.SetLabels(labels)
}
err := r.Update(ctx, object)
if err != nil {
if retryCount < constants.ErrorThreshold {
log.Info("Retrying", "retryCount", retryCount+1, "lastOperation", lastOperation, "err", inputErr)
return r.handleError(object, result, inputErr, lastOperation, retryCount+1)
}
log.Error(err, "Failed to set state to failed", "objectID", objectID)
}
return result, nil
}
labels[constants.ErrorCountKey] = strconv.FormatInt(count, 10)
object.SetLabels(labels)
err = r.Update(ctx, object)
if err != nil {
if retryCount < constants.ErrorThreshold {
log.Info("Retrying", "retryCount", retryCount+1, "lastOperation", lastOperation, "err", inputErr)
return r.handleError(object, result, inputErr, lastOperation, retryCount+1)
}
log.Error(err, "Failed to update error count label", "objectID", objectID, "count", count)
}
log.Info("Updated error count", "retryCount", retryCount, "lastOperation", lastOperation, "err", inputErr, "count", count)
return result, inputErr
}
// Will kill the process if watchlist has changed
func (r *ReconcileSFServiceInstance) restartOnWatchUpdate() {
if !constants.K8SDeployment {
return
}
interoperatorCfg := r.cfgManager.GetConfig()
if !watches.CompareWatchLists(interoperatorCfg.InstanceContollerWatchList, r.watchList) {
r.Log.Info("Instance watch list changed. Restarting interoperator")
os.Exit(1)
}
}
// Add the sfplan spec hash in the instance annotation
// This annotation is used by the autoUpdateInstances scheduler
func (r *ReconcileSFServiceInstance) updatePlanHash(namespacedName types.NamespacedName, retryCount int) error {
ctx := context.Background()
log := r.Log.WithValues("sfserviceinstance", namespacedName.String(), "function", "updatePlanHash")
instance := &osbv1alpha1.SFServiceInstance{}
err := r.Get(ctx, namespacedName, instance)
if err != nil {
if retryCount < constants.ErrorThreshold {
log.Info("Retrying", "retryCount", retryCount+1)
return r.updatePlanHash(namespacedName, retryCount+1)
}
log.Error(err, "Updating sfplan hash to annotation failed")
return err
}
serviceID := instance.Spec.ServiceID
planID := instance.Spec.PlanID
serviceNamespace := constants.InteroperatorNamespace
plan, err := services.FindPlanInfo(r, serviceID, planID, serviceNamespace)
if err != nil {
log.Error(err, "Failed finding plan info when updating plan hash", "serviceID", serviceID, "planID", planID)
return err
}
annotations := instance.GetAnnotations()
if annotations == nil {
annotations = make(map[string]string)
}
currentPlanHash := utils.CalculateHash(plan.Spec)
if planHash, ok := annotations[constants.PlanHashKey]; !ok || currentPlanHash != planHash {
annotations[constants.PlanHashKey] = utils.CalculateHash(plan.Spec)
instance.SetAnnotations(annotations)
err = r.Update(ctx, instance)
if err != nil {
if retryCount < constants.ErrorThreshold {
log.Info("Retrying", "retryCount", retryCount+1)
return r.updatePlanHash(namespacedName, retryCount+1)
}
log.Error(err, "Updating sfplan hash to annotation failed")
return err
}
log.Info("Updated sfplan hash to annotation")
}
return nil
}
// SetupWithManager registers the SFServiceInstance Controller with manager
// and setups the watches.
func (r *ReconcileSFServiceInstance) SetupWithManager(mgr ctrl.Manager) error {
if r.Log.GetSink() == nil {
r.Log = ctrl.Log.WithName("provisioners").WithName("instance")
}
if r.clusterRegistry == nil {
clusterRegistry, err := registry.New(mgr.GetConfig(), mgr.GetScheme(), mgr.GetRESTMapper())
if err != nil {
return err
}
r.clusterRegistry = clusterRegistry
}
if r.resourceManager == nil {
r.resourceManager = resources.New()
}
if r.uncachedClient == nil {
uncachedClient, err := client.New(mgr.GetConfig(), client.Options{
Scheme: mgr.GetScheme(),
Mapper: mgr.GetRESTMapper(),
})
if err != nil {
return err
}
r.uncachedClient = uncachedClient
}
cfgManager, err := config.New(mgr.GetConfig(), mgr.GetScheme(), mgr.GetRESTMapper())
if err != nil {
return err
}
interoperatorCfg := cfgManager.GetConfig()
r.cfgManager = cfgManager
builder := ctrl.NewControllerManagedBy(mgr).
Named("instance").
WithOptions(controller.Options{
MaxConcurrentReconciles: interoperatorCfg.InstanceWorkerCount,
}).
For(&osbv1alpha1.SFServiceInstance{})
// TODO dynamically setup rbac rules and watches
r.watchList = make([]osbv1alpha1.APIVersionKind, len(interoperatorCfg.InstanceContollerWatchList))
copy(r.watchList, interoperatorCfg.InstanceContollerWatchList)
subresources := make([]client.Object, len(r.watchList))
for i, gvk := range r.watchList {
object := &unstructured.Unstructured{}
object.SetKind(gvk.GetKind())
object.SetAPIVersion(gvk.GetAPIVersion())
subresources[i] = object
}
for _, subresource := range subresources {
builder = builder.Watches(
subresource,
handler.EnqueueRequestForOwner(mgr.GetScheme(), mgr.GetRESTMapper(), &osbv1alpha1.SFServiceInstance{}),
)
}
builder = builder.WithEventFilter(watches.NamespaceLabelFilter())
return builder.Complete(r)
}