From c0123cf182f238941ba3a57de50caba97ac4ecff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Han?= Date: Mon, 18 Jan 2021 18:57:11 +0100 Subject: [PATCH] ceph: add cephfs mirroring support MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit With Ceph Pacific, Rook can now deploy the cephfs-mirror daemon. This initial commit covers the deployment of a single daemon only. Multiple mirror daemons is currently untested. Only a single mirror daemon is recommended. The configuration of peers will come in a later PR since the mgr module is still pending upstream: https://github.com/ceph/ceph/pull/39050 The same goes for integration tests, they will get added later once we start testing on Pacific. Closes: https://github.com/rook/rook/issues/7002 Signed-off-by: Sébastien Han --- Documentation/ceph-cluster-crd.md | 1 - Documentation/ceph-filesystem.md | 19 ++ Documentation/ceph-fs-mirror-crd.md | 45 +++ PendingReleaseNotes.md | 1 + .../charts/rook-ceph/templates/resources.yaml | 49 ++++ cluster/examples/kubernetes/ceph/crds.yaml | 51 ++++ .../kubernetes/ceph/filesystem-mirror.yaml | 38 +++ .../examples/kubernetes/ceph/filesystem.yaml | 2 + .../olm/ceph/assemble/metadata-common.yaml | 5 + cluster/olm/ceph/generate-rook-csv.sh | 2 + pkg/apis/ceph.rook.io/v1/register.go | 2 + pkg/apis/ceph.rook.io/v1/resources.go | 2 + pkg/apis/ceph.rook.io/v1/types.go | 45 +++ .../ceph.rook.io/v1/zz_generated.deepcopy.go | 114 ++++++++ .../ceph.rook.io/v1/ceph.rook.io_client.go | 5 + .../ceph.rook.io/v1/cephfilesystemmirror.go | 178 ++++++++++++ .../v1/fake/fake_ceph.rook.io_client.go | 4 + .../v1/fake/fake_cephfilesystemmirror.go | 130 +++++++++ .../ceph.rook.io/v1/generated_expansion.go | 2 + .../ceph.rook.io/v1/cephfilesystemmirror.go | 90 ++++++ .../ceph.rook.io/v1/interface.go | 7 + .../informers/externalversions/generic.go | 2 + .../ceph.rook.io/v1/cephfilesystemmirror.go | 99 +++++++ .../ceph.rook.io/v1/expansion_generated.go | 8 + pkg/daemon/ceph/client/filesystem_mirror.go | 115 ++++++++ .../ceph/client/filesystem_mirror_test.go | 104 +++++++ pkg/operator/ceph/cluster/cluster.go | 16 ++ pkg/operator/ceph/cluster/rbd/controller.go | 1 + .../ceph/cluster/register_controllers.go | 2 + pkg/operator/ceph/config/config.go | 3 + pkg/operator/ceph/controller/predicate.go | 25 ++ pkg/operator/ceph/file/controller.go | 11 + pkg/operator/ceph/file/mirror/config.go | 77 +++++ pkg/operator/ceph/file/mirror/controller.go | 263 ++++++++++++++++++ .../ceph/file/mirror/controller_test.go | 228 +++++++++++++++ pkg/operator/ceph/file/mirror/mirror.go | 116 ++++++++ pkg/operator/ceph/file/mirror/spec.go | 127 +++++++++ pkg/operator/ceph/file/mirror/spec_test.go | 100 +++++++ pkg/operator/ceph/test/podspec.go | 2 +- tests/framework/installer/ceph_installer.go | 3 +- tests/framework/installer/ceph_manifests.go | 43 +++ tests/scripts/validate_cluster.sh | 9 + 42 files changed, 2143 insertions(+), 3 deletions(-) create mode 100644 Documentation/ceph-fs-mirror-crd.md create mode 100644 cluster/examples/kubernetes/ceph/filesystem-mirror.yaml create mode 100644 pkg/client/clientset/versioned/typed/ceph.rook.io/v1/cephfilesystemmirror.go create mode 100644 pkg/client/clientset/versioned/typed/ceph.rook.io/v1/fake/fake_cephfilesystemmirror.go create mode 100644 pkg/client/informers/externalversions/ceph.rook.io/v1/cephfilesystemmirror.go create mode 100644 pkg/client/listers/ceph.rook.io/v1/cephfilesystemmirror.go create mode 100644 pkg/daemon/ceph/client/filesystem_mirror.go create mode 100644 pkg/daemon/ceph/client/filesystem_mirror_test.go create mode 100644 pkg/operator/ceph/file/mirror/config.go create mode 100644 pkg/operator/ceph/file/mirror/controller.go create mode 100644 pkg/operator/ceph/file/mirror/controller_test.go create mode 100644 pkg/operator/ceph/file/mirror/mirror.go create mode 100644 pkg/operator/ceph/file/mirror/spec.go create mode 100644 pkg/operator/ceph/file/mirror/spec_test.go diff --git a/Documentation/ceph-cluster-crd.md b/Documentation/ceph-cluster-crd.md index 82a28f568..0080e9df9 100755 --- a/Documentation/ceph-cluster-crd.md +++ b/Documentation/ceph-cluster-crd.md @@ -514,7 +514,6 @@ You can set annotations / labels for Rook components for the list of key value p * `mon`: Set annotations / labels for mons * `osd`: Set annotations / labels for OSDs * `prepareosd`: Set annotations / labels for OSD Prepare Jobs - When other keys are set, `all` will be merged together with the specific component. ### Placement Configuration Settings diff --git a/Documentation/ceph-filesystem.md b/Documentation/ceph-filesystem.md index 78d0094b0..a555ca1d5 100644 --- a/Documentation/ceph-filesystem.md +++ b/Documentation/ceph-filesystem.md @@ -128,6 +128,25 @@ Create the storage class. kubectl create -f cluster/examples/kubernetes/ceph/csi/cephfs/storageclass.yaml ``` +## Mirroring + +Since Ceph Pacific, CephFS supports asynchronous replication of snapshots to a remote CephFS file system via cephfs-mirror tool. Snapshots are synchronized by mirroring snapshot data followed by creating a snapshot with the same name (for a given directory on the remote file system) as the snapshot being synchronized. +It is generally useful when planning for Disaster Recovery. +For clusters that are geographically distributed and stretching is not possible due to high latencies. + +```yaml +apiVersion: ceph.rook.io/v1 +kind: CephFilesystem +metadata: + name: myfs + namespace: rook-ceph +spec: +... +... + mirroring: + enabled: true +``` + ## Quotas > **IMPORTANT**: The CephFS CSI driver uses quotas to enforce the PVC size requested. diff --git a/Documentation/ceph-fs-mirror-crd.md b/Documentation/ceph-fs-mirror-crd.md new file mode 100644 index 000000000..9c4168117 --- /dev/null +++ b/Documentation/ceph-fs-mirror-crd.md @@ -0,0 +1,45 @@ +--- +title: FilesystemMirror CRD +weight: 3600 +indent: true +--- + +# Ceph FilesystemMirror CRD + +Rook allows creation and updating the fs-mirror daemon through the custom resource definitions (CRDs). +CephFS will support asynchronous replication of snapshots to a remote (different Ceph cluster) CephFS file system via cephfs-mirror tool. +Snapshots are synchronized by mirroring snapshot data followed by creating a snapshot with the same name (for a given directory on the remote file system) as the snapshot being synchronized. +For more information about user management and capabilities see the [Ceph docs](https://docs.ceph.com/en/latest/dev/cephfs-mirroring/#cephfs-mirroring). + +## Creating daemon + +To get you started, here is a simple example of a CRD to deploy an cephfs-mirror daemon. + +```yaml +apiVersion: ceph.rook.io/v1 +kind: CephFilesystemMirror +metadata: + name: my-fs-mirror + namespace: rook-ceph +``` + +### Prerequisites + +This guide assumes you have created a Rook cluster as explained in the main [Quickstart guide](ceph-quickstart.md) + +## Settings + +If any setting is unspecified, a suitable default will be used automatically. + +### FilesystemMirror metadata + +* `name`: The name that will be used for the Ceph cephfs-mirror daemon. +* `namespace`: The Kubernetes namespace that will be created for the Rook cluster. The services, pods, and other resources created by the operator will be added to this namespace. + +### FilesystemMirror Settings + +* `placement`: The cephfs-mirror pods can be given standard Kubernetes placement restrictions with `nodeAffinity`, `tolerations`, `podAffinity`, and `podAntiAffinity` similar to placement defined for daemons configured by the [cluster CRD](https://github.com/rook/rook/blob/{{ branchName }}/cluster/examples/kubernetes/ceph/cluster.yaml). +* `annotations`: Key value pair list of annotations to add. +* `labels`: Key value pair list of labels to add. +* `resources`: The resource requirements for the cephfs-mirror pods. +* `priorityClassName`: The priority class to set on the cephfs-mirror pods. diff --git a/PendingReleaseNotes.md b/PendingReleaseNotes.md index 46623f054..abbb1f60c 100644 --- a/PendingReleaseNotes.md +++ b/PendingReleaseNotes.md @@ -19,3 +19,4 @@ v1.6... * CephClient CRD has been converted to use the controller-runtime library * Extending the support of vault KMS configuration for Ceph RGW * Enable disruption budgets (PDBs) by default for Mon, RGW, MDS, and OSD daemons +* Add CephFilesystemMirror CRD to deploy cephfs-mirror daemon diff --git a/cluster/charts/rook-ceph/templates/resources.yaml b/cluster/charts/rook-ceph/templates/resources.yaml index 5ff481ad8..f417f7eda 100644 --- a/cluster/charts/rook-ceph/templates/resources.yaml +++ b/cluster/charts/rook-ceph/templates/resources.yaml @@ -640,6 +640,12 @@ spec: type: boolean preserveFilesystemOnDelete: type: boolean + mirroring: + type: object + nullable: true + properties: + enabled: + type: boolean status: type: object x-kubernetes-preserve-unknown-fields: true @@ -1355,6 +1361,49 @@ spec: subresources: status: {} --- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: cephfilesystemmirrors.ceph.rook.io +spec: + group: ceph.rook.io + names: + kind: CephFilesystemMirror + listKind: CephFilesystemMirrorList + plural: cephfilesystemmirrors + singular: cephfilesystemmirror + scope: Namespaced + versions: + - name: v1 + served: true + storage: true + schema: + openAPIV3Schema: + type: object + properties: + spec: + type: object + properties: + resources: + type: object + nullable: true + x-kubernetes-preserve-unknown-fields: true + priorityClassName: + type: string + placement: + type: object + nullable: true + x-kubernetes-preserve-unknown-fields: true + annotations: + type: object + nullable: true + x-kubernetes-preserve-unknown-fields: true + status: + type: object + x-kubernetes-preserve-unknown-fields: true + subresources: + status: {} +--- {{- else }} --- apiVersion: apiextensions.k8s.io/v1beta1 diff --git a/cluster/examples/kubernetes/ceph/crds.yaml b/cluster/examples/kubernetes/ceph/crds.yaml index 3fa604a27..66e1b50d8 100644 --- a/cluster/examples/kubernetes/ceph/crds.yaml +++ b/cluster/examples/kubernetes/ceph/crds.yaml @@ -496,6 +496,51 @@ spec: status: {} # OLM: END CEPH RBD MIRROR CRD +# OLM: BEGIN CEPH FS MIRROR CRD +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: cephfilesystemmirrors.ceph.rook.io +spec: + group: ceph.rook.io + names: + kind: CephFilesystemMirror + listKind: CephFilesystemMirrorList + plural: cephfilesystemmirrors + singular: cephfilesystemmirror + scope: Namespaced + versions: + - name: v1 + served: true + storage: true + schema: + openAPIV3Schema: + type: object + properties: + spec: + type: object + properties: + resources: + type: object + nullable: true + x-kubernetes-preserve-unknown-fields: true + priorityClassName: + type: string + placement: + type: object + nullable: true + x-kubernetes-preserve-unknown-fields: true + annotations: + type: object + nullable: true + x-kubernetes-preserve-unknown-fields: true + status: + type: object + x-kubernetes-preserve-unknown-fields: true + subresources: + status: {} +# OLM: END CEPH FS MIRROR CRD # OLM: BEGIN CEPH FS CRD --- apiVersion: apiextensions.k8s.io/v1 @@ -649,6 +694,12 @@ spec: type: boolean preserveFilesystemOnDelete: type: boolean + mirroring: + type: object + nullable: true + properties: + enabled: + type: boolean status: type: object x-kubernetes-preserve-unknown-fields: true diff --git a/cluster/examples/kubernetes/ceph/filesystem-mirror.yaml b/cluster/examples/kubernetes/ceph/filesystem-mirror.yaml new file mode 100644 index 000000000..85ab0c6c3 --- /dev/null +++ b/cluster/examples/kubernetes/ceph/filesystem-mirror.yaml @@ -0,0 +1,38 @@ +################################################################################################################# +# Create filesystem-mirror daemon +# kubectl create -f filesystem-mirror.yaml +################################################################################################################# + +apiVersion: ceph.rook.io/v1 +kind: CephFilesystemMirror +metadata: + name: my-fs-mirror + namespace: rook-ceph # namespace:cluster +spec: + # The affinity rules to apply to the mds deployment + placement: + # nodeAffinity: + # requiredDuringSchedulingIgnoredDuringExecution: + # nodeSelectorTerms: + # - matchExpressions: + # - key: role + # operator: In + # values: + # - cephfs-mirror + # tolerations: + # - key: cephfs-mirror-node + # operator: Exists + # podAffinity: + # podAntiAffinity: + # A key/value list of annotations + annotations: + # key: value + resources: + # The requests and limits, for example to allow the cephfs-mirror pod(s) to use half of one CPU core and 1 gigabyte of memory + # limits: + # cpu: "500m" + # memory: "1024Mi" + # requests: + # cpu: "500m" + # memory: "1024Mi" + # priorityClassName: my-priority-class diff --git a/cluster/examples/kubernetes/ceph/filesystem.yaml b/cluster/examples/kubernetes/ceph/filesystem.yaml index dd2da681f..fbb9289ca 100644 --- a/cluster/examples/kubernetes/ceph/filesystem.yaml +++ b/cluster/examples/kubernetes/ceph/filesystem.yaml @@ -47,6 +47,8 @@ spec: # If false, standbys will be available, but will not have a warm cache. activeStandby: true # The affinity rules to apply to the mds deployment + mirroring: + enabled: false placement: # nodeAffinity: # requiredDuringSchedulingIgnoredDuringExecution: diff --git a/cluster/olm/ceph/assemble/metadata-common.yaml b/cluster/olm/ceph/assemble/metadata-common.yaml index 6dbe524e4..c487c77cf 100644 --- a/cluster/olm/ceph/assemble/metadata-common.yaml +++ b/cluster/olm/ceph/assemble/metadata-common.yaml @@ -128,6 +128,11 @@ spec: version: v1 displayName: Ceph Filesystem description: Represents a Ceph Filesystem. + - kind: CephFilesystemMirror + name: cephfilesystemmirrors.ceph.rook.io + version: v1 + displayName: Ceph Filesystem Mirror + description: Represents a Ceph Filesystem Mirror. - kind: CephRBDMirror name: cephrbdmirrors.ceph.rook.io version: v1 diff --git a/cluster/olm/ceph/generate-rook-csv.sh b/cluster/olm/ceph/generate-rook-csv.sh index 88fa6c910..2829c37e5 100755 --- a/cluster/olm/ceph/generate-rook-csv.sh +++ b/cluster/olm/ceph/generate-rook-csv.sh @@ -103,6 +103,7 @@ CEPH_FILESYSTEMS_CRD_YAML_FILE="$OLM_CATALOG_DIR/deploy/crds/cephfilesystems.cep CEPH_NFS_CRD_YAML_FILE="$OLM_CATALOG_DIR/deploy/crds/cephnfses.ceph.rook.io.crds.yaml" CEPH_CLIENT_CRD_YAML_FILE="$OLM_CATALOG_DIR/deploy/crds/cephclients.ceph.rook.io.crds.yaml" CEPH_RBD_MIRROR_CRD_YAML_FILE="$OLM_CATALOG_DIR/deploy/crds/cephrbdmirrors.ceph.rook.io.crds.yaml" +CEPH_FS_MIRROR_CRD_YAML_FILE="$OLM_CATALOG_DIR/deploy/crds/cephfilesystemmirrors.ceph.rook.io.crds.yaml" CEPH_EXTERNAL_SCRIPT_FILE="cluster/examples/kubernetes/ceph/create-external-cluster-resources.py" if [[ -d "$CSV_BUNDLE_PATH" ]]; then @@ -228,6 +229,7 @@ function generate_crds_yaml() { if [ "$OLM_INCLUDE_CEPHFS_CSI" = true ]; then sed -n '/^# OLM: BEGIN CEPH FS CRD$/,/# OLM: END CEPH FS CRD/p' "$CRD_YAML_FILE" | grep -v '^#' > "$CEPH_FILESYSTEMS_CRD_YAML_FILE" + sed -n '/^# OLM: BEGIN CEPH FS MIRROR CRD$/,/# OLM: END CEPH FS MIRROR CRD$/p' "$CRD_YAML_FILE" | grep -v '^#' > "$CEPH_FS_MIRROR_CRD_YAML_FILE" fi } diff --git a/pkg/apis/ceph.rook.io/v1/register.go b/pkg/apis/ceph.rook.io/v1/register.go index 1ee141e88..d1d0e4940 100644 --- a/pkg/apis/ceph.rook.io/v1/register.go +++ b/pkg/apis/ceph.rook.io/v1/register.go @@ -76,6 +76,8 @@ func addKnownTypes(scheme *runtime.Scheme) error { &CephObjectZoneList{}, &CephRBDMirror{}, &CephRBDMirrorList{}, + &CephFilesystemMirror{}, + &CephFilesystemMirrorList{}, ) metav1.AddToGroupVersion(scheme, SchemeGroupVersion) return nil diff --git a/pkg/apis/ceph.rook.io/v1/resources.go b/pkg/apis/ceph.rook.io/v1/resources.go index e5acdf5c5..10cd96514 100644 --- a/pkg/apis/ceph.rook.io/v1/resources.go +++ b/pkg/apis/ceph.rook.io/v1/resources.go @@ -38,6 +38,8 @@ const ( ResourcesKeyLogCollector = "logcollector" // ResourcesKeyRBDMirror represents the name of resource in the CR for the rbd mirror ResourcesKeyRBDMirror = "rbdmirror" + // ResourcesKeyFilesystemMirror represents the name of resource in the CR for the filesystem mirror + ResourcesKeyFilesystemMirror = "fsmirror" // ResourcesKeyCleanup represents the name of resource in the CR for the cleanup ResourcesKeyCleanup = "cleanup" ) diff --git a/pkg/apis/ceph.rook.io/v1/types.go b/pkg/apis/ceph.rook.io/v1/types.go index 20eb59f58..6c381eda8 100755 --- a/pkg/apis/ceph.rook.io/v1/types.go +++ b/pkg/apis/ceph.rook.io/v1/types.go @@ -524,6 +524,9 @@ type FilesystemSpec struct { // The mds pod info MetadataServer MetadataServerSpec `json:"metadataServer"` + + // The mirroring settings + Mirroring FSMirroringSpec `json:"mirroring"` } type MetadataServerSpec struct { @@ -550,6 +553,12 @@ type MetadataServerSpec struct { PriorityClassName string `json:"priorityClassName,omitempty"` } +// FSMirroringSpec represents the setting for a mirrored filesystem +type FSMirroringSpec struct { + // Enabled whether this filesystem is mirrored or not + Enabled bool `json:"enabled,omitempty"` +} + // +genclient // +genclient:noStatus // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object @@ -953,6 +962,42 @@ type RBDMirroringPeerSpec struct { SecretNames []string `json:"secretNames,omitempty"` } +// +genclient +// +genclient:noStatus +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +type CephFilesystemMirror struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata"` + Spec FilesystemMirroringSpec `json:"spec"` + Status *Status `json:"status"` +} + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object + +type CephFilesystemMirrorList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata"` + Items []CephFilesystemMirror `json:"items"` +} + +type FilesystemMirroringSpec struct { + // The affinity to place the rgw pods (default is to place on any available node) + Placement rookv1.Placement `json:"placement"` + + // The annotations-related configuration to add/set on each Pod related object. + Annotations rookv1.Annotations `json:"annotations,omitempty"` + + // The labels-related configuration to add/set on each Pod related object. + Labels rookv1.Labels `json:"labels,omitempty"` + + // The resource requirements for the cephfs-mirror pods + Resources v1.ResourceRequirements `json:"resources"` + + // PriorityClassName sets priority class on the cephfs-mirror pods + PriorityClassName string `json:"priorityClassName,omitempty"` +} + // IPFamilyType represents the single stack Ipv4 or Ipv6 protocol. type IPFamilyType string 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 fd13bf503..102f36386 100644 --- a/pkg/apis/ceph.rook.io/v1/zz_generated.deepcopy.go +++ b/pkg/apis/ceph.rook.io/v1/zz_generated.deepcopy.go @@ -429,6 +429,71 @@ func (in *CephFilesystemList) DeepCopyObject() runtime.Object { return nil } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CephFilesystemMirror) DeepCopyInto(out *CephFilesystemMirror) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + if in.Status != nil { + in, out := &in.Status, &out.Status + *out = new(Status) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CephFilesystemMirror. +func (in *CephFilesystemMirror) DeepCopy() *CephFilesystemMirror { + if in == nil { + return nil + } + out := new(CephFilesystemMirror) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *CephFilesystemMirror) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CephFilesystemMirrorList) DeepCopyInto(out *CephFilesystemMirrorList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]CephFilesystemMirror, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CephFilesystemMirrorList. +func (in *CephFilesystemMirrorList) DeepCopy() *CephFilesystemMirrorList { + if in == nil { + return nil + } + out := new(CephFilesystemMirrorList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *CephFilesystemMirrorList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CephHealthMessage) DeepCopyInto(out *CephHealthMessage) { *out = *in @@ -1329,6 +1394,54 @@ func (in *ExternalSpec) DeepCopy() *ExternalSpec { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *FSMirroringSpec) DeepCopyInto(out *FSMirroringSpec) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new FSMirroringSpec. +func (in *FSMirroringSpec) DeepCopy() *FSMirroringSpec { + if in == nil { + return nil + } + out := new(FSMirroringSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *FilesystemMirroringSpec) DeepCopyInto(out *FilesystemMirroringSpec) { + *out = *in + in.Placement.DeepCopyInto(&out.Placement) + if in.Annotations != nil { + in, out := &in.Annotations, &out.Annotations + *out = make(rookiov1.Annotations, len(*in)) + for key, val := range *in { + (*out)[key] = val + } + } + if in.Labels != nil { + in, out := &in.Labels, &out.Labels + *out = make(rookiov1.Labels, len(*in)) + for key, val := range *in { + (*out)[key] = val + } + } + in.Resources.DeepCopyInto(&out.Resources) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new FilesystemMirroringSpec. +func (in *FilesystemMirroringSpec) DeepCopy() *FilesystemMirroringSpec { + if in == nil { + return nil + } + out := new(FilesystemMirroringSpec) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *FilesystemSpec) DeepCopyInto(out *FilesystemSpec) { *out = *in @@ -1341,6 +1454,7 @@ func (in *FilesystemSpec) DeepCopyInto(out *FilesystemSpec) { } } in.MetadataServer.DeepCopyInto(&out.MetadataServer) + out.Mirroring = in.Mirroring return } diff --git a/pkg/client/clientset/versioned/typed/ceph.rook.io/v1/ceph.rook.io_client.go b/pkg/client/clientset/versioned/typed/ceph.rook.io/v1/ceph.rook.io_client.go index 51dfb5ebd..6bf780016 100644 --- a/pkg/client/clientset/versioned/typed/ceph.rook.io/v1/ceph.rook.io_client.go +++ b/pkg/client/clientset/versioned/typed/ceph.rook.io/v1/ceph.rook.io_client.go @@ -30,6 +30,7 @@ type CephV1Interface interface { CephClientsGetter CephClustersGetter CephFilesystemsGetter + CephFilesystemMirrorsGetter CephNFSesGetter CephObjectRealmsGetter CephObjectStoresGetter @@ -60,6 +61,10 @@ func (c *CephV1Client) CephFilesystems(namespace string) CephFilesystemInterface return newCephFilesystems(c, namespace) } +func (c *CephV1Client) CephFilesystemMirrors(namespace string) CephFilesystemMirrorInterface { + return newCephFilesystemMirrors(c, namespace) +} + func (c *CephV1Client) CephNFSes(namespace string) CephNFSInterface { return newCephNFSes(c, namespace) } diff --git a/pkg/client/clientset/versioned/typed/ceph.rook.io/v1/cephfilesystemmirror.go b/pkg/client/clientset/versioned/typed/ceph.rook.io/v1/cephfilesystemmirror.go new file mode 100644 index 000000000..867b42f09 --- /dev/null +++ b/pkg/client/clientset/versioned/typed/ceph.rook.io/v1/cephfilesystemmirror.go @@ -0,0 +1,178 @@ +/* +Copyright The Kubernetes Authors. + +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. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package v1 + +import ( + "context" + "time" + + v1 "github.com/rook/rook/pkg/apis/ceph.rook.io/v1" + scheme "github.com/rook/rook/pkg/client/clientset/versioned/scheme" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + rest "k8s.io/client-go/rest" +) + +// CephFilesystemMirrorsGetter has a method to return a CephFilesystemMirrorInterface. +// A group's client should implement this interface. +type CephFilesystemMirrorsGetter interface { + CephFilesystemMirrors(namespace string) CephFilesystemMirrorInterface +} + +// CephFilesystemMirrorInterface has methods to work with CephFilesystemMirror resources. +type CephFilesystemMirrorInterface interface { + Create(ctx context.Context, cephFilesystemMirror *v1.CephFilesystemMirror, opts metav1.CreateOptions) (*v1.CephFilesystemMirror, error) + Update(ctx context.Context, cephFilesystemMirror *v1.CephFilesystemMirror, opts metav1.UpdateOptions) (*v1.CephFilesystemMirror, error) + Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error + DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error + Get(ctx context.Context, name string, opts metav1.GetOptions) (*v1.CephFilesystemMirror, error) + List(ctx context.Context, opts metav1.ListOptions) (*v1.CephFilesystemMirrorList, error) + Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.CephFilesystemMirror, err error) + CephFilesystemMirrorExpansion +} + +// cephFilesystemMirrors implements CephFilesystemMirrorInterface +type cephFilesystemMirrors struct { + client rest.Interface + ns string +} + +// newCephFilesystemMirrors returns a CephFilesystemMirrors +func newCephFilesystemMirrors(c *CephV1Client, namespace string) *cephFilesystemMirrors { + return &cephFilesystemMirrors{ + client: c.RESTClient(), + ns: namespace, + } +} + +// Get takes name of the cephFilesystemMirror, and returns the corresponding cephFilesystemMirror object, and an error if there is any. +func (c *cephFilesystemMirrors) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.CephFilesystemMirror, err error) { + result = &v1.CephFilesystemMirror{} + err = c.client.Get(). + Namespace(c.ns). + Resource("cephfilesystemmirrors"). + Name(name). + VersionedParams(&options, scheme.ParameterCodec). + Do(ctx). + Into(result) + return +} + +// List takes label and field selectors, and returns the list of CephFilesystemMirrors that match those selectors. +func (c *cephFilesystemMirrors) List(ctx context.Context, opts metav1.ListOptions) (result *v1.CephFilesystemMirrorList, err error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + result = &v1.CephFilesystemMirrorList{} + err = c.client.Get(). + Namespace(c.ns). + Resource("cephfilesystemmirrors"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Do(ctx). + Into(result) + return +} + +// Watch returns a watch.Interface that watches the requested cephFilesystemMirrors. +func (c *cephFilesystemMirrors) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + opts.Watch = true + return c.client.Get(). + Namespace(c.ns). + Resource("cephfilesystemmirrors"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Watch(ctx) +} + +// Create takes the representation of a cephFilesystemMirror and creates it. Returns the server's representation of the cephFilesystemMirror, and an error, if there is any. +func (c *cephFilesystemMirrors) Create(ctx context.Context, cephFilesystemMirror *v1.CephFilesystemMirror, opts metav1.CreateOptions) (result *v1.CephFilesystemMirror, err error) { + result = &v1.CephFilesystemMirror{} + err = c.client.Post(). + Namespace(c.ns). + Resource("cephfilesystemmirrors"). + VersionedParams(&opts, scheme.ParameterCodec). + Body(cephFilesystemMirror). + Do(ctx). + Into(result) + return +} + +// Update takes the representation of a cephFilesystemMirror and updates it. Returns the server's representation of the cephFilesystemMirror, and an error, if there is any. +func (c *cephFilesystemMirrors) Update(ctx context.Context, cephFilesystemMirror *v1.CephFilesystemMirror, opts metav1.UpdateOptions) (result *v1.CephFilesystemMirror, err error) { + result = &v1.CephFilesystemMirror{} + err = c.client.Put(). + Namespace(c.ns). + Resource("cephfilesystemmirrors"). + Name(cephFilesystemMirror.Name). + VersionedParams(&opts, scheme.ParameterCodec). + Body(cephFilesystemMirror). + Do(ctx). + Into(result) + return +} + +// Delete takes name of the cephFilesystemMirror and deletes it. Returns an error if one occurs. +func (c *cephFilesystemMirrors) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error { + return c.client.Delete(). + Namespace(c.ns). + Resource("cephfilesystemmirrors"). + Name(name). + Body(&opts). + Do(ctx). + Error() +} + +// DeleteCollection deletes a collection of objects. +func (c *cephFilesystemMirrors) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error { + var timeout time.Duration + if listOpts.TimeoutSeconds != nil { + timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second + } + return c.client.Delete(). + Namespace(c.ns). + Resource("cephfilesystemmirrors"). + VersionedParams(&listOpts, scheme.ParameterCodec). + Timeout(timeout). + Body(&opts). + Do(ctx). + Error() +} + +// Patch applies the patch and returns the patched cephFilesystemMirror. +func (c *cephFilesystemMirrors) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.CephFilesystemMirror, err error) { + result = &v1.CephFilesystemMirror{} + err = c.client.Patch(pt). + Namespace(c.ns). + Resource("cephfilesystemmirrors"). + Name(name). + SubResource(subresources...). + VersionedParams(&opts, scheme.ParameterCodec). + Body(data). + Do(ctx). + Into(result) + return +} diff --git a/pkg/client/clientset/versioned/typed/ceph.rook.io/v1/fake/fake_ceph.rook.io_client.go b/pkg/client/clientset/versioned/typed/ceph.rook.io/v1/fake/fake_ceph.rook.io_client.go index 3a81884e9..afbe03dcd 100644 --- a/pkg/client/clientset/versioned/typed/ceph.rook.io/v1/fake/fake_ceph.rook.io_client.go +++ b/pkg/client/clientset/versioned/typed/ceph.rook.io/v1/fake/fake_ceph.rook.io_client.go @@ -44,6 +44,10 @@ func (c *FakeCephV1) CephFilesystems(namespace string) v1.CephFilesystemInterfac return &FakeCephFilesystems{c, namespace} } +func (c *FakeCephV1) CephFilesystemMirrors(namespace string) v1.CephFilesystemMirrorInterface { + return &FakeCephFilesystemMirrors{c, namespace} +} + func (c *FakeCephV1) CephNFSes(namespace string) v1.CephNFSInterface { return &FakeCephNFSes{c, namespace} } diff --git a/pkg/client/clientset/versioned/typed/ceph.rook.io/v1/fake/fake_cephfilesystemmirror.go b/pkg/client/clientset/versioned/typed/ceph.rook.io/v1/fake/fake_cephfilesystemmirror.go new file mode 100644 index 000000000..1394c4556 --- /dev/null +++ b/pkg/client/clientset/versioned/typed/ceph.rook.io/v1/fake/fake_cephfilesystemmirror.go @@ -0,0 +1,130 @@ +/* +Copyright The Kubernetes Authors. + +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. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package fake + +import ( + "context" + + cephrookiov1 "github.com/rook/rook/pkg/apis/ceph.rook.io/v1" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + labels "k8s.io/apimachinery/pkg/labels" + schema "k8s.io/apimachinery/pkg/runtime/schema" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + testing "k8s.io/client-go/testing" +) + +// FakeCephFilesystemMirrors implements CephFilesystemMirrorInterface +type FakeCephFilesystemMirrors struct { + Fake *FakeCephV1 + ns string +} + +var cephfilesystemmirrorsResource = schema.GroupVersionResource{Group: "ceph.rook.io", Version: "v1", Resource: "cephfilesystemmirrors"} + +var cephfilesystemmirrorsKind = schema.GroupVersionKind{Group: "ceph.rook.io", Version: "v1", Kind: "CephFilesystemMirror"} + +// Get takes name of the cephFilesystemMirror, and returns the corresponding cephFilesystemMirror object, and an error if there is any. +func (c *FakeCephFilesystemMirrors) Get(ctx context.Context, name string, options v1.GetOptions) (result *cephrookiov1.CephFilesystemMirror, err error) { + obj, err := c.Fake. + Invokes(testing.NewGetAction(cephfilesystemmirrorsResource, c.ns, name), &cephrookiov1.CephFilesystemMirror{}) + + if obj == nil { + return nil, err + } + return obj.(*cephrookiov1.CephFilesystemMirror), err +} + +// List takes label and field selectors, and returns the list of CephFilesystemMirrors that match those selectors. +func (c *FakeCephFilesystemMirrors) List(ctx context.Context, opts v1.ListOptions) (result *cephrookiov1.CephFilesystemMirrorList, err error) { + obj, err := c.Fake. + Invokes(testing.NewListAction(cephfilesystemmirrorsResource, cephfilesystemmirrorsKind, c.ns, opts), &cephrookiov1.CephFilesystemMirrorList{}) + + if obj == nil { + return nil, err + } + + label, _, _ := testing.ExtractFromListOptions(opts) + if label == nil { + label = labels.Everything() + } + list := &cephrookiov1.CephFilesystemMirrorList{ListMeta: obj.(*cephrookiov1.CephFilesystemMirrorList).ListMeta} + for _, item := range obj.(*cephrookiov1.CephFilesystemMirrorList).Items { + if label.Matches(labels.Set(item.Labels)) { + list.Items = append(list.Items, item) + } + } + return list, err +} + +// Watch returns a watch.Interface that watches the requested cephFilesystemMirrors. +func (c *FakeCephFilesystemMirrors) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { + return c.Fake. + InvokesWatch(testing.NewWatchAction(cephfilesystemmirrorsResource, c.ns, opts)) + +} + +// Create takes the representation of a cephFilesystemMirror and creates it. Returns the server's representation of the cephFilesystemMirror, and an error, if there is any. +func (c *FakeCephFilesystemMirrors) Create(ctx context.Context, cephFilesystemMirror *cephrookiov1.CephFilesystemMirror, opts v1.CreateOptions) (result *cephrookiov1.CephFilesystemMirror, err error) { + obj, err := c.Fake. + Invokes(testing.NewCreateAction(cephfilesystemmirrorsResource, c.ns, cephFilesystemMirror), &cephrookiov1.CephFilesystemMirror{}) + + if obj == nil { + return nil, err + } + return obj.(*cephrookiov1.CephFilesystemMirror), err +} + +// Update takes the representation of a cephFilesystemMirror and updates it. Returns the server's representation of the cephFilesystemMirror, and an error, if there is any. +func (c *FakeCephFilesystemMirrors) Update(ctx context.Context, cephFilesystemMirror *cephrookiov1.CephFilesystemMirror, opts v1.UpdateOptions) (result *cephrookiov1.CephFilesystemMirror, err error) { + obj, err := c.Fake. + Invokes(testing.NewUpdateAction(cephfilesystemmirrorsResource, c.ns, cephFilesystemMirror), &cephrookiov1.CephFilesystemMirror{}) + + if obj == nil { + return nil, err + } + return obj.(*cephrookiov1.CephFilesystemMirror), err +} + +// Delete takes name of the cephFilesystemMirror and deletes it. Returns an error if one occurs. +func (c *FakeCephFilesystemMirrors) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { + _, err := c.Fake. + Invokes(testing.NewDeleteAction(cephfilesystemmirrorsResource, c.ns, name), &cephrookiov1.CephFilesystemMirror{}) + + return err +} + +// DeleteCollection deletes a collection of objects. +func (c *FakeCephFilesystemMirrors) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { + action := testing.NewDeleteCollectionAction(cephfilesystemmirrorsResource, c.ns, listOpts) + + _, err := c.Fake.Invokes(action, &cephrookiov1.CephFilesystemMirrorList{}) + return err +} + +// Patch applies the patch and returns the patched cephFilesystemMirror. +func (c *FakeCephFilesystemMirrors) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *cephrookiov1.CephFilesystemMirror, err error) { + obj, err := c.Fake. + Invokes(testing.NewPatchSubresourceAction(cephfilesystemmirrorsResource, c.ns, name, pt, data, subresources...), &cephrookiov1.CephFilesystemMirror{}) + + if obj == nil { + return nil, err + } + return obj.(*cephrookiov1.CephFilesystemMirror), err +} diff --git a/pkg/client/clientset/versioned/typed/ceph.rook.io/v1/generated_expansion.go b/pkg/client/clientset/versioned/typed/ceph.rook.io/v1/generated_expansion.go index 8086a7534..675dadf45 100644 --- a/pkg/client/clientset/versioned/typed/ceph.rook.io/v1/generated_expansion.go +++ b/pkg/client/clientset/versioned/typed/ceph.rook.io/v1/generated_expansion.go @@ -26,6 +26,8 @@ type CephClusterExpansion interface{} type CephFilesystemExpansion interface{} +type CephFilesystemMirrorExpansion interface{} + type CephNFSExpansion interface{} type CephObjectRealmExpansion interface{} diff --git a/pkg/client/informers/externalversions/ceph.rook.io/v1/cephfilesystemmirror.go b/pkg/client/informers/externalversions/ceph.rook.io/v1/cephfilesystemmirror.go new file mode 100644 index 000000000..b697fa68e --- /dev/null +++ b/pkg/client/informers/externalversions/ceph.rook.io/v1/cephfilesystemmirror.go @@ -0,0 +1,90 @@ +/* +Copyright The Kubernetes Authors. + +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. +*/ + +// Code generated by informer-gen. DO NOT EDIT. + +package v1 + +import ( + "context" + time "time" + + cephrookiov1 "github.com/rook/rook/pkg/apis/ceph.rook.io/v1" + versioned "github.com/rook/rook/pkg/client/clientset/versioned" + internalinterfaces "github.com/rook/rook/pkg/client/informers/externalversions/internalinterfaces" + v1 "github.com/rook/rook/pkg/client/listers/ceph.rook.io/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + runtime "k8s.io/apimachinery/pkg/runtime" + watch "k8s.io/apimachinery/pkg/watch" + cache "k8s.io/client-go/tools/cache" +) + +// CephFilesystemMirrorInformer provides access to a shared informer and lister for +// CephFilesystemMirrors. +type CephFilesystemMirrorInformer interface { + Informer() cache.SharedIndexInformer + Lister() v1.CephFilesystemMirrorLister +} + +type cephFilesystemMirrorInformer struct { + factory internalinterfaces.SharedInformerFactory + tweakListOptions internalinterfaces.TweakListOptionsFunc + namespace string +} + +// NewCephFilesystemMirrorInformer constructs a new informer for CephFilesystemMirror type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewCephFilesystemMirrorInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { + return NewFilteredCephFilesystemMirrorInformer(client, namespace, resyncPeriod, indexers, nil) +} + +// NewFilteredCephFilesystemMirrorInformer constructs a new informer for CephFilesystemMirror type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewFilteredCephFilesystemMirrorInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { + return cache.NewSharedIndexInformer( + &cache.ListWatch{ + ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.CephV1().CephFilesystemMirrors(namespace).List(context.TODO(), options) + }, + WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.CephV1().CephFilesystemMirrors(namespace).Watch(context.TODO(), options) + }, + }, + &cephrookiov1.CephFilesystemMirror{}, + resyncPeriod, + indexers, + ) +} + +func (f *cephFilesystemMirrorInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { + return NewFilteredCephFilesystemMirrorInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) +} + +func (f *cephFilesystemMirrorInformer) Informer() cache.SharedIndexInformer { + return f.factory.InformerFor(&cephrookiov1.CephFilesystemMirror{}, f.defaultInformer) +} + +func (f *cephFilesystemMirrorInformer) Lister() v1.CephFilesystemMirrorLister { + return v1.NewCephFilesystemMirrorLister(f.Informer().GetIndexer()) +} diff --git a/pkg/client/informers/externalversions/ceph.rook.io/v1/interface.go b/pkg/client/informers/externalversions/ceph.rook.io/v1/interface.go index e764bd022..869909158 100644 --- a/pkg/client/informers/externalversions/ceph.rook.io/v1/interface.go +++ b/pkg/client/informers/externalversions/ceph.rook.io/v1/interface.go @@ -32,6 +32,8 @@ type Interface interface { CephClusters() CephClusterInformer // CephFilesystems returns a CephFilesystemInformer. CephFilesystems() CephFilesystemInformer + // CephFilesystemMirrors returns a CephFilesystemMirrorInformer. + CephFilesystemMirrors() CephFilesystemMirrorInformer // CephNFSes returns a CephNFSInformer. CephNFSes() CephNFSInformer // CephObjectRealms returns a CephObjectRealmInformer. @@ -79,6 +81,11 @@ func (v *version) CephFilesystems() CephFilesystemInformer { return &cephFilesystemInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} } +// CephFilesystemMirrors returns a CephFilesystemMirrorInformer. +func (v *version) CephFilesystemMirrors() CephFilesystemMirrorInformer { + return &cephFilesystemMirrorInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} +} + // CephNFSes returns a CephNFSInformer. func (v *version) CephNFSes() CephNFSInformer { return &cephNFSInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions} diff --git a/pkg/client/informers/externalversions/generic.go b/pkg/client/informers/externalversions/generic.go index 83d26d9cc..1002b4d75 100644 --- a/pkg/client/informers/externalversions/generic.go +++ b/pkg/client/informers/externalversions/generic.go @@ -69,6 +69,8 @@ func (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource return &genericInformer{resource: resource.GroupResource(), informer: f.Ceph().V1().CephClusters().Informer()}, nil case v1.SchemeGroupVersion.WithResource("cephfilesystems"): return &genericInformer{resource: resource.GroupResource(), informer: f.Ceph().V1().CephFilesystems().Informer()}, nil + case v1.SchemeGroupVersion.WithResource("cephfilesystemmirrors"): + return &genericInformer{resource: resource.GroupResource(), informer: f.Ceph().V1().CephFilesystemMirrors().Informer()}, nil case v1.SchemeGroupVersion.WithResource("cephnfses"): return &genericInformer{resource: resource.GroupResource(), informer: f.Ceph().V1().CephNFSes().Informer()}, nil case v1.SchemeGroupVersion.WithResource("cephobjectrealms"): diff --git a/pkg/client/listers/ceph.rook.io/v1/cephfilesystemmirror.go b/pkg/client/listers/ceph.rook.io/v1/cephfilesystemmirror.go new file mode 100644 index 000000000..a686b27e6 --- /dev/null +++ b/pkg/client/listers/ceph.rook.io/v1/cephfilesystemmirror.go @@ -0,0 +1,99 @@ +/* +Copyright The Kubernetes Authors. + +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. +*/ + +// Code generated by lister-gen. DO NOT EDIT. + +package v1 + +import ( + v1 "github.com/rook/rook/pkg/apis/ceph.rook.io/v1" + "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/labels" + "k8s.io/client-go/tools/cache" +) + +// CephFilesystemMirrorLister helps list CephFilesystemMirrors. +// All objects returned here must be treated as read-only. +type CephFilesystemMirrorLister interface { + // List lists all CephFilesystemMirrors in the indexer. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*v1.CephFilesystemMirror, err error) + // CephFilesystemMirrors returns an object that can list and get CephFilesystemMirrors. + CephFilesystemMirrors(namespace string) CephFilesystemMirrorNamespaceLister + CephFilesystemMirrorListerExpansion +} + +// cephFilesystemMirrorLister implements the CephFilesystemMirrorLister interface. +type cephFilesystemMirrorLister struct { + indexer cache.Indexer +} + +// NewCephFilesystemMirrorLister returns a new CephFilesystemMirrorLister. +func NewCephFilesystemMirrorLister(indexer cache.Indexer) CephFilesystemMirrorLister { + return &cephFilesystemMirrorLister{indexer: indexer} +} + +// List lists all CephFilesystemMirrors in the indexer. +func (s *cephFilesystemMirrorLister) List(selector labels.Selector) (ret []*v1.CephFilesystemMirror, err error) { + err = cache.ListAll(s.indexer, selector, func(m interface{}) { + ret = append(ret, m.(*v1.CephFilesystemMirror)) + }) + return ret, err +} + +// CephFilesystemMirrors returns an object that can list and get CephFilesystemMirrors. +func (s *cephFilesystemMirrorLister) CephFilesystemMirrors(namespace string) CephFilesystemMirrorNamespaceLister { + return cephFilesystemMirrorNamespaceLister{indexer: s.indexer, namespace: namespace} +} + +// CephFilesystemMirrorNamespaceLister helps list and get CephFilesystemMirrors. +// All objects returned here must be treated as read-only. +type CephFilesystemMirrorNamespaceLister interface { + // List lists all CephFilesystemMirrors in the indexer for a given namespace. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*v1.CephFilesystemMirror, err error) + // Get retrieves the CephFilesystemMirror from the indexer for a given namespace and name. + // Objects returned here must be treated as read-only. + Get(name string) (*v1.CephFilesystemMirror, error) + CephFilesystemMirrorNamespaceListerExpansion +} + +// cephFilesystemMirrorNamespaceLister implements the CephFilesystemMirrorNamespaceLister +// interface. +type cephFilesystemMirrorNamespaceLister struct { + indexer cache.Indexer + namespace string +} + +// List lists all CephFilesystemMirrors in the indexer for a given namespace. +func (s cephFilesystemMirrorNamespaceLister) List(selector labels.Selector) (ret []*v1.CephFilesystemMirror, err error) { + err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { + ret = append(ret, m.(*v1.CephFilesystemMirror)) + }) + return ret, err +} + +// Get retrieves the CephFilesystemMirror from the indexer for a given namespace and name. +func (s cephFilesystemMirrorNamespaceLister) Get(name string) (*v1.CephFilesystemMirror, error) { + obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) + if err != nil { + return nil, err + } + if !exists { + return nil, errors.NewNotFound(v1.Resource("cephfilesystemmirror"), name) + } + return obj.(*v1.CephFilesystemMirror), nil +} diff --git a/pkg/client/listers/ceph.rook.io/v1/expansion_generated.go b/pkg/client/listers/ceph.rook.io/v1/expansion_generated.go index 36069d13f..458e22da9 100644 --- a/pkg/client/listers/ceph.rook.io/v1/expansion_generated.go +++ b/pkg/client/listers/ceph.rook.io/v1/expansion_generated.go @@ -50,6 +50,14 @@ type CephFilesystemListerExpansion interface{} // CephFilesystemNamespaceLister. type CephFilesystemNamespaceListerExpansion interface{} +// CephFilesystemMirrorListerExpansion allows custom methods to be added to +// CephFilesystemMirrorLister. +type CephFilesystemMirrorListerExpansion interface{} + +// CephFilesystemMirrorNamespaceListerExpansion allows custom methods to be added to +// CephFilesystemMirrorNamespaceLister. +type CephFilesystemMirrorNamespaceListerExpansion interface{} + // CephNFSListerExpansion allows custom methods to be added to // CephNFSLister. type CephNFSListerExpansion interface{} diff --git a/pkg/daemon/ceph/client/filesystem_mirror.go b/pkg/daemon/ceph/client/filesystem_mirror.go new file mode 100644 index 000000000..519c62168 --- /dev/null +++ b/pkg/daemon/ceph/client/filesystem_mirror.go @@ -0,0 +1,115 @@ +/* +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 client + +import ( + "github.com/pkg/errors" + "github.com/rook/rook/pkg/clusterd" +) + +// AddFilesystemMirrorPeer add a mirror peer in the cephfs-mirror configuration +func AddFilesystemMirrorPeer(context *clusterd.Context, clusterInfo *ClusterInfo, filesystem, peer, remoteFilesystem string) error { + logger.Infof("adding cephfs-mirror peer for filesystem %q", filesystem) + + // Build command + args := []string{"fs", "snapshot", "mirror", "peer_add", filesystem, peer, remoteFilesystem} + cmd := NewCephCommand(context, clusterInfo, args) + + // Run command + output, err := cmd.Run() + if err != nil { + return errors.Wrapf(err, "failed to add cephfs-mirror peer for filesystem %q. %s", filesystem, output) + } + + return nil +} + +// RemoveFilesystemMirrorPeer add a mirror peer in the cephfs-mirror configuration +func RemoveFilesystemMirrorPeer(context *clusterd.Context, clusterInfo *ClusterInfo, peerUUID string) error { + logger.Infof("removing cephfs-mirror peer %q", peerUUID) + + // Build command + args := []string{"fs", "snapshot", "mirror", "peer_remove", peerUUID} + cmd := NewCephCommand(context, clusterInfo, args) + + // Run command + output, err := cmd.Run() + if err != nil { + return errors.Wrapf(err, "failed to remove cephfs-mirror peer for filesystem %q. %s", peerUUID, output) + } + + return nil +} + +// EnableFilesystemSnapshotMirror enables filesystem snapshot mirroring +func EnableFilesystemSnapshotMirror(context *clusterd.Context, clusterInfo *ClusterInfo, filesystem string) error { + logger.Infof("enabling ceph filesystem snapshot mirror for filesystem %q", filesystem) + + // Build command + args := []string{"fs", "snapshot", "mirror", "enable", filesystem} + cmd := NewCephCommand(context, clusterInfo, args) + + // Run command + output, err := cmd.Run() + if err != nil { + return errors.Wrapf(err, "failed to enable ceph filesystem snapshot mirror for filesystem %q. %s", filesystem, output) + } + + return nil +} + +// DisableFilesystemSnapshotMirror enables filesystem snapshot mirroring +func DisableFilesystemSnapshotMirror(context *clusterd.Context, clusterInfo *ClusterInfo, filesystem string) error { + logger.Infof("disabling ceph filesystem snapshot mirror for filesystem %q", filesystem) + + // Build command + args := []string{"fs", "snapshot", "mirror", "disable", filesystem} + cmd := NewCephCommand(context, clusterInfo, args) + + // Run command + output, err := cmd.Run() + if err != nil { + return errors.Wrapf(err, "failed to disable ceph filesystem snapshot mirror for filesystem %q. %s", filesystem, output) + } + + return nil +} + +// AuthorizeFilesystemMirror add a mirror peer in the rbd-mirror configuration +// Create a user for each file system peer (on the secondary/remote cluster). +// This user needs to have full capabilities on the MDS (to take snapshots) and the OSDs +func AuthorizeFilesystemMirror(context *clusterd.Context, clusterInfo *ClusterInfo, filesystem, client string) ([]byte, error) { + logger.Infof("disabling ceph filesystem mirror for filesystem %q", filesystem) + + // Build command, do not get confused by the "/ rwps" + // The "/" is the fs path + // The "rwps" are the permissions: + // r: read + // w: write + // p: layout or quota + // s: snapshots + args := []string{"fs", "authorize", filesystem, client, "/", "rwps"} + cmd := NewCephCommand(context, clusterInfo, args) + + // Run command + output, err := cmd.Run() + if err != nil { + return nil, errors.Wrapf(err, "failed to authorize ceph client %q for filesystem %q. %s", client, filesystem, output) + } + + return output, nil +} diff --git a/pkg/daemon/ceph/client/filesystem_mirror_test.go b/pkg/daemon/ceph/client/filesystem_mirror_test.go new file mode 100644 index 000000000..7e189b7b5 --- /dev/null +++ b/pkg/daemon/ceph/client/filesystem_mirror_test.go @@ -0,0 +1,104 @@ +/* +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 client + +import ( + "testing" + + "github.com/pkg/errors" + "github.com/rook/rook/pkg/clusterd" + exectest "github.com/rook/rook/pkg/util/exec/test" + "github.com/stretchr/testify/assert" +) + +func TestEnableFilesystemSnapshotMirror(t *testing.T) { + fs := "myfs" + executor := &exectest.MockExecutor{} + executor.MockExecuteCommandWithOutput = func(command string, args ...string) (string, error) { + if args[0] == "fs" { + assert.Equal(t, "snapshot", args[1]) + assert.Equal(t, "mirror", args[2]) + assert.Equal(t, "enable", args[3]) + assert.Equal(t, fs, args[4]) + return "", nil + } + return "", errors.New("unknown command") + } + context := &clusterd.Context{Executor: executor} + + err := EnableFilesystemSnapshotMirror(context, AdminClusterInfo("mycluster"), fs) + assert.NoError(t, err) +} + +func TestDisableFilesystemSnapshotMirror(t *testing.T) { + fs := "myfs" + executor := &exectest.MockExecutor{} + executor.MockExecuteCommandWithOutput = func(command string, args ...string) (string, error) { + if args[0] == "fs" { + assert.Equal(t, "snapshot", args[1]) + assert.Equal(t, "mirror", args[2]) + assert.Equal(t, "disable", args[3]) + assert.Equal(t, fs, args[4]) + return "", nil + } + return "", errors.New("unknown command") + } + context := &clusterd.Context{Executor: executor} + + err := DisableFilesystemSnapshotMirror(context, AdminClusterInfo("mycluster"), fs) + assert.NoError(t, err) +} + +func TestAddFilesystemMirrorPeer(t *testing.T) { + fs := "myfs" + peer := "my-peer" + remoteFS := "remoteFS" + executor := &exectest.MockExecutor{} + executor.MockExecuteCommandWithOutput = func(command string, args ...string) (string, error) { + if args[0] == "fs" { + assert.Equal(t, "mirror", args[1]) + assert.Equal(t, "peer_add", args[2]) + assert.Equal(t, fs, args[3]) + assert.Equal(t, peer, args[4]) + assert.Equal(t, remoteFS, args[5]) + return "", nil + } + return "", errors.New("unknown command") + } + context := &clusterd.Context{Executor: executor} + + err := AddFilesystemMirrorPeer(context, AdminClusterInfo("mycluster"), fs, peer, remoteFS) + assert.NoError(t, err) +} + +func TestRemoveFilesystemMirrorPeer(t *testing.T) { + peerUUID := "peer-uuid" + executor := &exectest.MockExecutor{} + executor.MockExecuteCommandWithOutput = func(command string, args ...string) (string, error) { + if args[0] == "fs" { + assert.Equal(t, "mirror", args[1]) + assert.Equal(t, "peer_remove", args[2]) + assert.Equal(t, peerUUID, args[3]) + return "", nil + } + return "", errors.New("unknown command") + } + context := &clusterd.Context{Executor: executor} + + err := RemoveFilesystemMirrorPeer(context, AdminClusterInfo("mycluster"), peerUUID) + assert.NoError(t, err) +} diff --git a/pkg/operator/ceph/cluster/cluster.go b/pkg/operator/ceph/cluster/cluster.go index 70f08bad3..f1c9ff696 100755 --- a/pkg/operator/ceph/cluster/cluster.go +++ b/pkg/operator/ceph/cluster/cluster.go @@ -323,6 +323,22 @@ func (c *cluster) notifyChildControllerOfUpgrade() error { } } + cephFilesystemMirrors, err := c.context.RookClientset.CephV1().CephFilesystemMirrors(c.Namespace).List(ctx, metav1.ListOptions{}) + if err != nil { + return errors.Wrap(err, "failed to list cephfs mirror CRs") + } + for _, cephFilesystemMirror := range cephFilesystemMirrors.Items { + if cephFilesystemMirror.Labels == nil { + cephFilesystemMirror.Labels = map[string]string{} + } + cephFilesystemMirror.Labels["ceph_version"] = version + localCephFilesystemMirror := cephFilesystemMirror + _, err := c.context.RookClientset.CephV1().CephFilesystemMirrors(c.Namespace).Update(ctx, &localCephFilesystemMirror, metav1.UpdateOptions{}) + if err != nil { + return errors.Wrapf(err, "failed to update ceph nfs CR %q with new label", cephFilesystemMirror.Name) + } + } + return nil } diff --git a/pkg/operator/ceph/cluster/rbd/controller.go b/pkg/operator/ceph/cluster/rbd/controller.go index 3feccf381..986dbd159 100644 --- a/pkg/operator/ceph/cluster/rbd/controller.go +++ b/pkg/operator/ceph/cluster/rbd/controller.go @@ -110,6 +110,7 @@ func add(mgr manager.Manager, r reconcile.Reconciler) error { if err != nil { return err } + logger.Info("successfully started") // Watch for changes on the cephRBDMirror CRD object err = c.Watch(&source.Kind{Type: &cephv1.CephRBDMirror{TypeMeta: controllerTypeMeta}}, &handler.EnqueueRequestForObject{}, opcontroller.WatchControllerPredicate()) diff --git a/pkg/operator/ceph/cluster/register_controllers.go b/pkg/operator/ceph/cluster/register_controllers.go index 151bc8dcc..93e1d4da6 100644 --- a/pkg/operator/ceph/cluster/register_controllers.go +++ b/pkg/operator/ceph/cluster/register_controllers.go @@ -27,6 +27,7 @@ import ( "github.com/rook/rook/pkg/operator/ceph/disruption/machinedisruption" "github.com/rook/rook/pkg/operator/ceph/disruption/machinelabel" "github.com/rook/rook/pkg/operator/ceph/file" + "github.com/rook/rook/pkg/operator/ceph/file/mirror" "github.com/rook/rook/pkg/operator/ceph/nfs" "github.com/rook/rook/pkg/operator/ceph/object" "github.com/rook/rook/pkg/operator/ceph/object/realm" @@ -67,6 +68,7 @@ var AddToManagerFuncs = []func(manager.Manager, *clusterd.Context) error{ nfs.Add, rbd.Add, client.Add, + mirror.Add, } // AddToManager adds all the registered controllers to the passed manager. diff --git a/pkg/operator/ceph/config/config.go b/pkg/operator/ceph/config/config.go index 4e4f1a26d..54483ed66 100644 --- a/pkg/operator/ceph/config/config.go +++ b/pkg/operator/ceph/config/config.go @@ -52,6 +52,9 @@ const ( // RbdMirrorType defines the rbd-mirror DaemonType RbdMirrorType = "rbd-mirror" + // FilesystemMirrorType defines the fs-mirror DaemonType + FilesystemMirrorType = "fs-mirror" + // CrashType defines the crash collector DaemonType CrashType = "crashcollector" diff --git a/pkg/operator/ceph/controller/predicate.go b/pkg/operator/ceph/controller/predicate.go index e2fe3938b..45b88a755 100644 --- a/pkg/operator/ceph/controller/predicate.go +++ b/pkg/operator/ceph/controller/predicate.go @@ -285,6 +285,31 @@ func WatchControllerPredicate() predicate.Funcs { if isUpgrade { return true } + + case *cephv1.CephFilesystemMirror: + objNew := e.ObjectNew.(*cephv1.CephFilesystemMirror) + logger.Debug("update event on CephFilesystemMirror CR") + // If the labels "do_not_reconcile" is set on the object, let's not reconcile that request + IsDoNotReconcile := IsDoNotReconcile(objNew.GetLabels()) + if IsDoNotReconcile { + logger.Debugf("object %q matched on update but %q label is set, doing nothing", DoNotReconcileLabelName, objNew.Name) + return false + } + diff := cmp.Diff(objOld.Spec, objNew.Spec, resourceQtyComparer) + if diff != "" { + logger.Infof("CR has changed for %q. diff=%s", objNew.Name, diff) + return true + } else if objOld.GetDeletionTimestamp() != objNew.GetDeletionTimestamp() { + logger.Debugf("CR %q is going be deleted", objNew.Name) + return true + } else if objOld.GetGeneration() != objNew.GetGeneration() { + logger.Debugf("skipping resource %q update with unchanged spec", objNew.Name) + } + // Handling upgrades + isUpgrade := isUpgrade(objOld.GetLabels(), objNew.GetLabels()) + if isUpgrade { + return true + } } return false diff --git a/pkg/operator/ceph/file/controller.go b/pkg/operator/ceph/file/controller.go index 4da7beaba..c07d18bd3 100644 --- a/pkg/operator/ceph/file/controller.go +++ b/pkg/operator/ceph/file/controller.go @@ -288,6 +288,17 @@ func (r *ReconcileCephFilesystem) reconcileCreateFilesystem(cephFilesystem *ceph return reconcile.Result{}, errors.Wrapf(err, "failed to create filesystem %q", cephFilesystem.Name) } + // Enable mirroring if needed + if r.clusterInfo.CephVersion.IsAtLeastPacific() { + if cephFilesystem.Spec.Mirroring.Enabled { + // Enable the mgr module + err = cephclient.MgrEnableModule(r.context, r.clusterInfo, "mirroring", false) + if err != nil { + return reconcile.Result{}, errors.Wrap(err, "failed to enable mirroring mgr module") + } + } + } + return reconcile.Result{}, nil } diff --git a/pkg/operator/ceph/file/mirror/config.go b/pkg/operator/ceph/file/mirror/config.go new file mode 100644 index 000000000..6acd2340c --- /dev/null +++ b/pkg/operator/ceph/file/mirror/config.go @@ -0,0 +1,77 @@ +/* +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 mirror + +import ( + "fmt" + + "github.com/rook/rook/pkg/daemon/ceph/client" + "github.com/rook/rook/pkg/operator/ceph/config" + "github.com/rook/rook/pkg/operator/ceph/config/keyring" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +const ( + keyringTemplate = ` +[client.fs-mirror.%s] + key = %s + caps mon = "allow r" + caps mgr = "allow r" + caps mds = "allow r" + caps osd = "'allow rw tag cephfs metadata=*, allow r tag cephfs data=*'" + +` +) + +// daemonConfig for a single rbd-mirror +type daemonConfig struct { + ResourceName string // the name rook gives to mirror resources in k8s metadata + DaemonID string // the ID of the Ceph daemon ("a", "b", ...) + DataPathMap *config.DataPathMap // location to store data in container + ownerRef metav1.OwnerReference +} + +// PeerToken is the content of the peer token +type PeerToken struct { + ClusterFSID string `json:"fsid"` + ClientID string `json:"client_id"` + Key string `json:"key"` + MonHost string `json:"mon_host"` +} + +func (r *ReconcileFilesystemMirror) generateKeyring(clusterInfo *client.ClusterInfo, daemonConfig *daemonConfig) (string, error) { + user := fullDaemonName(daemonConfig.DaemonID) + access := []string{ + "mon", "allow r", + "mgr", "allow r", + "mds", "allow r", + "osd", "allow rw tag cephfs metadata=*, allow r tag cephfs data=*", + } + s := keyring.GetSecretStore(r.context, clusterInfo, &daemonConfig.ownerRef) + + key, err := s.GenerateKey(user, access) + if err != nil { + return "", err + } + + keyring := fmt.Sprintf(keyringTemplate, daemonConfig.DaemonID, key) + return keyring, s.CreateOrUpdate(daemonConfig.ResourceName, keyring) +} + +func fullDaemonName(daemonID string) string { + return fmt.Sprintf("client.fs-mirror.%s", daemonID) +} diff --git a/pkg/operator/ceph/file/mirror/controller.go b/pkg/operator/ceph/file/mirror/controller.go new file mode 100644 index 000000000..2d879e54d --- /dev/null +++ b/pkg/operator/ceph/file/mirror/controller.go @@ -0,0 +1,263 @@ +/* +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 mirror + +import ( + "context" + "fmt" + "reflect" + + "github.com/coreos/pkg/capnslog" + "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" + opconfig "github.com/rook/rook/pkg/operator/ceph/config" + opcontroller "github.com/rook/rook/pkg/operator/ceph/controller" + "github.com/rook/rook/pkg/operator/k8sutil" + + appsv1 "k8s.io/api/apps/v1" + 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/runtime" + "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/controller" + "sigs.k8s.io/controller-runtime/pkg/handler" + "sigs.k8s.io/controller-runtime/pkg/manager" + "sigs.k8s.io/controller-runtime/pkg/reconcile" + "sigs.k8s.io/controller-runtime/pkg/source" +) + +const ( + controllerName = "ceph-filesystem-mirror-controller" +) + +var logger = capnslog.NewPackageLogger("github.com/rook/rook", controllerName) + +// List of object resources to watch by the controller +var objectsToWatch = []client.Object{ + &v1.ConfigMap{TypeMeta: metav1.TypeMeta{Kind: "ConfigMap", APIVersion: v1.SchemeGroupVersion.String()}}, + &v1.Secret{TypeMeta: metav1.TypeMeta{Kind: "Secret", APIVersion: v1.SchemeGroupVersion.String()}}, + &appsv1.Deployment{TypeMeta: metav1.TypeMeta{Kind: "Deployment", APIVersion: appsv1.SchemeGroupVersion.String()}}, +} + +var cephFilesystemMirrorKind = reflect.TypeOf(cephv1.CephFilesystemMirror{}).Name() + +// Sets the type meta for the controller main object +var controllerTypeMeta = metav1.TypeMeta{ + Kind: cephFilesystemMirrorKind, + APIVersion: fmt.Sprintf("%s/%s", cephv1.CustomResourceGroup, cephv1.Version), +} + +// ReconcileFilesystemMirror reconciles a CephFilesystemMirror object +type ReconcileFilesystemMirror struct { + context *clusterd.Context + clusterInfo *cephclient.ClusterInfo + client client.Client + scheme *runtime.Scheme + cephClusterSpec *cephv1.ClusterSpec +} + +// Add creates a new CephFilesystemMirror Controller and adds it to the Manager. The Manager will set fields on the Controller +// and Start it when the Manager is Started. +func Add(mgr manager.Manager, context *clusterd.Context) error { + return add(mgr, newReconciler(mgr, context)) +} + +// newReconciler returns a new reconcile.Reconciler +func newReconciler(mgr manager.Manager, context *clusterd.Context) reconcile.Reconciler { + // Add the cephv1 scheme to the manager scheme so that the controller knows about it + mgrScheme := mgr.GetScheme() + if err := cephv1.AddToScheme(mgr.GetScheme()); err != nil { + panic(err) + } + return &ReconcileFilesystemMirror{ + client: mgr.GetClient(), + scheme: mgrScheme, + context: context, + } +} + +func add(mgr manager.Manager, r reconcile.Reconciler) error { + // Create a new controller + c, err := controller.New(controllerName, mgr, controller.Options{Reconciler: r}) + if err != nil { + return err + } + logger.Info("successfully started") + + // Watch for changes on the CephFilesystemMirror CRD object + err = c.Watch(&source.Kind{Type: &cephv1.CephFilesystemMirror{TypeMeta: controllerTypeMeta}}, &handler.EnqueueRequestForObject{}, opcontroller.WatchControllerPredicate()) + if err != nil { + return err + } + + // Watch all other resources + for _, t := range objectsToWatch { + err = c.Watch(&source.Kind{Type: t}, &handler.EnqueueRequestForOwner{ + IsController: true, + OwnerType: &cephv1.CephFilesystemMirror{}, + }, opcontroller.WatchPredicateForNonCRDObject(&cephv1.CephFilesystemMirror{TypeMeta: controllerTypeMeta}, mgr.GetScheme())) + if err != nil { + return err + } + } + + // Build Handler function to return the list of ceph object + // This is used by the watchers below + handlerFunc, err := opcontroller.ObjectToCRMapper(mgr.GetClient(), &cephv1.CephFilesystemMirrorList{}, mgr.GetScheme()) + if err != nil { + return err + } + + // Watch for CephCluster Spec changes that we want to propagate to us + err = c.Watch(&source.Kind{Type: &cephv1.CephCluster{ + TypeMeta: metav1.TypeMeta{ + Kind: opcontroller.ClusterResource.Kind, + APIVersion: opcontroller.ClusterResource.APIVersion, + }, + }, + }, handler.EnqueueRequestsFromMapFunc(handlerFunc), opcontroller.WatchCephClusterPredicate()) + if err != nil { + return err + } + + return nil +} + +// Reconcile reads that state of the cluster for a CephFilesystemMirror object and makes changes based on the state read +// and what is in the CephFilesystemMirror.Spec +// 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 *ReconcileFilesystemMirror) 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 { + updateStatus(r.client, request.NamespacedName, k8sutil.FailedStatus) + logger.Errorf("failed to reconcile %v", err) + } + + return reconcileResponse, err +} + +func (r *ReconcileFilesystemMirror) reconcile(request reconcile.Request) (reconcile.Result, error) { + // Fetch the CephFilesystemMirror instance + filesystemMirror := &cephv1.CephFilesystemMirror{} + err := r.client.Get(context.TODO(), request.NamespacedName, filesystemMirror) + if err != nil { + if kerrors.IsNotFound(err) { + logger.Debug("CephFilesystemMirror resource not found. Ignoring since object must be deleted.") + return reconcile.Result{}, nil + } + // Error reading the object - requeue the request. + return reconcile.Result{}, errors.Wrap(err, "failed to get CephFilesystemMirror") + } + + // The CR was just created, initializing status fields + if filesystemMirror.Status == nil { + updateStatus(r.client, request.NamespacedName, k8sutil.Created) + } + + // Make sure a CephCluster is present otherwise do nothing + cephCluster, isReadyToReconcile, _, reconcileResponse := opcontroller.IsReadyToReconcile(r.client, r.context, request.NamespacedName, controllerName) + if !isReadyToReconcile { + logger.Debugf("CephCluster resource not ready in namespace %q, retrying in %q.", request.NamespacedName.Namespace, reconcileResponse.RequeueAfter.String()) + return reconcileResponse, nil + } + + // Assign the clusterSpec + r.cephClusterSpec = &cephCluster.Spec + + // Populate clusterInfo + r.clusterInfo, _, _, err = mon.LoadClusterInfo(r.context, request.NamespacedName.Namespace) + if err != nil { + return opcontroller.ImmediateRetryResult, errors.Wrap(err, "failed to populate cluster info") + } + + // Populate CephVersion + daemon := string(opconfig.MonType) + currentCephVersion, err := cephclient.LeastUptodateDaemonVersion(r.context, r.clusterInfo, daemon) + if err != nil { + return opcontroller.ImmediateRetryResult, errors.Wrapf(err, "failed to retrieve current ceph %q version", daemon) + } + // Validate Ceph version + if !currentCephVersion.IsAtLeastPacific() { + return opcontroller.ImmediateRetryResult, errors.Errorf("ceph pacific version is required to deploy cephfs mirroring, current cluster runs %q", currentCephVersion.String()) + } + r.clusterInfo.CephVersion = currentCephVersion + + // CREATE/UPDATE + logger.Debug("reconciling ceph filesystem mirror deployments") + reconcileResponse, err = r.reconcileFilesystemMirror(filesystemMirror) + if err != nil { + return opcontroller.ImmediateRetryResult, errors.Wrap(err, "failed to create ceph filesystem mirror deployments") + } + + // Set Ready status, we are done reconciling + updateStatus(r.client, request.NamespacedName, k8sutil.ReadyStatus) + + // Return and do not requeue + logger.Debug("done reconciling ceph filesystem mirror") + return reconcile.Result{}, nil + +} + +func (r *ReconcileFilesystemMirror) reconcileFilesystemMirror(filesystemMirror *cephv1.CephFilesystemMirror) (reconcile.Result, error) { + if r.cephClusterSpec.External.Enable { + _, err := opcontroller.ValidateCephVersionsBetweenLocalAndExternalClusters(r.context, r.clusterInfo) + if err != nil { + // This handles the case where the operator is running, the external cluster has been upgraded and a CR creation is called + // If that's a major version upgrade we fail, if it's a minor version, we continue, it's not ideal but not critical + return opcontroller.ImmediateRetryResult, errors.Wrap(err, "refusing to run new crd") + } + } + + err := r.start(filesystemMirror) + if err != nil { + return opcontroller.ImmediateRetryResult, errors.Wrap(err, "failed to start filesystem mirror") + } + + return reconcile.Result{}, nil +} + +// updateStatus updates an object with a given status +func updateStatus(client client.Client, name types.NamespacedName, status string) { + fsMirror := &cephv1.CephFilesystemMirror{} + err := client.Get(context.TODO(), name, fsMirror) + if err != nil { + if kerrors.IsNotFound(err) { + logger.Debug("CephFilesystemMirror resource not found. Ignoring since object must be deleted.") + return + } + logger.Warningf("failed to retrieve filesystem mirror %q to update status to %q. %v", name, status, err) + return + } + + if fsMirror.Status == nil { + fsMirror.Status = &cephv1.Status{} + } + + fsMirror.Status.Phase = status + if err := opcontroller.UpdateStatus(client, fsMirror); err != nil { + logger.Errorf("failed to set filesystem mirror %q status to %q. %v", fsMirror.Name, status, err) + return + } + logger.Debugf("filesystem mirror %q status updated to %q", name, status) +} diff --git a/pkg/operator/ceph/file/mirror/controller_test.go b/pkg/operator/ceph/file/mirror/controller_test.go new file mode 100644 index 000000000..e4532f9e0 --- /dev/null +++ b/pkg/operator/ceph/file/mirror/controller_test.go @@ -0,0 +1,228 @@ +/* +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 mirror to manage a rook filesystem +package mirror + +import ( + "context" + "os" + "testing" + + "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/client/clientset/versioned/scheme" + "github.com/rook/rook/pkg/clusterd" + "github.com/rook/rook/pkg/operator/k8sutil" + "github.com/rook/rook/pkg/operator/test" + 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" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/reconcile" +) + +const ( + cephAuthGetOrCreateKey = `{"key":"AQCvzWBeIV9lFRAAninzm+8XFxbSfTiPwoX50g=="}` + dummyVersionsRaw = ` + { + "mon": { + "ceph version 14.2.8 (3a54b2b6d167d4a2a19e003a705696d4fe619afc) nautilus (stable)": 3 + } + }` + pacificVersionsRaw = ` + { + "mon": { + "ceph version 16.2.1 (3a54b2b6d167d4a2a19e003a705696d4fe619afc) pacific (stable)": 3 + } + }` +) + +func TestCephFilesystemMirrorController(t *testing.T) { + ctx := context.TODO() + var ( + name = "my-fs-mirror" + namespace = "rook-ceph" + ) + // Set DEBUG logging + capnslog.SetGlobalLogLevel(capnslog.DEBUG) + os.Setenv("ROOK_LOG_LEVEL", "DEBUG") + + // + // TEST 1 SETUP + // + // FAILURE because no CephCluster + // + // An cephfs-mirror resource with metadata and spec. + fsMirror := &cephv1.CephFilesystemMirror{ + ObjectMeta: metav1.ObjectMeta{ + Name: name, + Namespace: namespace, + }, + Spec: cephv1.FilesystemMirroringSpec{}, + TypeMeta: controllerTypeMeta, + } + + // Objects to track in the fake client. + object := []runtime.Object{ + fsMirror, + } + + executor := &exectest.MockExecutor{ + MockExecuteCommandWithOutputFile: func(command, outfile string, args ...string) (string, error) { + if args[0] == "status" { + return `{"fsid":"c47cac40-9bee-4d52-823b-ccd803ba5bfe","health":{"checks":{},"status":"HEALTH_ERR"},"pgmap":{"num_pgs":100,"pgs_by_state":[{"state_name":"active+clean","count":100}]}}`, nil + } + if args[0] == "auth" && args[1] == "get-or-create-key" { + return cephAuthGetOrCreateKey, nil + } + if args[0] == "versions" { + return dummyVersionsRaw, nil + } + return "", nil + }, + } + clientset := test.New(t, 3) + c := &clusterd.Context{ + Executor: executor, + RookClientset: rookclient.NewSimpleClientset(), + Clientset: clientset, + } + + // Register operator types with the runtime scheme. + s := scheme.Scheme + s.AddKnownTypes(cephv1.SchemeGroupVersion, &cephv1.CephFilesystemMirror{}) + s.AddKnownTypes(cephv1.SchemeGroupVersion, &cephv1.CephCluster{}) + + // Create a fake client to mock API calls. + cl := fake.NewClientBuilder().WithScheme(s).WithRuntimeObjects(object...).Build() + + // Create a ReconcileFilesystemMirror object with the scheme and fake client. + r := &ReconcileFilesystemMirror{client: cl, scheme: s, context: c} + + // Mock request to simulate Reconcile() being called on an event for a + // watched resource . + req := reconcile.Request{ + NamespacedName: types.NamespacedName{ + Name: name, + Namespace: namespace, + }, + } + logger.Info("STARTING PHASE 1") + res, err := r.Reconcile(ctx, req) + assert.NoError(t, err) + assert.True(t, res.Requeue) + logger.Info("PHASE 1 DONE") + + // + // TEST 2: + // + // FAILURE we have a cluster but it's not ready + // + cephCluster := &cephv1.CephCluster{ + ObjectMeta: metav1.ObjectMeta{ + Name: namespace, + Namespace: namespace, + }, + Status: cephv1.ClusterStatus{ + Phase: "", + CephStatus: &cephv1.CephStatus{ + Health: "", + }, + }, + } + object = append(object, cephCluster) + // Create a fake client to mock API calls. + cl = fake.NewClientBuilder().WithScheme(s).WithRuntimeObjects(object...).Build() + // Create a ReconcileFilesystemMirror object with the scheme and fake client. + r = &ReconcileFilesystemMirror{client: cl, scheme: s, context: c} + logger.Info("STARTING PHASE 2") + res, err = r.Reconcile(ctx, req) + assert.NoError(t, err) + assert.True(t, res.Requeue) + logger.Info("PHASE 2 DONE") + + // + // TEST 3: + // + // SUCCESS! The CephCluster is ready but version is too old! + // + + // Mock clusterInfo + 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) + + // Add ready status to the CephCluster + cephCluster.Status.Phase = k8sutil.ReadyStatus + cephCluster.Status.CephStatus.Health = "HEALTH_OK" + + // Create a fake client to mock API calls. + cl = fake.NewClientBuilder().WithScheme(s).WithRuntimeObjects(object...).Build() + + // Create a ReconcileFilesystemMirror object with the scheme and fake client. + r = &ReconcileFilesystemMirror{ + client: cl, + scheme: s, + context: c, + } + res, err = r.Reconcile(ctx, req) + assert.Error(t, err) + assert.True(t, res.Requeue) + + // + // TEST 4: + // + // SUCCESS! The CephCluster is ready and running Ceph Pacific! + // + r.context.Executor = &exectest.MockExecutor{ + MockExecuteCommandWithOutputFile: func(command, outfile string, args ...string) (string, error) { + if args[0] == "status" { + return `{"fsid":"c47cac40-9bee-4d52-823b-ccd803ba5bfe","health":{"checks":{},"status":"HEALTH_ERR"},"pgmap":{"num_pgs":100,"pgs_by_state":[{"state_name":"active+clean","count":100}]}}`, nil + } + if args[0] == "auth" && args[1] == "get-or-create-key" { + return cephAuthGetOrCreateKey, nil + } + if args[0] == "versions" { + return pacificVersionsRaw, nil + } + return "", nil + }, + } + + res, err = r.Reconcile(ctx, req) + assert.NoError(t, err) + assert.False(t, res.Requeue) + err = r.client.Get(context.TODO(), req.NamespacedName, fsMirror) + assert.NoError(t, err) + assert.Equal(t, "Ready", fsMirror.Status.Phase, fsMirror) +} diff --git a/pkg/operator/ceph/file/mirror/mirror.go b/pkg/operator/ceph/file/mirror/mirror.go new file mode 100644 index 000000000..1c31ccfc5 --- /dev/null +++ b/pkg/operator/ceph/file/mirror/mirror.go @@ -0,0 +1,116 @@ +/* +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 mirror for mirroring +package mirror + +import ( + "context" + "fmt" + + "github.com/banzaicloud/k8s-objectmatcher/patch" + "github.com/pkg/errors" + cephv1 "github.com/rook/rook/pkg/apis/ceph.rook.io/v1" + "github.com/rook/rook/pkg/operator/ceph/cluster/mon" + "github.com/rook/rook/pkg/operator/ceph/config" + "github.com/rook/rook/pkg/operator/ceph/controller" + opcontroller "github.com/rook/rook/pkg/operator/ceph/controller" + "github.com/rook/rook/pkg/operator/k8sutil" + kerrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" +) + +const ( + // AppName is the ceph filesystem mirror application name + AppName = "rook-ceph-fs-mirror" + // minimum amount of memory in MB to run the pod + cephFilesystemMirrorPodMinimumMemory uint64 = 512 +) + +var updateDeploymentAndWait = mon.UpdateCephDeploymentAndWait + +// Start begins the process of running filesystem mirroring daemons. +func (r *ReconcileFilesystemMirror) start(filesystemMirror *cephv1.CephFilesystemMirror) error { + ctx := context.TODO() + // Validate pod's memory if specified + err := controller.CheckPodMemory(cephv1.ResourcesKeyFilesystemMirror, filesystemMirror.Spec.Resources, cephFilesystemMirrorPodMinimumMemory) + if err != nil { + return errors.Wrap(err, "error checking pod memory") + } + + // Create the controller owner ref + // It will be associated to all resources of the CephRBDMirror + ref, err := opcontroller.GetControllerObjectOwnerReference(filesystemMirror, r.scheme) + if err != nil || ref == nil { + return errors.Wrapf(err, "failed to get controller %q owner reference", filesystemMirror.Name) + } + + daemonID := k8sutil.IndexToName(0) + resourceName := fmt.Sprintf("%s-%s", AppName, daemonID) + daemonConf := &daemonConfig{ + DaemonID: daemonID, + ResourceName: resourceName, + DataPathMap: config.NewDatalessDaemonDataPathMap(filesystemMirror.Namespace, r.cephClusterSpec.DataDirHostPath), + ownerRef: *ref, + } + + _, err = r.generateKeyring(r.clusterInfo, daemonConf) + if err != nil { + return errors.Wrapf(err, "failed to generate keyring for %q", resourceName) + } + + // Start the deployment + d, err := r.makeDeployment(daemonConf, filesystemMirror) + if err != nil { + return errors.Wrap(err, "failed to create filesystem-mirror deployment") + } + + // Set owner ref to filesystemMirror object + err = controllerutil.SetControllerReference(filesystemMirror, d, r.scheme) + if err != nil { + return errors.Wrapf(err, "failed to set owner reference for ceph filesystem-mirror %q secret", d.Name) + } + + // Set the deployment hash as an annotation + err = patch.DefaultAnnotator.SetLastAppliedAnnotation(d) + if err != nil { + return errors.Wrapf(err, "failed to set annotation for deployment %q", d.Name) + } + + if _, err := r.context.Clientset.AppsV1().Deployments(filesystemMirror.Namespace).Create(ctx, d, metav1.CreateOptions{}); err != nil { + if !kerrors.IsAlreadyExists(err) { + return errors.Wrapf(err, "failed to create %q deployment", resourceName) + } + logger.Infof("deployment for filesystem-mirror %q already exists. updating if needed", resourceName) + + if err := updateDeploymentAndWait(r.context, r.clusterInfo, d, config.RbdMirrorType, daemonConf.DaemonID, r.cephClusterSpec.SkipUpgradeChecks, false); err != nil { + // fail could be an issue updating label selector (immutable), so try del and recreate + logger.Debugf("updateDeploymentAndWait failed for filesystem-mirror %q. Attempting del-and-recreate. %v", resourceName, err) + err = r.context.Clientset.AppsV1().Deployments(filesystemMirror.Namespace).Delete(ctx, filesystemMirror.Name, metav1.DeleteOptions{}) + if err != nil { + return errors.Wrapf(err, "failed to delete filesystem-mirror %q during del-and-recreate update attempt", resourceName) + } + if _, err := r.context.Clientset.AppsV1().Deployments(filesystemMirror.Namespace).Create(ctx, d, metav1.CreateOptions{}); err != nil { + return errors.Wrapf(err, "failed to recreate filesystem-mirror deployment %q during del-and-recreate update attempt", resourceName) + } + } + } + + logger.Infof("%q deployment started", resourceName) + + return nil +} diff --git a/pkg/operator/ceph/file/mirror/spec.go b/pkg/operator/ceph/file/mirror/spec.go new file mode 100644 index 000000000..ca26465df --- /dev/null +++ b/pkg/operator/ceph/file/mirror/spec.go @@ -0,0 +1,127 @@ +/* +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 mirror + +import ( + "fmt" + + cephv1 "github.com/rook/rook/pkg/apis/ceph.rook.io/v1" + "github.com/rook/rook/pkg/operator/ceph/config" + "github.com/rook/rook/pkg/operator/ceph/controller" + "github.com/rook/rook/pkg/operator/k8sutil" + apps "k8s.io/api/apps/v1" + v1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +func (r *ReconcileFilesystemMirror) makeDeployment(daemonConfig *daemonConfig, fsMirror *cephv1.CephFilesystemMirror) (*apps.Deployment, error) { + podSpec := v1.PodTemplateSpec{ + ObjectMeta: metav1.ObjectMeta{ + Name: daemonConfig.ResourceName, + Labels: controller.CephDaemonAppLabels(AppName, fsMirror.Namespace, config.FilesystemMirrorType, daemonConfig.DaemonID, true), + }, + Spec: v1.PodSpec{ + InitContainers: []v1.Container{ + r.makeChownInitContainer(daemonConfig, fsMirror), + }, + Containers: []v1.Container{ + r.makeFsMirroringDaemonContainer(daemonConfig, fsMirror), + }, + RestartPolicy: v1.RestartPolicyAlways, + Volumes: controller.DaemonVolumes(daemonConfig.DataPathMap, daemonConfig.ResourceName), + HostNetwork: r.cephClusterSpec.Network.IsHost(), + PriorityClassName: fsMirror.Spec.PriorityClassName, + }, + } + + // If the log collector is enabled we add the side-car container + if r.cephClusterSpec.LogCollector.Enabled { + shareProcessNamespace := true + podSpec.Spec.ShareProcessNamespace = &shareProcessNamespace + podSpec.Spec.Containers = append(podSpec.Spec.Containers, *controller.LogCollectorContainer(fmt.Sprintf("ceph-client.fs-mirror.%s", daemonConfig.DaemonID), r.clusterInfo.Namespace, *r.cephClusterSpec)) + } + + // Replace default unreachable node toleration + k8sutil.AddUnreachableNodeToleration(&podSpec.Spec) + fsMirror.Spec.Annotations.ApplyToObjectMeta(&podSpec.ObjectMeta) + fsMirror.Spec.Labels.ApplyToObjectMeta(&podSpec.ObjectMeta) + + if r.cephClusterSpec.Network.IsHost() { + podSpec.Spec.DNSPolicy = v1.DNSClusterFirstWithHostNet + } else if r.cephClusterSpec.Network.IsMultus() { + if err := k8sutil.ApplyMultus(r.cephClusterSpec.Network.NetworkSpec, &podSpec.ObjectMeta); err != nil { + return nil, err + } + } + fsMirror.Spec.Placement.ApplyToPodSpec(&podSpec.Spec) + + replicas := int32(1) + d := &apps.Deployment{ + ObjectMeta: metav1.ObjectMeta{ + Name: daemonConfig.ResourceName, + Namespace: fsMirror.Namespace, + Annotations: fsMirror.Spec.Annotations, + Labels: controller.CephDaemonAppLabels(AppName, fsMirror.Namespace, config.FilesystemMirrorType, daemonConfig.DaemonID, true), + }, + Spec: apps.DeploymentSpec{ + Selector: &metav1.LabelSelector{ + MatchLabels: podSpec.Labels, + }, + Template: podSpec, + Replicas: &replicas, + }, + } + k8sutil.AddRookVersionLabelToDeployment(d) + controller.AddCephVersionLabelToDeployment(r.clusterInfo.CephVersion, d) + fsMirror.Spec.Annotations.ApplyToObjectMeta(&d.ObjectMeta) + fsMirror.Spec.Labels.ApplyToObjectMeta(&d.ObjectMeta) + + return d, nil +} + +func (r *ReconcileFilesystemMirror) makeChownInitContainer(daemonConfig *daemonConfig, fsMirror *cephv1.CephFilesystemMirror) v1.Container { + return controller.ChownCephDataDirsInitContainer( + *daemonConfig.DataPathMap, + r.cephClusterSpec.CephVersion.Image, + controller.DaemonVolumeMounts(daemonConfig.DataPathMap, daemonConfig.ResourceName), + fsMirror.Spec.Resources, + controller.PodSecurityContext(), + ) +} + +func (r *ReconcileFilesystemMirror) makeFsMirroringDaemonContainer(daemonConfig *daemonConfig, fsMirror *cephv1.CephFilesystemMirror) v1.Container { + container := v1.Container{ + Name: "fs-mirror", + Command: []string{ + "cephfs-mirror", + }, + Args: append( + controller.DaemonFlags(r.clusterInfo, r.cephClusterSpec, daemonConfig.DaemonID), + "--foreground", + "--name="+fullDaemonName(daemonConfig.DaemonID), + ), + Image: r.cephClusterSpec.CephVersion.Image, + VolumeMounts: controller.DaemonVolumeMounts(daemonConfig.DataPathMap, daemonConfig.ResourceName), + Env: controller.DaemonEnvVars(r.cephClusterSpec.CephVersion.Image), + Resources: fsMirror.Spec.Resources, + SecurityContext: controller.PodSecurityContext(), + // TODO: + // LivenessProbe: controller.GenerateLivenessProbeExecDaemon(config.fsMirrorType, daemonConfig.DaemonID), + } + + return container +} diff --git a/pkg/operator/ceph/file/mirror/spec_test.go b/pkg/operator/ceph/file/mirror/spec_test.go new file mode 100644 index 000000000..f31a2c2b3 --- /dev/null +++ b/pkg/operator/ceph/file/mirror/spec_test.go @@ -0,0 +1,100 @@ +/* +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 mirror + +import ( + "testing" + + cephv1 "github.com/rook/rook/pkg/apis/ceph.rook.io/v1" + "github.com/rook/rook/pkg/client/clientset/versioned/scheme" + cephclient "github.com/rook/rook/pkg/daemon/ceph/client" + "github.com/rook/rook/pkg/operator/ceph/config" + cephtest "github.com/rook/rook/pkg/operator/ceph/test" + cephver "github.com/rook/rook/pkg/operator/ceph/version" + "github.com/stretchr/testify/assert" + v1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/api/resource" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "sigs.k8s.io/controller-runtime/pkg/client/fake" +) + +func TestPodSpec(t *testing.T) { + namespace := "ns" + daemonConf := daemonConfig{ + DaemonID: "a", + ResourceName: "rook-ceph-fs-mirror-a", + DataPathMap: config.NewDatalessDaemonDataPathMap("rook-ceph", "/var/lib/rook"), + } + cephCluster := &cephv1.CephCluster{ + ObjectMeta: metav1.ObjectMeta{ + Name: namespace, + Namespace: namespace, + }, + Spec: cephv1.ClusterSpec{ + CephVersion: cephv1.CephVersionSpec{ + Image: "ceph/ceph:v16", + }, + }, + } + + fsMirror := &cephv1.CephFilesystemMirror{ + ObjectMeta: metav1.ObjectMeta{ + Name: "a", + Namespace: namespace, + }, + Spec: cephv1.FilesystemMirroringSpec{ + Resources: v1.ResourceRequirements{ + Limits: v1.ResourceList{ + v1.ResourceCPU: *resource.NewQuantity(200.0, resource.BinarySI), + v1.ResourceMemory: *resource.NewQuantity(600.0, resource.BinarySI), + }, + Requests: v1.ResourceList{ + v1.ResourceCPU: *resource.NewQuantity(100.0, resource.BinarySI), + v1.ResourceMemory: *resource.NewQuantity(300.0, resource.BinarySI), + }, + }, + PriorityClassName: "my-priority-class", + }, + TypeMeta: controllerTypeMeta, + } + clusterInfo := &cephclient.ClusterInfo{ + CephVersion: cephver.Nautilus, + } + s := scheme.Scheme + object := []runtime.Object{fsMirror} + cl := fake.NewClientBuilder().WithScheme(s).WithRuntimeObjects(object...).Build() + r := &ReconcileFilesystemMirror{client: cl, scheme: s} + r.cephClusterSpec = &cephCluster.Spec + r.clusterInfo = clusterInfo + + d, err := r.makeDeployment(&daemonConf, fsMirror) + assert.NoError(t, err) + assert.Equal(t, "rook-ceph-fs-mirror-a", d.Name) + assert.Equal(t, 4, len(d.Spec.Template.Spec.Volumes)) + assert.Equal(t, 1, len(d.Spec.Template.Spec.Volumes[0].Projected.Sources)) + assert.Equal(t, 4, len(d.Spec.Template.Spec.Containers[0].VolumeMounts)) + + // Deployment should have Ceph labels + cephtest.AssertLabelsContainCephRequirements(t, d.ObjectMeta.Labels, + config.FilesystemMirrorType, "a", AppName, "ns") + + podTemplate := cephtest.NewPodTemplateSpecTester(t, &d.Spec.Template) + podTemplate.RunFullSuite(config.FilesystemMirrorType, "a", AppName, "ns", "ceph/ceph:v16", + "200", "100", "600", "300", /* resources */ + "my-priority-class") +} diff --git a/pkg/operator/ceph/test/podspec.go b/pkg/operator/ceph/test/podspec.go index 421912aed..e0647531b 100644 --- a/pkg/operator/ceph/test/podspec.go +++ b/pkg/operator/ceph/test/podspec.go @@ -74,7 +74,7 @@ func (ps *PodSpecTester) AssertVolumesMeetCephRequirements( keyringSecretName = "rook-ceph-mons-keyring" } requiredVols := []string{"rook-config-override", keyringSecretName} - if daemonType != config.RbdMirrorType { + if daemonType != config.RbdMirrorType && daemonType != config.FilesystemMirrorType { requiredVols = append(requiredVols, "ceph-daemon-data") } vols := []string{} diff --git a/tests/framework/installer/ceph_installer.go b/tests/framework/installer/ceph_installer.go index c0894b2a2..391889759 100644 --- a/tests/framework/installer/ceph_installer.go +++ b/tests/framework/installer/ceph_installer.go @@ -624,7 +624,8 @@ func (h *CephInstaller) UninstallRookFromMultipleNS(systemNamespace string, name "volumes.rook.io", "objectbuckets.objectbucket.io", "objectbucketclaims.objectbucket.io", - "cephrbdmirrors.ceph.rook.io") + "cephrbdmirrors.ceph.rook.io", + "cephfilesystemmirrors.ceph.rook.io") checkError(h.T(), err, "cannot delete CRDs") if !h.useHelm { diff --git a/tests/framework/installer/ceph_manifests.go b/tests/framework/installer/ceph_manifests.go index 54fb0a6fe..52149296d 100644 --- a/tests/framework/installer/ceph_manifests.go +++ b/tests/framework/installer/ceph_manifests.go @@ -1433,6 +1433,49 @@ spec: status: type: object x-kubernetes-preserve-unknown-fields: true + subresources: + status: {} +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: cephfilesystemmirrors.ceph.rook.io +spec: + group: ceph.rook.io + names: + kind: CephFilesystemMirror + listKind: CephFilesystemMirrorList + plural: cephfilesystemmirrors + singular: cephfilesystemmirror + scope: Namespaced + versions: + - name: v1 + served: true + storage: true + schema: + openAPIV3Schema: + type: object + properties: + spec: + type: object + properties: + resources: + type: object + nullable: true + x-kubernetes-preserve-unknown-fields: true + priorityClassName: + type: string + placement: + type: object + nullable: true + x-kubernetes-preserve-unknown-fields: true + annotations: + type: object + nullable: true + x-kubernetes-preserve-unknown-fields: true + status: + type: object + x-kubernetes-preserve-unknown-fields: true subresources: status: {}` } diff --git a/tests/scripts/validate_cluster.sh b/tests/scripts/validate_cluster.sh index 17c5dc656..bbdca3d09 100755 --- a/tests/scripts/validate_cluster.sh +++ b/tests/scripts/validate_cluster.sh @@ -65,6 +65,15 @@ function test_demo_rbd_mirror { return $(wait_for_daemon "$EXEC_COMMAND -s | grep -sq 'rbd-mirror:'") } +function test_demo_fs_mirror { + # shellcheck disable=SC2046 + timeout 90 sh -c 'until [ $(kubectl -n rook-ceph get pods --field-selector=status.phase=Running -l app=rook-ceph-filesystem-mirror --no-headers=true|wc -l) -eq 1 ]; do sleep 1; done' + if [ $? -eq 0 ]; then + return 0 + fi + return 1 +} + function test_demo_pool { # shellcheck disable=SC2046 return $(wait_for_daemon "$EXEC_COMMAND -s | grep -sq '11 pools'")