-
Notifications
You must be signed in to change notification settings - Fork 303
/
hostedcontrolplane_controller.go
4961 lines (4454 loc) · 217 KB
/
hostedcontrolplane_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
package hostedcontrolplane
import (
"context"
crand "crypto/rand"
"errors"
"fmt"
"math/big"
"net/http"
"os"
"sort"
"strings"
"time"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys"
azureutil "github.com/Azure/go-autorest/autorest/azure"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/openshift/hypershift/control-plane-operator/controllers/hostedcontrolplane/cco"
"github.com/openshift/hypershift/control-plane-operator/controllers/hostedcontrolplane/pkioperator"
pkimanifests "github.com/openshift/hypershift/control-plane-pki-operator/manifests"
"k8s.io/apimachinery/pkg/runtime"
awssdk "github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-sdk-go/service/ec2/ec2iface"
"github.com/aws/aws-sdk-go/service/kms"
"github.com/go-logr/logr"
routev1 "github.com/openshift/api/route/v1"
hyperv1 "github.com/openshift/hypershift/api/hypershift/v1beta1"
awsutil "github.com/openshift/hypershift/cmd/infra/aws/util"
"github.com/openshift/hypershift/control-plane-operator/controllers/hostedcontrolplane/autoscaler"
"github.com/openshift/hypershift/control-plane-operator/controllers/hostedcontrolplane/cloud/aws"
"github.com/openshift/hypershift/control-plane-operator/controllers/hostedcontrolplane/cloud/azure"
"github.com/openshift/hypershift/control-plane-operator/controllers/hostedcontrolplane/cloud/kubevirt"
"github.com/openshift/hypershift/control-plane-operator/controllers/hostedcontrolplane/cloud/powervs"
"github.com/openshift/hypershift/control-plane-operator/controllers/hostedcontrolplane/clusterpolicy"
"github.com/openshift/hypershift/control-plane-operator/controllers/hostedcontrolplane/cno"
"github.com/openshift/hypershift/control-plane-operator/controllers/hostedcontrolplane/common"
"github.com/openshift/hypershift/control-plane-operator/controllers/hostedcontrolplane/configoperator"
kubevirtcsi "github.com/openshift/hypershift/control-plane-operator/controllers/hostedcontrolplane/csi/kubevirt"
"github.com/openshift/hypershift/control-plane-operator/controllers/hostedcontrolplane/cvo"
"github.com/openshift/hypershift/control-plane-operator/controllers/hostedcontrolplane/dnsoperator"
"github.com/openshift/hypershift/control-plane-operator/controllers/hostedcontrolplane/etcd"
"github.com/openshift/hypershift/control-plane-operator/controllers/hostedcontrolplane/ignition"
"github.com/openshift/hypershift/control-plane-operator/controllers/hostedcontrolplane/ignitionserver"
"github.com/openshift/hypershift/control-plane-operator/controllers/hostedcontrolplane/imageprovider"
"github.com/openshift/hypershift/control-plane-operator/controllers/hostedcontrolplane/ingress"
"github.com/openshift/hypershift/control-plane-operator/controllers/hostedcontrolplane/ingressoperator"
"github.com/openshift/hypershift/control-plane-operator/controllers/hostedcontrolplane/kas"
"github.com/openshift/hypershift/control-plane-operator/controllers/hostedcontrolplane/kcm"
"github.com/openshift/hypershift/control-plane-operator/controllers/hostedcontrolplane/konnectivity"
"github.com/openshift/hypershift/control-plane-operator/controllers/hostedcontrolplane/machineapprover"
"github.com/openshift/hypershift/control-plane-operator/controllers/hostedcontrolplane/manifests"
"github.com/openshift/hypershift/control-plane-operator/controllers/hostedcontrolplane/mcs"
"github.com/openshift/hypershift/control-plane-operator/controllers/hostedcontrolplane/nto"
"github.com/openshift/hypershift/control-plane-operator/controllers/hostedcontrolplane/oapi"
"github.com/openshift/hypershift/control-plane-operator/controllers/hostedcontrolplane/oauth"
"github.com/openshift/hypershift/control-plane-operator/controllers/hostedcontrolplane/ocm"
"github.com/openshift/hypershift/control-plane-operator/controllers/hostedcontrolplane/olm"
"github.com/openshift/hypershift/control-plane-operator/controllers/hostedcontrolplane/pki"
"github.com/openshift/hypershift/control-plane-operator/controllers/hostedcontrolplane/registryoperator"
"github.com/openshift/hypershift/control-plane-operator/controllers/hostedcontrolplane/routecm"
"github.com/openshift/hypershift/control-plane-operator/controllers/hostedcontrolplane/scheduler"
"github.com/openshift/hypershift/control-plane-operator/controllers/hostedcontrolplane/snapshotcontroller"
"github.com/openshift/hypershift/control-plane-operator/controllers/hostedcontrolplane/storage"
supportawsutil "github.com/openshift/hypershift/support/awsutil"
"github.com/openshift/hypershift/support/capabilities"
"github.com/openshift/hypershift/support/certs"
"github.com/openshift/hypershift/support/conditions"
"github.com/openshift/hypershift/support/config"
"github.com/openshift/hypershift/support/events"
"github.com/openshift/hypershift/support/globalconfig"
"github.com/openshift/hypershift/support/metrics"
"github.com/openshift/hypershift/support/releaseinfo"
"github.com/openshift/hypershift/support/upsert"
"github.com/openshift/hypershift/support/util"
prometheusoperatorv1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1"
appsv1 "k8s.io/api/apps/v1"
batchv1 "k8s.io/api/batch/v1"
corev1 "k8s.io/api/core/v1"
policyv1 "k8s.io/api/policy/v1"
rbacv1 "k8s.io/api/rbac/v1"
"k8s.io/apimachinery/pkg/api/equality"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/duration"
utilerrors "k8s.io/apimachinery/pkg/util/errors"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/util/workqueue"
"k8s.io/utils/pointer"
"k8s.io/utils/ptr"
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/controller/controllerutil"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
)
const (
finalizer = "hypershift.openshift.io/finalizer"
DefaultAdminKubeconfigKey = "kubeconfig"
ImageStreamAutoscalerImage = "cluster-autoscaler"
ImageStreamClusterMachineApproverImage = "cluster-machine-approver"
resourceDeletionTimeout = 10 * time.Minute
hcpReadyRequeueInterval = 1 * time.Minute
hcpNotReadyRequeueInterval = 15 * time.Second
)
type InfrastructureStatus struct {
APIHost string
APIPort int32
OAuthEnabled bool
OAuthHost string
OAuthPort int32
KonnectivityHost string
KonnectivityPort int32
OpenShiftAPIHost string
OauthAPIServerHost string
PackageServerAPIAddress string
Message string
InternalHCPRouterHost string
NeedInternalRouter bool
ExternalHCPRouterHost string
NeedExternalRouter bool
}
func (s InfrastructureStatus) IsReady() bool {
isReady := len(s.APIHost) > 0 &&
len(s.KonnectivityHost) > 0 &&
s.APIPort > 0 &&
s.KonnectivityPort > 0
if s.OAuthEnabled {
isReady = isReady && len(s.OAuthHost) > 0 && s.OAuthPort > 0
}
if s.NeedInternalRouter {
isReady = isReady && len(s.InternalHCPRouterHost) > 0
}
if s.NeedExternalRouter {
isReady = isReady && len(s.ExternalHCPRouterHost) > 0
}
return isReady
}
type HostedControlPlaneReconciler struct {
client.Client
// ManagementClusterCapabilities can be asked for support of optional management cluster capabilities
ManagementClusterCapabilities capabilities.CapabiltyChecker
// SetDefaultSecurityContext is used to configure Security Context for containers
SetDefaultSecurityContext bool
// CertRotationScale determines how quickly we rotate certificates - should only be set faster in testing
CertRotationScale time.Duration
Log logr.Logger
ReleaseProvider releaseinfo.ProviderWithOpenShiftImageRegistryOverrides
createOrUpdate func(hcp *hyperv1.HostedControlPlane) upsert.CreateOrUpdateFN
EnableCIDebugOutput bool
OperateOnReleaseImage string
DefaultIngressDomain string
MetricsSet metrics.MetricsSet
SREConfigHash string
ec2Client ec2iface.EC2API
awsSession *session.Session
reconcileInfrastructureStatus func(ctx context.Context, hcp *hyperv1.HostedControlPlane) (InfrastructureStatus, error)
EnableCVOManagementClusterMetricsAccess bool
}
func (r *HostedControlPlaneReconciler) SetupWithManager(mgr ctrl.Manager, createOrUpdate upsert.CreateOrUpdateFN) error {
r.setup(createOrUpdate)
b := ctrl.NewControllerManagedBy(mgr).
For(&hyperv1.HostedControlPlane{}).
WithOptions(controller.Options{
RateLimiter: workqueue.NewItemExponentialFailureRateLimiter(1*time.Second, 10*time.Second),
})
for _, handler := range r.eventHandlers(mgr.GetScheme(), mgr.GetRESTMapper()) {
b.Watches(handler.obj, handler.handler)
}
if _, err := b.Build(r); err != nil {
return fmt.Errorf("failed setting up with a controller manager %w", err)
}
// Set based on SCC capability
// When SCC is available (OpenShift), the container's security context and UID range is automatically set
// When SCC is not available (Kubernetes), we want to explicitly set a default (non-root) security context
r.SetDefaultSecurityContext = !r.ManagementClusterCapabilities.Has(capabilities.CapabilitySecurityContextConstraint)
r.reconcileInfrastructureStatus = r.defaultReconcileInfrastructureStatus
r.ec2Client, r.awsSession = getEC2Client()
return nil
}
func getEC2Client() (ec2iface.EC2API, *session.Session) {
// AWS_SHARED_CREDENTIALS_FILE and AWS_REGION envvar should be set in operator deployment
// when reconciling an AWS hosted control plane
if os.Getenv("AWS_SHARED_CREDENTIALS_FILE") != "" {
awsSession := awsutil.NewSession("control-plane-operator", "", "", "", "")
awsConfig := awssdk.NewConfig()
ec2Client := ec2.New(awsSession, awsConfig)
return ec2Client, awsSession
}
return nil, nil
}
func isScrapeConfig(obj client.Object) bool {
switch obj.(type) {
case *prometheusoperatorv1.ServiceMonitor:
return true
case *prometheusoperatorv1.PodMonitor:
return true
}
return false
}
func isClusterVersionAvailable(hcp *hyperv1.HostedControlPlane) bool {
condition := meta.FindStatusCondition(hcp.Status.Conditions, string(hyperv1.ClusterVersionAvailable))
return condition != nil && condition.Status == metav1.ConditionTrue
}
func createOrUpdateWithDelayForScrapeConfigs(hcp *hyperv1.HostedControlPlane, upstreamCreateOrUpdate upsert.CreateOrUpdateFN) upsert.CreateOrUpdateFN {
return func(ctx context.Context, c client.Client, obj client.Object, f controllerutil.MutateFn) (controllerutil.OperationResult, error) {
// Skipping creation / update of scrape configs (servicemonitor and podmonitor resources) till condition ClusterVersionAvailable is met.
// Meeting this condition is equivalent to reach 'Complete' progress on the corresponding hosted cluster
if isScrapeConfig(obj) && !isClusterVersionAvailable(hcp) {
log := ctrl.LoggerFrom(ctx)
log.Info("Skipping creation/update of scrape config as "+string(hyperv1.ClusterVersionAvailable)+" condition is not yet met", "scrapeConfig", obj)
return controllerutil.OperationResultNone, nil
}
return upstreamCreateOrUpdate(ctx, c, obj, f)
}
}
func (r *HostedControlPlaneReconciler) setup(upstreamCreateOrUpdate upsert.CreateOrUpdateFN) {
createOrUpdateFactory := createOrUpdateWithOwnerRefFactory(upstreamCreateOrUpdate)
r.createOrUpdate = func(hcp *hyperv1.HostedControlPlane) upsert.CreateOrUpdateFN {
return createOrUpdateWithDelayForScrapeConfigs(hcp, createOrUpdateFactory(hcp))
}
}
type eventHandler struct {
obj client.Object
handler handler.EventHandler
}
func (r *HostedControlPlaneReconciler) eventHandlers(scheme *runtime.Scheme, restMapper meta.RESTMapper) []eventHandler {
handlers := []eventHandler{
{obj: &corev1.Event{}, handler: handler.EnqueueRequestsFromMapFunc(r.hostedControlPlaneInNamespace)},
{obj: &corev1.ConfigMap{}, handler: handler.EnqueueRequestsFromMapFunc(r.hostedControlPlaneInNamespace)},
{obj: &corev1.Service{}, handler: handler.EnqueueRequestForOwner(scheme, restMapper, &hyperv1.HostedControlPlane{})},
{obj: &appsv1.Deployment{}, handler: handler.EnqueueRequestForOwner(scheme, restMapper, &hyperv1.HostedControlPlane{})},
{obj: &appsv1.StatefulSet{}, handler: handler.EnqueueRequestForOwner(scheme, restMapper, &hyperv1.HostedControlPlane{})},
{obj: &corev1.Secret{}, handler: handler.EnqueueRequestForOwner(scheme, restMapper, &hyperv1.HostedControlPlane{})},
{obj: &corev1.ServiceAccount{}, handler: handler.EnqueueRequestForOwner(scheme, restMapper, &hyperv1.HostedControlPlane{})},
{obj: &policyv1.PodDisruptionBudget{}, handler: handler.EnqueueRequestForOwner(scheme, restMapper, &hyperv1.HostedControlPlane{})},
{obj: &prometheusoperatorv1.PodMonitor{}, handler: handler.EnqueueRequestForOwner(scheme, restMapper, &hyperv1.HostedControlPlane{})},
{obj: &prometheusoperatorv1.ServiceMonitor{}, handler: handler.EnqueueRequestForOwner(scheme, restMapper, &hyperv1.HostedControlPlane{})},
{obj: &prometheusoperatorv1.PrometheusRule{}, handler: handler.EnqueueRequestForOwner(scheme, restMapper, &hyperv1.HostedControlPlane{})},
{obj: &rbacv1.Role{}, handler: handler.EnqueueRequestForOwner(scheme, restMapper, &hyperv1.HostedControlPlane{})},
{obj: &rbacv1.RoleBinding{}, handler: handler.EnqueueRequestForOwner(scheme, restMapper, &hyperv1.HostedControlPlane{})},
{obj: &batchv1.CronJob{}, handler: handler.EnqueueRequestForOwner(scheme, restMapper, &hyperv1.HostedControlPlane{})},
}
if r.ManagementClusterCapabilities.Has(capabilities.CapabilityRoute) {
handlers = append(handlers, eventHandler{obj: &routev1.Route{}, handler: handler.EnqueueRequestForOwner(scheme, restMapper, &hyperv1.HostedControlPlane{})})
}
return handlers
}
func (r *HostedControlPlaneReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
r.Log = ctrl.LoggerFrom(ctx)
r.Log.Info("Reconciling")
// Fetch the hostedControlPlane instance
hostedControlPlane := &hyperv1.HostedControlPlane{}
err := r.Client.Get(ctx, req.NamespacedName, hostedControlPlane)
if err != nil {
if apierrors.IsNotFound(err) {
return ctrl.Result{}, nil
}
return ctrl.Result{}, err
}
originalHostedControlPlane := hostedControlPlane.DeepCopy()
// This is the best effort ping to the identity provider
// that enables access from the operator to the cloud provider resources.
healthCheckIdentityProvider(ctx, hostedControlPlane)
// We want to ensure the healthCheckIdentityProvider condition is in status before we go through the deletion timestamp path.
if err := r.Client.Status().Patch(ctx, hostedControlPlane, client.MergeFromWithOptions(originalHostedControlPlane, client.MergeFromWithOptimisticLock{})); err != nil {
return ctrl.Result{}, fmt.Errorf("failed to update status: %w", err)
}
originalHostedControlPlane = hostedControlPlane.DeepCopy()
// Return early if deleted
if !hostedControlPlane.DeletionTimestamp.IsZero() {
condition := &metav1.Condition{
Type: string(hyperv1.AWSDefaultSecurityGroupDeleted),
}
if shouldCleanupCloudResources(r.Log, hostedControlPlane) {
if code, destroyErr := r.destroyAWSDefaultSecurityGroup(ctx, hostedControlPlane); destroyErr != nil {
condition.Message = "failed to delete AWS default security group"
if code == "DependencyViolation" {
condition.Message = destroyErr.Error()
}
condition.Reason = hyperv1.AWSErrorReason
condition.Status = metav1.ConditionFalse
meta.SetStatusCondition(&hostedControlPlane.Status.Conditions, *condition)
if err := r.Client.Status().Patch(ctx, hostedControlPlane, client.MergeFromWithOptions(originalHostedControlPlane, client.MergeFromWithOptimisticLock{})); err != nil {
return ctrl.Result{}, fmt.Errorf("failed to update status on hcp for security group deletion: %w. Condition error message: %v", err, condition.Message)
}
if code == "UnauthorizedOperation" {
r.Log.Error(destroyErr, "Skipping AWS default security group deletion because of unauthorized operation.")
}
if code == "DependencyViolation" {
r.Log.Error(destroyErr, "Skipping AWS default security group deletion because of dependency violation.")
} else {
return ctrl.Result{}, fmt.Errorf("failed to delete AWS default security group: %w", destroyErr)
}
} else {
condition.Message = hyperv1.AllIsWellMessage
condition.Reason = hyperv1.AsExpectedReason
condition.Status = metav1.ConditionTrue
meta.SetStatusCondition(&hostedControlPlane.Status.Conditions, *condition)
if err := r.Client.Status().Patch(ctx, hostedControlPlane, client.MergeFromWithOptions(originalHostedControlPlane, client.MergeFromWithOptimisticLock{})); err != nil {
return ctrl.Result{}, fmt.Errorf("failed to update status on hcp for security group deletion: %w. Condition message: %v", err, condition.Message)
}
}
done, err := r.removeCloudResources(ctx, hostedControlPlane)
if err != nil {
return ctrl.Result{}, fmt.Errorf("failed to ensure cloud resources are removed: %w", err)
}
if !done {
return ctrl.Result{RequeueAfter: time.Minute}, nil
}
}
if controllerutil.ContainsFinalizer(hostedControlPlane, finalizer) {
originalHCP := hostedControlPlane.DeepCopy()
controllerutil.RemoveFinalizer(hostedControlPlane, finalizer)
if err := r.Patch(ctx, hostedControlPlane, client.MergeFromWithOptions(originalHCP, client.MergeFromWithOptimisticLock{})); err != nil {
return ctrl.Result{}, fmt.Errorf("failed to remove finalizer from cluster: %w", err)
}
}
return ctrl.Result{}, nil
}
// Ensure the hostedControlPlane has a finalizer for cleanup
if !controllerutil.ContainsFinalizer(hostedControlPlane, finalizer) {
originalHCP := hostedControlPlane.DeepCopy()
controllerutil.AddFinalizer(hostedControlPlane, finalizer)
if err := r.Patch(ctx, hostedControlPlane, client.MergeFromWithOptions(originalHCP, client.MergeFromWithOptimisticLock{})); err != nil {
return ctrl.Result{}, fmt.Errorf("failed to add finalizer to hostedControlPlane: %w", err)
}
}
if r.OperateOnReleaseImage != "" && r.OperateOnReleaseImage != util.HCPControlPlaneReleaseImage(hostedControlPlane) {
r.Log.Info("releaseImage is " + util.HCPControlPlaneReleaseImage(hostedControlPlane) + ", but this operator is configured for " + r.OperateOnReleaseImage + ", skipping reconciliation")
return ctrl.Result{}, nil
}
// Reconcile global configuration validation status
{
condition := metav1.Condition{
Type: string(hyperv1.ValidHostedControlPlaneConfiguration),
ObservedGeneration: hostedControlPlane.Generation,
}
if err := r.validateConfigAndClusterCapabilities(hostedControlPlane); err != nil {
condition.Status = metav1.ConditionFalse
condition.Message = err.Error()
condition.Reason = hyperv1.InsufficientClusterCapabilitiesReason
} else {
condition.Status = metav1.ConditionTrue
condition.Message = "Configuration passes validation"
condition.Reason = hyperv1.AsExpectedReason
}
meta.SetStatusCondition(&hostedControlPlane.Status.Conditions, condition)
}
// Reconcile etcd cluster status
{
newCondition := metav1.Condition{
Type: string(hyperv1.EtcdAvailable),
Status: metav1.ConditionUnknown,
Reason: hyperv1.StatusUnknownReason,
}
switch hostedControlPlane.Spec.Etcd.ManagementType {
case hyperv1.Managed:
r.Log.Info("Reconciling etcd cluster status for managed strategy")
sts := manifests.EtcdStatefulSet(hostedControlPlane.Namespace)
if err := r.Get(ctx, client.ObjectKeyFromObject(sts), sts); err != nil {
if apierrors.IsNotFound(err) {
newCondition = metav1.Condition{
Type: string(hyperv1.EtcdAvailable),
Status: metav1.ConditionFalse,
Reason: hyperv1.EtcdStatefulSetNotFoundReason,
}
} else {
return ctrl.Result{}, fmt.Errorf("failed to fetch etcd statefulset %s/%s: %w", sts.Namespace, sts.Name, err)
}
} else {
conditionPtr, err := r.etcdStatefulSetCondition(ctx, sts)
if err != nil {
return ctrl.Result{}, fmt.Errorf("failed to get etcd statefulset status: %w", err)
}
newCondition = *conditionPtr
}
case hyperv1.Unmanaged:
r.Log.Info("Assuming Etcd cluster is running in unmanaged etcd strategy")
newCondition = metav1.Condition{
Type: string(hyperv1.EtcdAvailable),
Status: metav1.ConditionTrue,
Reason: "EtcdRunning",
Message: "Etcd cluster is assumed to be running in unmanaged state",
}
}
newCondition.ObservedGeneration = hostedControlPlane.Generation
meta.SetStatusCondition(&hostedControlPlane.Status.Conditions, newCondition)
}
// Reconcile etcd restore status
if hostedControlPlane.Spec.Etcd.ManagementType == hyperv1.Managed &&
hostedControlPlane.Spec.Etcd.Managed != nil && len(hostedControlPlane.Spec.Etcd.Managed.Storage.RestoreSnapshotURL) > 0 {
restoreCondition := meta.FindStatusCondition(hostedControlPlane.Status.Conditions, string(hyperv1.EtcdSnapshotRestored))
if restoreCondition == nil {
r.Log.Info("Reconciling etcd cluster restore status")
sts := manifests.EtcdStatefulSet(hostedControlPlane.Namespace)
if err := r.Get(ctx, client.ObjectKeyFromObject(sts), sts); err == nil {
newCondition := metav1.Condition{}
conditionPtr := r.etcdRestoredCondition(ctx, sts)
if conditionPtr != nil {
newCondition = *conditionPtr
newCondition.ObservedGeneration = hostedControlPlane.Generation
meta.SetStatusCondition(&hostedControlPlane.Status.Conditions, newCondition)
}
}
}
}
// Validate KMS config
switch hostedControlPlane.Spec.Platform.Type {
case hyperv1.AWSPlatform:
r.validateAWSKMSConfig(ctx, hostedControlPlane)
case hyperv1.AzurePlatform:
r.validateAzureKMSConfig(ctx, hostedControlPlane)
}
// Reconcile Kube APIServer status
{
newCondition := metav1.Condition{
Type: string(hyperv1.KubeAPIServerAvailable),
Status: metav1.ConditionUnknown,
Reason: hyperv1.StatusUnknownReason,
}
deployment := manifests.KASDeployment(hostedControlPlane.Namespace)
if err := r.Get(ctx, client.ObjectKeyFromObject(deployment), deployment); err != nil {
if apierrors.IsNotFound(err) {
newCondition = metav1.Condition{
Type: string(hyperv1.KubeAPIServerAvailable),
Status: metav1.ConditionFalse,
Reason: hyperv1.NotFoundReason,
Message: "Kube APIServer deployment not found",
}
} else {
return ctrl.Result{}, fmt.Errorf("failed to fetch Kube APIServer deployment %s/%s: %w", deployment.Namespace, deployment.Name, err)
}
} else {
// Assume the deployment is unavailable until proven otherwise.
newCondition = metav1.Condition{
Type: string(hyperv1.KubeAPIServerAvailable),
Status: metav1.ConditionFalse,
Reason: hyperv1.StatusUnknownReason,
}
for _, cond := range deployment.Status.Conditions {
if cond.Type == appsv1.DeploymentAvailable {
if cond.Status == corev1.ConditionTrue {
newCondition = metav1.Condition{
Type: string(hyperv1.KubeAPIServerAvailable),
Status: metav1.ConditionTrue,
Reason: hyperv1.AsExpectedReason,
Message: "Kube APIServer deployment is available",
}
} else {
newCondition = metav1.Condition{
Type: string(hyperv1.KubeAPIServerAvailable),
Status: metav1.ConditionFalse,
Reason: hyperv1.WaitingForAvailableReason,
Message: "Waiting for Kube APIServer deployment to become available",
}
}
break
}
}
}
newCondition.ObservedGeneration = hostedControlPlane.Generation
meta.SetStatusCondition(&hostedControlPlane.Status.Conditions, newCondition)
}
// Reconcile Degraded status
{
condition := metav1.Condition{
Type: string(hyperv1.HostedControlPlaneDegraded),
Status: metav1.ConditionFalse,
Reason: hyperv1.AsExpectedReason,
ObservedGeneration: hostedControlPlane.Generation,
}
cpoManagedDeploymentList := &appsv1.DeploymentList{}
if err := r.List(ctx, cpoManagedDeploymentList, client.MatchingLabels{
config.ManagedByLabel: "control-plane-operator",
}, client.InNamespace(hostedControlPlane.Namespace)); err != nil {
if !apierrors.IsNotFound(err) {
return ctrl.Result{}, fmt.Errorf("failed to list managed deployments in namespace %s: %w", hostedControlPlane.Namespace, err)
}
}
var errs []error
sort.SliceStable(cpoManagedDeploymentList.Items, func(i, j int) bool {
return cpoManagedDeploymentList.Items[i].Name < cpoManagedDeploymentList.Items[j].Name
})
for _, deployment := range cpoManagedDeploymentList.Items {
if deployment.Status.UnavailableReplicas > 0 {
errs = append(errs, fmt.Errorf("%s deployment has %d unavailable replicas", deployment.Name, deployment.Status.UnavailableReplicas))
}
}
err := utilerrors.NewAggregate(errs)
if err != nil {
condition.Status = metav1.ConditionTrue
condition.Reason = "UnavailableReplicas"
condition.Message = err.Error()
}
meta.SetStatusCondition(&hostedControlPlane.Status.Conditions, condition)
}
// Reconcile infrastructure status
{
r.Log.Info("Reconciling infrastructure status")
newCondition := metav1.Condition{
Type: string(hyperv1.InfrastructureReady),
Status: metav1.ConditionUnknown,
Reason: hyperv1.StatusUnknownReason,
}
infraStatus, err := r.reconcileInfrastructureStatus(ctx, hostedControlPlane)
if err != nil {
newCondition = metav1.Condition{
Type: string(hyperv1.InfrastructureReady),
Status: metav1.ConditionUnknown,
Reason: hyperv1.InfraStatusFailureReason,
Message: err.Error(),
}
r.Log.Error(err, "failed to determine infrastructure status")
} else {
if infraStatus.IsReady() {
hostedControlPlane.Status.ControlPlaneEndpoint = hyperv1.APIEndpoint{
Host: infraStatus.APIHost,
Port: infraStatus.APIPort,
}
newCondition = metav1.Condition{
Type: string(hyperv1.InfrastructureReady),
Status: metav1.ConditionTrue,
Message: hyperv1.AllIsWellMessage,
Reason: hyperv1.AsExpectedReason,
}
if util.HCPOAuthEnabled(hostedControlPlane) {
hostedControlPlane.Status.OAuthCallbackURLTemplate = fmt.Sprintf("https://%s:%d/oauth2callback/[identity-provider-name]", infraStatus.OAuthHost, infraStatus.OAuthPort)
}
} else {
message := "Cluster infrastructure is still provisioning"
if len(infraStatus.Message) > 0 {
message = infraStatus.Message
}
newCondition = metav1.Condition{
Type: string(hyperv1.InfrastructureReady),
Status: metav1.ConditionFalse,
Reason: hyperv1.WaitingOnInfrastructureReadyReason,
Message: message,
}
r.Log.Info("Infrastructure is not yet ready")
}
}
newCondition.ObservedGeneration = hostedControlPlane.Generation
meta.SetStatusCondition(&hostedControlPlane.Status.Conditions, newCondition)
}
// Reconcile external DNS status
{
newCondition := metav1.Condition{
Type: string(hyperv1.ExternalDNSReachable),
Status: metav1.ConditionUnknown,
Reason: hyperv1.StatusUnknownReason,
}
kasExternalHostname := util.ServiceExternalDNSHostname(hostedControlPlane, hyperv1.APIServer)
if kasExternalHostname != "" {
if err := util.ResolveDNSHostname(ctx, kasExternalHostname); err != nil {
newCondition = metav1.Condition{
Type: string(hyperv1.ExternalDNSReachable),
Status: metav1.ConditionFalse,
Reason: hyperv1.ExternalDNSHostNotReachableReason,
Message: err.Error(),
}
} else {
newCondition = metav1.Condition{
Type: string(hyperv1.ExternalDNSReachable),
Status: metav1.ConditionTrue,
Message: hyperv1.AllIsWellMessage,
Reason: hyperv1.AsExpectedReason,
}
}
} else {
newCondition.Message = "External DNS is not configured"
}
newCondition.ObservedGeneration = hostedControlPlane.Generation
meta.SetStatusCondition(&hostedControlPlane.Status.Conditions, newCondition)
}
// Reconcile hostedcontrolplane availability and Ready flag
{
infrastructureCondition := meta.FindStatusCondition(hostedControlPlane.Status.Conditions, string(hyperv1.InfrastructureReady))
kubeConfigAvailable := hostedControlPlane.Status.KubeConfig != nil
etcdCondition := meta.FindStatusCondition(hostedControlPlane.Status.Conditions, string(hyperv1.EtcdAvailable))
kubeAPIServerCondition := meta.FindStatusCondition(hostedControlPlane.Status.Conditions, string(hyperv1.KubeAPIServerAvailable))
healthCheckErr := r.healthCheckKASLoadBalancers(ctx, hostedControlPlane)
status := metav1.ConditionFalse
var reason, message string
switch {
case infrastructureCondition == nil && etcdCondition == nil && kubeAPIServerCondition == nil:
reason = hyperv1.StatusUnknownReason
message = ""
case infrastructureCondition != nil && infrastructureCondition.Status == metav1.ConditionFalse:
reason = infrastructureCondition.Reason
message = infrastructureCondition.Message
case !kubeConfigAvailable:
reason = hyperv1.KubeconfigWaitingForCreateReason
message = "Waiting for hosted control plane kubeconfig to be created"
case etcdCondition != nil && etcdCondition.Status == metav1.ConditionFalse:
reason = etcdCondition.Reason
message = etcdCondition.Message
case kubeAPIServerCondition != nil && kubeAPIServerCondition.Status == metav1.ConditionFalse:
reason = kubeAPIServerCondition.Reason
message = kubeAPIServerCondition.Message
case healthCheckErr != nil:
reason = hyperv1.KASLoadBalancerNotReachableReason
message = healthCheckErr.Error()
default:
reason = hyperv1.AsExpectedReason
message = ""
status = metav1.ConditionTrue
}
hostedControlPlane.Status.Ready = status == metav1.ConditionTrue
condition := metav1.Condition{
Type: string(hyperv1.HostedControlPlaneAvailable),
Status: status,
Reason: reason,
Message: message,
ObservedGeneration: hostedControlPlane.Generation,
}
meta.SetStatusCondition(&hostedControlPlane.Status.Conditions, condition)
}
kubeconfig := manifests.KASExternalKubeconfigSecret(hostedControlPlane.Namespace, hostedControlPlane.Spec.KubeConfig)
if err := r.Get(ctx, client.ObjectKeyFromObject(kubeconfig), kubeconfig); err != nil {
if !apierrors.IsNotFound(err) {
return reconcile.Result{}, err
}
} else {
hostedControlPlane.Status.KubeConfig = &hyperv1.KubeconfigSecretRef{
Name: kubeconfig.Name,
Key: DefaultAdminKubeconfigKey,
}
if hostedControlPlane.Spec.KubeConfig != nil {
hostedControlPlane.Status.KubeConfig.Key = hostedControlPlane.Spec.KubeConfig.Key
}
}
explicitOauthConfig := hostedControlPlane.Spec.Configuration != nil && hostedControlPlane.Spec.Configuration.OAuth != nil
if explicitOauthConfig {
hostedControlPlane.Status.KubeadminPassword = nil
} else {
kubeadminPassword := common.KubeadminPasswordSecret(hostedControlPlane.Namespace)
if err := r.Get(ctx, client.ObjectKeyFromObject(kubeadminPassword), kubeadminPassword); err != nil {
if !apierrors.IsNotFound(err) {
return reconcile.Result{}, fmt.Errorf("failed to get kubeadmin password: %w", err)
}
} else {
hostedControlPlane.Status.KubeadminPassword = &corev1.LocalObjectReference{
Name: kubeadminPassword.Name,
}
}
}
// Reconcile valid release info status
releaseImage, err := r.LookupReleaseImage(ctx, hostedControlPlane)
if err != nil {
return reconcile.Result{}, fmt.Errorf("failed to look up release image metadata: %w", err)
}
releaseImageProvider := imageprovider.New(releaseImage)
{
if len(releaseImageProvider.GetMissingImages()) == 0 {
meta.SetStatusCondition(&hostedControlPlane.Status.Conditions, metav1.Condition{
Type: string(hyperv1.ValidReleaseInfo),
Status: metav1.ConditionTrue,
Reason: hyperv1.AsExpectedReason,
Message: hyperv1.AllIsWellMessage,
ObservedGeneration: hostedControlPlane.Generation,
})
} else {
meta.SetStatusCondition(&hostedControlPlane.Status.Conditions, metav1.Condition{
Type: string(hyperv1.ValidReleaseInfo),
Status: metav1.ConditionFalse,
Reason: hyperv1.MissingReleaseImagesReason,
Message: strings.Join(releaseImageProvider.GetMissingImages(), ", "),
ObservedGeneration: hostedControlPlane.Generation,
})
}
}
hostedControlPlane.Status.Initialized = true
meta.SetStatusCondition(&hostedControlPlane.Status.Conditions, util.GenerateReconciliationActiveCondition(hostedControlPlane.Spec.PausedUntil, hostedControlPlane.Generation))
// Always update status based on the current state of the world.
if err := r.Client.Status().Patch(ctx, hostedControlPlane, client.MergeFromWithOptions(originalHostedControlPlane, client.MergeFromWithOptimisticLock{})); err != nil {
return ctrl.Result{}, fmt.Errorf("failed to update status: %w", err)
}
if isPaused, duration := util.IsReconciliationPaused(r.Log, hostedControlPlane.Spec.PausedUntil); isPaused {
r.Log.Info("Reconciliation paused", "pausedUntil", *hostedControlPlane.Spec.PausedUntil)
return ctrl.Result{
RequeueAfter: duration,
}, nil
}
// Block here if the cluster configuration does not pass validation
{
validConfig := meta.FindStatusCondition(hostedControlPlane.Status.Conditions, string(hyperv1.ValidHostedControlPlaneConfiguration))
if validConfig != nil && validConfig.Status == metav1.ConditionFalse {
r.Log.Info("Configuration is invalid, reconciliation is blocked")
return reconcile.Result{}, nil
}
}
// Perform the hosted control plane reconciliation
result, err := r.update(ctx, hostedControlPlane, releaseImage)
if err != nil {
return ctrl.Result{}, fmt.Errorf("failed to update control plane: %w", err)
}
r.Log.Info("Successfully reconciled")
if !result.IsZero() {
return result, nil
}
if !hostedControlPlane.Status.Ready {
return ctrl.Result{RequeueAfter: hcpNotReadyRequeueInterval}, nil
}
return ctrl.Result{RequeueAfter: hcpReadyRequeueInterval}, nil
}
// healthCheckKASLoadBalancers performs a health check on the KubeAPI server /healthz endpoint using the public and private load balancers hostnames directly
// This will detect if load balancers are down or deleted out of band
func (r *HostedControlPlaneReconciler) healthCheckKASLoadBalancers(ctx context.Context, hcp *hyperv1.HostedControlPlane) error {
serviceStrategy := util.ServicePublishingStrategyByTypeForHCP(hcp, hyperv1.APIServer)
if serviceStrategy == nil {
return fmt.Errorf("APIServer service strategy not specified")
}
switch {
case !util.IsPublicHCP(hcp):
// When the cluster is private, checking the load balancers will depend on whether the load balancer is
// using the right subnets. To avoid uncertainty, we'll limit the check to the service endpoint.
if hcp.Spec.Platform.Type == hyperv1.IBMCloudPlatform {
return healthCheckKASEndpoint(manifests.KubeAPIServerService("").Name, config.KASSVCIBMCloudPort)
}
return healthCheckKASEndpoint(manifests.KubeAPIServerService("").Name, config.KASSVCPort)
case serviceStrategy.Type == hyperv1.Route:
externalRoute := manifests.KubeAPIServerExternalPublicRoute(hcp.Namespace)
if err := r.Get(ctx, client.ObjectKeyFromObject(externalRoute), externalRoute); err != nil {
return fmt.Errorf("failed to get kube apiserver external route: %w", err)
}
if len(externalRoute.Status.Ingress) == 0 || externalRoute.Status.Ingress[0].RouterCanonicalHostname == "" {
return fmt.Errorf("APIServer external route not admitted")
}
return healthCheckKASEndpoint(externalRoute.Status.Ingress[0].RouterCanonicalHostname, 443)
case serviceStrategy.Type == hyperv1.LoadBalancer:
svc := manifests.KubeAPIServerService(hcp.Namespace)
port := config.KASSVCPort
if hcp.Spec.Platform.Type == hyperv1.IBMCloudPlatform {
port = config.KASSVCIBMCloudPort
}
if hcp.Spec.Platform.Type == hyperv1.AzurePlatform {
// If Azure we get the SVC handling the LB.
// TODO(alberto): remove this hack when having proper traffic management for Azure.
svc = manifests.KubeAPIServerServiceAzureLB(hcp.Namespace)
port = config.KASSVCLBAzurePort
}
if err := r.Get(ctx, client.ObjectKeyFromObject(svc), svc); err != nil {
return fmt.Errorf("failed to get kube apiserver service: %w", err)
}
if len(svc.Status.LoadBalancer.Ingress) == 0 ||
svc.Status.LoadBalancer.Ingress[0].Hostname == "" && svc.Status.LoadBalancer.Ingress[0].IP == "" {
return fmt.Errorf("APIServer load balancer is not provisioned")
}
LBIngress := svc.Status.LoadBalancer.Ingress[0]
ingressPoint := ""
if LBIngress.Hostname != "" {
ingressPoint = LBIngress.Hostname
} else if LBIngress.IP != "" {
ingressPoint = LBIngress.IP
}
return healthCheckKASEndpoint(ingressPoint, port)
}
return nil
}
func healthCheckKASEndpoint(ingressPoint string, port int) error {
healthEndpoint := fmt.Sprintf("https://%s:%d/healthz", ingressPoint, port)
httpClient := util.InsecureHTTPClient()
httpClient.Timeout = 10 * time.Second
resp, err := httpClient.Get(healthEndpoint)
if err != nil {
return err
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("APIServer endpoint %s is not healthy", ingressPoint)
}
return nil
}
func (r *HostedControlPlaneReconciler) validateConfigAndClusterCapabilities(hc *hyperv1.HostedControlPlane) error {
for _, svc := range hc.Spec.Services {
if svc.Type == hyperv1.Route && !r.ManagementClusterCapabilities.Has(capabilities.CapabilityRoute) {
return fmt.Errorf("cluster does not support Routes, but service %q is exposed via a Route", svc.Service)
}
}
return nil
}
func (r *HostedControlPlaneReconciler) LookupReleaseImage(ctx context.Context, hcp *hyperv1.HostedControlPlane) (*releaseinfo.ReleaseImage, error) {
pullSecret := common.PullSecret(hcp.Namespace)
if err := r.Client.Get(ctx, client.ObjectKeyFromObject(pullSecret), pullSecret); err != nil {
return nil, err
}
lookupCtx, lookupCancel := context.WithTimeout(ctx, 2*time.Minute)
defer lookupCancel()
return r.ReleaseProvider.Lookup(lookupCtx, util.HCPControlPlaneReleaseImage(hcp), pullSecret.Data[corev1.DockerConfigJsonKey])
}
func (r *HostedControlPlaneReconciler) update(ctx context.Context, hostedControlPlane *hyperv1.HostedControlPlane, releaseImage *releaseinfo.ReleaseImage) (reconcile.Result, error) {
createOrUpdate := r.createOrUpdate(hostedControlPlane)
r.Log.Info("Reconciling infrastructure services")
if err := r.reconcileInfrastructure(ctx, hostedControlPlane, createOrUpdate); err != nil {
return reconcile.Result{}, fmt.Errorf("failed to ensure infrastructure: %w", err)
}
// Block here until infra status reports readiness
// TODO(dmace): This seems a bit heavy handed vs. making more granular bits no-op if
// they don't have the specific required inputs
infraStatus, err := r.reconcileInfrastructureStatus(ctx, hostedControlPlane)
if err != nil {
return reconcile.Result{}, fmt.Errorf("failed to look up infra status: %w", err)
}
if !infraStatus.IsReady() {
r.Log.Info("Waiting for infrastructure to be ready before proceeding")
return reconcile.Result{RequeueAfter: time.Minute}, nil
}
return ctrl.Result{}, r.reconcile(ctx, hostedControlPlane, createOrUpdate, imageprovider.New(releaseImage), infraStatus)
}
// useHCPRouter returns true if a dedicated common router is created for a HCP to handle ingress for the managed endpoints.
// This is true when the API input specifies intent for the following:
// 1 - AWS endpointAccess is private somehow (i.e. publicAndPrivate or private) or is public and configured with external DNS.
// 2 - When 1 is true, we recommend (and automate via CLI) ServicePublishingStrategy to be "Route" for all endpoints but the KAS
// which needs a dedicated Service type LB external to be exposed if no external DNS is supported.
// Otherwise, the Routes use the management cluster Domain and resolve through the default ingress controller.
func useHCPRouter(hostedControlPlane *hyperv1.HostedControlPlane) bool {
return util.IsPrivateHCP(hostedControlPlane) || util.IsPublicKASWithDNS(hostedControlPlane)
}
func IsStorageAndCSIManaged(hostedControlPlane *hyperv1.HostedControlPlane) bool {
if hostedControlPlane.Spec.Platform.Type == hyperv1.IBMCloudPlatform || hostedControlPlane.Spec.Platform.Type == hyperv1.PowerVSPlatform {
return false
}
return true
}
func (r *HostedControlPlaneReconciler) reconcile(ctx context.Context, hostedControlPlane *hyperv1.HostedControlPlane, createOrUpdate upsert.CreateOrUpdateFN, releaseImageProvider *imageprovider.ReleaseImageProvider, infraStatus InfrastructureStatus) error {
// releaseImage might be overriden by spec.controlPlaneReleaseImage
// User facing components should reflect the version from spec.releaseImage
pullSecret := common.PullSecret(hostedControlPlane.Namespace)
if err := r.Client.Get(ctx, client.ObjectKeyFromObject(pullSecret), pullSecret); err != nil {
return err
}
userReleaseImage, err := r.ReleaseProvider.Lookup(ctx, hostedControlPlane.Spec.ReleaseImage, pullSecret.Data[corev1.DockerConfigJsonKey])
if err != nil {
return fmt.Errorf("failed to get lookup release image: %w", err)
}
userReleaseImageProvider := imageprovider.New(userReleaseImage)
// Reconcile default service account
r.Log.Info("Reconciling default service account")
if err := r.reconcileDefaultServiceAccount(ctx, hostedControlPlane, createOrUpdate); err != nil {
return fmt.Errorf("failed to reconcile default service account: %w", err)
}
openShiftTrustedCABundleConfigMapForCPOExists, err := doesOpenShiftTrustedCABundleConfigMapForCPOExist(ctx, r.Client, hostedControlPlane.Namespace)
if err != nil {
return err
}
// Reconcile PKI
if _, exists := hostedControlPlane.Annotations[hyperv1.DisablePKIReconciliationAnnotation]; !exists {
r.Log.Info("Reconciling PKI")
if err := r.reconcilePKI(ctx, hostedControlPlane, infraStatus, createOrUpdate); err != nil {
return fmt.Errorf("failed to reconcile PKI: %w", err)
}
r.Log.Info("Reconciling Control Plane PKI Operator")
if err := r.reconcileControlPlanePKIOperator(ctx, hostedControlPlane, releaseImageProvider, createOrUpdate, openShiftTrustedCABundleConfigMapForCPOExists, r.CertRotationScale); err != nil {
return fmt.Errorf("failed to reconcile control plane pki operator: %w", err)
}
}
// Reconcile etcd
r.Log.Info("Reconciling Etcd")
switch hostedControlPlane.Spec.Etcd.ManagementType {
case hyperv1.Managed:
statefulSet := manifests.EtcdStatefulSet(hostedControlPlane.Namespace)
if err := r.reconcileManagedEtcd(ctx, hostedControlPlane, releaseImageProvider, createOrUpdate, statefulSet); err != nil {
return fmt.Errorf("failed to reconcile etcd: %w", err)
}
// Block until etcd is fully rolled out at the desired generation
if ready := util.IsStatefulSetReady(ctx, statefulSet); !ready {
r.Log.Info("Waiting for etcd statefulset to become ready")
return nil
}
case hyperv1.Unmanaged:
if err := r.reconcileUnmanagedEtcd(ctx, hostedControlPlane, createOrUpdate); err != nil {
return fmt.Errorf("failed to reconcile etcd: %w", err)
}
default:
return fmt.Errorf("unrecognized etcd management type: %s", hostedControlPlane.Spec.Etcd.ManagementType)
}
// Reconcile Cloud Provider Config
r.Log.Info("Reconciling cloud provider config")
if err := r.reconcileCloudProviderConfig(ctx, hostedControlPlane, createOrUpdate); err != nil {
return fmt.Errorf("failed to reconcile cloud provider config: %w", err)
}
// Reconcile kube apiserver
r.Log.Info("Reconciling Kube API Server")
kubeAPIServerDeployment := manifests.KASDeployment(hostedControlPlane.Namespace)
if err := r.reconcileKubeAPIServer(ctx, hostedControlPlane, releaseImageProvider, userReleaseImageProvider, infraStatus.APIHost, infraStatus.APIPort, infraStatus.OAuthHost, infraStatus.OAuthPort, createOrUpdate, kubeAPIServerDeployment); err != nil {
return fmt.Errorf("failed to reconcile kube apiserver: %w", err)
}
// Block until kube apiserver is fully ready to enforce upgrade order of version skew policy
// https://kubernetes.io/releases/version-skew-policy/#supported-component-upgrade-order
if ready := util.IsDeploymentReady(ctx, kubeAPIServerDeployment); !ready {
r.Log.Info("Waiting for kube apiserver deployment to become ready")
return nil
}
// Reconcile kube controller manager
r.Log.Info("Reconciling Kube Controller Manager")
kcmDeployment := manifests.KCMDeployment(hostedControlPlane.Namespace)
if err := r.reconcileKubeControllerManager(ctx, hostedControlPlane, releaseImageProvider, createOrUpdate, kcmDeployment); err != nil {
return fmt.Errorf("failed to reconcile kube controller manager: %w", err)
}
// Reconcile kube scheduler