Golang Based Operator Quickstart

This guide walks through an example of building a simple memcached-operator using the operator-sdk CLI tool and controller-runtime library API.

Create a new project

Use the CLI to create a new memcached-operator project:

  1. $ mkdir -p $HOME/projects
  2. $ cd $HOME/projects
  3. $ operator-sdk new memcached-operator --repo=github.com/example-inc/memcached-operator
  4. $ cd memcached-operator

To learn about the project directory structure, see project layout doc.

A note on dependency management

operator-sdk new generates a go.mod file to be used with Go modules. The --repo=<path> flag is required when creating a project outside of $GOPATH/src, as scaffolded files require a valid module path. Ensure you activate module support before using the SDK. From the Go modules Wiki:

You can activate module support in one of two ways:

  • Invoke the go command in a directory with a valid go.mod file in the current directory or any parent of it and the environment variable GO111MODULE unset (or explicitly set to auto).
  • Invoke the go command with GO111MODULE=on environment variable set.
Vendoring

By default --vendor=false, so an operator’s dependencies are downloaded and cached in the Go modules cache. Calls to go {build,clean,get,install,list,run,test} by operator-sdk subcommands will use an external modules directory. Execute go help modules for more information.

The Operator SDK can create a vendor directory for Go dependencies if the project is initialized with --vendor=true.

Operator scope

Read the operator scope documentation on how to run your operator as namespace-scoped vs cluster-scoped.

Manager

The main program for the operator cmd/manager/main.go initializes and runs the Manager.

The Manager will automatically register the scheme for all custom resources defined under pkg/apis/... and run all controllers under pkg/controller/....

The Manager can restrict the namespace that all controllers will watch for resources:

  1. mgr, err := manager.New(cfg, manager.Options{Namespace: namespace})

By default this will be the namespace that the operator is running in. To watch all namespaces leave the namespace option empty:

  1. mgr, err := manager.New(cfg, manager.Options{Namespace: ""})

It is also possible to use the MultiNamespacedCacheBuilder to watch a specific set of namespaces:

  1. var namespaces []string // List of Namespaces
  2. // Create a new Cmd to provide shared dependencies and start components
  3. mgr, err := manager.New(cfg, manager.Options{
  4. NewCache: cache.MultiNamespacedCacheBuilder(namespaces),
  5. MapperProvider: restmapper.NewDynamicRESTMapper,
  6. MetricsBindAddress: fmt.Sprintf("%s:%d", metricsHost, metricsPort),
  7. })

By default the main program will set the manager’s namespace using the value of WATCH_NAMESPACE env defined in deploy/operator.yaml.

Add a new Custom Resource Definition

Add a new Custom Resource Definition(CRD) API called Memcached, with APIVersion cache.example.com/v1alpha1 and Kind Memcached.

  1. $ operator-sdk add api --api-version=cache.example.com/v1alpha1 --kind=Memcached

This will scaffold the Memcached resource API under pkg/apis/cache/v1alpha1/....

Define the spec and status

Modify the spec and status of the Memcached Custom Resource(CR) at pkg/apis/cache/v1alpha1/memcached_types.go:

  1. type MemcachedSpec struct {
  2. // Size is the size of the memcached deployment
  3. Size int32 `json:"size"`
  4. }
  5. type MemcachedStatus struct {
  6. // Nodes are the names of the memcached pods
  7. Nodes []string `json:"nodes"`
  8. }

After modifying the *_types.go file always run the following command to update the generated code for that resource type:

  1. $ operator-sdk generate k8s

Updating CRD manifests

Now that MemcachedSpec and MemcachedStatus have fields and possibly annotations, the CRD corresponding to the API’s group and kind must be updated. To do so, run the following command:

  1. $ operator-sdk generate crds

Notes:

  • Your CRD must specify exactly one storage version. Use the +kubebuilder:storageversion marker to indicate the GVK that should be used to store data by the API server. This marker should be in a comment above your Memcached type.

OpenAPI validation

OpenAPIv3 schemas are added to CRD manifests in the spec.validation block when the manifests are generated. This validation block allows Kubernetes to validate the properties in a Memcached Custom Resource when it is created or updated.

Markers (annotations) are available to configure validations for your API. These markers will always have a +kubebuilder:validation prefix. For example, adding an enum type specification can be done by adding the following marker:

  1. // +kubebuilder:validation:Enum=Lion;Wolf;Dragon
  2. type Alias string

Usage of markers in API code is discussed in the kubebuilder CRD generation and marker documentation. A full list of OpenAPIv3 validation markers can be found here.

To update the CRD deploy/crds/cache.example.com_memcacheds_crd.yaml, run the following command:

  1. $ operator-sdk generate crds

An example of the generated YAML is as follows:

  1. spec:
  2. validation:
  3. openAPIV3Schema:
  4. properties:
  5. spec:
  6. properties:
  7. size:
  8. format: int32
  9. type: integer

To learn more about OpenAPI v3.0 validation schemas in Custom Resource Definitions, refer to the Kubernetes Documentation.

Add a new Controller

Add a new Controller to the project that will watch and reconcile the Memcached resource:

  1. $ operator-sdk add controller --api-version=cache.example.com/v1alpha1 --kind=Memcached

This will scaffold a new Controller implementation under pkg/controller/memcached/....

For this example replace the generated Controller file pkg/controller/memcached/memcached_controller.go with the example memcached_controller.go implementation.

The example Controller executes the following reconciliation logic for each Memcached CR:

  • Create a memcached Deployment if it doesn’t exist
  • Ensure that the Deployment size is the same as specified by the Memcached CR spec
  • Update the Memcached CR status using the status writer with the names of the memcached pods

The next two subsections explain how the Controller watches resources and how the reconcile loop is triggered. Skip to the Build section to see how to build and run the operator.

Resources watched by the Controller

Inspect the Controller implementation at pkg/controller/memcached/memcached_controller.go to see how the Controller watches resources.

The first watch is for the Memcached type as the primary resource. For each Add/Update/Delete event the reconcile loop will be sent a reconcile Request (a namespace/name key) for that Memcached object:

  1. err := c.Watch(
  2. &source.Kind{Type: &cachev1alpha1.Memcached{}}, &handler.EnqueueRequestForObject{})

The next watch is for Deployments but the event handler will map each event to a reconcile Request for the owner of the Deployment. Which in this case is the Memcached object for which the Deployment was created. This allows the controller to watch Deployments as a secondary resource.

  1. err := c.Watch(&source.Kind{Type: &appsv1.Deployment{}}, &handler.EnqueueRequestForOwner{
  2. IsController: true,
  3. OwnerType: &cachev1alpha1.Memcached{},
  4. })

Controller configurations

There are a number of useful configurations that can be made when initialzing a controller and declaring the watch parameters. For more details on these configurations consult the upstream controller godocs.

  • Set the max number of concurrent Reconciles for the controller via the MaxConcurrentReconciles option. Defaults to 1.

    1. _, err := controller.New("memcached-controller", mgr, controller.Options{
    2. MaxConcurrentReconciles: 2,
    3. ...
    4. })
  • Filter watch events using predicates

  • Choose the type of EventHandler to change how a watch event will translate to reconcile requests for the reconcile loop. For operator relationships that are more complex than primary and secondary resources, the EnqueueRequestsFromMapFunc handler can be used to transform a watch event into an arbitrary set of reconcile requests.

Reconcile loop

Every Controller has a Reconciler object with a Reconcile() method that implements the reconcile loop. The reconcile loop is passed the Request argument which is a Namespace/Name key used to lookup the primary resource object, Memcached, from the cache:

  1. func (r *ReconcileMemcached) Reconcile(request reconcile.Request) (reconcile.Result, error) {
  2. // Lookup the Memcached instance for this reconcile request
  3. memcached := &cachev1alpha1.Memcached{}
  4. err := r.client.Get(context.TODO(), request.NamespacedName, memcached)
  5. ...
  6. }

Based on the return values, Result and error, the Request may be requeued and the reconcile loop may be triggered again:

  1. // Reconcile successful - don't requeue
  2. return reconcile.Result{}, nil
  3. // Reconcile failed due to error - requeue
  4. return reconcile.Result{}, err
  5. // Requeue for any reason other than error
  6. return reconcile.Result{Requeue: true}, nil

You can set the Result.RequeueAfter to requeue the Request after a grace period as well:

  1. import "time"
  2. // Reconcile for any reason than error after 5 seconds
  3. return reconcile.Result{RequeueAfter: time.Second*5}, nil

Note: Returning Result with RequeueAfter set is how you can periodically reconcile a CR.

Reconcile Result Use Cases

The following are possible reconcile loop return options.

1. With the error:

If an error is encountered during processing the appropriate return option is to return an error. This results in the reconcile loop being re-triggered to run again.

Usage

  1. return reconcile.Result{}, err

Example:

In the example below a reconcile.Result{}, err is used when there is an error reading the object. As a result the request is requeued for another try.

  1. // Fetch the Memcached instance
  2. memcached := &cachev1alpha1.Memcached{}
  3. err := r.client.Get(context.TODO(), request.NamespacedName, memcached)
  4. if err != nil {
  5. if errors.IsNotFound(err) {
  6. ...
  7. }
  8. // Error reading the object - requeue the request.
  9. reqLogger.Error(err, "Failed to get Memcached")
  10. return reconcile.Result{}, err
  11. }

2. Without an error:

There are several situations where although no error occured, the reconcile loop should signify during its return that it needs to run again.

Usage

  1. return reconcile.Result{Requeue: true}, nil

Example:

In the example below a reconcile.Result{Requeue: true}, nil is used because a new resource is being created and as such there is the potential that further processing is required. Thus, the reconcile loop needs to trigger a requeue but there is no error associated with this requeue. As a result the request is requeued for another try.

  1. // Define a new deployment
  2. dep := r.deploymentForMemcached(memcached)
  3. ...
  4. // Deployment created successfully - return and requeue
  5. return reconcile.Result{Requeue: true}, nil

3. Without an error and no need to requeue the request:

In some situations, such as when the primary resource has been deleted, there is no need to requeue the request for another attempt

Usage

  1. return reconcile.Result{}, nil

Example:

In the example below a reconcile.Result{}, nil is used because the Memcached resource was not found, and no further processing is required.

  1. // Fetch the Memcached instance
  2. memcached := &cachev1alpha1.Memcached{}
  3. err := r.client.Get(context.TODO(), request.NamespacedName, memcached)
  4. if err != nil {
  5. if errors.IsNotFound(err) {
  6. // Request object not found, could have been deleted after reconcile request.
  7. // Owned objects are automatically garbage collected. For additional cleanup logic use finalizers.
  8. // Return and don't requeue
  9. reqLogger.Info("Memcached resource not found. Ignoring since object must be deleted")
  10. return reconcile.Result{}, nil
  11. }
  12. ...

For a guide on Reconcilers, Clients, and interacting with resource Events, see the Client API doc and the controller-runtime documentation over reconcile.

Build and run the operator

Before running the operator, the CRD must be registered with the Kubernetes apiserver:

  1. $ kubectl create -f deploy/crds/cache.example.com_memcacheds_crd.yaml

Once this is done, there are two ways to run the operator:

  • As a Deployment inside a Kubernetes cluster
  • As Go program outside a cluster

1. Run as a Deployment inside the cluster

Note: operator-sdk build invokes docker build by default, and optionally buildah bud. If using buildah, skip to the operator-sdk build invocation instructions below. If using docker, make sure your docker daemon is running and that you can run the docker client without sudo. You can check if this is the case by running docker version, which should complete without errors. Follow instructions for your OS/distribution on how to start the docker daemon and configure your access permissions, if needed.

Note: If a vendor/ directory is present, run

  1. $ go mod vendor

before building the memcached-operator image.

Build the memcached-operator image and push it to a registry. Make sure to modify quay.io/example/ in the example below to reference a container repository that you have access to. You can obtain an account for storing containers at repository sites such quay.io or hub.docker.com:

  1. $ operator-sdk build quay.io/example/memcached-operator:v0.0.1
  2. $ sed -i 's|REPLACE_IMAGE|quay.io/example/memcached-operator:v0.0.1|g' deploy/operator.yaml
  3. $ docker push quay.io/example/memcached-operator:v0.0.1

Note If you are performing these steps on OSX, use the following sed command instead:

  1. $ sed -i "" 's|REPLACE_IMAGE|quay.io/example/memcached-operator:v0.0.1|g' deploy/operator.yaml

The Deployment manifest is generated at deploy/operator.yaml. Be sure to update the deployment image as shown above since the default is just a placeholder.

Setup RBAC and deploy the memcached-operator:

  1. $ kubectl create -f deploy/service_account.yaml
  2. $ kubectl create -f deploy/role.yaml
  3. $ kubectl create -f deploy/role_binding.yaml
  4. $ kubectl create -f deploy/operator.yaml

Verify that the memcached-operator is up and running:

  1. $ kubectl get deployment
  2. NAME DESIRED CURRENT UP-TO-DATE AVAILABLE AGE
  3. memcached-operator 1 1 1 1 1m

2. Run locally outside the cluster

This method is preferred during development cycle to deploy and test faster.

Set the name of the operator in an environment variable:

  1. export OPERATOR_NAME=memcached-operator

Run the operator locally with the default Kubernetes config file present at $HOME/.kube/config. And watch the namespace default:

  1. $ operator-sdk run local --watch-namespace=default
  2. 2018/09/30 23:10:11 Go Version: go1.10.2
  3. 2018/09/30 23:10:11 Go OS/Arch: darwin/amd64
  4. 2018/09/30 23:10:11 operator-sdk Version: 0.0.6+git
  5. 2018/09/30 23:10:12 Registering Components.
  6. 2018/09/30 23:10:12 Starting the Cmd.

You can use a specific kubeconfig via the flag --kubeconfig=<path/to/kubeconfig>.

3. Deploy your Operator with the Operator Lifecycle Manager (OLM)

OLM will manage creation of most if not all resources required to run your operator, using a bit of setup from other operator-sdk commands. Check out the OLM integration user guide for more information.

Create a Memcached CR

Create the example Memcached CR that was generated at deploy/crds/cache.example.com_v1alpha1_memcached_cr.yaml:

  1. $ cat deploy/crds/cache.example.com_v1alpha1_memcached_cr.yaml
  2. apiVersion: "cache.example.com/v1alpha1"
  3. kind: "Memcached"
  4. metadata:
  5. name: "example-memcached"
  6. spec:
  7. size: 3
  8. $ kubectl apply -f deploy/crds/cache.example.com_v1alpha1_memcached_cr.yaml

Ensure that the memcached-operator creates the deployment for the CR:

  1. $ kubectl get deployment
  2. NAME DESIRED CURRENT UP-TO-DATE AVAILABLE AGE
  3. memcached-operator 1 1 1 1 2m
  4. example-memcached 3 3 3 3 1m

Check the pods and CR status to confirm the status is updated with the memcached pod names:

  1. $ kubectl get pods
  2. NAME READY STATUS RESTARTS AGE
  3. example-memcached-6fd7c98d8-7dqdr 1/1 Running 0 1m
  4. example-memcached-6fd7c98d8-g5k7v 1/1 Running 0 1m
  5. example-memcached-6fd7c98d8-m7vn7 1/1 Running 0 1m
  6. memcached-operator-7cc7cfdf86-vvjqk 1/1 Running 0 2m
  1. $ kubectl get memcached/example-memcached -o yaml
  2. apiVersion: cache.example.com/v1alpha1
  3. kind: Memcached
  4. metadata:
  5. clusterName: ""
  6. creationTimestamp: 2018-03-31T22:51:08Z
  7. generation: 0
  8. name: example-memcached
  9. namespace: default
  10. resourceVersion: "245453"
  11. selfLink: /apis/cache.example.com/v1alpha1/namespaces/default/memcacheds/example-memcached
  12. uid: 0026cc97-3536-11e8-bd83-0800274106a1
  13. spec:
  14. size: 3
  15. status:
  16. nodes:
  17. - example-memcached-6fd7c98d8-7dqdr
  18. - example-memcached-6fd7c98d8-g5k7v
  19. - example-memcached-6fd7c98d8-m7vn7

Update the size

Change the spec.size field in the memcached CR from 3 to 4 and apply the change:

  1. $ cat deploy/crds/cache.example.com_v1alpha1_memcached_cr.yaml
  2. apiVersion: "cache.example.com/v1alpha1"
  3. kind: "Memcached"
  4. metadata:
  5. name: "example-memcached"
  6. spec:
  7. size: 4
  8. $ kubectl apply -f deploy/crds/cache.example.com_v1alpha1_memcached_cr.yaml

Confirm that the operator changes the deployment size:

  1. $ kubectl get deployment
  2. NAME DESIRED CURRENT UP-TO-DATE AVAILABLE AGE
  3. example-memcached 4 4 4 4 5m

Cleanup

Clean up the resources:

  1. $ kubectl delete -f deploy/crds/cache.example.com_v1alpha1_memcached_cr.yaml
  2. $ kubectl delete -f deploy/operator.yaml
  3. $ kubectl delete -f deploy/role_binding.yaml
  4. $ kubectl delete -f deploy/role.yaml
  5. $ kubectl delete -f deploy/service_account.yaml

Advanced Topics

Manage CR status conditions

An often-used pattern is to include Conditions in the status of custom resources. Conditions represent the latest available observations of an object’s state (see the Kubernetes API conventionsdocumentation for more information).

The Conditions field added to the MemcachedStatus struct simplifies the management of your CR’s conditions. It:

  • Enables callers to add and remove conditions.
  • Ensures that there are no duplicates.
  • Sorts the conditions deterministically to avoid unnecessary repeated reconciliations.
  • Automatically handles the each condition’s LastTransitionTime.
  • Provides helper methods to make it easy to determine the state of a condition.

To use conditions in your custom resource, add a Conditions field to the Status struct in _types.go:

  1. import (
  2. "github.com/operator-framework/operator-sdk/pkg/status"
  3. )
  4. type MyAppStatus struct {
  5. // Conditions represent the latest available observations of an object's state
  6. Conditions status.Conditions `json:"conditions"`
  7. }

Then, in your controller, you can use Conditions methods to make it easier to set and remove conditions or check their current values.

Adding 3rd Party Resources To Your Operator

The operator’s Manager supports the Core Kubernetes resource types as found in the client-go scheme package and will also register the schemes of all custom resource types defined in your project under pkg/apis.

  1. import (
  2. "github.com/example-inc/memcached-operator/pkg/apis"
  3. ...
  4. )
  5. // Setup Scheme for all resources
  6. if err := apis.AddToScheme(mgr.GetScheme()); err != nil {
  7. log.Error(err, "")
  8. os.Exit(1)
  9. }

To add a 3rd party resource to an operator, you must add it to the Manager’s scheme. By creating an AddToScheme() method or reusing one you can easily add a resource to your scheme. An example shows that you define a function and then use the runtime package to create a SchemeBuilder.

Register with the Manager’s scheme

Call the AddToScheme() function for your 3rd party resource and pass it the Manager’s scheme via mgr.GetScheme() in cmd/manager/main.go.

Example:

  1. import (
  2. ....
  3. routev1 "github.com/openshift/api/route/v1"
  4. )
  5. func main() {
  6. ....
  7. // Adding the routev1
  8. if err := routev1.AddToScheme(mgr.GetScheme()); err != nil {
  9. log.Error(err, "")
  10. os.Exit(1)
  11. }
  12. ....
  13. // Setup all Controllers
  14. if err := controller.AddToManager(mgr); err != nil {
  15. log.Error(err, "")
  16. os.Exit(1)
  17. }
  18. }
If 3rd party resource does not have AddToScheme() function

Use the SchemeBuilder package from controller-runtime to initialize a new scheme builder that can be used to register the 3rd party resource with the manager’s scheme.

Example of registering DNSEndpoints 3rd party resource from external-dns:

  1. import (
  2. ...
  3. "k8s.io/apimachinery/pkg/runtime/schema"
  4. "sigs.k8s.io/controller-runtime/pkg/scheme"
  5. ...
  6. // DNSEndoints
  7. externaldns "github.com/kubernetes-incubator/external-dns/endpoint"
  8. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  9. )
  10. func main() {
  11. ....
  12. log.Info("Registering Components.")
  13. schemeBuilder := &scheme.Builder{GroupVersion: schema.GroupVersion{Group: "externaldns.k8s.io", Version: "v1alpha1"}}
  14. schemeBuilder.Register(&externaldns.DNSEndpoint{}, &externaldns.DNSEndpointList{})
  15. if err := schemeBuilder.AddToScheme(mgr.GetScheme()); err != nil {
  16. log.Error(err, "")
  17. os.Exit(1)
  18. }
  19. ....
  20. // Setup all Controllers
  21. if err := controller.AddToManager(mgr); err != nil {
  22. log.Error(err, "")
  23. os.Exit(1)
  24. }
  25. }

NOTES:

  • After adding new import paths to your operator project, run go mod vendor if a vendor/ directory is present in the root of your project directory to fulfill these dependencies.
  • Your 3rd party resource needs to be added before add the controller in "Setup all Controllers".

Default Metrics exported with 3rd party resource

By default, SDK operator projects are set up to export metrics through addMetrics in cmd/manager/main.go. See that it will call the serveCRMetrics:

  1. func serveCRMetrics(cfg *rest.Config) error {
  2. ...
  3. filteredGVK, err := k8sutil.GetGVKsFromAddToScheme(apis.AddToScheme)
  4. if err != nil {
  5. return err
  6. }
  7. ...
  8. // Generate and serve custom resource specific metrics.
  9. err = kubemetrics.GenerateAndServeCRMetrics(cfg, ns, filteredGVK, metricsHost, operatorMetricsPort)
  10. if err != nil {
  11. return err
  12. }

The kubemetrics.GenerateAndServeCRMetrics function requires an RBAC rule to list all GroupVersionKinds in the list of watched namespaces, so you might need to filter the kinds returned by k8sutil.GetGVKsFromAddToScheme more stringently to avoid authorization errors such as Failed to list *unstructured.Unstructured.

In this scenario, this error may occur because your Operator RBAC roles do not include permissions to LIST the third party API schemas or the schemas which are required to them and will be added with. See that the default SDK implementation will just add the Kubernetes schemas and they will be ignored in the metrics It means that you might need to do an similar implementation to filter the third party API schemas and their dependencies added in order to provide a filtered a List of GVK(GroupVersionKind) to the GenerateAndServeCRMetrics method.

Handle Cleanup on Deletion

To implement complex deletion logic, you can add a finalizer to your Custom Resource. This will prevent your Custom Resource from being deleted until you remove the finalizer (ie, after your cleanup logic has successfully run). For more information, see the official Kubernetes documentation on finalizers.

Example:

The following is a snippet from the controller file under pkg/controller/memcached/memcached_controller.go

  1. import (
  2. ...
  3. "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
  4. )
  5. const memcachedFinalizer = "finalizer.cache.example.com"
  6. func (r *ReconcileMemcached) Reconcile(request reconcile.Request) (reconcile.Result, error) {
  7. reqLogger := log.WithValues("Request.Namespace", request.Namespace, "Request.Name", request.Name)
  8. reqLogger.Info("Reconciling Memcached")
  9. // Fetch the Memcached instance
  10. memcached := &cachev1alpha1.Memcached{}
  11. err := r.client.Get(context.TODO(), request.NamespacedName, memcached)
  12. if err != nil {
  13. if errors.IsNotFound(err) {
  14. // Request object not found, could have been deleted after reconcile request.
  15. // Owned objects are automatically garbage collected. For additional cleanup logic use finalizers.
  16. // Return and don't requeue
  17. reqLogger.Info("Memcached resource not found. Ignoring since object must be deleted.")
  18. return reconcile.Result{}, nil
  19. }
  20. // Error reading the object - requeue the request.
  21. reqLogger.Error(err, "Failed to get Memcached.")
  22. return reconcile.Result{}, err
  23. }
  24. ...
  25. // Check if the Memcached instance is marked to be deleted, which is
  26. // indicated by the deletion timestamp being set.
  27. isMemcachedMarkedToBeDeleted := memcached.GetDeletionTimestamp() != nil
  28. if isMemcachedMarkedToBeDeleted {
  29. if contains(memcached.GetFinalizers(), memcachedFinalizer) {
  30. // Run finalization logic for memcachedFinalizer. If the
  31. // finalization logic fails, don't remove the finalizer so
  32. // that we can retry during the next reconciliation.
  33. if err := r.finalizeMemcached(reqLogger, memcached); err != nil {
  34. return reconcile.Result{}, err
  35. }
  36. // Remove memcachedFinalizer. Once all finalizers have been
  37. // removed, the object will be deleted.
  38. controllerutil.RemoveFinalizer(memcached, memcachedFinalizer)
  39. err := r.client.Update(context.TODO(), memcached)
  40. if err != nil {
  41. return reconcile.Result{}, err
  42. }
  43. }
  44. return reconcile.Result{}, nil
  45. }
  46. // Add finalizer for this CR
  47. if !contains(memcached.GetFinalizers(), memcachedFinalizer) {
  48. if err := r.addFinalizer(reqLogger, memcached); err != nil {
  49. return reconcile.Result{}, err
  50. }
  51. }
  52. ...
  53. return reconcile.Result{}, nil
  54. }
  55. func (r *ReconcileMemcached) finalizeMemcached(reqLogger logr.Logger, m *cachev1alpha1.Memcached) error {
  56. // TODO(user): Add the cleanup steps that the operator
  57. // needs to do before the CR can be deleted. Examples
  58. // of finalizers include performing backups and deleting
  59. // resources that are not owned by this CR, like a PVC.
  60. reqLogger.Info("Successfully finalized memcached")
  61. return nil
  62. }
  63. func (r *ReconcileMemcached) addFinalizer(reqLogger logr.Logger, m *cachev1alpha1.Memcached) error {
  64. reqLogger.Info("Adding Finalizer for the Memcached")
  65. controllerutil.AddFinalizer(m, memcachedFinalizer)
  66. // Update CR
  67. err := r.client.Update(context.TODO(), m)
  68. if err != nil {
  69. reqLogger.Error(err, "Failed to update Memcached with finalizer")
  70. return err
  71. }
  72. return nil
  73. }
  74. func contains(list []string, s string) bool {
  75. for _, v := range list {
  76. if v == s {
  77. return true
  78. }
  79. }
  80. return false
  81. }

Metrics

To learn about how metrics work in the Operator SDK read the metrics section of the user documentation.

Leader election

During the lifecycle of an operator it’s possible that there may be more than 1 instance running at any given time e.g when rolling out an upgrade for the operator. In such a scenario it is necessary to avoid contention between multiple operator instances via leader election so that only one leader instance handles the reconciliation while the other instances are inactive but ready to take over when the leader steps down.

There are two different leader election implementations to choose from, each with its own tradeoff.

  • Leader-for-life: The leader pod only gives up leadership (via garbage collection) when it is deleted. This implementation precludes the possibility of 2 instances mistakenly running as leaders (split brain). However, this method can be subject to a delay in electing a new leader. For instance when the leader pod is on an unresponsive or partitioned node, the pod-eviction-timeout dictates how long it takes for the leader pod to be deleted from the node and step down (default 5m).
  • Leader-with-lease: The leader pod periodically renews the leader lease and gives up leadership when it can’t renew the lease. This implementation allows for a faster transition to a new leader when the existing leader is isolated, but there is a possibility of split brain in certain situations.

By default the SDK enables the leader-for-life implementation. However you should consult the docs above for both approaches to consider the tradeoffs that make sense for your use case.

The following examples illustrate how to use the two options:

Leader for life

A call to leader.Become() will block the operator as it retries until it can become the leader by creating the configmap named memcached-operator-lock.

  1. import (
  2. ...
  3. "github.com/operator-framework/operator-sdk/pkg/leader"
  4. )
  5. func main() {
  6. ...
  7. err = leader.Become(context.TODO(), "memcached-operator-lock")
  8. if err != nil {
  9. log.Error(err, "Failed to retry for leader lock")
  10. os.Exit(1)
  11. }
  12. ...
  13. }

If the operator is not running inside a cluster leader.Become() will simply return without error to skip the leader election since it can’t detect the operator’s namespace.

Leader with lease

The leader-with-lease approach can be enabled via the Manager Options for leader election.

  1. import (
  2. ...
  3. "sigs.k8s.io/controller-runtime/pkg/manager"
  4. )
  5. func main() {
  6. ...
  7. opts := manager.Options{
  8. ...
  9. LeaderElection: true,
  10. LeaderElectionID: "memcached-operator-lock"
  11. }
  12. mgr, err := manager.New(cfg, opts)
  13. ...
  14. }

When the operator is not running in a cluster, the Manager will return an error on starting since it can’t detect the operator’s namespace in order to create the configmap for leader election. You can override this namespace by setting the Manager’s LeaderElectionNamespace option.

Last modified June 24, 2020: [v0.18.x] Fix links after kubernetes renamed access-kubernetes to extend-kubernes-api (#3219) (#3285) (72f19f0c)