diff --git a/build/makelib/common.mk b/build/makelib/common.mk index 822cd9b95..0b0e2df11 100644 --- a/build/makelib/common.mk +++ b/build/makelib/common.mk @@ -95,7 +95,7 @@ BUILD_REGISTRY := build-$(shell echo $(HOSTNAME)-$(ROOT_DIR) | shasum -a 256 | c endif # Select which images (backends) to make; default to all possible images -IMAGES ?= ceph cockroachdb minio nfs +IMAGES ?= ceph cockroachdb minio nfs cassandra COMMA := , SPACE := diff --git a/cluster/examples/kubernetes/cassandra/cluster.yaml b/cluster/examples/kubernetes/cassandra/cluster.yaml new file mode 100644 index 000000000..629642344 --- /dev/null +++ b/cluster/examples/kubernetes/cassandra/cluster.yaml @@ -0,0 +1,95 @@ +# Namespace where the Cassandra Cluster will be created +apiVersion: v1 +kind: Namespace +metadata: + name: rook-cassandra + +--- + +# Role for cassandra members. +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: rook-cassandra-member + namespace: rook-cassandra +rules: + - apiGroups: + - "" + resources: + - pods + verbs: + - get + - apiGroups: + - "" + resources: + - services + verbs: + - get + - list + - patch + - watch + - apiGroups: + - cassandra.rook.io + resources: + - clusters + verbs: + - get + +--- + +# ServiceAccount for cassandra members. +apiVersion: v1 +kind: ServiceAccount +metadata: + name: rook-cassandra-member + namespace: rook-cassandra + +--- + +# RoleBinding for cassandra members. +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: rook-cassandra-member + namespace: rook-cassandra +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: rook-cassandra-member +subjects: +- kind: ServiceAccount + name: rook-cassandra-member + namespace: rook-cassandra + +--- + +# Cassandra Cluster +apiVersion: cassandra.rook.io/v1alpha1 +kind: Cluster +metadata: + name: rook-cassandra + namespace: rook-cassandra +spec: + version: 3.11.1 + mode: cassandra + datacenter: + name: us-east-1 + racks: + - name: us-east-1a + members: 3 + storage: + volumeClaimTemplates: + - metadata: + name: rook-cassandra-data + spec: + resources: + requests: + storage: 5Gi + resources: + requests: + cpu: 1 + memory: 2Gi + limits: + cpu: 1 + memory: 2Gi + diff --git a/cluster/examples/kubernetes/cassandra/operator.yaml b/cluster/examples/kubernetes/cassandra/operator.yaml new file mode 100644 index 000000000..9cfdcda7c --- /dev/null +++ b/cluster/examples/kubernetes/cassandra/operator.yaml @@ -0,0 +1,202 @@ + +# Namespace where Cassandra Operator will live +apiVersion: v1 +kind: Namespace +metadata: + name: rook-cassandra-system + +--- + +# Cassandra Cluster CRD +apiVersion: apiextensions.k8s.io/v1beta1 +kind: CustomResourceDefinition +metadata: + name: clusters.cassandra.rook.io +spec: + group: cassandra.rook.io + names: + kind: Cluster + listKind: ClusterList + plural: clusters + singular: cluster + scope: Namespaced + version: v1alpha1 + validation: + openAPIV3Schema: + properties: + spec: + type: object + properties: + version: + type: string + description: "Version of Cassandra" + datacenter: + type: object + properties: + name: + type: string + description: "Datacenter Name" + racks: + type: array + properties: + name: + type: string + members: + type: integer + configMapName: + type: string + storage: + type: object + properties: + volumeClaimTemplates: + type: object + # TODO: Check if we can ref the already existing schema + required: + - "volumeClaimTemplates" + placement: + type: object + resources: + type: object + properties: + # TODO: Check if we can ref the already existing schema + cassandra: + type: object + sidecar: + type: object + required: + - "cassandra" + - "sidecar" + sidecarImage: + type: object + required: + - "name" + - "members" + - "storage" + - "resources" + required: + - "name" + required: + - "version" + - "datacenter" + +--- + +# ClusterRole for cassandra-operator. +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: rook-cassandra-operator +rules: + - apiGroups: + - "" + resources: + - pods + verbs: + - get + - list + - watch + - delete + - apiGroups: + - "" + resources: + - services + verbs: + - "*" + - apiGroups: + - "" + resources: + - persistentvolumes + - persistentvolumeclaims + verbs: + - get + - delete + - apiGroups: + - "" + resources: + - nodes + verbs: + - get + - apiGroups: + - apps + resources: + - statefulsets + verbs: + - "*" + - apiGroups: + - policy + resources: + - poddisruptionbudgets + verbs: + - create + - apiGroups: + - cassandra.rook.io + resources: + - "*" + verbs: + - "*" + - apiGroups: + - "" + resources: + - events + verbs: + - create + - update + - patch +--- +# ServiceAccount for cassandra-operator. Serves as its authorization identity. +apiVersion: v1 +kind: ServiceAccount +metadata: + name: rook-cassandra-operator + namespace: rook-cassandra-system +--- +# Bind cassandra-operator ServiceAccount with ClusterRole. +kind: ClusterRoleBinding +apiVersion: rbac.authorization.k8s.io/v1 +metadata: + name: rook-cassandra-operator +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: rook-cassandra-operator +subjects: +- kind: ServiceAccount + name: rook-cassandra-operator + namespace: rook-cassandra-system +--- +# cassandra-operator StatefulSet. + apiVersion: apps/v1 + kind: StatefulSet + metadata: + name: rook-cassandra-operator + namespace: rook-cassandra-system + labels: + app: rook-cassandra-operator + spec: + replicas: 1 + serviceName: "non-existent-service" + selector: + matchLabels: + app: rook-cassandra-operator + template: + metadata: + labels: + app: rook-cassandra-operator + spec: + serviceAccountName: rook-cassandra-operator + containers: + - name: rook-cassandra-operator + image: rook/cassandra:master + imagePullPolicy: "Always" + args: ["cassandra", "operator"] + env: + - name: POD_NAME + valueFrom: + fieldRef: + fieldPath: metadata.name + - name: POD_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace + + diff --git a/cmd/rook/cassandra/cassandra.go b/cmd/rook/cassandra/cassandra.go new file mode 100644 index 000000000..8d9420e17 --- /dev/null +++ b/cmd/rook/cassandra/cassandra.go @@ -0,0 +1,51 @@ +/* +Copyright 2018 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 cassandra + +import ( + "github.com/coreos/pkg/capnslog" + "github.com/rook/rook/cmd/rook/rook" + "github.com/rook/rook/pkg/clusterd" + "github.com/rook/rook/pkg/operator/k8sutil" + "github.com/rook/rook/pkg/util/exec" + "github.com/spf13/cobra" +) + +// Cmd exports cobra command according to the cobra documentation. +var Cmd = &cobra.Command{ + Use: "cassandra", + Short: "Main command for cassandra controller pod.", + Hidden: true, +} + +var ( + logger = capnslog.NewPackageLogger("github.com/rook/rook", "cassandracmd") +) + +func init() { + Cmd.AddCommand(operatorCmd) + Cmd.AddCommand(sidecarCmd) +} + +func createContext() *clusterd.Context { + executor := &exec.CommandExecutor{} + return &clusterd.Context{ + Executor: executor, + ConfigDir: k8sutil.DataDir, + LogLevel: rook.Cfg.LogLevel, + } +} diff --git a/cmd/rook/cassandra/operator.go b/cmd/rook/cassandra/operator.go new file mode 100644 index 000000000..3022000ee --- /dev/null +++ b/cmd/rook/cassandra/operator.go @@ -0,0 +1,108 @@ +/* +Copyright 2018 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 cassandra + +import ( + "fmt" + "github.com/rook/rook/cmd/rook/rook" + rookinformers "github.com/rook/rook/pkg/client/informers/externalversions" + "github.com/rook/rook/pkg/operator/cassandra/constants" + "github.com/rook/rook/pkg/operator/cassandra/controller" + "github.com/rook/rook/pkg/operator/k8sutil" + "github.com/rook/rook/pkg/util/flags" + "github.com/spf13/cobra" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apiserver/pkg/server" + kubeinformers "k8s.io/client-go/informers" + "k8s.io/client-go/informers/internalinterfaces" + "time" +) + +const resyncPeriod = time.Second * 30 + +var operatorCmd = &cobra.Command{ + Use: "operator", + Short: "Runs the cassandra operator to deploy and manage cassandra in Kubernetes", + Long: `Runs the cassandra operator to deploy and manage cassandra in kubernetes clusters. +https://github.com/rook/rook`, +} + +func init() { + flags.SetFlagsFromEnv(operatorCmd.Flags(), rook.RookEnvVarPrefix) + + operatorCmd.RunE = startOperator +} + +func startOperator(cmd *cobra.Command, args []string) error { + rook.SetLogLevel() + rook.LogStartupInfo(operatorCmd.Flags()) + + kubeClient, _, rookClient, err := rook.GetClientset() + if err != nil { + rook.TerminateFatal(fmt.Errorf("failed to get k8s clients. %+v", err)) + } + + logger.Infof("starting cassandra operator") + + // Using the current image version to deploy other rook pods + pod, err := k8sutil.GetRunningPod(kubeClient) + if err != nil { + rook.TerminateFatal(fmt.Errorf("failed to get pod. %+v\n", err)) + } + + rookImage, err := k8sutil.GetContainerImage(pod, "") + if err != nil { + rook.TerminateFatal(fmt.Errorf("failed to get container image. %+v\n", err)) + } + + // Only watch kubernetes resources relevant to our app + var tweakListOptionsFunc internalinterfaces.TweakListOptionsFunc + tweakListOptionsFunc = func(options *metav1.ListOptions) { + + options.LabelSelector = fmt.Sprintf("%s=%s", "app", constants.AppName) + } + + kubeInformerFactory := kubeinformers.NewSharedInformerFactoryWithOptions(kubeClient, resyncPeriod, kubeinformers.WithTweakListOptions(tweakListOptionsFunc)) + rookInformerFactory := rookinformers.NewSharedInformerFactory(rookClient, resyncPeriod) + + c := controller.New( + rookImage, + kubeClient, + rookClient, + rookInformerFactory.Cassandra().V1alpha1().Clusters(), + kubeInformerFactory.Apps().V1().StatefulSets(), + kubeInformerFactory.Core().V1().Services(), + kubeInformerFactory.Core().V1().Pods(), + kubeInformerFactory.Core().V1().ServiceAccounts(), + kubeInformerFactory.Rbac().V1().Roles(), + kubeInformerFactory.Rbac().V1().RoleBindings(), + ) + + // Create a channel to receive OS signals + stopCh := server.SetupSignalHandler() + + // Start the informer factories + go kubeInformerFactory.Start(stopCh) + go rookInformerFactory.Start(stopCh) + + // Start the controller + if err = c.Run(1, stopCh); err != nil { + logger.Fatalf("Error running controller: %s", err.Error()) + } + + return nil +} diff --git a/cmd/rook/main.go b/cmd/rook/main.go index f3fca4000..0478a2429 100644 --- a/cmd/rook/main.go +++ b/cmd/rook/main.go @@ -18,6 +18,7 @@ package main import ( "fmt" + "github.com/rook/rook/cmd/rook/cassandra" "github.com/rook/rook/cmd/rook/ceph" "github.com/rook/rook/cmd/rook/cockroachdb" "github.com/rook/rook/cmd/rook/minio" @@ -40,6 +41,7 @@ func addCommands() { rook.RootCmd.AddCommand(cockroachdb.Cmd) rook.RootCmd.AddCommand(minio.Cmd) rook.RootCmd.AddCommand(nfs.Cmd) + rook.RootCmd.AddCommand(cassandra.Cmd) // add the ceph legacy commands to the main command for backwards compatibility // TODO: remove these Ceph legacy commands in the future diff --git a/images/Makefile b/images/Makefile index 636b6d2e6..cf9f424be 100644 --- a/images/Makefile +++ b/images/Makefile @@ -38,6 +38,10 @@ minio.%: nfs.%: @$(MAKE) -C nfs PLATFORM=$* +cassandra.%: + @$(MAKE) -C cassandra PLATFORM=$* + + do.build.images.%: $(foreach i,$(IMAGES), $(i).%); do.build: do.build.images.$(PLATFORM) ; diff --git a/images/cassandra/Dockerfile b/images/cassandra/Dockerfile new file mode 100644 index 000000000..2c3962d5b --- /dev/null +++ b/images/cassandra/Dockerfile @@ -0,0 +1,36 @@ +#Copyright 2018 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. + +FROM alpine:3.8 + +ARG ARCH +ARG TINI_VERSION + +ADD rook /usr/local/bin/ + +# Add files for the sidecar +RUN mkdir -p /sidecar +RUN mkdir -p /sidecar/plugins + +ADD rook /sidecar/ +# Jolokia plugin for JMX<->HTTP +ADD "http://search.maven.org/remotecontent?filepath=org/jolokia/jolokia-jvm/1.6.0/jolokia-jvm-1.6.0-agent.jar" /sidecar/plugins/jolokia.jar + +# Run tini as PID 1 and avoid signal handling issues +ADD https://github.com/krallin/tini/releases/download/${TINI_VERSION}/tini-static-${ARCH} /sidecar/tini +RUN chmod +x /sidecar/tini && chmod +x /usr/local/bin/rook + + +ENTRYPOINT ["/sidecar/tini", "--", "/usr/local/bin/rook"] +CMD [""] diff --git a/images/cassandra/Makefile b/images/cassandra/Makefile new file mode 100644 index 000000000..214558caf --- /dev/null +++ b/images/cassandra/Makefile @@ -0,0 +1,37 @@ +#Copyright 2018 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. + + +include ../image.mk + +# ==================================================================================== +# Image Build Options + +CASSANDRA_OPERATOR_IMAGE = $(BUILD_REGISTRY)/cassandra-$(GOARCH) + +TEMP := $(shell mktemp -d) + +# ==================================================================================== +# Build Rook Cassandra + +do.build: + @echo === docker build $(CASSANDRA_OPERATOR_IMAGE) + @cp Dockerfile $(TEMP) + @cp $(OUTPUT_DIR)/bin/linux_$(GOARCH)/rook $(TEMP) + @docker build $(BUILD_ARGS) \ + --build-arg ARCH=$(GOARCH) \ + --build-arg TINI_VERSION=$(TINI_VERSION) \ + -t $(CASSANDRA_OPERATOR_IMAGE) \ + $(TEMP) + @rm -fr $(TEMP) diff --git a/pkg/operator/cassandra/controller/controller.go b/pkg/operator/cassandra/controller/controller.go new file mode 100644 index 000000000..ef979abea --- /dev/null +++ b/pkg/operator/cassandra/controller/controller.go @@ -0,0 +1,344 @@ +/* +Copyright 2018 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 controller + +import ( + "fmt" + "github.com/coreos/pkg/capnslog" + "github.com/davecgh/go-spew/spew" + cassandrav1alpha1 "github.com/rook/rook/pkg/apis/cassandra.rook.io/v1alpha1" + rookClientset "github.com/rook/rook/pkg/client/clientset/versioned" + rookScheme "github.com/rook/rook/pkg/client/clientset/versioned/scheme" + informersv1alpha1 "github.com/rook/rook/pkg/client/informers/externalversions/cassandra.rook.io/v1alpha1" + listersv1alpha1 "github.com/rook/rook/pkg/client/listers/cassandra.rook.io/v1alpha1" + "github.com/rook/rook/pkg/operator/cassandra/controller/util" + appsv1 "k8s.io/api/apps/v1" + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/util/runtime" + "k8s.io/apimachinery/pkg/util/wait" + appsinformers "k8s.io/client-go/informers/apps/v1" + coreinformers "k8s.io/client-go/informers/core/v1" + rbacinformers "k8s.io/client-go/informers/rbac/v1" + "k8s.io/client-go/kubernetes" + "k8s.io/client-go/kubernetes/scheme" + typedcorev1 "k8s.io/client-go/kubernetes/typed/core/v1" + appslisters "k8s.io/client-go/listers/apps/v1" + corelisters "k8s.io/client-go/listers/core/v1" + "k8s.io/client-go/tools/cache" + "k8s.io/client-go/tools/record" + "k8s.io/client-go/util/workqueue" + "reflect" + "time" +) + +const ( + controllerName = "cassandra-controller" + clusterQueueName = "cluster-queue" +) + +var logger = capnslog.NewPackageLogger("github.com/rook/rook", "cassandra-controller") + +// ClusterController encapsulates all the tools the controller needs +// in order to talk to the Kubernetes API +type ClusterController struct { + rookImage string + kubeClient kubernetes.Interface + rookClient rookClientset.Interface + clusterLister listersv1alpha1.ClusterLister + clusterListerSynced cache.InformerSynced + statefulSetLister appslisters.StatefulSetLister + statefulSetListerSynced cache.InformerSynced + serviceLister corelisters.ServiceLister + serviceListerSynced cache.InformerSynced + podLister corelisters.PodLister + podListerSynced cache.InformerSynced + + // queue is a rate limited work queue. This is used to queue work to be + // processed instead of performing it as soon as a change happens. This + // means we can ensure we only process a fixed amount of resources at a + // time, and makes it easy to ensure we are never processing the same item + // simultaneously in two different workers. + queue workqueue.RateLimitingInterface + // recorder is an event recorder for recording Event resources to the Kubernetes API + recorder record.EventRecorder +} + +// New returns a new ClusterController +func New( + rookImage string, + kubeClient kubernetes.Interface, + rookClient rookClientset.Interface, + clusterInformer informersv1alpha1.ClusterInformer, + statefulSetInformer appsinformers.StatefulSetInformer, + serviceInformer coreinformers.ServiceInformer, + podInformer coreinformers.PodInformer, + serviceAccountInformer coreinformers.ServiceAccountInformer, + roleInformer rbacinformers.RoleInformer, + roleBindingInformer rbacinformers.RoleBindingInformer, + +) *ClusterController { + + // Add sample-controller types to the default Kubernetes Scheme so Events can be + // logged for sample-controller types. + rookScheme.AddToScheme(scheme.Scheme) + // Create event broadcaster + logger.Infof("creating event broadcaster...") + eventBroadcaster := record.NewBroadcaster() + eventBroadcaster.StartLogging(logger.Infof) + eventBroadcaster.StartRecordingToSink(&typedcorev1.EventSinkImpl{Interface: kubeClient.CoreV1().Events("")}) + recorder := eventBroadcaster.NewRecorder(scheme.Scheme, corev1.EventSource{Component: controllerName}) + + cc := &ClusterController{ + rookImage: rookImage, + kubeClient: kubeClient, + rookClient: rookClient, + + clusterLister: clusterInformer.Lister(), + clusterListerSynced: clusterInformer.Informer().HasSynced, + statefulSetLister: statefulSetInformer.Lister(), + statefulSetListerSynced: statefulSetInformer.Informer().HasSynced, + podLister: podInformer.Lister(), + podListerSynced: podInformer.Informer().HasSynced, + serviceLister: serviceInformer.Lister(), + serviceListerSynced: serviceInformer.Informer().HasSynced, + + queue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), clusterQueueName), + recorder: recorder, + } + + // Add event handling functions + + clusterInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ + AddFunc: func(obj interface{}) { + newCluster := obj.(*cassandrav1alpha1.Cluster) + cc.enqueueCluster(newCluster) + }, + UpdateFunc: func(old, new interface{}) { + newCluster := new.(*cassandrav1alpha1.Cluster) + oldCluster := old.(*cassandrav1alpha1.Cluster) + // If the Spec is the same as the one in our cache, there aren't + // any changes we are interested in. + if reflect.DeepEqual(newCluster.Spec, oldCluster.Spec) { + return + } + cc.enqueueCluster(newCluster) + }, + DeleteFunc: func(obj interface{}) { + // TODO: handle deletion + }, + }) + + statefulSetInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ + AddFunc: cc.handleObject, + UpdateFunc: func(old, new interface{}) { + newStatefulSet := new.(*appsv1.StatefulSet) + oldStatefulSet := old.(*appsv1.StatefulSet) + // If the StatefulSet is the same as the one in our cache, there + // is no use adding it again. + if newStatefulSet.ResourceVersion == oldStatefulSet.ResourceVersion { + return + } + // If ObservedGeneration != Generation, it means that the StatefulSet controller + // has not yet processed the current StatefulSet object. + // That means its Status is stale and we don't want to queue it. + if newStatefulSet.Status.ObservedGeneration != newStatefulSet.Generation { + return + } + cc.handleObject(new) + }, + DeleteFunc: cc.handleObject, + }) + + serviceInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ + AddFunc: func(obj interface{}) { + service := obj.(*corev1.Service) + if service.Spec.ClusterIP == corev1.ClusterIPNone { + return + } + cc.handleObject(obj) + }, + UpdateFunc: func(old, new interface{}) { + newService := new.(*corev1.Service) + oldService := old.(*corev1.Service) + if oldService.ResourceVersion == newService.ResourceVersion { + return + } + cc.handleObject(new) + }, + DeleteFunc: func(obj interface{}) { + // TODO: investigate if further action needs to be taken + }, + }) + + return cc +} + +// Run starts the ClusterController process loop +func (cc *ClusterController) Run(threadiness int, stopCh <-chan struct{}) error { + defer runtime.HandleCrash() + defer cc.queue.ShutDown() + + // Start the informer factories to begin populating the informer caches + logger.Info("starting cassandra controller") + + // Wait for the caches to be synced before starting workers + logger.Info("waiting for informers caches to sync...") + if ok := cache.WaitForCacheSync( + stopCh, + cc.clusterListerSynced, + cc.statefulSetListerSynced, + cc.podListerSynced, + cc.serviceListerSynced, + ); !ok { + return fmt.Errorf("failed to wait for caches to sync") + } + + logger.Info("starting workers") + for i := 0; i < threadiness; i++ { + go wait.Until(cc.runWorker, time.Second, stopCh) + } + + logger.Info("started workers") + <-stopCh + logger.Info("Shutting down cassandra controller workers") + + return nil +} + +func (cc *ClusterController) runWorker() { + for cc.processNextWorkItem() { + } +} + +func (cc *ClusterController) processNextWorkItem() bool { + obj, shutdown := cc.queue.Get() + + if shutdown { + return false + } + + err := func(obj interface{}) error { + defer cc.queue.Done(obj) + key, ok := obj.(string) + if !ok { + cc.queue.Forget(obj) + runtime.HandleError(fmt.Errorf("expected string in queue but got %#v", obj)) + } + if err := cc.syncHandler(key); err != nil { + cc.queue.AddRateLimited(key) + return fmt.Errorf("error syncing '%s', requeueing: %s", key, err.Error()) + } + cc.queue.Forget(obj) + logger.Infof("Successfully synced '%s'", key) + return nil + }(obj) + + if err != nil { + runtime.HandleError(err) + return true + } + + return true +} + +// syncHandler compares the actual state with the desired, and attempts to +// converge the two. It then updates the Status block of the Cluster +// resource with the current status of the resource. +func (cc *ClusterController) syncHandler(key string) error { + + // Convert the namespace/name string into a distinct namespace and name. + namespace, name, err := cache.SplitMetaNamespaceKey(key) + if err != nil { + runtime.HandleError(fmt.Errorf("invalid resource key: %s", key)) + return nil + } + + // Get the Cluster resource with this namespace/name + cluster, err := cc.clusterLister.Clusters(namespace).Get(name) + if err != nil { + // The Cluster resource may no longer exist, in which case we stop processing. + if apierrors.IsNotFound(err) { + runtime.HandleError(fmt.Errorf("cluster '%s' in work queue no longer exists", key)) + return nil + } + return fmt.Errorf("Unexpected error while getting cluster object: %s", err) + } + + logger.Infof("handling cluster object: %+v", spew.Sdump(cluster)) + // Deepcopy here to ensure nobody messes with the cache. + old, new := cluster, cluster.DeepCopy() + // If sync was successful and Status has changed, update the Cluster. + if err = cc.Sync(new); err == nil && !reflect.DeepEqual(old.Status, new.Status) { + err = util.PatchClusterStatus(new, cc.rookClient) + } + + return err +} + +// enqueueCluster takes a Cluster resource and converts it into a namespace/name +// string which is then put onto the work queue. This method should not be +// passed resources of any type other than Cluster. +func (cc *ClusterController) enqueueCluster(obj *cassandrav1alpha1.Cluster) { + var key string + var err error + if key, err = cache.MetaNamespaceKeyFunc(obj); err != nil { + runtime.HandleError(err) + return + } + cc.queue.AddRateLimited(key) +} + +// handleObject will take any resource implementing metav1.Object and attempt +// to find the Cluster resource that 'owns' it. It does this by looking at the +// objects metadata.ownerReferences field for an appropriate OwnerReference. +// It then enqueues that Cluster resource to be processed. If the object does not +// have an appropriate OwnerReference, it will simply be skipped. +func (cc *ClusterController) handleObject(obj interface{}) { + var object metav1.Object + var ok bool + if object, ok = obj.(metav1.Object); !ok { + tombstone, ok := obj.(cache.DeletedFinalStateUnknown) + if !ok { + runtime.HandleError(fmt.Errorf("error decoding object, invalid type")) + return + } + object, ok = tombstone.Obj.(metav1.Object) + if !ok { + runtime.HandleError(fmt.Errorf("error decoding object tombstone, invalid type")) + return + } + logger.Infof("Recovered deleted object '%s' from tombstone", object.GetName()) + } + logger.Infof("Processing object: %s", object.GetName()) + if ownerRef := metav1.GetControllerOf(object); ownerRef != nil { + // If the object is not a Cluster or doesn't belong to our APIVersion, skip it. + if ownerRef.Kind != "Cluster" || ownerRef.APIVersion != cassandrav1alpha1.APIVersion { + return + } + + cluster, err := cc.clusterLister.Clusters(object.GetNamespace()).Get(ownerRef.Name) + if err != nil { + logger.Infof("ignoring orphaned object '%s' of cluster '%s'", object.GetSelfLink(), ownerRef.Name) + return + } + + cc.enqueueCluster(cluster) + return + } +}