-
Notifications
You must be signed in to change notification settings - Fork 101
/
phase4_configuring.go
1848 lines (1646 loc) · 60.9 KB
/
phase4_configuring.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package system
import (
"context"
"errors"
"fmt"
"net"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
"encoding/json"
"cloud.google.com/go/storage"
"github.com/marstr/randname"
nbv1 "github.com/noobaa/noobaa-operator/v5/pkg/apis/noobaa/v1alpha1"
"github.com/noobaa/noobaa-operator/v5/pkg/bundle"
"github.com/noobaa/noobaa-operator/v5/pkg/nb"
"github.com/noobaa/noobaa-operator/v5/pkg/options"
"github.com/noobaa/noobaa-operator/v5/pkg/util"
secv1 "github.com/openshift/api/security/v1"
monitoringv1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1"
"github.com/sirupsen/logrus"
"google.golang.org/api/option"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes/scheme"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/service/sts"
)
const (
ibmEndpoint = "https://s3.direct.%s.cloud-object-storage.appdomain.cloud"
ibmLocation = "%s-standard"
ibmCosBucketCred = "ibm-cloud-cos-creds"
minutesToWaitForDefaultBSCreation = 10
credentialsKey = "credentials"
)
type gcpAuthJSON struct {
ProjectID string `json:"project_id"`
}
// ReconcilePhaseConfiguring runs the reconcile phase
func (r *Reconciler) ReconcilePhaseConfiguring() error {
r.SetPhase(
nbv1.SystemPhaseConfiguring,
"SystemPhaseConfiguring",
"noobaa operator started phase 4/4 - \"Configuring\"",
)
if err := r.ReconcileSystemSecrets(); err != nil {
return err
}
// No endpoint creation is required for remote noobaa client
if !util.IsRemoteClientNoobaa(r.NooBaa.GetAnnotations()) {
util.KubeCreateOptional(util.KubeObject(bundle.File_deploy_scc_endpoint_yaml).(*secv1.SecurityContextConstraints))
if err := r.ReconcileObject(r.DeploymentEndpoint, r.SetDesiredDeploymentEndpoint); err != nil {
return err
}
if err := r.ReconcileHPAEndpoint(); err != nil {
return err
}
}
if err := r.RegisterToCluster(); err != nil {
return err
}
if err := r.ReconcileDefaultBackingStore(); err != nil {
return err
}
if err := r.ReconcileDefaultNsfsPvc(); err != nil {
return err
}
if err := r.ReconcileDefaultNamespaceStore(); err != nil {
return err
}
if err := r.ReconcileDefaultBucketClass(); err != nil {
return err
}
if err := r.ReconcileOBCStorageClass(); err != nil {
return err
}
if err := r.ReconcilePrometheusRule(); err != nil {
return err
}
if err := r.ReconcileServiceMonitors(); err != nil {
return err
}
if err := r.ReconcileReadSystem(); err != nil {
return err
}
if err := r.ReconcileDeploymentEndpointStatus(); err != nil {
return err
}
return nil
}
// ReconcileSystemSecrets reconciles secrets used by the system and
// create the system if does not exists
func (r *Reconciler) ReconcileSystemSecrets() error {
if r.JoinSecret == nil {
if err := r.ReconcileObject(r.SecretAdmin, r.SetDesiredSecretAdmin); err != nil {
return err
}
// Point the admin account secret reference to the admin secret.
r.NooBaa.Status.Accounts.Admin.SecretRef.Name = r.SecretAdmin.Name
r.NooBaa.Status.Accounts.Admin.SecretRef.Namespace = r.SecretAdmin.Namespace
}
if err := r.ReconcileObject(r.SecretOp, r.SetDesiredSecretOp); err != nil {
return err
}
r.NBClient.SetAuthToken(r.SecretOp.StringData["auth_token"])
if r.JoinSecret == nil {
if err := r.ReconcileObject(r.SecretAdmin, r.SetDesiredSecretAdminAccountInfo); err != nil {
return err
}
}
if err := r.ReconcileObject(r.SecretEndpoints, r.SetDesiredSecretEndpoints); err != nil {
return err
}
return nil
}
// SetDesiredSecretAdmin set auth related info in admin secret
func (r *Reconciler) SetDesiredSecretAdmin() error {
// Load string data from data
util.SecretResetStringDataFromData(r.SecretAdmin)
r.SecretAdmin.StringData["system"] = r.NooBaa.Name
r.SecretAdmin.StringData["email"] = options.AdminAccountEmail
if r.SecretAdmin.StringData["password"] == "" {
r.SecretAdmin.StringData["password"] = util.RandomBase64(16)
}
return nil
}
// SetDesiredSecretOp set auth token in operator secret
func (r *Reconciler) SetDesiredSecretOp() error {
// Load string data from data
util.SecretResetStringDataFromData(r.SecretOp)
// SecretOp exists means the system already created and we can skip
if r.SecretOp.StringData["auth_token"] != "" {
return nil
}
// Local noobaa case
if r.JoinSecret == nil {
res1, err := r.NBClient.ReadSystemStatusAPI()
if err != nil {
return fmt.Errorf("Could not read the system status, error: %v", err)
}
if res1.State == "DOES_NOT_EXIST" {
res2, err := r.NBClient.CreateSystemAPI(nb.CreateSystemParams{
Name: r.Request.Name,
Email: r.SecretAdmin.StringData["email"],
Password: nb.MaskedString(r.SecretAdmin.StringData["password"]),
})
if err != nil {
return fmt.Errorf("system creation failed, error: %v", err)
}
r.SecretOp.StringData["auth_token"] = res2.OperatorToken
} else if res1.State == "COULD_NOT_INITIALIZE" {
// TODO: Try to recover from this situation, maybe delete the system.
return util.NewPersistentError("SystemCouldNotInitialize",
"Something went wrong during system initialization")
} else if res1.State == "READY" {
// Trying to create token for admin so we could use it to create
// a token for the operator account
res3, err := r.NBClient.CreateAuthAPI(nb.CreateAuthParams{
System: r.Request.Name,
Role: "admin",
Email: r.SecretAdmin.StringData["email"],
Password: r.SecretAdmin.StringData["password"],
})
if err != nil {
return fmt.Errorf("cannot create an auth token for admin, error: %v", err)
}
r.NBClient.SetAuthToken(res3.Token)
res4, err := r.NBClient.CreateAuthAPI(nb.CreateAuthParams{
System: r.Request.Name,
Role: "operator",
Email: options.OperatorAccountEmail,
})
if err != nil {
return fmt.Errorf("cannot create an auth token for operator, error: %v", err)
}
r.SecretOp.StringData["auth_token"] = res4.Token
}
// Remote noobaa case
} else {
// Set the operator secret from the join secret
r.SecretOp.StringData["auth_token"] = r.JoinSecret.StringData["auth_token"]
}
return nil
}
// SetDesiredSecretAdminAccountInfo set account related info in admin secret
func (r *Reconciler) SetDesiredSecretAdminAccountInfo() error {
util.SecretResetStringDataFromData(r.SecretAdmin)
account, err := r.NBClient.ReadAccountAPI(nb.ReadAccountParams{
Email: r.SecretAdmin.StringData["email"],
})
if err != nil {
return fmt.Errorf("cannot read admin account info, error: %v", err)
}
if account.AccessKeys == nil || len(account.AccessKeys) <= 0 {
return fmt.Errorf("admin account has no access keys yet")
}
r.SecretAdmin.StringData["AWS_ACCESS_KEY_ID"] = string(account.AccessKeys[0].AccessKey)
r.SecretAdmin.StringData["AWS_SECRET_ACCESS_KEY"] = string(account.AccessKeys[0].SecretKey)
return nil
}
// SetDesiredSecretEndpoints set auth related info in endpoints secret
func (r *Reconciler) SetDesiredSecretEndpoints() error {
if r.SecretEndpoints.UID != "" {
return nil
}
// Load string data from data
util.SecretResetStringDataFromData(r.SecretEndpoints)
res, err := r.NBClient.CreateAuthAPI(nb.CreateAuthParams{
System: r.Request.Name,
Role: "admin",
Email: options.AdminAccountEmail,
})
if err != nil {
return fmt.Errorf("cannot create auth token for use by endpoints, error: %v", err)
}
r.SecretEndpoints.StringData["auth_token"] = res.Token
return nil
}
// SetDesiredDeploymentEndpoint updates the endpoint deployment as desired for reconciling
func (r *Reconciler) SetDesiredDeploymentEndpoint() error {
r.DeploymentEndpoint.Spec.Selector.MatchLabels["noobaa-s3"] = r.Request.Name
r.DeploymentEndpoint.Spec.Template.Labels["noobaa-s3"] = r.Request.Name
r.DeploymentEndpoint.Spec.Template.Labels["app"] = r.Request.Name
endpointsSpec := r.NooBaa.Spec.Endpoints
podSpec := &r.DeploymentEndpoint.Spec.Template.Spec
podSpec.Tolerations = r.NooBaa.Spec.Tolerations
podSpec.Affinity = r.NooBaa.Spec.Affinity
if r.NooBaa.Spec.ImagePullSecret == nil {
podSpec.ImagePullSecrets =
[]corev1.LocalObjectReference{}
} else {
podSpec.ImagePullSecrets =
[]corev1.LocalObjectReference{*r.NooBaa.Spec.ImagePullSecret}
}
rootUIDGid := int64(0)
podSpec.SecurityContext.RunAsUser = &rootUIDGid
podSpec.SecurityContext.RunAsGroup = &rootUIDGid
podSpec.ServiceAccountName = "noobaa-endpoint"
honor := corev1.NodeInclusionPolicyHonor
disableDefaultTopologyConstraints, found := r.NooBaa.ObjectMeta.Annotations[nbv1.SkipTopologyConstraints]
if podSpec.TopologySpreadConstraints != nil {
r.Logger.Debugf("deployment %s TopologySpreadConstraints already exists, leaving as is", r.DeploymentEndpoint.Name)
} else if !util.HasNodeInclusionPolicyInPodTopologySpread() {
r.Logger.Debugf("deployment %s TopologySpreadConstraints cannot be set because feature gate NodeInclusionPolicyInPodTopologySpread is not supported on this cluster version",
r.DeploymentEndpoint.Name)
} else if found && disableDefaultTopologyConstraints == "true" {
r.Logger.Debugf("deployment %s TopologySpreadConstraints will not be set because annotation %s was set on noobaa CR",
r.DeploymentEndpoint.Name, nbv1.SkipTopologyConstraints)
} else {
r.Logger.Debugf("default TopologySpreadConstraints is added to %s deployment", r.DeploymentEndpoint.Name)
topologySpreadConstraint := corev1.TopologySpreadConstraint{
MaxSkew: 1,
TopologyKey: "kubernetes.io/hostname",
WhenUnsatisfiable: corev1.ScheduleAnyway,
NodeTaintsPolicy: &honor,
LabelSelector: &metav1.LabelSelector{
MatchLabels: map[string]string{
"noobaa-s3": r.Request.Name,
},
},
}
podSpec.TopologySpreadConstraints = []corev1.TopologySpreadConstraint{topologySpreadConstraint}
}
for i := range podSpec.Containers {
c := &podSpec.Containers[i]
switch c.Name {
case "endpoint":
c.Image = r.NooBaa.Status.ActualImage
if endpointsSpec != nil && endpointsSpec.Resources != nil {
c.Resources = *endpointsSpec.Resources
}
mgmtBaseAddr := ""
s3BaseAddr := ""
syslogBaseAddr := ""
util.MergeEnvArrays(&c.Env, &r.DefaultDeploymentEndpoint.Containers[0].Env)
if r.JoinSecret == nil {
mgmtBaseAddr = fmt.Sprintf(`wss://%s.%s.svc`, r.ServiceMgmt.Name, r.Request.Namespace)
s3BaseAddr = fmt.Sprintf(`wss://%s.%s.svc`, r.ServiceS3.Name, r.Request.Namespace)
syslogBaseAddr = fmt.Sprintf(`udp://%s.%s.svc`, r.ServiceSyslog.Name, r.Request.Namespace)
r.setDesiredCoreEnv(c)
}
for j := range c.Env {
switch c.Env[j].Name {
case "MGMT_ADDR":
if r.JoinSecret == nil {
port := nb.FindPortByName(r.ServiceMgmt, "mgmt-https")
c.Env[j].Value = fmt.Sprintf(`%s:%d`, mgmtBaseAddr, port.Port)
} else {
c.Env[j].Value = r.JoinSecret.StringData["mgmt_addr"]
}
case "SYSLOG_ADDR":
if r.JoinSecret == nil {
port := nb.FindPortByName(r.ServiceSyslog, "syslog")
c.Env[j].Value = fmt.Sprintf(`%s:%d`, syslogBaseAddr, port.Port)
} else {
c.Env[j].Value = r.JoinSecret.StringData["syslog"]
}
case "BG_ADDR":
if r.JoinSecret == nil {
port := nb.FindPortByName(r.ServiceMgmt, "bg-https")
c.Env[j].Value = fmt.Sprintf(`%s:%d`, mgmtBaseAddr, port.Port)
} else {
c.Env[j].Value = r.JoinSecret.StringData["bg_addr"]
}
case "MD_ADDR":
if r.JoinSecret == nil {
port := nb.FindPortByName(r.ServiceS3, "md-https")
c.Env[j].Value = fmt.Sprintf(`%s:%d`, s3BaseAddr, port.Port)
} else {
c.Env[j].Value = r.JoinSecret.StringData["md_addr"]
}
case "HOSTED_AGENTS_ADDR":
if r.JoinSecret == nil {
port := nb.FindPortByName(r.ServiceMgmt, "hosted-agents-https")
c.Env[j].Value = fmt.Sprintf(`%s:%d`, mgmtBaseAddr, port.Port)
} else {
c.Env[j].Value = r.JoinSecret.StringData["hosted_agents_addr"]
}
case "LOCAL_MD_SERVER":
if r.JoinSecret == nil {
c.Env[j].Value = "true"
}
case "LOCAL_N2N_AGENT":
if r.JoinSecret == nil {
c.Env[j].Value = "true"
}
case "NOOBAA_ROOT_SECRET":
c.Env[j].Value = r.SecretRootMasterKey
case "VIRTUAL_HOSTS":
hosts := []string{}
for _, addr := range r.NooBaa.Status.Services.ServiceS3.InternalDNS {
// Ignore mailformed addresses
if u, err := url.Parse(addr); err == nil {
if host, _, err := net.SplitHostPort(u.Host); err == nil {
hosts = append(hosts, host)
}
}
}
for _, addr := range r.NooBaa.Status.Services.ServiceS3.ExternalDNS {
// Ignore mailformed addresses
if u, err := url.Parse(addr); err == nil {
if host, _, err := net.SplitHostPort(u.Host); err == nil {
hosts = append(hosts, host)
}
}
}
if endpointsSpec != nil {
hosts = append(hosts, endpointsSpec.AdditionalVirtualHosts...)
}
c.Env[j].Value = fmt.Sprint(strings.Join(hosts[:], " "))
case "ENDPOINT_GROUP_ID":
c.Env[j].Value = fmt.Sprint(r.NooBaa.UID)
case "REGION":
if r.NooBaa.Spec.Region != nil {
c.Env[j].Value = *r.NooBaa.Spec.Region
} else {
c.Env[j].Value = ""
}
case "NODE_EXTRA_CA_CERTS":
c.Env[j].Value = r.ApplyCAsToPods
case "GUARANTEED_LOGS_PATH":
if r.NooBaa.Spec.BucketLogging.LoggingType == nbv1.BucketLoggingTypeGuaranteed {
c.Env[j].Value = r.BucketLoggingVolumeMount
} else {
c.Env[j].Value = ""
}
}
}
if r.NooBaa.Spec.BucketNotifications.Enabled {
envVar := corev1.EnvVar{
Name: "NOTIFICATION_LOG_DIR",
Value: "/var/logs/notifications",
}
util.MergeEnvArrays(&c.Env, &[]corev1.EnvVar{envVar});
}
c.SecurityContext = &corev1.SecurityContext{
Capabilities: &corev1.Capabilities{
Add: []corev1.Capability{"SETUID", "SETGID"},
},
}
util.ReflectEnvVariable(&c.Env, "HTTP_PROXY")
util.ReflectEnvVariable(&c.Env, "HTTPS_PROXY")
util.ReflectEnvVariable(&c.Env, "NO_PROXY")
if r.DeploymentEndpoint.Spec.Template.Annotations == nil {
r.DeploymentEndpoint.Spec.Template.Annotations = make(map[string]string)
}
r.DeploymentEndpoint.Spec.Template.Annotations["noobaa.io/configmap-hash"] = r.CoreAppConfig.Annotations["noobaa.io/configmap-hash"]
return r.setDesiredEndpointMounts(podSpec, c)
}
}
return nil
}
func (r *Reconciler) setDesiredRootMasterKeyMounts(podSpec *corev1.PodSpec, container *corev1.Container) {
// Don't map secret map volume if the string secret is used
if len(r.SecretRootMasterKey) > 0 {
return
}
if !util.KubeCheckQuiet(r.SecretRootMasterMap) {
return
}
rootMasterKeyVolumes := []corev1.Volume{{
Name: r.SecretRootMasterMap.Name,
VolumeSource: corev1.VolumeSource{
Secret: &corev1.SecretVolumeSource{
SecretName: r.SecretRootMasterMap.Name,
},
},
}}
util.MergeVolumeList(&podSpec.Volumes, &rootMasterKeyVolumes)
rootMasterKeyVolumeMounts := []corev1.VolumeMount{{
Name: r.SecretRootMasterMap.Name,
MountPath: "/etc/noobaa-server/root_keys",
ReadOnly: true,
}}
util.MergeVolumeMountList(&container.VolumeMounts, &rootMasterKeyVolumeMounts)
}
func (r *Reconciler) setDesiredEndpointMounts(podSpec *corev1.PodSpec, container *corev1.Container) error {
namespaceStoreList := &nbv1.NamespaceStoreList{}
if !util.KubeList(namespaceStoreList, client.InNamespace(options.Namespace)) {
return fmt.Errorf("Error: Cant list namespacestores")
}
podSpec.Volumes = r.DefaultDeploymentEndpoint.Volumes
container.VolumeMounts = r.DefaultDeploymentEndpoint.Containers[0].VolumeMounts
if util.KubeCheckQuiet(r.CaBundleConf) {
configMapVolumes := []corev1.Volume{{
Name: r.CaBundleConf.Name,
VolumeSource: corev1.VolumeSource{
ConfigMap: &corev1.ConfigMapVolumeSource{
LocalObjectReference: corev1.LocalObjectReference{
Name: r.CaBundleConf.Name,
},
Items: []corev1.KeyToPath{{
Key: "ca-bundle.crt",
Path: "ca-bundle.crt",
}},
},
},
}}
util.MergeVolumeList(&podSpec.Volumes, &configMapVolumes)
configMapVolumeMounts := []corev1.VolumeMount{{
Name: r.CaBundleConf.Name,
MountPath: "/etc/ocp-injected-ca-bundle.crt",
ReadOnly: true,
}}
util.MergeVolumeMountList(&container.VolumeMounts, &configMapVolumeMounts)
}
if r.ExternalPgSSLSecret != nil && util.KubeCheckQuiet(r.ExternalPgSSLSecret) {
secretVolumes := []corev1.Volume{{
Name: r.ExternalPgSSLSecret.Name,
VolumeSource: corev1.VolumeSource{
Secret: &corev1.SecretVolumeSource{
SecretName: r.ExternalPgSSLSecret.Name,
},
},
}}
util.MergeVolumeList(&podSpec.Volumes, &secretVolumes)
secretVolumeMounts := []corev1.VolumeMount{{
Name: r.ExternalPgSSLSecret.Name,
MountPath: "/etc/external-db-secret",
ReadOnly: true,
}}
util.MergeVolumeMountList(&container.VolumeMounts, &secretVolumeMounts)
}
if r.NooBaa.Spec.BucketLogging.LoggingType == nbv1.BucketLoggingTypeGuaranteed {
bucketLogVolumes := []corev1.Volume{{
Name: r.BucketLoggingVolume,
VolumeSource: corev1.VolumeSource{
PersistentVolumeClaim: &corev1.PersistentVolumeClaimVolumeSource{
ClaimName: r.BucketLoggingPVC.Name,
},
},
}}
util.MergeVolumeList(&podSpec.Volumes, &bucketLogVolumes)
bucketLogVolumeMounts := []corev1.VolumeMount{{
Name: r.BucketLoggingVolume,
MountPath: r.BucketLoggingVolumeMount,
}}
util.MergeVolumeMountList(&container.VolumeMounts, &bucketLogVolumeMounts)
}
if r.NooBaa.Spec.BucketNotifications.Enabled {
notificationVolumes := []corev1.Volume{{
Name: "notif-vol",
VolumeSource: corev1.VolumeSource{
PersistentVolumeClaim: &corev1.PersistentVolumeClaimVolumeSource{
ClaimName: r.BucketNotificationsPVC.Name,
},
},
}}
util.MergeVolumeList(&podSpec.Volumes, ¬ificationVolumes)
notificationVolumeMounts := []corev1.VolumeMount{{
Name: "notif-vol",
MountPath: "/var/logs/notifications",
}}
util.MergeVolumeMountList(&container.VolumeMounts, ¬ificationVolumeMounts)
}
r.setDesiredRootMasterKeyMounts(podSpec, container)
for _, nsStore := range namespaceStoreList.Items {
// Since namespacestore is able to get a rejected state on runtime errors,
// we want to skip namespacestores with invalid configuration only.
// Remove this validation when the kubernetes validations hooks will be available.
if !r.validateNsStoreNSFS(&nsStore) {
continue
}
if nsStore.Spec.NSFS != nil {
pvcName := nsStore.Spec.NSFS.PvcName
isPvcExist := false
volumeName := "nsfs-" + nsStore.Name
for _, volume := range podSpec.Volumes {
if volume.PersistentVolumeClaim != nil && volume.PersistentVolumeClaim.ClaimName == pvcName {
isPvcExist = true // PVC already attached to the pods - no need to add
volumeName = volume.Name
break
}
}
if !isPvcExist {
podSpec.Volumes = append(podSpec.Volumes, corev1.Volume{
Name: volumeName,
VolumeSource: corev1.VolumeSource{
PersistentVolumeClaim: &corev1.PersistentVolumeClaimVolumeSource{
ClaimName: pvcName,
},
},
})
}
subPath := nsStore.Spec.NSFS.SubPath
mountPath := "/nsfs/" + nsStore.Name
isMountExist := false
for _, volumeMount := range container.VolumeMounts {
if volumeMount.Name == volumeName && volumeMount.SubPath == subPath {
isMountExist = true // volumeMount already created - no need to add
break
}
}
if !isMountExist {
container.VolumeMounts = append(container.VolumeMounts, corev1.VolumeMount{
Name: volumeName,
MountPath: mountPath,
SubPath: subPath,
})
}
}
}
return nil
}
// Duplicate code from validation.go namespacetore pkg.
// Cannot import the namespacestore pkg, because the pkg imports the system pkg
// TODO remove the code
func (r *Reconciler) validateNsStoreNSFS(nsStore *nbv1.NamespaceStore) bool {
nsfs := nsStore.Spec.NSFS
if nsfs == nil {
return true
}
//pvcName validation
if nsfs.PvcName == "" {
return false
}
//Check the mountPath
mountPath := "/nsfs/" + nsStore.Name
if len(mountPath) > 63 {
return false
}
//SubPath validation
if nsfs.SubPath != "" {
path := nsfs.SubPath
if len(path) > 0 && path[0] == '/' {
return false
}
parts := strings.Split(path, "/")
for _, item := range parts {
if item == ".." {
return false
}
}
}
return true
}
// awaitEndpointDeploymentPods wait for the the endpoint deployment to become ready
// before creating the controlling HPA
// See https://bugzilla.redhat.com/show_bug.cgi?id=1885524
func (r *Reconciler) awaitEndpointDeploymentPods() error {
// Check that all deployment pods are available
availablePods := r.DeploymentEndpoint.Status.AvailableReplicas
desiredPods := r.DeploymentEndpoint.Status.Replicas
if availablePods == 0 || availablePods != desiredPods {
return errors.New("not enough available replicas in endpoint deployment")
}
// Check that deployment is ready
for _, condition := range r.DeploymentEndpoint.Status.Conditions {
if condition.Status != "True" {
return errors.New("endpoint deployment is not ready")
}
}
return nil
}
// ReconcileHPAEndpoint reconcile the endpoint's HPA and report the configuration
// back to the noobaa core
func (r *Reconciler) ReconcileHPAEndpoint() error {
// Wait for the the endpoint deployment to become ready
// only if HPA was not created yet
if err := r.awaitEndpointDeploymentPods(); err != nil {
return err
}
if err := r.reconcileAutoscaler(); err != nil {
return err
}
return r.updateNoobaaEndpoint()
}
func (r *Reconciler) updateNoobaaEndpoint() error {
endpointsSpec := r.NooBaa.Spec.Endpoints
var max, min int32 = 1, 2
if endpointsSpec != nil {
min = endpointsSpec.MinCount
max = endpointsSpec.MaxCount
}
region := ""
if r.NooBaa.Spec.Region != nil {
region = *r.NooBaa.Spec.Region
}
return r.NBClient.UpdateEndpointGroupAPI(nb.UpdateEndpointGroupParams{
GroupName: fmt.Sprint(r.NooBaa.UID),
IsRemote: r.JoinSecret != nil,
Region: region,
EndpointRange: nb.IntRange{
Min: min,
Max: max,
},
})
}
// RegisterToCluster registers the noobaa client with the noobaa cluster
func (r *Reconciler) RegisterToCluster() error {
// Skip if joining another NooBaa
if r.JoinSecret != nil {
return nil
}
return r.NBClient.RegisterToCluster()
}
// ReconcileDefaultNamespaceStore checks if the default NSFS pvc exists or not
// and attempts to create default NSFS namespacestore using NSFS pvc which in turn uses
// spectrum scale storage class.
func (r *Reconciler) ReconcileDefaultNamespaceStore() error {
// Skip if joining another NooBaa
if r.JoinSecret != nil {
return nil
}
log := r.Logger.WithField("func", "ReconcileDefaultNamespaceStore")
if r.DefaultNsfsPvc.UID == "" {
log.Infof("PVC %s does not exist. skipping Reconcile %s", r.DefaultNsfsPvc.Name, r.DefaultNamespaceStore.Name)
return nil
}
util.KubeCheck(r.DefaultNamespaceStore)
if r.DefaultNamespaceStore.UID != "" {
log.Infof("NamespaceStore %s already exists. skipping Reconcile", r.DefaultNamespaceStore.Name)
return nil
}
r.DefaultNamespaceStore.Spec.Type = nbv1.NSStoreTypeNSFS
r.DefaultNamespaceStore.Spec.NSFS = &nbv1.NSFSSpec{}
r.DefaultNamespaceStore.Spec.NSFS.PvcName = r.DefaultNsfsPvc.Name
r.DefaultNamespaceStore.Spec.NSFS.SubPath = ""
r.Own(r.DefaultNamespaceStore)
if err := r.Client.Create(r.Ctx, r.DefaultNamespaceStore); err != nil {
log.Errorf("got error on DefaultNamespaceStore creation. error: %v", err)
return err
}
return nil
}
// ReconcileDefaultNsfsPvc checks if the noobaa is running on Fusion HCI with
// spectrum scale and attempts to create default PVC for nsfs using spectrum scale
// storage class.
func (r *Reconciler) ReconcileDefaultNsfsPvc() error {
// Skip if joining another NooBaa
if r.JoinSecret != nil {
return nil
}
// Check if ODF is installed on Fusion HCI cluster with spectrum scale.
if !util.IsFusionHCIWithScale() {
return nil
}
r.Logger.Info("IBM Fusion HCI with Spectrum Scale detected.")
log := r.Logger.WithField("func", "ReconcileDefaultNsfsPvc")
util.KubeCheck(r.DefaultNsfsPvc)
if r.DefaultNsfsPvc.UID != "" {
log.Infof("DefaultNsfsPvc %s already exists. skipping Reconcile", r.DefaultNsfsPvc.Name)
return nil
}
if r.NooBaa.Spec.ManualDefaultBackingStore {
r.Logger.Info("ManualDefaultBackingStore is true, Skip Reconciling default nsfs pvc")
return nil
}
var sc = "ibm-spectrum-scale-csi-storageclass-version2"
defaultPVCSize := int64(30) * 1024 * 1024 * 1024 // 30GB
r.DefaultNsfsPvc.Spec.AccessModes = []corev1.PersistentVolumeAccessMode{corev1.ReadWriteMany}
r.DefaultNsfsPvc.Spec.Resources.Requests.Storage()
r.DefaultNsfsPvc.Spec.Resources.Requests[corev1.ResourceStorage] = *resource.NewQuantity(defaultPVCSize, resource.BinarySI)
r.DefaultNsfsPvc.Spec.StorageClassName = &sc
r.Own(r.DefaultNsfsPvc)
if err := r.Client.Create(r.Ctx, r.DefaultNsfsPvc); err != nil {
log.Errorf("got error on DefaultNsfsPvc creation. error: %v", err)
return err
}
return nil
}
// ReconcileDefaultBackingStore attempts to get credentials to cloud storage using the cloud-credentials operator
// and use it for the default backing store
func (r *Reconciler) ReconcileDefaultBackingStore() error {
// Skip if joining another NooBaa
if r.JoinSecret != nil {
return nil
}
log := r.Logger.WithField("func", "ReconcileDefaultBackingStore")
// Check if ODF is installed on Fusion HCI cluster with spectrum scale.
if util.IsFusionHCIWithScale() {
r.Logger.Info("IBM Fusion HCI with Spectrum Scale detected. Not creating Default Backing Store.")
return nil
}
util.KubeCheck(r.DefaultBackingStore)
// backing store already exists - we can skip
// TODO: check if there are any changes to reconcile
if r.DefaultBackingStore.UID != "" {
log.Infof("Backing store %s already exists. skipping ReconcileCloudCredentials", r.DefaultBackingStore.Name)
return nil
}
// If default backing store is disabled
if r.NooBaa.Spec.ManualDefaultBackingStore {
r.Logger.Info("ManualDefaultBackingStore is true, Skip Reconciling Backing Store Creation")
return nil
}
if r.CephObjectStoreUser.UID != "" {
log.Infof("CephObjectStoreUser %q created. Creating default backing store on ceph objectstore", r.CephObjectStoreUser.Name)
if err := r.prepareCephBackingStore(); err != nil {
return err
}
} else if r.AWSCloudCreds.UID != "" {
log.Infof("CredentialsRequest %q created. Creating default backing store on AWS objectstore", r.AWSCloudCreds.Name)
if err := r.prepareAWSBackingStore(); err != nil {
return err
}
} else if r.AzureCloudCreds.UID != "" {
log.Infof("CredentialsRequest %q created. Creating default backing store on Azure objectstore", r.AzureCloudCreds.Name)
if err := r.prepareAzureBackingStore(); err != nil {
return err
}
} else if r.GCPCloudCreds.UID != "" {
log.Infof("CredentialsRequest %q created. creating default backing store on GCP objectstore", r.GCPCloudCreds.Name)
if err := r.prepareGCPBackingStore(); err != nil {
return err
}
} else if r.IBMCosBucketCreds.UID != "" {
log.Infof("IBM objectstore credentials %q created. Creating default backing store on IBM objectstore", r.IBMCosBucketCreds.Name)
if err := r.prepareIBMBackingStore(); err != nil {
return err
}
} else {
minutesSinceCreation := time.Since(r.NooBaa.CreationTimestamp.Time).Minutes()
if minutesSinceCreation < 2 {
return nil
}
if err := r.preparePVPoolBackingStore(); err != nil {
return err
}
}
r.Own(r.DefaultBackingStore)
if err := r.Client.Create(r.Ctx, r.DefaultBackingStore); err != nil {
log.Errorf("got error on DefaultBackingStore creation. error: %v", err)
return err
}
return nil
}
func (r *Reconciler) preparePVPoolBackingStore() error {
// create backing store
defaultPVSize := int64(50) * 1024 * 1024 * 1024 // 50GB
r.DefaultBackingStore.Spec.Type = nbv1.StoreTypePVPool
r.DefaultBackingStore.Spec.PVPool = &nbv1.PVPoolSpec{}
r.DefaultBackingStore.Spec.PVPool.NumVolumes = 1
r.DefaultBackingStore.Spec.PVPool.VolumeResources = &corev1.VolumeResourceRequirements{
Requests: corev1.ResourceList{
corev1.ResourceStorage: *resource.NewQuantity(defaultPVSize, resource.BinarySI),
},
}
if r.NooBaa.Spec.PVPoolDefaultStorageClass != nil {
r.DefaultBackingStore.Spec.PVPool.StorageClass = *r.NooBaa.Spec.PVPoolDefaultStorageClass
} else {
storageClassName, err := r.findLocalStorageClass()
if err != nil {
r.Logger.Errorf("got error finding a default/local storage class. error: %v", err)
return err
}
r.DefaultBackingStore.Spec.PVPool.StorageClass = storageClassName
}
return nil
}
func (r *Reconciler) defaultBSCreationTimedout(timestampCreation time.Time) bool {
minutesSinceCreation := time.Since(timestampCreation).Minutes()
return minutesSinceCreation > float64(minutesToWaitForDefaultBSCreation)
}
func (r *Reconciler) fallbackToPVPoolWithEvent(backingStoreType nbv1.StoreType, secretName string) error {
message := fmt.Sprintf("Failed to create default backingstore with type %s by %d minutes, "+
"fallback to create %s backingstore",
backingStoreType, minutesToWaitForDefaultBSCreation, nbv1.StoreTypePVPool)
additionalInfoForLogs := fmt.Sprintf(" (could not get Secret %s).", secretName)
r.Logger.Info(message + additionalInfoForLogs)
r.Recorder.Event(r.NooBaa, corev1.EventTypeWarning, "DefaultBackingStoreFailure", message)
if err := r.preparePVPoolBackingStore(); err != nil {
return err
}
return nil
}
func (r *Reconciler) prepareAWSBackingStore() error {
// after we have cloud credential request, wait for credentials secret
secretName := r.AWSCloudCreds.Spec.SecretRef.Name
cloudCredsSecret := &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: secretName,
Namespace: r.AWSCloudCreds.Spec.SecretRef.Namespace,
},
}
util.KubeCheck(cloudCredsSecret)
if cloudCredsSecret.UID == "" {
// TODO: we need to figure out why secret is not created, and react accordingly
// e.g. maybe we are running on azure but our CredentialsRequest is for AWS
r.Logger.Infof("Secret %q was not created yet by cloud-credentials operator. retry on next reconcile..", secretName)
// in case we have a cred request but we do not get a secret
if r.defaultBSCreationTimedout(r.AWSCloudCreds.CreationTimestamp.Time) {
return r.fallbackToPVPoolWithEvent(nbv1.StoreTypeAWSS3, secretName)
}
return fmt.Errorf("cloud credentials secret %q is not ready yet", secretName)
}
r.Logger.Infof("Secret %s was created successfully by cloud-credentials operator", secretName)
// create the actual S3 bucket
region, err := util.GetAWSRegion()
if err != nil {
r.Recorder.Eventf(r.NooBaa, corev1.EventTypeWarning, "DefaultBackingStoreFailure",
"Failed to get AWSRegion. using us-east-1 as the default region. %q", err)
region = "us-east-1"
}
r.Logger.Infof("identified aws region %s", region)
var s3Config *aws.Config
if r.IsAWSSTSCluster { // handle STS case first
// get credentials
if len(cloudCredsSecret.StringData[credentialsKey]) == 0 {
return fmt.Errorf("invalid secret for aws sts credentials (should contain %s under data)",
credentialsKey)
}
data := cloudCredsSecret.StringData[credentialsKey]
info, err := r.getInfoFromAwsStsSecret(data)
if err != nil {
return fmt.Errorf("could not get the credentials from the aws sts secret %v", err)
}
roleARNInput := info["role_arn"]
webIdentityTokenPathInput := info["web_identity_token_file"]
r.Logger.Info("Initiating a Session with AWS")
sess, err := session.NewSession()
if err != nil {
return fmt.Errorf("could not create AWS Session %v", err)
}
stsClient := sts.New(sess)
r.Logger.Infof("AssumeRoleWithWebIdentityInput, roleARN = %s webIdentityTokenPath = %s, ",
roleARNInput, webIdentityTokenPathInput)
webIdentityTokenPathOutput, err := os.ReadFile(webIdentityTokenPathInput)
if err != nil {
return fmt.Errorf("could not read WebIdentityToken from path %s, %v",
webIdentityTokenPathInput, err)
}
WebIdentityToken := string(webIdentityTokenPathOutput)
input := &sts.AssumeRoleWithWebIdentityInput{
RoleArn: aws.String(roleARNInput),
RoleSessionName: aws.String(r.AWSSTSRoleSessionName),
WebIdentityToken: aws.String(WebIdentityToken),
}
result, err := stsClient.AssumeRoleWithWebIdentity(input)
if err != nil {
return fmt.Errorf("could not use AWS AssumeRoleWithWebIdentity with role name %s and web identity token file %s, %v",
roleARNInput, webIdentityTokenPathInput, err)
}
s3Config = &aws.Config{
Credentials: credentials.NewStaticCredentials(
*result.Credentials.AccessKeyId,
*result.Credentials.SecretAccessKey,
*result.Credentials.SessionToken,
),
Region: ®ion,
}
} else { // handle AWS long-lived credentials (not STS)
s3Config = &aws.Config{
Credentials: credentials.NewStaticCredentials(