-
Notifications
You must be signed in to change notification settings - Fork 35
/
managedocs_controller.go
2142 lines (1913 loc) · 73.4 KB
/
managedocs_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
/*
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"
"fmt"
"math"
"net/url"
"os"
"strconv"
"strings"
"time"
"gopkg.in/yaml.v2"
opv1a1 "github.com/operator-framework/api/pkg/operators/v1alpha1"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
storagev1 "k8s.io/api/storage/v1"
"k8s.io/apimachinery/pkg/api/equality"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/intstr"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/builder"
"sigs.k8s.io/controller-runtime/pkg/client"
controller "sigs.k8s.io/controller-runtime/pkg/controller"
"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"
"github.com/go-logr/logr"
configv1 "github.com/openshift/api/config/v1"
openshiftv1 "github.com/openshift/api/network/v1"
ovnv1 "github.com/ovn-org/ovn-kubernetes/go-controller/pkg/crd/egressfirewall/v1"
promv1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1"
promv1a1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1alpha1"
odfv1a1 "github.com/red-hat-data-services/odf-operator/api/v1alpha1"
ocsv1 "github.com/red-hat-storage/ocs-operator/api/v1"
ocsv1alpha1 "github.com/red-hat-storage/ocs-operator/api/v1alpha1"
v1 "github.com/red-hat-storage/ocs-osd-deployer/api/v1alpha1"
"github.com/red-hat-storage/ocs-osd-deployer/templates"
"github.com/red-hat-storage/ocs-osd-deployer/utils"
netv1 "k8s.io/api/networking/v1"
)
const (
ManagedOCSFinalizer = "managedocs.ocs.openshift.io"
EgressFirewallCRD = "egressfirewalls.k8s.ovn.org"
EgressNetworkPolicyCRD = "egressnetworkpolicies.network.openshift.io"
managedOCSName = "managedocs"
storageClusterName = "ocs-storagecluster"
prometheusName = "managed-ocs-prometheus"
prometheusServiceName = "prometheus"
alertmanagerName = "managed-ocs-alertmanager"
alertmanagerConfigName = "managed-ocs-alertmanager-config"
dmsRuleName = "dms-monitor-rule"
storageSizeKey = "size"
storageUnitKey = "unit"
onboardingTicketKey = "onboarding-ticket"
storageProviderEndpointKey = "storage-provider-endpoint"
enableMCGKey = "enable-mcg"
notificationEmailKeyPrefix = "notification-email"
onboardingValidationKey = "onboarding-validation-key"
deviceSetName = "default"
storageClassRbdName = "ocs-storagecluster-ceph-rbd"
storageClassCephFSName = "ocs-storagecluster-cephfs"
deployerCSVPrefix = "ocs-osd-deployer"
ocsOperatorName = "ocs-operator"
mcgOperatorName = "mcg-operator"
egressNetworkPolicyName = "egress-rule"
egressFirewallName = "default"
ingressNetworkPolicyName = "ingress-rule"
cephIngressNetworkPolicyName = "ceph-ingress-rule"
providerApiServerNetworkPolicyName = "provider-api-server-rule"
prometheusProxyNetworkPolicyName = "prometheus-proxy-rule"
monLabelKey = "app"
monLabelValue = "managed-ocs"
rookConfigMapName = "rook-ceph-operator-config"
k8sMetricsServiceMonitorName = "k8s-metrics-service-monitor"
alertRelabelConfigSecretName = "managed-ocs-alert-relabel-config-secret"
alertRelabelConfigSecretKey = "alertrelabelconfig.yaml"
onboardingValidationKeySecretName = "onboarding-ticket-key"
convergedDeploymentType = "converged"
consumerDeploymentType = "consumer"
providerDeploymentType = "provider"
rhobsRemoteWriteConfigIdSecretKey = "prom-remote-write-config-id"
rhobsRemoteWriteConfigSecretName = "prom-remote-write-config-secret"
csiKMSConnectionDetailsConfigMapName = "csi-kms-connection-details"
desiredODFSubscriptionChannel = "stable-4.11"
odfOLMPackageName = "odf-operator"
)
// ManagedOCSReconciler reconciles a ManagedOCS object
type ManagedOCSReconciler struct {
Client client.Client
UnrestrictedClient client.Client
Log logr.Logger
Scheme *runtime.Scheme
AddonParamSecretName string
AddonConfigMapName string
AddonConfigMapDeleteLabelKey string
PagerdutySecretName string
DeadMansSnitchSecretName string
SMTPSecretName string
SOPEndpoint string
AlertSMTPFrom string
CustomerNotificationHTMLPath string
DeploymentType string
RHOBSSecretName string
RHOBSEndpoint string
RHSSOTokenEndpoint string
AvailableCRDs map[string]bool
ctx context.Context
managedOCS *v1.ManagedOCS
storageCluster *ocsv1.StorageCluster
egressNetworkPolicy *openshiftv1.EgressNetworkPolicy
egressFirewall *ovnv1.EgressFirewall
ingressNetworkPolicy *netv1.NetworkPolicy
cephIngressNetworkPolicy *netv1.NetworkPolicy
providerAPIServerNetworkPolicy *netv1.NetworkPolicy
prometheusProxyNetworkPolicy *netv1.NetworkPolicy
prometheus *promv1.Prometheus
prometheusService *corev1.Service
dmsRule *promv1.PrometheusRule
alertmanager *promv1.Alertmanager
pagerdutySecret *corev1.Secret
deadMansSnitchSecret *corev1.Secret
smtpSecret *corev1.Secret
alertmanagerConfig *promv1a1.AlertmanagerConfig
alertRelabelConfigSecret *corev1.Secret
k8sMetricsServiceMonitor *promv1.ServiceMonitor
namespace string
reconcileStrategy v1.ReconcileStrategy
addonParams map[string]string
onboardingValidationKeySecret *corev1.Secret
prometheusKubeRBACConfigMap *corev1.ConfigMap
rhobsRemoteWriteConfigSecret *corev1.Secret
csiKMSConnectionDetailsConfigMap *corev1.ConfigMap
}
// Add necessary rbac permissions for managedocs finalizer in order to set blockOwnerDeletion.
// +kubebuilder:rbac:groups=ocs.openshift.io,namespace=system,resources={managedocs,managedocs/finalizers},verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=ocs.openshift.io,namespace=system,resources=managedocs/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=ocs.openshift.io,namespace=system,resources=storageclusters,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=ocs.openshift.io,namespace=system,resources=ocsinitializations,verbs=get;list;watch;update;patch
// +kubebuilder:rbac:groups=ocs.openshift.io,namespace=system,resources=storageconsumers,verbs=get;list;watch
// +kubebuilder:rbac:groups="monitoring.coreos.com",namespace=system,resources={alertmanagers,prometheuses,alertmanagerconfigs},verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups="monitoring.coreos.com",namespace=system,resources=prometheusrules,verbs=get;list;watch;create;update;patch
// +kubebuilder:rbac:groups="monitoring.coreos.com",namespace=system,resources=podmonitors,verbs=get;list;watch;update;patch
// +kubebuilder:rbac:groups="monitoring.coreos.com",namespace=system,resources=servicemonitors,verbs=get;list;watch;update;patch;create;delete
// +kubebuilder:rbac:groups="",namespace=system,resources=secrets,verbs=create;get;list;watch;update
// +kubebuilder:rbac:groups=operators.coreos.com,namespace=system,resources=clusterserviceversions,verbs=get;list;watch;delete;update;patch
// +kubebuilder:rbac:groups="operators.coreos.com",resources=subscriptions,verbs=get;watch;list;update
// +kubebuilder:rbac:groups="apps",namespace=system,resources=statefulsets,verbs=get;list;watch
// +kubebuilder:rbac:groups="",resources={persistentvolumes,secrets},verbs=get;list;watch
// +kubebuilder:rbac:groups="",resources={services},verbs=get;list;watch;create;update
// +kubebuilder:rbac:groups="storage.k8s.io",resources=storageclass,verbs=get;list;watch
// +kubebuilder:rbac:groups="networking.k8s.io",namespace=system,resources=networkpolicies,verbs=create;get;list;watch;update
// +kubebuilder:rbac:groups="network.openshift.io",namespace=system,resources=egressnetworkpolicies,verbs=create;get;list;watch;update
// +kubebuilder:rbac:groups="k8s.ovn.org",namespace=system,resources=egressfirewalls,verbs=create;get;list;watch;update
// +kubebuilder:rbac:groups="coordination.k8s.io",namespace=system,resources=leases,verbs=create;get;list;watch;update
// +kubebuilder:rbac:groups="odf.openshift.io",namespace=system,resources=storagesystems,verbs=list;watch;delete
// +kubebuilder:rbac:groups="config.openshift.io",resources=clusterversions,verbs=get;watch;list
// +kubebuilder:rbac:groups="apiextensions.k8s.io",resources=customresourcedefinitions,verbs=get;watch;list
// SetupWithManager creates an setup a ManagedOCSReconciler to work with the provided manager
func (r *ManagedOCSReconciler) SetupWithManager(mgr ctrl.Manager, ctrlOptions *controller.Options) error {
if ctrlOptions == nil {
ctrlOptions = &controller.Options{
MaxConcurrentReconciles: 1,
}
}
managedOCSPredicates := builder.WithPredicates(
predicate.GenerationChangedPredicate{},
)
secretPredicates := builder.WithPredicates(
predicate.NewPredicateFuncs(
func(client client.Object) bool {
name := client.GetName()
return name == r.AddonParamSecretName ||
name == r.PagerdutySecretName ||
name == r.DeadMansSnitchSecretName ||
name == r.SMTPSecretName ||
name == r.RHOBSSecretName
},
),
)
configMapPredicates := builder.WithPredicates(
predicate.NewPredicateFuncs(
func(client client.Object) bool {
name := client.GetName()
if name == r.AddonConfigMapName {
if _, ok := client.GetLabels()[r.AddonConfigMapDeleteLabelKey]; ok {
return true
}
} else if name == rookConfigMapName {
return true
} else if name == utils.IMDSConfigMapName {
return true
} else if name == csiKMSConnectionDetailsConfigMapName {
return true
}
return false
},
),
)
monResourcesPredicates := builder.WithPredicates(
predicate.NewPredicateFuncs(
func(client client.Object) bool {
labels := client.GetLabels()
return labels == nil || labels[monLabelKey] != monLabelValue
},
),
)
monStatefulSetPredicates := builder.WithPredicates(
predicate.NewPredicateFuncs(
func(client client.Object) bool {
name := client.GetName()
return name == fmt.Sprintf("prometheus-%s", prometheusName) ||
name == fmt.Sprintf("alertmanager-%s", alertmanagerName)
},
),
)
prometheusRulesPredicates := builder.WithPredicates(
predicate.NewPredicateFuncs(
func(client client.Object) bool {
labels := client.GetLabels()
return labels == nil || labels[monLabelKey] != monLabelValue
},
),
)
csvPredicates := builder.WithPredicates(
predicate.NewPredicateFuncs(
func(client client.Object) bool {
return strings.HasPrefix(client.GetName(), ocsOperatorName)
},
),
)
enqueueManangedOCSRequest := handler.EnqueueRequestsFromMapFunc(
func(client client.Object) []reconcile.Request {
return []reconcile.Request{{
NamespacedName: types.NamespacedName{
Name: managedOCSName,
Namespace: client.GetNamespace(),
},
}}
},
)
subPredicate := builder.WithPredicates(
predicate.NewPredicateFuncs(
func(client client.Object) bool {
if instance, ok := client.(*opv1a1.Subscription); ok {
// ignore if not a odf-operator subscription
return instance.Spec.Package != odfOLMPackageName
}
return false
},
),
)
managedOCSController := ctrl.NewControllerManagedBy(mgr).
WithOptions(*ctrlOptions).
For(&v1.ManagedOCS{}, managedOCSPredicates).
// Watch owned resources
Owns(&ocsv1.StorageCluster{}).
Owns(&promv1.Prometheus{}).
Owns(&promv1.Alertmanager{}).
Owns(&promv1a1.AlertmanagerConfig{}).
Owns(&promv1.PrometheusRule{}).
Owns(&promv1.ServiceMonitor{}).
Owns(&netv1.NetworkPolicy{}).
Owns(&corev1.Secret{}).
Owns(&corev1.Service{}).
Owns(&corev1.ConfigMap{}).
// Watch non-owned resources
Watches(
&source.Kind{Type: &corev1.Secret{}},
enqueueManangedOCSRequest,
secretPredicates,
).
Watches(
&source.Kind{Type: &corev1.ConfigMap{}},
enqueueManangedOCSRequest,
configMapPredicates,
).
Watches(
&source.Kind{Type: &promv1.PodMonitor{}},
enqueueManangedOCSRequest,
monResourcesPredicates,
).
Watches(
&source.Kind{Type: &promv1.ServiceMonitor{}},
enqueueManangedOCSRequest,
monResourcesPredicates,
).
Watches(
&source.Kind{Type: &promv1.PrometheusRule{}},
enqueueManangedOCSRequest,
prometheusRulesPredicates,
).
Watches(
&source.Kind{Type: &appsv1.StatefulSet{}},
enqueueManangedOCSRequest,
monStatefulSetPredicates,
).
Watches(
&source.Kind{Type: &ocsv1.OCSInitialization{}},
enqueueManangedOCSRequest,
).
Watches(
&source.Kind{Type: &opv1a1.ClusterServiceVersion{}},
enqueueManangedOCSRequest,
csvPredicates,
).
Watches(
&source.Kind{Type: &opv1a1.Subscription{}},
enqueueManangedOCSRequest,
subPredicate,
)
if r.AvailableCRDs[EgressFirewallCRD] {
managedOCSController = managedOCSController.Owns(&ovnv1.EgressFirewall{})
}
if r.AvailableCRDs[EgressNetworkPolicyCRD] {
managedOCSController = managedOCSController.Owns(&openshiftv1.EgressNetworkPolicy{})
}
// Create the controller
return managedOCSController.Complete(r)
}
// Reconcile changes to all owned resource based on the infromation provided by the ManagedOCS resource
func (r *ManagedOCSReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
log := r.Log.WithValues("req.Namespace", req.Namespace, "req.Name", req.Name)
log.Info("Starting reconcile for ManagedOCS")
// Initalize the reconciler properties from the request
r.initReconciler(ctx, req)
// Load the managed ocs resource (input)
if err := r.get(r.managedOCS); err != nil {
if errors.IsNotFound(err) {
r.Log.V(-1).Info("ManagedOCS resource not found")
} else {
return ctrl.Result{}, err
}
}
// Run the reconcile phases
result, err := r.reconcilePhases()
if err != nil {
r.Log.Error(err, "An error was encountered during reconcilePhases")
}
// Ensure status is updated once even on failed reconciles
var statusErr error
if r.managedOCS.UID != "" {
statusErr = r.Client.Status().Update(r.ctx, r.managedOCS)
}
// Reconcile errors have priority to status update errors
if err != nil {
return ctrl.Result{}, err
} else if statusErr != nil {
return ctrl.Result{}, statusErr
} else {
return result, nil
}
}
func (r *ManagedOCSReconciler) initReconciler(ctx context.Context, req ctrl.Request) {
r.ctx = ctx
r.namespace = req.NamespacedName.Namespace
r.addonParams = make(map[string]string)
r.DeploymentType = strings.ToLower(r.DeploymentType)
r.managedOCS = &v1.ManagedOCS{}
r.managedOCS.Name = req.NamespacedName.Name
r.managedOCS.Namespace = r.namespace
r.storageCluster = &ocsv1.StorageCluster{}
r.storageCluster.Name = storageClusterName
r.storageCluster.Namespace = r.namespace
r.egressNetworkPolicy = &openshiftv1.EgressNetworkPolicy{}
r.egressNetworkPolicy.Name = egressNetworkPolicyName
r.egressNetworkPolicy.Namespace = r.namespace
r.egressFirewall = &ovnv1.EgressFirewall{}
r.egressFirewall.Name = egressFirewallName
r.egressFirewall.Namespace = r.namespace
r.ingressNetworkPolicy = &netv1.NetworkPolicy{}
r.ingressNetworkPolicy.Name = ingressNetworkPolicyName
r.ingressNetworkPolicy.Namespace = r.namespace
r.cephIngressNetworkPolicy = &netv1.NetworkPolicy{}
r.cephIngressNetworkPolicy.Name = cephIngressNetworkPolicyName
r.cephIngressNetworkPolicy.Namespace = r.namespace
r.providerAPIServerNetworkPolicy = &netv1.NetworkPolicy{}
r.providerAPIServerNetworkPolicy.Name = providerApiServerNetworkPolicyName
r.providerAPIServerNetworkPolicy.Namespace = r.namespace
r.prometheusProxyNetworkPolicy = &netv1.NetworkPolicy{}
r.prometheusProxyNetworkPolicy.Name = prometheusProxyNetworkPolicyName
r.prometheusProxyNetworkPolicy.Namespace = r.namespace
r.prometheus = &promv1.Prometheus{}
r.prometheus.Name = prometheusName
r.prometheus.Namespace = r.namespace
r.prometheusService = &corev1.Service{}
r.prometheusService.Name = prometheusServiceName
r.prometheusService.Namespace = r.namespace
r.dmsRule = &promv1.PrometheusRule{}
r.dmsRule.Name = dmsRuleName
r.dmsRule.Namespace = r.namespace
r.alertmanager = &promv1.Alertmanager{}
r.alertmanager.Name = alertmanagerName
r.alertmanager.Namespace = r.namespace
r.pagerdutySecret = &corev1.Secret{}
r.pagerdutySecret.Name = r.PagerdutySecretName
r.pagerdutySecret.Namespace = r.namespace
r.smtpSecret = &corev1.Secret{}
r.smtpSecret.Name = r.SMTPSecretName
r.smtpSecret.Namespace = r.namespace
r.deadMansSnitchSecret = &corev1.Secret{}
r.deadMansSnitchSecret.Name = r.DeadMansSnitchSecretName
r.deadMansSnitchSecret.Namespace = r.namespace
r.alertmanagerConfig = &promv1a1.AlertmanagerConfig{}
r.alertmanagerConfig.Name = alertmanagerConfigName
r.alertmanagerConfig.Namespace = r.namespace
r.k8sMetricsServiceMonitor = &promv1.ServiceMonitor{}
r.k8sMetricsServiceMonitor.Name = k8sMetricsServiceMonitorName
r.k8sMetricsServiceMonitor.Namespace = r.namespace
r.alertRelabelConfigSecret = &corev1.Secret{}
r.alertRelabelConfigSecret.Name = alertRelabelConfigSecretName
r.alertRelabelConfigSecret.Namespace = r.namespace
r.onboardingValidationKeySecret = &corev1.Secret{}
r.onboardingValidationKeySecret.Name = onboardingValidationKeySecretName
r.onboardingValidationKeySecret.Namespace = r.namespace
r.prometheusKubeRBACConfigMap = &corev1.ConfigMap{}
r.prometheusKubeRBACConfigMap.Name = templates.PrometheusKubeRBACPoxyConfigMapName
r.prometheusKubeRBACConfigMap.Namespace = r.namespace
r.rhobsRemoteWriteConfigSecret = &corev1.Secret{}
r.rhobsRemoteWriteConfigSecret.Name = r.RHOBSSecretName
r.rhobsRemoteWriteConfigSecret.Namespace = r.namespace
r.csiKMSConnectionDetailsConfigMap = &corev1.ConfigMap{}
r.csiKMSConnectionDetailsConfigMap.Name = csiKMSConnectionDetailsConfigMapName
r.csiKMSConnectionDetailsConfigMap.Namespace = r.namespace
}
func (r *ManagedOCSReconciler) reconcilePhases() (reconcile.Result, error) {
// Uninstallation depends on the status of the components.
// We are checking the uninstallation condition before getting the component status
// to mitigate scenarios where changes to the component status occurs while the uninstallation logic is running.
initiateUninstall := r.checkUninstallCondition()
// Update the status of the components
r.updateComponentStatus()
if !r.managedOCS.DeletionTimestamp.IsZero() {
if r.verifyComponentsDoNotExist() {
// Deleting OCS CSV from the namespace
r.Log.Info("deleting OCS CSV")
if err := r.deleteCSVByPrefix(ocsOperatorName); err != nil {
return ctrl.Result{}, fmt.Errorf("unable to delete csv: %v", err)
}
r.Log.Info("removing finalizer from the ManagedOCS resource")
r.managedOCS.SetFinalizers(utils.Remove(r.managedOCS.GetFinalizers(), ManagedOCSFinalizer))
if err := r.Client.Update(r.ctx, r.managedOCS); err != nil {
return ctrl.Result{}, fmt.Errorf("failed to remove finalizer from managedOCS: %v", err)
}
r.Log.Info("finallizer removed successfully")
} else {
// Storage cluster needs to be deleted before we delete the CSV so we can not leave it to the
// k8s garbage collector to delete it
r.Log.Info("deleting storagecluster")
if err := r.delete(r.storageCluster); err != nil {
return ctrl.Result{}, fmt.Errorf("unable to delete storagecluster: %v", err)
}
// Deleting all storage systems from the namespace
r.Log.Info("deleting storageSystems")
storageSystemList := odfv1a1.StorageSystemList{}
if err := r.list(&storageSystemList); err != nil {
return ctrl.Result{}, fmt.Errorf("unable to list storageSystem resource: %v", err)
}
for i := range storageSystemList.Items {
storageSystem := storageSystemList.Items[i]
if err := r.delete(&storageSystem); err != nil {
return ctrl.Result{}, fmt.Errorf("unable to delete storageSystem: %v", err)
}
}
}
} else if r.managedOCS.UID != "" {
if !utils.Contains(r.managedOCS.GetFinalizers(), ManagedOCSFinalizer) {
r.Log.V(-1).Info("finalizer missing on the managedOCS resource, adding...")
r.managedOCS.SetFinalizers(append(r.managedOCS.GetFinalizers(), ManagedOCSFinalizer))
if err := r.update(r.managedOCS); err != nil {
return ctrl.Result{}, fmt.Errorf("failed to update managedOCS with finalizer: %v", err)
}
}
// Find the effective reconcile strategy
r.reconcileStrategy = v1.ReconcileStrategyStrict
if strings.EqualFold(string(r.managedOCS.Spec.ReconcileStrategy), string(v1.ReconcileStrategyNone)) {
r.reconcileStrategy = v1.ReconcileStrategyNone
}
// Read the add-on parameters secret and store it an addonParams map
addonParamSecret := &corev1.Secret{}
addonParamSecret.Name = r.AddonParamSecretName
addonParamSecret.Namespace = r.namespace
if err := r.get(addonParamSecret); err != nil {
return ctrl.Result{}, fmt.Errorf("Failed to get the addon parameters secret %v", r.AddonParamSecretName)
}
for key, value := range addonParamSecret.Data {
r.addonParams[key] = string(value)
}
// Deprecating consumer requested capacity addon parameter by overriding it with a very high pre-defined value
if r.DeploymentType == consumerDeploymentType {
r.Log.Info(fmt.Sprintf("Overriding addon parameter '%s' (currently '%s') with 1024", storageSizeKey, r.addonParams[storageSizeKey]))
r.addonParams[storageSizeKey] = "1024"
r.Log.Info(fmt.Sprintf("Overriding addon parameter '%s' (currently '%s') with Ti", storageUnitKey, r.addonParams[storageUnitKey]))
r.addonParams[storageUnitKey] = "Ti"
}
// Reconcile the different resources
if err := r.reconcileODFSubscription(); err != nil {
return ctrl.Result{}, err
}
if err := r.reconcileRookCephOperatorConfig(); err != nil {
return ctrl.Result{}, err
}
// Reconciles only for provider deployment type
if err := r.reconcileOnboardingValidationSecret(); err != nil {
return ctrl.Result{}, err
}
if err := r.reconcileStorageCluster(); err != nil {
return ctrl.Result{}, err
}
if err := r.reconcileCSV(); err != nil {
return ctrl.Result{}, err
}
if err := r.reconcileCSIKMSConnectionDetailsConfigMap(); err != nil {
return ctrl.Result{}, err
}
if err := r.reconcileAlertRelabelConfigSecret(); err != nil {
return ctrl.Result{}, err
}
if err := r.reconcilePrometheusKubeRBACConfigMap(); err != nil {
return ctrl.Result{}, err
}
if err := r.reconcilePrometheusService(); err != nil {
return ctrl.Result{}, err
}
if err := r.reconcilePrometheus(); err != nil {
return ctrl.Result{}, err
}
if err := r.reconcileAlertmanager(); err != nil {
return ctrl.Result{}, err
}
if err := r.reconcileAlertmanagerConfig(); err != nil {
return ctrl.Result{}, err
}
if err := r.reconcileK8SMetricsServiceMonitor(); err != nil {
return ctrl.Result{}, err
}
if err := r.reconcileMonitoringResources(); err != nil {
return ctrl.Result{}, err
}
if err := r.reconcileDMSPrometheusRule(); err != nil {
return ctrl.Result{}, err
}
if err := r.reconcileOCSInitialization(); err != nil {
return ctrl.Result{}, err
}
if err := r.reconcilePrometheusProxyNetworkPolicy(); err != nil {
return ctrl.Result{}, err
}
if err := r.reconcileEgressFirewall(); err != nil {
return ctrl.Result{}, err
}
if err := r.reconcileEgressNetworkPolicy(); err != nil {
return ctrl.Result{}, err
}
if err := r.reconcileIngressNetworkPolicy(); err != nil {
return ctrl.Result{}, err
}
if err := r.reconcileCephIngressNetworkPolicy(); err != nil {
return ctrl.Result{}, err
}
if err := r.reconcileProviderAPIServerNetworkPolicy(); err != nil {
return ctrl.Result{}, err
}
r.managedOCS.Status.ReconcileStrategy = r.reconcileStrategy
// Check if we need and can uninstall
if initiateUninstall && r.areComponentsReadyForUninstall() {
switch r.DeploymentType {
case convergedDeploymentType, consumerDeploymentType:
found, err := r.hasOCSVolumes()
if err != nil {
return ctrl.Result{}, err
}
if found {
r.Log.Info("Found consumer PVs using OCS storageclasses, cannot proceed with uninstallation")
return ctrl.Result{Requeue: true, RequeueAfter: 10 * time.Second}, nil
}
case providerDeploymentType:
found, err := r.hasOCSStorageConsumers()
if err != nil {
return ctrl.Result{}, err
}
if found {
r.Log.Info("Found OCS storage consumers, cannot proceed with uninstallation")
return ctrl.Result{Requeue: true, RequeueAfter: 10 * time.Second}, nil
}
}
r.Log.Info("starting OCS uninstallation - deleting managedocs")
if err := r.delete(r.managedOCS); err != nil {
return ctrl.Result{}, fmt.Errorf("unable to delete managedocs: %v", err)
}
// Refreshing local managedOCS object after deletion is scheduled
// to avoid conflict while updating status
if err := r.get(r.managedOCS); err != nil {
if !errors.IsNotFound(err) {
return ctrl.Result{}, err
}
r.Log.V(-1).Info("Trying to reload ManagedOCS resource after delete failed, ManagedOCS resource not found")
}
}
} else if initiateUninstall {
return ctrl.Result{}, r.removeOLMComponents()
}
return ctrl.Result{}, nil
}
func (r *ManagedOCSReconciler) updateComponentStatus() {
// Getting the status of the StorageCluster component.
scStatus := &r.managedOCS.Status.Components.StorageCluster
if err := r.get(r.storageCluster); err == nil {
if r.storageCluster.Status.Phase == "Ready" {
scStatus.State = v1.ComponentReady
} else {
scStatus.State = v1.ComponentPending
}
} else if errors.IsNotFound(err) {
scStatus.State = v1.ComponentNotFound
} else {
r.Log.V(-1).Info("error getting StorageCluster, setting compoment status to Unknown")
scStatus.State = v1.ComponentUnknown
}
// Getting the status of the Prometheus component.
promStatus := &r.managedOCS.Status.Components.Prometheus
if err := r.get(r.prometheus); err == nil {
promStatefulSet := &appsv1.StatefulSet{}
promStatefulSet.Namespace = r.namespace
promStatefulSet.Name = fmt.Sprintf("prometheus-%s", prometheusName)
if err := r.get(promStatefulSet); err == nil {
desiredReplicas := int32(1)
if r.prometheus.Spec.Replicas != nil {
desiredReplicas = *r.prometheus.Spec.Replicas
}
if promStatefulSet.Status.ReadyReplicas != desiredReplicas {
promStatus.State = v1.ComponentPending
} else {
promStatus.State = v1.ComponentReady
}
} else {
promStatus.State = v1.ComponentPending
}
} else if errors.IsNotFound(err) {
promStatus.State = v1.ComponentNotFound
} else {
r.Log.V(-1).Info("error getting Prometheus, setting compoment status to Unknown")
promStatus.State = v1.ComponentUnknown
}
// Getting the status of the Alertmanager component.
amStatus := &r.managedOCS.Status.Components.Alertmanager
if err := r.get(r.alertmanager); err == nil {
amStatefulSet := &appsv1.StatefulSet{}
amStatefulSet.Namespace = r.namespace
amStatefulSet.Name = fmt.Sprintf("alertmanager-%s", alertmanagerName)
if err := r.get(amStatefulSet); err == nil {
desiredReplicas := int32(1)
if r.alertmanager.Spec.Replicas != nil {
desiredReplicas = *r.alertmanager.Spec.Replicas
}
if amStatefulSet.Status.ReadyReplicas != desiredReplicas {
amStatus.State = v1.ComponentPending
} else {
amStatus.State = v1.ComponentReady
}
} else {
amStatus.State = v1.ComponentPending
}
} else if errors.IsNotFound(err) {
amStatus.State = v1.ComponentNotFound
} else {
r.Log.V(-1).Info("error getting Alertmanager, setting compoment status to Unknown")
amStatus.State = v1.ComponentUnknown
}
}
func (r *ManagedOCSReconciler) verifyComponentsDoNotExist() bool {
subComponent := r.managedOCS.Status.Components
return subComponent.StorageCluster.State == v1.ComponentNotFound
}
func (r *ManagedOCSReconciler) reconcileStorageCluster() error {
r.Log.Info("Reconciling StorageCluster")
_, err := ctrl.CreateOrUpdate(r.ctx, r.Client, r.storageCluster, func() error {
if err := r.own(r.storageCluster); err != nil {
return err
}
// Handle only strict mode reconciliation
if r.reconcileStrategy == v1.ReconcileStrategyStrict {
var desired *ocsv1.StorageCluster = nil
switch r.DeploymentType {
case convergedDeploymentType:
var err error
if desired, err = r.getDesiredConvergedStorageCluster(); err != nil {
return err
}
case consumerDeploymentType:
var err error
if desired, err = r.getDesiredConsumerStorageCluster(); err != nil {
return err
}
case providerDeploymentType:
var err error
if desired, err = r.getDesiredProviderStorageCluster(); err != nil {
return err
}
default:
return fmt.Errorf("Invalid deployment type value: %v", r.DeploymentType)
}
// Override storage cluster spec with desired spec from the template.
// We do not replace meta or status on purpose
r.storageCluster.Spec = desired.Spec
}
return nil
})
if err != nil {
return err
}
return nil
}
func (r *ManagedOCSReconciler) getDesiredConvergedStorageCluster() (*ocsv1.StorageCluster, error) {
sizeAsString := r.addonParams[storageSizeKey]
// Setting hardcoded value here to force no MCG deployment
enableMCGAsString := "false"
if enableMCGRaw, exists := r.addonParams[enableMCGKey]; exists {
enableMCGAsString = enableMCGRaw
}
r.Log.Info("Requested add-on settings", storageSizeKey, sizeAsString, enableMCGKey, enableMCGAsString)
desiredDeviceSetCount, err := strconv.Atoi(sizeAsString)
if err != nil {
return nil, fmt.Errorf("Invalid storage cluster size value: %v", sizeAsString)
}
// Get the storage device set count of the current storage cluster
currDeviceSetCount := 0
if desiredStorageDeviceSet := findStorageDeviceSet(r.storageCluster.Spec.StorageDeviceSets, deviceSetName); desiredStorageDeviceSet != nil {
currDeviceSetCount = desiredStorageDeviceSet.Count
}
// Get the desired storage device set from storage cluster template
sc := templates.ConvergedStorageClusterTemplate.DeepCopy()
var ds *ocsv1.StorageDeviceSet = nil
if desiredStorageDeviceSet := findStorageDeviceSet(sc.Spec.StorageDeviceSets, deviceSetName); desiredStorageDeviceSet != nil {
ds = desiredStorageDeviceSet
}
// Prevent downscaling by comparing count from secret and count from storage cluster
r.setDeviceSetCount(ds, desiredDeviceSetCount, currDeviceSetCount)
// Check and enable MCG in Storage Cluster spec
mcgEnable, err := strconv.ParseBool(enableMCGAsString)
if err != nil {
return nil, fmt.Errorf("Invalid Enable MCG value: %v", enableMCGAsString)
}
if err := r.ensureMCGDeployment(sc, mcgEnable); err != nil {
return nil, err
}
return sc, nil
}
func (r *ManagedOCSReconciler) getDesiredProviderStorageCluster() (*ocsv1.StorageCluster, error) {
sizeAsString := r.addonParams[storageSizeKey]
// Setting hardcoded value here to force no MCG deployment
enableMCGAsString := "false"
if enableMCGRaw, exists := r.addonParams[enableMCGKey]; exists {
enableMCGAsString = enableMCGRaw
}
r.Log.Info("Requested add-on settings", storageSizeKey, sizeAsString, enableMCGKey, enableMCGAsString)
desiredSize, err := strconv.Atoi(sizeAsString)
if err != nil {
return nil, fmt.Errorf("Invalid storage cluster size value: %v", sizeAsString)
}
// Convert the desired size to the device set count based on the underlaying OSD size
desiredDeviceSetCount := int(math.Ceil(float64(desiredSize) / templates.ProviderOSDSizeInTiB))
// Get the storage device set count of the current storage cluster
currDeviceSetCount := 0
if desiredStorageDeviceSet := findStorageDeviceSet(r.storageCluster.Spec.StorageDeviceSets, deviceSetName); desiredStorageDeviceSet != nil {
currDeviceSetCount = desiredStorageDeviceSet.Count
}
// Get the desired storage device set from storage cluster template
sc := templates.ProviderStorageClusterTemplate.DeepCopy()
var ds *ocsv1.StorageDeviceSet = nil
if desiredStorageDeviceSet := findStorageDeviceSet(sc.Spec.StorageDeviceSets, deviceSetName); desiredStorageDeviceSet != nil {
ds = desiredStorageDeviceSet
}
// Prevent downscaling by comparing count from secret and count from storage cluster
r.setDeviceSetCount(ds, desiredDeviceSetCount, currDeviceSetCount)
// Check and enable MCG in Storage Cluster spec
mcgEnable, err := strconv.ParseBool(enableMCGAsString)
if err != nil {
return nil, fmt.Errorf("Invalid Enable MCG value: %v", enableMCGAsString)
}
if err := r.ensureMCGDeployment(sc, mcgEnable); err != nil {
return nil, err
}
return sc, nil
}
func (r *ManagedOCSReconciler) getDesiredConsumerStorageCluster() (*ocsv1.StorageCluster, error) {
storageSize := r.addonParams[storageSizeKey]
storageUnit := r.addonParams[storageUnitKey]
onboardingTicket := r.addonParams[onboardingTicketKey]
storageProviderEndpoint := r.addonParams[storageProviderEndpointKey]
// Setting hardcoded value here to force no MCG deployment
enableMCGAsString := "false"
if enableMCGRaw, exists := r.addonParams[enableMCGKey]; exists {
enableMCGAsString = enableMCGRaw
}
r.Log.Info("Requested add-on settings", storageSizeKey, storageSize, storageUnitKey, storageUnit, enableMCGKey, enableMCGAsString,
onboardingTicketKey, onboardingTicket, storageProviderEndpointKey, storageProviderEndpoint)
sizeAsString := storageSize + storageUnit
requestedCapacity, err := resource.ParseQuantity(sizeAsString)
// Check if the requested capacity is valid
if err != nil || requestedCapacity.Sign() == -1 {
return nil, fmt.Errorf("Invalid storage cluster capacity value: %v", sizeAsString)
}
sc := templates.ConsumerStorageClusterTemplate.DeepCopy()
externalStorageSpec := &sc.Spec.ExternalStorage
externalStorageSpec.OnboardingTicket = onboardingTicket
externalStorageSpec.StorageProviderEndpoint = storageProviderEndpoint
externalStorageSpec.RequestedCapacity = &requestedCapacity
// Check and enable MCG in Storage Cluster spec
mcgEnable, err := strconv.ParseBool(enableMCGAsString)
if err != nil {
return nil, fmt.Errorf("Invalid Enable MCG value: %v", enableMCGAsString)
}
if err := r.ensureMCGDeployment(sc, mcgEnable); err != nil {
return nil, err
}
return sc, nil
}
func (r *ManagedOCSReconciler) reconcileOnboardingValidationSecret() error {
if r.DeploymentType != providerDeploymentType {
r.Log.Info("Non provider deployment, skipping reconcile for onboarding validation secret")
return nil
}
r.Log.Info("Reconciling onboardingValidationKeySecret")
_, err := ctrl.CreateOrUpdate(r.ctx, r.Client, r.onboardingValidationKeySecret, func() error {
if err := r.own(r.onboardingValidationKeySecret); err != nil {
return err
}
onboardingValidationData := fmt.Sprintf(
"-----BEGIN PUBLIC KEY-----\n%s\n-----END PUBLIC KEY-----",
strings.TrimSpace(r.addonParams[onboardingValidationKey]),
)
r.onboardingValidationKeySecret.Data = map[string][]byte{
"key": []byte(onboardingValidationData),
}
return nil
})
if err != nil {
return fmt.Errorf("Failed to update onboardingValidationKeySecret: %v", err)
}
return nil
}
func (r *ManagedOCSReconciler) reconcileCSIKMSConnectionDetailsConfigMap() error {
if r.DeploymentType != consumerDeploymentType {
r.Log.Info(fmt.Sprintf("Non consumer deployment, skipping reconcile for %s config map", csiKMSConnectionDetailsConfigMapName))
return nil
}
r.Log.Info(fmt.Sprintf("Reconciling %s configMap", csiKMSConnectionDetailsConfigMapName))
_, err := ctrl.CreateOrUpdate(r.ctx, r.Client, r.csiKMSConnectionDetailsConfigMap, func() error {
if err := r.own(r.csiKMSConnectionDetailsConfigMap); err != nil {
return err
}
awsStsMetadataTestAsString := string(
utils.ToJsonOrDie(
map[string]string{
"encryptionKMSType": "aws-sts-metadata",
"secretName": "ceph-csi-aws-credentials",
},
),
)
r.csiKMSConnectionDetailsConfigMap.Data = map[string]string{
"aws-sts-metadata-test": awsStsMetadataTestAsString,
}
return nil
})
if err != nil {
return fmt.Errorf("Failed to create or update %s config map: %v", csiKMSConnectionDetailsConfigMapName, err)
}
return nil
}
// AlertRelabelConfigSecret will have configuration for relabeling the alerts that are firing.
// It will add namespace label to firing alerts before they are sent to the alertmanager
func (r *ManagedOCSReconciler) reconcileAlertRelabelConfigSecret() error {
r.Log.Info("Reconciling alertRelabelConfigSecret")
_, err := ctrl.CreateOrUpdate(r.ctx, r.Client, r.alertRelabelConfigSecret, func() error {
if err := r.own(r.alertRelabelConfigSecret); err != nil {
return err
}
alertRelabelConfig := []struct {