/
credentialsrequest_controller.go
1081 lines (962 loc) · 38.8 KB
/
credentialsrequest_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
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 2018 The OpenShift 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 credentialsrequest
import (
"context"
"fmt"
"reflect"
"time"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/util/retry"
log "github.com/sirupsen/logrus"
"golang.org/x/time/rate"
corev1applyconfigurations "k8s.io/client-go/applyconfigurations/core/v1"
corev1client "k8s.io/client-go/kubernetes/typed/core/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/util/workqueue"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller"
"sigs.k8s.io/controller-runtime/pkg/event"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/predicate"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"sigs.k8s.io/controller-runtime/pkg/source"
configv1 "github.com/openshift/api/config/v1"
operatorv1 "github.com/openshift/api/operator/v1"
minterv1 "github.com/openshift/cloud-credential-operator/pkg/apis/cloudcredential/v1"
"github.com/openshift/cloud-credential-operator/pkg/operator/constants"
"github.com/openshift/cloud-credential-operator/pkg/operator/credentialsrequest/actuator"
"github.com/openshift/cloud-credential-operator/pkg/operator/metrics"
"github.com/openshift/cloud-credential-operator/pkg/operator/status"
"github.com/openshift/cloud-credential-operator/pkg/operator/utils"
)
const (
controllerName = "credreq"
labelControllerName = controllerName + "_labeller"
namespaceMissing = "NamespaceMissing"
namespaceExists = "NamespaceExists"
cloudCredsInsufficient = "CloudCredsInsufficient"
cloudCredsSufficient = "CloudCredsSufficient"
credentialsProvisionFailure = "CredentialsProvisionFailure"
credentialsProvisionSuccess = "CredentialsProvisionSuccess"
cloudCredDeprovisionFailure = "CloudCredDeprovisionFailure"
cloudCredDeprovisionSuccess = "CloudCredDeprovisionSuccess"
credentialsRequestInfraMismatch = "InfrastructureMismatch"
cloudResourceOrphaned = "CloudResourceOrphaned"
cloudResourceCleaned = "CloudResourceCleaned"
)
var (
syncPeriod = time.Hour
// Set some extra time when requeueing so we are guaranteed that the
// syncPeriod has elapsed when we re-reconcile an object.
defaultRequeueTime = syncPeriod + time.Minute*10
)
// AddWithActuator creates a new CredentialsRequest Controller and adds it to the Manager with
// default RBAC. The Manager will set fields on the Controller and Start it when
// the Manager is Started.
func AddWithActuator(mgr, adminMgr manager.Manager, actuator actuator.Actuator, platType configv1.PlatformType, mutatingClient corev1client.CoreV1Interface) error {
if err := add(mgr, adminMgr, newReconciler(mgr, adminMgr, actuator, platType)); err != nil {
return err
}
return addLabelController(mgr, mutatingClient)
}
// newReconciler returns a new reconcile.Reconciler
func newReconciler(mgr, adminMgr manager.Manager, actuator actuator.Actuator, platType configv1.PlatformType) reconcile.Reconciler {
r := &ReconcileCredentialsRequest{
Client: mgr.GetClient(),
AdminClient: adminMgr.GetClient(),
Actuator: actuator,
platformType: platType,
}
status.AddHandler(controllerName, r)
return r
}
// add adds a new Controller to mgr with r as the reconcile.Reconciler
func add(mgr, adminMgr manager.Manager, r reconcile.Reconciler) error {
operatorCache := mgr.GetCache()
name := "credentialsrequest_controller"
// Custom rateLimiter that sets minimum backoff to 2 seconds
rateLimiter := workqueue.NewMaxOfRateLimiter(
workqueue.NewItemExponentialFailureRateLimiter(2*time.Second, 1000*time.Second),
&workqueue.BucketRateLimiter{Limiter: rate.NewLimiter(rate.Limit(10), 100)},
)
c, err := controller.New(name, mgr, controller.Options{
Reconciler: r,
RateLimiter: rateLimiter,
})
if err != nil {
return err
}
// Watch for changes to CredentialsRequest
// TODO: we should limit the namespaces where we watch, we want all requests in one namespace so anyone with admin on a namespace cannot create
// a request for any credentials they want.
err = c.Watch(source.Kind(operatorCache, &minterv1.CredentialsRequest{}), &handler.EnqueueRequestForObject{})
if err != nil {
return err
}
// Define a mapping for secrets to the credentials requests that created them. (if applicable)
// We use an annotation on secrets that refers back to their owning credentials request because
// the normal owner reference is not namespaced, and we want to support credentials requests being
// in a centralized namespace, but writing secrets into component namespaces.
targetCredSecretMapFunc := handler.EnqueueRequestsFromMapFunc(func(ctx context.Context, a client.Object) []reconcile.Request {
namespace, name, err := cache.SplitMetaNamespaceKey(a.GetAnnotations()[minterv1.AnnotationCredentialsRequest])
if err != nil {
log.WithField("labels", a.GetAnnotations()).WithError(err).Error("error splitting namespace key for label")
// WARNING: No way to return an error here...
return []reconcile.Request{}
}
log.WithField("cr", fmt.Sprintf("%s/%s", namespace, name)).Debug("parsed annotation")
return []reconcile.Request{
{NamespacedName: types.NamespacedName{
Name: name,
Namespace: namespace,
}},
}
})
// These functions are used to determine if a event for the given Secret should trigger a sync:
p := predicate.Funcs{
UpdateFunc: func(e event.UpdateEvent) bool {
// The object doesn't contain our label, so we have nothing to reconcile.
if _, ok := e.ObjectOld.GetAnnotations()[minterv1.AnnotationCredentialsRequest]; !ok {
return false
}
return true
},
CreateFunc: func(e event.CreateEvent) bool {
if _, ok := e.Object.GetAnnotations()[minterv1.AnnotationCredentialsRequest]; !ok {
return false
}
return true
},
DeleteFunc: func(e event.DeleteEvent) bool {
if _, ok := e.Object.GetAnnotations()[minterv1.AnnotationCredentialsRequest]; !ok {
return false
}
return true
},
}
// Watch Secrets and reconcile if we see one with our label.
err = c.Watch(
source.Kind(mgr.GetCache(), &corev1.Secret{}),
targetCredSecretMapFunc,
p)
if err != nil {
return err
}
// allCredRequestsMapFn simply looks up all CredentialsRequests and requests they be reconciled.
allCredRequestsMapFn := handler.EnqueueRequestsFromMapFunc(func(ctx context.Context, a client.Object) []reconcile.Request {
log.Info("requeueing all CredentialsRequests")
crs := &minterv1.CredentialsRequestList{}
err := mgr.GetClient().List(ctx, crs)
var requests []reconcile.Request
if err != nil {
log.WithError(err).Error("error listing all cred requests for requeue")
return requests
}
for _, cr := range crs.Items {
requests = append(requests, reconcile.Request{
NamespacedName: types.NamespacedName{
Name: cr.Name,
Namespace: cr.Namespace,
},
})
}
return requests
})
adminCredSecretPredicate := predicate.Funcs{
UpdateFunc: func(e event.UpdateEvent) bool {
return IsAdminCredSecret(e.ObjectNew.GetNamespace(), e.ObjectNew.GetName())
},
CreateFunc: func(e event.CreateEvent) bool {
return IsAdminCredSecret(e.Object.GetNamespace(), e.Object.GetName())
},
DeleteFunc: func(e event.DeleteEvent) bool {
return IsAdminCredSecret(e.Object.GetNamespace(), e.Object.GetName())
},
}
// Watch Secrets and reconcile if we see an event for an admin credential secret in kube-system.
err = c.Watch(
source.Kind(adminMgr.GetCache(), &corev1.Secret{}),
allCredRequestsMapFn,
adminCredSecretPredicate)
if err != nil {
return err
}
// Monitor namespace creation, and check out list of credentials requests for any destined
// for that new namespace. This allows us to be up and running for other components that don't
// yet exist, but will.
namespaceMapFn := handler.EnqueueRequestsFromMapFunc(func(ctx context.Context, a client.Object) []reconcile.Request {
// Iterate all CredentailsRequests to determine if we have any that target
// this new namespace. We are not anticipating huge numbers of CredentialsRequests,
// nor namespace creations.
newNamespace := a.GetName()
log.WithField("namespace", newNamespace).Debug("checking for credentails requests targeting namespace")
crs := &minterv1.CredentialsRequestList{}
// Fixme: check for errors
mgr.GetClient().List(ctx, crs)
requests := []reconcile.Request{}
for _, cr := range crs.Items {
if !cr.Status.Provisioned && cr.Spec.SecretRef.Namespace == newNamespace {
log.WithFields(log.Fields{
"namespace": newNamespace,
"cr": fmt.Sprintf("%s/%s", cr.Spec.SecretRef.Namespace, cr.Spec.SecretRef.Name),
}).Info("found credentials request for namespace")
requests = append(requests, reconcile.Request{
NamespacedName: types.NamespacedName{
Name: cr.Name,
Namespace: cr.Namespace,
},
})
}
}
return requests
})
namespacePred := predicate.Funcs{
CreateFunc: func(e event.CreateEvent) bool {
// WARNING: on restart, the controller sees all namespaces as creates even if they
// are pre-existing
return true
},
UpdateFunc: func(e event.UpdateEvent) bool {
return false
},
DeleteFunc: func(e event.DeleteEvent) bool {
return false
},
}
err = c.Watch(
source.Kind(operatorCache, &metav1.PartialObjectMetadata{
TypeMeta: metav1.TypeMeta{
Kind: "Namespace",
APIVersion: "v1",
},
}),
namespaceMapFn,
namespacePred)
if err != nil {
return err
}
// Monitor the cloud-credential-operator-config configmap to check if operator is re-enabled.
// Check if attempts were made to delete the credentials requests when the operator was disabled.
// We have to have to reconcile all those credential requests.
// Check if operator is re-enabled in cloud-credential-operator-config configmap
configMapPredicate := predicate.Funcs{
UpdateFunc: func(e event.UpdateEvent) bool {
return isCloudCredOperatorConfigMap(e.ObjectNew)
},
CreateFunc: func(e event.CreateEvent) bool {
return isCloudCredOperatorConfigMap(e.Object)
},
DeleteFunc: func(e event.DeleteEvent) bool {
return isCloudCredOperatorConfigMap(e.Object)
},
}
err = c.Watch(
source.Kind(operatorCache, &corev1.ConfigMap{}),
allCredRequestsMapFn,
configMapPredicate)
if err != nil {
return err
}
// Watch the CloudCredential config object and reconcile everything on changes.
err = c.Watch(
source.Kind(operatorCache, &operatorv1.CloudCredential{}),
allCredRequestsMapFn,
)
if err != nil {
return err
}
return nil
}
// addLabelController adds a new Controller managing labels to mgr
func addLabelController(mgr manager.Manager, mutatingClient corev1client.CoreV1Interface) error {
labelReconciler := &ReconcileSecretMissingLabel{
cachedClient: mgr.GetClient(),
mutatingClient: mutatingClient,
}
labelController, err := controller.New(labelControllerName, mgr, controller.Options{
Reconciler: labelReconciler,
})
if err != nil {
return err
}
missingLabelSecretsMapFn := handler.EnqueueRequestsFromMapFunc(func(_ context.Context, a client.Object) []reconcile.Request {
return []reconcile.Request{
{
NamespacedName: types.NamespacedName{
Name: a.GetName(),
Namespace: a.GetNamespace(),
},
},
}
})
missingLabelCredSecretPredicate := predicate.Funcs{
UpdateFunc: func(e event.UpdateEvent) bool {
return IsMissingSecretLabel(e.ObjectNew)
},
CreateFunc: func(e event.CreateEvent) bool {
return IsMissingSecretLabel(e.Object)
},
DeleteFunc: func(e event.DeleteEvent) bool {
return IsMissingSecretLabel(e.Object)
},
}
err = labelController.Watch(
source.Kind(mgr.GetCache(), &corev1.Secret{}),
missingLabelSecretsMapFn,
missingLabelCredSecretPredicate)
if err != nil {
return err
}
status.AddHandler(labelControllerName, labelReconciler)
return nil
}
// IsMissingSecretLabel determines if the secret was created by the CCO but has not been labelled yet
func IsMissingSecretLabel(secret metav1.Object) bool {
_, hasAnnotation := secret.GetAnnotations()[minterv1.AnnotationCredentialsRequest]
value, hasLabel := secret.GetLabels()[minterv1.LabelCredentialsRequest]
hasValue := hasLabel && value == minterv1.LabelCredentialsRequestValue
return hasAnnotation && (!hasLabel || !hasValue)
}
type ReconcileSecretMissingLabel struct {
cachedClient client.Client
mutatingClient corev1client.SecretsGetter
}
func (r *ReconcileSecretMissingLabel) GetConditions(logger log.FieldLogger) ([]configv1.ClusterOperatorStatusCondition, error) {
var secrets corev1.SecretList
if err := r.cachedClient.List(context.TODO(), &secrets); err != nil {
return nil, err
}
var missing int
for _, item := range secrets.Items {
if IsMissingSecretLabel(&item) {
missing += 1
}
}
if missing > 0 {
return []configv1.ClusterOperatorStatusCondition{{
Type: configv1.OperatorProgressing,
Status: configv1.ConditionTrue,
Reason: "LabelsMissing",
Message: fmt.Sprintf("%d secrets created for CredentialsRequests have not been labelled", missing),
}}, nil
}
return []configv1.ClusterOperatorStatusCondition{}, nil
}
func (r *ReconcileSecretMissingLabel) GetRelatedObjects(logger log.FieldLogger) ([]configv1.ObjectReference, error) {
return nil, nil
}
func (r *ReconcileSecretMissingLabel) Name() string {
return labelControllerName
}
var _ reconcile.Reconciler = (*ReconcileSecretMissingLabel)(nil)
var _ status.Handler = (*ReconcileSecretMissingLabel)(nil)
func (r *ReconcileSecretMissingLabel) Reconcile(ctx context.Context, request reconcile.Request) (reconcile.Result, error) {
start := time.Now()
logger := log.WithFields(log.Fields{
"controller": labelControllerName,
"secret": fmt.Sprintf("%s/%s", request.NamespacedName.Namespace, request.NamespacedName.Name),
})
defer func() {
dur := time.Since(start)
metrics.MetricControllerReconcileTime.WithLabelValues(labelControllerName).Observe(dur.Seconds())
}()
logger.Info("syncing secret")
secret := &corev1.Secret{}
err := r.cachedClient.Get(ctx, request.NamespacedName, secret)
if err != nil {
if errors.IsNotFound(err) {
logger.Debug("secret no longer exists")
return reconcile.Result{}, nil
}
logger.WithError(err).Error("error getting secret, re-queuing")
return reconcile.Result{}, err
}
applyConfig := corev1applyconfigurations.Secret(secret.Name, secret.Namespace)
applyConfig.WithLabels(map[string]string{
minterv1.LabelCredentialsRequest: minterv1.LabelCredentialsRequestValue,
})
if _, err := r.mutatingClient.Secrets(secret.Namespace).Apply(ctx, applyConfig, metav1.ApplyOptions{
Force: true, // we're the authoritative owner of this field and should not allow anyone to stomp it
FieldManager: labelControllerName,
}); err != nil {
logger.WithError(err).Error("failed to update label")
return reconcile.Result{}, err
}
return reconcile.Result{}, nil
}
// isCloudCredOperatorConfigMap returns true if given configmap is cloud-credential-operator-config configmap
func isCloudCredOperatorConfigMap(cm metav1.Object) bool {
return cm.GetName() == constants.CloudCredOperatorConfigMap && cm.GetNamespace() == minterv1.CloudCredOperatorNamespace
}
func IsAdminCredSecret(namespace, secretName string) bool {
if namespace == constants.CloudCredSecretNamespace {
if secretName == constants.AWSCloudCredSecretName ||
secretName == constants.AzureCloudCredSecretName ||
secretName == constants.GCPCloudCredSecretName ||
secretName == constants.OpenStackCloudCredsSecretName ||
secretName == constants.OvirtCloudCredsSecretName ||
secretName == constants.KubevirtCloudCredSecretName ||
secretName == constants.VSphereCloudCredSecretName {
log.WithField("secret", secretName).WithField("namespace", namespace).Info("observed admin cloud credential secret event")
return true
}
}
return false
}
var _ reconcile.Reconciler = &ReconcileCredentialsRequest{}
// ReconcileCredentialsRequest reconciles a CredentialsRequest object
type ReconcileCredentialsRequest struct {
client.Client
AdminClient client.Client
Actuator actuator.Actuator
platformType configv1.PlatformType
}
// Reconcile reads that state of the cluster for a CredentialsRequest object and
// makes changes based on the state read and what is in the CredentialsRequest.Spec
// Automatically generate RBAC rules to allow the Controller to read and write required types.
// +kubebuilder:rbac:groups=cloudcredential.openshift.io,resources=credentialsrequests;credentialsrequests/status;credentialsrequests/finalizers,verbs=get;list;watch;create;update;patch;delete
// Configmaps required for leader election:
// +kubebuilder:rbac:groups=core,resources=secrets;configmaps;events,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=core,resources=namespaces,verbs=get;list;watch
// +kubebuilder:rbac:groups=config.openshift.io,resources=clusterversions,verbs=get;list;watch
// +kubebuilder:rbac:groups=config.openshift.io,resources=infrastructures;dnses,verbs=get;list;watch
// +kubebuilder:rbac:groups=config.openshift.io,resources=clusteroperators;clusteroperators/status,verbs=create;get;update;list;watch
func (r *ReconcileCredentialsRequest) Reconcile(ctx context.Context, request reconcile.Request) (reconcile.Result, error) {
start := time.Now()
logger := log.WithFields(log.Fields{
"controller": controllerName,
"cr": fmt.Sprintf("%s/%s", request.NamespacedName.Namespace, request.NamespacedName.Name),
})
defer func() {
dur := time.Since(start)
metrics.MetricControllerReconcileTime.WithLabelValues(controllerName).Observe(dur.Seconds())
}()
mode, conflict, err := utils.GetOperatorConfiguration(r.Client, logger)
stsDetected := false
stsDetected, _ = utils.IsTimedTokenCluster(r.Client, ctx, logger)
if err != nil {
logger.WithError(err).Error("error checking if operator is disabled")
return reconcile.Result{}, err
} else if conflict {
logger.Error("configuration conflict between legacy configmap and operator config")
return reconcile.Result{}, fmt.Errorf("configuration conflict")
} else if mode == operatorv1.CloudCredentialsModeManual {
if !stsDetected {
logger.Infof("operator set to disabled / manual mode")
return reconcile.Result{}, err
} else {
logger.Infof("operator detects STS enabled cluster")
}
}
logger.Info("syncing credentials request")
cr := &minterv1.CredentialsRequest{}
err = r.Get(ctx, request.NamespacedName, cr)
if err != nil {
if errors.IsNotFound(err) {
logger.Debug("credentials request no longer exists")
return reconcile.Result{}, nil
}
logger.WithError(err).Error("error getting credentials request, requeuing")
return reconcile.Result{}, err
}
logger = logger.WithFields(log.Fields{
"secret": fmt.Sprintf("%s/%s", cr.Spec.SecretRef.Namespace, cr.Spec.SecretRef.Name),
})
// Maintain a copy, but work on a copy of the credentials request:
origCR := cr
cr = cr.DeepCopy()
// Ignore CR if it's for a different cloud/infra
infraMatch, err := crInfraMatches(cr, r.platformType)
if err != nil {
logger.WithError(err).Error("failed to determine cloud platform type")
return reconcile.Result{}, err
}
if !infraMatch {
logger.Debug("ignoring cr as it is for a different cloud")
setIgnoredCondition(cr, r.platformType)
err := utils.UpdateStatus(r.Client, origCR, cr, logger)
if err != nil {
logger.WithError(err).Error("failed to update conditions")
}
return reconcile.Result{}, err
}
// Handle deletion and the deprovision finalizer:
if cr.DeletionTimestamp != nil {
if HasFinalizer(cr, minterv1.FinalizerDeprovision) {
err = r.Actuator.Delete(ctx, cr)
if err != nil {
logger.WithError(err).Error("actuator error deleting credentials exist")
setCredentialsDeprovisionFailureCondition(cr, true, err)
if err := utils.UpdateStatus(r.Client, origCR, cr, logger); err != nil {
logger.WithError(err).Error("failed to update condition")
return reconcile.Result{}, err
}
return reconcile.Result{}, err
} else {
setCredentialsDeprovisionFailureCondition(cr, false, nil)
if err := utils.UpdateStatus(r.Client, origCR, cr, logger); err != nil {
// Just a warning, since on deprovision we're just tearing down
// the CredentialsRequest object anyway
logger.Warnf("unable to update condition: %v", err)
}
}
// Delete the target secret if it exists:
targetSecret := &corev1.Secret{}
err := r.Client.Get(ctx, types.NamespacedName{Namespace: cr.Spec.SecretRef.Namespace, Name: cr.Spec.SecretRef.Name}, targetSecret)
sLog := logger.WithFields(log.Fields{
"targetSecret": fmt.Sprintf("%s/%s", cr.Spec.SecretRef.Namespace, cr.Spec.SecretRef.Name),
})
if err != nil {
if errors.IsNotFound(err) {
sLog.Debug("target secret does not exist")
} else {
sLog.WithError(err).Error("unexpected error getting target secret to delete")
return reconcile.Result{}, err
}
} else {
err := r.Client.Delete(ctx, targetSecret)
if err != nil {
sLog.WithError(err).Error("error deleting target secret")
return reconcile.Result{}, err
} else {
sLog.Info("target secret deleted successfully")
}
}
logger.Info("actuator deletion complete, removing finalizer")
err = r.removeDeprovisionFinalizer(ctx, cr)
if err != nil {
logger.WithError(err).Error("error removing deprovision finalizer")
return reconcile.Result{}, err
}
return reconcile.Result{}, nil
} else {
logger.Info("credentials request deleted and finalizer no longer present, nothing to do")
return reconcile.Result{}, nil
}
} else {
if !HasFinalizer(cr, minterv1.FinalizerDeprovision) {
// Ensure the finalizer is set on any not-deleted requests:
logger.Infof("adding finalizer: %s", minterv1.FinalizerDeprovision)
err = r.addDeprovisionFinalizer(ctx, cr)
if err != nil {
logger.WithError(err).Error("error adding finalizer")
}
return reconcile.Result{}, err
}
}
// Ensure the target namespace exists for the secret, if not, there's no point
// continuing:
targetNS := &corev1.Namespace{}
err = r.Get(ctx, types.NamespacedName{Name: cr.Spec.SecretRef.Namespace}, targetNS)
if err != nil {
if errors.IsNotFound(err) {
// TODO: technically we should deprovision if a credential was in this ns, but it
// was then deleted.
logger.Warn("secret namespace does not yet exist")
setMissingTargetNamespaceCondition(cr, true)
if err := utils.UpdateStatus(r.Client, origCR, cr, logger); err != nil {
logger.WithError(err).Error("error updating condition")
return reconcile.Result{}, err
}
// We will re-sync immediately when the namespace is created.
return reconcile.Result{}, nil
}
logger.WithError(err).Error("unexpected error looking up namespace")
return reconcile.Result{}, err
} else {
logger.Debug("found secret namespace")
setMissingTargetNamespaceCondition(cr, false)
}
// Check if the secret the credRequest wants created already exists
var crSecretExists bool
crSecret := &corev1.Secret{}
secretKey := types.NamespacedName{Name: cr.Spec.SecretRef.Name, Namespace: cr.Spec.SecretRef.Namespace}
if err := r.Get(ctx, secretKey, crSecret); err != nil {
if errors.IsNotFound(err) {
crSecretExists = false
} else {
logger.WithError(err).Error("could not query whether secret already exists")
return reconcile.Result{}, err
}
} else {
crSecretExists = true
}
if stsDetected {
// create time-based tokens based on settings in CredentialsRequests
logger.Debugf("timed token access cluster detected: %t, so not trying to provision with root secret",
stsDetected)
credsExists, err := r.Actuator.Exists(ctx, cr)
if err != nil {
logger.Errorf("error checking whether credentials already exists: %v", err)
return reconcile.Result{}, err
}
var syncErr error
syncErr = r.CreateOrUpdateOnCredsExist(ctx, credsExists, syncErr, cr)
var provisionErr bool
if syncErr != nil {
switch t := syncErr.(type) {
case actuator.ActuatorStatus:
if t.Reason() == minterv1.OrphanedCloudResource {
// not a critical error, just set the condition to communicate
// what happened
provisionErr = false
} else {
logger.Errorf("error syncing credentials: %v", syncErr)
provisionErr = true
}
updateErr := r.UpdateProvisionedStatus(cr, !provisionErr)
if updateErr != nil {
logger.Errorf("failed to update credentialsrequest status: %v", updateErr)
}
logger.Errorf("errored with condition: %v", t.Reason())
r.updateActuatorConditions(cr, t.Reason(), syncErr)
// Update the status of the CredentialsRequest object
err := r.Client.Status().Update(ctx, cr)
if err != nil {
logger.Errorf("failed to update credentialsrequest status: %v", err)
}
default:
logger.Errorf("unexpected error while syncing credentialsrequest: %v", syncErr)
return reconcile.Result{}, syncErr
}
} else {
// it worked so clear any actuator conditions if they exist
r.updateActuatorConditions(cr, "", nil)
updateErr := r.UpdateProvisionedStatus(cr, true)
if updateErr != nil {
logger.Errorf("failed to update credentialsrequest status: %v", updateErr)
}
}
} else {
credentialsRootSecret, err := r.Actuator.GetCredentialsRootSecret(ctx, cr)
if err != nil {
log.WithError(err).Debug("error retrieving cloud credentials secret, admin can remove root credentials in mint mode")
}
cloudCredsSecretUpdated := credentialsRootSecret != nil && credentialsRootSecret.ResourceVersion != cr.Status.LastSyncCloudCredsSecretResourceVersion
isStale := cr.Generation != cr.Status.LastSyncGeneration
hasRecentlySynced := cr.Status.LastSyncTimestamp != nil && cr.Status.LastSyncTimestamp.Add(syncPeriod).After(time.Now())
hasActiveFailureConditions := checkForFailureConditions(cr)
log.WithFields(log.Fields{
"cloudCredsSecretUpdated": cloudCredsSecretUpdated,
"NOT isStale": isStale,
"hasRecentlySynced": hasRecentlySynced,
"crSecretExists": crSecretExists,
"NOT hasActiveFailureConditions": hasActiveFailureConditions,
"cr.Status.Provisioned": cr.Status.Provisioned,
}).Debug("The above are ANDed together to determine: lastsyncgeneration is current and lastsynctimestamp < an hour ago")
if !cloudCredsSecretUpdated && !isStale && hasRecentlySynced && crSecretExists && !hasActiveFailureConditions && cr.Status.Provisioned {
logger.Debug("lastsyncgeneration is current and lastsynctimestamp was less than an hour ago, so no need to sync")
// Since we get no events for changes made directly to the cloud/platform, set the requeueAfter so that we at
// least periodically check that nothing out in the cloud/platform was modified that would require us to fix up
// users/permissions/tags/etc.
return reconcile.Result{RequeueAfter: defaultRequeueTime}, nil
}
credsExists, err := r.Actuator.Exists(ctx, cr)
if err != nil {
logger.Errorf("error checking whether credentials already exists: %v", err)
return reconcile.Result{}, err
}
var syncErr error
syncErr = r.CreateOrUpdateOnCredsExist(ctx, credsExists, syncErr, cr)
var provisionErr bool
if syncErr != nil {
switch t := syncErr.(type) {
case actuator.ActuatorStatus:
if t.Reason() == minterv1.OrphanedCloudResource {
// not a critical error, just set the condition to communicate
// what happened
provisionErr = false
} else {
logger.Errorf("error syncing credentials: %v", syncErr)
provisionErr = true
}
cr.Status.Provisioned = !provisionErr
logger.Errorf("errored with condition: %v", t.Reason())
r.updateActuatorConditions(cr, t.Reason(), syncErr)
default:
logger.Errorf("unexpected error while syncing credentialsrequest: %v", syncErr)
return reconcile.Result{}, syncErr
}
} else {
// it worked so clear any actuator conditions if they exist
r.updateActuatorConditions(cr, "", nil)
cr.Status.Provisioned = true
}
// if provisionErr == false, it means we successfully provisioned even if there
// were non-critical errors encountered
if !provisionErr {
cr.Status.LastSyncTimestamp = &metav1.Time{
Time: time.Now(),
}
cr.Status.LastSyncGeneration = origCR.Generation
if credentialsRootSecret != nil {
cr.Status.LastSyncCloudCredsSecretResourceVersion = credentialsRootSecret.ResourceVersion
}
}
err = utils.UpdateStatus(r.Client, origCR, cr, logger)
if err != nil {
logger.Errorf("error updating status: %v", err)
return reconcile.Result{}, err
}
// Since we get no events for changes made directly to the cloud/platform, set the requeueAfter so that we at
// least periodically check that nothing out in the cloud/platform was modified that would require us to fix up
// users/permissions/tags/etc.
if syncErr != nil && !provisionErr {
// We could have a non-critical error (eg OrphanedCloudResource) in the syncErr
// but we wouldn't want to treat that as an overal controller error while
// reconciling.
return reconcile.Result{RequeueAfter: defaultRequeueTime}, nil
} else {
return reconcile.Result{RequeueAfter: defaultRequeueTime}, syncErr
}
}
return reconcile.Result{RequeueAfter: defaultRequeueTime}, nil
}
func (r *ReconcileCredentialsRequest) CreateOrUpdateOnCredsExist(ctx context.Context, credsExists bool, syncErr error, cr *minterv1.CredentialsRequest) error {
if !credsExists {
syncErr = r.Actuator.Create(ctx, cr)
} else {
syncErr = r.Actuator.Update(ctx, cr)
}
return syncErr
}
func (r *ReconcileCredentialsRequest) updateActuatorConditions(cr *minterv1.CredentialsRequest, reason minterv1.CredentialsRequestConditionType, conditionError error) {
if reason == minterv1.CredentialsProvisionFailure {
setFailedToProvisionCredentialsRequest(cr, true, conditionError)
} else {
// If this is not our error, ensure the condition is cleared.
setFailedToProvisionCredentialsRequest(cr, false, nil)
}
if reason == minterv1.InsufficientCloudCredentials {
setInsufficientCredsCondition(cr, true)
} else {
// If this is not our error, ensure the condition is cleared.
setInsufficientCredsCondition(cr, false)
}
if reason == minterv1.OrphanedCloudResource {
setOrphanedCloudResourceCondition(cr, true, conditionError)
} else {
setOrphanedCloudResourceCondition(cr, false, conditionError)
}
return
}
func setMissingTargetNamespaceCondition(cr *minterv1.CredentialsRequest, missing bool) {
var (
msg, reason string
status corev1.ConditionStatus
updateCheck utils.UpdateConditionCheck
)
if missing {
msg = fmt.Sprintf("target namespace %v not found", cr.Spec.SecretRef.Namespace)
status = corev1.ConditionTrue
reason = namespaceMissing
updateCheck = utils.UpdateConditionIfReasonOrMessageChange
} else {
msg = fmt.Sprintf("target namespace %v found", cr.Spec.SecretRef.Namespace)
status = corev1.ConditionFalse
reason = namespaceExists
updateCheck = utils.UpdateConditionNever
}
cr.Status.Conditions = utils.SetCredentialsRequestCondition(cr.Status.Conditions, minterv1.MissingTargetNamespace,
status, reason, msg, updateCheck)
}
func setOrphanedCloudResourceCondition(cr *minterv1.CredentialsRequest, orphaned bool, orphanedErr error) {
var (
msg, reason string
status corev1.ConditionStatus
updateCheck utils.UpdateConditionCheck
)
if orphaned {
msg = fmt.Sprintf("unable to clean up previously created cloud resource: %s", orphanedErr.Error())
status = corev1.ConditionTrue
reason = cloudResourceOrphaned
updateCheck = utils.UpdateConditionIfReasonOrMessageChange
} else {
msg = "cleaned up cloud resources"
status = corev1.ConditionFalse
reason = cloudResourceCleaned
updateCheck = utils.UpdateConditionNever
}
cr.Status.Conditions = utils.SetCredentialsRequestCondition(cr.Status.Conditions, minterv1.OrphanedCloudResource,
status, reason, msg, updateCheck)
}
func setInsufficientCredsCondition(cr *minterv1.CredentialsRequest, insufficient bool) {
var (
msg, reason string
status corev1.ConditionStatus
updateCheck utils.UpdateConditionCheck
)
if insufficient {
msg = fmt.Sprintf("cloud creds are insufficient to satisfy CredentialsRequest")
status = corev1.ConditionTrue
reason = cloudCredsInsufficient
updateCheck = utils.UpdateConditionIfReasonOrMessageChange
} else {
msg = fmt.Sprintf("cloud credentials sufficient for minting or passthrough")
status = corev1.ConditionFalse
reason = cloudCredsSufficient
updateCheck = utils.UpdateConditionNever
}
cr.Status.Conditions = utils.SetCredentialsRequestCondition(cr.Status.Conditions, minterv1.InsufficientCloudCredentials,
status, reason, msg, updateCheck)
}
func setFailedToProvisionCredentialsRequest(cr *minterv1.CredentialsRequest, failed bool, err error) {
var (
msg, reason string
status corev1.ConditionStatus
updateCheck utils.UpdateConditionCheck
)
if failed {
msg = fmt.Sprintf("failed to grant creds: %v", utils.ErrorScrub(err))
status = corev1.ConditionTrue
reason = credentialsProvisionFailure
updateCheck = utils.UpdateConditionIfReasonOrMessageChange
} else {
msg = fmt.Sprintf("successfully granted credentials request")
status = corev1.ConditionFalse
reason = credentialsProvisionSuccess
updateCheck = utils.UpdateConditionNever
}
cr.Status.Conditions = utils.SetCredentialsRequestCondition(cr.Status.Conditions, minterv1.CredentialsProvisionFailure,
status, reason, msg, updateCheck)
}
func setCredentialsDeprovisionFailureCondition(cr *minterv1.CredentialsRequest, failed bool, err error) {
var (
msg, reason string
status corev1.ConditionStatus
updateCheck utils.UpdateConditionCheck
)
if failed {
msg = fmt.Sprintf("failed to deprovision resource: %v", utils.ErrorScrub(err))
status = corev1.ConditionTrue
reason = cloudCredDeprovisionFailure
updateCheck = utils.UpdateConditionIfReasonOrMessageChange
} else {
msg = fmt.Sprintf("deprovisioned cloud credential resource(s)")
status = corev1.ConditionFalse
reason = cloudCredDeprovisionSuccess
updateCheck = utils.UpdateConditionNever
}
cr.Status.Conditions = utils.SetCredentialsRequestCondition(cr.Status.Conditions, minterv1.CredentialsDeprovisionFailure,
status, reason, msg, updateCheck)
}
func setIgnoredCondition(cr *minterv1.CredentialsRequest, clusterPlatform configv1.PlatformType) {
// Only supporting the ability to set the condition
msg := fmt.Sprintf("CredentialsRequest is not for platform %s", clusterPlatform)
reason := credentialsRequestInfraMismatch
updateCheck := utils.UpdateConditionIfReasonOrMessageChange
status := corev1.ConditionTrue
cr.Status.Conditions = utils.SetCredentialsRequestCondition(cr.Status.Conditions, minterv1.Ignored,
status, reason, msg, updateCheck)
// Also clear any other conditions since we are ignoring this cred request,
// and we don't want to be in a degraded state b/c of cred requests that we're ignoring.
for _, cond := range minterv1.FailureConditionTypes {
cr.Status.Conditions = utils.SetCredentialsRequestCondition(cr.Status.Conditions, cond,
corev1.ConditionFalse, reason, msg, updateCheck)
}
}
func (r *ReconcileCredentialsRequest) addDeprovisionFinalizer(ctx context.Context, cr *minterv1.CredentialsRequest) error {
AddFinalizer(cr, minterv1.FinalizerDeprovision)
return r.Update(ctx, cr)
}
func (r *ReconcileCredentialsRequest) removeDeprovisionFinalizer(ctx context.Context, cr *minterv1.CredentialsRequest) error {
DeleteFinalizer(cr, minterv1.FinalizerDeprovision)
return r.Update(ctx, cr)
}
// HasFinalizer returns true if the given object has the given finalizer
func HasFinalizer(object metav1.Object, finalizer string) bool {
for _, f := range object.GetFinalizers() {
if f == finalizer {
return true
}
}