func (c *Controller) enqueueDataBase(obj interface{}) {
	var key string
	var err error
	if key, err = cache.MetaNamespaceKeyFunc(obj); err != nil {
		runtime.HandleError(err)
		return
	}
	c.workqueue.AddRateLimited(key)
}
enqueueDataBase takes a Database 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 Database.
package main
import (
	"fmt"
	"time"
	"github.com/golang/glog"
	appsv1 "k8s.io/api/apps/v1"
	corev1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/apimachinery/pkg/util/runtime"
	"k8s.io/apimachinery/pkg/util/wait"
	kubeinformers "k8s.io/client-go/informers"
	"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"
	"k8s.io/client-go/tools/cache"
	"k8s.io/client-go/tools/record"
	"k8s.io/client-go/util/workqueue"
	examplev1 "github.com/nikhita/custom-database-controller/pkg/apis/example.com/v1"
	clientset "github.com/nikhita/custom-database-controller/pkg/client/clientset/versioned"
	samplescheme "github.com/nikhita/custom-database-controller/pkg/client/clientset/versioned/scheme"
	informers "github.com/nikhita/custom-database-controller/pkg/client/informers/externalversions"
	listers "github.com/nikhita/custom-database-controller/pkg/client/listers/example.com/v1"
)
const controllerAgentName = "mysql-controller"
const (
	SuccessSynced = "Synced"
	ErrResourceExists = "ErrResourceExists"
	MessageResourceExists = "Resource %q already exists and is not managed by Database"
	MessageResourceSynced = "Database synced successfully"
)
type Controller struct {
	kubeclientset kubernetes.Interface
	exampleclientset clientset.Interface
	deploymentsLister appslisters.DeploymentLister
	deploymentsSynced cache.InformerSynced
	databaseLister    listers.DatabaseLister
	databaseSynced    cache.InformerSynced
	workqueue workqueue.RateLimitingInterface
	recorder record.EventRecorder
}
func NewController(
	kubeclientset kubernetes.Interface,
	exampleclientset clientset.Interface,
	kubeInformerFactory kubeinformers.SharedInformerFactory,
	exampleInformerFactory informers.SharedInformerFactory) *Controller {
	deploymentInformer := kubeInformerFactory.Apps().V1().Deployments()
	databaseInformer := exampleInformerFactory.Example().V1().Databases()
	samplescheme.AddToScheme(scheme.Scheme)
	glog.V(4).Info("Creating event broadcaster")
	eventBroadcaster := record.NewBroadcaster()
	eventBroadcaster.StartLogging(glog.Infof)
	eventBroadcaster.StartRecordingToSink(&typedcorev1.EventSinkImpl{Interface: kubeclientset.CoreV1().Events("")})
	recorder := eventBroadcaster.NewRecorder(scheme.Scheme, corev1.EventSource{Component: controllerAgentName})
	controller := &Controller{
		kubeclientset:     kubeclientset,
		exampleclientset:  exampleclientset,
		deploymentsLister: deploymentInformer.Lister(),
		deploymentsSynced: deploymentInformer.Informer().HasSynced,
		databaseLister:    databaseInformer.Lister(),
		databaseSynced:    databaseInformer.Informer().HasSynced,
		workqueue:         workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), ""),
		recorder:          recorder,
	}
	glog.Info("Setting up event handlers")
	databaseInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
		AddFunc: controller.enqueueDataBase,
		UpdateFunc: func(old, new interface{}) {
			controller.enqueueDataBase(new)
		},
	})
	deploymentInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
		AddFunc: controller.handleObject,
		UpdateFunc: func(old, new interface{}) {
			newDepl := new.(*appsv1.Deployment)
			oldDepl := old.(*appsv1.Deployment)
			if newDepl.ResourceVersion == oldDepl.ResourceVersion {
				return
			}
			controller.handleObject(new)
		},
		DeleteFunc: controller.handleObject,
	})
	return controller
}
func (c *Controller) Run(threadiness int, stopCh <-chan struct{}) error {
	defer runtime.HandleCrash()
	defer c.workqueue.ShutDown()
	glog.Info("Starting Database controller")
	glog.Info("Waiting for informer caches to sync")
	if ok := cache.WaitForCacheSync(stopCh, c.deploymentsSynced, c.databaseSynced); !ok {
		return fmt.Errorf("failed to wait for caches to sync")
	}
	glog.Info("Starting workers")
	for i := 0; i < threadiness; i++ {
		go wait.Until(c.runWorker, time.Second, stopCh)
	}
	glog.Info("Started workers")
	<-stopCh
	glog.Info("Shutting down workers")
	return nil
}
func (c *Controller) runWorker() {
	for c.processNextWorkItem() {
	}
}
func (c *Controller) processNextWorkItem() bool {
	obj, shutdown := c.workqueue.Get()
	if shutdown {
		return false
	}
	err := func(obj interface{}) error {
		defer c.workqueue.Done(obj)
		var key string
		var ok bool
		if key, ok = obj.(string); !ok {
			c.workqueue.Forget(obj)
			runtime.HandleError(fmt.Errorf("expected string in workqueue but got %#v", obj))
			return nil
		}
		if err := c.syncHandler(key); err != nil {
			return fmt.Errorf("error syncing '%s': %s", key, err.Error())
		}
		c.workqueue.Forget(obj)
		glog.Infof("Successfully synced '%s'", key)
		return nil
	}(obj)
	if err != nil {
		runtime.HandleError(err)
		return true
	}
	return true
}
func (c *Controller) syncHandler(key string) error {
	namespace, name, err := cache.SplitMetaNamespaceKey(key)
	if err != nil {
		runtime.HandleError(fmt.Errorf("invalid resource key: %s", key))
		return nil
	}
	database, err := c.databaseLister.Databases(namespace).Get(name)
	if err != nil {
		if errors.IsNotFound(err) {
			runtime.HandleError(fmt.Errorf("database '%s' in work queue no longer exists", key))
			return nil
		}
		return err
	}
	deploymentName := database.Spec.User
	if deploymentName == "" {
		runtime.HandleError(fmt.Errorf("%s: deployment name must be specified", key))
		return nil
	}
	deployment, err := c.deploymentsLister.Deployments(database.Namespace).Get(deploymentName)
	if errors.IsNotFound(err) {
		deployment, err = c.kubeclientset.AppsV1().Deployments(database.Namespace).Create(newDeployment(database))
	}
	if err != nil {
		return err
	}
	if !metav1.IsControlledBy(deployment, database) {
		msg := fmt.Sprintf(MessageResourceExists, deployment.Name)
		c.recorder.Event(database, corev1.EventTypeWarning, ErrResourceExists, msg)
		return fmt.Errorf(msg)
	}
	if database.Spec.Replicas != nil && *database.Spec.Replicas != *deployment.Spec.Replicas {
		glog.V(4).Infof("Database %s replicas: %d, deployment replicas: %d", name, *database.Spec.Replicas, *deployment.Spec.Replicas)
		deployment, err = c.kubeclientset.AppsV1().Deployments(database.Namespace).Update(newDeployment(database))
	}
	if err != nil {
		return err
	}
	err = c.updateDatabaseStatus(database, deployment)
	if err != nil {
		return err
	}
	c.recorder.Event(database, corev1.EventTypeNormal, SuccessSynced, MessageResourceSynced)
	return nil
}
func (c *Controller) updateDatabaseStatus(database *examplev1.Database, deployment *appsv1.Deployment) error {
	databaseCopy := database.DeepCopy()
	databaseCopy.Status.AvailableReplicas = deployment.Status.AvailableReplicas
	_, err := c.exampleclientset.ExampleV1().Databases(database.Namespace).UpdateStatus(databaseCopy)
	return err
}