-
Notifications
You must be signed in to change notification settings - Fork 169
Expand file tree
/
Copy pathhyperconverged_controller.go
More file actions
1276 lines (1084 loc) · 43 KB
/
hyperconverged_controller.go
File metadata and controls
1276 lines (1084 loc) · 43 KB
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 hyperconverged
import (
"cmp"
"context"
"fmt"
"io/fs"
"os"
"reflect"
"slices"
"time"
"github.com/blang/semver/v4"
jsonpatch "github.com/evanphx/json-patch/v5"
"github.com/go-logr/logr"
netattdefv1 "github.com/k8snetworkplumbingwg/network-attachment-definition-client/pkg/apis/k8s.cni.cncf.io/v1"
openshiftconfigv1 "github.com/openshift/api/config/v1"
consolev1 "github.com/openshift/api/console/v1"
imagev1 "github.com/openshift/api/image/v1"
routev1 "github.com/openshift/api/route/v1"
securityv1 "github.com/openshift/api/security/v1"
operatorhandler "github.com/operator-framework/operator-lib/handler"
monitoringv1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
networkingv1 "k8s.io/api/networking/v1"
rbacv1 "k8s.io/api/rbac/v1"
schedulingv1 "k8s.io/api/scheduling/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
apimetav1 "k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"k8s.io/utils/ptr"
"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"
logf "sigs.k8s.io/controller-runtime/pkg/log"
"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"
networkaddonsv1 "github.com/kubevirt/cluster-network-addons-operator/pkg/apis/networkaddonsoperator/v1"
kubevirtcorev1 "kubevirt.io/api/core/v1"
aaqv1alpha1 "kubevirt.io/application-aware-quota/staging/src/kubevirt.io/application-aware-quota-api/pkg/apis/core/v1alpha1"
cdiv1beta1 "kubevirt.io/containerized-data-importer-api/pkg/apis/core/v1beta1"
migrationv1alpha1 "kubevirt.io/kubevirt-migration-operator/api/v1alpha1"
sspv1beta3 "kubevirt.io/ssp-operator/api/v1beta3"
hcov1beta1 "github.com/kubevirt/hyperconverged-cluster-operator/api/v1beta1"
"github.com/kubevirt/hyperconverged-cluster-operator/controllers/alerts"
"github.com/kubevirt/hyperconverged-cluster-operator/controllers/common"
"github.com/kubevirt/hyperconverged-cluster-operator/controllers/operandhandler"
"github.com/kubevirt/hyperconverged-cluster-operator/controllers/reqresolver"
"github.com/kubevirt/hyperconverged-cluster-operator/pkg/monitoring/hyperconverged/metrics"
"github.com/kubevirt/hyperconverged-cluster-operator/pkg/nodeinfo"
"github.com/kubevirt/hyperconverged-cluster-operator/pkg/upgradepatch"
hcoutil "github.com/kubevirt/hyperconverged-cluster-operator/pkg/util"
"github.com/kubevirt/hyperconverged-cluster-operator/version"
)
var (
log = logf.Log.WithName("controller_hyperconverged")
)
const (
// We cannot set owner reference of cluster-wide resources to namespaced HyperConverged object. Therefore,
// use finalizers to manage the cleanup.
FinalizerName = "kubevirt.io/hyperconverged"
// OpenshiftNamespace is for resources that belong in the openshift namespace
reconcileInit = "Init"
reconcileInitMessage = "Initializing HyperConverged cluster"
reconcileCompleted = "ReconcileCompleted"
reconcileCompletedMessage = "Reconcile completed successfully"
invalidRequestReason = "InvalidRequest"
invalidRequestMessageFormat = "Request does not match expected name (%v) and namespace (%v)"
commonDegradedReason = "HCODegraded"
commonProgressingReason = "HCOProgressing"
taintedConfigurationReason = "UnsupportedFeatureAnnotation"
taintedConfigurationMessage = "Unsupported feature was activated via an HCO annotation"
systemHealthStatusHealthy = "healthy"
systemHealthStatusWarning = "warning"
systemHealthStatusError = "error"
hcoVersionName = "operator"
requestedStatusKey = "requested status"
requeueAfter = time.Millisecond * 100
)
// JSONPatchAnnotationNames - annotations used to patch operand CRs with unsupported/unofficial/hidden features.
// The presence of any of these annotations raises the hcov1beta1.ConditionTaintedConfiguration condition.
var JSONPatchAnnotationNames = []string{
common.JSONPatchKVAnnotationName,
common.JSONPatchCDIAnnotationName,
common.JSONPatchCNAOAnnotationName,
common.JSONPatchSSPAnnotationName,
}
// RegisterReconciler creates a new HyperConverged Reconciler and registers it into manager.
func RegisterReconciler(mgr manager.Manager,
ci hcoutil.ClusterInfo,
upgradeableCond hcoutil.Condition,
ingressEventCh <-chan event.GenericEvent,
nodeEventChannel <-chan event.GenericEvent) error {
return add(mgr, newReconciler(mgr, ci, upgradeableCond), ci, ingressEventCh, nodeEventChannel)
}
// newReconciler returns a new reconcile.Reconciler
func newReconciler(mgr manager.Manager, ci hcoutil.ClusterInfo, upgradeableCond hcoutil.Condition) reconcile.Reconciler {
ownVersion := cmp.Or(os.Getenv(hcoutil.HcoKvIoVersionName), version.Version)
var pwdFS fs.FS
pwd, err := os.Getwd()
if err != nil {
panic("can't get the working directory")
}
pwdFS = os.DirFS(pwd)
r := &ReconcileHyperConverged{
client: mgr.GetClient(),
scheme: mgr.GetScheme(),
operandHandler: operandhandler.NewOperandHandler(mgr.GetClient(), mgr.GetScheme(), ci, hcoutil.GetEventEmitter()),
upgradeMode: false,
ownVersion: ownVersion,
eventEmitter: hcoutil.GetEventEmitter(),
firstLoop: true,
upgradeableCondition: upgradeableCond,
pwdFS: pwdFS,
}
if ci.IsMonitoringAvailable() {
r.monitoringReconciler = alerts.NewMonitoringReconciler(ci, r.client, hcoutil.GetEventEmitter(), r.scheme)
}
return r
}
// newCRDremover returns a new CRDRemover
func add(mgr manager.Manager, r reconcile.Reconciler, ci hcoutil.ClusterInfo, ingressEventCh <-chan event.GenericEvent, nodeEventChannel <-chan event.GenericEvent) error {
// Create a new controller
c, err := controller.New("hyperconverged-controller", mgr, controller.Options{Reconciler: r})
if err != nil {
return err
}
// Watch for changes to primary resource HyperConverged
err = c.Watch(
source.Kind(
mgr.GetCache(), client.Object(&hcov1beta1.HyperConverged{}),
&operatorhandler.InstrumentedEnqueueRequestForObject[client.Object]{},
predicate.Or[client.Object](predicate.GenerationChangedPredicate{}, predicate.AnnotationChangedPredicate{},
predicate.ResourceVersionChangedPredicate{}),
))
if err != nil {
return err
}
// To limit the memory usage, the controller manager got instantiated with a custom cache
// that is watching only a specific set of objects with selectors.
// When a new object got added here, it has also to be added to the custom cache
// managed by getNewManagerCache()
secondaryResources := []client.Object{
&kubevirtcorev1.KubeVirt{},
&cdiv1beta1.CDI{},
&networkaddonsv1.NetworkAddonsConfig{},
&aaqv1alpha1.AAQ{},
&migrationv1alpha1.MigController{},
&schedulingv1.PriorityClass{},
&corev1.ConfigMap{},
&corev1.Service{},
&corev1.ServiceAccount{},
&appsv1.DaemonSet{},
&rbacv1.Role{},
&rbacv1.RoleBinding{},
&rbacv1.ClusterRole{},
&rbacv1.ClusterRoleBinding{},
}
if ci.IsMonitoringAvailable() {
secondaryResources = append(secondaryResources, []client.Object{
&monitoringv1.ServiceMonitor{},
&monitoringv1.PrometheusRule{},
&networkingv1.NetworkPolicy{},
&corev1.Secret{},
}...)
}
if ci.IsOpenshift() {
secondaryResources = append(secondaryResources, []client.Object{
&sspv1beta3.SSP{},
&corev1.Service{},
&routev1.Route{},
&consolev1.ConsoleCLIDownload{},
&consolev1.ConsoleQuickStart{},
&consolev1.ConsolePlugin{},
&imagev1.ImageStream{},
&corev1.Namespace{},
&appsv1.Deployment{},
&securityv1.SecurityContextConstraints{},
}...)
}
if ci.IsNADAvailable() {
secondaryResources = append(secondaryResources, []client.Object{
&netattdefv1.NetworkAttachmentDefinition{},
}...)
}
// Watch secondary resources
for _, resource := range secondaryResources {
msg := fmt.Sprintf("Reconciling for %T", resource)
err = c.Watch(
source.Kind(mgr.GetCache(), resource,
handler.EnqueueRequestsFromMapFunc(func(ctx context.Context, a client.Object) []reconcile.Request {
// enqueue using a placeholder to be able to discriminate request triggered
// by changes on the HyperConverged object from request triggered by changes
// on a secondary CR controlled by HCO
log.Info(msg)
return []reconcile.Request{
reqresolver.GetSecondaryCRRequest(),
}
}),
))
if err != nil {
return err
}
}
if ci.IsOpenshift() {
err = c.Watch(
source.Kind(
mgr.GetCache(),
client.Object(&openshiftconfigv1.APIServer{}),
handler.EnqueueRequestsFromMapFunc(func(ctx context.Context, a client.Object) []reconcile.Request {
// enqueue using a placeholder to signal that the change is not
// directly on HCO CR but on the APIServer CR that we want to reload
// only if really changed
log.Info("Reconciling for openshiftconfigv1.APIServer")
return []reconcile.Request{
reqresolver.GetAPIServerCRRequest(),
}
}),
))
if err != nil {
return err
}
err = c.Watch(
source.Channel(
ingressEventCh,
handler.EnqueueRequestsFromMapFunc(func(ctx context.Context, a client.Object) []reconcile.Request {
// the ingress-cluster controller initiate this by pushing an event to the ingressEventCh channel
// This will force this controller to update the URL of the cli download route, if the user
// customized the hostname.
log.Info("Reconciling for openshiftconfigv1.Ingress")
return []reconcile.Request{
reqresolver.GetIngressCRResource(),
}
}),
))
if err != nil {
return err
}
err = c.Watch(
source.Channel(
nodeEventChannel,
handler.EnqueueRequestsFromMapFunc(func(ctx context.Context, a client.Object) []reconcile.Request {
// the nodes controller initiate this by pushing an event to the nodeEventChannel channel
// This will force this controller to update the status fields related to the cluster nodes, and
// to re-generate the DataImportCronTemplates in the SSP CR.
log.Info("Reconciling for core.Node")
return []reconcile.Request{
reqresolver.GetNodeResource(),
}
}),
))
if err != nil {
return err
}
}
return nil
}
var _ reconcile.Reconciler = &ReconcileHyperConverged{}
// ReconcileHyperConverged reconciles a HyperConverged object
type ReconcileHyperConverged struct {
// This client, initialized using mgr.Client() above, is a split client
// that reads objects from the cache and writes to the apiserver
client client.Client
scheme *runtime.Scheme
operandHandler *operandhandler.OperandHandler
upgradeMode bool
ownVersion string
eventEmitter hcoutil.EventEmitter
firstLoop bool
upgradeableCondition hcoutil.Condition
monitoringReconciler *alerts.MonitoringReconciler
pwdFS fs.FS
}
// Reconcile reads that state of the cluster for a HyperConverged object and makes changes based on the state read
// and what is in the HyperConverged.Spec
// Note:
// The Controller will requeue the Request to be processed again if the returned error is non-nil or
// Result.Requeue is true, otherwise upon completion it will remove the work from the queue.
func (r *ReconcileHyperConverged) Reconcile(ctx context.Context, request reconcile.Request) (reconcile.Result, error) {
logger := log.WithValues("Request.Namespace", request.Namespace, "Request.Name", request.Name)
err := r.refreshAPIServerCR(ctx, logger, request)
if err != nil {
return reconcile.Result{}, err
}
resolvedRequest, hcoTriggered := reqresolver.ResolveReconcileRequest(logger, request)
hcoRequest := common.NewHcoRequest(ctx, resolvedRequest, logger, r.upgradeMode, hcoTriggered)
if hcoTriggered {
r.operandHandler.Reset()
}
err = r.monitoringReconciler.Reconcile(hcoRequest, r.firstLoop)
if err != nil {
return reconcile.Result{}, err
}
// Fetch the HyperConverged instance
instance, err := r.getHyperConverged(hcoRequest)
if err != nil {
return reconcile.Result{}, err
}
hcoRequest.Instance = instance
if instance == nil {
// if the HyperConverged CR was deleted during an upgrade process, then this is not an upgrade anymore
r.upgradeMode = false
err = r.setOperatorUpgradeableStatus(hcoRequest)
return reconcile.Result{}, err
}
if r.firstLoop {
r.firstLoopInitialization(hcoRequest)
}
if err = r.monitoringReconciler.UpdateRelatedObjects(hcoRequest); err != nil {
logger.Error(err, "Failed to update the PrometheusRule as a related object")
return reconcile.Result{}, err
}
result, err := r.doReconcile(hcoRequest)
if err != nil {
r.eventEmitter.EmitEvent(hcoRequest.Instance, corev1.EventTypeWarning, "ReconcileError", err.Error())
return result, err
}
if err = r.setOperatorUpgradeableStatus(hcoRequest); err != nil {
return reconcile.Result{}, err
}
requeue, err := r.updateHyperConverged(hcoRequest)
if requeue || apierrors.IsConflict(err) {
result.RequeueAfter = requeueAfter
}
return result, err
}
// refreshAPIServerCR refreshes the APIServer cR, if the request is triggered by this CR.
func (r *ReconcileHyperConverged) refreshAPIServerCR(ctx context.Context, logger logr.Logger, originalRequest reconcile.Request) error {
if reqresolver.IsTriggeredByAPIServerCR(originalRequest) {
logger.Info("Refreshing the ApiServer CR")
return hcoutil.GetClusterInfo().RefreshAPIServerCR(ctx, r.client)
}
return nil
}
func (r *ReconcileHyperConverged) doReconcile(req *common.HcoRequest) (reconcile.Result, error) {
valid := r.validateNamespace(req)
if !valid {
return reconcile.Result{}, nil
}
// Add conditions if there are none
init := req.Instance.Status.Conditions == nil
if init {
r.eventEmitter.EmitEvent(req.Instance, corev1.EventTypeNormal, "InitHCO", "Initiating the HyperConverged")
r.setInitialConditions(req)
req.StatusDirty = true
}
r.setLabels(req)
updateStatus(req)
metrics.SetHCOMetricMemoryOvercommitPercentage(
getMemoryOvercommitPercentage(req.Instance.Spec.HigherWorkloadDensity),
)
// in-memory conditions should start off empty. It will only ever hold
// negative conditions (!Available, Degraded, Progressing)
req.Conditions = common.NewHcoConditions()
// Handle finalizers
if !checkFinalizers(req) {
if !req.HCOTriggered {
// this is just the effect of a delete request created by HCO
// in the previous iteration, ignore it
return reconcile.Result{}, nil
}
return r.ensureHcoDeleted(req)
}
applyDataImportSchedule(req)
// If the current version is not updated in CR ,then we're updating. This is also works when updating from
// an old version, since Status.Versions will be empty.
knownHcoVersion, _ := GetVersion(&req.Instance.Status, hcoVersionName)
// detect upgrade mode
if !r.upgradeMode && !init && knownHcoVersion != r.ownVersion {
// get into upgrade mode
r.upgradeMode = true
r.eventEmitter.EmitEvent(req.Instance, corev1.EventTypeNormal, "UpgradeHCO", "Upgrading the HyperConverged to version "+r.ownVersion)
req.Logger.Info(fmt.Sprintf("Start upgrading from version %s to version %s", knownHcoVersion, r.ownVersion))
}
req.SetUpgradeMode(r.upgradeMode)
if r.upgradeMode {
if result, err := r.handleUpgrade(req); result != nil {
return *result, err
}
}
return r.EnsureOperandAndComplete(req, init)
}
func (r *ReconcileHyperConverged) handleUpgrade(req *common.HcoRequest) (*reconcile.Result, error) {
modified, err := r.migrateBeforeUpgrade(req)
if err != nil {
return &reconcile.Result{RequeueAfter: requeueAfter}, err
}
if modified {
r.updateConditions(req)
return &reconcile.Result{RequeueAfter: requeueAfter}, nil
}
return nil, nil
}
func (r *ReconcileHyperConverged) EnsureOperandAndComplete(req *common.HcoRequest, init bool) (reconcile.Result, error) {
if err := r.operandHandler.Ensure(req); err != nil {
r.updateConditions(req)
requeue := time.Duration(0)
if init {
requeue = requeueAfter
}
return reconcile.Result{RequeueAfter: requeue}, nil
}
req.Logger.Info("Reconcile complete")
// Requeue if we just created everything
if init {
return reconcile.Result{RequeueAfter: requeueAfter}, nil
}
r.completeReconciliation(req)
return reconcile.Result{}, nil
}
func updateStatus(req *common.HcoRequest) {
if req.Instance.Generation != req.Instance.Status.ObservedGeneration {
req.Instance.Status.ObservedGeneration = req.Instance.Generation
req.StatusDirty = true
}
if infraHighlyAvailable := nodeinfo.IsInfrastructureHighlyAvailable(); req.Instance.Status.InfrastructureHighlyAvailable == nil ||
*req.Instance.Status.InfrastructureHighlyAvailable != infraHighlyAvailable {
if infraHighlyAvailable {
req.Logger.Info("infrastructure became highly available")
} else {
req.Logger.Info("infrastructure became not highly available")
}
req.Instance.Status.InfrastructureHighlyAvailable = ptr.To(infraHighlyAvailable)
req.StatusDirty = true
}
if cpArch := nodeinfo.GetControlPlaneArchitectures(); slices.Compare(req.Instance.Status.NodeInfo.ControlPlaneArchitectures, cpArch) != 0 {
req.Instance.Status.NodeInfo.ControlPlaneArchitectures = cpArch
req.StatusDirty = true
}
if workloadsArch := nodeinfo.GetWorkloadsArchitectures(); slices.Compare(req.Instance.Status.NodeInfo.WorkloadsArchitectures, workloadsArch) != 0 {
req.Instance.Status.NodeInfo.WorkloadsArchitectures = workloadsArch
req.StatusDirty = true
}
if cpuModels := nodeinfo.GetRecommendedCpuModels(); !slices.EqualFunc(req.Instance.Status.NodeInfo.RecommendedCpuModels, cpuModels, hcov1beta1.CpuModelInfo.Equal) {
req.Instance.Status.NodeInfo.RecommendedCpuModels = cpuModels
req.StatusDirty = true
}
}
// getHyperConverged gets the HyperConverged resource from the Kubernetes API.
func (r *ReconcileHyperConverged) getHyperConverged(req *common.HcoRequest) (*hcov1beta1.HyperConverged, error) {
instance := &hcov1beta1.HyperConverged{}
err := r.client.Get(req.Ctx, req.NamespacedName, instance)
// Green path first
if err == nil {
metrics.SetHCOMetricHyperConvergedExists()
return instance, nil
}
// Error path
if apierrors.IsNotFound(err) {
req.Logger.Info("No HyperConverged resource")
metrics.SetHCOMetricHyperConvergedNotExists()
// Request object not found, could have been deleted after reconcile request.
// Owned objects are automatically garbage collected. For additional cleanup logic use finalizers.
// Return and don't requeue
return nil, nil
}
// Another error reading the object.
// Just return the error so that the request is requeued.
return nil, err
}
// updateHyperConverged updates the HyperConverged resource according to its state in the request.
func (r *ReconcileHyperConverged) updateHyperConverged(request *common.HcoRequest) (bool, error) {
// Since the status subresource is enabled for the HyperConverged kind,
// we need to update the status and the metadata separately.
// Moreover, we need to update the status first, in order to prevent a conflict.
// In addition, metadata and spec changes are removed by status update, but since status update done first, we need
// to store metadata and spec and recover it after status update
var spec hcov1beta1.HyperConvergedSpec
var meta metav1.ObjectMeta
if request.Dirty {
request.Instance.Spec.DeepCopyInto(&spec)
request.Instance.ObjectMeta.DeepCopyInto(&meta)
}
err := r.updateHyperConvergedStatus(request)
if err != nil {
request.Logger.Error(err, "Failed to update HCO Status")
return false, err
}
if request.Dirty {
request.Instance.Annotations = meta.Annotations
request.Instance.Finalizers = meta.Finalizers
request.Instance.Labels = meta.Labels
request.Instance.Spec = spec
err = r.updateHyperConvergedSpecMetadata(request)
if err != nil {
request.Logger.Error(err, "Failed to update HCO CR")
return false, err
}
// version update is a two steps process
knownHcoVersion, _ := GetVersion(&request.Instance.Status, hcoVersionName)
if r.ownVersion != knownHcoVersion && request.StatusDirty {
return true, nil
}
}
return false, nil
}
// updateHyperConvergedSpecMetadata updates the HyperConverged resource's spec and metadata.
func (r *ReconcileHyperConverged) updateHyperConvergedSpecMetadata(request *common.HcoRequest) error {
if !request.Dirty {
return nil
}
return r.client.Update(request.Ctx, request.Instance)
}
// updateHyperConvergedSpecMetadata updates the HyperConverged resource's status (and metadata).
func (r *ReconcileHyperConverged) updateHyperConvergedStatus(request *common.HcoRequest) error {
if !request.StatusDirty {
return nil
}
return r.client.Status().Update(request.Ctx, request.Instance)
}
func (r *ReconcileHyperConverged) validateNamespace(req *common.HcoRequest) bool {
// Ignore invalid requests
if !reqresolver.IsTriggeredByHyperConverged(req.NamespacedName) {
req.Logger.Info("Invalid request", "HyperConverged.Namespace", req.Namespace, "HyperConverged.Name", req.Name)
hc := reqresolver.GetHyperConvergedNamespacedName()
req.Conditions.SetStatusCondition(metav1.Condition{
Type: hcov1beta1.ConditionReconcileComplete,
Status: metav1.ConditionFalse,
Reason: invalidRequestReason,
Message: fmt.Sprintf(invalidRequestMessageFormat, hc.Name, hc.Namespace),
ObservedGeneration: req.Instance.Generation,
})
r.updateConditions(req)
return false
}
return true
}
func (r *ReconcileHyperConverged) setInitialConditions(req *common.HcoRequest) {
UpdateVersion(&req.Instance.Status, hcoVersionName, r.ownVersion)
req.Conditions.SetStatusCondition(metav1.Condition{
Type: hcov1beta1.ConditionReconcileComplete,
Status: metav1.ConditionUnknown, // we just started trying to reconcile
Reason: reconcileInit,
Message: reconcileInitMessage,
ObservedGeneration: req.Instance.Generation,
})
req.Conditions.SetStatusCondition(metav1.Condition{
Type: hcov1beta1.ConditionAvailable,
Status: metav1.ConditionFalse,
Reason: reconcileInit,
Message: reconcileInitMessage,
ObservedGeneration: req.Instance.Generation,
})
req.Conditions.SetStatusCondition(metav1.Condition{
Type: hcov1beta1.ConditionProgressing,
Status: metav1.ConditionTrue,
Reason: reconcileInit,
Message: reconcileInitMessage,
ObservedGeneration: req.Instance.Generation,
})
req.Conditions.SetStatusCondition(metav1.Condition{
Type: hcov1beta1.ConditionDegraded,
Status: metav1.ConditionFalse,
Reason: reconcileInit,
Message: reconcileInitMessage,
ObservedGeneration: req.Instance.Generation,
})
req.Conditions.SetStatusCondition(metav1.Condition{
Type: hcov1beta1.ConditionUpgradeable,
Status: metav1.ConditionUnknown,
Reason: reconcileInit,
Message: reconcileInitMessage,
ObservedGeneration: req.Instance.Generation,
})
r.updateConditions(req)
}
func (r *ReconcileHyperConverged) ensureHcoDeleted(req *common.HcoRequest) (reconcile.Result, error) {
err := r.operandHandler.EnsureDeleted(req)
if err != nil {
return reconcile.Result{}, err
}
requeue := time.Duration(0)
// Remove the finalizers
if idx := slices.Index(req.Instance.Finalizers, FinalizerName); idx >= 0 {
req.Instance.Finalizers = slices.Delete(req.Instance.Finalizers, idx, idx+1)
req.Dirty = true
requeue = requeueAfter
}
// Need to requeue because finalizer update does not change metadata.generation
return reconcile.Result{RequeueAfter: requeue}, nil
}
func (r *ReconcileHyperConverged) aggregateComponentConditions(req *common.HcoRequest) bool {
/*
See the chart at design/aggregateComponentConditions.svg; The numbers below follows the numbers in the chart
Here is the PlantUML code for the chart that describes the aggregation of the sub-components conditions.
Find the PlantURL syntax here: https://plantuml.com/activity-diagram-beta
@startuml ../../../design/aggregateComponentConditions.svg
title Aggregate Component Conditions
start
#springgreen:Set **ReconcileComplete = True**]
!x=1
if ((x) [Degraded = True] Exists) then
!x=x+1
#orangered:<<implicit>>\n**Degraded = True** /
-[#orangered]-> yes;
if ((x) [Progressing = True] Exists) then
!x=x+1
-[#springgreen]-> no;
#springgreen:(x) Set **Progressing = False**]
!x=x+1
else
-[#orangered]-> yes;
#orangered:<<implicit>>\n**Progressing = True** /
endif
if ((x) [Upgradable = False] Exists) then
!x=x+1
-[#springgreen]-> no;
#orangered:(x) Set **Upgradable = False**]
!x=x+1
else
-[#orangered]-> yes;
#orangered:<<implicit>>\n**Upgradable = False** /
endif
if ((x) [Available = False] Exists) then
!x=x+1
-[#springgreen]-> no;
#orangered:(x) Set **Available = False**]
!x=x+1
else
-[#orangered]-> yes;
#orangered:<<implicit>>\n**Available = False** /
endif
else
-[#springgreen]-> no;
#springgreen:(x) Set **Degraded = False**]
!x=x+1
if ((x) [Progressing = True] Exists) then
!x=x+1
-[#orangered]-> yes;
#orangered:<<implicit>>\n**Progressing = True** /
if ((x) [Upgradable = False] Exists) then
!x=x+1
-[#springgreen]-> no;
#orangered:(x) Set **Upgradable = False**]
!x=x+1
else
-[#orangered]-> yes;
#orangered:<<implicit>>\n**Upgradable = False** /
endif
if ((x) [Available = False] Exists) then
!x=x+1
-[#springgreen]-> no;
#springgreen:(x) Set **Available = True**]
!x=x+1
else
#orangered:<<implicit>>\n**Available = False** /
-[#orangered]-> yes;
endif
else
-[#springgreen]-> no;
#springgreen:(x) Set **Progressing = False**]
!x=x+1
if ((x) [Upgradable = False] Exists) then
!x=x+1
-[#springgreen]-> no;
#springgreen:(x) Set **Upgradable = True**]
!x=x+1
else
#orangered:<<implicit>>\n**Upgradable = False** /
-[#orangered]-> yes;
endif
if ((x) [Available = False] Exists) then
!x=x+1
-[#springgreen]-> no;
#springgreen:(x) Set **Available = True**]
!x=x+1
else
-[#orangered]-> yes;
#orangered:<<implicit>>\n**Available = False** /
endif
endif
endif
end
@enduml
*/
/*
If any component operator reports negatively we want to write that to
the instance while preserving it's lastTransitionTime.
For example, consider the KubeVirt resource has the Available condition
type with type "False". When reconciling KubeVirt's resource we would
add it to the in-memory representation of HCO's conditions (r.conditions)
and here we are simply writing it back to the server.
One shortcoming is that only one failure of a particular condition can be
captured at one time (ie. if KubeVirt and CDI are both reporting !Available,
you will only see CDI as it updates last).
*/
allComponentsAreUp := req.Conditions.IsEmpty()
req.Conditions.SetStatusCondition(metav1.Condition{
Type: hcov1beta1.ConditionReconcileComplete,
Status: metav1.ConditionTrue,
Reason: reconcileCompleted,
Message: reconcileCompletedMessage,
ObservedGeneration: req.Instance.Generation,
})
if req.Conditions.HasCondition(hcov1beta1.ConditionDegraded) { // (#chart 1)
req.Conditions.SetStatusConditionIfUnset(metav1.Condition{ // (#chart 2,3)
Type: hcov1beta1.ConditionProgressing,
Status: metav1.ConditionFalse,
Reason: reconcileCompleted,
Message: reconcileCompletedMessage,
ObservedGeneration: req.Instance.Generation,
})
req.Conditions.SetStatusConditionIfUnset(metav1.Condition{ // (#chart 4,5)
Type: hcov1beta1.ConditionUpgradeable,
Status: metav1.ConditionFalse,
Reason: commonDegradedReason,
Message: "HCO is not Upgradeable due to degraded components",
ObservedGeneration: req.Instance.Generation,
})
req.Conditions.SetStatusConditionIfUnset(metav1.Condition{ // (#chart 6,7)
Type: hcov1beta1.ConditionAvailable,
Status: metav1.ConditionFalse,
Reason: commonDegradedReason,
Message: "HCO is not available due to degraded components",
ObservedGeneration: req.Instance.Generation,
})
} else {
// Degraded is not found. add it.
req.Conditions.SetStatusCondition(metav1.Condition{ // (#chart 8)
Type: hcov1beta1.ConditionDegraded,
Status: metav1.ConditionFalse,
Reason: reconcileCompleted,
Message: reconcileCompletedMessage,
ObservedGeneration: req.Instance.Generation,
})
if req.Conditions.HasCondition(hcov1beta1.ConditionProgressing) { // (#chart 9)
req.Conditions.SetStatusConditionIfUnset(metav1.Condition{ // (#chart 10,11)
Type: hcov1beta1.ConditionUpgradeable,
Status: metav1.ConditionFalse,
Reason: commonProgressingReason,
Message: "HCO is not Upgradeable due to progressing components",
ObservedGeneration: req.Instance.Generation,
})
req.Conditions.SetStatusConditionIfUnset(metav1.Condition{ // (#chart 12,13)
Type: hcov1beta1.ConditionAvailable,
Status: metav1.ConditionTrue,
Reason: reconcileCompleted,
Message: reconcileCompletedMessage,
ObservedGeneration: req.Instance.Generation,
})
} else {
req.Conditions.SetStatusCondition(metav1.Condition{ // (#chart 14)
Type: hcov1beta1.ConditionProgressing,
Status: metav1.ConditionFalse,
Reason: reconcileCompleted,
Message: reconcileCompletedMessage,
ObservedGeneration: req.Instance.Generation,
})
req.Conditions.SetStatusConditionIfUnset(metav1.Condition{ // (#chart 15,16)
Type: hcov1beta1.ConditionUpgradeable,
Status: metav1.ConditionTrue,
Reason: reconcileCompleted,
Message: reconcileCompletedMessage,
ObservedGeneration: req.Instance.Generation,
})
req.Conditions.SetStatusConditionIfUnset(metav1.Condition{ // (#chart 17,18)
Type: hcov1beta1.ConditionAvailable,
Status: metav1.ConditionTrue,
Reason: reconcileCompleted,
Message: reconcileCompletedMessage,
ObservedGeneration: req.Instance.Generation,
})
}
}
return allComponentsAreUp
}
func (r *ReconcileHyperConverged) completeReconciliation(req *common.HcoRequest) {
allComponentsAreUp := r.aggregateComponentConditions(req)
hcoReady := false
if allComponentsAreUp {
req.Logger.Info("No component operator reported negatively")
// if in upgrade mode, and all the components are upgraded, and nothing pending to be written - upgrade is completed
if r.upgradeMode && req.ComponentUpgradeInProgress && !req.Dirty {
// update the new version only when upgrade is completed
UpdateVersion(&req.Instance.Status, hcoVersionName, r.ownVersion)
req.StatusDirty = true
r.upgradeMode = false
req.ComponentUpgradeInProgress = false
req.Logger.Info(fmt.Sprintf("Successfully upgraded to version %s", r.ownVersion))
r.eventEmitter.EmitEvent(req.Instance, corev1.EventTypeNormal, "UpgradeHCO", fmt.Sprintf("Successfully upgraded to version %s", r.ownVersion))
}
// If not in upgrade mode, then we're ready, because all the operators reported positive conditions.
// if upgrade was done successfully, r.upgradeMode is already false here.
hcoReady = !r.upgradeMode
}
if r.upgradeMode {
// override the Progressing condition during upgrade
req.Conditions.SetStatusCondition(metav1.Condition{
Type: hcov1beta1.ConditionProgressing,
Status: metav1.ConditionTrue,
Reason: "HCOUpgrading",
Message: "HCO is now upgrading to version " + r.ownVersion,
ObservedGeneration: req.Instance.Generation,
})
}
// check if HCO was available before this reconcile loop
hcoWasAvailable := apimetav1.IsStatusConditionTrue(req.Instance.Status.Conditions, hcov1beta1.ConditionAvailable) &&
apimetav1.IsStatusConditionFalse(req.Instance.Status.Conditions, hcov1beta1.ConditionProgressing)
if hcoReady {
// If no operator whose conditions we are watching reports an error, then it is safe
// to set readiness.
if !hcoWasAvailable { // only when become available
r.eventEmitter.EmitEvent(req.Instance, corev1.EventTypeNormal, "ReconcileHCO", "HCO Reconcile completed successfully")
}
} else {
// If for any reason we marked ourselves !upgradeable...then unset readiness
if !r.upgradeMode && hcoWasAvailable { // only when become not ready
r.eventEmitter.EmitEvent(req.Instance, corev1.EventTypeWarning, "ReconcileHCO", "Not all the operators are ready")
}
}
r.updateConditions(req)
}
// This function is used to exit from the reconcile function, updating the conditions and returns the reconcile result
func (r *ReconcileHyperConverged) updateConditions(req *common.HcoRequest) {
conditions := slices.Clone(req.Instance.Status.Conditions)
for _, condType := range common.HcoConditionTypes {
cond, found := req.Conditions[condType]
if !found {
cond = metav1.Condition{
Type: condType,
Status: metav1.ConditionUnknown,
Message: "Unknown Status",
Reason: "StatusUnknown",
ObservedGeneration: req.Instance.Generation,
}
}
apimetav1.SetStatusCondition(&conditions, cond)
}
// Detect a "TaintedConfiguration" state, and raise a corresponding event
r.detectTaintedConfiguration(req, &conditions)
if !reflect.DeepEqual(conditions, req.Instance.Status.Conditions) {
req.Instance.Status.Conditions = conditions
req.StatusDirty = true
}
systemHealthStatus := r.getSystemHealthStatus(req)
if systemHealthStatus != req.Instance.Status.SystemHealthStatus {
req.Instance.Status.SystemHealthStatus = systemHealthStatus
req.StatusDirty = true
}
metrics.SetHCOMetricSystemHealthStatus(getNumericalHealthStatus(systemHealthStatus))
}
func (r *ReconcileHyperConverged) setLabels(req *common.HcoRequest) {
if req.Instance.Labels == nil {
req.Instance.Labels = map[string]string{}
}
if req.Instance.Labels[hcoutil.AppLabel] == "" {
req.Instance.Labels[hcoutil.AppLabel] = req.Instance.Name
req.Dirty = true
}
}
func (r *ReconcileHyperConverged) detectTaintedConfiguration(req *common.HcoRequest, conditions *[]metav1.Condition) {
conditionExists := apimetav1.IsStatusConditionTrue(req.Instance.Status.Conditions, hcov1beta1.ConditionTaintedConfiguration)