forked from openshift/origin
/
controller_instance.go
2105 lines (1884 loc) · 70.5 KB
/
controller_instance.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
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2017 The Kubernetes 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 controller
import (
"fmt"
"net/http"
"net/url"
"time"
"github.com/golang/glog"
osb "github.com/pmorie/go-open-service-broker-client/v2"
"k8s.io/apimachinery/pkg/runtime"
utilfeature "k8s.io/apiserver/pkg/util/feature"
"github.com/kubernetes-incubator/service-catalog/pkg/api"
"github.com/kubernetes-incubator/service-catalog/pkg/apis/servicecatalog/v1beta1"
scfeatures "github.com/kubernetes-incubator/service-catalog/pkg/features"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/client-go/tools/cache"
)
var typeSI = "ServiceInstance"
const (
successDeprovisionReason string = "DeprovisionedSuccessfully"
successDeprovisionMessage string = "The instance was deprovisioned successfully"
successUpdateInstanceReason string = "InstanceUpdatedSuccessfully"
successUpdateInstanceMessage string = "The instance was updated successfully"
successProvisionReason string = "ProvisionedSuccessfully"
successProvisionMessage string = "The instance was provisioned successfully"
successOrphanMitigationReason string = "OrphanMitigationSuccessful"
successOrphanMitigationMessage string = "Orphan mitigation was completed successfully"
errorWithParameters string = "ErrorWithParameters"
errorProvisionCallFailedReason string = "ProvisionCallFailed"
errorErrorCallingProvisionReason string = "ErrorCallingProvision"
errorUpdateInstanceCallFailedReason string = "UpdateInstanceCallFailed"
errorErrorCallingUpdateInstanceReason string = "ErrorCallingUpdateInstance"
errorDeprovisionCalledReason string = "DeprovisionCallFailed"
errorDeprovisionBlockedByCredentialsReason string = "DeprovisionBlockedByExistingCredentials"
errorPollingLastOperationReason string = "ErrorPollingLastOperation"
errorWithOriginatingIdentity string = "Error with Originating Identity"
errorWithOngoingAsyncOperation string = "ErrorAsyncOperationInProgress"
errorWithOngoingAsyncOperationMessage string = "Another operation for this service instance is in progress. "
errorNonexistentClusterServiceClassReason string = "ReferencesNonexistentServiceClass"
errorNonexistentClusterServiceClassMessage string = "ReferencesNonexistentServiceClass"
errorNonexistentClusterServicePlanReason string = "ReferencesNonexistentServicePlan"
errorNonexistentClusterServiceBrokerReason string = "ReferencesNonexistentBroker"
errorDeletedClusterServiceClassReason string = "ReferencesDeletedServiceClass"
errorDeletedClusterServiceClassMessage string = "ReferencesDeletedServiceClass"
errorDeletedClusterServicePlanReason string = "ReferencesDeletedServicePlan"
errorDeletedClusterServicePlanMessage string = "ReferencesDeletedServicePlan"
errorFindingNamespaceServiceInstanceReason string = "ErrorFindingNamespaceForInstance"
errorOrphanMitigationFailedReason string = "OrphanMitigationFailed"
asyncProvisioningReason string = "Provisioning"
asyncProvisioningMessage string = "The instance is being provisioned asynchronously"
asyncUpdatingInstanceReason string = "UpdatingInstance"
asyncUpdatingInstanceMessage string = "The instance is being updated asynchronously"
asyncDeprovisioningReason string = "Deprovisioning"
asyncDeprovisioningMessage string = "The instance is being deprovisioned asynchronously"
provisioningInFlightReason string = "ProvisionRequestInFlight"
provisioningInFlightMessage string = "Provision request for ServiceInstance in-flight to Broker"
instanceUpdatingInFlightReason string = "UpdateInstanceRequestInFlight"
instanceUpdatingInFlightMessage string = "Update request for ServiceInstance in-flight to Broker"
deprovisioningInFlightReason string = "DeprovisionRequestInFlight"
deprovisioningInFlightMessage string = "Deprovision request for ServiceInstance in-flight to Broker"
startingInstanceOrphanMitigationReason string = "StartingInstanceOrphanMitigation"
startingInstanceOrphanMitigationMessage string = "The instance provision call failed with an ambiguous error; attempting to deprovision the instance in order to mitigate an orphaned resource"
)
// ServiceInstance handlers and control-loop
func (c *controller) instanceAdd(obj interface{}) {
key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj)
if err != nil {
glog.Errorf("Couldn't get key for object %+v: %v", obj, err)
return
}
c.instanceQueue.Add(key)
}
func (c *controller) instanceUpdate(oldObj, newObj interface{}) {
// Instances with ongoing asynchronous operations will be manually added
// to the polling queue by the reconciler. They should be ignored here in
// order to enforce polling rate-limiting.
instance := newObj.(*v1beta1.ServiceInstance)
if !instance.Status.AsyncOpInProgress {
c.instanceAdd(newObj)
}
}
func (c *controller) instanceDelete(obj interface{}) {
instance, ok := obj.(*v1beta1.ServiceInstance)
if instance == nil || !ok {
return
}
glog.V(4).Infof(
`%s "%s/%s": Received delete event; no further processing will occur`,
typeSI, instance.Namespace, instance.Name,
)
}
// Async operations on instances have a somewhat convoluted flow in order to
// ensure that only a single goroutine works on an instance at any given time.
// The flow is:
//
// 1. When the controller wants to begin polling the state of an operation on
// an instance, it calls its beginPollingServiceInstance method (or
// calls continuePollingServiceInstance, an alias of that method)
// 2. begin/continuePollingServiceInstance do a rate-limited add to the polling queue
// 3. the pollingQueue calls requeueServiceInstanceForPoll, which adds the instance's
// key to the instance work queue
// 4. the worker servicing the instance polling queue forgets the instances key,
// requiring the controller to call continuePollingServiceInstance if additional
// work is needed.
// 5. the instance work queue is the single work queue that actually services
// instances by calling reconcileServiceInstance
// 6. when an asynchronous operation is completed, the controller calls
// finishPollingServiceInstance to forget the instance from the polling queue
// requeueServiceInstanceForPoll adds the given instance key to the controller's work
// queue for instances. It is used to trigger polling for the status of an
// async operation on and instance and is called by the worker servicing the
// instance polling queue. After requeueServiceInstanceForPoll exits, the worker
// forgets the key from the polling queue, so the controller must call
// continuePollingServiceInstance if the instance requires additional polling.
func (c *controller) requeueServiceInstanceForPoll(key string) error {
c.instanceQueue.Add(key)
return nil
}
// beginPollingServiceInstance does a rate-limited add of the key for the given
// instance to the controller's instance polling queue.
func (c *controller) beginPollingServiceInstance(instance *v1beta1.ServiceInstance) error {
key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(instance)
if err != nil {
glog.Errorf(
`%s "%s/%s": Couldn't create a key for object %+v: %v`,
typeSI, instance.Namespace, instance.Name, instance, err,
)
return fmt.Errorf("Couldn't create a key for object %+v: %v", instance, err)
}
c.pollingQueue.AddRateLimited(key)
return nil
}
// continuePollingServiceInstance does a rate-limited add of the key for the given
// instance to the controller's instance polling queue.
func (c *controller) continuePollingServiceInstance(instance *v1beta1.ServiceInstance) error {
return c.beginPollingServiceInstance(instance)
}
// finishPollingServiceInstance removes the instance's key from the controller's instance
// polling queue.
func (c *controller) finishPollingServiceInstance(instance *v1beta1.ServiceInstance) error {
key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(instance)
if err != nil {
glog.Errorf(
`%s "%s/%s": Couldn't create a key for object %+v: %v`,
typeSI, instance.Namespace, instance.Name, instance, err,
)
return fmt.Errorf(`Couldn't create a key for object %+v: %v`, instance, err)
}
c.pollingQueue.Forget(key)
return nil
}
func (c *controller) reconcileServiceInstanceKey(key string) error {
// For namespace-scoped resources, SplitMetaNamespaceKey splits the key
// i.e. "namespace/name" into two separate strings
namespace, name, err := cache.SplitMetaNamespaceKey(key)
if err != nil {
return err
}
instance, err := c.instanceLister.ServiceInstances(namespace).Get(name)
if errors.IsNotFound(err) {
glog.Infof(
`%s "%s/%s": Not doing work for %v because it has been deleted`,
typeSI, namespace, name, key,
)
return nil
}
if err != nil {
glog.Errorf(
`%s "%s/%s": Unable to retrieve %v from store: %v`,
typeSI, instance.Namespace, instance.Name, key, err,
)
return err
}
return c.reconcileServiceInstance(instance)
}
// reconcileServiceInstanceDelete is responsible for handling any instance whose
// deletion timestamp is set.
func (c *controller) reconcileServiceInstanceDelete(instance *v1beta1.ServiceInstance) error {
// nothing to do...
if instance.DeletionTimestamp == nil && !instance.Status.OrphanMitigationInProgress {
return nil
}
glog.V(4).Infof(
`%s "%s/%s": Processing deleting event`,
typeSI, instance.Namespace, instance.Name,
)
// Determine if any credentials exist for this instance. We don't want to
// delete the instance if there are any associated creds
credentialsLister := c.bindingLister.ServiceBindings(instance.Namespace)
selector := labels.NewSelector()
credentialsList, err := credentialsLister.List(selector)
if err != nil {
return err
}
for _, credentials := range credentialsList {
if instance.Name == credentials.Spec.ServiceInstanceRef.Name {
// found credentials, block the deletion until they are removed
clone, err := api.Scheme.DeepCopy(instance)
if err != nil {
return err
}
toUpdate := clone.(*v1beta1.ServiceInstance)
s := "Delete instance blocked by existing ServiceBindings associated with this instance. All credentials must be removed first"
glog.Warningf(
`%s "%s/%s": %s`,
typeSI, instance.Namespace, instance.Name, s,
)
c.recorder.Event(instance, corev1.EventTypeWarning, errorDeprovisionBlockedByCredentialsReason, s)
setServiceInstanceCondition(
toUpdate,
v1beta1.ServiceInstanceConditionReady,
v1beta1.ConditionFalse,
errorDeprovisionBlockedByCredentialsReason,
"Delete instance failed. "+s)
if _, err = c.updateServiceInstanceStatus(toUpdate); err != nil {
return err
}
return nil
}
}
finalizerToken := v1beta1.FinalizerServiceCatalog
finalizers := sets.NewString(instance.Finalizers...)
if !finalizers.Has(finalizerToken) {
return nil
}
// If there is no op in progress, and the instance either was never
// provisioned or was already deprovisioned due to orphan mitigation,
// we can just clear the finalizer and delete. One possible scenario
// is if the service class name referenced never existed.
if instance.Status.CurrentOperation == "" &&
instance.Status.ReconciledGeneration == 0 ||
(isServiceInstanceFailed(instance) && instance.Status.ReconciledGeneration == 1) {
glog.V(5).Infof(
`%s "%s/%s": Clearing catalog finalizer`,
typeSI, instance.Namespace, instance.Name,
)
clone, err := api.Scheme.DeepCopy(instance)
if err != nil {
return err
}
toUpdate := clone.(*v1beta1.ServiceInstance)
// Clear the finalizer
finalizers.Delete(finalizerToken)
toUpdate.Finalizers = finalizers.List()
if _, err := c.updateServiceInstanceStatus(toUpdate); err != nil {
return err
}
return nil
}
// All updates not having a DeletingTimestamp will have been handled above
// and returned early. If we reach this point, we're dealing with an update
// that's actually a soft delete-- i.e. we have some finalization to do.
serviceClass, servicePlan, brokerName, brokerClient, err := c.getClusterServiceClassPlanAndClusterServiceBroker(instance)
if err != nil {
return err
}
// we will definitely update the instance's status - make a deep copy now
// for use later in this method.
clone, err := api.Scheme.DeepCopy(instance)
if err != nil {
return err
}
toUpdate := clone.(*v1beta1.ServiceInstance)
request := &osb.DeprovisionRequest{
InstanceID: instance.Spec.ExternalID,
ServiceID: serviceClass.Spec.ExternalID,
PlanID: servicePlan.Spec.ExternalID,
AcceptsIncomplete: true,
}
if utilfeature.DefaultFeatureGate.Enabled(scfeatures.OriginatingIdentity) {
originatingIdentity, err := buildOriginatingIdentity(instance.Spec.UserInfo)
if err != nil {
s := fmt.Sprintf("Error building originating identity headers when deprovisioning: %v", err)
glog.Warningf(
`%s "%s/%s": %s`,
typeSI, instance.Namespace, instance.Name, s,
)
c.recorder.Event(instance, corev1.EventTypeWarning, errorWithOriginatingIdentity, s)
setServiceInstanceCondition(
toUpdate,
v1beta1.ServiceInstanceConditionReady,
v1beta1.ConditionFalse,
errorWithOriginatingIdentity,
s,
)
if _, err := c.updateServiceInstanceStatus(toUpdate); err != nil {
return err
}
return err
}
request.OriginatingIdentity = originatingIdentity
}
if instance.Status.OrphanMitigationInProgress && instance.Status.OperationStartTime == nil {
now := metav1.Now()
toUpdate.Status.OperationStartTime = &now
}
if toUpdate.Status.CurrentOperation == "" {
toUpdate, err = c.recordStartOfServiceInstanceOperation(toUpdate, v1beta1.ServiceInstanceOperationDeprovision)
if err != nil {
// There has been an update to the instance. Start reconciliation
// over with a fresh view of the instance.
return err
}
}
glog.V(4).Infof(
`%s "%s/%s": Deprovisioning`,
typeSI, instance.Namespace, instance.Name,
)
response, err := brokerClient.DeprovisionInstance(request)
if err != nil {
if httpErr, ok := osb.IsHTTPError(err); ok {
s := fmt.Sprintf(
"Deprovision call failed; received error response from broker: %v",
httpErr.Error(),
)
glog.Warningf(
`%s "%s/%s": %s`,
typeSI, instance.Namespace, instance.Name, s,
)
c.recorder.Event(instance, corev1.EventTypeWarning, errorDeprovisionCalledReason, s)
if instance.Status.OrphanMitigationInProgress {
setServiceInstanceCondition(
toUpdate,
v1beta1.ServiceInstanceConditionReady,
v1beta1.ConditionUnknown,
errorOrphanMitigationFailedReason,
"Orphan mitigation deprovision call failed. "+s)
} else {
setServiceInstanceCondition(
toUpdate,
v1beta1.ServiceInstanceConditionReady,
v1beta1.ConditionUnknown,
errorDeprovisionCalledReason,
"Deprovision call failed. "+s)
// Do not overwrite 'Failed' message if deprovisioning due to orphan
// mitigation in order to prevent loss of original reason for the
// orphan.
setServiceInstanceCondition(
toUpdate,
v1beta1.ServiceInstanceConditionFailed,
v1beta1.ConditionTrue,
errorDeprovisionCalledReason,
s,
)
}
c.clearServiceInstanceCurrentOperation(toUpdate)
if _, err := c.updateServiceInstanceStatus(toUpdate); err != nil {
return err
}
return nil
}
s := fmt.Sprintf(
`Error deprovisioning, ClusterServiceClass (K8S: %q ExternalName: %q) at ClusterServiceBroker %q: %v`,
serviceClass.Name, serviceClass.Spec.ExternalName, brokerName, err,
)
glog.Warningf(
`%s "%s/%s": %s`,
typeSI, instance.Namespace, instance.Name, s,
)
c.recorder.Event(instance, corev1.EventTypeWarning, errorDeprovisionCalledReason, s)
setServiceInstanceCondition(
toUpdate,
v1beta1.ServiceInstanceConditionReady,
v1beta1.ConditionUnknown,
errorDeprovisionCalledReason,
"Deprovision call failed. "+s)
if !time.Now().Before(toUpdate.Status.OperationStartTime.Time.Add(c.reconciliationRetryDuration)) {
s := "Stopping reconciliation retries because too much time has elapsed"
glog.Infof(
`%s "%s/%s": %s`,
typeSI, instance.Namespace, instance.Name, s,
)
c.recorder.Event(instance, corev1.EventTypeWarning, errorReconciliationRetryTimeoutReason, s)
if instance.Status.OrphanMitigationInProgress {
setServiceInstanceCondition(
toUpdate,
v1beta1.ServiceInstanceConditionReady,
v1beta1.ConditionUnknown,
errorOrphanMitigationFailedReason,
"Orphan mitigation deprovision call failed. "+s)
} else {
setServiceInstanceCondition(toUpdate,
v1beta1.ServiceInstanceConditionFailed,
v1beta1.ConditionTrue,
errorReconciliationRetryTimeoutReason,
s)
}
c.clearServiceInstanceCurrentOperation(toUpdate)
if _, err := c.updateServiceInstanceStatus(toUpdate); err != nil {
return err
}
return nil
}
if _, err := c.updateServiceInstanceStatus(toUpdate); err != nil {
return err
}
return err
}
if response.Async {
glog.V(5).Infof(
`%s "%s/%s": Received asynchronous de-provisioning response, %s at %s: response: %+v`,
typeSI, instance.Namespace, instance.Name, serviceClass.Name, brokerName, response,
)
if response.OperationKey != nil && *response.OperationKey != "" {
key := string(*response.OperationKey)
toUpdate.Status.LastOperation = &key
}
// Tag this instance as having an ongoing async operation so we can enforce
// no other operations against it can start.
toUpdate.Status.AsyncOpInProgress = true
setServiceInstanceCondition(
toUpdate,
v1beta1.ServiceInstanceConditionReady,
v1beta1.ConditionFalse,
asyncDeprovisioningReason,
asyncDeprovisioningMessage,
)
if _, err := c.updateServiceInstanceStatus(toUpdate); err != nil {
return err
}
err = c.beginPollingServiceInstance(instance)
if err != nil {
return err
}
c.recorder.Eventf(instance, corev1.EventTypeNormal, asyncDeprovisioningReason, asyncDeprovisioningMessage)
return nil
}
glog.V(5).Infof(
`%s "%s/%s": Deprovision call to broker succeeded, finalizing`,
typeSI, instance.Namespace, instance.Name,
)
c.clearServiceInstanceCurrentOperation(toUpdate)
toUpdate.Status.ExternalProperties = nil
if instance.DeletionTimestamp != nil {
glog.V(5).Infof(
`%s "%s/%s": Successfully deprovisioned, %s at %s`,
typeSI, instance.Namespace, instance.Name, serviceClass.Name, brokerName,
)
c.recorder.Event(instance, corev1.EventTypeNormal, successDeprovisionReason, successDeprovisionMessage)
setServiceInstanceCondition(
toUpdate,
v1beta1.ServiceInstanceConditionReady,
v1beta1.ConditionFalse,
successDeprovisionReason,
successDeprovisionMessage,
)
// Clear the finalizer for normal instance deletions
finalizers.Delete(v1beta1.FinalizerServiceCatalog)
toUpdate.Finalizers = finalizers.List()
} else {
// Deprovision due to orphan mitigation successful
glog.V(5).Infof(
`%s "%s/%s": %s`,
typeSI,
instance.Namespace,
instance.Name,
successOrphanMitigationMessage,
)
c.recorder.Event(instance, corev1.EventTypeNormal, successOrphanMitigationReason, successOrphanMitigationMessage)
setServiceInstanceCondition(
toUpdate,
v1beta1.ServiceInstanceConditionReady,
v1beta1.ConditionFalse,
successOrphanMitigationReason,
successOrphanMitigationMessage,
)
}
if _, err = c.updateServiceInstanceStatus(toUpdate); err != nil {
return err
}
return nil
}
// isServiceInstanceFailed returns whether the instance has a failed condition with
// status true.
func isServiceInstanceFailed(instance *v1beta1.ServiceInstance) bool {
for _, condition := range instance.Status.Conditions {
if condition.Type == v1beta1.ServiceInstanceConditionFailed && condition.Status == v1beta1.ConditionTrue {
return true
}
}
return false
}
// reconcileServiceInstance is the control-loop for reconciling Instances. An
// error is returned to indicate that the instance has not been fully
// processed and should be resubmitted at a later time.
func (c *controller) reconcileServiceInstance(instance *v1beta1.ServiceInstance) error {
if instance.Status.AsyncOpInProgress {
return c.pollServiceInstance(instance)
}
if instance.ObjectMeta.DeletionTimestamp != nil || instance.Status.OrphanMitigationInProgress {
return c.reconcileServiceInstanceDelete(instance)
}
// Currently, we only set a failure condition if the initial provision
// call fails, so if that condition is set, we only need to remove the
// finalizer from the instance. We will need to reevaluate this logic as
// we make any changes to capture permanent failure in new cases.
if isServiceInstanceFailed(instance) {
glog.V(4).Infof(
`%s "%s/%s": Not processing event because status showed that it has failed`,
typeSI, instance.Namespace, instance.Name,
)
return nil
}
// If the instance's "metadata.generation" matches its
// "status.reconciledGeneration", then no new changes have been made to
// the instance's spec, and we can just return.
if instance.Status.ReconciledGeneration == instance.Generation {
glog.V(4).Infof(
`%s "%s/%s": Not processing event because reconciled generation showed there is no work to do`,
typeSI, instance.Namespace, instance.Name,
)
return nil
}
// we will definitely update the instance's status - make a deep copy now
// for use later in this method.
clone, err := api.Scheme.DeepCopy(instance)
if err != nil {
return err
}
toUpdate := clone.(*v1beta1.ServiceInstance)
// Update references to ClusterServicePlan / ClusterServiceClass if necessary.
toUpdate, err = c.resolveReferences(toUpdate)
if err != nil {
return err
}
glog.V(4).Infof(
`%s "%s/%s": Processing adding/updating event`,
typeSI, instance.Namespace, instance.Name,
)
serviceClass, servicePlan, brokerName, brokerClient, err := c.getClusterServiceClassPlanAndClusterServiceBroker(toUpdate)
if err != nil {
return err
}
// Check if the ServiceClass or ServicePlan has been deleted and do not allow
// creation of new ServiceInstances or plan upgrades. It's little complicated
// since we do want to allow parameter changes on an instance whose plan or class
// has been removed from the broker's catalog.
// If changes are not allowed, the method will set the appropriate status / record
// events, so we can just return here on failure.
err = c.checkForRemovedClassAndPlan(instance, serviceClass, servicePlan)
if err != nil {
return err
}
ns, err := c.kubeClient.CoreV1().Namespaces().Get(instance.Namespace, metav1.GetOptions{})
if err != nil {
s := fmt.Sprintf("Failed to get namespace %q during instance create: %s", instance.Namespace, err)
glog.Infof(
`%s "%s/%s": %s`,
typeSI, instance.Namespace, instance.Name, s,
)
c.recorder.Event(instance, corev1.EventTypeWarning, errorFindingNamespaceServiceInstanceReason, s)
setServiceInstanceCondition(
toUpdate,
v1beta1.ServiceInstanceConditionReady,
v1beta1.ConditionFalse,
errorFindingNamespaceServiceInstanceReason,
"Error finding namespace for instance. "+s,
)
if _, err := c.updateServiceInstanceStatus(toUpdate); err != nil {
return err
}
return err
}
var (
parameters map[string]interface{}
parametersChecksum string
rawParametersWithRedaction *runtime.RawExtension
)
if instance.Spec.Parameters != nil || instance.Spec.ParametersFrom != nil {
var parametersWithSecretsRedacted map[string]interface{}
parameters, parametersWithSecretsRedacted, err = buildParameters(c.kubeClient, instance.Namespace, instance.Spec.ParametersFrom, instance.Spec.Parameters)
if err != nil {
s := fmt.Sprintf(`Failed to prepare ServiceInstance parameters %s: %s`, instance.Spec.Parameters, err)
glog.Warningf(
`%s "%s/%s": %s`,
typeSI, instance.Namespace, instance.Name, s,
)
c.recorder.Event(instance, corev1.EventTypeWarning, errorWithParameters, s)
setServiceInstanceCondition(
toUpdate,
v1beta1.ServiceInstanceConditionReady,
v1beta1.ConditionFalse,
errorWithParameters,
s,
)
if _, err := c.updateServiceInstanceStatus(toUpdate); err != nil {
return err
}
return err
}
parametersChecksum, err = generateChecksumOfParameters(parameters)
if err != nil {
s := fmt.Sprintf("Failed to generate the parameters checksum to store in Status: %s", err)
glog.Infof(
`%s "%s/%s": %s`,
typeSI, instance.Namespace, instance.Name, s,
)
c.recorder.Eventf(instance, corev1.EventTypeWarning, errorWithParameters, s)
setServiceInstanceCondition(
toUpdate,
v1beta1.ServiceInstanceConditionReady,
v1beta1.ConditionFalse,
errorWithParameters,
s)
if _, err := c.updateServiceInstanceStatus(toUpdate); err != nil {
return err
}
return err
}
marshalledParametersWithRedaction, err := MarshalRawParameters(parametersWithSecretsRedacted)
if err != nil {
s := fmt.Sprintf("Failed to marshal the parameters to store in the Status: %s", err)
glog.Infof(
`%s "%s/%s": %s`,
typeSI, instance.Namespace, instance.Name, s,
)
c.recorder.Eventf(instance, corev1.EventTypeWarning, errorWithParameters, s)
setServiceInstanceCondition(
toUpdate,
v1beta1.ServiceInstanceConditionReady,
v1beta1.ConditionFalse,
errorWithParameters,
s)
if _, err := c.updateServiceInstanceStatus(toUpdate); err != nil {
return err
}
return err
}
rawParametersWithRedaction = &runtime.RawExtension{
Raw: marshalledParametersWithRedaction,
}
}
toUpdate.Status.InProgressProperties = &v1beta1.ServiceInstancePropertiesState{
ClusterServicePlanExternalName: servicePlan.Spec.ExternalName,
Parameters: rawParametersWithRedaction,
ParametersChecksum: parametersChecksum,
UserInfo: instance.Spec.UserInfo,
}
var originatingIdentity *osb.OriginatingIdentity
if utilfeature.DefaultFeatureGate.Enabled(scfeatures.OriginatingIdentity) {
originatingIdentity, err = buildOriginatingIdentity(instance.Spec.UserInfo)
if err != nil {
s := fmt.Sprintf("Error building originating identity headers for provisioning: %v", err)
glog.Warningf(
`%s "%s/%s": %s`,
typeSI, instance.Namespace, instance.Name, s,
)
c.recorder.Event(instance, corev1.EventTypeWarning, errorWithOriginatingIdentity, s)
setServiceInstanceCondition(
toUpdate,
v1beta1.ServiceInstanceConditionReady,
v1beta1.ConditionFalse,
errorWithOriginatingIdentity,
s,
)
if _, err := c.updateServiceInstanceStatus(toUpdate); err != nil {
return err
}
return err
}
}
var (
isProvisioning bool
provisionRequest *osb.ProvisionRequest
updateRequest *osb.UpdateInstanceRequest
currentOperation v1beta1.ServiceInstanceOperation
provisionOrUpdateText string
provisionedOrUpdatedText string
provisioningOrUpdatingText string
)
if toUpdate.Status.ReconciledGeneration == 0 {
isProvisioning = true
// osb client handles whether or not to really send this based
// on the version of the client.
requestContext := map[string]interface{}{
"platform": ContextProfilePlatformKubernetes,
"namespace": instance.Namespace,
}
provisionRequest = &osb.ProvisionRequest{
AcceptsIncomplete: true,
InstanceID: instance.Spec.ExternalID,
ServiceID: serviceClass.Spec.ExternalID,
PlanID: servicePlan.Spec.ExternalID,
Parameters: parameters,
OrganizationGUID: string(ns.UID),
SpaceGUID: string(ns.UID),
Context: requestContext,
OriginatingIdentity: originatingIdentity,
}
currentOperation = v1beta1.ServiceInstanceOperationProvision
provisionOrUpdateText = "provision"
provisionedOrUpdatedText = "provisioned"
provisioningOrUpdatingText = "provisioning"
} else {
isProvisioning = false
updateRequest = &osb.UpdateInstanceRequest{
AcceptsIncomplete: true,
InstanceID: instance.Spec.ExternalID,
ServiceID: serviceClass.Spec.ExternalID,
OriginatingIdentity: originatingIdentity,
}
// Only send the plan ID if the plan name has changed from what the Broker has
if toUpdate.Status.ExternalProperties == nil ||
toUpdate.Status.InProgressProperties.ClusterServicePlanExternalName != toUpdate.Status.ExternalProperties.ClusterServicePlanExternalName {
planID := servicePlan.Spec.ExternalID
updateRequest.PlanID = &planID
}
// Only send the parameters if they have changed from what the Broker has
if toUpdate.Status.ExternalProperties == nil ||
toUpdate.Status.InProgressProperties.ParametersChecksum != toUpdate.Status.ExternalProperties.ParametersChecksum {
updateRequest.Parameters = parameters
}
currentOperation = v1beta1.ServiceInstanceOperationUpdate
provisionOrUpdateText = "update"
provisionedOrUpdatedText = "updated"
provisioningOrUpdatingText = "updating"
}
if toUpdate.Status.CurrentOperation == "" {
toUpdate, err = c.recordStartOfServiceInstanceOperation(toUpdate, currentOperation)
if err != nil {
// There has been an update to the instance. Start reconciliation
// over with a fresh view of the instance.
return err
}
}
var provisionResponse *osb.ProvisionResponse
var updateResponse *osb.UpdateInstanceResponse
if isProvisioning {
glog.V(4).Infof(
`%s "%s/%s": Provisioning a new ServiceInstance of ClusterServiceClass (K8S: %q ExternalName: %q) at ClusterServiceBroker %q`,
typeSI, instance.Namespace, instance.Name, serviceClass.Name, serviceClass.Spec.ExternalName, brokerName,
)
provisionResponse, err = brokerClient.ProvisionInstance(provisionRequest)
} else {
glog.V(4).Infof(
`%s "%s/%s": Updating ServiceInstance of ClusterServiceClass (K8S: %q ExternalName: %q) at ClusterServiceBroker %q`,
typeSI, instance.Namespace, instance.Name, serviceClass.Name, serviceClass.Spec.ExternalName, brokerName,
)
updateResponse, err = brokerClient.UpdateInstance(updateRequest)
}
if err != nil {
// There are two buckets of errors to handle:
// 1. Errors that represent a failure response from the broker
// 2. All other errors
if httpErr, ok := osb.IsHTTPError(err); ok {
reason := errorProvisionCallFailedReason
if !isProvisioning {
reason = errorUpdateInstanceCallFailedReason
}
// An error from the broker represents a permanent failure and
// should not be retried; set the Failed condition.
s := fmt.Sprintf(
"Error %v ServiceInstance of ClusterServiceClass (K8S: %q ExternalName: %q) at ClusterServiceBroker %q: %s",
provisioningOrUpdatingText, serviceClass.Name, serviceClass.Spec.ExternalName, brokerName, httpErr,
)
glog.Warningf(
`%s "%s/%s": %s`,
typeSI, instance.Namespace, instance.Name, s,
)
c.recorder.Event(instance, corev1.EventTypeWarning, reason, s)
setServiceInstanceCondition(
toUpdate,
v1beta1.ServiceInstanceConditionFailed,
v1beta1.ConditionTrue,
"ClusterServiceBrokerReturnedFailure",
s)
if isProvisioning && shouldStartOrphanMitigation(httpErr.StatusCode) {
c.setServiceInstanceStartOrphanMitigation(toUpdate)
if _, err := c.updateServiceInstanceStatus(toUpdate); err != nil {
return err
}
return httpErr
}
setServiceInstanceCondition(
toUpdate,
v1beta1.ServiceInstanceConditionReady,
v1beta1.ConditionFalse,
reason,
fmt.Sprintf("ClusterServiceBroker returned a failure for %v call; operation will not be retried: %v", provisionOrUpdateText, s))
c.clearServiceInstanceCurrentOperation(toUpdate)
if _, err := c.updateServiceInstanceStatus(toUpdate); err != nil {
return err
}
return nil
}
reason := errorErrorCallingProvisionReason
if !isProvisioning {
reason = errorErrorCallingUpdateInstanceReason
}
s := fmt.Sprintf("Error communicating with broker for %q: %s", provisioningOrUpdatingText, err)
glog.Warningf(
`%s "%s/%s": %s`,
typeSI, instance.Namespace, instance.Name, s,
)
c.recorder.Event(instance, corev1.EventTypeWarning, reason, s)
urlErr, ok := err.(*url.Error)
if ok && urlErr.Timeout() {
var (
reason string
message string
)
if isProvisioning {
reason = errorErrorCallingProvisionReason
} else {
reason = errorErrorCallingUpdateInstanceReason
}
message = "Communication with the ClusterServiceBroker timed out; operation will not be retried: " + s
// Communication to the broker timed out. Treat as terminal failure and
// begin orphan mitigation.
setServiceInstanceCondition(
toUpdate,
v1beta1.ServiceInstanceConditionFailed,
v1beta1.ConditionTrue,
reason,
message)
if isProvisioning {
c.setServiceInstanceStartOrphanMitigation(toUpdate)
} else {
setServiceInstanceCondition(
toUpdate,
v1beta1.ServiceInstanceConditionReady,
v1beta1.ConditionFalse,
reason,
message)
c.clearServiceInstanceCurrentOperation(toUpdate)
}
if _, err := c.updateServiceInstanceStatus(toUpdate); err != nil {
return err
}
return err
}
setServiceInstanceCondition(
toUpdate,
v1beta1.ServiceInstanceConditionReady,
v1beta1.ConditionFalse,
reason,
fmt.Sprintf("The %v call failed and will be retried: %v", provisionOrUpdateText, s))
if !time.Now().Before(toUpdate.Status.OperationStartTime.Time.Add(c.reconciliationRetryDuration)) {
s := "Stopping reconciliation retries because too much time has elapsed"
glog.Infof(
`%s "%s/%s": %s`,
typeSI, instance.Namespace, instance.Name, s,
)
c.recorder.Event(instance, corev1.EventTypeWarning, errorReconciliationRetryTimeoutReason, s)
setServiceInstanceCondition(toUpdate,
v1beta1.ServiceInstanceConditionFailed,
v1beta1.ConditionTrue,
errorReconciliationRetryTimeoutReason,
s)
c.clearServiceInstanceCurrentOperation(toUpdate)
if _, err := c.updateServiceInstanceStatus(toUpdate); err != nil {
return err
}
return nil
}
if _, err := c.updateServiceInstanceStatus(toUpdate); err != nil {
return err
}
return err
}
if isProvisioning && provisionResponse.DashboardURL != nil && *provisionResponse.DashboardURL != "" {
url := *provisionResponse.DashboardURL
toUpdate.Status.DashboardURL = &url
}
// ClusterServiceBroker can return either a synchronous or asynchronous
// response, if the response is StatusAccepted it's an async