diff --git a/pkg/operator/ceph/controller/predicate.go b/pkg/operator/ceph/controller/predicate.go index 9841c75e0..cefeb953b 100644 --- a/pkg/operator/ceph/controller/predicate.go +++ b/pkg/operator/ceph/controller/predicate.go @@ -19,6 +19,7 @@ package controller import ( "encoding/json" "os" + "reflect" "strings" "syscall" @@ -374,9 +375,8 @@ func WatchControllerPredicate() predicate.Funcs { logger.Debugf("object %q matched on update but %q label is set, doing nothing", objNew.Name, DoNotReconcileLabelName) return false } - diff := cmp.Diff(objOld.Labels, objNew.Labels, resourceQtyComparer) - if diff != "" { - logger.Infof("CR labels has changed for %q. diff=%s", objNew.Name, diff) + if !reflect.DeepEqual(objOld.Labels, objNew.Labels) { + logger.Infof("CR labels has changed for %q", objNew.Name) return true } else if objOld.Spec.ObjectBucketName != objNew.Spec.ObjectBucketName { logger.Infof("CR %q bucket name changed from %q to %q", objNew.Name, objOld.Spec.ObjectBucketName, objNew.Spec.ObjectBucketName) diff --git a/pkg/operator/ceph/object/bucket/provisioner.go b/pkg/operator/ceph/object/bucket/provisioner.go index 4607e65ad..388eff634 100644 --- a/pkg/operator/ceph/object/bucket/provisioner.go +++ b/pkg/operator/ceph/object/bucket/provisioner.go @@ -428,7 +428,7 @@ func (p *Provisioner) composeObjectBucket() *bktv1alpha1.ObjectBucket { }, }, AdditionalState: map[string]string{ - cephUser: p.cephUserName, + CephUser: p.cephUserName, }, } @@ -685,7 +685,7 @@ func (p Provisioner) updateAdditionalSettings(ob *bktv1alpha1.ObjectBucket) erro return errors.Wrapf(err, "failed to parse maxSize quota for user %q", p.cephUserName) } } - objectUser, err := p.adminOpsClient.GetUser(p.clusterInfo.Context, admin.User{ID: ob.Spec.Connection.AdditionalState[cephUser]}) + objectUser, err := p.adminOpsClient.GetUser(p.clusterInfo.Context, admin.User{ID: ob.Spec.Connection.AdditionalState[CephUser]}) if err != nil { return errors.Wrapf(err, "failed to fetch user %q", p.cephUserName) } diff --git a/pkg/operator/ceph/object/bucket/util.go b/pkg/operator/ceph/object/bucket/util.go index e9f03b18e..f5b08c9ff 100644 --- a/pkg/operator/ceph/object/bucket/util.go +++ b/pkg/operator/ceph/object/bucket/util.go @@ -35,7 +35,7 @@ var logger = capnslog.NewPackageLogger("github.com/rook/rook", "op-bucket-prov") const ( genUserLen = 8 - cephUser = "cephUser" + CephUser = "cephUser" objectStoreName = "objectStoreName" objectStoreNamespace = "objectStoreNamespace" objectStoreEndpoint = "endpoint" @@ -72,7 +72,7 @@ func isStaticBucket(sc *storagev1.StorageClass) (string, bool) { } func getCephUser(ob *bktv1alpha1.ObjectBucket) string { - return ob.Spec.AdditionalState[cephUser] + return ob.Spec.AdditionalState[CephUser] } func (p *Provisioner) getObjectStore() (*cephv1.CephObjectStore, error) { diff --git a/pkg/operator/ceph/object/notification/controller.go b/pkg/operator/ceph/object/notification/controller.go index a33bd52bd..3e84a55a8 100644 --- a/pkg/operator/ceph/object/notification/controller.go +++ b/pkg/operator/ceph/object/notification/controller.go @@ -14,11 +14,11 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package notification to manage a rook bucket notifications. package notification import ( "context" - "strings" "time" "github.com/coreos/pkg/capnslog" @@ -29,6 +29,8 @@ import ( cephclient "github.com/rook/rook/pkg/daemon/ceph/client" "github.com/rook/rook/pkg/operator/ceph/cluster/mon" opcontroller "github.com/rook/rook/pkg/operator/ceph/controller" + "github.com/rook/rook/pkg/operator/ceph/object" + "github.com/rook/rook/pkg/operator/ceph/object/bucket" "github.com/rook/rook/pkg/operator/ceph/object/topic" kerrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/types" @@ -55,8 +57,6 @@ var waitForRequeueIfObjectBucketNotReady = reconcile.Result{Requeue: true, Reque type ReconcileNotifications struct { client client.Client context *clusterd.Context - clusterInfo *cephclient.ClusterInfo - clusterSpec *cephv1.ClusterSpec opManagerContext context.Context } @@ -99,7 +99,6 @@ func addNotificationReconciler(mgr manager.Manager, r reconcile.Reconciler) erro // 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 *ReconcileNotifications) Reconcile(context context.Context, request reconcile.Request) (reconcile.Result, error) { - // workaround because the rook logging mechanism is not compatible with the controller-runtime logging interface reconcileResponse, err := r.reconcile(request) if err != nil { logger.Errorf("failed to reconcile %v", err) @@ -121,36 +120,6 @@ func (r *ReconcileNotifications) reconcile(request reconcile.Request) (reconcile return reconcile.Result{}, errors.Wrapf(err, "failed to retrieve CephBucketNotification %q", request.NamespacedName) } - // get the topic associated with the notification - bucketTopic := &cephv1.CephBucketTopic{} - topicName := types.NamespacedName{Namespace: notification.Namespace, Name: notification.Spec.Topic} - if err := r.client.Get(r.opManagerContext, topicName, bucketTopic); err != nil { - if kerrors.IsNotFound(err) { - logger.Infof("CephBucketTopic %q not provisioned yet", topicName) - return waitForRequeueIfTopicNotReady, nil - } - return reconcile.Result{}, errors.Wrapf(err, "failed to retrieve CephBucketTopic %q", topicName) - } - - // find the namespace for the ceph cluster (may be different than the namespace of the notification CR) - // Make sure a CephCluster is present otherwise do nothing - cephCluster, isReadyToReconcile, cephClusterExists, reconcileResponse := opcontroller.IsReadyToReconcile( - r.opManagerContext, - r.client, - types.NamespacedName{Namespace: bucketTopic.Spec.ObjectStoreNamespace}, - controllerName, - ) - if !isReadyToReconcile { - // This handles the case where the Ceph Cluster is gone and we want to delete that CR - if !notification.GetDeletionTimestamp().IsZero() && !cephClusterExists { - // Return and do not requeue. Successful deletion. - return reconcile.Result{}, nil - } - logger.Debug("Ceph cluster not yet present.") - return reconcileResponse, nil - } - r.clusterSpec = &cephCluster.Spec - // DELETE: the CR was deleted if !notification.GetDeletionTimestamp().IsZero() { logger.Debugf("CephBucketNotification %q was deleted", notification.Name) @@ -159,53 +128,24 @@ func (r *ReconcileNotifications) reconcile(request reconcile.Request) (reconcile return reconcile.Result{}, nil } + // get the topic associated with the notification, and make sure it is provisioned + topicName := types.NamespacedName{Namespace: notification.Namespace, Name: notification.Spec.Topic} + bucketTopic, err := topic.GetProvisioned(r.client, r.opManagerContext, topicName) + if err != nil { + logger.Infof("CephBucketTopic %q not provisioned yet", topicName) + return waitForRequeueIfTopicNotReady, nil + } + // Populate clusterInfo during each reconcile - r.clusterInfo, _, _, err = mon.LoadClusterInfo(r.context, r.opManagerContext, cephCluster.Namespace) + clusterInfo, clusterSpec, err := getReadyCluster(r.client, r.opManagerContext, *r.context, bucketTopic.Spec.ObjectStoreNamespace) if err != nil { - return reconcile.Result{}, errors.Wrap(err, "failed to populate cluster info") + return opcontroller.WaitForRequeueIfCephClusterNotReady, errors.Wrapf(err, "cluster is not ready") + } + if clusterInfo == nil || clusterSpec == nil { + return opcontroller.WaitForRequeueIfCephClusterNotReady, nil } - // create the notification if needed - return r.updateCephBucketNotification(notification, bucketTopic) -} - -func getCephObjectStoreName(ob bktv1alpha1.ObjectBucket) (objectStoreName types.NamespacedName, err error) { - // prase the following string: -rgw-..svc - // to ge the object store name and namespace - logger.Debugf("BucketHost of %q is %q", - types.NamespacedName{Name: ob.Name, Namespace: ob.Namespace}.String(), - ob.Spec.Endpoint.BucketHost, - ) - parsedBucketHost := strings.Split(ob.Spec.Endpoint.BucketHost, ".") - if len(parsedBucketHost) < 3 { - err = errors.Errorf("malformed BucketHost %q", ob.Spec.Endpoint.BucketHost) - return - } - parsedSubdomain := strings.Split(parsedBucketHost[0], "-rgw-") - if len(parsedSubdomain) != 2 { - err = errors.Errorf("malformed BucketHost subdomain %q", parsedBucketHost[0]) - return - } - objectStoreName.Namespace = parsedBucketHost[1] - objectStoreName.Name = parsedSubdomain[1] - return -} - -// verify that object store is configured correctly for OB, CephBucketNotification and CephBucketTopic -func validateObjectStoreName(topic *cephv1.CephBucketTopic, bucketStoreName types.NamespacedName) error { - topicStoreName := types.NamespacedName{Name: topic.Spec.ObjectStoreName, Namespace: topic.Spec.ObjectStoreNamespace} - if topicStoreName != bucketStoreName { - return errors.Errorf("object store name mismatch between topic and bucket. %q != %q", topicStoreName, bucketStoreName) - } - return nil -} - -func (r *ReconcileNotifications) updateCephBucketNotification(notification *cephv1.CephBucketNotification, bucketTopic *cephv1.CephBucketTopic) (reconcile.Result, error) { - topicARN, err := topic.GetARN(bucketTopic) - if err != nil { - return reconcile.Result{}, errors.Wrapf(err, "failed to get topic ARN for CephBucketTopic %q", types.NamespacedName{Name: bucketTopic.Name, Namespace: bucketTopic.Namespace}) - } - // fetch all OBCs that has a label matching this CBN + // fetch all OBCs that has a label matching this CephBucketNotification namespace := notification.Namespace bnName := types.NamespacedName{Namespace: namespace, Name: notification.Name} namespaceListOpt := client.InNamespace(namespace) @@ -224,6 +164,10 @@ func (r *ReconcileNotifications) updateCephBucketNotification(notification *ceph // loop through all OBCs in the list and get their OBs for _, obc := range obcList.Items { + if obc.Spec.ObjectBucketName == "" { + logger.Infof("ObjectBucketClaim %q resource did not create the bucket yet. will retry", types.NamespacedName{Name: obc.Name, Namespace: obc.Namespace}) + return waitForRequeueIfObjectBucketNotReady, nil + } ob := bktv1alpha1.ObjectBucket{} bucketName := types.NamespacedName{Namespace: namespace, Name: obc.Spec.ObjectBucketName} if err := r.client.Get(r.opManagerContext, bucketName, &ob); err != nil { @@ -237,22 +181,19 @@ func (r *ReconcileNotifications) updateCephBucketNotification(notification *ceph return reconcile.Result{}, err } - // provision the notification - provisioner := Provisioner{ - Client: r.client, - Context: r.context, - ClusterInfo: r.clusterInfo, - ClusterSpec: r.clusterSpec, - opManagerContext: r.opManagerContext, - } - session, err := provisioner.createSession( - ob.Spec.AdditionalState["cephUser"], - objectStoreName, + err = createNotificationFunc( + provisioner{ + context: r.context, + clusterInfo: clusterInfo, + clusterSpec: clusterSpec, + opManagerContext: r.opManagerContext, + owner: ob.Spec.AdditionalState[bucket.CephUser], + objectStoreName: objectStoreName, + }, + &ob, + *bucketTopic.Status.ARN, + notification, ) - if err != nil { - return reconcile.Result{}, errors.Wrapf(err, "failed to create session for CephBucketNotification provisioning %q for ObjectBucketClaims %q", bnName, bucketName) - } - err = provisioner.Create(&ob, topicARN, notification, session) if err != nil { return reconcile.Result{}, errors.Wrapf(err, "failed to provision CephBucketNotification %q for ObjectBucketClaims %q", bnName, bucketName) } @@ -260,3 +201,47 @@ func (r *ReconcileNotifications) updateCephBucketNotification(notification *ceph return reconcile.Result{}, nil } + +func getCephObjectStoreName(ob bktv1alpha1.ObjectBucket) (types.NamespacedName, error) { + // parse the following string: -rgw-..svc + // to ge the object store name and namespace + logger.Debugf("BucketHost of %q is %q", + types.NamespacedName{Name: ob.Name, Namespace: ob.Namespace}.String(), + ob.Spec.Connection.Endpoint.BucketHost, + ) + objectStoreName, err := object.ParseDomainName(ob.Spec.Connection.Endpoint.BucketHost) + if err != nil { + return types.NamespacedName{}, errors.Wrapf(err, "malformed BucketHost %q", ob.Spec.Endpoint.BucketHost) + } + return objectStoreName, nil +} + +// verify that object store is configured correctly for OB, CephBucketNotification and CephBucketTopic +func validateObjectStoreName(topic *cephv1.CephBucketTopic, bucketStoreName types.NamespacedName) error { + topicStoreName := types.NamespacedName{Name: topic.Spec.ObjectStoreName, Namespace: topic.Spec.ObjectStoreNamespace} + if topicStoreName != bucketStoreName { + return errors.Errorf("object store name mismatch between topic and bucket. %q != %q", topicStoreName, bucketStoreName) + } + return nil +} + +// getReadyCluster get cluster info and spec if the cluster is ready +func getReadyCluster(client client.Client, opManagerContext context.Context, context clusterd.Context, objectStoreNamespace string) (*cephclient.ClusterInfo, *cephv1.ClusterSpec, error) { + // find the namespace for the ceph cluster (may be different than the namespace of the notification CR) + // Make sure a CephCluster is present otherwise do nothing + cephCluster, isReadyToReconcile, cephClusterExists, _ := opcontroller.IsReadyToReconcile( + opManagerContext, + client, + types.NamespacedName{Namespace: objectStoreNamespace}, + controllerName, + ) + if !isReadyToReconcile || !cephClusterExists { + logger.Debug("Ceph cluster not yet present.") + return nil, nil, nil + } + clusterInfo, _, _, err := mon.LoadClusterInfo(&context, opManagerContext, cephCluster.Namespace) + if err != nil { + return nil, nil, errors.Wrap(err, "failed to populate cluster info") + } + return clusterInfo, &cephCluster.Spec, nil +} diff --git a/pkg/operator/ceph/object/notification/controller_test.go b/pkg/operator/ceph/object/notification/controller_test.go new file mode 100644 index 000000000..0859a2fe9 --- /dev/null +++ b/pkg/operator/ceph/object/notification/controller_test.go @@ -0,0 +1,515 @@ +/* +Copyright 2021 The Rook Authors. All rights reserved. + +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 notification to manage a rook bucket notifications. +package notification + +import ( + "context" + "os" + "testing" + + "github.com/coreos/pkg/capnslog" + bktv1alpha1 "github.com/kube-object-storage/lib-bucket-provisioner/pkg/apis/objectbucket.io/v1alpha1" + cephv1 "github.com/rook/rook/pkg/apis/ceph.rook.io/v1" + rookclient "github.com/rook/rook/pkg/client/clientset/versioned/fake" + "github.com/rook/rook/pkg/operator/test" + + "github.com/rook/rook/pkg/clusterd" + "github.com/rook/rook/pkg/operator/ceph/object" + "github.com/rook/rook/pkg/operator/k8sutil" + exectest "github.com/rook/rook/pkg/util/exec/test" + "github.com/stretchr/testify/assert" + v1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" + "k8s.io/client-go/kubernetes/scheme" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/reconcile" +) + +var ( + testTopicName = "topic-a" + testNotificationName = "notification-a" + testNamespace = "rook-ceph" + testStoreName = "test-store" + testARN = "arn:aws:sns:" + testStoreName + "::" + testTopicName + testBucketName = "my-bucket" + testSCName = "my-storage-class" +) + +var createWasInvoked bool + +func mockCleanup() { + createWasInvoked = false + createNotificationFunc = createNotification + deleteAllNotificationsFunc = deleteAllNotifications +} + +func mockSetup() { + createWasInvoked = false + createNotificationFunc = func(p provisioner, bucket *bktv1alpha1.ObjectBucket, topicARN string, notification *cephv1.CephBucketNotification) error { + createWasInvoked = true + return nil + } + deleteAllNotificationsFunc = func(p provisioner, bucket *bktv1alpha1.ObjectBucket) error { + return nil + } +} + +func TestCephBucketNotificationController(t *testing.T) { + mockSetup() + defer mockCleanup() + ctx := context.TODO() + capnslog.SetGlobalLogLevel(capnslog.DEBUG) + os.Setenv("ROOK_LOG_LEVEL", "DEBUG") + + bucketTopic := &cephv1.CephBucketTopic{ + ObjectMeta: metav1.ObjectMeta{ + Name: testTopicName, + Namespace: testNamespace, + }, + TypeMeta: metav1.TypeMeta{ + Kind: "CephBucketTopic", + }, + Spec: cephv1.BucketTopicSpec{ + ObjectStoreName: testStoreName, + ObjectStoreNamespace: testNamespace, + Endpoint: cephv1.TopicEndpointSpec{ + HTTP: &cephv1.HTTPEndpointSpec{ + URI: "http://localhost", + }, + }, + }, + Status: &cephv1.BucketTopicStatus{ARN: nil}, + } + bucketNotification := &cephv1.CephBucketNotification{ + ObjectMeta: metav1.ObjectMeta{ + Name: testNotificationName, + Namespace: testNamespace, + }, + TypeMeta: metav1.TypeMeta{ + Kind: "CephBucketNotification", + }, + Spec: cephv1.BucketNotificationSpec{ + Topic: testTopicName, + }, + } + cephCluster := &cephv1.CephCluster{ + ObjectMeta: metav1.ObjectMeta{ + Name: testNamespace, + Namespace: testNamespace, + }, + Status: cephv1.ClusterStatus{ + Phase: k8sutil.EmptyStatus, + CephStatus: &cephv1.CephStatus{ + Health: "", + }, + }, + } + req := reconcile.Request{ + NamespacedName: types.NamespacedName{ + Name: testNotificationName, + Namespace: testNamespace, + }, + } + + s := scheme.Scheme + s.AddKnownTypes( + cephv1.SchemeGroupVersion, + &cephv1.CephBucketNotification{}, + &cephv1.CephBucketNotificationList{}, + &cephv1.CephBucketTopic{}, + &cephv1.CephBucketTopicList{}, + &cephv1.CephCluster{}, + &cephv1.CephClusterList{}, + &bktv1alpha1.ObjectBucketClaim{}, + &bktv1alpha1.ObjectBucketClaimList{}, + ) + + c := &clusterd.Context{ + Executor: &exectest.MockExecutor{}, + RookClientset: rookclient.NewSimpleClientset(), + Clientset: test.New(t, 3), + } + + secrets := map[string][]byte{ + "fsid": []byte("name"), + "mon-secret": []byte("monsecret"), + "admin-secret": []byte("adminsecret"), + } + secret := &v1.Secret{ + ObjectMeta: metav1.ObjectMeta{ + Name: "rook-ceph-mon", + Namespace: testNamespace, + }, + Data: secrets, + Type: k8sutil.RookType, + } + + _, err := c.Clientset.CoreV1().Secrets(testNamespace).Create(ctx, secret, metav1.CreateOptions{}) + assert.NoError(t, err) + + t.Run("create notification configuration without a topic", func(t *testing.T) { + // Objects to track in the fake client. + objects := []runtime.Object{ + bucketNotification, + } + + cl := fake.NewClientBuilder().WithScheme(s).WithRuntimeObjects(objects...).Build() + + r := &ReconcileNotifications{client: cl, context: c, opManagerContext: ctx} + + res, err := r.Reconcile(ctx, req) + // provisioning requeued because the topic is not configured + assert.NoError(t, err) + assert.True(t, res.Requeue) + // notification configuration is set + err = r.client.Get(ctx, types.NamespacedName{Name: testNotificationName, Namespace: testNamespace}, bucketNotification) + assert.NoError(t, err, bucketNotification) + assert.False(t, createWasInvoked) + }) + + t.Run("create notification and topic configuration when there is no cluster", func(t *testing.T) { + objects := []runtime.Object{ + bucketNotification, + bucketTopic, + } + + cl := fake.NewClientBuilder().WithScheme(s).WithRuntimeObjects(objects...).Build() + + r := &ReconcileNotifications{client: cl, context: c, opManagerContext: ctx} + + res, err := r.Reconcile(ctx, req) + // provisioning requeued because the cluster does not exist + assert.NoError(t, err) + assert.True(t, res.Requeue) + // notification configuration is set + err = r.client.Get(ctx, types.NamespacedName{Name: testNotificationName, Namespace: testNamespace}, bucketNotification) + assert.NoError(t, err, bucketNotification) + assert.False(t, createWasInvoked) + }) + + t.Run("create notification and topic configuration cluster is not ready", func(t *testing.T) { + objects := []runtime.Object{ + bucketNotification, + bucketTopic, + cephCluster, + } + + cl := fake.NewClientBuilder().WithScheme(s).WithRuntimeObjects(objects...).Build() + + r := &ReconcileNotifications{client: cl, context: c, opManagerContext: ctx} + + res, err := r.Reconcile(ctx, req) + // provisioning requeued because the cluster is not ready + assert.NoError(t, err) + assert.True(t, res.Requeue) + // notification configuration is set + err = r.client.Get(ctx, types.NamespacedName{Name: testNotificationName, Namespace: testNamespace}, bucketNotification) + assert.NoError(t, err, bucketNotification) + assert.False(t, createWasInvoked) + }) + + t.Run("create notification and topic configuration when topic is not yet provisioned", func(t *testing.T) { + cephCluster.Status.Phase = k8sutil.ReadyStatus + cephCluster.Status.CephStatus.Health = "HEALTH_OK" + objects := []runtime.Object{ + bucketNotification, + bucketTopic, + cephCluster, + } + + cl := fake.NewClientBuilder().WithScheme(s).WithRuntimeObjects(objects...).Build() + + r := &ReconcileNotifications{client: cl, context: c, opManagerContext: ctx} + + res, err := r.Reconcile(ctx, req) + // provisioning requeued because the topic is not provisioned on the RGW + assert.NoError(t, err) + assert.True(t, res.Requeue) + // notification configuration is set + err = r.client.Get(ctx, types.NamespacedName{Name: testNotificationName, Namespace: testNamespace}, bucketNotification) + assert.NoError(t, err, bucketNotification) + assert.False(t, createWasInvoked) + }) + + t.Run("create notification and topic configuration", func(t *testing.T) { + cephCluster.Status.Phase = k8sutil.ReadyStatus + cephCluster.Status.CephStatus.Health = "HEALTH_OK" + bucketTopic.Status.ARN = &testARN + objects := []runtime.Object{ + bucketNotification, + bucketTopic, + cephCluster, + } + + cl := fake.NewClientBuilder().WithScheme(s).WithRuntimeObjects(objects...).Build() + + r := &ReconcileNotifications{client: cl, context: c, opManagerContext: ctx} + + res, err := r.Reconcile(ctx, req) + assert.NoError(t, err) + assert.False(t, res.Requeue) + // notification configuration is set + err = r.client.Get(ctx, types.NamespacedName{Name: testNotificationName, Namespace: testNamespace}, bucketNotification) + assert.NoError(t, err, bucketNotification) + assert.False(t, createWasInvoked) + }) +} + +func TestCephBucketNotificationControllerWithOBC(t *testing.T) { + mockSetup() + defer mockCleanup() + ctx := context.TODO() + capnslog.SetGlobalLogLevel(capnslog.DEBUG) + os.Setenv("ROOK_LOG_LEVEL", "DEBUG") + + bucketTopic := &cephv1.CephBucketTopic{ + ObjectMeta: metav1.ObjectMeta{ + Name: testTopicName, + Namespace: testNamespace, + }, + TypeMeta: metav1.TypeMeta{ + Kind: "CephBucketTopic", + }, + Spec: cephv1.BucketTopicSpec{ + ObjectStoreName: testStoreName, + ObjectStoreNamespace: testNamespace, + Endpoint: cephv1.TopicEndpointSpec{ + HTTP: &cephv1.HTTPEndpointSpec{ + URI: "http://localhost", + }, + }, + }, + Status: &cephv1.BucketTopicStatus{ARN: &testARN}, + } + bucketNotification := &cephv1.CephBucketNotification{ + ObjectMeta: metav1.ObjectMeta{ + Name: testNotificationName, + Namespace: testNamespace, + }, + TypeMeta: metav1.TypeMeta{ + Kind: "CephBucketNotification", + }, + Spec: cephv1.BucketNotificationSpec{ + Topic: testTopicName, + }, + } + cephCluster := &cephv1.CephCluster{ + ObjectMeta: metav1.ObjectMeta{ + Name: testNamespace, + Namespace: testNamespace, + }, + Status: cephv1.ClusterStatus{ + Phase: k8sutil.ReadyStatus, + CephStatus: &cephv1.CephStatus{ + Health: "HEALTH_OK", + }, + }, + } + obc := &bktv1alpha1.ObjectBucketClaim{ + ObjectMeta: metav1.ObjectMeta{ + Name: testBucketName, + Namespace: testNamespace, + Labels: map[string]string{ + notificationLabelPrefix + testNotificationName: testNotificationName, + }, + }, + TypeMeta: metav1.TypeMeta{ + Kind: "ObjectBucketClaim", + }, + Spec: bktv1alpha1.ObjectBucketClaimSpec{ + StorageClassName: testSCName, + GenerateBucketName: testBucketName, + }, + Status: bktv1alpha1.ObjectBucketClaimStatus{ + Phase: bktv1alpha1.ObjectBucketClaimStatusPhasePending, + }, + } + req := reconcile.Request{ + NamespacedName: types.NamespacedName{ + Name: testNotificationName, + Namespace: testNamespace, + }, + } + + s := scheme.Scheme + s.AddKnownTypes( + cephv1.SchemeGroupVersion, + &cephv1.CephBucketNotification{}, + &cephv1.CephBucketNotificationList{}, + &cephv1.CephBucketTopic{}, + &cephv1.CephBucketTopicList{}, + &cephv1.CephCluster{}, + &cephv1.CephClusterList{}, + &bktv1alpha1.ObjectBucketClaim{}, + &bktv1alpha1.ObjectBucketClaimList{}, + &bktv1alpha1.ObjectBucket{}, + &bktv1alpha1.ObjectBucketList{}, + ) + + c := &clusterd.Context{ + Executor: &exectest.MockExecutor{}, + RookClientset: rookclient.NewSimpleClientset(), + Clientset: test.New(t, 3), + } + + secrets := map[string][]byte{ + "fsid": []byte("name"), + "mon-secret": []byte("monsecret"), + "admin-secret": []byte("adminsecret"), + } + secret := &v1.Secret{ + ObjectMeta: metav1.ObjectMeta{ + Name: "rook-ceph-mon", + Namespace: testNamespace, + }, + Data: secrets, + Type: k8sutil.RookType, + } + + _, err := c.Clientset.CoreV1().Secrets(testNamespace).Create(ctx, secret, metav1.CreateOptions{}) + assert.NoError(t, err) + + t.Run("provision notification when OBC exists but no OB", func(t *testing.T) { + objects := []runtime.Object{ + bucketNotification, + bucketTopic, + cephCluster, + obc, + } + + cl := fake.NewClientBuilder().WithScheme(s).WithRuntimeObjects(objects...).Build() + + r := &ReconcileNotifications{client: cl, context: c, opManagerContext: ctx} + + res, err := r.Reconcile(ctx, req) + assert.NoError(t, err) + assert.True(t, res.Requeue) + // notification configuration is set + err = r.client.Get(ctx, types.NamespacedName{Name: testNotificationName, Namespace: testNamespace}, bucketNotification) + assert.NoError(t, err, bucketNotification) + assert.False(t, createWasInvoked) + }) + + t.Run("provision notification when OB exists", func(t *testing.T) { + ob := &bktv1alpha1.ObjectBucket{ + ObjectMeta: metav1.ObjectMeta{ + Name: testBucketName, + Namespace: testNamespace, + }, + TypeMeta: metav1.TypeMeta{ + Kind: "ObjectBucket", + }, + Spec: bktv1alpha1.ObjectBucketSpec{ + StorageClassName: testSCName, + Connection: &bktv1alpha1.Connection{ + Endpoint: &bktv1alpha1.Endpoint{ + BucketHost: object.BuildDomainName(testStoreName, testNamespace), + }, + }, + }, + Status: bktv1alpha1.ObjectBucketStatus{ + Phase: bktv1alpha1.ObjectBucketStatusPhaseBound, + }, + } + obc.Spec.ObjectBucketName = testBucketName + obc.Status.Phase = bktv1alpha1.ObjectBucketClaimStatusPhaseBound + objects := []runtime.Object{ + bucketNotification, + bucketTopic, + cephCluster, + obc, + ob, + } + + cl := fake.NewClientBuilder().WithScheme(s).WithRuntimeObjects(objects...).Build() + + r := &ReconcileNotifications{client: cl, context: c, opManagerContext: ctx} + + res, err := r.Reconcile(ctx, req) + assert.NoError(t, err) + assert.False(t, res.Requeue) + // notification configuration is set + err = r.client.Get(ctx, types.NamespacedName{Name: testNotificationName, Namespace: testNamespace}, bucketNotification) + assert.NoError(t, err, bucketNotification) + assert.True(t, createWasInvoked) + }) +} + +func TestGetCephObjectStoreName(t *testing.T) { + ob := bktv1alpha1.ObjectBucket{ + ObjectMeta: metav1.ObjectMeta{ + Name: testBucketName, + Namespace: testNamespace, + }, + TypeMeta: metav1.TypeMeta{ + Kind: "ObjectBucket", + }, + Spec: bktv1alpha1.ObjectBucketSpec{ + StorageClassName: testSCName, + Connection: &bktv1alpha1.Connection{ + Endpoint: &bktv1alpha1.Endpoint{ + BucketHost: "", + }, + }, + }, + Status: bktv1alpha1.ObjectBucketStatus{ + Phase: bktv1alpha1.ObjectBucketStatusPhaseBound, + }, + } + + t.Run("empty bucket host", func(t *testing.T) { + objectStore, err := getCephObjectStoreName(ob) + assert.Error(t, err) + assert.Empty(t, objectStore.Name) + }) + t.Run("malformed suffix", func(t *testing.T) { + ob.Spec.Connection.Endpoint.BucketHost = "rook-ceph-rgw-" + testStoreName + ".." + objectStore, err := getCephObjectStoreName(ob) + assert.Error(t, err) + assert.Empty(t, objectStore.Name) + }) + t.Run("malformed prefix", func(t *testing.T) { + ob.Spec.Connection.Endpoint.BucketHost = "rook-rgw-" + testStoreName + "." + testNamespace + ".svc" + objectStore, err := getCephObjectStoreName(ob) + assert.Error(t, err) + assert.Empty(t, objectStore.Name) + }) + t.Run("empty store name", func(t *testing.T) { + ob.Spec.Connection.Endpoint.BucketHost = "rook-ceph-rgw-" + "." + testNamespace + ".svc" + objectStore, err := getCephObjectStoreName(ob) + assert.Error(t, err) + assert.Empty(t, objectStore.Name) + }) + t.Run("store name contains rgw", func(t *testing.T) { + testStoreNameWithRGW := "my-rgw-store" + ob.Spec.Connection.Endpoint.BucketHost = "rook-ceph-rgw-" + testStoreNameWithRGW + "." + testNamespace + ".svc" + objectStore, err := getCephObjectStoreName(ob) + assert.NoError(t, err) + assert.Equal(t, testStoreNameWithRGW, objectStore.Name) + assert.Equal(t, testNamespace, objectStore.Namespace) + }) + t.Run("valid store name", func(t *testing.T) { + ob.Spec.Connection.Endpoint.BucketHost = "rook-ceph-rgw-" + testStoreName + "." + testNamespace + ".svc" + objectStore, err := getCephObjectStoreName(ob) + assert.NoError(t, err) + assert.Equal(t, testStoreName, objectStore.Name) + assert.Equal(t, testNamespace, objectStore.Namespace) + }) +} diff --git a/pkg/operator/ceph/object/notification/obc_label_controller.go b/pkg/operator/ceph/object/notification/obc_label_controller.go index 7e86435fe..15f20a4c1 100644 --- a/pkg/operator/ceph/object/notification/obc_label_controller.go +++ b/pkg/operator/ceph/object/notification/obc_label_controller.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package notification to manage a rook bucket notifications. package notification import ( @@ -24,9 +25,8 @@ import ( "github.com/pkg/errors" cephv1 "github.com/rook/rook/pkg/apis/ceph.rook.io/v1" "github.com/rook/rook/pkg/clusterd" - cephclient "github.com/rook/rook/pkg/daemon/ceph/client" - "github.com/rook/rook/pkg/operator/ceph/cluster/mon" opcontroller "github.com/rook/rook/pkg/operator/ceph/controller" + "github.com/rook/rook/pkg/operator/ceph/object/bucket" "github.com/rook/rook/pkg/operator/ceph/object/topic" kerrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/types" @@ -46,8 +46,6 @@ const ( type ReconcileOBCLabels struct { client client.Client context *clusterd.Context - clusterInfo *cephclient.ClusterInfo - clusterSpec *cephv1.ClusterSpec opManagerContext context.Context } @@ -96,6 +94,13 @@ func (r *ReconcileOBCLabels) reconcile(request reconcile.Request) (reconcile.Res return reconcile.Result{}, errors.Wrapf(err, "failed to retrieve ObjectBucketClaim %q", request.NamespacedName) } + // DELETE: the CR was deleted + if !obc.GetDeletionTimestamp().IsZero() { + logger.Debugf("ObjectBucketClaim %q was deleted", request.NamespacedName) + // Return and do not requeue. Successful deletion. + return reconcile.Result{}, nil + } + // reschedule if ObjectBucket was not created yet if obc.Spec.ObjectBucketName == "" { logger.Infof("ObjectBucketClaim %q resource did not create the bucket yet. will retry", request.NamespacedName) @@ -113,54 +118,25 @@ func (r *ReconcileOBCLabels) reconcile(request reconcile.Request) (reconcile.Res return reconcile.Result{}, errors.Wrapf(err, "failed to get object store from ObjectBucket %q", bucketName) } - // find the namespace for the ceph cluster (may be different than the namespace of the topic CR) - // Make sure a CephCluster is present otherwise do nothing - cephCluster, isReadyToReconcile, cephClusterExists, reconcileResponse := opcontroller.IsReadyToReconcile( - r.opManagerContext, - r.client, - types.NamespacedName{Namespace: objectStoreName.Namespace}, - controllerName, - ) - if !isReadyToReconcile { - // This handles the case where the Ceph Cluster is gone and we want to delete that CR - if !obc.GetDeletionTimestamp().IsZero() && !cephClusterExists { - // Return and do not requeue. Successful deletion. - return reconcile.Result{}, nil - } - logger.Debug("Ceph cluster not yet present") - return reconcileResponse, nil - } - r.clusterSpec = &cephCluster.Spec - - // DELETE: the CR was deleted - if !obc.GetDeletionTimestamp().IsZero() { - logger.Debugf("ObjectBucketClaim %q was deleted", request.NamespacedName) - // Return and do not requeue. Successful deletion. - return reconcile.Result{}, nil - } - // Populate clusterInfo during each reconcile - r.clusterInfo, _, _, err = mon.LoadClusterInfo(r.context, r.opManagerContext, cephCluster.Namespace) + clusterInfo, clusterSpec, err := getReadyCluster(r.client, r.opManagerContext, *r.context, objectStoreName.Namespace) if err != nil { - return reconcile.Result{}, errors.Wrap(err, "failed to populate cluster info") + return opcontroller.WaitForRequeueIfCephClusterNotReady, errors.Wrapf(err, "cluster is not ready") + } + if clusterInfo == nil || clusterSpec == nil { + return opcontroller.WaitForRequeueIfCephClusterNotReady, nil } // delete all existing notifications - provisioner := Provisioner{ - Client: r.client, - Context: r.context, - ClusterInfo: r.clusterInfo, - ClusterSpec: r.clusterSpec, + p := provisioner{ + context: r.context, + clusterInfo: clusterInfo, + clusterSpec: clusterSpec, opManagerContext: r.opManagerContext, + owner: ob.Spec.AdditionalState[bucket.CephUser], + objectStoreName: objectStoreName, } - session, err := provisioner.createSession( - ob.Spec.AdditionalState["cephUser"], - objectStoreName, - ) - if err != nil { - return reconcile.Result{}, errors.Wrapf(err, "failed to create session for bucket notification provisioning for ObjectBucketClaim %q", bucketName) - } - err = provisioner.DeleteAll(&ob, session) + err = deleteAllNotificationsFunc(p, &ob) if err != nil { return reconcile.Result{}, errors.Wrapf(err, "failed delete all bucket notifications from ObjectbucketClaim %q", bucketName) } @@ -185,19 +161,12 @@ func (r *ReconcileOBCLabels) reconcile(request reconcile.Request) (reconcile.Res return reconcile.Result{}, errors.Wrapf(err, "failed to retrieve CephBucketNotification %q", bnName) } - // verify that the associated topic configuration exists with an ARN - bucketTopic := &cephv1.CephBucketTopic{} - topicName := types.NamespacedName{Namespace: obc.Namespace, Name: notification.Spec.Topic} - if err := r.client.Get(r.opManagerContext, topicName, bucketTopic); err != nil { - if kerrors.IsNotFound(err) { - logger.Infof("CephBucketTopic %q not found", topicName) - return waitForRequeueIfTopicNotReady, nil - } - return reconcile.Result{}, errors.Wrapf(err, "failed to retrieve CephBucketTopic %q", topicName) - } - topicARN, err := topic.GetARN(bucketTopic) + // get the topic associated with the notification, and make sure it is provisioned + topicName := types.NamespacedName{Namespace: notification.Namespace, Name: notification.Spec.Topic} + bucketTopic, err := topic.GetProvisioned(r.client, r.opManagerContext, topicName) if err != nil { - return waitForRequeueIfTopicNotReady, errors.Wrapf(err, "CephBucketTopic %q not provisioned", topicName) + logger.Infof("CephBucketTopic %q not provisioned yet", topicName) + return waitForRequeueIfTopicNotReady, nil } if err = validateObjectStoreName(bucketTopic, objectStoreName); err != nil { @@ -205,7 +174,7 @@ func (r *ReconcileOBCLabels) reconcile(request reconcile.Request) (reconcile.Res } // provision the notification - err = provisioner.Create(&ob, topicARN, notification, session) + err = createNotificationFunc(p, &ob, *bucketTopic.Status.ARN, notification) if err != nil { return reconcile.Result{}, errors.Wrapf(err, "failed to provision CephBucketNotification %q", bnName) } diff --git a/pkg/operator/ceph/object/notification/obc_label_controller_test.go b/pkg/operator/ceph/object/notification/obc_label_controller_test.go new file mode 100644 index 000000000..c7fbaf362 --- /dev/null +++ b/pkg/operator/ceph/object/notification/obc_label_controller_test.go @@ -0,0 +1,268 @@ +/* +Copyright 2021 The Rook Authors. All rights reserved. + +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 notification to manage a rook bucket notifications. +package notification + +import ( + "context" + "os" + "testing" + + "github.com/coreos/pkg/capnslog" + bktv1alpha1 "github.com/kube-object-storage/lib-bucket-provisioner/pkg/apis/objectbucket.io/v1alpha1" + cephv1 "github.com/rook/rook/pkg/apis/ceph.rook.io/v1" + rookclient "github.com/rook/rook/pkg/client/clientset/versioned/fake" + "github.com/rook/rook/pkg/operator/test" + + "github.com/rook/rook/pkg/clusterd" + "github.com/rook/rook/pkg/operator/ceph/object" + "github.com/rook/rook/pkg/operator/k8sutil" + exectest "github.com/rook/rook/pkg/util/exec/test" + "github.com/stretchr/testify/assert" + v1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" + "k8s.io/client-go/kubernetes/scheme" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/reconcile" +) + +func TestCephBucketNotificationOBCLabelController(t *testing.T) { + mockSetup() + defer mockCleanup() + ctx := context.TODO() + capnslog.SetGlobalLogLevel(capnslog.DEBUG) + os.Setenv("ROOK_LOG_LEVEL", "DEBUG") + + bucketTopic := &cephv1.CephBucketTopic{ + ObjectMeta: metav1.ObjectMeta{ + Name: testTopicName, + Namespace: testNamespace, + }, + TypeMeta: metav1.TypeMeta{ + Kind: "CephBucketTopic", + }, + Spec: cephv1.BucketTopicSpec{ + ObjectStoreName: testStoreName, + ObjectStoreNamespace: testNamespace, + Endpoint: cephv1.TopicEndpointSpec{ + HTTP: &cephv1.HTTPEndpointSpec{ + URI: "http://localhost", + }, + }, + }, + Status: &cephv1.BucketTopicStatus{ARN: &testARN}, + } + bucketNotification := &cephv1.CephBucketNotification{ + ObjectMeta: metav1.ObjectMeta{ + Name: testNotificationName, + Namespace: testNamespace, + }, + TypeMeta: metav1.TypeMeta{ + Kind: "CephBucketNotification", + }, + Spec: cephv1.BucketNotificationSpec{ + Topic: testTopicName, + }, + } + cephCluster := &cephv1.CephCluster{ + ObjectMeta: metav1.ObjectMeta{ + Name: testNamespace, + Namespace: testNamespace, + }, + Status: cephv1.ClusterStatus{ + Phase: k8sutil.ReadyStatus, + CephStatus: &cephv1.CephStatus{ + Health: "HEALTH_OK", + }, + }, + } + obc := &bktv1alpha1.ObjectBucketClaim{ + ObjectMeta: metav1.ObjectMeta{ + Name: testBucketName, + Namespace: testNamespace, + Labels: map[string]string{ + notificationLabelPrefix + testNotificationName: testNotificationName, + }, + }, + TypeMeta: metav1.TypeMeta{ + Kind: "ObjectBucketClaim", + }, + Spec: bktv1alpha1.ObjectBucketClaimSpec{ + StorageClassName: testSCName, + GenerateBucketName: testBucketName, + }, + Status: bktv1alpha1.ObjectBucketClaimStatus{ + Phase: bktv1alpha1.ObjectBucketClaimStatusPhasePending, + }, + } + ob := &bktv1alpha1.ObjectBucket{ + ObjectMeta: metav1.ObjectMeta{ + Name: testBucketName, + Namespace: testNamespace, + }, + TypeMeta: metav1.TypeMeta{ + Kind: "ObjectBucket", + }, + Spec: bktv1alpha1.ObjectBucketSpec{ + StorageClassName: testSCName, + Connection: &bktv1alpha1.Connection{ + Endpoint: &bktv1alpha1.Endpoint{ + BucketHost: object.BuildDomainName(testStoreName, testNamespace), + }, + }, + }, + Status: bktv1alpha1.ObjectBucketStatus{ + Phase: bktv1alpha1.ObjectBucketStatusPhaseBound, + }, + } + req := reconcile.Request{ + NamespacedName: types.NamespacedName{ + Name: testBucketName, + Namespace: testNamespace, + }, + } + + s := scheme.Scheme + s.AddKnownTypes( + cephv1.SchemeGroupVersion, + &cephv1.CephBucketNotification{}, + &cephv1.CephBucketNotificationList{}, + &cephv1.CephBucketTopic{}, + &cephv1.CephBucketTopicList{}, + &cephv1.CephCluster{}, + &cephv1.CephClusterList{}, + &bktv1alpha1.ObjectBucketClaim{}, + &bktv1alpha1.ObjectBucketClaimList{}, + &bktv1alpha1.ObjectBucket{}, + &bktv1alpha1.ObjectBucketList{}, + ) + + c := &clusterd.Context{ + Executor: &exectest.MockExecutor{}, + RookClientset: rookclient.NewSimpleClientset(), + Clientset: test.New(t, 3), + } + + secrets := map[string][]byte{ + "fsid": []byte("name"), + "mon-secret": []byte("monsecret"), + "admin-secret": []byte("adminsecret"), + } + secret := &v1.Secret{ + ObjectMeta: metav1.ObjectMeta{ + Name: "rook-ceph-mon", + Namespace: testNamespace, + }, + Data: secrets, + Type: k8sutil.RookType, + } + + _, err := c.Clientset.CoreV1().Secrets(testNamespace).Create(ctx, secret, metav1.CreateOptions{}) + assert.NoError(t, err) + + t.Run("provision OBC with notification label with no ob", func(t *testing.T) { + objects := []runtime.Object{ + cephCluster, + obc, + } + + cl := fake.NewClientBuilder().WithScheme(s).WithRuntimeObjects(objects...).Build() + + r := &ReconcileOBCLabels{client: cl, context: c, opManagerContext: ctx} + + res, err := r.Reconcile(ctx, req) + assert.NoError(t, err) + assert.True(t, res.Requeue) + assert.False(t, createWasInvoked) + }) + + t.Run("provision OBC with notification label with not ready ob", func(t *testing.T) { + objects := []runtime.Object{ + cephCluster, + obc, + ob, + } + + cl := fake.NewClientBuilder().WithScheme(s).WithRuntimeObjects(objects...).Build() + + r := &ReconcileOBCLabels{client: cl, context: c, opManagerContext: ctx} + + res, err := r.Reconcile(ctx, req) + assert.NoError(t, err) + assert.True(t, res.Requeue) + assert.False(t, createWasInvoked) + }) + + obc.Spec.ObjectBucketName = testBucketName + obc.Status.Phase = bktv1alpha1.ObjectBucketClaimStatusPhaseBound + + t.Run("provision OBC with notification label with no notification", func(t *testing.T) { + objects := []runtime.Object{ + cephCluster, + obc, + ob, + } + + cl := fake.NewClientBuilder().WithScheme(s).WithRuntimeObjects(objects...).Build() + + r := &ReconcileOBCLabels{client: cl, context: c, opManagerContext: ctx} + + res, err := r.Reconcile(ctx, req) + assert.NoError(t, err) + assert.True(t, res.Requeue) + assert.False(t, createWasInvoked) + }) + + t.Run("provision OBC with notification label and notification with no topic", func(t *testing.T) { + objects := []runtime.Object{ + cephCluster, + obc, + ob, + bucketNotification, + } + + cl := fake.NewClientBuilder().WithScheme(s).WithRuntimeObjects(objects...).Build() + + r := &ReconcileOBCLabels{client: cl, context: c, opManagerContext: ctx} + + res, err := r.Reconcile(ctx, req) + assert.NoError(t, err) + assert.True(t, res.Requeue) + assert.False(t, createWasInvoked) + }) + + t.Run("provision OBC with notification label", func(t *testing.T) { + objects := []runtime.Object{ + cephCluster, + obc, + ob, + bucketNotification, + bucketTopic, + } + + cl := fake.NewClientBuilder().WithScheme(s).WithRuntimeObjects(objects...).Build() + + r := &ReconcileOBCLabels{client: cl, context: c, opManagerContext: ctx} + + res, err := r.Reconcile(ctx, req) + assert.NoError(t, err) + assert.False(t, res.Requeue) + assert.True(t, createWasInvoked) + }) +} diff --git a/pkg/operator/ceph/object/notification/provisioner.go b/pkg/operator/ceph/object/notification/provisioner.go index f7f533201..5e9c6a3c9 100644 --- a/pkg/operator/ceph/object/notification/provisioner.go +++ b/pkg/operator/ceph/object/notification/provisioner.go @@ -21,9 +21,6 @@ import ( "context" "net/http" - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/credentials" - awssession "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/s3" "github.com/ceph/go-ceph/rgw/admin" "github.com/coreos/pkg/capnslog" @@ -35,25 +32,23 @@ import ( "github.com/rook/rook/pkg/operator/ceph/object" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" - "sigs.k8s.io/controller-runtime/pkg/client" ) -type Provisioner struct { - Client client.Client - Context *clusterd.Context - ClusterInfo *cephclient.ClusterInfo - ClusterSpec *cephv1.ClusterSpec +type provisioner struct { + context *clusterd.Context + clusterInfo *cephclient.ClusterInfo + clusterSpec *cephv1.ClusterSpec opManagerContext context.Context + owner string + objectStoreName types.NamespacedName } -func (p *Provisioner) getCephUser(username string, objStore *cephv1.CephObjectStore, objContext *object.Context) (accessKey string, secretKey string, err error) { +func getUserCredentials(opManagerContext context.Context, username string, objStore *cephv1.CephObjectStore, objContext *object.Context) (accessKey string, secretKey string, err error) { if len(username) == 0 { err = errors.New("no user name provided") return } - // CephClusterSpec is needed for GetAdminOPSUserCredentials() - objContext.CephClusterSpec = *p.ClusterSpec adminAccessKey, adminSecretKey, err := object.GetAdminOPSUserCredentials(objContext, &objStore.Spec) if err != nil { err = errors.Wrapf(err, "failed to get Ceph RGW admin ops user credentials when getting user %q", username) @@ -67,7 +62,7 @@ func (p *Provisioner) getCephUser(username string, objStore *cephv1.CephObjectSt } var u admin.User - u, err = adminOpsClient.GetUser(p.opManagerContext, admin.User{ID: username}) + u, err = adminOpsClient.GetUser(opManagerContext, admin.User{ID: username}) if err != nil { err = errors.Wrapf(err, "failed to get ceph user %q", username) return @@ -79,61 +74,25 @@ func (p *Provisioner) getCephUser(username string, objStore *cephv1.CephObjectSt return } -func (p *Provisioner) createSession(owner string, objectStoreName types.NamespacedName) (*awssession.Session, error) { - objStore, err := p.Context.RookClientset.CephV1().CephObjectStores(objectStoreName.Namespace).Get(p.opManagerContext, objectStoreName.Name, metav1.GetOptions{}) +func newS3Agent(p provisioner) (*object.S3Agent, error) { + objStore, err := p.context.RookClientset.CephV1().CephObjectStores(p.objectStoreName.Namespace).Get(p.opManagerContext, p.objectStoreName.Name, metav1.GetOptions{}) if err != nil { - return nil, errors.Wrapf(err, "failed to get CephObjectStore %v", objectStoreName) + return nil, errors.Wrapf(err, "failed to get CephObjectStore %v", p.objectStoreName) } - objContext, err := object.NewMultisiteContext(p.Context, p.ClusterInfo, objStore) + objContext, err := object.NewMultisiteContext(p.context, p.clusterInfo, objStore) if err != nil { - return nil, errors.Wrapf(err, "failed to get object context for CephObjectStore %v", objectStoreName) + return nil, errors.Wrapf(err, "failed to get object context for CephObjectStore %v", p.objectStoreName) } + // CephClusterSpec is needed for GetAdminOPSUserCredentials() + objContext.CephClusterSpec = *p.clusterSpec - accessKey, secretKey, err := p.getCephUser(owner, objStore, objContext) + accessKey, secretKey, err := getUserCredentials(p.opManagerContext, p.owner, objStore, objContext) if err != nil { - return nil, errors.Wrapf(err, "failed to get owner credentials for %q", owner) + return nil, errors.Wrapf(err, "failed to get owner credentials for %q", p.owner) } - // pass log level to AWS session - logLevel := aws.LogOff - if logger.LevelAt(capnslog.DEBUG) { - logLevel = aws.LogDebugWithHTTPBody - } - - // pass TLS indication and certificates to AWS session - client := http.Client{ - Timeout: object.HttpTimeOut, - } - tlsEnabled := objStore.Spec.IsTLSEnabled() - if tlsEnabled { - tlsCert := objContext.Context.KubeConfig.CertData - if len(tlsCert) > 0 { - client.Transport = object.BuildTransportTLS(tlsCert, false) - } - } - - session, err := awssession.NewSession( - aws.NewConfig(). - WithHTTPClient(&client). - WithRegion(objContext.ZoneGroup). - WithCredentials(credentials.NewStaticCredentials(accessKey, secretKey, "")). - WithEndpoint(objContext.Endpoint). - WithMaxRetries(3). - WithDisableSSL(!tlsEnabled). - WithS3ForcePathStyle(true). - WithLogLevel(logLevel), - ) - if err != nil { - return nil, errors.Wrapf(err, "failed to create a new session for CephBucketNotification provisioning with %q", objectStoreName) - } - - logger.Debugf("session created. endpoint %q region %q secure %v", - *session.Config.Endpoint, - *session.Config.Region, - tlsEnabled, - ) - return session, nil + return object.NewS3Agent(accessKey, secretKey, objContext.Endpoint, objContext.ZoneGroup, logger.LevelAt(capnslog.DEBUG), objContext.Context.KubeConfig.CertData) } // TODO: convert all rules without restrictions once the AWS SDK supports that @@ -174,10 +133,17 @@ func createS3Events(events []cephv1.BucketNotificationEvent) []*string { return s3Events } -func (p *Provisioner) Create(bucket *bktv1alpha1.ObjectBucket, topicARN string, notification *cephv1.CephBucketNotification, sess *awssession.Session) error { +// Allow overriding this function for unit tests +var createNotificationFunc = createNotification + +var createNotification = func(p provisioner, bucket *bktv1alpha1.ObjectBucket, topicARN string, notification *cephv1.CephBucketNotification) error { bucketName := bucket.Spec.Endpoint.BucketName bnName := types.NamespacedName{Namespace: notification.Namespace, Name: notification.Name} - _, err := s3.New(sess).PutBucketNotificationConfiguration(&s3.PutBucketNotificationConfigurationInput{ + s3Agent, err := newS3Agent(p) + if err != nil { + return errors.Wrapf(err, "failed to create S3 agent for CephBucketNotification %q provisioning for bucket %q", bnName, bucketName) + } + _, err = s3Agent.Client.PutBucketNotificationConfiguration(&s3.PutBucketNotificationConfigurationInput{ Bucket: &bucketName, NotificationConfiguration: &s3.NotificationConfiguration{ TopicConfigurations: []*s3.TopicConfiguration{ @@ -199,9 +165,16 @@ func (p *Provisioner) Create(bucket *bktv1alpha1.ObjectBucket, topicARN string, return nil } -func (p *Provisioner) DeleteAll(bucket *bktv1alpha1.ObjectBucket, sess *awssession.Session) error { +// Allow overriding this function for unit tests +var deleteAllNotificationsFunc = deleteAllNotifications + +var deleteAllNotifications = func(p provisioner, bucket *bktv1alpha1.ObjectBucket) error { bucketName := types.NamespacedName{Namespace: bucket.Namespace, Name: bucket.Name} - if err := DeleteBucketNotification(s3.New(sess), &DeleteBucketNotificationRequestInput{ + s3Agent, err := newS3Agent(p) + if err != nil { + return errors.Wrapf(err, "failed to create S3 agent for deleting all bucket notifications from bucket %q", bucketName) + } + if err := DeleteBucketNotification(s3Agent.Client, &DeleteBucketNotificationRequestInput{ Bucket: &bucket.Spec.Endpoint.BucketName, }); err != nil { return errors.Wrapf(err, "failed to delete all bucket notifications from bucket %q", bucketName) diff --git a/pkg/operator/ceph/object/notification/s3ext.go b/pkg/operator/ceph/object/notification/s3ext.go index ab269e43b..7de5ce05f 100644 --- a/pkg/operator/ceph/object/notification/s3ext.go +++ b/pkg/operator/ceph/object/notification/s3ext.go @@ -66,7 +66,7 @@ func (s *DeleteBucketNotificationRequestInput) Validate() error { const opDeleteBucketNotification = "DeleteBucketNotification" -func DeleteBucketNotificationRequest(c *s3.S3, input *DeleteBucketNotificationRequestInput) (req *request.Request) { +func DeleteBucketNotificationRequest(c *s3.S3, input *DeleteBucketNotificationRequestInput) *request.Request { op := &request.Operation{ Name: opDeleteBucketNotification, HTTPMethod: http.MethodDelete, @@ -77,8 +77,7 @@ func DeleteBucketNotificationRequest(c *s3.S3, input *DeleteBucketNotificationRe input = &DeleteBucketNotificationRequestInput{} } - req = c.NewRequest(op, input, nil) - return + return c.NewRequest(op, input, nil) } func DeleteBucketNotification(c *s3.S3, input *DeleteBucketNotificationRequestInput) error { diff --git a/pkg/operator/ceph/object/rgw.go b/pkg/operator/ceph/object/rgw.go index f8e9e4049..030c32701 100644 --- a/pkg/operator/ceph/object/rgw.go +++ b/pkg/operator/ceph/object/rgw.go @@ -23,6 +23,7 @@ import ( "net/http" "reflect" "strconv" + "strings" "syscall" "github.com/banzaicloud/k8s-objectmatcher/patch" @@ -38,6 +39,7 @@ import ( v1 "k8s.io/api/core/v1" kerrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" ) @@ -315,6 +317,22 @@ func BuildDomainName(name, namespace string) string { return fmt.Sprintf("%s-%s.%s.%s", AppName, name, namespace, svcDNSSuffix) } +// ParseDomainName parse the name and namespace from the dns name +func ParseDomainName(domainName string) (types.NamespacedName, error) { + parsedDomain := strings.Split(domainName, ".") + if len(parsedDomain) != 3 || + parsedDomain[0] == "" || + parsedDomain[1] == "" || + parsedDomain[2] != svcDNSSuffix { + return types.NamespacedName{}, errors.Errorf("malformed domain name %q", domainName) + } + name := strings.TrimPrefix(parsedDomain[0], AppName+"-") + if name == parsedDomain[0] || name == "" { + return types.NamespacedName{}, errors.Errorf("malformed subdomain name %q", parsedDomain[0]) + } + return types.NamespacedName{Name: name, Namespace: parsedDomain[1]}, nil +} + // BuildDNSEndpoint build the dns name to reach out the service endpoint func BuildDNSEndpoint(domainName string, port int32, secure bool) string { httpPrefix := "http" diff --git a/pkg/operator/ceph/object/topic/controller.go b/pkg/operator/ceph/object/topic/controller.go index b18401294..9b27d0829 100644 --- a/pkg/operator/ceph/object/topic/controller.go +++ b/pkg/operator/ceph/object/topic/controller.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -// Package topic to manage a rook bucket notification topic. +// Package topic to manage a rook bucket topics. package topic import ( @@ -190,26 +190,30 @@ func (r *ReconcileBucketTopic) reconcile(request reconcile.Request) (reconcile.R } func (r *ReconcileBucketTopic) createCephBucketTopic(topic *cephv1.CephBucketTopic) (topicARN *string, err error) { - provisioner := Provisioner{ - Client: r.client, - Context: r.context, - ClusterInfo: r.clusterInfo, - ClusterSpec: r.clusterSpec, - opManagerContext: r.opManagerContext, - } - topicARN, err = provisioner.Create(topic) + topicARN, err = createTopicFunc( + provisioner{ + client: r.client, + context: r.context, + clusterInfo: r.clusterInfo, + clusterSpec: r.clusterSpec, + opManagerContext: r.opManagerContext, + }, + topic, + ) return } func (r *ReconcileBucketTopic) deleteCephBucketTopic(topic *cephv1.CephBucketTopic) error { - provisioner := Provisioner{ - Client: r.client, - Context: r.context, - ClusterInfo: r.clusterInfo, - ClusterSpec: r.clusterSpec, - opManagerContext: r.opManagerContext, - } - return provisioner.Delete(topic) + return deleteTopicFunc( + provisioner{ + client: r.client, + context: r.context, + clusterInfo: r.clusterInfo, + clusterSpec: r.clusterSpec, + opManagerContext: r.opManagerContext, + }, + topic, + ) } func (r *ReconcileBucketTopic) setFailedStatus(name types.NamespacedName, errMessage string, err error) (reconcile.Result, error) { diff --git a/pkg/operator/ceph/object/topic/controller_test.go b/pkg/operator/ceph/object/topic/controller_test.go new file mode 100644 index 000000000..c716b30fa --- /dev/null +++ b/pkg/operator/ceph/object/topic/controller_test.go @@ -0,0 +1,245 @@ +/* +Copyright 2021 The Rook Authors. All rights reserved. + +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 topic to manage a rook bucket topics. +package topic + +import ( + "context" + "os" + "testing" + "time" + + "github.com/coreos/pkg/capnslog" + cephv1 "github.com/rook/rook/pkg/apis/ceph.rook.io/v1" + rookclient "github.com/rook/rook/pkg/client/clientset/versioned/fake" + "github.com/rook/rook/pkg/operator/test" + + "github.com/rook/rook/pkg/clusterd" + cephclient "github.com/rook/rook/pkg/daemon/ceph/client" + "github.com/rook/rook/pkg/operator/k8sutil" + exectest "github.com/rook/rook/pkg/util/exec/test" + "github.com/stretchr/testify/assert" + v1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" + "k8s.io/client-go/kubernetes/scheme" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/reconcile" +) + +var ( + name = "topic-a" + namespace = "rook-ceph" + store = "test-store" + userCreateJSON = `{ + "user_id": "rgw-admin-ops-user", + "display_name": "RGW Admin Ops User", + "email": "", + "suspended": 0, + "max_buckets": 0, + "subusers": [], + "keys": [ + { + "user": "rgw-admin-ops-user", + "access_key": "EOE7FYCNOBZJ5VFV909G", + "secret_key": "qmIqpWm8HxCzmynCrD6U6vKWi4hnDBndOnmxXNsV" + } + ] + }` +) + +func TestCephBucketTopicController(t *testing.T) { + ctx := context.TODO() + capnslog.SetGlobalLogLevel(capnslog.DEBUG) + os.Setenv("ROOK_LOG_LEVEL", "DEBUG") + + bucketTopic := &cephv1.CephBucketTopic{ + ObjectMeta: metav1.ObjectMeta{ + Name: name, + Namespace: namespace, + }, + TypeMeta: metav1.TypeMeta{ + Kind: "CephBucketTopic", + }, + Spec: cephv1.BucketTopicSpec{ + ObjectStoreName: store, + ObjectStoreNamespace: namespace, + Endpoint: cephv1.TopicEndpointSpec{ + HTTP: &cephv1.HTTPEndpointSpec{ + URI: "http://localhost", + }, + }, + }, + } + clusterInfo := cephclient.AdminClusterInfo(namespace, "rook") + clusterSpec := cephv1.ClusterSpec{} + req := reconcile.Request{ + NamespacedName: types.NamespacedName{ + Name: name, + Namespace: namespace, + }, + } + + t.Run("do nothing since there is no CephCluster", func(t *testing.T) { + // Objects to track in the fake client. + objects := []runtime.Object{ + bucketTopic, + } + + c := &clusterd.Context{ + Executor: &exectest.MockExecutor{}, + RookClientset: rookclient.NewSimpleClientset(), + Clientset: test.New(t, 3), + } + + s := scheme.Scheme + s.AddKnownTypes(cephv1.SchemeGroupVersion, &cephv1.CephBucketTopic{}, &cephv1.CephBucketTopicList{}) + + cl := fake.NewClientBuilder().WithScheme(s).WithRuntimeObjects(objects...).Build() + + r := &ReconcileBucketTopic{client: cl, context: c, clusterInfo: clusterInfo, clusterSpec: &clusterSpec, opManagerContext: ctx} + + res, err := r.Reconcile(ctx, req) + assert.NoError(t, err) + assert.True(t, res.Requeue) + }) + + t.Run("CephCluster is not ready", func(t *testing.T) { + // Objects to track in the fake client. + objects := []runtime.Object{ + bucketTopic, + &cephv1.CephCluster{ + ObjectMeta: metav1.ObjectMeta{ + Name: namespace, + Namespace: namespace, + }, + Status: cephv1.ClusterStatus{ + Phase: "", + CephStatus: &cephv1.CephStatus{ + Health: "", + }, + }, + }, + } + + c := &clusterd.Context{ + Executor: &exectest.MockExecutor{}, + RookClientset: rookclient.NewSimpleClientset(), + Clientset: test.New(t, 3), + } + + s := scheme.Scheme + s.AddKnownTypes(cephv1.SchemeGroupVersion, &cephv1.CephBucketTopic{}, &cephv1.CephBucketTopicList{}, &cephv1.CephCluster{}, &cephv1.CephClusterList{}) + cl := fake.NewClientBuilder().WithScheme(s).WithRuntimeObjects(objects...).Build() + + r := &ReconcileBucketTopic{client: cl, context: c, clusterInfo: clusterInfo, clusterSpec: &clusterSpec, opManagerContext: ctx} + res, err := r.Reconcile(ctx, req) + assert.NoError(t, err) + assert.True(t, res.Requeue) + }) + + t.Run("creating a topic", func(t *testing.T) { + // Objects to track in the fake client. + objects := []runtime.Object{ + bucketTopic, + &cephv1.CephCluster{ + ObjectMeta: metav1.ObjectMeta{ + Name: namespace, + Namespace: namespace, + }, + Status: cephv1.ClusterStatus{ + Phase: k8sutil.ReadyStatus, + CephStatus: &cephv1.CephStatus{ + Health: "HEALTH_OK", + }, + }, + }, + } + + executor := &exectest.MockExecutor{ + MockExecuteCommandWithTimeout: func(timeout time.Duration, command string, args ...string) (string, error) { + if args[0] == "user" && args[1] == "create" { + return userCreateJSON, nil + } + return "", nil + }, + } + + c := &clusterd.Context{ + Executor: executor, + RookClientset: rookclient.NewSimpleClientset(), + Clientset: test.New(t, 3), + } + + secrets := map[string][]byte{ + "fsid": []byte("name"), + "mon-secret": []byte("monsecret"), + "admin-secret": []byte("adminsecret"), + } + secret := &v1.Secret{ + ObjectMeta: metav1.ObjectMeta{ + Name: "rook-ceph-mon", + Namespace: namespace, + }, + Data: secrets, + Type: k8sutil.RookType, + } + _, err := c.Clientset.CoreV1().Secrets(namespace).Create(ctx, secret, metav1.CreateOptions{}) + assert.NoError(t, err) + + s := scheme.Scheme + s.AddKnownTypes(cephv1.SchemeGroupVersion, &cephv1.CephBucketTopic{}, &cephv1.CephBucketTopicList{}, &cephv1.CephCluster{}, &cephv1.CephClusterList{}) + + cl := fake.NewClientBuilder().WithScheme(s).WithRuntimeObjects(objects...).Build() + + cephObjectStore := &cephv1.CephObjectStore{ + ObjectMeta: metav1.ObjectMeta{ + Name: store, + Namespace: namespace, + }, + TypeMeta: metav1.TypeMeta{ + Kind: "CephObjectStore"}, + Spec: cephv1.ObjectStoreSpec{ + Gateway: cephv1.GatewaySpec{ + Port: int32(80), + }, + }, + } + + _, err = c.RookClientset.CephV1().CephObjectStores(namespace).Create(ctx, cephObjectStore, metav1.CreateOptions{}) + assert.NoError(t, err) + r := &ReconcileBucketTopic{client: cl, context: c, clusterInfo: clusterInfo, clusterSpec: &clusterSpec, opManagerContext: ctx} + + err = r.client.Get(ctx, types.NamespacedName{Name: name, Namespace: namespace}, bucketTopic) + assert.NoError(t, err, bucketTopic) + + // mock the provisioner + expectedARN := "arn:aws:sns:" + store + "::" + bucketTopic.Name + createTopicFunc = func(p provisioner, topic *cephv1.CephBucketTopic) (*string, error) { + return &expectedARN, nil + } + defer func() { createTopicFunc = createTopic }() + res, err := r.Reconcile(ctx, req) + assert.NoError(t, err) + assert.False(t, res.Requeue) + err = r.client.Get(ctx, req.NamespacedName, bucketTopic) + assert.NoError(t, err) + assert.NotNil(t, bucketTopic.Status.ARN) + assert.Equal(t, *bucketTopic.Status.ARN, expectedARN) + }) +} diff --git a/pkg/operator/ceph/object/topic/provisioner.go b/pkg/operator/ceph/object/topic/provisioner.go index 588513bcd..f94bf8fbf 100644 --- a/pkg/operator/ceph/object/topic/provisioner.go +++ b/pkg/operator/ceph/object/topic/provisioner.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -// Package topic to manage a rook bucket notification topic. +// Package topic to manage a rook bucket topics. package topic import ( @@ -47,27 +47,28 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" ) -type Provisioner struct { - Client client.Client - Context *clusterd.Context - ClusterInfo *cephclient.ClusterInfo - ClusterSpec *cephv1.ClusterSpec +type provisioner struct { + client client.Client + context *clusterd.Context + clusterInfo *cephclient.ClusterInfo + clusterSpec *cephv1.ClusterSpec opManagerContext context.Context } -func (p *Provisioner) createSession(objectStoreName types.NamespacedName) (*awssession.Session, error) { - objStore, err := p.Context.RookClientset.CephV1().CephObjectStores(objectStoreName.Namespace).Get(p.opManagerContext, objectStoreName.Name, metav1.GetOptions{}) +// A new client type is needed here since topic management is part of AWS's Simple Notification Service (SNS) and not part of S3 +func createSNSClient(p provisioner, objectStoreName types.NamespacedName) (*sns.SNS, error) { + objStore, err := p.context.RookClientset.CephV1().CephObjectStores(objectStoreName.Namespace).Get(p.opManagerContext, objectStoreName.Name, metav1.GetOptions{}) if err != nil { return nil, errors.Wrapf(err, "failed to get CephObjectStore %v", objectStoreName) } - objContext, err := object.NewMultisiteContext(p.Context, p.ClusterInfo, objStore) + objContext, err := object.NewMultisiteContext(p.context, p.clusterInfo, objStore) if err != nil { return nil, errors.Wrapf(err, "failed to get object context for CephObjectStore %v", objectStoreName) } // CephClusterSpec is needed for GetAdminOPSUserCredentials() - objContext.CephClusterSpec = *p.ClusterSpec + objContext.CephClusterSpec = *p.clusterSpec accessKey, secretKey, err := object.GetAdminOPSUserCredentials(objContext, &objStore.Spec) if err != nil { return nil, errors.Wrap(err, "failed to get Ceph RGW admin ops user credentials") @@ -109,12 +110,7 @@ func (p *Provisioner) createSession(objectStoreName types.NamespacedName) (*awss *sess.Config.Region, tlsEnabled, ) - return sess, nil -} - -// A new client type is needed here since topic management is part of AWS's Simple Notification Service (SNS) and not part of S3 -func createSNSClient(sess *awssession.Session) (snsClient *sns.SNS) { - snsClient = sns.New(sess) + snsClient := sns.New(sess) // This is a hack to workaround the following RGW issue: https://tracker.ceph.com/issues/50039 // note that using: "github.com/aws/aws-sdk-go/private/signer/v2" // * would add the signature to the query and not the header @@ -142,16 +138,14 @@ func createSNSClient(sess *awssession.Session) (snsClient *sns.SNS) { } }, }) - return + return snsClient, nil } -func (p *Provisioner) Create(topic *cephv1.CephBucketTopic) (*string, error) { - nsName := types.NamespacedName{Name: topic.Name, Namespace: topic.Namespace} +// Allow overriding this function for unit tests +var createTopicFunc = createTopic - session, err := p.createSession(types.NamespacedName{Name: topic.Spec.ObjectStoreName, Namespace: topic.Spec.ObjectStoreNamespace}) - if err != nil { - return nil, errors.Wrapf(err, "failed to create session for CephBucketTopic %q provisioning", nsName) - } +func createTopic(p provisioner, topic *cephv1.CephBucketTopic) (*string, error) { + nsName := types.NamespacedName{Name: topic.Name, Namespace: topic.Namespace} attr := make(map[string]*string) @@ -184,7 +178,11 @@ func (p *Provisioner) Create(topic *cephv1.CephBucketTopic) (*string, error) { attr["verify-ssl"] = &verifySSL } - topicOutput, err := createSNSClient(session).CreateTopic(&sns.CreateTopicInput{ + snsClient, err := createSNSClient(p, types.NamespacedName{Name: topic.Spec.ObjectStoreName, Namespace: topic.Spec.ObjectStoreNamespace}) + if err != nil { + return nil, errors.Wrapf(err, "failed to create SNS client for CephBucketTopic %q provisioning", nsName) + } + topicOutput, err := snsClient.CreateTopic(&sns.CreateTopicInput{ Name: &topic.Name, Attributes: attr, }) @@ -198,7 +196,10 @@ func (p *Provisioner) Create(topic *cephv1.CephBucketTopic) (*string, error) { return topicOutput.TopicArn, nil } -func (p *Provisioner) Delete(topic *cephv1.CephBucketTopic) error { +// Allow overriding this function for unit tests +var deleteTopicFunc = deleteTopic + +func deleteTopic(p provisioner, topic *cephv1.CephBucketTopic) error { nsName := types.NamespacedName{Name: topic.Name, Namespace: topic.Namespace} logger.Infof("deleting CephBucketTopic %q", nsName) @@ -207,12 +208,12 @@ func (p *Provisioner) Delete(topic *cephv1.CephBucketTopic) error { return nil } - session, err := p.createSession(types.NamespacedName{Name: topic.Spec.ObjectStoreName, Namespace: topic.Spec.ObjectStoreNamespace}) + snsClient, err := createSNSClient(p, types.NamespacedName{Name: topic.Spec.ObjectStoreName, Namespace: topic.Spec.ObjectStoreNamespace}) if err != nil { - return errors.Wrapf(err, "failed to create session for CephBucketTopic %q deletion", nsName) + return errors.Wrapf(err, "failed to create SNS client for CephBucketTopic %q deletion", nsName) } - _, err = createSNSClient(session).DeleteTopic(&sns.DeleteTopicInput{TopicArn: topic.Status.ARN}) + _, err = snsClient.DeleteTopic(&sns.DeleteTopicInput{TopicArn: topic.Status.ARN}) if err != nil { if err.(awserr.Error).Code() != sns.ErrCodeNotFoundException { @@ -226,23 +227,26 @@ func (p *Provisioner) Delete(topic *cephv1.CephBucketTopic) error { return nil } -func GetARN(topic *cephv1.CephBucketTopic) (string, error) { - nsName := types.NamespacedName{Name: topic.Name, Namespace: topic.Namespace} - if topic.Status == nil || topic.Status.ARN == nil { - return "", errors.Errorf("no ARN in topic. CephBucketTopic %q was not provisioned yet", nsName) +func GetProvisioned(cl client.Client, ctx context.Context, topicName types.NamespacedName) (*cephv1.CephBucketTopic, error) { + bucketTopic := &cephv1.CephBucketTopic{} + if err := cl.Get(ctx, topicName, bucketTopic); err != nil { + return nil, errors.Wrapf(err, "failed to retrieve CephBucketTopic %q", topicName) } - topicARN := *topic.Status.ARN + if bucketTopic.Status == nil || bucketTopic.Status.ARN == nil { + return nil, errors.Errorf("no ARN in topic. CephBucketTopic %q was not provisioned yet", topicName) + } + topicARN := *bucketTopic.Status.ARN parsedTopicARN, err := arn.Parse(topicARN) if err != nil { - return topicARN, errors.Wrapf(err, "failed to parse CephBucketTopic %q ARN %q", nsName, topicARN) + return nil, errors.Wrapf(err, "failed to parse CephBucketTopic %q ARN %q", topicName, topicARN) } if strings.ToLower(parsedTopicARN.Service) != "sns" { - return topicARN, errors.Errorf("CephBucketTopic %q ARN %q must have 'sns' service", nsName, topicARN) + return nil, errors.Errorf("CephBucketTopic %q ARN %q must have 'sns' service", topicName, topicARN) } if parsedTopicARN.Resource == "" { - return topicARN, errors.Errorf("CephBucketTopic %q is missing a topic inside ARN %q", nsName, topicARN) + return nil, errors.Errorf("CephBucketTopic %q is missing a topic inside ARN %q", topicName, topicARN) } - logger.Debugf("CephBucketTopic %q found with valid ARN %q", nsName, topicARN) + logger.Debugf("CephBucketTopic %q found with valid ARN %q", topicName, topicARN) - return topicARN, nil + return bucketTopic, nil }