object: do not create service for external object stores

External CephObjectStores already have endpoints defined by
spec.gateway.externalRgwEndpoints, and if the external store is
configured with TLS (HTTPS), the store's certificates will likely not
accept connections intended for the Service endpoint Rook creates. Some
users might not be able to easily add the service endpoint to their
certificates. Therefore, don't even bother creating a Service for
external clusters.

This does introduce a few issues. The Service seems to have been
initially created to allow multiple external RGW endpoints to be
addressable via a single address in Rook. For all connections to an
external CephObjectStore with multiple endpoints, simply choose an
endpoint at random. Random selection will prevent Rook from failing to
create buckets or users on an external store if one of the external
store's endpoints fails.

The latest OBC library (lib-bucket-provisioner) allows updating the
endpoints on ObjectBuckets after they are created. This allows Rook
users to change endpoints on external CephObjectStores without breaking
all existing OBCs. It requires implementation of the new GetUserID()
library call, requires updating Provision() and Grant() calls to be
idempotent, and it requires removing the Update() call.

Signed-off-by: Blaine Gardner <blaine.gardner@redhat.com>
(cherry picked from commit a777b1d7d1)

# Conflicts:
#	pkg/apis/ceph.rook.io/v1/types.go
This commit is contained in:
Blaine Gardner committed 2022-11-07 14:30:58 -07:00
1 parent acd178835f
commit cb10fe35fa
26 files changed
+651 -337

No files matched your search

@@ -108,7 +108,12 @@ The gateway settings correspond to the RGW daemon settings.
* `port`: The port on which the Object service will be reachable. If host networking is enabled, the RGW daemons will also listen on that port. If running on SDN, the RGW daemon listening port will be 8080 internally.
* `securePort`: The secure port on which RGW pods will be listening. A TLS certificate must be specified either via `sslCerticateRef` or `service.annotations`
* `instances`: The number of pods that will be started to load balance this object store.
* `externalRgwEndpoints`: A list of IP addresses to connect to external existing Rados Gateways (works with external mode). This setting will be ignored if the `CephCluster` does not have `external` spec enabled. Refer to the [external cluster section](../Cluster/ceph-cluster-crd.md#external-cluster) for more details.
* `externalRgwEndpoints`: A list of IP addresses to connect to external existing Rados Gateways
(works with external mode). This setting will be ignored if the `CephCluster` does not have
`external` spec enabled. Refer to the [external cluster section](../Cluster/ceph-cluster-crd.md#external-cluster)
for more details. Multiple endpoints can be given, but for stability of ObjectBucketClaims, we
highly recommend that users give only a single external RGW endpoint that is a load balancer that
sends requests to the multiple RGWs.
* `annotations`: Key value pair list of annotations to add.
* `labels`: Key value pair list of labels to add.
* `placement`: The Kubernetes placement settings to determine where the RGW pods should be started in the cluster.
@@ -11564,46 +11564,16 @@ spec:
nullable: true
type: string
externalRgwEndpoints:
description: ExternalRgwEndpoints points to external rgw endpoint(s)
description: ExternalRgwEndpoints points to external RGW endpoint(s). Multiple endpoints can be given, but for stability of ObjectBucketClaims, we highly recommend that users give only a single external RGW endpoint that is a load balancer that sends requests to the multiple RGWs.
items:
description: EndpointAddress is a tuple that describes single IP address.
description: EndpointAddress is a tuple that describes a single IP address or host name. This is a subset of Kubernetes's v1.EndpointAddress.
properties:
hostname:
description: The Hostname of this endpoint
type: string
ip:
description: 'The IP of this endpoint. May not be loopback (127.0.0.0/8), link-local (169.254.0.0/16), or link-local multicast ((224.0.0.0/24). IPv6 is also accepted but not fully supported on all platforms. Also, certain kubernetes components, like kube-proxy, are not IPv6 ready. TODO: This should allow hostname or IP, See #4447.'
description: The IP of this endpoint.
type: string
nodeName:
description: 'Optional: Node hosting this endpoint. This can be used to determine endpoints local to a node.'
type: string
targetRef:
description: Reference to object providing the endpoint.
properties:
apiVersion:
description: API version of the referent.
type: string
fieldPath:
description: 'If referring to a piece of an object instead of an entire object, this string should contain a valid JSON/Go field access statement, such as desiredState.manifest.containers[2]. For example, if the object reference is to a container within a pod, this would take on a value like: "spec.containers{name}" (where "name" refers to the name of the container that triggered the event) or if no container name is specified "spec.containers[2]" (container with index 2 in this pod). This syntax is chosen only to have some well-defined way of referencing a part of an object. TODO: this design is not final and this field is subject to change in the future.'
type: string
kind:
description: 'Kind of the referent. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds'
type: string
name:
description: 'Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names'
type: string
namespace:
description: 'Namespace of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/'
type: string
resourceVersion:
description: 'Specific resourceVersion to which this reference is made, if any. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency'
type: string
uid:
description: 'UID of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#uids'
type: string
type: object
required:
- ip
type: object
nullable: true
type: array
@@ -12823,6 +12793,17 @@ spec:
type: string
type: object
type: array
endpoints:
properties:
insecure:
items:
type: string
type: array
secure:
items:
type: string
type: array
type: object
info:
additionalProperties:
type: string
@@ -12837,6 +12818,8 @@ spec:
phase:
description: ConditionType represent a resource's status
type: string
required:
- endpoints
type: object
x-kubernetes-preserve-unknown-fields: true
required:
+16 -33
View File
@@ -11556,46 +11556,16 @@ spec:
nullable: true
type: string
externalRgwEndpoints:
description: ExternalRgwEndpoints points to external rgw endpoint(s)
description: ExternalRgwEndpoints points to external RGW endpoint(s). Multiple endpoints can be given, but for stability of ObjectBucketClaims, we highly recommend that users give only a single external RGW endpoint that is a load balancer that sends requests to the multiple RGWs.
items:
description: EndpointAddress is a tuple that describes single IP address.
description: EndpointAddress is a tuple that describes a single IP address or host name. This is a subset of Kubernetes's v1.EndpointAddress.
properties:
hostname:
description: The Hostname of this endpoint
type: string
ip:
description: 'The IP of this endpoint. May not be loopback (127.0.0.0/8), link-local (169.254.0.0/16), or link-local multicast ((224.0.0.0/24). IPv6 is also accepted but not fully supported on all platforms. Also, certain kubernetes components, like kube-proxy, are not IPv6 ready. TODO: This should allow hostname or IP, See #4447.'
description: The IP of this endpoint.
type: string
nodeName:
description: 'Optional: Node hosting this endpoint. This can be used to determine endpoints local to a node.'
type: string
targetRef:
description: Reference to object providing the endpoint.
properties:
apiVersion:
description: API version of the referent.
type: string
fieldPath:
description: 'If referring to a piece of an object instead of an entire object, this string should contain a valid JSON/Go field access statement, such as desiredState.manifest.containers[2]. For example, if the object reference is to a container within a pod, this would take on a value like: "spec.containers{name}" (where "name" refers to the name of the container that triggered the event) or if no container name is specified "spec.containers[2]" (container with index 2 in this pod). This syntax is chosen only to have some well-defined way of referencing a part of an object. TODO: this design is not final and this field is subject to change in the future.'
type: string
kind:
description: 'Kind of the referent. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds'
type: string
name:
description: 'Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names'
type: string
namespace:
description: 'Namespace of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/'
type: string
resourceVersion:
description: 'Specific resourceVersion to which this reference is made, if any. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency'
type: string
uid:
description: 'UID of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#uids'
type: string
type: object
required:
- ip
type: object
nullable: true
type: array
@@ -12815,6 +12785,17 @@ spec:
type: string
type: object
type: array
endpoints:
properties:
insecure:
items:
type: string
type: array
secure:
items:
type: string
type: array
type: object
info:
additionalProperties:
type: string
@@ -12829,6 +12810,8 @@ spec:
phase:
description: ConditionType represent a resource's status
type: string
required:
- endpoints
type: object
x-kubernetes-preserve-unknown-fields: true
required:
+1 -1
View File
@@ -18,7 +18,7 @@ require (
github.com/hashicorp/vault/sdk v0.6.1-0.20221010215534-6545e24b6023
github.com/jetstack/cert-manager v1.7.3
github.com/k8snetworkplumbingwg/network-attachment-definition-client v1.3.0
github.com/kube-object-storage/lib-bucket-provisioner v0.0.0-20220811192603-abc54caa34ac
github.com/kube-object-storage/lib-bucket-provisioner v0.0.0-20221103224036-07dde5c41fdd
github.com/libopenstorage/secrets v0.0.0-20220823020833-2ecadaf59d8a
github.com/openshift/api v0.0.0-20210105115604-44119421ec6b
github.com/openshift/cluster-api v0.0.0-20191129101638-b09907ac6668
+2 -2
View File
@@ -1161,8 +1161,8 @@ github.com/kr/pty v1.1.5/go.mod h1:9r2w37qlBe7rQ6e1fg1S/9xpWHSnaqNdHD3WcMdbPDA=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/kube-object-storage/lib-bucket-provisioner v0.0.0-20220811192603-abc54caa34ac h1:7B0uHL8ttX9Az1vDaHK8JVVC+SY4riK6qgGyo+3e2D8=
github.com/kube-object-storage/lib-bucket-provisioner v0.0.0-20220811192603-abc54caa34ac/go.mod h1:my+EVjOJLeQ9lUR9uVkxRvNNkhO2saSGIgzV8GZT9HY=
github.com/kube-object-storage/lib-bucket-provisioner v0.0.0-20221103224036-07dde5c41fdd h1:w9t8utABD/pa2t1+J3KZH8zyNhJpDFUcIWcAxpcSbVI=
github.com/kube-object-storage/lib-bucket-provisioner v0.0.0-20221103224036-07dde5c41fdd/go.mod h1:my+EVjOJLeQ9lUR9uVkxRvNNkhO2saSGIgzV8GZT9HY=
github.com/kubernetes-csi/external-snapshotter/client/v4 v4.0.0/go.mod h1:YBCo4DoEeDndqvAn6eeu0vWM7QdXmHEeI9cFWplmBys=
github.com/lib/pq v1.1.1/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
github.com/lib/pq v1.2.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
+9
View File
@@ -121,3 +121,12 @@ func (c *CephObjectStore) GetStatusConditions() *[]Condition {
func (z *CephObjectZone) GetStatusConditions() *[]Condition {
return &z.Status.Conditions
}
// String returns an addressable string representation of the EndpointAddress.
func (e *EndpointAddress) String() string {
// hostname is easier to read, and it is probably less likely to change, so prefer it over IP
if e.Hostname != "" {
return e.Hostname
}
return e.IP
}
+25 -3
View File
@@ -1425,10 +1425,12 @@ type GatewaySpec struct {
// +optional
PriorityClassName string `json:"priorityClassName,omitempty"`
// ExternalRgwEndpoints points to external rgw endpoint(s)
// ExternalRgwEndpoints points to external RGW endpoint(s). Multiple endpoints can be given, but
// for stability of ObjectBucketClaims, we highly recommend that users give only a single
// external RGW endpoint that is a load balancer that sends requests to the multiple RGWs.
// +nullable
// +optional
ExternalRgwEndpoints []v1.EndpointAddress `json:"externalRgwEndpoints,omitempty"`
ExternalRgwEndpoints []EndpointAddress `json:"externalRgwEndpoints,omitempty"`
// The configuration related to add/set on each rgw service.
// +optional
@@ -1442,6 +1444,18 @@ type GatewaySpec struct {
HostNetwork *bool `json:"hostNetwork,omitempty"`
}
// EndpointAddress is a tuple that describes a single IP address or host name. This is a subset of
// Kubernetes's v1.EndpointAddress.
// +structType=atomic
type EndpointAddress struct {
// The IP of this endpoint.
// +optional
IP string `json:"ip" protobuf:"bytes,1,opt,name=ip"`
// The Hostname of this endpoint
// +optional
Hostname string `json:"hostname,omitempty" protobuf:"bytes,3,opt,name=hostname"`
}
// ZoneSpec represents a Ceph Object Store Gateway Zone specification
type ZoneSpec struct {
// RGW Zone the Object Store is in
@@ -1455,7 +1469,8 @@ type ObjectStoreStatus struct {
// +optional
Message string `json:"message,omitempty"`
// +optional
BucketStatus *BucketStatus `json:"bucketStatus,omitempty"`
BucketStatus *BucketStatus `json:"bucketStatus,omitempty"`
Endpoints ObjectEndpoints `json:"endpoints"`
// +optional
// +nullable
Info map[string]string `json:"info,omitempty"`
@@ -1477,6 +1492,13 @@ type BucketStatus struct {
LastChanged string `json:"lastChanged,omitempty"`
}
type ObjectEndpoints struct {
// +optional
Insecure []string `json:"insecure"`
// +optional
Secure []string `json:"secure"`
}
// CephObjectStoreUser represents a Ceph Object Store Gateway User
// +genclient
// +genclient:noStatus
@@ -2009,6 +2009,22 @@ func (in *EncryptionSpec) DeepCopy() *EncryptionSpec {
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *EndpointAddress) DeepCopyInto(out *EndpointAddress) {
*out = *in
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EndpointAddress.
func (in *EndpointAddress) DeepCopy() *EndpointAddress {
if in == nil {
return nil
}
out := new(EndpointAddress)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ErasureCodedSpec) DeepCopyInto(out *ErasureCodedSpec) {
*out = *in
@@ -2353,10 +2369,8 @@ func (in *GatewaySpec) DeepCopyInto(out *GatewaySpec) {
in.Resources.DeepCopyInto(&out.Resources)
if in.ExternalRgwEndpoints != nil {
in, out := &in.ExternalRgwEndpoints, &out.ExternalRgwEndpoints
*out = make([]corev1.EndpointAddress, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
*out = make([]EndpointAddress, len(*in))
copy(*out, *in)
}
if in.Service != nil {
in, out := &in.Service, &out.Service
@@ -3059,6 +3073,32 @@ func (in *NotificationKeyFilterRule) DeepCopy() *NotificationKeyFilterRule {
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ObjectEndpoints) DeepCopyInto(out *ObjectEndpoints) {
*out = *in
if in.Insecure != nil {
in, out := &in.Insecure, &out.Insecure
*out = make([]string, len(*in))
copy(*out, *in)
}
if in.Secure != nil {
in, out := &in.Secure, &out.Secure
*out = make([]string, len(*in))
copy(*out, *in)
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ObjectEndpoints.
func (in *ObjectEndpoints) DeepCopy() *ObjectEndpoints {
if in == nil {
return nil
}
out := new(ObjectEndpoints)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ObjectRealmSpec) DeepCopyInto(out *ObjectRealmSpec) {
*out = *in
@@ -3128,6 +3168,7 @@ func (in *ObjectStoreStatus) DeepCopyInto(out *ObjectStoreStatus) {
*out = new(BucketStatus)
**out = **in
}
in.Endpoints.DeepCopyInto(&out.Endpoints)
if in.Info != nil {
in, out := &in.Info, &out.Info
*out = make(map[string]string, len(*in))
+4 -4
View File
@@ -117,7 +117,7 @@ func NewMultisiteContext(context *clusterd.Context, clusterInfo *cephclient.Clus
objContext := NewContext(context, clusterInfo, store.Name)
objContext.UID = string(store.UID)
if err := UpdateEndpoint(objContext, &store.Spec); err != nil {
if err := UpdateEndpoint(objContext, store); err != nil {
return nil, err
}
@@ -133,14 +133,14 @@ func NewMultisiteContext(context *clusterd.Context, clusterInfo *cephclient.Clus
}
// UpdateEndpoint updates an object.Context using the latest info from the CephObjectStore spec
func UpdateEndpoint(objContext *Context, spec *cephv1.ObjectStoreSpec) error {
func UpdateEndpoint(objContext *Context, store *cephv1.CephObjectStore) error {
nsName := fmt.Sprintf("%s/%s", objContext.clusterInfo.Namespace, objContext.Name)
port, err := spec.GetPort()
port, err := store.Spec.GetPort()
if err != nil {
return errors.Wrapf(err, "failed to get port for object store %q", nsName)
}
objContext.Endpoint = BuildDNSEndpoint(BuildDomainName(objContext.Name, objContext.clusterInfo.Namespace), port, spec.IsTLSEnabled())
objContext.Endpoint = BuildDNSEndpoint(GetDomainName(store), port, store.Spec.IsTLSEnabled())
return nil
}
+98 -130
View File
@@ -19,12 +19,12 @@ package bucket
import (
"fmt"
"net/http"
"strconv"
"strings"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/ceph/go-ceph/rgw/admin"
"github.com/coreos/pkg/capnslog"
"github.com/kube-object-storage/lib-bucket-provisioner/pkg/apis/objectbucket.io/v1alpha1"
bktv1alpha1 "github.com/kube-object-storage/lib-bucket-provisioner/pkg/apis/objectbucket.io/v1alpha1"
apibkt "github.com/kube-object-storage/lib-bucket-provisioner/pkg/provisioner/api"
opcontroller "github.com/rook/rook/pkg/operator/ceph/controller"
@@ -63,6 +63,16 @@ func NewProvisioner(context *clusterd.Context, clusterInfo *client.ClusterInfo)
return &Provisioner{context: context, clusterInfo: clusterInfo}
}
func (p Provisioner) GenerateUserID(obc *v1alpha1.ObjectBucketClaim, ob *v1alpha1.ObjectBucket) (string, error) {
if ob != nil {
return getCephUser(ob), nil
}
username := p.genUserName(obc.Name, obc.Namespace)
return username, nil
}
// Provision creates an s3 bucket and returns a connection info
// representing the bucket's endpoint and user access credentials.
func (p Provisioner) Provision(options *apibkt.BucketOptions) (*bktv1alpha1.ObjectBucket, error) {
@@ -74,8 +84,7 @@ func (p Provisioner) Provision(options *apibkt.BucketOptions) (*bktv1alpha1.Obje
}
logger.Infof("Provision: creating bucket %q for OBC %q", p.bucketName, options.ObjectBucketClaim.Name)
// dynamically create a new ceph user
p.accessKeyID, p.secretAccessKey, err = p.createCephUser("")
p.accessKeyID, p.secretAccessKey, err = p.createCephUser(options.UserID)
if err != nil {
return nil, errors.Wrap(err, "Provision: can't create ceph user")
}
@@ -87,32 +96,37 @@ func (p Provisioner) Provision(options *apibkt.BucketOptions) (*bktv1alpha1.Obje
s3svc, err = object.NewS3Agent(p.accessKeyID, p.secretAccessKey, p.getObjectStoreEndpoint(), logger.LevelAt(capnslog.DEBUG), p.tlsCert)
}
if err != nil {
p.deleteOBCResourceLogError("")
return nil, err
}
// create the bucket
err = s3svc.CreateBucket(p.bucketName)
var bucketExists bool
bucketExists, err = p.bucketExists(p.bucketName)
if err != nil {
err = errors.Wrapf(err, "error creating bucket %q", p.bucketName)
logger.Errorf(err.Error())
p.deleteOBCResourceLogError("")
return nil, err
return nil, errors.Wrapf(err, "error creating bucket %q. failed to check if bucket already exists", p.bucketName)
}
if !bucketExists {
// if bucket already exists, this returns error: TooManyBuckets because we set the quota
// below. If it already exists, assume we are good to go
logger.Debugf("creating bucket %q", p.bucketName)
err = s3svc.CreateBucket(p.bucketName)
if err != nil {
return nil, errors.Wrapf(err, "error creating bucket %q", p.bucketName)
}
} else {
logger.Debugf("bucket %q already exists", p.bucketName)
}
singleBucketQuota := 1
_, err = p.adminOpsClient.ModifyUser(p.clusterInfo.Context, admin.User{ID: p.cephUserName, MaxBuckets: &singleBucketQuota})
if err != nil {
p.deleteOBCResourceLogError(p.bucketName)
return nil, err
return nil, errors.Wrapf(err, "failed to set user %q bucket quota to %d", p.cephUserName, singleBucketQuota)
}
logger.Infof("set user %q bucket max to %d", p.cephUserName, singleBucketQuota)
// setting quota limit if it is enabled
err = p.setAdditionalSettings(options)
if err != nil {
p.deleteOBCResourceLogError(p.bucketName)
return nil, err
return nil, errors.Wrapf(err, "failed to set additional settings for OBC %q", options.ObjectBucketClaim.Name)
}
return p.composeObjectBucket(), nil
@@ -136,29 +150,27 @@ func (p Provisioner) Grant(options *apibkt.BucketOptions) (*bktv1alpha1.ObjectBu
return nil, errors.Wrapf(err, "bucket %s does not exist", p.bucketName)
}
p.accessKeyID, p.secretAccessKey, err = p.createCephUser("")
// get or create ceph user
p.accessKeyID, p.secretAccessKey, err = p.createCephUser(options.UserID)
if err != nil {
return nil, err
return nil, errors.Wrap(err, "Provision: can't create ceph user")
}
// need to quota into -1 for restricting creation of new buckets in rgw
restrictBucketCreation := -1
// restrict creation of new buckets in rgw
restrictBucketCreation := 0
_, err = p.adminOpsClient.ModifyUser(p.clusterInfo.Context, admin.User{ID: p.cephUserName, MaxBuckets: &restrictBucketCreation})
if err != nil {
p.deleteOBCResourceLogError("")
return nil, err
}
// get the bucket's owner via the bucket metadata
stats, err := p.adminOpsClient.GetBucketInfo(p.clusterInfo.Context, admin.Bucket{Bucket: p.bucketName})
if err != nil {
p.deleteOBCResourceLogError("")
return nil, errors.Wrapf(err, "failed to get bucket %q stats", p.bucketName)
}
objectUser, err := p.adminOpsClient.GetUser(p.clusterInfo.Context, admin.User{ID: stats.Owner})
if err != nil {
p.deleteOBCResourceLogError("")
return nil, errors.Wrapf(err, "failed to get user %q", stats.Owner)
}
@@ -169,7 +181,6 @@ func (p Provisioner) Grant(options *apibkt.BucketOptions) (*bktv1alpha1.ObjectBu
s3svc, err = object.NewS3Agent(objectUser.Keys[0].AccessKey, objectUser.Keys[0].SecretKey, p.getObjectStoreEndpoint(), logger.LevelAt(capnslog.DEBUG), p.tlsCert)
}
if err != nil {
p.deleteOBCResourceLogError("")
return nil, err
}
@@ -178,7 +189,6 @@ func (p Provisioner) Grant(options *apibkt.BucketOptions) (*bktv1alpha1.ObjectBu
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
if aerr.Code() != "NoSuchBucketPolicy" {
p.deleteOBCResourceLogError("")
return nil, err
}
}
@@ -200,14 +210,12 @@ func (p Provisioner) Grant(options *apibkt.BucketOptions) (*bktv1alpha1.ObjectBu
logger.Infof("PutBucketPolicy output: %v", out)
if err != nil {
p.deleteOBCResourceLogError("")
return nil, err
}
// setting quota limit if it is enabled
err = p.setAdditionalSettings(options)
if err != nil {
p.deleteOBCResourceLogError("")
return nil, err
}
@@ -321,7 +329,11 @@ func (p Provisioner) Revoke(ob *bktv1alpha1.ObjectBucket) error {
}
// finally, delete the user
p.deleteOBCResourceLogError("")
err = p.deleteOBCResource("")
if err != nil {
return errors.Wrapf(err, "failed to delete user %q", p.cephUserName)
}
return nil
}
@@ -378,6 +390,11 @@ func (p *Provisioner) initializeCreateOrGrant(options *apibkt.BucketOptions) err
return errors.Wrap(err, "failed to set admin ops api client")
}
if len(options.UserID) == 0 {
return errors.Errorf("user ID for OBC %q is empty", obc.Name)
}
p.cephUserName = options.UserID
return nil
}
@@ -427,6 +444,8 @@ func (p *Provisioner) composeObjectBucket() *bktv1alpha1.ObjectBucket {
conn := &bktv1alpha1.Connection{
Endpoint: &bktv1alpha1.Endpoint{
// if there are multiple endpoints on the object store, the OBC will get the endpoint
// that it used for provisioning to make sure that the configmap gets a working config
BucketHost: p.storeDomainName,
BucketPort: int(p.storePort),
BucketName: p.bucketName,
@@ -439,7 +458,9 @@ func (p *Provisioner) composeObjectBucket() *bktv1alpha1.ObjectBucket {
},
},
AdditionalState: map[string]string{
CephUser: p.cephUserName,
CephUser: p.cephUserName,
ObjectStoreName: p.objectStoreName,
ObjectStoreNamespace: p.clusterInfo.Namespace,
},
}
@@ -482,15 +503,12 @@ func (p *Provisioner) setObjectContext() error {
// setObjectStoreDomainName sets the provisioner.storeDomainName and provisioner.port
// must be called after setObjectStoreName and setObjectStoreNamespace
func (p *Provisioner) setObjectStoreDomainName(sc *storagev1.StorageClass) error {
name := getObjectStoreName(sc)
namespace := getObjectStoreNameSpace(sc)
// make sure the object store actually exists
_, err := p.getObjectStore()
store, err := p.getObjectStore()
if err != nil {
return err
}
p.storeDomainName = object.BuildDomainName(name, namespace)
p.storeDomainName = object.GetDomainName(store)
return nil
}
@@ -504,7 +522,7 @@ func (p *Provisioner) setObjectStorePort() error {
}
func (p *Provisioner) setObjectStoreName(sc *storagev1.StorageClass) {
p.objectStoreName = sc.Parameters[objectStoreName]
p.objectStoreName = sc.Parameters[ObjectStoreName]
}
func (p *Provisioner) setBucketName(name string) {
@@ -551,53 +569,69 @@ func (p *Provisioner) populateDomainAndPort(sc *storagev1.StorageClass) error {
return nil
}
func (p *Provisioner) deleteOBCResourceLogError(bucketname string) {
if err := p.deleteOBCResource(bucketname); err != nil {
logger.Warningf("failed to delete OBC resource. %v", err)
}
}
// Check for additional options mentioned in OBC and set them accordingly
func (p Provisioner) setAdditionalSettings(options *apibkt.BucketOptions) error {
quotaEnabled := true
func (p *Provisioner) setAdditionalSettings(options *apibkt.BucketOptions) error {
var maxObjectsInt64 int64 = -1
var maxSizeInt64 int64 = -1
var err error
var quotaEnabled bool
maxObjects := MaxObjectQuota(options.ObjectBucketClaim.Spec.AdditionalConfig)
maxSize := MaxSizeQuota(options.ObjectBucketClaim.Spec.AdditionalConfig)
if maxObjects == "" && maxSize == "" {
return nil
}
// Enabling quota for the user
err := p.adminOpsClient.SetUserQuota(p.clusterInfo.Context, admin.QuotaSpec{UID: p.cephUserName, Enabled: &quotaEnabled})
if err != nil {
return errors.Wrapf(err, "failed to enable user %q quota for obc", p.cephUserName)
}
if maxObjects != "" {
maxObjectsInt, err := strconv.Atoi(maxObjects)
quotaEnabled = true
maxObjectsInt64, err = toInt64(maxObjects)
if err != nil {
return errors.Wrap(err, "failed to convert maxObjects to integer")
}
maxObjectsInt64 := int64(maxObjectsInt)
err = p.adminOpsClient.SetUserQuota(p.clusterInfo.Context, admin.QuotaSpec{UID: p.cephUserName, MaxObjects: &maxObjectsInt64})
if err != nil {
return errors.Wrapf(err, "failed to set MaxObject to user %q", p.cephUserName)
return errors.Wrapf(err, "failed to parse maxObjects quota for user %q", p.cephUserName)
}
}
maxSize := MaxSizeQuota(options.ObjectBucketClaim.Spec.AdditionalConfig)
if maxSize != "" {
maxSizeInt, err := maxSizeToInt64(maxSize)
quotaEnabled = true
maxSizeInt64, err = toInt64(maxSize)
if err != nil {
return errors.Wrapf(err, "failed to parse maxSize quota for user %q", p.cephUserName)
}
err = p.adminOpsClient.SetUserQuota(p.clusterInfo.Context, admin.QuotaSpec{UID: p.cephUserName, MaxSize: &maxSizeInt})
}
objectUser, err := p.adminOpsClient.GetUser(p.clusterInfo.Context, admin.User{ID: p.cephUserName})
if err != nil {
return errors.Wrapf(err, "failed to fetch user %q", p.cephUserName)
}
// enable or disable quota for user
if *objectUser.UserQuota.Enabled != quotaEnabled {
err = p.adminOpsClient.SetUserQuota(p.clusterInfo.Context, admin.QuotaSpec{UID: p.cephUserName, Enabled: &quotaEnabled})
if err != nil {
return errors.Wrapf(err, "failed to set MaxSize to user %q", p.cephUserName)
return errors.Wrapf(err, "failed to set user %q quota enabled=%v for obc", p.cephUserName, quotaEnabled)
}
}
if !quotaEnabled {
// no need to process anything else if quotas are disabled
return nil
}
if *objectUser.UserQuota.MaxObjects != maxObjectsInt64 {
err = p.adminOpsClient.SetUserQuota(p.clusterInfo.Context, admin.QuotaSpec{UID: p.cephUserName, MaxObjects: &maxObjectsInt64})
if err != nil {
return errors.Wrapf(err, "failed to set MaxObjects=%v to user %q", maxObjectsInt64, p.cephUserName)
}
}
if *&objectUser.UserQuota.MaxSize != &maxSizeInt64 {
err = p.adminOpsClient.SetUserQuota(p.clusterInfo.Context, admin.QuotaSpec{UID: p.cephUserName, MaxSize: &maxSizeInt64})
if err != nil {
return errors.Wrapf(err, "failed to set MaxSize=%v to user %q", maxSizeInt64, p.cephUserName)
}
}
return nil
}
func maxSizeToInt64(maxSize string) (int64, error) {
func toInt64(maxSize string) (int64, error) {
maxSizeInt, err := resource.ParseQuantity(maxSize)
if err != nil {
return 0, errors.Wrap(err, "failed to parse quantity")
@@ -654,7 +688,7 @@ func (p *Provisioner) setAdminOpsAPIClient() error {
}
// Build endpoint
s3endpoint := object.BuildDNSEndpoint(object.BuildDomainName(p.objectContext.Name, cephObjectStore.Namespace), p.storePort, cephObjectStore.Spec.IsTLSEnabled())
s3endpoint := object.BuildDNSEndpoint(object.GetDomainName(cephObjectStore), p.storePort, cephObjectStore.Spec.IsTLSEnabled())
// If DEBUG level is set we will mutate the HTTP client for printing request and response
if logger.LevelAt(capnslog.DEBUG) {
@@ -671,69 +705,3 @@ func (p *Provisioner) setAdminOpsAPIClient() error {
return nil
}
func (p Provisioner) updateAdditionalSettings(ob *bktv1alpha1.ObjectBucket) error {
var maxObjectsInt64 int64
var maxSizeInt64 int64
var err error
var quotaEnabled bool
maxObjects := MaxObjectQuota(ob.Spec.Endpoint.AdditionalConfigData)
maxSize := MaxSizeQuota(ob.Spec.Endpoint.AdditionalConfigData)
if maxObjects != "" {
maxObjectsInt, err := strconv.Atoi(maxObjects)
if err != nil {
return errors.Wrap(err, "failed to convert maxObjects to integer")
}
maxObjectsInt64 = int64(maxObjectsInt)
}
if maxSize != "" {
maxSizeInt64, err = maxSizeToInt64(maxSize)
if err != nil {
return errors.Wrapf(err, "failed to parse maxSize quota for user %q", p.cephUserName)
}
}
objectUser, err := p.adminOpsClient.GetUser(p.clusterInfo.Context, admin.User{ID: ob.Spec.Connection.AdditionalState[CephUser]})
if err != nil {
return errors.Wrapf(err, "failed to fetch user %q", p.cephUserName)
}
if *objectUser.UserQuota.Enabled &&
(maxObjects == "" || maxObjectsInt64 < 0) &&
(maxSize == "" || maxSizeInt64 < 0) {
quotaEnabled = false
err = p.adminOpsClient.SetUserQuota(p.clusterInfo.Context, admin.QuotaSpec{UID: p.cephUserName, Enabled: &quotaEnabled})
if err != nil {
return errors.Wrapf(err, "failed to disable quota to user %q", p.cephUserName)
}
return nil
}
quotaEnabled = true
quotaSpec := admin.QuotaSpec{UID: p.cephUserName, Enabled: &quotaEnabled}
//MaxObject is modified
if maxObjects != "" && (maxObjectsInt64 != *objectUser.UserQuota.MaxObjects) {
quotaSpec.MaxObjects = &maxObjectsInt64
}
//MaxSize is modified
if maxSize != "" && (maxSizeInt64 != *objectUser.UserQuota.MaxSize) {
quotaSpec.MaxSize = &maxSizeInt64
}
err = p.adminOpsClient.SetUserQuota(p.clusterInfo.Context, quotaSpec)
if err != nil {
return errors.Wrapf(err, "failed to update quota to user %q", p.cephUserName)
}
return nil
}
// Update is sent when only there is modification to AdditionalConfig field in OBC
func (p Provisioner) Update(ob *bktv1alpha1.ObjectBucket) error {
logger.Debugf("Update event for OB: %+v", ob)
err := p.initializeDeleteOrRevoke(ob)
if err != nil {
return err
}
return p.updateAdditionalSettings(ob)
}
@@ -17,10 +17,17 @@ limitations under the License.
package bucket
import (
"bytes"
"context"
"fmt"
"io/ioutil"
"net/http"
"strings"
"testing"
"github.com/ceph/go-ceph/rgw/admin"
"github.com/kube-object-storage/lib-bucket-provisioner/pkg/apis/objectbucket.io/v1alpha1"
apibkt "github.com/kube-object-storage/lib-bucket-provisioner/pkg/provisioner/api"
cephv1 "github.com/rook/rook/pkg/apis/ceph.rook.io/v1"
rookclient "github.com/rook/rook/pkg/client/clientset/versioned/fake"
"github.com/rook/rook/pkg/clusterd"
@@ -121,7 +128,7 @@ func TestMaxSizeToInt64(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := maxSizeToInt64(tt.args.maxSize)
got, err := toInt64(tt.args.maxSize)
if (err != nil) != tt.wantErr {
t.Errorf("maxSizeToInt64() error = %v, wantErr %v", err, tt.wantErr)
return
@@ -132,3 +139,228 @@ func TestMaxSizeToInt64(t *testing.T) {
})
}
}
func TestProvisioner_setAdditionalSettings(t *testing.T) {
newProvisioner := func(t *testing.T, getUserResult string, putValsSeen *[]string) *Provisioner {
mockClient := &object.MockClient{
MockDo: func(req *http.Request) (*http.Response, error) {
// t.Logf("HTTP req: %#v", req)
t.Logf("HTTP %s: %s %s", req.Method, req.URL.Path, req.URL.RawQuery)
assert.Contains(t, req.URL.RawQuery, "&uid=bob")
if req.Method == http.MethodGet {
if req.URL.Path == "my.endpoint.net/admin/user" {
statusCode := 200
if getUserResult == "" {
statusCode = 500
}
return &http.Response{
StatusCode: statusCode,
Body: ioutil.NopCloser(bytes.NewReader([]byte(getUserResult))),
}, nil
}
}
if req.Method == http.MethodPut {
if req.URL.Path == "my.endpoint.net/admin/user" {
*putValsSeen = append(*putValsSeen, req.URL.RawQuery)
return &http.Response{
StatusCode: 200,
Body: ioutil.NopCloser(bytes.NewReader([]byte(`[]`))),
}, nil
}
}
panic(fmt.Sprintf("unexpected request: %q. method %q. path %q", req.URL.RawQuery, req.Method, req.URL.Path))
},
}
adminClient, err := admin.New("my.endpoint.net", "accesskey", "secretkey", mockClient)
assert.NoError(t, err)
p := &Provisioner{
clusterInfo: &client.ClusterInfo{
Context: context.Background(),
},
cephUserName: "bob",
adminOpsClient: adminClient,
}
return p
}
t.Run("quota should remain disabled", func(t *testing.T) {
putValsSeen := []string{}
p := newProvisioner(t,
`{"user_quota":{"enabled":false,"max_size":-1,"max_objects":-1}}`,
&putValsSeen,
)
err := p.setAdditionalSettings(&apibkt.BucketOptions{
ObjectBucketClaim: &v1alpha1.ObjectBucketClaim{
Spec: v1alpha1.ObjectBucketClaimSpec{
AdditionalConfig: map[string]string{},
},
},
})
assert.NoError(t, err)
assert.Len(t, putValsSeen, 0)
})
t.Run("quota should be disabled", func(t *testing.T) {
putValsSeen := []string{}
p := newProvisioner(t,
`{"user_quota":{"enabled":true,"max_size":-1,"max_objects":2}}`,
&putValsSeen,
)
err := p.setAdditionalSettings(&apibkt.BucketOptions{
ObjectBucketClaim: &v1alpha1.ObjectBucketClaim{
Spec: v1alpha1.ObjectBucketClaimSpec{
AdditionalConfig: map[string]string{},
},
},
})
assert.NoError(t, err)
// quota should be disabled, and that's it
assert.Len(t, putValsSeen, 1)
assert.Equal(t, 1, numberOfPutsWithValue(`enabled=false`, putValsSeen))
})
t.Run("maxSize quota should be enabled", func(t *testing.T) {
putValsSeen := []string{}
p := newProvisioner(t,
`{"user_quota":{"enabled":false,"max_size":-1,"max_objects":-1}}`,
&putValsSeen,
)
err := p.setAdditionalSettings(&apibkt.BucketOptions{
ObjectBucketClaim: &v1alpha1.ObjectBucketClaim{
Spec: v1alpha1.ObjectBucketClaimSpec{
AdditionalConfig: map[string]string{
"maxSize": "2",
},
},
},
})
assert.NoError(t, err)
assert.Zero(t, numberOfPutsWithValue(`enabled=false`, putValsSeen)) // no puts should disable
assert.NotEmpty(t, putWithValue(`enabled=true`, putValsSeen)) // at least one put enables
// there is only one time that max-size is set, and it's to the right value
assert.Equal(t, 1, numberOfPutsWithValue(`max-size`, putValsSeen))
assert.NotEmpty(t, putWithValue(`max-size=2`, putValsSeen))
})
t.Run("maxObjects quota should be enabled", func(t *testing.T) {
putValsSeen := []string{}
p := newProvisioner(t,
`{"user_quota":{"enabled":false,"max_size":-1,"max_objects":-1}}`,
&putValsSeen,
)
err := p.setAdditionalSettings(&apibkt.BucketOptions{
ObjectBucketClaim: &v1alpha1.ObjectBucketClaim{
Spec: v1alpha1.ObjectBucketClaimSpec{
AdditionalConfig: map[string]string{
"maxObjects": "2",
},
},
},
})
assert.NoError(t, err)
assert.Zero(t, numberOfPutsWithValue(`enabled=false`, putValsSeen)) // no puts should disable
assert.NotEmpty(t, putWithValue(`enabled=true`, putValsSeen)) // at least one put enables
// there is only one time max-objects is set, and it's to the right value
assert.NotEmpty(t, putWithValue(`max-objects=2`, putValsSeen))
assert.Equal(t, 1, numberOfPutsWithValue(`max-objects`, putValsSeen))
})
t.Run("maxObjects and maxSize quotas should be enabled", func(t *testing.T) {
putValsSeen := []string{}
p := newProvisioner(t,
`{"user_quota":{"enabled":false,"max_size":-1,"max_objects":-1}}`,
&putValsSeen,
)
err := p.setAdditionalSettings(&apibkt.BucketOptions{
ObjectBucketClaim: &v1alpha1.ObjectBucketClaim{
Spec: v1alpha1.ObjectBucketClaimSpec{
AdditionalConfig: map[string]string{
"maxSize": "2",
"maxObjects": "3",
},
},
},
})
assert.NoError(t, err)
assert.Zero(t, numberOfPutsWithValue(`enabled=false`, putValsSeen)) // no puts should disable
assert.NotEmpty(t, putWithValue(`enabled=true`, putValsSeen)) // at least one put enables
// there is only one time that max-size is set, and it's to the right value
assert.Equal(t, 1, numberOfPutsWithValue(`max-size`, putValsSeen))
assert.NotEmpty(t, putWithValue(`max-size=2`, putValsSeen))
// there is only one time max-objects is set, and it's to the right value
assert.NotEmpty(t, putWithValue(`max-objects=3`, putValsSeen))
assert.Equal(t, 1, numberOfPutsWithValue(`max-objects`, putValsSeen))
})
t.Run("quotas are enabled and need updated enabled", func(t *testing.T) {
putValsSeen := []string{}
p := newProvisioner(t,
`{"user_quota":{"enabled":true,"max_size":1,"max_objects":1}}`,
&putValsSeen,
)
err := p.setAdditionalSettings(&apibkt.BucketOptions{
ObjectBucketClaim: &v1alpha1.ObjectBucketClaim{
Spec: v1alpha1.ObjectBucketClaimSpec{
AdditionalConfig: map[string]string{
"maxSize": "2",
"maxObjects": "3",
},
},
},
})
assert.NoError(t, err)
assert.Zero(t, numberOfPutsWithValue(`enabled=false`, putValsSeen)) // no puts should disable
// there is only one time that max-size is set, and it's to the right value
assert.Equal(t, 1, numberOfPutsWithValue(`max-size`, putValsSeen))
assert.NotEmpty(t, putWithValue(`max-size=2`, putValsSeen))
// there is only one time max-objects is set, and it's to the right value
assert.NotEmpty(t, putWithValue(`max-objects=3`, putValsSeen))
assert.Equal(t, 1, numberOfPutsWithValue(`max-objects`, putValsSeen))
})
}
func numberOfPutsWithValue(substr string, strs []string) int {
count := 0
for _, s := range strs {
if strings.Contains(s, substr) {
count++
}
}
return count
}
func putWithValue(substr string, strs []string) string {
for _, s := range strs {
if strings.Contains(s, substr) {
return s
}
}
return ""
}
@@ -1,8 +1,6 @@
package bucket
import (
"fmt"
"github.com/ceph/go-ceph/rgw/admin"
"github.com/pkg/errors"
)
@@ -18,27 +16,11 @@ func (p *Provisioner) bucketExists(name string) (bool, error) {
return true, nil
}
func (p *Provisioner) userExists(name string) (bool, error) {
_, err := p.adminOpsClient.GetUser(p.clusterInfo.Context, admin.User{ID: name})
if err != nil {
if errors.Is(err, admin.ErrNoSuchUser) {
return false, nil
} else {
return false, errors.Wrapf(err, "failed to get ceph user %q", name)
}
}
return true, nil
}
// Create a Ceph user based on the passed-in name or a generated name. Return the
// accessKeys and set user name and keys in receiver.
func (p *Provisioner) createCephUser(username string) (accKey string, secKey string, err error) {
if len(username) == 0 {
username, err = p.genUserName()
if len(username) == 0 || err != nil {
return "", "", errors.Wrap(err, "no user name provided and unable to generate a unique name")
}
return "", "", errors.Wrap(err, "no user name provided")
}
p.cephUserName = username
@@ -65,24 +47,10 @@ func (p *Provisioner) createCephUser(username string) (accKey string, secKey str
return u.Keys[0].AccessKey, u.Keys[0].SecretKey, nil
}
// returns "" if unable to generate a unique name.
func (p *Provisioner) genUserName() (genName string, err error) {
const (
maxTries = 10
prefix = "ceph-user"
)
notUnique := true
// generate names and check that the user does not already exist. otherwise,
// radosgw-admin will just return the existing user.
// when notUnique == true, the loop breaks and `name` contains the latest generated name
for i := 0; notUnique && i < maxTries; i++ {
genName = fmt.Sprintf("%s-%s", prefix, randomString(genUserLen))
if notUnique, err = p.userExists(genName); err != nil {
return "", err
}
}
return genName, nil
func (p *Provisioner) genUserName(obcName, obcNamespace string) string {
// user name can be deterministically generated by obc name and namespace
// since there can't be 2 obcs in the same namespace with the same name, this will not collide
return "obc-" + obcNamespace + "-" + obcName
}
// Delete the user and bucket created by OBC with help of radosgw-admin commands
@@ -97,17 +65,17 @@ func (p *Provisioner) deleteOBCResource(bucketName string) error {
thePurge := true
err := p.adminOpsClient.RemoveBucket(p.clusterInfo.Context, admin.Bucket{Bucket: bucketName, PurgeObject: &thePurge})
if err == nil {
logger.Infof("bucket %q successfully deleted", p.bucketName)
logger.Infof("bucket %q successfully deleted", bucketName)
} else if errors.Is(err, admin.ErrNoSuchBucket) {
// opinion: "not found" is not an error
logger.Infof("bucket %q does not exist", p.bucketName)
logger.Infof("bucket %q does not exist", bucketName)
} else if errors.Is(err, admin.ErrNoSuchKey) {
// ceph might return NoSuchKey than NoSuchBucket when the target bucket does not exist.
// then we can use GetBucketInfo() to judge the existence of the bucket.
// see: https://github.com/ceph/ceph/pull/44413
_, err2 := p.adminOpsClient.GetBucketInfo(p.clusterInfo.Context, admin.Bucket{Bucket: bucketName, PurgeObject: &thePurge})
if errors.Is(err2, admin.ErrNoSuchBucket) {
logger.Infof("bucket info %q does not exist", p.bucketName)
logger.Infof("bucket info %q does not exist", bucketName)
} else {
return errors.Wrapf(err, "failed to delete bucket %q (could not get bucket info)", bucketName)
}
+40 -22
View File
@@ -17,9 +17,10 @@ limitations under the License.
package bucket
import (
"crypto/rand"
"fmt"
"github.com/coreos/pkg/capnslog"
"github.com/kube-object-storage/lib-bucket-provisioner/pkg/apis/objectbucket.io/v1alpha1"
bktv1alpha1 "github.com/kube-object-storage/lib-bucket-provisioner/pkg/apis/objectbucket.io/v1alpha1"
"github.com/kube-object-storage/lib-bucket-provisioner/pkg/provisioner"
"github.com/pkg/errors"
@@ -28,16 +29,16 @@ import (
storagev1 "k8s.io/api/storage/v1"
kerrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/rest"
)
var logger = capnslog.NewPackageLogger("github.com/rook/rook", "op-bucket-prov")
const (
genUserLen = 8
CephUser = "cephUser"
objectStoreName = "objectStoreName"
objectStoreNamespace = "objectStoreNamespace"
ObjectStoreName = "objectStoreName"
ObjectStoreNamespace = "objectStoreNamespace"
objectStoreEndpoint = "endpoint"
)
@@ -50,11 +51,7 @@ func NewBucketController(cfg *rest.Config, p *Provisioner, data map[string]strin
}
func getObjectStoreName(sc *storagev1.StorageClass) string {
return sc.Parameters[objectStoreName]
}
func getObjectStoreNameSpace(sc *storagev1.StorageClass) string {
return sc.Parameters[objectStoreNamespace]
return sc.Parameters[ObjectStoreName]
}
func getObjectStoreEndpoint(sc *storagev1.StorageClass) string {
@@ -101,19 +98,6 @@ func (p *Provisioner) getCephCluster() (*cephv1.CephCluster, error) {
return &cephCluster.Items[0], err
}
func randomString(n int) string {
var letterRunes = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
b := make([]byte, n)
if _, err := rand.Read(b); err != nil {
return ""
}
for k, v := range b {
b[k] = letterRunes[v%byte(len(letterRunes))]
}
return string(b)
}
func MaxObjectQuota(AdditionalConfig map[string]string) string {
return AdditionalConfig["maxObjects"]
}
@@ -121,3 +105,37 @@ func MaxObjectQuota(AdditionalConfig map[string]string) string {
func MaxSizeQuota(AdditionalConfig map[string]string) string {
return AdditionalConfig["maxSize"]
}
func GetObjectStoreNameFromBucket(ob *v1alpha1.ObjectBucket) (types.NamespacedName, error) {
// Rook v1.11 OBCs have additional state labels that tell the object store namespace and name.
// This is critical for CephObjectStores in external mode that connect to RGW endpoints directly
// which don't have a deterministic domain structure.
nsName, err := getNSNameFromAdditionalState(ob.Spec.AdditionalState)
if err == nil {
return nsName, nil
}
// TODO: remove after Rook v1.12
// Older OBCs don't have the additional state labels, but they will always be configured to use
// the legacy CephObjectStore Service which has a deterministic domain structure.
logger.Debugf("falling back to legacy method for determining OBC \"%s/%s\"'s CephObjectStore from endpoint %q",
ob.Namespace, ob.Name, ob.Spec.Connection.Endpoint.BucketHost)
nsName, err = cephObject.ParseDomainName(ob.Spec.Connection.Endpoint.BucketHost)
if err != nil {
return types.NamespacedName{}, errors.Wrapf(err, "malformed BucketHost %q", ob.Spec.Endpoint.BucketHost)
}
return nsName, nil
}
func getNSNameFromAdditionalState(state map[string]string) (types.NamespacedName, error) {
name, ok := state[ObjectStoreName]
if !ok {
return types.NamespacedName{}, fmt.Errorf("failed to get %q from OB additional state: %v", ObjectStoreName, state)
}
namespace, ok := state[ObjectStoreNamespace]
if !ok {
return types.NamespacedName{}, fmt.Errorf("failed to get %q from OB additional state: %v", ObjectStoreNamespace, state)
}
return types.NamespacedName{Name: name, Namespace: namespace}, nil
}
+42 -14
View File
@@ -192,6 +192,8 @@ func (r *ReconcileCephObjectStore) reconcile(request reconcile.Request) (reconci
if cephObjectStore.Status == nil {
// The store is not available so let's not build the status Info yet
updateStatus(r.opManagerContext, k8sutil.ObservedGenerationNotAvailable, r.client, request.NamespacedName, cephv1.ConditionProgressing, map[string]string{})
} else {
updateStatus(r.opManagerContext, k8sutil.ObservedGenerationNotAvailable, r.client, request.NamespacedName, cephv1.ConditionProgressing, buildStatusInfo(cephObjectStore))
}
// Make sure a CephCluster is present otherwise do nothing
@@ -379,22 +381,48 @@ func (r *ReconcileCephObjectStore) reconcileCreateObjectStore(cephObjectStore *c
if cephObjectStore.Spec.IsExternal() {
logger.Info("reconciling external object store")
// RECONCILE SERVICE
logger.Info("reconciling object store service")
err = cfg.reconcileService(cephObjectStore)
// Before v1.11, Rook created a Service and custom Endpoints that routed to external RGW
// endpoints. This causes problems if the external endpoint has TLS certificates that block
// connections to other endpoints. This also makes it impossible to create an external mode
// CephObjectStore that references another CephObjectStore's Service endpoint in the same
// Kubernetes cluster.
//
// TODO: this code block can be removed once OBCs are no longer supported. The legacy
// service can also be removed at that point.
service := cfg.generateService(cephObjectStore)
clientset := cfg.context.Clientset
clusterCtx := cfg.clusterInfo.Context
_, err = clientset.CoreV1().Services(service.Namespace).Get(clusterCtx, service.Name, metav1.GetOptions{})
if err != nil {
return r.setFailedStatus(k8sutil.ObservedGenerationNotAvailable, namespacedName, "failed to reconcile service", err)
if kerrors.IsNotFound(err) {
// We do not need to create Services/Endpoints for new CephObjectStores.
} else {
return r.setFailedStatus(k8sutil.ObservedGenerationNotAvailable, namespacedName,
"failed to determine if legacy external service exists", err)
}
} else {
// For any legacy users that have an external mode CephObjectStore successfully using
// the Service/Endpoints and who have already created OBCs,we leave the legacy
// Service/Endpoints in place. We need to update legacy services if the user edits the
// externalRgwEndpoint -- perhaps their RGW node changed IPs.
// RECONCILE SERVICE
logger.Info("reconciling legacy external object store service")
err = cfg.reconcileService(cephObjectStore)
if err != nil {
return r.setFailedStatus(k8sutil.ObservedGenerationNotAvailable, namespacedName, "failed to reconcile service", err)
}
// RECONCILE ENDPOINTS
// Always add the endpoint AFTER the service otherwise it will get overridden
logger.Info("reconciling legacy external object store endpoint")
err = cfg.reconcileExternalEndpoint(cephObjectStore)
if err != nil {
return r.setFailedStatus(k8sutil.ObservedGenerationNotAvailable, namespacedName, "failed to reconcile external endpoint", err)
}
}
// RECONCILE ENDPOINTS
// Always add the endpoint AFTER the service otherwise it will get overridden
logger.Info("reconciling external object store endpoint")
err = cfg.reconcileExternalEndpoint(cephObjectStore)
if err != nil {
return r.setFailedStatus(k8sutil.ObservedGenerationNotAvailable, namespacedName, "failed to reconcile external endpoint", err)
}
if err := UpdateEndpoint(objContext, &cephObjectStore.Spec); err != nil {
if err := UpdateEndpoint(objContext, cephObjectStore); err != nil {
return r.setFailedStatus(k8sutil.ObservedGenerationNotAvailable, namespacedName, "failed to set endpoint", err)
}
} else {
@@ -426,7 +454,7 @@ func (r *ReconcileCephObjectStore) reconcileCreateObjectStore(cephObjectStore *c
return r.setFailedStatus(k8sutil.ObservedGenerationNotAvailable, namespacedName, "failed to reconcile service", err)
}
if err := UpdateEndpoint(objContext, &cephObjectStore.Spec); err != nil {
if err := UpdateEndpoint(objContext, cephObjectStore); err != nil {
return r.setFailedStatus(k8sutil.ObservedGenerationNotAvailable, namespacedName, "failed to set endpoint", err)
}
+1 -1
View File
@@ -844,7 +844,7 @@ func TestCephObjectExternalStoreController(t *testing.T) {
}
externalObjectStore.Spec.Gateway.Port = 81
externalObjectStore.Spec.Gateway.ExternalRgwEndpoints = []v1.EndpointAddress{{IP: ""}}
externalObjectStore.Spec.Gateway.ExternalRgwEndpoints = []cephv1.EndpointAddress{{IP: ""}}
rgwAdminOpsUserSecret := &v1.Secret{
ObjectMeta: metav1.ObjectMeta{
+10 -1
View File
@@ -25,6 +25,7 @@ import (
cephv1 "github.com/rook/rook/pkg/apis/ceph.rook.io/v1"
"github.com/rook/rook/pkg/clusterd"
"github.com/rook/rook/pkg/operator/k8sutil"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client"
)
@@ -141,7 +142,15 @@ func (c *bucketChecker) checkObjectStoreHealth() error {
*/
// Keep admin ops context up-to date if there are config changes
if err := UpdateEndpoint(&c.objContext.Context, c.objectStoreSpec); err != nil {
minimalStore := &cephv1.CephObjectStore{
ObjectMeta: metav1.ObjectMeta{
// UpdateEndpoint needs the name and namespace, plus the spec of the store passed to it
Name: c.namespacedName.Name,
Namespace: c.namespacedName.Namespace,
},
Spec: *c.objectStoreSpec,
}
if err := UpdateEndpoint(&c.objContext.Context, minimalStore); err != nil {
return errors.Wrapf(err, "failed to parse updated CephObjectStore spec")
}
@@ -28,7 +28,6 @@ import (
"github.com/rook/rook/pkg/clusterd"
cephclient "github.com/rook/rook/pkg/daemon/ceph/client"
opcontroller "github.com/rook/rook/pkg/operator/ceph/controller"
"github.com/rook/rook/pkg/operator/ceph/object"
"github.com/rook/rook/pkg/operator/ceph/object/bucket"
"github.com/rook/rook/pkg/operator/ceph/object/topic"
"github.com/rook/rook/pkg/operator/ceph/reporting"
@@ -209,17 +208,7 @@ func (r *ReconcileNotifications) reconcile(request reconcile.Request) (reconcile
}
func getCephObjectStoreName(ob bktv1alpha1.ObjectBucket) (types.NamespacedName, error) {
// parse the following string: <prefix>-rgw-<store>.<namespace>.svc
// to ge the object store name and namespace
logger.Debugf("BucketHost of %q is %q",
types.NamespacedName{Name: ob.Name, Namespace: ob.Namespace}.String(),
ob.Spec.Connection.Endpoint.BucketHost,
)
objectStoreName, err := object.ParseDomainName(ob.Spec.Connection.Endpoint.BucketHost)
if err != nil {
return types.NamespacedName{}, errors.Wrapf(err, "malformed BucketHost %q", ob.Spec.Endpoint.BucketHost)
}
return objectStoreName, nil
return bucket.GetObjectStoreNameFromBucket(&ob)
}
// verify that object store is configured correctly for OB, CephBucketNotification and CephBucketTopic
@@ -31,7 +31,6 @@ import (
"github.com/rook/rook/pkg/operator/test"
"github.com/rook/rook/pkg/clusterd"
"github.com/rook/rook/pkg/operator/ceph/object"
"github.com/rook/rook/pkg/operator/k8sutil"
exectest "github.com/rook/rook/pkg/util/exec/test"
"github.com/stretchr/testify/assert"
@@ -151,7 +150,7 @@ func mockSetup(t *testing.T) {
}
return nil, nil
}
deleteNotification = func(p provisioner, bucket *bktv1alpha1.ObjectBucket, notificationId string) error {
deleteNotificationFunc = func(p provisioner, bucket *bktv1alpha1.ObjectBucket, notificationId string) error {
deletedNotifications = append(deletedNotifications, notificationId)
return nil
}
@@ -427,7 +426,7 @@ func TestCephBucketNotificationControllerWithOBC(t *testing.T) {
StorageClassName: testSCName,
Connection: &bktv1alpha1.Connection{
Endpoint: &bktv1alpha1.Endpoint{
BucketHost: object.BuildDomainName(testStoreName, testNamespace),
BucketHost: "rook-ceph-rgw-test-store.rook-ceph.svc",
},
},
},
@@ -23,7 +23,6 @@ import (
bktv1alpha1 "github.com/kube-object-storage/lib-bucket-provisioner/pkg/apis/objectbucket.io/v1alpha1"
cephv1 "github.com/rook/rook/pkg/apis/ceph.rook.io/v1"
"github.com/rook/rook/pkg/operator/ceph/object"
"github.com/rook/rook/pkg/operator/k8sutil"
"github.com/stretchr/testify/assert"
corev1 "k8s.io/api/core/v1"
@@ -59,7 +58,7 @@ func createOBResources(name string) (*bktv1alpha1.ObjectBucketClaim, *bktv1alpha
StorageClassName: testSCName,
Connection: &bktv1alpha1.Connection{
Endpoint: &bktv1alpha1.Endpoint{
BucketHost: object.BuildDomainName(testStoreName, testNamespace),
BucketHost: "rook-ceph-rgw-test-store.rook-ceph.svc",
},
},
ClaimRef: &corev1.ObjectReference{
+48 -3
View File
@@ -20,6 +20,7 @@ package object
import (
"fmt"
"io/ioutil"
"math/rand"
"net/http"
"reflect"
"strconv"
@@ -313,9 +314,53 @@ func EmptyPool(pool cephv1.PoolSpec) bool {
return reflect.DeepEqual(pool, cephv1.PoolSpec{})
}
// BuildDomainName build the dns name to reach out the service endpoint
func BuildDomainName(name, namespace string) string {
return fmt.Sprintf("%s-%s.%s.%s", AppName, name, namespace, svcDNSSuffix)
// GetDomainName build the dns name to reach out the service endpoint
func GetDomainName(s *cephv1.CephObjectStore) string {
return getDomainName(s, true)
}
func GetStableDomainName(s *cephv1.CephObjectStore) string {
return getDomainName(s, false)
}
func getDomainName(s *cephv1.CephObjectStore, returnRandomDomainIfMultiple bool) string {
if s.Spec.IsExternal() {
// if the store is external, pick a random endpoint to use. if the endpoint is down, this
// reconcile may fail, but a future reconcile will eventually pick a different endpoint to try
endpoints := s.Spec.Gateway.ExternalRgwEndpoints
idx := 0
if returnRandomDomainIfMultiple {
idx = rand.Intn(len(endpoints)) //nolint:gosec // G404: cryptographically weak RNG is fine here
}
return endpoints[idx].String()
}
return domainNameOfService(s)
}
func domainNameOfService(s *cephv1.CephObjectStore) string {
return fmt.Sprintf("%s-%s.%s.%s", AppName, s.Name, s.Namespace, svcDNSSuffix)
}
func getAllDomainNames(s *cephv1.CephObjectStore) []string {
if s.Spec.IsExternal() {
domains := []string{}
for _, e := range s.Spec.Gateway.ExternalRgwEndpoints {
domains = append(domains, e.String())
}
logger.Debugf("domains: +%v", domains)
return domains
}
return []string{domainNameOfService(s)}
}
func getAllDNSEndpoints(s *cephv1.CephObjectStore, port int32, secure bool) []string {
endpoints := []string{}
for _, d := range getAllDomainNames(s) {
endpoints = append(endpoints, BuildDNSEndpoint(d, port, secure))
}
return endpoints
}
// ParseDomainName parse the name and namespace from the dns name
+7 -3
View File
@@ -156,9 +156,13 @@ func TestEmptyPoolSpec(t *testing.T) {
}
func TestBuildDomainNameAndEndpoint(t *testing.T) {
name := "my-store"
ns := "rook-ceph"
dns := BuildDomainName(name, ns)
s := &cephv1.CephObjectStore{
ObjectMeta: metav1.ObjectMeta{
Name: "my-store",
Namespace: "rook-ceph",
},
}
dns := GetDomainName(s)
assert.Equal(t, "rook-ceph-rgw-my-store.rook-ceph.svc", dns)
// non-secure endpoint
+1
View File
@@ -99,6 +99,7 @@ func (s *S3Agent) createBucket(name string, infoLogging bool) error {
bucketInput := &s3.CreateBucketInput{
Bucket: &name,
}
_, err := s.Client.CreateBucket(bucketInput)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
+14 -5
View File
@@ -503,6 +503,15 @@ func (c *clusterConfig) generateService(cephObjectStore *cephv1.CephObjectStore)
func (c *clusterConfig) generateEndpoint(cephObjectStore *cephv1.CephObjectStore) *v1.Endpoints {
labels := getLabels(cephObjectStore.Name, cephObjectStore.Namespace, true)
k8sEndpointAddrs := []v1.EndpointAddress{}
for _, rookEndpoint := range cephObjectStore.Spec.Gateway.ExternalRgwEndpoints {
k8sEndpointAddr := v1.EndpointAddress{
IP: rookEndpoint.IP,
Hostname: rookEndpoint.Hostname,
}
k8sEndpointAddrs = append(k8sEndpointAddrs, k8sEndpointAddr)
}
endpoints := &v1.Endpoints{
ObjectMeta: metav1.ObjectMeta{
Name: instanceName(cephObjectStore.Name),
@@ -511,7 +520,7 @@ func (c *clusterConfig) generateEndpoint(cephObjectStore *cephv1.CephObjectStore
},
Subsets: []v1.EndpointSubset{
{
Addresses: cephObjectStore.Spec.Gateway.ExternalRgwEndpoints,
Addresses: k8sEndpointAddrs,
},
},
}
@@ -540,17 +549,17 @@ func (c *clusterConfig) reconcileExternalEndpoint(cephObjectStore *cephv1.CephOb
return nil
}
func (c *clusterConfig) reconcileService(cephObjectStore *cephv1.CephObjectStore) error {
service := c.generateService(cephObjectStore)
func (c *clusterConfig) reconcileService(store *cephv1.CephObjectStore) error {
service := c.generateService(store)
// Set owner ref to the parent object
err := c.ownerInfo.SetControllerReference(service)
if err != nil {
return errors.Wrapf(err, "failed to set owner reference to ceph object store service %q", service.Name)
}
svc, err := k8sutil.CreateOrUpdateService(c.clusterInfo.Context, c.context.Clientset, cephObjectStore.Namespace, service)
svc, err := k8sutil.CreateOrUpdateService(c.clusterInfo.Context, c.context.Clientset, store.Namespace, service)
if err != nil {
return errors.Wrapf(err, "failed to create or update object store %q service", cephObjectStore.Name)
return errors.Wrapf(err, "failed to create or update object store %q service", store.Name)
}
logger.Infof("ceph object store gateway service running at %s", svc.Spec.ClusterIP)
+1 -1
View File
@@ -316,7 +316,7 @@ func TestValidateSpec(t *testing.T) {
assert.Nil(t, err)
// external with endpoints, success
s.Spec.Gateway.ExternalRgwEndpoints = []v1.EndpointAddress{
s.Spec.Gateway.ExternalRgwEndpoints = []cephv1.EndpointAddress{
{
IP: "192.168.0.1",
},
+19 -5
View File
@@ -49,7 +49,12 @@ func updateStatus(ctx context.Context, observedGeneration int64, client client.C
return errors.Wrapf(err, "failed to retrieve object store %q to update status to %q", namespacedName.String(), status)
}
if objectStore.Status == nil {
objectStore.Status = &cephv1.ObjectStoreStatus{}
objectStore.Status = &cephv1.ObjectStoreStatus{
Endpoints: cephv1.ObjectEndpoints{
Insecure: []string{},
Secure: []string{},
},
}
}
if objectStore.Status.Phase == cephv1.ConditionDeleting {
@@ -63,6 +68,15 @@ func updateStatus(ctx context.Context, observedGeneration int64, client client.C
objectStore.Status.ObservedGeneration = observedGeneration
}
insecurePort := objectStore.Spec.Gateway.Port
if insecurePort > 0 {
objectStore.Status.Endpoints.Insecure = getAllDNSEndpoints(objectStore, insecurePort, false)
}
securePort := objectStore.Spec.Gateway.SecurePort
if securePort > 0 {
objectStore.Status.Endpoints.Secure = getAllDNSEndpoints(objectStore, securePort, true)
}
if err := reporting.UpdateStatus(client, objectStore); err != nil {
return errors.Wrapf(err, "failed to set object store %q status to %q", namespacedName.String(), status)
}
@@ -115,12 +129,12 @@ func buildStatusInfo(cephObjectStore *cephv1.CephObjectStore) map[string]string
m := make(map[string]string)
if cephObjectStore.Spec.Gateway.SecurePort != 0 && cephObjectStore.Spec.Gateway.Port != 0 {
m["secureEndpoint"] = BuildDNSEndpoint(BuildDomainName(cephObjectStore.Name, cephObjectStore.Namespace), cephObjectStore.Spec.Gateway.SecurePort, true)
m["endpoint"] = BuildDNSEndpoint(BuildDomainName(cephObjectStore.Name, cephObjectStore.Namespace), cephObjectStore.Spec.Gateway.Port, false)
m["secureEndpoint"] = BuildDNSEndpoint(GetStableDomainName(cephObjectStore), cephObjectStore.Spec.Gateway.SecurePort, true)
m["endpoint"] = BuildDNSEndpoint(GetStableDomainName(cephObjectStore), cephObjectStore.Spec.Gateway.Port, false)
} else if cephObjectStore.Spec.Gateway.SecurePort != 0 {
m["endpoint"] = BuildDNSEndpoint(BuildDomainName(cephObjectStore.Name, cephObjectStore.Namespace), cephObjectStore.Spec.Gateway.SecurePort, true)
m["endpoint"] = BuildDNSEndpoint(GetStableDomainName(cephObjectStore), cephObjectStore.Spec.Gateway.SecurePort, true)
} else {
m["endpoint"] = BuildDNSEndpoint(BuildDomainName(cephObjectStore.Name, cephObjectStore.Namespace), cephObjectStore.Spec.Gateway.Port, false)
m["endpoint"] = BuildDNSEndpoint(GetStableDomainName(cephObjectStore), cephObjectStore.Spec.Gateway.Port, false)
}
return m
+1 -13
View File
@@ -138,18 +138,6 @@ func runObjectE2ETest(helper *clients.TestClient, k8sh *utils.K8sHelper, install
deleteStore := true
runObjectE2ETestLite(t, helper, k8sh, installer, namespace, otherStoreName, 1, deleteStore, tlsEnable)
})
if tlsEnable {
// test that a third object store can be created (and deleted) while the first exists
s.T().Run("run a third object store with broken tls", func(t *testing.T) {
otherStoreName := "broken-" + storeName
// The lite e2e test is perfect, as it only creates a cluster, checks that it is healthy,
// and then deletes it.
deleteStore := true
objectStoreServicePrefix = objectStoreServicePrefixUniq
runObjectE2ETestLite(t, helper, k8sh, installer, namespace, otherStoreName, 1, deleteStore, tlsEnable)
objectStoreServicePrefix = objectStoreServicePrefixUniq
})
}
// now test operation of the first object store
testObjectStoreOperations(s, helper, k8sh, namespace, storeName)
@@ -249,7 +237,7 @@ func testObjectStoreOperations(s *suite.Suite, helper *clients.TestClient, k8sh
t.Run("update quota limits", func(t *testing.T) {
poErr := helper.BucketClient.UpdateObc(obcName, bucketStorageClassName, bucketname, newMaxObject, true)
assert.Nil(t, poErr)
updated := utils.Retry(5, 2*time.Second, "OBC is updated", func() bool {
updated := utils.Retry(20, 2*time.Second, "OBC is updated", func() bool {
return helper.BucketClient.CheckOBMaxObject(obcName, newMaxObject)
})
assert.True(t, updated)