From c98628eb0fffdbd5d82b0b161bb25ac6673e88c5 Mon Sep 17 00:00:00 2001 From: Jiffin Tony Thottan Date: Tue, 2 Aug 2022 18:39:25 +0530 Subject: [PATCH] rgw: delete zone/pools for multisite configuation Allow option to delete the zone/pools created by ceph object zone CR. Signed-off-by: Jiffin Tony Thottan --- .../ceph-object-multisite-crd.md | 13 +- .../Object-Storage/ceph-object-store-crd.md | 4 + .../charts/rook-ceph/templates/resources.yaml | 158 +++++ deploy/examples/crds.yaml | 158 +++++ deploy/examples/object-multisite-test.yaml | 2 + deploy/examples/object-multisite.yaml | 2 + design/ceph/object/ceph-multisite-overview.md | 3 + design/ceph/object/zone.md | 22 +- pkg/apis/ceph.rook.io/v1/object.go | 4 + pkg/apis/ceph.rook.io/v1/types.go | 8 +- .../ceph.rook.io/v1/zz_generated.deepcopy.go | 21 +- pkg/operator/ceph/object/admin.go | 1 - pkg/operator/ceph/object/dependents.go | 61 +- pkg/operator/ceph/object/dependents_test.go | 632 +++++++++++++++++- pkg/operator/ceph/object/objectstore.go | 48 +- pkg/operator/ceph/object/objectstore_test.go | 2 +- pkg/operator/ceph/object/rgw.go | 6 +- pkg/operator/ceph/object/rgw_test.go | 8 +- pkg/operator/ceph/object/zone/controller.go | 171 ++++- pkg/operator/ceph/object/zone/dependents.go | 57 ++ .../ceph/object/zone/dependents_test.go | 112 ++++ 21 files changed, 1432 insertions(+), 61 deletions(-) create mode 100644 pkg/operator/ceph/object/zone/dependents.go create mode 100644 pkg/operator/ceph/object/zone/dependents_test.go diff --git a/Documentation/CRDs/Object-Storage/ceph-object-multisite-crd.md b/Documentation/CRDs/Object-Storage/ceph-object-multisite-crd.md index 80a8fa5ea..8a22065c9 100644 --- a/Documentation/CRDs/Object-Storage/ceph-object-multisite-crd.md +++ b/Documentation/CRDs/Object-Storage/ceph-object-multisite-crd.md @@ -86,6 +86,7 @@ spec: codingChunks: 1 customEndpoints: - "http://rgw-a.fqdn" + preservePoolsOnDelete: true ``` ### Object Zone Settings @@ -106,8 +107,14 @@ The pools allow all of the settings defined in the Pool CRD spec. For more detai * `dataPool`: The settings to create the object store data pool. Can use replication or erasure coding. * `customEndpoints`: Specify the endpoint(s) that will accept multisite replication traffic for this zone. You may include the port in the definition if necessary. For example: "https://my-object-store.my-domain.net:443". By default, Rook will set this to the DNS name of the ClusterIP Service created for the CephObjectStore that corresponds to this zone. - Most multisite configurations will not exist within the same Kubernetes cluster, meaning the default value will not be useful. In these cases, you will be required to create your own custom ingress resource for the CephObjectStore in order to make the zone available for replication. You must add the endpoint for your custom ingress resource to this list to allow the store to accept replication traffic. + Most multisite configurations will not exist within the same Kubernetes cluster, meaning the default value will not be useful. In these cases, you will be required to create your own custom ingress resource for the CephObjectStore in order to make the zone available for replication. You must add the endpoint for your custom ingress resource to this list to allow the store to accept replication traffic. - In the case of multiple stores (or multiple endpoints for a single store), you are not required to put all endpoints in this list. Only specify the endpoints that should be used for replication traffic. + In the case of multiple stores (or multiple endpoints for a single store), you are not required to put all endpoints in this list. Only specify the endpoints that should be used for replication traffic. - If you update `customEndpoints` to return to an empty list, you must the Rook operator to automatically add the CephObjectStore service endpoint to Ceph's internal configuration. + If you update `customEndpoints` to return to an empty list, you must the Rook operator to automatically add the CephObjectStore service endpoint to Ceph's internal configuration. + + * `preservePoolsOnDelete`: If it is set to 'true' the pools used to support the CephObjectZone will remain when it is deleted. This is a security measure to avoid accidental loss of data. It is set to 'true' by default. + + It is better to check whether data synced with other peer zones before triggering the deletion to avoid accidental loss of data via steps mentioned [here](https://docs.ceph.com/en/latest/radosgw/multisite/#check-synchronization-status) + + When deleting a CephObjectZone, deletion will be blocked until all `CephObjectStores` belonging to the zone are removed. diff --git a/Documentation/CRDs/Object-Storage/ceph-object-store-crd.md b/Documentation/CRDs/Object-Storage/ceph-object-store-crd.md index f509af9ca..babc909be 100644 --- a/Documentation/CRDs/Object-Storage/ceph-object-store-crd.md +++ b/Documentation/CRDs/Object-Storage/ceph-object-store-crd.md @@ -260,3 +260,7 @@ Rook will warn about which buckets are blocking deletion in three ways: 1. An event will be registered on the CephObjectStore resource 1. A status condition will be added to the CephObjectStore resource 1. An error will be added to the Rook Ceph Operator log + +If the CephObjectStore is configured in a [multisite setup](ceph-object-multisite-crd.md) the above conditions are applicable only to stores that belong to a single master zone. +Otherwise the conditions are ignored. Even if the store is removed the user can access the +data from a peer object store. diff --git a/deploy/charts/rook-ceph/templates/resources.yaml b/deploy/charts/rook-ceph/templates/resources.yaml index 6456ba6fa..4f9b4ad31 100644 --- a/deploy/charts/rook-ceph/templates/resources.yaml +++ b/deploy/charts/rook-ceph/templates/resources.yaml @@ -572,6 +572,28 @@ spec: status: description: Status represents the status of an object properties: + conditions: + items: + description: Condition represents a status condition on any Rook-Ceph Custom Resource. + properties: + lastHeartbeatTime: + format: date-time + type: string + lastTransitionTime: + format: date-time + type: string + message: + type: string + reason: + description: ConditionReason is a reason for a condition + type: string + status: + type: string + type: + description: ConditionType represent a resource's status + type: string + type: object + type: array observedGeneration: description: ObservedGeneration is the latest generation observed by the controller. format: int64 @@ -5108,6 +5130,28 @@ spec: status: description: Status represents the status of an object properties: + conditions: + items: + description: Condition represents a status condition on any Rook-Ceph Custom Resource. + properties: + lastHeartbeatTime: + format: date-time + type: string + lastTransitionTime: + format: date-time + type: string + message: + type: string + reason: + description: ConditionReason is a reason for a condition + type: string + status: + type: string + type: + description: ConditionType represent a resource's status + type: string + type: object + type: array observedGeneration: description: ObservedGeneration is the latest generation observed by the controller. format: int64 @@ -8283,6 +8327,28 @@ spec: status: description: Status represents the status of an object properties: + conditions: + items: + description: Condition represents a status condition on any Rook-Ceph Custom Resource. + properties: + lastHeartbeatTime: + format: date-time + type: string + lastTransitionTime: + format: date-time + type: string + message: + type: string + reason: + description: ConditionReason is a reason for a condition + type: string + status: + type: string + type: + description: ConditionType represent a resource's status + type: string + type: object + type: array observedGeneration: description: ObservedGeneration is the latest generation observed by the controller. format: int64 @@ -8351,6 +8417,28 @@ spec: status: description: Status represents the status of an object properties: + conditions: + items: + description: Condition represents a status condition on any Rook-Ceph Custom Resource. + properties: + lastHeartbeatTime: + format: date-time + type: string + lastTransitionTime: + format: date-time + type: string + message: + type: string + reason: + description: ConditionReason is a reason for a condition + type: string + status: + type: string + type: + description: ConditionType represent a resource's status + type: string + type: object + type: array observedGeneration: description: ObservedGeneration is the latest generation observed by the controller. format: int64 @@ -10058,6 +10146,28 @@ spec: status: description: Status represents the status of an object properties: + conditions: + items: + description: Condition represents a status condition on any Rook-Ceph Custom Resource. + properties: + lastHeartbeatTime: + format: date-time + type: string + lastTransitionTime: + format: date-time + type: string + message: + type: string + reason: + description: ConditionReason is a reason for a condition + type: string + status: + type: string + type: + description: ConditionType represent a resource's status + type: string + type: object + type: array observedGeneration: description: ObservedGeneration is the latest generation observed by the controller. format: int64 @@ -10450,6 +10560,10 @@ spec: type: object x-kubernetes-preserve-unknown-fields: true type: object + preservePoolsOnDelete: + default: true + description: Preserve pools on object zone deletion + type: boolean zoneGroup: description: The display name for the ceph users type: string @@ -10461,6 +10575,28 @@ spec: status: description: Status represents the status of an object properties: + conditions: + items: + description: Condition represents a status condition on any Rook-Ceph Custom Resource. + properties: + lastHeartbeatTime: + format: date-time + type: string + lastTransitionTime: + format: date-time + type: string + message: + type: string + reason: + description: ConditionReason is a reason for a condition + type: string + status: + type: string + type: + description: ConditionType represent a resource's status + type: string + type: object + type: array observedGeneration: description: ObservedGeneration is the latest generation observed by the controller. format: int64 @@ -11123,6 +11259,28 @@ spec: status: description: Status represents the status of an object properties: + conditions: + items: + description: Condition represents a status condition on any Rook-Ceph Custom Resource. + properties: + lastHeartbeatTime: + format: date-time + type: string + lastTransitionTime: + format: date-time + type: string + message: + type: string + reason: + description: ConditionReason is a reason for a condition + type: string + status: + type: string + type: + description: ConditionType represent a resource's status + type: string + type: object + type: array observedGeneration: description: ObservedGeneration is the latest generation observed by the controller. format: int64 diff --git a/deploy/examples/crds.yaml b/deploy/examples/crds.yaml index 59833c652..d3f526389 100644 --- a/deploy/examples/crds.yaml +++ b/deploy/examples/crds.yaml @@ -573,6 +573,28 @@ spec: status: description: Status represents the status of an object properties: + conditions: + items: + description: Condition represents a status condition on any Rook-Ceph Custom Resource. + properties: + lastHeartbeatTime: + format: date-time + type: string + lastTransitionTime: + format: date-time + type: string + message: + type: string + reason: + description: ConditionReason is a reason for a condition + type: string + status: + type: string + type: + description: ConditionType represent a resource's status + type: string + type: object + type: array observedGeneration: description: ObservedGeneration is the latest generation observed by the controller. format: int64 @@ -5105,6 +5127,28 @@ spec: status: description: Status represents the status of an object properties: + conditions: + items: + description: Condition represents a status condition on any Rook-Ceph Custom Resource. + properties: + lastHeartbeatTime: + format: date-time + type: string + lastTransitionTime: + format: date-time + type: string + message: + type: string + reason: + description: ConditionReason is a reason for a condition + type: string + status: + type: string + type: + description: ConditionType represent a resource's status + type: string + type: object + type: array observedGeneration: description: ObservedGeneration is the latest generation observed by the controller. format: int64 @@ -8277,6 +8321,28 @@ spec: status: description: Status represents the status of an object properties: + conditions: + items: + description: Condition represents a status condition on any Rook-Ceph Custom Resource. + properties: + lastHeartbeatTime: + format: date-time + type: string + lastTransitionTime: + format: date-time + type: string + message: + type: string + reason: + description: ConditionReason is a reason for a condition + type: string + status: + type: string + type: + description: ConditionType represent a resource's status + type: string + type: object + type: array observedGeneration: description: ObservedGeneration is the latest generation observed by the controller. format: int64 @@ -8344,6 +8410,28 @@ spec: status: description: Status represents the status of an object properties: + conditions: + items: + description: Condition represents a status condition on any Rook-Ceph Custom Resource. + properties: + lastHeartbeatTime: + format: date-time + type: string + lastTransitionTime: + format: date-time + type: string + message: + type: string + reason: + description: ConditionReason is a reason for a condition + type: string + status: + type: string + type: + description: ConditionType represent a resource's status + type: string + type: object + type: array observedGeneration: description: ObservedGeneration is the latest generation observed by the controller. format: int64 @@ -10048,6 +10136,28 @@ spec: status: description: Status represents the status of an object properties: + conditions: + items: + description: Condition represents a status condition on any Rook-Ceph Custom Resource. + properties: + lastHeartbeatTime: + format: date-time + type: string + lastTransitionTime: + format: date-time + type: string + message: + type: string + reason: + description: ConditionReason is a reason for a condition + type: string + status: + type: string + type: + description: ConditionType represent a resource's status + type: string + type: object + type: array observedGeneration: description: ObservedGeneration is the latest generation observed by the controller. format: int64 @@ -10439,6 +10549,10 @@ spec: type: object x-kubernetes-preserve-unknown-fields: true type: object + preservePoolsOnDelete: + default: true + description: Preserve pools on object zone deletion + type: boolean zoneGroup: description: The display name for the ceph users type: string @@ -10450,6 +10564,28 @@ spec: status: description: Status represents the status of an object properties: + conditions: + items: + description: Condition represents a status condition on any Rook-Ceph Custom Resource. + properties: + lastHeartbeatTime: + format: date-time + type: string + lastTransitionTime: + format: date-time + type: string + message: + type: string + reason: + description: ConditionReason is a reason for a condition + type: string + status: + type: string + type: + description: ConditionType represent a resource's status + type: string + type: object + type: array observedGeneration: description: ObservedGeneration is the latest generation observed by the controller. format: int64 @@ -11111,6 +11247,28 @@ spec: status: description: Status represents the status of an object properties: + conditions: + items: + description: Condition represents a status condition on any Rook-Ceph Custom Resource. + properties: + lastHeartbeatTime: + format: date-time + type: string + lastTransitionTime: + format: date-time + type: string + message: + type: string + reason: + description: ConditionReason is a reason for a condition + type: string + status: + type: string + type: + description: ConditionType represent a resource's status + type: string + type: object + type: array observedGeneration: description: ObservedGeneration is the latest generation observed by the controller. format: int64 diff --git a/deploy/examples/object-multisite-test.yaml b/deploy/examples/object-multisite-test.yaml index 8e7fe4a7f..74575be6c 100644 --- a/deploy/examples/object-multisite-test.yaml +++ b/deploy/examples/object-multisite-test.yaml @@ -38,6 +38,8 @@ spec: # recommended to set this value if ingress used for exposing rgw endpoints # customEndpoints: # - "http://rgw-a.fqdn" + # if the pools need to be removed from backend enable following setting + # preservePoolsOnDelete: false --- apiVersion: ceph.rook.io/v1 kind: CephObjectStore diff --git a/deploy/examples/object-multisite.yaml b/deploy/examples/object-multisite.yaml index c391a7627..a835983f6 100644 --- a/deploy/examples/object-multisite.yaml +++ b/deploy/examples/object-multisite.yaml @@ -40,6 +40,8 @@ spec: # customEndpoints: # - "http://rgw-a.fqdn" # - "http://rgw-b.fqdn" + # if the pools need to be removed from backend enable following setting + # preservePoolsOnDelete: false --- apiVersion: ceph.rook.io/v1 kind: CephObjectStore diff --git a/design/ceph/object/ceph-multisite-overview.md b/design/ceph/object/ceph-multisite-overview.md index 4ac040b82..214e1ed9e 100644 --- a/design/ceph/object/ceph-multisite-overview.md +++ b/design/ceph/object/ceph-multisite-overview.md @@ -48,6 +48,9 @@ To enable Ceph's multisite, the following steps need to happen. 3. A master zone in the master zone group needs to be created 4. An object store needs to be added to the master zone +### Master Zone/Zonegroup +The master zone of the master zonegroup is designated as the 'metadata master zone', and all changes to user and bucket metadata are written through that zone first before replicating to other zones via metadata sync. This is different from data sync, where objects can be written to any zone and replicated to its peers in the zonegroup. + ## Rook Ceph Multisite Steps 1. If an admin is creating a new realm on a Rook Ceph cluster, the admin should create: diff --git a/design/ceph/object/zone.md b/design/ceph/object/zone.md index cb84004ad..1073811c4 100644 --- a/design/ceph/object/zone.md +++ b/design/ceph/object/zone.md @@ -40,6 +40,7 @@ spec: codingChunks: 2 customEndpoints: - "http://zone-a.fqdn" + preservePoolsOnDelete: true ``` Now create the ceph-object-zone. @@ -70,7 +71,7 @@ The order in which these resources are created is not important. When the storage admin is ready to sync data from another Ceph cluster with multisite set up (primary cluster) to a Rook Ceph cluster (pulling cluster), the pulling cluster will have a newly created in the zone group from the primary cluster. -A [ceph-object-pull-realm](/design/object/ceph-object-pull-realm.md) resource must be created to pull the realm information from the primary cluster to the pulling cluster. +A [ceph-object-pull-realm](/design/ceph/object/ceph-object-pull-realm.md) resource must be created to pull the realm information from the primary cluster to the pulling cluster. Once the ceph-object-pull-realm is configured a ceph-object-zone must be created. @@ -78,11 +79,21 @@ After an ceph-object-store is configured to be in this ceph-object-zone, the all ## Deleting and Reconfiguring the Ceph Object Zone -At the moment creating an ceph-object-zone resource only handles Day 1 initial configuration for the zone. +At the moment creating a CephObjectZone resource does not handle configuration updates for the zone. -Changes made to the resource's configuration or deletion of the resource are not reflected on the Ceph cluster. +By default when a CephObjectZone is deleted, the pools supporting the zone are not deleted from the Ceph cluster. But if `preservePoolsOnDelete` is set to false, then pools are deleted from the Ceph cluster. -To be clear, when the ceph-object-zone resource is deleted or modified, the zone is not deleted from the Ceph cluster. Zone deletion must be done through the toolbox. +A CephObjectZone will be removed only if all CephObjectStores that reference the zone are deleted first. + +### Deleting CephObjectStores in a multisite configuration + +One of the following scenarios is possible when deleting a CephObjectStore in a multisite configuration. Rook's behavior is noted after each scenario. +1. The store belongs to a [master zone](/design/ceph/object/ceph-multisite-overview.md/#master-zonezonegroup) that has no other peers. + - This case is essentially the same as deleting a CephObjectStore outside of a multisite configuration; Rook should check for dependents before deleting the store +2. The store belongs to a master zone that has other peers + - Rook will error on this condition with a message instructing the user to manually set another zone as the master zone once that zone has all data backed up to it +3. The store is a non-master peer + - Rook will not check for dependents in this case, as the data in the master zone is assumed to have a copy of all user data ### Deleting Zone through Toolboxes @@ -134,6 +145,8 @@ The following variables can be configured in the ceph-object-zone resource. - `customEndpoints`: Specify the endpoint(s) that will accept multisite replication traffic for this zone. You may include the port in the definition if necessary. For example: "https://my-object-store.my-domain.net:443". +- `preservePoolsOnDelete`: If it is set to 'true' the pools used to support the zone will remain when the CephObjectZone is deleted. This is a security measure to avoid accidental loss of data. It is set to 'true' by default. If not specified it is also deemed as 'true'. + ```yaml apiVersion: ceph.rook.io/v1alpha1 kind: CephObjectZone @@ -153,6 +166,7 @@ spec: codingChunks: 2 customEndpoints: - "http://rgw-a.fqdn" + preservePoolsOnDelete: true ``` ### Pools diff --git a/pkg/apis/ceph.rook.io/v1/object.go b/pkg/apis/ceph.rook.io/v1/object.go index c8ce342cc..903bacf54 100644 --- a/pkg/apis/ceph.rook.io/v1/object.go +++ b/pkg/apis/ceph.rook.io/v1/object.go @@ -109,3 +109,7 @@ func (s *ObjectStoreSpec) GetServiceServingCert() string { func (c *CephObjectStore) GetStatusConditions() *[]Condition { return &c.Status.Conditions } + +func (z *CephObjectZone) GetStatusConditions() *[]Condition { + return &z.Status.Conditions +} diff --git a/pkg/apis/ceph.rook.io/v1/types.go b/pkg/apis/ceph.rook.io/v1/types.go index 1ccdac3d1..3f3472175 100755 --- a/pkg/apis/ceph.rook.io/v1/types.go +++ b/pkg/apis/ceph.rook.io/v1/types.go @@ -864,7 +864,8 @@ type Status struct { Phase string `json:"phase,omitempty"` // ObservedGeneration is the latest generation observed by the controller. // +optional - ObservedGeneration int64 `json:"observedGeneration,omitempty"` + ObservedGeneration int64 `json:"observedGeneration,omitempty"` + Conditions []Condition `json:"conditions,omitempty"` } // ReplicatedSpec represents the spec for replication in a pool @@ -1673,6 +1674,11 @@ type ObjectZoneSpec struct { // +nullable // +optional CustomEndpoints []string `json:"customEndpoints,omitempty"` + + // Preserve pools on object zone deletion + // +optional + // +kubebuilder:default=true + PreservePoolsOnDelete bool `json:"preservePoolsOnDelete"` } // CephBucketTopic represents a Ceph Object Topic for Bucket Notifications diff --git a/pkg/apis/ceph.rook.io/v1/zz_generated.deepcopy.go b/pkg/apis/ceph.rook.io/v1/zz_generated.deepcopy.go index e384ccd96..721906dac 100644 --- a/pkg/apis/ceph.rook.io/v1/zz_generated.deepcopy.go +++ b/pkg/apis/ceph.rook.io/v1/zz_generated.deepcopy.go @@ -448,7 +448,7 @@ func (in *CephBucketNotification) DeepCopyInto(out *CephBucketNotification) { if in.Status != nil { in, out := &in.Status, &out.Status *out = new(Status) - **out = **in + (*in).DeepCopyInto(*out) } return } @@ -911,7 +911,7 @@ func (in *CephFilesystemMirror) DeepCopyInto(out *CephFilesystemMirror) { if in.Status != nil { in, out := &in.Status, &out.Status *out = new(Status) - **out = **in + (*in).DeepCopyInto(*out) } return } @@ -1136,7 +1136,7 @@ func (in *CephNFS) DeepCopyInto(out *CephNFS) { if in.Status != nil { in, out := &in.Status, &out.Status *out = new(Status) - **out = **in + (*in).DeepCopyInto(*out) } return } @@ -1201,7 +1201,7 @@ func (in *CephObjectRealm) DeepCopyInto(out *CephObjectRealm) { if in.Status != nil { in, out := &in.Status, &out.Status *out = new(Status) - **out = **in + (*in).DeepCopyInto(*out) } return } @@ -1396,7 +1396,7 @@ func (in *CephObjectZone) DeepCopyInto(out *CephObjectZone) { if in.Status != nil { in, out := &in.Status, &out.Status *out = new(Status) - **out = **in + (*in).DeepCopyInto(*out) } return } @@ -1428,7 +1428,7 @@ func (in *CephObjectZoneGroup) DeepCopyInto(out *CephObjectZoneGroup) { if in.Status != nil { in, out := &in.Status, &out.Status *out = new(Status) - **out = **in + (*in).DeepCopyInto(*out) } return } @@ -1526,7 +1526,7 @@ func (in *CephRBDMirror) DeepCopyInto(out *CephRBDMirror) { if in.Status != nil { in, out := &in.Status, &out.Status *out = new(Status) - **out = **in + (*in).DeepCopyInto(*out) } return } @@ -3871,6 +3871,13 @@ func (in *StatesSpec) DeepCopy() *StatesSpec { // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Status) DeepCopyInto(out *Status) { *out = *in + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]Condition, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } return } diff --git a/pkg/operator/ceph/object/admin.go b/pkg/operator/ceph/object/admin.go index fa777a082..b6db1e743 100644 --- a/pkg/operator/ceph/object/admin.go +++ b/pkg/operator/ceph/object/admin.go @@ -250,7 +250,6 @@ func runAdminCommand(c *Context, expectJSON bool, args ...string) (string, error fmt.Sprintf("--rgw-zonegroup=%s", c.ZoneGroup), fmt.Sprintf("--rgw-zone=%s", c.Zone), } - args = append(args, options...) } diff --git a/pkg/operator/ceph/object/dependents.go b/pkg/operator/ceph/object/dependents.go index cf7d6cb4b..bba074993 100644 --- a/pkg/operator/ceph/object/dependents.go +++ b/pkg/operator/ceph/object/dependents.go @@ -27,7 +27,10 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) -const bucketDependentType = "buckets in the object store (could be from ObjectBucketClaims or COSI Buckets)" +const ( + bucketDependentType = "buckets in the object store (could be from ObjectBucketClaims or COSI Buckets)" + zoneIsMasterWithPeersDependentType = "zone is master and has peers" +) // CephObjectStoreDependents returns the buckets which exist in the object store that should block // deletion. @@ -44,6 +47,34 @@ func CephObjectStoreDependents( deps := dependents.NewDependentList() + if store.Spec.IsMultisite() { + // stores in multisite configs have different conditions that change what dependents should be checked + zoneIsMaster, err := CheckZoneIsMaster(objCtx) + if err != nil { + return deps, errors.Wrapf(err, baseErrMsg) + } + if !zoneIsMaster { + // zone is a peer, and the master is the source of truth + // we assume master is up-to-date and this peer can be deleted safely + // without checking for bucket dependents + return deps, nil + } + + // check whether any peer zone exists + err = getMasterZoneDependents(deps, clusterdCtx, clusterInfo, store, objCtx) + if err != nil { + return deps, errors.Wrapf(err, "%s. failed to check multisite dependents", baseErrMsg) + } + if !deps.Empty() { + // zone is master with peers; require user intervention + logger.Errorf("%s. Either change the master or remove its peers before the deletion", zoneIsMasterWithPeersDependentType) + return deps, errors.Errorf("%s: %q\nall peer zones must be deleted, or a peer zone must be manually set as the master zone after that peer has all necessary data synched to it", zoneIsMasterWithPeersDependentType, deps.OfKind(zoneIsMasterWithPeersDependentType)) + } + + // this is a master zone with NO peers. it is the last store that has this data, + // so we should prevent users from accidentally deleting it by continuing to check for buckets + } + // NOTE: we should still check for buckets when the RGW connection is external since we have no // way of knowing if the bucket was created due to an ObjectBucketClaim or COSI Bucket. err := getBucketDependents(deps, clusterdCtx, clusterInfo, store, objCtx, opsCtx) @@ -106,3 +137,31 @@ func getBucketDependents( return nil } + +func getMasterZoneDependents( + deps *dependents.DependentList, + clusterdCtx *clusterd.Context, + clusterInfo *client.ClusterInfo, + store *v1.CephObjectStore, + objContext *Context, +) error { + realmArg := fmt.Sprintf("--rgw-realm=%s", objContext.Realm) + zoneGroupArg := fmt.Sprintf("--rgw-zonegroup=%s", objContext.ZoneGroup) + zoneGroupOutput, err := RunAdminCommandNoMultisite(objContext, true, "zonegroup", "get", realmArg, zoneGroupArg) + if err != nil { + return errors.Wrapf(err, "failed to fetch zonegroup %q", objContext.ZoneGroup) + } + zoneGroupJson, err := DecodeZoneGroupConfig(zoneGroupOutput) + if err != nil { + return errors.Wrapf(err, "failed to decode zonegroup %q", objContext.ZoneGroup) + } + // if only master zone remains then it is okay delete + if len(zoneGroupJson.Zones) > 1 { + for _, zone := range zoneGroupJson.Zones { + if zone.Name != store.Spec.Zone.Name { + deps.Add(zoneIsMasterWithPeersDependentType, zone.Name) + } + } + } + return nil +} diff --git a/pkg/operator/ceph/object/dependents_test.go b/pkg/operator/ceph/object/dependents_test.go index 58fde43b2..6c1574c0e 100644 --- a/pkg/operator/ceph/object/dependents_test.go +++ b/pkg/operator/ceph/object/dependents_test.go @@ -32,6 +32,7 @@ import ( rookclient "github.com/rook/rook/pkg/client/clientset/versioned/fake" "github.com/rook/rook/pkg/clusterd" "github.com/rook/rook/pkg/daemon/ceph/client" + cephclient "github.com/rook/rook/pkg/daemon/ceph/client" "github.com/rook/rook/pkg/util/exec" exectest "github.com/rook/rook/pkg/util/exec/test" "github.com/stretchr/testify/assert" @@ -39,6 +40,182 @@ import ( "k8s.io/apimachinery/pkg/runtime" ) +const ( + zoneA = "zone-a" + zoneB = "zone-b" + zoneGroupGetSingleZoneJSON = `{ + "id": "fd8ff110-d3fd-49b4-b24f-f6cd3dddfedf", + "name": "zonegroup-a", + "api_name": "zonegroup-a", + "is_master": "true", + "endpoints": [ + "http://rook-ceph-rgw-store-a.rook-ceph.svc:80" + ], + "hostnames": [], + "hostnames_s3website": [], + "master_zone": "6cb39d2c-3005-49da-9be3-c1a92a97d28a", + "zones": [ + { + "id": "6cb39d2c-3005-49da-9be3-c1a92a97d28a", + "name": "zone-a", + "endpoints": [ + "http://rook-ceph-rgw-store-a.rook-ceph.svc:80" + ], + "log_meta": "false", + "log_data": "false", + "bucket_index_max_shards": 0, + "read_only": "false", + "tier_type": "", + "sync_from_all": "true", + "sync_from": [], + "redirect_zone": "" + } + ], + "placement_targets": [ + { + "name": "default-placement", + "tags": [], + "storage_classes": [ + "STANDARD" + ] + } + ], + "default_placement": "default-placement", + "realm_id": "237e6250-5f7d-4b85-9359-8cb2b1848507" + }` + zoneGroupGetMultipleZoneJSON = `{ + "id": "fd8ff110-d3fd-49b4-b24f-f6cd3dddfedf", + "name": "zonegroup-a", + "api_name": "zonegroup-a", + "is_master": "true", + "endpoints": [ + "http://rook-ceph-rgw-store-a.rook-ceph.svc:80" + ], + "hostnames": [], + "hostnames_s3website": [], + "master_zone": "6cb39d2c-3005-49da-9be3-c1a92a97d28a", + "zones": [ + { + "id": "6cb39d2c-3005-49da-9be3-c1a92a97d28a", + "name": "zone-a", + "endpoints": [ + "http://rook-ceph-rgw-store-a.rook-ceph.svc:80" + ], + "log_meta": "false", + "log_data": "false", + "bucket_index_max_shards": 0, + "read_only": "false", + "tier_type": "", + "sync_from_all": "true", + "sync_from": [], + "redirect_zone": "" + }, + { + "id": "6cb39d2c-3005-49da-9be3-c1a92a97d28b", + "name": "zone-b", + "endpoints": [ + "http://rook-ceph-rgw-store-b.rook-ceph.svc:80" + ], + "log_meta": "false", + "log_data": "false", + "bucket_index_max_shards": 0, + "read_only": "false", + "tier_type": "", + "sync_from_all": "true", + "sync_from": [], + "redirect_zone": "" + } + ], + "placement_targets": [ + { + "name": "default-placement", + "tags": [], + "storage_classes": [ + "STANDARD" + ] + } + ], + "default_placement": "default-placement", + "realm_id": "237e6250-5f7d-4b85-9359-8cb2b1848507" + }` + zoneGetZoneAJSON = `{ + "id": "6cb39d2c-3005-49da-9be3-c1a92a97d28a", + "name": "zone-a", + "domain_root": "zone-a.rgw.meta:root", + "control_pool": "zone-a.rgw.control", + "gc_pool": "zone-a.rgw.log:gc", + "lc_pool": "zone-a.rgw.log:lc", + "log_pool": "zone-a.rgw.log", + "intent_log_pool": "zone-a.rgw.log:intent", + "usage_log_pool": "zone-a.rgw.log:usage", + "reshard_pool": "zone-a.rgw.log:reshard", + "user_keys_pool": "zone-a.rgw.meta:users.keys", + "user_email_pool": "zone-a.rgw.meta:users.email", + "user_swift_pool": "zone-a.rgw.meta:users.swift", + "user_uid_pool": "zone-a.rgw.meta:users.uid", + "otp_pool": "zone-a.rgw.otp", + "system_key": { + "access_key": "", + "secret_key": "" + }, + "placement_pools": [ + { + "key": "default-placement", + "val": { + "index_pool": "zone-a.rgw.buckets.index", + "storage_classes": { + "STANDARD": { + "data_pool": "zone-a.rgw.buckets.data" + } + }, + "data_extra_pool": "zone-a.rgw.buckets.non-ec", + "index_type": 0 + } + } + ], + "metadata_heap": "", + "realm_id": "" + }` + zoneGetZoneBJSON = `{ + "id": "6cb39d2c-3005-49da-9be3-c1a92a97d28b", + "name": "zone-b", + "domain_root": "zone-b.rgw.meta:root", + "control_pool": "zone-b.rgw.control", + "gc_pool": "zone-b.rgw.log:gc", + "lc_pool": "zone-b.rgw.log:lc", + "log_pool": "zone-b.rgw.log", + "intent_log_pool": "zone-b.rgw.log:intent", + "usage_log_pool": "zone-b.rgw.log:usage", + "reshard_pool": "zone-b.rgw.log:reshard", + "user_keys_pool": "zone-b.rgw.meta:users.keys", + "user_email_pool": "zone-b.rgw.meta:users.email", + "user_swift_pool": "zone-b.rgw.meta:users.swift", + "user_uid_pool": "zone-b.rgw.meta:users.uid", + "otp_pool": "zone-b.rgw.otp", + "system_key": { + "access_key": "", + "secret_key": "" + }, + "placement_pools": [ + { + "key": "default-placement", + "val": { + "index_pool": "zone-b.rgw.buckets.index", + "storage_classes": { + "STANDARD": { + "data_pool": "zone-b.rgw.buckets.data" + } + }, + "data_extra_pool": "zone-b.rgw.buckets.non-ec", + "index_type": 0 + } + } + ], + "metadata_heap": "", + "realm_id": "" + }` +) + func TestCephObjectStoreDependents(t *testing.T) { scheme := runtime.NewScheme() assert.NoError(t, cephv1.AddToScheme(scheme)) @@ -74,8 +251,28 @@ func TestCephObjectStoreDependents(t *testing.T) { {Name: "my-store.rgw.buckets.data"}, {Name: ".rgw.root"}, {Name: "my-store.rgw.buckets.index"}, + {Name: "my-store.rgw.otp"}, + } + zoneBPools := []*client.CephStoragePoolSummary{ + {Name: "zone-b.rgw.control"}, + {Name: "zone-b.rgw.meta"}, + {Name: "zone-b.rgw.log"}, + {Name: "zone-b.rgw.buckets.non-ec"}, + {Name: "zone-b.rgw.buckets.data"}, + {Name: ".rgw.root"}, + {Name: "zone-b.rgw.buckets.index"}, + {Name: "zone-b.rgw.otp"}, + } + zoneAPools := []*client.CephStoragePoolSummary{ + {Name: "zone-a.rgw.control"}, + {Name: "zone-a.rgw.meta"}, + {Name: "zone-a.rgw.log"}, + {Name: "zone-a.rgw.buckets.non-ec"}, + {Name: "zone-a.rgw.buckets.data"}, + {Name: ".rgw.root"}, + {Name: "zone-a.rgw.buckets.index"}, + {Name: "zone-a.rgw.otp"}, } - // Mock HTTP call mockClient := func(bucket string) *MockClient { return &MockClient{ @@ -91,6 +288,9 @@ func TestCephObjectStoreDependents(t *testing.T) { } } + setMultisiteContext := func(context *clusterd.Context, clusterInfo *cephclient.ClusterInfo, store *cephv1.CephObjectStore) *Context { + return &Context{Context: context, Name: store.Name, clusterInfo: clusterInfo, Realm: "realm-a", ZoneGroup: "zonegroup-a", Zone: store.Spec.Zone.Name} + } clusterInfo := client.AdminTestClusterInfo(ns) // Create objectmeta with the given name in our test namespace meta := func(name string) v1.ObjectMeta { @@ -112,6 +312,32 @@ func TestCephObjectStoreDependents(t *testing.T) { Gateway: cephv1.GatewaySpec{Port: 80}, }, } + storeZoneB := &cephv1.CephObjectStore{ + ObjectMeta: v1.ObjectMeta{ + Name: "zone-b-store", + Namespace: ns, + }, + TypeMeta: v1.TypeMeta{ + Kind: "CephObjectStore", + }, + Spec: cephv1.ObjectStoreSpec{ + Gateway: cephv1.GatewaySpec{Port: 80}, + Zone: cephv1.ZoneSpec{Name: zoneB}, + }, + } + storeZoneA := &cephv1.CephObjectStore{ + ObjectMeta: v1.ObjectMeta{ + Name: "zone-a-store", + Namespace: ns, + }, + TypeMeta: v1.TypeMeta{ + Kind: "CephObjectStore", + }, + Spec: cephv1.ObjectStoreSpec{ + Gateway: cephv1.GatewaySpec{Port: 80}, + Zone: cephv1.ZoneSpec{Name: zoneA}, + }, + } t.Run("missing pools so skipping", func(t *testing.T) { c = newClusterdCtx(executor) @@ -209,13 +435,13 @@ func TestCephObjectStoreDependents(t *testing.T) { assert.ElementsMatch(t, []string{"u1"}, deps.OfKind("CephObjectStoreUsers")) }) - t.Run("no objectstore users and buckets", func(t *testing.T) { + t.Run("store belong to secondary zone with no objectstore users and no buckets", func(t *testing.T) { executor = &exectest.MockExecutor{ MockExecuteCommandWithOutput: func(command string, args ...string) (string, error) { logger.Infof("Command: %s %v", command, args) if args[0] == "osd" { if args[1] == "lspools" { - output, err := json.Marshal(pools) + output, err := json.Marshal(zoneBPools) assert.Nil(t, err) return string(output), nil } @@ -226,15 +452,413 @@ func TestCephObjectStoreDependents(t *testing.T) { if command == "radosgw-admin" && args[0] == "user" { return userCreateJSON, nil } + if command == "radosgw-admin" && args[0] == "zonegroup" && args[1] == "get" { + return zoneGroupGetMultipleZoneJSON, nil + } + if command == "radosgw-admin" && args[0] == "zone" && args[1] == "get" { + return zoneGetZoneBJSON, nil + } + return "", errors.Errorf("no such command %v %v", command, args) + }, + } + c = newClusterdCtx(executor) + client, err := admin.New("rook-ceph-rgw-my-store.mycluster.svc", "53S6B9S809NUP19IJ2K3", "1bXPegzsGClvoGAiJdHQD1uOW2sQBLAZM9j9VtXR", mockClient(`[]`)) + assert.NoError(t, err) + store.Spec.Zone.Name = zoneB + deps, err := CephObjectStoreDependents(c, clusterInfo, storeZoneB, setMultisiteContext(c, clusterInfo, storeZoneB), &AdminOpsContext{AdminOpsClient: client}) + assert.NoError(t, err) + assert.True(t, deps.Empty()) + }) + + t.Run("store belong to secondary zone with one objectstore users but wrong store and no buckets", func(t *testing.T) { + executor = &exectest.MockExecutor{ + MockExecuteCommandWithOutput: func(command string, args ...string) (string, error) { + logger.Infof("Command: %s %v", command, args) + if args[0] == "osd" { + if args[1] == "lspools" { + output, err := json.Marshal(zoneBPools) + assert.Nil(t, err) + return string(output), nil + } + } + return "", errors.Errorf("unexpected ceph command %q", args) + }, + MockExecuteCommandWithTimeout: func(timeout time.Duration, command string, args ...string) (string, error) { + if command == "radosgw-admin" && args[0] == "user" { + return userCreateJSON, nil + } + if command == "radosgw-admin" && args[0] == "zonegroup" && args[1] == "get" { + return zoneGroupGetMultipleZoneJSON, nil + } + if command == "radosgw-admin" && args[0] == "zone" && args[1] == "get" { + return zoneGetZoneBJSON, nil + } + return "", errors.Errorf("no such command %v %v", command, args) + }, + } + c = newClusterdCtx(executor, &cephv1.CephObjectStoreUser{ObjectMeta: meta("u1")}) + _, err := c.RookClientset.CephV1().CephObjectStoreUsers(clusterInfo.Namespace).Create(context.TODO(), &cephv1.CephObjectStoreUser{ObjectMeta: meta("u1")}, v1.CreateOptions{}) + assert.NoError(t, err) + client, err := admin.New("rook-ceph-rgw-my-store.mycluster.svc", "53S6B9S809NUP19IJ2K3", "1bXPegzsGClvoGAiJdHQD1uOW2sQBLAZM9j9VtXR", mockClient(`[]`)) + assert.NoError(t, err) + deps, err := CephObjectStoreDependents(c, clusterInfo, storeZoneB, setMultisiteContext(c, clusterInfo, storeZoneB), &AdminOpsContext{AdminOpsClient: client}) + assert.NoError(t, err) + assert.True(t, deps.Empty()) + }) + + t.Run("store belong to secondary zone with one objectstore users and no buckets", func(t *testing.T) { + executor = &exectest.MockExecutor{ + MockExecuteCommandWithOutput: func(command string, args ...string) (string, error) { + logger.Infof("Command: %s %v", command, args) + if args[0] == "osd" { + if args[1] == "lspools" { + output, err := json.Marshal(zoneBPools) + assert.Nil(t, err) + return string(output), nil + } + } + return "", errors.Errorf("unexpected ceph command %q", args) + }, + MockExecuteCommandWithTimeout: func(timeout time.Duration, command string, args ...string) (string, error) { + if command == "radosgw-admin" && args[0] == "user" { + return userCreateJSON, nil + } + if command == "radosgw-admin" && args[0] == "zonegroup" && args[1] == "get" { + return zoneGroupGetMultipleZoneJSON, nil + } + if command == "radosgw-admin" && args[0] == "zone" && args[1] == "get" { + return zoneGetZoneBJSON, nil + } + return "", errors.Errorf("no such command %v %v", command, args) + }, + } + c = newClusterdCtx(executor, &cephv1.CephObjectStoreUser{ObjectMeta: meta("u1")}) + _, err := c.RookClientset.CephV1().CephObjectStoreUsers(clusterInfo.Namespace).Create(context.TODO(), &cephv1.CephObjectStoreUser{ObjectMeta: meta("u1"), Spec: cephv1.ObjectStoreUserSpec{Store: storeZoneB.Name}}, v1.CreateOptions{}) + assert.NoError(t, err) + client, err := admin.New("rook-ceph-rgw-my-store.mycluster.svc", "53S6B9S809NUP19IJ2K3", "1bXPegzsGClvoGAiJdHQD1uOW2sQBLAZM9j9VtXR", mockClient(`[]`)) + assert.NoError(t, err) + deps, err := CephObjectStoreDependents(c, clusterInfo, storeZoneB, setMultisiteContext(c, clusterInfo, storeZoneB), &AdminOpsContext{AdminOpsClient: client}) + assert.NoError(t, err) + assert.True(t, deps.Empty()) + }) + + t.Run("store belong to secondary zone with no objectstore users and one bucket", func(t *testing.T) { + executor = &exectest.MockExecutor{ + MockExecuteCommandWithOutput: func(command string, args ...string) (string, error) { + logger.Infof("Command: %s %v", command, args) + if args[0] == "osd" { + if args[1] == "lspools" { + output, err := json.Marshal(zoneBPools) + assert.Nil(t, err) + return string(output), nil + } + } + return "", errors.Errorf("unexpected ceph command %q", args) + }, + MockExecuteCommandWithTimeout: func(timeout time.Duration, command string, args ...string) (string, error) { + if command == "radosgw-admin" && args[0] == "user" { + return userCreateJSON, nil + } + if command == "radosgw-admin" && args[0] == "zonegroup" && args[1] == "get" { + return zoneGroupGetMultipleZoneJSON, nil + } + if command == "radosgw-admin" && args[0] == "zone" && args[1] == "get" { + return zoneGetZoneBJSON, nil + } return "", errors.Errorf("no such command %v %v", command, args) }, } c = newClusterdCtx(executor) client, err := admin.New("rook-ceph-rgw-my-store.mycluster.svc", "53S6B9S809NUP19IJ2K3", "1bXPegzsGClvoGAiJdHQD1uOW2sQBLAZM9j9VtXR", mockClient(`["my-bucket"]`)) assert.NoError(t, err) - deps, err := CephObjectStoreDependents(c, clusterInfo, store, NewContext(c, clusterInfo, store.Name), &AdminOpsContext{AdminOpsClient: client}) + deps, err := CephObjectStoreDependents(c, clusterInfo, storeZoneB, setMultisiteContext(c, clusterInfo, storeZoneB), &AdminOpsContext{AdminOpsClient: client}) + assert.NoError(t, err) + assert.True(t, deps.Empty()) + }) + + t.Run("store belong to master zone with no objectstore users, no buckets and no peers", func(t *testing.T) { + executor = &exectest.MockExecutor{ + MockExecuteCommandWithOutput: func(command string, args ...string) (string, error) { + logger.Infof("Command: %s %v", command, args) + if args[0] == "osd" { + if args[1] == "lspools" { + output, err := json.Marshal(zoneAPools) + assert.Nil(t, err) + return string(output), nil + } + } + return "", errors.Errorf("unexpected ceph command %q", args) + }, + MockExecuteCommandWithTimeout: func(timeout time.Duration, command string, args ...string) (string, error) { + if command == "radosgw-admin" && args[0] == "user" { + return userCreateJSON, nil + } + if command == "radosgw-admin" && args[0] == "zonegroup" && args[1] == "get" { + return zoneGroupGetSingleZoneJSON, nil + } + if command == "radosgw-admin" && args[0] == "zone" && args[1] == "get" { + return zoneGetZoneAJSON, nil + } + return "", errors.Errorf("no such command %v %v", command, args) + }, + } + c = newClusterdCtx(executor) + client, err := admin.New("rook-ceph-rgw-my-store.mycluster.svc", "53S6B9S809NUP19IJ2K3", "1bXPegzsGClvoGAiJdHQD1uOW2sQBLAZM9j9VtXR", mockClient(`[]`)) + assert.NoError(t, err) + deps, err := CephObjectStoreDependents(c, clusterInfo, storeZoneA, setMultisiteContext(c, clusterInfo, storeZoneA), &AdminOpsContext{AdminOpsClient: client}) + assert.NoError(t, err) + assert.True(t, deps.Empty()) + }) + + t.Run("store belong to master zone with one objectstore users but wrong store and no buckets and no peers", func(t *testing.T) { + executor = &exectest.MockExecutor{ + MockExecuteCommandWithOutput: func(command string, args ...string) (string, error) { + logger.Infof("Command: %s %v", command, args) + if args[0] == "osd" { + if args[1] == "lspools" { + output, err := json.Marshal(zoneAPools) + assert.Nil(t, err) + return string(output), nil + } + } + return "", errors.Errorf("unexpected ceph command %q", args) + }, + MockExecuteCommandWithTimeout: func(timeout time.Duration, command string, args ...string) (string, error) { + if command == "radosgw-admin" && args[0] == "user" { + return userCreateJSON, nil + } + if command == "radosgw-admin" && args[0] == "zonegroup" && args[1] == "get" { + return zoneGroupGetSingleZoneJSON, nil + } + if command == "radosgw-admin" && args[0] == "zone" && args[1] == "get" { + return zoneGetZoneAJSON, nil + } + return "", errors.Errorf("no such command %v %v", command, args) + }, + } + c = newClusterdCtx(executor, &cephv1.CephObjectStoreUser{ObjectMeta: meta("u1")}) + _, err := c.RookClientset.CephV1().CephObjectStoreUsers(clusterInfo.Namespace).Create(context.TODO(), &cephv1.CephObjectStoreUser{ObjectMeta: meta("u1")}, v1.CreateOptions{}) + assert.NoError(t, err) + client, err := admin.New("rook-ceph-rgw-my-store.mycluster.svc", "53S6B9S809NUP19IJ2K3", "1bXPegzsGClvoGAiJdHQD1uOW2sQBLAZM9j9VtXR", mockClient(`[]`)) + assert.NoError(t, err) + deps, err := CephObjectStoreDependents(c, clusterInfo, storeZoneA, setMultisiteContext(c, clusterInfo, storeZoneA), &AdminOpsContext{AdminOpsClient: client}) + assert.NoError(t, err) + assert.True(t, deps.Empty()) + }) + + t.Run("store belong to master zone with one objectstore users and no buckets and no peers", func(t *testing.T) { + executor = &exectest.MockExecutor{ + MockExecuteCommandWithOutput: func(command string, args ...string) (string, error) { + logger.Infof("Command: %s %v", command, args) + if args[0] == "osd" { + if args[1] == "lspools" { + output, err := json.Marshal(zoneAPools) + assert.Nil(t, err) + return string(output), nil + } + } + return "", errors.Errorf("unexpected ceph command %q", args) + }, + MockExecuteCommandWithTimeout: func(timeout time.Duration, command string, args ...string) (string, error) { + if command == "radosgw-admin" && args[0] == "user" { + return userCreateJSON, nil + } + if command == "radosgw-admin" && args[0] == "zonegroup" && args[1] == "get" { + return zoneGroupGetSingleZoneJSON, nil + } + if command == "radosgw-admin" && args[0] == "zone" && args[1] == "get" { + return zoneGetZoneAJSON, nil + } + return "", errors.Errorf("no such command %v %v", command, args) + }, + } + c = newClusterdCtx(executor, &cephv1.CephObjectStoreUser{ObjectMeta: meta("u1")}) + _, err := c.RookClientset.CephV1().CephObjectStoreUsers(clusterInfo.Namespace).Create(context.TODO(), &cephv1.CephObjectStoreUser{ObjectMeta: meta("u1"), Spec: cephv1.ObjectStoreUserSpec{Store: storeZoneA.Name}}, v1.CreateOptions{}) + assert.NoError(t, err) + client, err := admin.New("rook-ceph-rgw-my-store.mycluster.svc", "53S6B9S809NUP19IJ2K3", "1bXPegzsGClvoGAiJdHQD1uOW2sQBLAZM9j9VtXR", mockClient(`[]`)) + assert.NoError(t, err) + deps, err := CephObjectStoreDependents(c, clusterInfo, storeZoneA, setMultisiteContext(c, clusterInfo, storeZoneA), &AdminOpsContext{AdminOpsClient: client}) + assert.NoError(t, err) + assert.False(t, deps.Empty()) + assert.ElementsMatch(t, []string{"u1"}, deps.OfKind("CephObjectStoreUsers")) + }) + + t.Run("store belong to master zone with no objectstore users and one bucket and no peer", func(t *testing.T) { + executor = &exectest.MockExecutor{ + MockExecuteCommandWithOutput: func(command string, args ...string) (string, error) { + logger.Infof("Command: %s %v", command, args) + if args[0] == "osd" { + if args[1] == "lspools" { + output, err := json.Marshal(zoneAPools) + assert.Nil(t, err) + return string(output), nil + } + } + return "", errors.Errorf("unexpected ceph command %q", args) + }, + MockExecuteCommandWithTimeout: func(timeout time.Duration, command string, args ...string) (string, error) { + if command == "radosgw-admin" && args[0] == "user" { + return userCreateJSON, nil + } + if command == "radosgw-admin" && args[0] == "zonegroup" && args[1] == "get" { + return zoneGroupGetSingleZoneJSON, nil + } + if command == "radosgw-admin" && args[0] == "zone" && args[1] == "get" { + return zoneGetZoneAJSON, nil + } + return "", errors.Errorf("no such command %v %v", command, args) + }, + } + c = newClusterdCtx(executor) + client, err := admin.New("rook-ceph-rgw-my-store.mycluster.svc", "53S6B9S809NUP19IJ2K3", "1bXPegzsGClvoGAiJdHQD1uOW2sQBLAZM9j9VtXR", mockClient(`["my-bucket"]`)) + assert.NoError(t, err) + deps, err := CephObjectStoreDependents(c, clusterInfo, storeZoneA, setMultisiteContext(c, clusterInfo, storeZoneA), &AdminOpsContext{AdminOpsClient: client}) assert.NoError(t, err) assert.False(t, deps.Empty()) assert.ElementsMatch(t, []string{"my-bucket"}, deps.OfKind("buckets in the object store (could be from ObjectBucketClaims or COSI Buckets)"), deps) }) + + t.Run("store belong to master zone with no objectstore users, no buckets and one peer", func(t *testing.T) { + executor = &exectest.MockExecutor{ + MockExecuteCommandWithOutput: func(command string, args ...string) (string, error) { + logger.Infof("Command: %s %v", command, args) + if args[0] == "osd" { + if args[1] == "lspools" { + output, err := json.Marshal(zoneAPools) + assert.Nil(t, err) + return string(output), nil + } + } + return "", errors.Errorf("unexpected ceph command %q", args) + }, + MockExecuteCommandWithTimeout: func(timeout time.Duration, command string, args ...string) (string, error) { + if command == "radosgw-admin" && args[0] == "user" { + return userCreateJSON, nil + } + if command == "radosgw-admin" && args[0] == "zonegroup" && args[1] == "get" { + return zoneGroupGetMultipleZoneJSON, nil + } + if command == "radosgw-admin" && args[0] == "zone" && args[1] == "get" { + return zoneGetZoneAJSON, nil + } + return "", errors.Errorf("no such command %v %v", command, args) + }, + } + c = newClusterdCtx(executor) + client, err := admin.New("rook-ceph-rgw-my-store.mycluster.svc", "53S6B9S809NUP19IJ2K3", "1bXPegzsGClvoGAiJdHQD1uOW2sQBLAZM9j9VtXR", mockClient(`[]`)) + assert.NoError(t, err) + deps, err := CephObjectStoreDependents(c, clusterInfo, storeZoneA, setMultisiteContext(c, clusterInfo, storeZoneA), &AdminOpsContext{AdminOpsClient: client}) + assert.Error(t, err) + assert.False(t, deps.Empty()) + assert.ElementsMatch(t, []string{"zone-b"}, deps.OfKind(zoneIsMasterWithPeersDependentType)) + }) + + t.Run("store belong to master zone with one objectstore users but wrong store and no buckets and one peer", func(t *testing.T) { + executor = &exectest.MockExecutor{ + MockExecuteCommandWithOutput: func(command string, args ...string) (string, error) { + logger.Infof("Command: %s %v", command, args) + if args[0] == "osd" { + if args[1] == "lspools" { + output, err := json.Marshal(zoneAPools) + assert.Nil(t, err) + return string(output), nil + } + } + return "", errors.Errorf("unexpected ceph command %q", args) + }, + MockExecuteCommandWithTimeout: func(timeout time.Duration, command string, args ...string) (string, error) { + if command == "radosgw-admin" && args[0] == "user" { + return userCreateJSON, nil + } + if command == "radosgw-admin" && args[0] == "zonegroup" && args[1] == "get" { + return zoneGroupGetMultipleZoneJSON, nil + } + if command == "radosgw-admin" && args[0] == "zone" && args[1] == "get" { + return zoneGetZoneAJSON, nil + } + return "", errors.Errorf("no such command %v %v", command, args) + }, + } + c = newClusterdCtx(executor, &cephv1.CephObjectStoreUser{ObjectMeta: meta("u1")}) + _, err := c.RookClientset.CephV1().CephObjectStoreUsers(clusterInfo.Namespace).Create(context.TODO(), &cephv1.CephObjectStoreUser{ObjectMeta: meta("u1")}, v1.CreateOptions{}) + assert.NoError(t, err) + client, err := admin.New("rook-ceph-rgw-my-store.mycluster.svc", "53S6B9S809NUP19IJ2K3", "1bXPegzsGClvoGAiJdHQD1uOW2sQBLAZM9j9VtXR", mockClient(`[]`)) + assert.NoError(t, err) + deps, err := CephObjectStoreDependents(c, clusterInfo, storeZoneA, setMultisiteContext(c, clusterInfo, storeZoneA), &AdminOpsContext{AdminOpsClient: client}) + assert.Error(t, err) + assert.False(t, deps.Empty()) + assert.ElementsMatch(t, []string{"zone-b"}, deps.OfKind(zoneIsMasterWithPeersDependentType)) + }) + + t.Run("store belong to master zone with one objectstore users and no buckets and one peer", func(t *testing.T) { + executor = &exectest.MockExecutor{ + MockExecuteCommandWithOutput: func(command string, args ...string) (string, error) { + logger.Infof("Command: %s %v", command, args) + if args[0] == "osd" { + if args[1] == "lspools" { + output, err := json.Marshal(zoneAPools) + assert.Nil(t, err) + return string(output), nil + } + } + return "", errors.Errorf("unexpected ceph command %q", args) + }, + MockExecuteCommandWithTimeout: func(timeout time.Duration, command string, args ...string) (string, error) { + if command == "radosgw-admin" && args[0] == "user" { + return userCreateJSON, nil + } + if command == "radosgw-admin" && args[0] == "zonegroup" && args[1] == "get" { + return zoneGroupGetMultipleZoneJSON, nil + } + if command == "radosgw-admin" && args[0] == "zone" && args[1] == "get" { + return zoneGetZoneAJSON, nil + } + return "", errors.Errorf("no such command %v %v", command, args) + }, + } + c = newClusterdCtx(executor, &cephv1.CephObjectStoreUser{ObjectMeta: meta("u1")}) + _, err := c.RookClientset.CephV1().CephObjectStoreUsers(clusterInfo.Namespace).Create(context.TODO(), &cephv1.CephObjectStoreUser{ObjectMeta: meta("u1"), Spec: cephv1.ObjectStoreUserSpec{Store: storeZoneA.Name}}, v1.CreateOptions{}) + assert.NoError(t, err) + client, err := admin.New("rook-ceph-rgw-my-store.mycluster.svc", "53S6B9S809NUP19IJ2K3", "1bXPegzsGClvoGAiJdHQD1uOW2sQBLAZM9j9VtXR", mockClient(`[]`)) + assert.NoError(t, err) + deps, err := CephObjectStoreDependents(c, clusterInfo, storeZoneA, setMultisiteContext(c, clusterInfo, storeZoneA), &AdminOpsContext{AdminOpsClient: client}) + assert.Error(t, err) + assert.False(t, deps.Empty()) + assert.ElementsMatch(t, []string{"zone-b"}, deps.OfKind(zoneIsMasterWithPeersDependentType)) + }) + + t.Run("store belong to master zone with no objectstore users and one bucket and one peer", func(t *testing.T) { + executor = &exectest.MockExecutor{ + MockExecuteCommandWithOutput: func(command string, args ...string) (string, error) { + logger.Infof("Command: %s %v", command, args) + if args[0] == "osd" { + if args[1] == "lspools" { + output, err := json.Marshal(zoneAPools) + assert.Nil(t, err) + return string(output), nil + } + } + return "", errors.Errorf("unexpected ceph command %q", args) + }, + MockExecuteCommandWithTimeout: func(timeout time.Duration, command string, args ...string) (string, error) { + if command == "radosgw-admin" && args[0] == "user" { + return userCreateJSON, nil + } + if command == "radosgw-admin" && args[0] == "zonegroup" && args[1] == "get" { + return zoneGroupGetMultipleZoneJSON, nil + } + if command == "radosgw-admin" && args[0] == "zone" && args[1] == "get" { + return zoneGetZoneAJSON, nil + } + return "", errors.Errorf("no such command %v %v", command, args) + }, + } + c = newClusterdCtx(executor) + client, err := admin.New("rook-ceph-rgw-my-store.mycluster.svc", "53S6B9S809NUP19IJ2K3", "1bXPegzsGClvoGAiJdHQD1uOW2sQBLAZM9j9VtXR", mockClient(`["my-bucket"]`)) + assert.NoError(t, err) + deps, err := CephObjectStoreDependents(c, clusterInfo, storeZoneA, setMultisiteContext(c, clusterInfo, storeZoneA), &AdminOpsContext{AdminOpsClient: client}) + assert.Error(t, err) + assert.False(t, deps.Empty()) + assert.ElementsMatch(t, []string{"zone-b"}, deps.OfKind(zoneIsMasterWithPeersDependentType)) + }) } diff --git a/pkg/operator/ceph/object/objectstore.go b/pkg/operator/ceph/object/objectstore.go index 31a1e40d6..9b8798a54 100644 --- a/pkg/operator/ceph/object/objectstore.go +++ b/pkg/operator/ceph/object/objectstore.go @@ -61,6 +61,7 @@ var ( "rgw.log", "rgw.buckets.index", "rgw.buckets.non-ec", + "rgw.otp", } dataPoolName = "rgw.buckets.data" @@ -119,7 +120,7 @@ func removeObjectStoreFromMultisite(objContext *Context, spec cephv1.ObjectStore zoneEndpoints := strings.Join(zoneEndpointsList, ",") endpointArg := fmt.Sprintf("--endpoints=%s", zoneEndpoints) - zoneIsMaster, err := checkZoneIsMaster(objContext) + zoneIsMaster, err := CheckZoneIsMaster(objContext) if err != nil { return errors.Wrapf(err, "failed to determine if zone %q is master", objContext.Zone) } @@ -183,7 +184,11 @@ func deleteSingleSiteRealmAndPools(objContext *Context, spec cephv1.ObjectStoreS } if !spec.PreservePoolsOnDelete { - err = deletePools(objContext, spec, lastStore) + if EmptyPool(spec.DataPool) && EmptyPool(spec.MetadataPool) { + logger.Info("skipping removal of pools since not specified in the object store") + return nil + } + err = DeletePools(objContext, lastStore, objContext.Name) if err != nil { return errors.Wrap(err, "failed to delete object store pools") } @@ -227,7 +232,7 @@ func getMultisiteForObjectStore(ctx context.Context, clusterdContext *clusterd.C return name, name, name, nil } -func checkZoneIsMaster(objContext *Context) (bool, error) { +func CheckZoneIsMaster(objContext *Context) (bool, error) { logger.Debugf("checking if zone %v is the master zone", objContext.Zone) realmArg := fmt.Sprintf("--rgw-realm=%s", objContext.Realm) zoneGroupArg := fmt.Sprintf("--rgw-zonegroup=%s", objContext.ZoneGroup) @@ -452,7 +457,7 @@ func JoinMultisite(objContext *Context, endpointArg, zoneEndpoints, namespace st zoneGroupArg := fmt.Sprintf("--rgw-zonegroup=%s", objContext.ZoneGroup) zoneArg := fmt.Sprintf("--rgw-zone=%s", objContext.Zone) - zoneIsMaster, err := checkZoneIsMaster(objContext) + zoneIsMaster, err := CheckZoneIsMaster(objContext) if err != nil { return err } @@ -632,12 +637,7 @@ func getObjectStores(context *Context) ([]string, error) { return r.Realms, nil } -func deletePools(ctx *Context, spec cephv1.ObjectStoreSpec, lastStore bool) error { - if emptyPool(spec.DataPool) && emptyPool(spec.MetadataPool) { - logger.Info("skipping removal of pools since not specified in the object store") - return nil - } - +func DeletePools(ctx *Context, lastStore bool, poolPrefix string) error { pools := append(metadataPools, dataPoolName) if lastStore { pools = append(pools, rootPool) @@ -646,7 +646,7 @@ func deletePools(ctx *Context, spec cephv1.ObjectStoreSpec, lastStore bool) erro if configurePoolsConcurrently() { waitGroup, _ := errgroup.WithContext(ctx.clusterInfo.Context) for _, pool := range pools { - name := poolName(ctx.Name, pool) + name := poolName(poolPrefix, pool) waitGroup.Go(func() error { if err := cephclient.DeletePool(ctx.Context, ctx.clusterInfo, name); err != nil { return errors.Wrapf(err, "failed to delete pool %q. ", name) @@ -663,7 +663,7 @@ func deletePools(ctx *Context, spec cephv1.ObjectStoreSpec, lastStore bool) erro } else { for _, pool := range pools { - name := poolName(ctx.Name, pool) + name := poolName(poolPrefix, pool) if err := cephclient.DeletePool(ctx.Context, ctx.clusterInfo, name); err != nil { logger.Warningf("failed to delete pool %q. %v", name, err) } @@ -714,7 +714,7 @@ func missingPools(context *Context) ([]string, error) { } missingPools := []string{} - for _, objPool := range allObjectPools(context.Name) { + for _, objPool := range allObjectPools(context.Zone) { if !existingPools.Has(objPool) { missingPools = append(missingPools, objPool) } @@ -724,7 +724,7 @@ func missingPools(context *Context) ([]string, error) { } func CreatePools(context *Context, clusterSpec *cephv1.ClusterSpec, metadataPool, dataPool cephv1.PoolSpec) error { - if emptyPool(dataPool) && emptyPool(metadataPool) { + if EmptyPool(dataPool) && EmptyPool(metadataPool) { logger.Info("no pools specified for the CR, checking for their existence...") missingPools, err := missingPools(context) if err != nil { @@ -806,12 +806,12 @@ func createRGWPool(ctx *Context, clusterSpec *cephv1.ClusterSpec, poolSpec cephv return nil } -func poolName(storeName, poolName string) string { +func poolName(poolPrefix, poolName string) string { if strings.HasPrefix(poolName, ".") { return poolName } // the name of the pool is ., except for the pool ".rgw.root" that spans object stores - return fmt.Sprintf("%s.%s", storeName, poolName) + return fmt.Sprintf("%s.%s", poolPrefix, poolName) } // GetObjectBucketProvisioner returns the bucket provisioner name appended with operator namespace if OBC is watching on it @@ -1048,3 +1048,19 @@ func listsAreEqual(a, b []string) bool { } return true } + +func CheckIfZonePresentInZoneGroup(objContext *Context) (bool, error) { + output, err := runAdminCommand(objContext, true, "zonegroup", "get") + if err != nil { + return false, err + } + zoneGroupJson, err := DecodeZoneGroupConfig(output) + if err != nil { + return false, errors.Wrap(err, "failed to parse `radosgw-admin zonegroup get` output") + } + zoneExists, _ := findZoneEndpoints(objContext.Zone, zoneGroupJson.Zones) + if zoneExists { + return true, nil + } + return false, nil +} diff --git a/pkg/operator/ceph/object/objectstore_test.go b/pkg/operator/ceph/object/objectstore_test.go index 95538d7a2..4216f8729 100644 --- a/pkg/operator/ceph/object/objectstore_test.go +++ b/pkg/operator/ceph/object/objectstore_test.go @@ -211,7 +211,7 @@ func deleteStore(t *testing.T, name string, existingStores string, expectedDelet } err = deleteRealmAndPools(context, spec) assert.Nil(t, err) - expectedPoolsDeleted = 6 + expectedPoolsDeleted = 7 if expectedDeleteRootPool { expectedPoolsDeleted++ } diff --git a/pkg/operator/ceph/object/rgw.go b/pkg/operator/ceph/object/rgw.go index 87628ff88..66c8c6782 100644 --- a/pkg/operator/ceph/object/rgw.go +++ b/pkg/operator/ceph/object/rgw.go @@ -291,12 +291,12 @@ func (r *ReconcileCephObjectStore) validateStore(s *cephv1.CephObjectStore) erro // Validate the pool settings, but allow for empty pools specs in case they have already been created // such as by the ceph mgr - if !emptyPool(s.Spec.MetadataPool) { + if !EmptyPool(s.Spec.MetadataPool) { if err := pool.ValidatePoolSpec(r.context, r.clusterInfo, r.clusterSpec, &s.Spec.MetadataPool); err != nil { return errors.Wrap(err, "invalid metadata pool spec") } } - if !emptyPool(s.Spec.DataPool) { + if !EmptyPool(s.Spec.DataPool) { if err := pool.ValidatePoolSpec(r.context, r.clusterInfo, r.clusterSpec, &s.Spec.DataPool); err != nil { return errors.Wrap(err, "invalid data pool spec") } @@ -309,7 +309,7 @@ func (c *clusterConfig) generateSecretName(id string) string { return fmt.Sprintf("%s-%s-%s-keyring", AppName, c.store.Name, id) } -func emptyPool(pool cephv1.PoolSpec) bool { +func EmptyPool(pool cephv1.PoolSpec) bool { return reflect.DeepEqual(pool, cephv1.PoolSpec{}) } diff --git a/pkg/operator/ceph/object/rgw_test.go b/pkg/operator/ceph/object/rgw_test.go index e04703716..cace7ba3f 100644 --- a/pkg/operator/ceph/object/rgw_test.go +++ b/pkg/operator/ceph/object/rgw_test.go @@ -143,16 +143,16 @@ func TestGenerateSecretName(t *testing.T) { } func TestEmptyPoolSpec(t *testing.T) { - assert.True(t, emptyPool(cephv1.PoolSpec{})) + assert.True(t, EmptyPool(cephv1.PoolSpec{})) p := cephv1.PoolSpec{FailureDomain: "foo"} - assert.False(t, emptyPool(p)) + assert.False(t, EmptyPool(p)) p = cephv1.PoolSpec{Replicated: cephv1.ReplicatedSpec{Size: 1}} - assert.False(t, emptyPool(p)) + assert.False(t, EmptyPool(p)) p = cephv1.PoolSpec{ErasureCoded: cephv1.ErasureCodedSpec{CodingChunks: 1}} - assert.False(t, emptyPool(p)) + assert.False(t, EmptyPool(p)) } func TestBuildDomainNameAndEndpoint(t *testing.T) { diff --git a/pkg/operator/ceph/object/zone/controller.go b/pkg/operator/ceph/object/zone/controller.go index 992494ed6..2663784fa 100644 --- a/pkg/operator/ceph/object/zone/controller.go +++ b/pkg/operator/ceph/object/zone/controller.go @@ -19,6 +19,7 @@ package zone import ( "context" + "encoding/json" "fmt" "reflect" "strings" @@ -27,7 +28,6 @@ import ( opcontroller "github.com/rook/rook/pkg/operator/ceph/controller" "github.com/rook/rook/pkg/operator/ceph/reporting" - v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/client-go/tools/record" "sigs.k8s.io/controller-runtime/pkg/controller" @@ -55,6 +55,10 @@ const ( controllerName = "ceph-object-zone-controller" ) +type domainRootType struct { + DomainRoot string `json:"domain_root"` +} + var waitForRequeueIfObjectZoneGroupNotReady = reconcile.Result{Requeue: true, RequeueAfter: 10 * time.Second} var logger = capnslog.NewPackageLogger("github.com/rook/rook", controllerName) @@ -135,11 +139,16 @@ func (r *ReconcileObjectZone) reconcile(request reconcile.Request) (reconcile.Re // Error reading the object - requeue the request. return reconcile.Result{}, *cephObjectZone, errors.Wrap(err, "failed to get CephObjectZone") } + // update observedGeneration local variable with current generation value, // because generation can be changed before reconcile got completed // CR status will be updated at end of reconcile, so to reflect the reconcile has finished observedGeneration := cephObjectZone.ObjectMeta.Generation - + // Set a finalizer so we can do cleanup before the object goes away + err = opcontroller.AddFinalizerIfNotPresent(r.opManagerContext, r.client, cephObjectZone) + if err != nil { + return reconcile.Result{}, *cephObjectZone, errors.Wrap(err, "failed to add finalizer") + } // The CR was just created, initializing status fields if cephObjectZone.Status == nil { r.updateStatus(k8sutil.ObservedGenerationNotAvailable, request.NamespacedName, k8sutil.EmptyStatus) @@ -151,6 +160,11 @@ func (r *ReconcileObjectZone) reconcile(request reconcile.Request) (reconcile.Re // This handles the case where the Ceph Cluster is gone and we want to delete that CR // if !cephObjectZone.GetDeletionTimestamp().IsZero() && !cephClusterExists { + // Remove finalizer + err := opcontroller.RemoveFinalizer(r.opManagerContext, r.client, cephObjectZone) + if err != nil { + return reconcile.Result{}, *cephObjectZone, errors.Wrap(err, "failed to remove finalizer") + } // Return and do not requeue. Successful deletion. return reconcile.Result{}, *cephObjectZone, nil } @@ -158,15 +172,6 @@ func (r *ReconcileObjectZone) reconcile(request reconcile.Request) (reconcile.Re } r.clusterSpec = &cephCluster.Spec - // DELETE: the CR was deleted - if !cephObjectZone.GetDeletionTimestamp().IsZero() { - logger.Debugf("deleting zone CR %q", cephObjectZone.Name) - r.recorder.Eventf(cephObjectZone, v1.EventTypeNormal, string(cephv1.ReconcileStarted), "deleting CephObjectZOne %q", cephObjectZone.Name) - - // Return and do not requeue. Successful deletion. - return reconcile.Result{}, *cephObjectZone, nil - } - // Populate clusterInfo during each reconcile r.clusterInfo, _, _, err = opcontroller.LoadClusterInfo(r.context, r.opManagerContext, request.NamespacedName.Namespace) if err != nil { @@ -180,15 +185,21 @@ func (r *ReconcileObjectZone) reconcile(request reconcile.Request) (reconcile.Re return reconcile.Result{}, *cephObjectZone, errors.Wrapf(err, "invalid CephObjectZone CR %q", cephObjectZone.Name) } - // Start object reconciliation, updating status for this - r.updateStatus(k8sutil.ObservedGenerationNotAvailable, request.NamespacedName, k8sutil.ReconcilingStatus) - // Make sure an ObjectZoneGroup is present - realmName, reconcileResponse, err := r.reconcileObjectZoneGroup(cephObjectZone) + realmName, reconcileResponse, err := r.getCephObjectZoneGroup(cephObjectZone) if err != nil { return reconcileResponse, *cephObjectZone, err } + // DELETE: the CR was deleted + if !cephObjectZone.GetDeletionTimestamp().IsZero() { + res, err := r.deleteCephObjectZone(cephObjectZone, realmName) + return res, *cephObjectZone, err + } + + // Start object reconciliation, updating status for this + r.updateStatus(k8sutil.ObservedGenerationNotAvailable, request.NamespacedName, k8sutil.ReconcilingStatus) + // Make sure zone group has been created in Ceph Cluster reconcileResponse, err = r.reconcileCephZoneGroup(cephObjectZone, realmName) if err != nil { @@ -313,7 +324,7 @@ func (r *ReconcileObjectZone) createPoolsAndZone(objContext *object.Context, zon return nil } -func (r *ReconcileObjectZone) reconcileObjectZoneGroup(zone *cephv1.CephObjectZone) (string, reconcile.Result, error) { +func (r *ReconcileObjectZone) getCephObjectZoneGroup(zone *cephv1.CephObjectZone) (string, reconcile.Result, error) { // empty zoneGroup gets filled by r.client.Get() zoneGroup := &cephv1.CephObjectZoneGroup{} err := r.client.Get(r.opManagerContext, types.NamespacedName{Name: zone.Spec.ZoneGroup, Namespace: zone.Namespace}, zoneGroup) @@ -396,3 +407,131 @@ func (r *ReconcileObjectZone) updateStatus(observedGeneration int64, name types. } logger.Debugf("object zone %q status updated to %q", name, status) } +func (r *ReconcileObjectZone) deleteZone(objContext *object.Context) error { + realmArg := fmt.Sprintf("--rgw-realm=%s", objContext.Realm) + // zoneGroupArg := fmt.Sprintf("--rgw-zonegroup=%s", objContext.ZoneGroup) + zoneArg := fmt.Sprintf("--rgw-zone=%s", objContext.Zone) + + args := []string{"zone", "delete", realmArg, zoneArg} + output, err := object.RunAdminCommandNoMultisite(objContext, false, args...) + if err != nil { + return errors.Wrapf(err, "failed to delete ceph zone %q for reason %q", objContext.Zone, output) + } + return nil +} + +func (r *ReconcileObjectZone) removeZoneFromZonegroup(objContext *object.Context) error { + realmArg := fmt.Sprintf("--rgw-realm=%s", objContext.Realm) + zoneGroupArg := fmt.Sprintf("--rgw-zonegroup=%s", objContext.ZoneGroup) + zoneArg := fmt.Sprintf("--rgw-zone=%s", objContext.Zone) + + args := []string{"zonegroup", "remove", realmArg, zoneGroupArg, zoneArg} + output, err := object.RunAdminCommandNoMultisite(objContext, false, args...) + if err != nil { + return errors.Wrapf(err, "failed to delete ceph zone %q for reason %q", objContext.Zone, output) + } + + args = []string{"period", "update", "--commit", realmArg, zoneGroupArg} + output, err = object.RunAdminCommandNoMultisite(objContext, false, args...) + if err != nil { + return errors.Wrapf(err, "failed to commit updates in ceph zonegroup %q for reason %q", objContext.ZoneGroup, output) + } + return nil +} + +func (r *ReconcileObjectZone) deleteZonePools(objContext *object.Context, zone *cephv1.CephObjectZone, realmName string) error { + realmArg := fmt.Sprintf("--rgw-realm=%s", realmName) + zoneGroupArg := fmt.Sprintf("--rgw-zonegroup=%s", zone.Spec.ZoneGroup) + zoneArg := fmt.Sprintf("--rgw-zone=%s", zone.Name) + + zoneOutput, err := object.RunAdminCommandNoMultisite(objContext, true, "zone", "get", realmArg, zoneGroupArg, zoneArg) + if err != nil { + return errors.Wrapf(err, "failed to get zone %q", zone.Name) + } + poolPrefix, err := decodePoolPrefixfromZone(zoneOutput) + if err != nil { + return errors.Wrapf(err, "failed to parse pool prefix for zone json %v", zoneOutput) + } + + logger.Debugf("deleting pools for ceph zone %q with prefix %q", zone.Name, poolPrefix) + + if object.EmptyPool(zone.Spec.DataPool) && object.EmptyPool(zone.Spec.MetadataPool) { + logger.Info("skipping removal of pools since not specified in the object zone") + return nil + } + err = object.DeletePools(objContext, false, poolPrefix) + if err != nil { + return errors.Wrap(err, "failed to delete rgw pools") + } + + return nil +} + +func decodePoolPrefixfromZone(data string) (string, error) { + var domain domainRootType + err := json.Unmarshal([]byte(data), &domain) + if err != nil { + return "", errors.Wrap(err, "failed to unmarshal json") + } + s := strings.Split(domain.DomainRoot, ".rgw.") + return s[0], err +} +func (r *ReconcileObjectZone) deleteCephObjectZone(zone *cephv1.CephObjectZone, realmName string) (reconcile.Result, error) { + logger.Debugf("deleting zone CR %q", zone.Name) + objContext := object.NewContext(r.context, r.clusterInfo, zone.Name) + objContext.Realm = realmName + objContext.ZoneGroup = zone.Spec.ZoneGroup + objContext.Zone = zone.Name + zonePresent, err := object.CheckIfZonePresentInZoneGroup(objContext) + if err != nil { + return reconcile.Result{}, err + } + zoneIsMaster, err := object.CheckZoneIsMaster(objContext) + if err != nil { + return reconcile.Result{}, err + } + if zonePresent { + deps, err := CephObjectZoneDependentStores(r.context, r.clusterInfo, zone, objContext) + if err != nil { + return reconcile.Result{}, err + } + if !deps.Empty() { + err := reporting.ReportDeletionBlockedDueToDependents(r.opManagerContext, logger, r.client, zone, deps) + return opcontroller.WaitForRequeueIfFinalizerBlocked, err + } + reporting.ReportDeletionNotBlockedDueToDependents(r.opManagerContext, logger, r.client, r.recorder, zone) + if !zoneIsMaster { + err = r.removeZoneFromZonegroup(objContext) + if err != nil { + return reconcile.Result{}, err + } + zonePresent = false + } + } + + // zone successfully removed from zonegroup proceed with delete + // master zone cannot be removed from zonegroup, it will be always present + if !zonePresent || zoneIsMaster { + if !zone.Spec.PreservePoolsOnDelete { + // This case zone is removed only after the successful pool deletion + err = r.deleteZonePools(objContext, zone, realmName) + if err != nil { + res, _, err := r.setFailedStatus(k8sutil.ObservedGenerationNotAvailable, zone, types.NamespacedName{Namespace: zone.Namespace, Name: zone.Name}, "failed to delete ceph zone", err) + return res, err + } + } else { + logger.Infof("PreservePoolsOnDelete is set in object zone %s. Pools is not deleted, but Zone is not removed", objContext.Name) + } + err = r.deleteZone(objContext) + if err != nil { + return reconcile.Result{}, errors.Wrapf(err, "failed to delete zone %s", objContext.Name) + } + // Remove finalizer + err = opcontroller.RemoveFinalizer(r.opManagerContext, r.client, zone) + if err != nil { + return reconcile.Result{}, errors.Wrap(err, "failed to remove finalizer") + } + } + // Return and do not requeue. Successful deletion. + return reconcile.Result{}, nil +} diff --git a/pkg/operator/ceph/object/zone/dependents.go b/pkg/operator/ceph/object/zone/dependents.go new file mode 100644 index 000000000..7b7ec61c8 --- /dev/null +++ b/pkg/operator/ceph/object/zone/dependents.go @@ -0,0 +1,57 @@ +/* +Copyright 2022 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 zone + +import ( + "fmt" + + "github.com/pkg/errors" + v1 "github.com/rook/rook/pkg/apis/ceph.rook.io/v1" + "github.com/rook/rook/pkg/clusterd" + "github.com/rook/rook/pkg/daemon/ceph/client" + "github.com/rook/rook/pkg/operator/ceph/object" + "github.com/rook/rook/pkg/util/dependents" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +func CephObjectZoneDependentStores( + clusterdCtx *clusterd.Context, + clusterInfo *client.ClusterInfo, + zone *v1.CephObjectZone, + objContext *object.Context, +) (*dependents.DependentList, error) { + nsName := fmt.Sprintf("%s/%s", zone.Namespace, zone.Name) + baseErrMsg := fmt.Sprintf("failed to get dependents of CephObjectZone %q", nsName) + + deps := dependents.NewDependentList() + // CephObjectStores + stores, err := clusterdCtx.RookClientset.CephV1().CephObjectStores(zone.Namespace).List(clusterInfo.Context, metav1.ListOptions{}) + if err != nil { + return deps, errors.Wrapf(err, "%s. failed to list CephObjectStores for CephObjectZone %q", baseErrMsg, nsName) + } + for _, store := range stores.Items { + if store.Spec.Zone.Name == zone.Name { + deps.Add("CephObjectStore", store.Name) + logger.Debugf("found CephObjectStore %q that depends on CephObjectZone %q", store.Name, nsName) + + } else { + logger.Debugf("found CephObjectStore %q that does not depend on CephObjectZone %q", store.Name, nsName) + } + } + + return deps, nil +} diff --git a/pkg/operator/ceph/object/zone/dependents_test.go b/pkg/operator/ceph/object/zone/dependents_test.go new file mode 100644 index 000000000..c911979a7 --- /dev/null +++ b/pkg/operator/ceph/object/zone/dependents_test.go @@ -0,0 +1,112 @@ +package zone + +import ( + "context" + "testing" + + 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/clusterd" + "github.com/rook/rook/pkg/daemon/ceph/client" + "github.com/rook/rook/pkg/operator/ceph/object" + "github.com/rook/rook/pkg/util/exec" + exectest "github.com/rook/rook/pkg/util/exec/test" + "github.com/stretchr/testify/assert" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" +) + +func TestCephObjectZoneDependentStores(t *testing.T) { + scheme := runtime.NewScheme() + assert.NoError(t, cephv1.AddToScheme(scheme)) + namespace := "test-ceph-object-store-dependents" + zoneGroupName := "zonegroup-a" + metadataPool := cephv1.PoolSpec{} + dataPool := cephv1.PoolSpec{} + clusterInfo := client.AdminTestClusterInfo(namespace) + + objectZoneA := &cephv1.CephObjectZone{ + ObjectMeta: metav1.ObjectMeta{ + Name: "zone-a", + Namespace: namespace, + }, + TypeMeta: metav1.TypeMeta{ + Kind: "CephObjectZone", + }, + Spec: cephv1.ObjectZoneSpec{ + ZoneGroup: zoneGroupName, + MetadataPool: metadataPool, + DataPool: dataPool, + }, + } + + objectStoreA := &cephv1.CephObjectStore{ + ObjectMeta: metav1.ObjectMeta{ + Name: "store-a", + Namespace: namespace, + }, + TypeMeta: metav1.TypeMeta{ + Kind: "CephObjectStore", + }, + Spec: cephv1.ObjectStoreSpec{}, + } + objectStoreA.Spec.Zone.Name = "zone-a" + objectStoreA.Spec.Gateway.Port = 80 + objectStoreB := &cephv1.CephObjectStore{ + ObjectMeta: metav1.ObjectMeta{ + Name: "store-b", + Namespace: namespace, + }, + TypeMeta: metav1.TypeMeta{ + Kind: "CephObjectStore", + }, + Spec: cephv1.ObjectStoreSpec{}, + } + objectStoreB.Spec.Zone.Name = "zone-b" + objectStoreB.Spec.Gateway.Port = 80 + + var c *clusterd.Context + executor := &exectest.MockExecutor{} + newClusterdCtx := func(executor exec.Executor) *clusterd.Context { + return &clusterd.Context{ + RookClientset: rookclient.NewSimpleClientset(), + Executor: executor, + } + } + t.Run("no objectstores exists", func(t *testing.T) { + c = newClusterdCtx(executor) + deps, err := CephObjectZoneDependentStores(c, clusterInfo, objectZoneA, object.NewContext(c, clusterInfo, objectZoneA.Name)) + assert.NoError(t, err) + assert.True(t, deps.Empty()) + }) + t.Run("one objectstores exists", func(t *testing.T) { + c = newClusterdCtx(executor) + _, err := c.RookClientset.CephV1().CephObjectStores(clusterInfo.Namespace).Create(context.TODO(), objectStoreA, v1.CreateOptions{}) + assert.NoError(t, err) + deps, err := CephObjectZoneDependentStores(c, clusterInfo, objectZoneA, object.NewContext(c, clusterInfo, objectZoneA.Name)) + assert.NoError(t, err) + assert.False(t, deps.Empty()) + assert.ElementsMatch(t, []string{"store-a"}, deps.OfKind("CephObjectStore")) + }) + t.Run("objectstore exists for different zone", func(t *testing.T) { + c = newClusterdCtx(executor) + _, err := c.RookClientset.CephV1().CephObjectStores(clusterInfo.Namespace).Create(context.TODO(), objectStoreB, v1.CreateOptions{}) + assert.NoError(t, err) + deps, err := CephObjectZoneDependentStores(c, clusterInfo, objectZoneA, object.NewContext(c, clusterInfo, objectZoneA.Name)) + assert.NoError(t, err) + assert.True(t, deps.Empty()) + }) + t.Run("multipleobjectstore exists for zone", func(t *testing.T) { + c = newClusterdCtx(executor) + _, err := c.RookClientset.CephV1().CephObjectStores(clusterInfo.Namespace).Create(context.TODO(), objectStoreA, v1.CreateOptions{}) + assert.NoError(t, err) + objectStoreB.Spec.Zone.Name = "zone-a" + _, err = c.RookClientset.CephV1().CephObjectStores(clusterInfo.Namespace).Create(context.TODO(), objectStoreB, v1.CreateOptions{}) + assert.NoError(t, err) + deps, err := CephObjectZoneDependentStores(c, clusterInfo, objectZoneA, object.NewContext(c, clusterInfo, objectZoneA.Name)) + assert.NoError(t, err) + assert.False(t, deps.Empty()) + assert.ElementsMatch(t, []string{"store-a", "store-b"}, deps.OfKind("CephObjectStore")) + }) +}