-
Notifications
You must be signed in to change notification settings - Fork 192
/
clusterdeployments_controller.go
2243 lines (2019 loc) · 85.7 KB
/
clusterdeployments_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 2020.
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 controllers
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"reflect"
"strings"
"time"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
"github.com/google/uuid"
. "github.com/openshift/assisted-service/api/common"
hiveext "github.com/openshift/assisted-service/api/hiveextension/v1beta1"
aiv1beta1 "github.com/openshift/assisted-service/api/v1beta1"
restclient "github.com/openshift/assisted-service/client"
"github.com/openshift/assisted-service/internal/bminventory"
"github.com/openshift/assisted-service/internal/cluster"
"github.com/openshift/assisted-service/internal/cluster/validations"
"github.com/openshift/assisted-service/internal/common"
"github.com/openshift/assisted-service/internal/constants"
"github.com/openshift/assisted-service/internal/gencrypto"
"github.com/openshift/assisted-service/internal/host"
manifestsapi "github.com/openshift/assisted-service/internal/manifests/api"
"github.com/openshift/assisted-service/internal/network"
"github.com/openshift/assisted-service/internal/operators"
"github.com/openshift/assisted-service/internal/spoke_k8s_client"
"github.com/openshift/assisted-service/internal/versions"
"github.com/openshift/assisted-service/models"
"github.com/openshift/assisted-service/pkg/auth"
logutil "github.com/openshift/assisted-service/pkg/log"
"github.com/openshift/assisted-service/restapi/operations/installer"
operations "github.com/openshift/assisted-service/restapi/operations/manifests"
hivev1 "github.com/openshift/hive/apis/hive/v1"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/thoas/go-funk"
"gorm.io/gorm"
corev1 "k8s.io/api/core/v1"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/utils/pointer"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/builder"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/apiutil"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"sigs.k8s.io/controller-runtime/pkg/event"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/predicate"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"sigs.k8s.io/controller-runtime/pkg/source"
)
const (
adminPasswordSecretStringTemplate = "%s-admin-password"
adminKubeConfigStringTemplate = "%s-admin-kubeconfig"
InstallConfigOverrides = aiv1beta1.Group + "/install-config-overrides"
ClusterDeploymentFinalizerName = "clusterdeployments." + aiv1beta1.Group + "/ai-deprovision"
AgentClusterInstallFinalizerName = "agentclusterinstall." + aiv1beta1.Group + "/ai-deprovision"
)
const HighAvailabilityModeNone = "None"
const defaultRequeueAfterOnError = 10 * time.Second
const longerRequeueAfterOnError = 1 * time.Minute
// ClusterDeploymentsReconciler reconciles a Cluster object
type ClusterDeploymentsReconciler struct {
client.Client
APIReader client.Reader
Log logrus.FieldLogger
Scheme *runtime.Scheme
Installer bminventory.InstallerInternals
ClusterApi cluster.API
HostApi host.API
CRDEventsHandler CRDEventsHandler
Manifests manifestsapi.ClusterManifestsInternals
ServiceBaseURL string
PullSecretHandler
AuthType auth.AuthType
VersionsHandler versions.Handler
SpokeK8sClientFactory spoke_k8s_client.SpokeK8sClientFactory
}
const minimalOpenShiftVersionForDefaultNetworkTypeOVNKubernetes = "4.12.0-0.0"
// +kubebuilder:rbac:groups="",resources=secrets,verbs=get;list;watch;update;create
// +kubebuilder:rbac:groups="",resources=configmaps,verbs=get;list;watch
// +kubebuilder:rbac:groups=hive.openshift.io,resources=clusterdeployments,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=hive.openshift.io,resources=clusterdeployments/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=hive.openshift.io,resources=clusterdeployments/finalizers,verbs=update
// +kubebuilder:rbac:groups=hive.openshift.io,resources=clusterimagesets,verbs=get;list;watch;create
// +kubebuilder:rbac:groups=extensions.hive.openshift.io,resources=agentclusterinstalls,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=extensions.hive.openshift.io,resources=agentclusterinstalls/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=extensions.hive.openshift.io,resources=agentclusterinstalls/finalizers,verbs=update
// +kubebuilder:rbac:groups=config.openshift.io,resources=dnses,verbs=get
func (r *ClusterDeploymentsReconciler) Reconcile(origCtx context.Context, req ctrl.Request) (ctrl.Result, error) {
ctx := addRequestIdIfNeeded(origCtx)
logFields := logrus.Fields{
"cluster_deployment": req.Name,
"cluster_deployment_namespace": req.Namespace,
}
log := logutil.FromContext(ctx, r.Log).WithFields(logFields)
defer func() {
log.Info("ClusterDeployment Reconcile ended")
}()
log.Info("ClusterDeployment Reconcile started")
clusterDeployment := &hivev1.ClusterDeployment{}
clusterInstallDeleted := false
if err := r.Get(ctx, req.NamespacedName, clusterDeployment); err != nil {
log.WithError(err).Errorf("failed to get ClusterDeployment name=%s namespace=%s", req.Name, req.Namespace)
return ctrl.Result{}, client.IgnoreNotFound(err)
}
// ignore unsupported platforms
if !isSupportedPlatform(clusterDeployment) {
return ctrl.Result{}, nil
}
clusterInstall := &hiveext.AgentClusterInstall{}
if clusterDeployment.Spec.ClusterInstallRef == nil {
log.Infof("AgentClusterInstall not set for ClusterDeployment %s", clusterDeployment.Name)
return ctrl.Result{}, nil
}
aciName := clusterDeployment.Spec.ClusterInstallRef.Name
err := r.Get(ctx,
types.NamespacedName{
Namespace: clusterDeployment.Namespace,
Name: aciName,
},
clusterInstall)
if err != nil {
if k8serrors.IsNotFound(err) {
// mark that clusterInstall was already deleted so we skip it if needed.
clusterInstallDeleted = true
log.WithField("AgentClusterInstall", aciName).Infof("AgentClusterInstall does not exist for ClusterDeployment %s", clusterDeployment.Name)
if clusterDeployment.ObjectMeta.DeletionTimestamp.IsZero() {
// we have no agentClusterInstall and clusterDeployment is not being deleted. stop reconciliation.
return ctrl.Result{}, nil
}
} else {
log.WithError(err).Errorf("failed to get AgentClusterInstall name=%s namespace=%s", aciName, clusterDeployment.Namespace)
return ctrl.Result{Requeue: true}, err
}
}
if !clusterInstallDeleted {
logFields["agent_cluster_install"] = clusterInstall.Name
logFields["agent_cluster_install_namespace"] = clusterInstall.Namespace
log = logutil.FromContext(ctx, log).WithFields(logFields)
aciReply, aciErr := r.agentClusterInstallFinalizer(ctx, log, req, clusterInstall)
if aciReply != nil {
return *aciReply, aciErr
}
}
cdReply, cdErr := r.clusterDeploymentFinalizer(ctx, log, clusterDeployment)
if cdReply != nil {
return *cdReply, cdErr
}
err = r.ensureOwnerRef(ctx, log, clusterDeployment, clusterInstall)
if err != nil {
log.WithError(err).Error("error setting owner reference")
return ctrl.Result{Requeue: true}, err
}
cluster, err := r.Installer.GetClusterByKubeKey(req.NamespacedName)
if errors.Is(err, gorm.ErrRecordNotFound) {
if !isInstalled(clusterDeployment, clusterInstall) {
return r.createNewCluster(ctx, log, req.NamespacedName, clusterDeployment, clusterInstall)
}
return r.createNewDay2Cluster(ctx, log, req.NamespacedName, clusterDeployment, clusterInstall)
}
if err != nil {
return r.updateStatus(ctx, log, clusterInstall, cluster, err)
}
err = r.validateClusterDeployment(ctx, log, clusterDeployment, clusterInstall)
if err != nil {
log.Error(err)
return r.updateStatus(ctx, log, clusterInstall, cluster, err)
}
// check for updates from user, compare spec and update if needed
cluster, err = r.updateIfNeeded(ctx, log, clusterDeployment, clusterInstall, cluster)
if err != nil {
log.WithError(err).Error("failed to update cluster")
return r.updateStatus(ctx, log, clusterInstall, cluster, err)
}
// check for install config overrides and update if needed
err = r.updateInstallConfigOverrides(ctx, log, clusterInstall, cluster)
if err != nil {
log.WithError(err).Error("failed to update install config overrides")
return r.updateStatus(ctx, log, clusterInstall, cluster, err)
}
// In case the Cluster is a Day 1 cluster and is installed, update the Metadata and create secrets for credentials
if *cluster.Status == models.ClusterStatusInstalled && swag.StringValue(cluster.Kind) == models.ClusterKindCluster {
return r.handleClusterInstalled(ctx, log, clusterDeployment, cluster, clusterInstall, req.NamespacedName)
}
// Create Kubeconfig no-ingress if needed
if *cluster.Status == models.ClusterStatusInstalling || *cluster.Status == models.ClusterStatusFinalizing {
if err1 := r.createNoIngressKubeConfig(ctx, log, clusterDeployment, cluster, clusterInstall); err1 != nil {
log.WithError(err1).Error("failed to create kubeconfig no-ingress secret")
return r.updateStatus(ctx, log, clusterInstall, cluster, err1)
}
}
if swag.StringValue(cluster.Kind) == models.ClusterKindCluster && !clusterInstall.Spec.HoldInstallation {
// Day 1
pullSecret, err := r.PullSecretHandler.GetValidPullSecret(ctx, getPullSecretKey(req.Namespace, clusterDeployment.Spec.PullSecretRef))
if err != nil {
log.WithError(err).Error("failed to get pull secret")
return r.updateStatus(ctx, log, clusterInstall, nil, err)
}
return r.installDay1(ctx, log, clusterDeployment, clusterInstall, cluster, pullSecret)
} else if swag.StringValue(cluster.Kind) == models.ClusterKindAddHostsCluster {
// Day 2
return r.installDay2Hosts(ctx, log, clusterDeployment, clusterInstall, cluster)
}
return r.updateStatus(ctx, log, clusterInstall, cluster, nil)
}
func (r *ClusterDeploymentsReconciler) validateClusterDeployment(ctx context.Context, log logrus.FieldLogger,
clusterDeployment *hivev1.ClusterDeployment, clusterInstall *hiveext.AgentClusterInstall) error {
// Make sure that the ImageSetRef is set for clusters not already installed
if clusterInstall.Spec.ImageSetRef == nil && !clusterDeployment.Spec.Installed {
return newInputError("missing ImageSetRef for cluster that is not installed")
}
return nil
}
func (r *ClusterDeploymentsReconciler) agentClusterInstallFinalizer(ctx context.Context, log logrus.FieldLogger, req ctrl.Request,
clusterInstall *hiveext.AgentClusterInstall) (*ctrl.Result, error) {
if clusterInstall.ObjectMeta.DeletionTimestamp.IsZero() { // clusterInstall not being deleted
// Register a finalizer if it is absent.
if !funk.ContainsString(clusterInstall.GetFinalizers(), AgentClusterInstallFinalizerName) {
controllerutil.AddFinalizer(clusterInstall, AgentClusterInstallFinalizerName)
if err := r.Update(ctx, clusterInstall); err != nil {
log.WithError(err).Errorf("failed to add finalizer %s to resource %s %s",
AgentClusterInstallFinalizerName, clusterInstall.Name, clusterInstall.Namespace)
return &ctrl.Result{Requeue: true}, err
}
}
} else { // clusterInstall is being deleted
if funk.ContainsString(clusterInstall.GetFinalizers(), AgentClusterInstallFinalizerName) {
cluster, err := r.Installer.GetClusterByKubeKey(req.NamespacedName)
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
return &ctrl.Result{Requeue: true}, err
}
if err == nil {
if swag.StringValue(cluster.Status) == models.ClusterStatusInstalling || swag.StringValue(cluster.Status) == models.ClusterStatusPreparingForInstallation {
log.Infof("ClusterInstall is being deleted, cancel installation for cluster %s", *cluster.ID)
if _, err = r.Installer.CancelInstallationInternal(ctx, installer.V2CancelInstallationParams{
ClusterID: *cluster.ID,
}); err != nil {
return &ctrl.Result{Requeue: true}, err
}
}
}
//Unbind agents
if err = r.unbindAgents(ctx, log, req.NamespacedName); err != nil {
return &ctrl.Result{Requeue: true}, err
}
// deletion finalizer found, deregister the backend cluster
reply, cleanUpErr := r.deregisterClusterIfNeeded(ctx, log, req.NamespacedName)
if cleanUpErr != nil {
log.WithError(cleanUpErr).Errorf("failed to run pre-deletion cleanup for finalizer %s on resource %s %s",
AgentClusterInstallFinalizerName, clusterInstall.Name, clusterInstall.Namespace)
return &reply, cleanUpErr
}
// remove our finalizer from the list and update it.
controllerutil.RemoveFinalizer(clusterInstall, AgentClusterInstallFinalizerName)
if err := r.Update(ctx, clusterInstall); err != nil {
log.WithError(err).Errorf("failed to remove finalizer %s from resource %s %s",
AgentClusterInstallFinalizerName, clusterInstall.Name, clusterInstall.Namespace)
return &ctrl.Result{Requeue: true}, err
}
}
// Stop reconciliation as the item is being deleted
return &ctrl.Result{}, nil
}
return nil, nil
}
func (r *ClusterDeploymentsReconciler) clusterDeploymentFinalizer(ctx context.Context, log logrus.FieldLogger, clusterDeployment *hivev1.ClusterDeployment) (*ctrl.Result, error) {
if clusterDeployment.ObjectMeta.DeletionTimestamp.IsZero() { // clusterDeployment not being deleted
// Register a finalizer if it is absent.
if !funk.ContainsString(clusterDeployment.GetFinalizers(), ClusterDeploymentFinalizerName) {
controllerutil.AddFinalizer(clusterDeployment, ClusterDeploymentFinalizerName)
if err := r.Update(ctx, clusterDeployment); err != nil {
log.WithError(err).Errorf("failed to add finalizer %s to resource %s %s",
ClusterDeploymentFinalizerName, clusterDeployment.Name, clusterDeployment.Namespace)
return &ctrl.Result{Requeue: true}, err
}
}
} else { // clusterDeployment is being deleted
if funk.ContainsString(clusterDeployment.GetFinalizers(), ClusterDeploymentFinalizerName) {
reply, cleanUpErr := r.deleteClusterInstall(ctx, log, clusterDeployment)
if cleanUpErr != nil {
log.WithError(cleanUpErr).Errorf(
"clusterDeployment %s %s is still waiting for clusterInstall %s to be deleted",
clusterDeployment.Name, clusterDeployment.Namespace, clusterDeployment.Spec.ClusterInstallRef.Name,
)
return &reply, cleanUpErr
}
// remove our finalizer from the list and update it.
controllerutil.RemoveFinalizer(clusterDeployment, ClusterDeploymentFinalizerName)
if err := r.Update(ctx, clusterDeployment); err != nil {
log.WithError(err).Errorf("failed to remove finalizer %s from resource %s %s",
ClusterDeploymentFinalizerName, clusterDeployment.Name, clusterDeployment.Namespace)
return &ctrl.Result{Requeue: true}, err
}
}
// Stop reconciliation as the item is being deleted
return &ctrl.Result{}, nil
}
return nil, nil
}
func isInstalled(clusterDeployment *hivev1.ClusterDeployment, clusterInstall *hiveext.AgentClusterInstall) bool {
if clusterDeployment.Spec.Installed {
return true
}
cond := FindStatusCondition(clusterInstall.Status.Conditions, hiveext.ClusterCompletedCondition)
return cond != nil && cond.Reason == hiveext.ClusterInstalledReason
}
func (r *ClusterDeploymentsReconciler) installDay1(ctx context.Context, log logrus.FieldLogger, clusterDeployment *hivev1.ClusterDeployment,
clusterInstall *hiveext.AgentClusterInstall, cluster *common.Cluster, pullSecret string) (ctrl.Result, error) {
ready, err := r.isReadyForInstallation(ctx, log, clusterInstall, cluster)
if err != nil {
log.WithError(err).Error("failed to check if cluster ready for installation")
return r.updateStatus(ctx, log, clusterInstall, cluster, err)
}
if ready {
// create custom manifests if needed before installation
err = r.addCustomManifests(ctx, log, clusterInstall, cluster)
if err != nil {
log.WithError(err).Error("failed to add custom manifests")
_, _ = r.updateStatus(ctx, log, clusterInstall, cluster, err)
// We decided to requeue with one minute timeout in order to give user a chance to fix manifest
// this timeout allows us not to run reconcile too much time and
// still have a nice feedback when user will fix the error
return ctrl.Result{Requeue: true, RequeueAfter: longerRequeueAfterOnError}, nil
}
log.Infof("Installing clusterDeployment %s %s", clusterDeployment.Name, clusterDeployment.Namespace)
var ic *common.Cluster
ic, err = r.Installer.InstallClusterInternal(ctx, installer.V2InstallClusterParams{
ClusterID: *cluster.ID,
})
if err != nil {
log.WithError(err).Error("failed to start cluster install")
return r.updateStatus(ctx, log, clusterInstall, cluster, err)
}
return r.updateStatus(ctx, log, clusterInstall, ic, err)
}
return r.updateStatus(ctx, log, clusterInstall, cluster, nil)
}
func (r *ClusterDeploymentsReconciler) spokeKubeClient(ctx context.Context, clusterDeployment *hivev1.ClusterDeployment) (spoke_k8s_client.SpokeK8sClient, error) {
adminKubeConfigSecretName := getClusterDeploymentAdminKubeConfigSecretName(clusterDeployment)
namespacedName := types.NamespacedName{
Namespace: clusterDeployment.Namespace,
Name: adminKubeConfigSecretName,
}
secret, err := getSecret(ctx, r.Client, r.APIReader, namespacedName)
if err != nil {
r.Log.WithError(err).Errorf("failed to get kubeconfig secret %s", namespacedName)
return nil, err
}
if err = ensureSecretIsLabelled(ctx, r.Client, secret, namespacedName); err != nil {
r.Log.WithError(err).Errorf("failed to label kubeconfig secret %s", namespacedName)
return nil, err
}
return r.SpokeK8sClientFactory.CreateFromSecret(secret)
}
func (r *ClusterDeploymentsReconciler) updateWorkerMcpPaused(ctx context.Context, log logrus.FieldLogger, clusterInstall *hiveext.AgentClusterInstall, clusterDeployment *hivev1.ClusterDeployment) error {
agents, err := findAgentsByAgentClusterInstall(r.Client, ctx, log, clusterInstall)
if err != nil {
log.WithError(err).Errorf("failed to find agents for cluster install %s/%s", clusterInstall.Namespace, clusterInstall.Name)
return err
}
var paused, shouldUpdate bool
funk.ForEach(agents, func(agent *aiv1beta1.Agent) {
// State is checked to be not equal to "installed" to verify that day1 installed nodes are not taken into account
if !funk.IsEmpty(agent.Spec.NodeLabels) && agent.Spec.MachineConfigPool != "" && agent.Status.DebugInfo.State != models.HostStatusInstalled {
shouldUpdate = true
// MCP should be paused when there is at least 1 installing day2 node. Otherwise, it should be unpaused
if agent.Status.Progress.CurrentStage != models.HostStageDone &&
funk.ContainsString([]string{models.HostStatusInstalling, models.HostStatusInstallingInProgress}, agent.Status.DebugInfo.State) {
paused = true
}
}
})
if shouldUpdate {
spokeClient, err := r.spokeKubeClient(ctx, clusterDeployment)
if err != nil {
log.WithError(err).Errorf("failed to create spoke client for cluster deployment %s/%s", clusterDeployment.Namespace, clusterDeployment.Name)
return err
}
err = spokeClient.PatchMachineConfigPoolPaused(ctx, paused, "worker")
if err != nil {
log.WithError(err).Errorf("failed to patch worker machine config pool for cluster deployment %s/%s", clusterDeployment.Namespace, clusterDeployment.Name)
return err
}
}
return nil
}
func (r *ClusterDeploymentsReconciler) installDay2Hosts(ctx context.Context, log logrus.FieldLogger, clusterDeployment *hivev1.ClusterDeployment, clusterInstall *hiveext.AgentClusterInstall, cluster *common.Cluster) (ctrl.Result, error) {
hosts, err := r.Installer.GetKnownApprovedHosts(*cluster.ID)
if err != nil {
log.WithError(err).Errorf("Failed to get ready and approved hosts for cluster %s", cluster.ID.String())
return r.updateStatus(ctx, log, clusterInstall, cluster, err)
}
for _, h := range hosts {
log.Infof("Installing Day2 host %s in %s %s", *h.ID, clusterDeployment.Name, clusterDeployment.Namespace)
err = r.Installer.InstallSingleDay2HostInternal(ctx, *cluster.ID, h.InfraEnvID, *h.ID)
if err != nil {
return r.updateStatus(ctx, log, clusterInstall, cluster, err)
}
}
err = r.updateWorkerMcpPaused(ctx, log, clusterInstall, clusterDeployment)
return r.updateStatus(ctx, log, clusterInstall, cluster, err)
}
func (r *ClusterDeploymentsReconciler) createNoIngressKubeConfig(ctx context.Context, log logrus.FieldLogger, cluster *hivev1.ClusterDeployment, c *common.Cluster, clusterInstall *hiveext.AgentClusterInstall) error {
if clusterInstall.Spec.ClusterMetadata != nil {
return nil
}
k, err := r.ensureKubeConfigNoIngressSecret(ctx, log, cluster, c)
if err != nil {
return err
}
clusterInstall.Spec.ClusterMetadata = &hivev1.ClusterMetadata{
ClusterID: c.OpenshiftClusterID.String(),
InfraID: string(*c.ID),
AdminKubeconfigSecretRef: corev1.LocalObjectReference{
Name: k.Name,
},
}
return r.Update(ctx, clusterInstall)
}
func (r *ClusterDeploymentsReconciler) updateClusterMetadata(ctx context.Context, log logrus.FieldLogger, cluster *hivev1.ClusterDeployment, c *common.Cluster, clusterInstall *hiveext.AgentClusterInstall) error {
s, err := r.ensureAdminPasswordSecret(ctx, log, cluster, c)
if err != nil {
return err
}
k, err := r.updateKubeConfigSecret(ctx, log, cluster, c)
if err != nil {
return err
}
clusterInstall.Spec.ClusterMetadata = &hivev1.ClusterMetadata{
ClusterID: c.OpenshiftClusterID.String(),
InfraID: string(*c.ID),
AdminPasswordSecretRef: &corev1.LocalObjectReference{
Name: s.Name,
},
AdminKubeconfigSecretRef: corev1.LocalObjectReference{
Name: k.Name,
},
}
return r.Update(ctx, clusterInstall)
}
func (r *ClusterDeploymentsReconciler) ensureAdminPasswordSecret(ctx context.Context, log logrus.FieldLogger, cluster *hivev1.ClusterDeployment, c *common.Cluster) (*corev1.Secret, error) {
name := fmt.Sprintf(adminPasswordSecretStringTemplate, cluster.Name)
secretRef := types.NamespacedName{Namespace: cluster.Namespace, Name: name}
s, getErr := getSecret(ctx, r.Client, r.APIReader, secretRef)
if getErr == nil || !k8serrors.IsNotFound(getErr) {
return s, getErr
}
if err := ensureSecretIsLabelled(ctx, r.Client, s, secretRef); err != nil {
return s, errors.Wrap(err, "Failed to label user-data secret")
}
cred, err := r.Installer.GetCredentialsInternal(ctx, installer.V2GetCredentialsParams{
ClusterID: *c.ID,
})
if err != nil {
return nil, err
}
data := map[string][]byte{
"username": []byte(cred.Username),
"password": []byte(cred.Password),
}
return r.createClusterCredentialSecret(ctx, log, cluster, name, data, "kubeadmincreds")
}
func (r *ClusterDeploymentsReconciler) updateKubeConfigSecret(ctx context.Context, log logrus.FieldLogger, cluster *hivev1.ClusterDeployment, c *common.Cluster) (*corev1.Secret, error) {
name := getClusterDeploymentAdminKubeConfigSecretName(cluster)
secretRef := types.NamespacedName{Namespace: cluster.Namespace, Name: name}
s, getErr := getSecret(ctx, r.Client, r.APIReader, secretRef)
if getErr != nil && !k8serrors.IsNotFound(getErr) {
return nil, getErr
}
if err := ensureSecretIsLabelled(ctx, r.Client, s, secretRef); err != nil {
return s, errors.Wrap(err, "Failed to label user-data secret")
}
respBody, _, err := r.Installer.V2DownloadClusterCredentialsInternal(ctx, installer.V2DownloadClusterCredentialsParams{
ClusterID: *c.ID,
FileName: constants.Kubeconfig,
})
if err != nil {
return nil, err
}
respBytes, err := io.ReadAll(respBody)
if err != nil {
return nil, err
}
data := map[string][]byte{
"kubeconfig": respBytes,
}
if k8serrors.IsNotFound(getErr) {
return r.createClusterCredentialSecret(ctx, log, cluster, name, data, "kubeconfig")
}
s.Data = data
return s, r.Update(ctx, s)
}
func (r *ClusterDeploymentsReconciler) ensureKubeConfigNoIngressSecret(ctx context.Context, log logrus.FieldLogger, cluster *hivev1.ClusterDeployment, c *common.Cluster) (*corev1.Secret, error) {
s := &corev1.Secret{}
name := getClusterDeploymentAdminKubeConfigSecretName(cluster)
getErr := r.Get(ctx, types.NamespacedName{Namespace: cluster.Namespace, Name: name}, s)
if getErr == nil || !k8serrors.IsNotFound(getErr) {
return s, getErr
}
respBody, _, err := r.Installer.V2DownloadClusterCredentialsInternal(ctx, installer.V2DownloadClusterCredentialsParams{
ClusterID: *c.ID,
FileName: constants.KubeconfigNoIngress,
})
if err != nil {
return nil, err
}
respBytes, err := io.ReadAll(respBody)
if err != nil {
return nil, err
}
data := map[string][]byte{
"kubeconfig": respBytes,
}
return r.createClusterCredentialSecret(ctx, log, cluster, name, data, "kubeconfig")
}
func (r *ClusterDeploymentsReconciler) createClusterCredentialSecret(ctx context.Context, log logrus.FieldLogger, cluster *hivev1.ClusterDeployment, name string, data map[string][]byte, secretType string) (*corev1.Secret, error) {
s := &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: cluster.Namespace,
},
Data: data,
}
s.Labels = AddLabel(s.Labels, "hive.openshift.io/cluster-deployment-name", cluster.Name)
s.Labels = AddLabel(s.Labels, "hive.openshift.io/secret-type", secretType)
deploymentGVK, err := apiutil.GVKForObject(cluster, r.Scheme)
if err != nil {
log.WithError(err).Errorf("error getting GVK for clusterdeployment")
return nil, err
}
s.OwnerReferences = []metav1.OwnerReference{{
APIVersion: deploymentGVK.GroupVersion().String(),
Kind: deploymentGVK.Kind,
Name: cluster.Name,
UID: cluster.UID,
BlockOwnerDeletion: pointer.BoolPtr(true),
}}
return s, r.Create(ctx, s)
}
func (r *ClusterDeploymentsReconciler) isReadyForInstallation(ctx context.Context, log logrus.FieldLogger, clusterInstall *hiveext.AgentClusterInstall, c *common.Cluster) (bool, error) {
if ready, _ := r.ClusterApi.IsReadyForInstallation(c); !ready {
return false, nil
}
registered, approvedHosts, err := r.getNumOfClusterAgents(c)
if err != nil {
log.WithError(err).Error("failed to fetch agents")
return false, err
}
agents, err := findAgentsByAgentClusterInstall(r.Client, ctx, log, clusterInstall)
if err != nil {
log.WithError(err).Error("failed to fetch ACI's agents")
return false, err
}
unsyncedHosts := getNumOfUnsyncedAgents(agents)
log.Debugf("Calculating installation readiness, found %d unsynced agents out of total of %d agents", unsyncedHosts, len(agents))
expectedHosts := clusterInstall.Spec.ProvisionRequirements.ControlPlaneAgents +
clusterInstall.Spec.ProvisionRequirements.WorkerAgents
return approvedHosts == expectedHosts && registered == approvedHosts && unsyncedHosts == 0, nil
}
func isSupportedPlatform(cluster *hivev1.ClusterDeployment) bool {
if cluster.Spec.ClusterInstallRef == nil ||
cluster.Spec.ClusterInstallRef.Group != hiveext.Group ||
cluster.Spec.ClusterInstallRef.Kind != "AgentClusterInstall" {
return false
}
return true
}
// UserManagedNetworking is considered false if
// 1. The cluster is an SNO (with no workers)
// 2. The User specifically set this parameter to false
// 3. Or, if the user did not set the value at all
func isUserManagedNetwork(clusterInstall *hiveext.AgentClusterInstall) bool {
return swag.BoolValue(clusterInstall.Spec.Networking.UserManagedNetworking) ||
clusterInstall.Spec.ProvisionRequirements.ControlPlaneAgents == 1 && clusterInstall.Spec.ProvisionRequirements.WorkerAgents == 0
}
func isDiskEncryptionEnabled(clusterInstall *hiveext.AgentClusterInstall) bool {
if clusterInstall.Spec.DiskEncryption == nil {
return false
}
switch swag.StringValue(clusterInstall.Spec.DiskEncryption.EnableOn) {
case models.DiskEncryptionEnableOnAll, models.DiskEncryptionEnableOnMasters, models.DiskEncryptionEnableOnWorkers:
return true
case models.DiskEncryptionEnableOnNone:
return false
default:
return false
}
}
// see https://docs.openshift.com/container-platform/4.7/installing/installing_platform_agnostic/installing-platform-agnostic.html#installation-bare-metal-config-yaml_installing-platform-agnostic
func hyperthreadingInSpec(clusterInstall *hiveext.AgentClusterInstall) bool {
//check if either master or worker pool hyperthreading settings are explicitly specified
return clusterInstall.Spec.ControlPlane != nil ||
funk.Contains(clusterInstall.Spec.Compute, func(pool hiveext.AgentMachinePool) bool {
return pool.Name == hiveext.WorkerAgentMachinePool
})
}
func getPlatform(aciSpec hiveext.AgentClusterInstallSpec) (*models.Platform, error) {
openshiftPlatformType := aciSpec.PlatformType
if openshiftPlatformType == "" {
//empty platform type means N/A. The service assigns a platform
//according to the cluster specifications (HA, UserManagedNetworking etc.)
return nil, nil
}
//convert between openshift API and the service platform name convension
switch openshiftPlatformType {
case hiveext.VSpherePlatformType:
return &models.Platform{
Type: common.PlatformTypePtr(models.PlatformTypeVsphere),
}, nil
case hiveext.NonePlatformType:
return &models.Platform{
Type: common.PlatformTypePtr(models.PlatformTypeNone),
}, nil
case hiveext.BareMetalPlatformType:
return &models.Platform{
Type: common.PlatformTypePtr(models.PlatformTypeBaremetal),
}, nil
case hiveext.ExternalPlatformType:
if aciSpec.ExternalPlatformSpec != nil && aciSpec.ExternalPlatformSpec.PlatformName == string(models.PlatformTypeOci) {
return &models.Platform{
Type: common.PlatformTypePtr(models.PlatformTypeOci),
}, nil
} else {
return nil, errors.New(fmt.Sprintf("For external platform, the platformName must be %s", string(models.PlatformTypeOci)))
}
case hiveext.NutanixPlatformType:
return &models.Platform{
Type: common.PlatformTypePtr(models.PlatformTypeNutanix),
}, nil
default:
return nil, nil
}
}
func getPlatformType(platform *models.Platform) hiveext.PlatformType {
if platform == nil || platform.Type == nil {
return ""
}
switch *platform.Type {
case models.PlatformTypeBaremetal:
return hiveext.BareMetalPlatformType
case models.PlatformTypeNone:
return hiveext.NonePlatformType
case models.PlatformTypeVsphere:
return hiveext.VSpherePlatformType
case models.PlatformTypeNutanix:
return hiveext.NutanixPlatformType
case models.PlatformTypeOci:
return hiveext.ExternalPlatformType
default:
return ""
}
}
func getHyperthreading(clusterInstall *hiveext.AgentClusterInstall) *string {
const (
None = 0
Workers = 1
Masters = 2
All = 3
)
var config uint = 0
//if there is no configuration of hyperthreading in the Spec then
//we are opting of the default behavior which is all enabled
if !hyperthreadingInSpec(clusterInstall) {
config = All
}
//check if the Spec enables hyperthreading for workers
for _, machinePool := range clusterInstall.Spec.Compute {
if machinePool.Name == hiveext.WorkerAgentMachinePool && machinePool.Hyperthreading == hiveext.HyperthreadingEnabled {
config = config | Workers
}
}
//check if the Spec enables hyperthreading for masters
if clusterInstall.Spec.ControlPlane != nil {
if clusterInstall.Spec.ControlPlane.Hyperthreading == hiveext.HyperthreadingEnabled {
config = config | Masters
}
}
//map between CRD Spec and cluster API
switch config {
case None:
return swag.String(models.ClusterHyperthreadingNone)
case Workers:
return swag.String(models.ClusterHyperthreadingWorkers)
case Masters:
return swag.String(models.ClusterHyperthreadingMasters)
default:
return swag.String(models.ClusterHyperthreadingAll)
}
}
func (r *ClusterDeploymentsReconciler) getEncodedCACert(ctx context.Context,
log logrus.FieldLogger,
caCertificateRef *hiveext.CaCertificateReference) (*string, error) {
secretRef := types.NamespacedName{Namespace: caCertificateRef.Namespace, Name: caCertificateRef.Name}
caSecret, err := getSecret(ctx, r.Client, r.APIReader, secretRef)
if err != nil {
return nil, errors.Wrap(err, "error getting ca certificate secret")
}
if err := ensureSecretIsLabelled(ctx, r.Client, caSecret, secretRef); err != nil {
return nil, errors.Wrap(err, "Failed to label user-data secret")
}
caCertBytes, hasCACert := caSecret.Data[corev1.TLSCertKey]
if !hasCACert {
return nil, fmt.Errorf("CA Secret is missing tls.crt key")
}
encodedCACert := base64.StdEncoding.EncodeToString(caCertBytes)
caCertificate := swag.String(encodedCACert)
return caCertificate, nil
}
func (r *ClusterDeploymentsReconciler) parseIgnitionEndpoint(ctx context.Context,
log logrus.FieldLogger,
kubeapiIgnitionEndpoint *hiveext.IgnitionEndpoint) (*models.IgnitionEndpoint, error) {
ignitionEndpoint := &models.IgnitionEndpoint{}
ignitionEndpoint.URL = swag.String(kubeapiIgnitionEndpoint.Url)
caCertificateReference := kubeapiIgnitionEndpoint.CaCertificateReference
if caCertificateReference != nil {
caCertificate, err := r.getEncodedCACert(ctx, log, caCertificateReference)
if err == nil {
ignitionEndpoint.CaCertificate = caCertificate
} else {
return nil, err
}
} else {
ignitionEndpoint.CaCertificate = swag.String("")
}
return ignitionEndpoint, nil
}
func (r *ClusterDeploymentsReconciler) updateIgnitionInUpdateParams(ctx context.Context,
log logrus.FieldLogger,
clusterInstall *hiveext.AgentClusterInstall,
cluster *common.Cluster,
params *models.V2ClusterUpdateParams) (bool, error) {
update := false
if clusterInstall.Spec.IgnitionEndpoint != nil {
ignitionEndpoint, err := r.parseIgnitionEndpoint(ctx, log, clusterInstall.Spec.IgnitionEndpoint)
if err == nil {
params.IgnitionEndpoint = ignitionEndpoint
if cluster.IgnitionEndpoint == nil || !reflect.DeepEqual(cluster.IgnitionEndpoint, ignitionEndpoint) {
update = true
}
} else {
log.WithError(err).Errorf("Failed to get and parse ignition ca certificate %s/%s", clusterInstall.Namespace, clusterInstall.Name)
return false, errors.Wrap(err, fmt.Sprintf("Failed to get and parse ignition ca certificate %s/%s", clusterInstall.Namespace, clusterInstall.Name))
}
} else {
if cluster.IgnitionEndpoint != nil {
if cluster.IgnitionEndpoint.URL != nil {
update = true
params.IgnitionEndpoint.URL = swag.String("")
}
if cluster.IgnitionEndpoint.CaCertificate != nil {
update = true
params.IgnitionEndpoint.CaCertificate = swag.String("")
}
}
}
return update, nil
}
func (r *ClusterDeploymentsReconciler) updateNetworkParams(clusterDeployment *hivev1.ClusterDeployment,
clusterInstall *hiveext.AgentClusterInstall,
cluster *common.Cluster, params *models.V2ClusterUpdateParams) (*bool, error) {
update := false
updateString := func(new, old string, target **string) {
if new != old {
*target = swag.String(new)
update = true
}
}
if len(clusterInstall.Spec.Networking.ClusterNetwork) > 0 {
newClusterNetworks := clusterNetworksEntriesToArray(clusterInstall.Spec.Networking.ClusterNetwork)
if len(newClusterNetworks) != len(cluster.ClusterNetworks) {
params.ClusterNetworks = newClusterNetworks
update = true
} else {
for index := range newClusterNetworks {
if newClusterNetworks[index].Cidr != cluster.ClusterNetworks[index].Cidr ||
newClusterNetworks[index].HostPrefix != cluster.ClusterNetworks[index].HostPrefix {
params.ClusterNetworks = newClusterNetworks
update = true
break
}
}
}
}
if len(clusterInstall.Spec.Networking.ServiceNetwork) > 0 {
newServiceNetworks := serviceNetworksEntriesToArray(clusterInstall.Spec.Networking.ServiceNetwork)
if len(newServiceNetworks) != len(cluster.ServiceNetworks) {
params.ServiceNetworks = newServiceNetworks
update = true
} else {
for index := range newServiceNetworks {
if newServiceNetworks[index].Cidr != cluster.ServiceNetworks[index].Cidr {
params.ServiceNetworks = newServiceNetworks
update = true
break
}
}
}
}
if len(clusterInstall.Spec.Networking.MachineNetwork) > 0 {
newMachineNetworks := machineNetworksEntriesToArray(clusterInstall.Spec.Networking.MachineNetwork)
if len(newMachineNetworks) != len(cluster.MachineNetworks) {
params.MachineNetworks = newMachineNetworks
update = true
} else {
for index := range newMachineNetworks {
if newMachineNetworks[index].Cidr != cluster.MachineNetworks[index].Cidr {
params.MachineNetworks = newMachineNetworks
update = true
break
}
}
}
}
if clusterInstall.Spec.Networking.NetworkType != "" {
updateString(clusterInstall.Spec.Networking.NetworkType, swag.StringValue(cluster.NetworkType), ¶ms.NetworkType)
} else if !clusterDeployment.Spec.Installed {
desiredNetworkType, err := selectClusterNetworkType(params, cluster)
if err != nil {
return nil, err
}
updateString(swag.StringValue(desiredNetworkType), swag.StringValue(cluster.NetworkType), ¶ms.NetworkType)
}
// Update APIVIP and IngressVIP only if cluster spec has VIPs defined and no DHCP enabled.
// In absence of this check, the reconcile loop in the controller fails all the time.
//
// We must not run this reconciler in case VIPs are missing from the cluster spec as this can
// indicate a scenario when backend calculates them automatically, e.g. SNO cluster.
isDHCPEnabled := swag.BoolValue(cluster.VipDhcpAllocation)
if !isDHCPEnabled && (clusterInstall.Spec.APIVIP != "" || clusterInstall.Spec.IngressVIP != "") {
desiredApiVips, _ := validations.HandleApiVipBackwardsCompatibility(
*cluster.ID,
clusterInstall.Spec.APIVIP,
apiVipsEntriesToArray(clusterInstall.Spec.APIVIPs))
if clusterInstall.Spec.APIVIP != cluster.APIVip ||
!network.AreApiVipsIdentical(desiredApiVips, cluster.APIVips) {
params.APIVip = swag.String(clusterInstall.Spec.APIVIP)
params.APIVips = desiredApiVips
update = true
}
desiredIngressVips, _ := validations.HandleIngressVipBackwardsCompatibility(*cluster.ID,
clusterInstall.Spec.IngressVIP,
ingressVipsEntriesToArray(clusterInstall.Spec.IngressVIPs))
if clusterInstall.Spec.IngressVIP != cluster.IngressVip ||
!network.AreIngressVipsIdentical(desiredIngressVips, cluster.IngressVips) {
params.IngressVip = swag.String(clusterInstall.Spec.IngressVIP)
params.IngressVips = desiredIngressVips
update = true
}
}
if userManagedNetwork := isUserManagedNetwork(clusterInstall); userManagedNetwork != swag.BoolValue(cluster.UserManagedNetworking) {
params.UserManagedNetworking = swag.Bool(userManagedNetwork)
update = true
}
return swag.Bool(update), nil
}
func (r *ClusterDeploymentsReconciler) updateIfNeeded(ctx context.Context,
log logrus.FieldLogger,
clusterDeployment *hivev1.ClusterDeployment,
clusterInstall *hiveext.AgentClusterInstall,
cluster *common.Cluster) (*common.Cluster, error) {
update := false
params := &models.V2ClusterUpdateParams{}
spec := clusterDeployment.Spec
updateString := func(new, old string, target **string) {
if new != old {
*target = swag.String(new)
update = true
}
}
updateString(spec.ClusterName, cluster.Name, ¶ms.Name)
updateString(spec.BaseDomain, cluster.BaseDNSDomain, ¶ms.BaseDNSDomain)
shouldUpdateNetworkParams, err := r.updateNetworkParams(clusterDeployment, clusterInstall, cluster, params)
if err != nil {
return cluster, errors.Wrap(err, "failed to update network params")
}
update = swag.BoolValue(shouldUpdateNetworkParams) || update
// Trim key before comapring as done in RegisterClusterInternal
sshPublicKey := strings.TrimSpace(clusterInstall.Spec.SSHPublicKey)
updateString(sshPublicKey, cluster.SSHPublicKey, ¶ms.SSHPublicKey)
// Update ignition endpoint if needed
shouldUpdate, err := r.updateIgnitionInUpdateParams(ctx, log, clusterInstall, cluster, params)
if err != nil {
return cluster, errors.Wrap(err, "Couldn't resolve clusterdeployment ignition fields")