{"owner":"operator-framework","repo":"operator-sdk","hasSkills":true,"totalSkillsCount":7,"totalTokensCount":11023,"categories":["anthropic-skill"],"hasMcp":false,"mcpConfig":null,"found":["website/content/en/docs/building-operators/golang/references/_index.md","website/content/en/docs/building-operators/golang/references/client.md","website/content/en/docs/building-operators/golang/references/event-filtering.md","website/content/en/docs/building-operators/golang/references/logging.md","website/content/en/docs/building-operators/golang/references/markers.md","website/content/en/docs/building-operators/golang/references/openapi-validation.md","website/content/en/docs/building-operators/golang/references/proxy-vars.md"],"skills":{"website/content/en/docs/building-operators/golang/references/_index.md":"---\ntitle: Go-based Operator Reference\nlinkTitle: Reference\nweight: 100\n---","website/content/en/docs/building-operators/golang/references/client.md":"---\ntitle: Controller Runtime Client API\nlinkTitle: Controller Runtime Client API\nweight: 10\n---\n\n## Overview\n\nThe [`controller-runtime`][repo-controller-runtime] library provides various abstractions to watch and reconcile resources in a Kubernetes cluster via CRUD (Create, Update, Delete, as well as Get and List in this case) operations. Operators use at least one controller to perform a coherent set of tasks within a cluster, usually through a combination of CRUD operations. The Operator SDK uses controller-runtime's [Client][doc-client] interface, which provides the interface for these operations.\n\ncontroller-runtime defines several interfaces used for cluster interaction:\n- `client.Client`: implementers perform CRUD operations on a Kubernetes cluster.\n- `manager.Manager`: manages shared dependencies, such as Caches and Clients.\n- `reconcile.Reconciler`: compares provided state with actual cluster state and updates the cluster on finding state differences using a Client.\n\nClients are the focus of this document. A separate document will discuss Managers.\n\n**Note:** this document uses parts of the sample [`memcached-operator`][memcached-testdata] for example code.\nImport paths may be different for brevity.\n\n## Client Usage\n\n### Default Client\n\nThe SDK relies on a `manager.Manager` to create a `client.Client` interface that performs Create, Update, Delete, Get, and List operations within a `reconcile.Reconciler`'s Reconcile function. The SDK will generate code to create a Manager, which holds a Cache and a Client to be used in CRUD operations and communicate with the API server. By default a Controller's Reconciler will be populated with the Manager's Client which is a [split-client][doc-split-client].\n\nThe following code, found in `controllers/memcached_controller.go`, demonstrates how the Manager's client is passed to a reconciler.\n\n```Go\nimport (\n\tappsv1 \"k8s.io/api/apps/v1\"\n\tctrl \"sigs.k8s.io/controller-runtime\"\n\n\tcachev1alpha1 \"github.com/example/memcached-operator/api/v1alpha1\"\n)\n\nfunc (r *MemcachedReconciler) SetupWithManager(mgr ctrl.Manager) error {\n\treturn ctrl.NewControllerManagedBy(mgr). // mgr's Client is passed to r.\n\t\tFor(&cachev1alpha1.Memcached{}).\n\t\tOwns(&appsv1.Deployment{}).\n\t\tComplete(r)\n}\n\ntype MemcachedReconciler struct {\n    client.Client // Populated above from a manager.Manager.\n\n    Log    logr.Logger\n    Scheme *runtime.Scheme\n}\n```\n\nA split client reads (Get and List) from the Cache and writes (Create, Update, Delete) to the API server. Reading from the Cache significantly reduces request load on the API server; as long as the Cache is updated by the API server, read operations are eventually consistent.\n\n### Non-default Client\n\nAn operator developer may wish to create their own Client that serves read requests(Get List) from the API server instead of the cache, for example. controller-runtime provides a [constructor][doc-client-constr] for Clients:\n\n```Go\n// New returns a new Client using the provided config and Options.\nfunc New(config *rest.Config, options client.Options) (client.Client, error)\n```\n\n`client.Options` allow the caller to specify how the new Client should communicate with the API server.\n\n```Go\n// Options are creation options for a Client\ntype Options struct {\n    // Scheme, if provided, will be used to map go structs to GroupVersionKinds\n    Scheme *runtime.Scheme\n\n    // Mapper, if provided, will be used to map GroupVersionKinds to Resources\n    Mapper meta.RESTMapper\n}\n```\n\nExample:\n\n```Go\nimport (\n    \"sigs.k8s.io/controller-runtime/pkg/client/config\"\n    \"sigs.k8s.io/controller-runtime/pkg/client\"\n)\n\ncfg, err := config.GetConfig()\n...\nc, err := client.New(cfg, client.Options{})\n...\n```\n\n**Note**: defaults are set by `client.New` when Options are empty. The default [scheme][code-scheme-default] will have the [core][doc-k8s-core] Kubernetes resource types registered. The caller *must* set a scheme that has custom operator types registered for the new Client to recognize these types.\n\nCreating a new Client is not usually necessary nor advised, as the default Client is sufficient for most use cases.\n\n### Reconcile and the Client API\n\nA Reconciler implements the [`reconcile.Reconciler`][doc-reconcile-reconciler] interface, which exposes the Reconcile method. Reconcilers are added to a corresponding Controller for a Kind; Reconcile is called in response to cluster or external Events, with a `reconcile.Request` object argument, to read and write cluster state by the Controller, and returns a `ctrl.Result`. SDK Reconcilers have access to a Client in order to make Kubernetes API calls.\n\n```Go\n// MemcachedReconciler reconciles a Memcached object\ntype MemcachedReconciler struct {\n    // client, initialized using mgr.Client() above, is a split client\n    // that reads objects from the cache and writes to the apiserver\n    client.Client\n\n    Log    logr.Logger\n\n    // scheme defines methods for serializing and deserializing API objects,\n    // a type registry for converting group, version, and kind information\n    // to and from Go schemas, and mappings between Go schemas of different\n    // versions. A scheme is the foundation for a versioned API and versioned\n    // configuration over time.\n    Scheme *runtime.Scheme\n}\n\n// Reconcile watches for Events and reconciles cluster state with desired\n// state defined in the method body.\n// The Controller will requeue the Request to be processed again if an error\n// is non-nil or Result.Requeue is true, otherwise upon completion it will\n// remove the work from the queue.\nfunc (r *MemcachedReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error)\n```\n\nReconcile is where Controller business logic lives, i.e. where Client API calls are made via `MemcachedReconciler.client`. A `client.Client` implementer performs the following operations:\n\n#### Get\n\n```Go\n// Get retrieves an API object for a given object key from the Kubernetes cluster\n// and stores it in obj.\nfunc (c Client) Get(ctx context.Context, key client.ObjectKey, obj client.Object) error\n```\n\n**Note**: A `client.ObjectKey` is simply an alias for [`types.NamespacedName`][doc-types-nsname].\n\nExample:\n\n```Go\nimport (\n    \"context\"\n\n    ctrl \"sigs.k8s.io/controller-runtime\"\n\n    cachev1alpha1 \"github.com/example/memcached-operator/api/v1alpha1\"\n)\n\nfunc (r *MemcachedReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {\n    ...\n\n    memcached := &cachev1alpha1.Memcached{}\n    err := r.Get(ctx, request.NamespacedName, memcached)\n\n    ...\n}\n```\n\n#### List\n\n```Go\n// List retrieves a list of objects for a given namespace and list options\n// and stores the list in obj.\nfunc (c Client) List(ctx context.Context, list client.Object, opts ...client.ListOption) error\n```\n\nA `client.ListOption` is an interface that sets [`client.ListOptions`][list-options] fields. A `client.ListOption` is created by using one of the provided implementations: [`MatchingLabels`][matching-labels], [`MatchingFields`][matching-fields], [`InNamespace`][in-namespace].\n\nExample:\n\n```Go\nimport (\n    \"context\"\n    \"fmt\"\n\n    \"k8s.io/api/core/v1\"\n    ctrl \"sigs.k8s.io/controller-runtime\"\n    \"sigs.k8s.io/controller-runtime/pkg/client\"\n)\n\nfunc (r *MemcachedReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {\n    ...\n\n    // Return all pods in the request namespace with a label of `instance=<name>`\n    // and phase `Running`.\n    podList := &v1.PodList{}\n    opts := []client.ListOption{\n        client.InNamespace(request.NamespacedName.Namespace),\n        client.MatchingLabels{\"instance\": request.NamespacedName.Name},\n        client.MatchingFields{\"status.phase\": \"Running\"},\n    }\n    err := r.List(ctx, podList, opts...)\n\n    ...\n}\n```\n\n[list-options]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#ListOptions\n[matching-labels]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#MatchingLabels\n[matching-fields]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#MatchingFields\n[in-namespace]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#InNamespace\n\n#### Create\n\n```Go\n// Create saves the object obj in the Kubernetes cluster.\n// Returns an error\nfunc (c Client) Create(ctx context.Context, obj client.Object, opts ...client.CreateOption) error\n```\n\nA `client.CreateOption` is an interface that sets [`client.CreateOptions`][create-options] fields. A `client.CreateOption` is created by using one of the provided implementations: [`DryRunAll`][dry-run-all], [`ForceOwnership`][force-ownership]. Generally these options are not needed.\n\nExample:\n\n```Go\nimport (\n    \"context\"\n\n    \"k8s.io/api/apps/v1\"\n    ctrl \"sigs.k8s.io/controller-runtime\"\n)\n\nfunc (r *MemcachedReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {\n    ...\n\n    dep := &v1.Deployment{ // Any cluster object you want to create.\n        ...\n    }\n    err := r.Create(ctx, dep)\n\n    ...\n}\n```\n\n[create-options]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#CreateOptions\n\n#### Update\n\n```Go\n// Update updates the given obj in the Kubernetes cluster. obj must be a\n// struct pointer so that obj can be updated with the content returned\n// by the API server. Update does *not* update the resource's status\n// subresource\nfunc (c Client) Update(ctx context.Context, obj client.Object, opts ...client.UpdateOption) error\n```\n\nA `client.UpdateOption` is an interface that sets [`client.UpdateOptions`][update-options] fields. A `client.UpdateOption` is created by using one of the provided implementations: [`DryRunAll`][dry-run-all], [`ForceOwnership`][force-ownership]. Generally these options are not needed.\n\nExample:\n\n```Go\nimport (\n    \"context\"\n\n    \"k8s.io/api/apps/v1\"\n    ctrl \"sigs.k8s.io/controller-runtime\"\n)\n\nfunc (r *MemcachedReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {\n    ...\n\n    dep := &v1.Deployment{}\n    err := r.Get(ctx, request.NamespacedName, dep)\n\n    ...\n\n    dep.Spec.Selector.MatchLabels[\"is_running\"] = \"true\"\n    err := r.Update(ctx, dep)\n\n    ...\n}\n```\n\n[update-options]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#UpdateOptions\n\n#### Patch\n\n```Go\n// Patch patches the given obj in the Kubernetes cluster. obj must be a\n// struct pointer so that obj can be updated with the content returned by the Server.\nfunc (c Client) Patch(ctx context.Context, obj client.Object, patch client.Patch, opts ...client.PatchOption) error\n```\n\nA `client.PatchOption` is an interface that sets [`client.PatchOptions`][patch-options] fields. A `client.PatchOption` is created by using one of the provided implementations: [`DryRunAll`][dry-run-all], [`ForceOwnership`][force-ownership]. Generally these options are not needed.\n\nExample:\n\n```Go\nimport (\n    \"context\"\n\n    \"k8s.io/api/apps/v1\"\n    ctrl \"sigs.k8s.io/controller-runtime\"\n    \"sigs.k8s.io/controller-runtime/pkg/client\"\n)\n\nfunc (r *MemcachedReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {\n    ...\n\n    dep := &v1.Deployment{}\n    err := r.Get(ctx, request.NamespacedName, dep)\n\n    ...\n\n    // A merge patch will preserve other fields modified at runtime.\n    patch := client.MergeFrom(dep.DeepCopy())\n    dep.Spec.Selector.MatchLabels[\"is_running\"] = \"true\"\n    err := r.Patch(ctx, dep, patch)\n\n    ...\n}\n```\n\n[patch-options]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#PatchOption\n[dry-run-all]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#DryRunAll\n[force-ownership]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#ForceOwnership\n\n##### Updating Status Subresource\n\nWhen updating the [status subresource][cr-status-subresource] from the client, the [`StatusWriter`][status-writer] must be used. The status subresource is retrieved with `Status()` and updated with `Update()` or patched with `Patch()`.\n\n`Update()` takes variadic `client.UpdateOption`'s, and `Patch()` takes variadic `client.PatchOption`'s. See [`Client.Update()`](#update) and [`Client.Patch()`](#patch) for more details. Generally these options are not needed.\n\n##### Status\n\n```Go\n// Status() returns a StatusWriter object that can be used to update the\n// object's status subresource\nfunc (c Client) Status() (client.StatusWriter, error)\n```\n\nExample:\n```Go\nimport (\n    \"context\"\n\n    ctrl \"sigs.k8s.io/controller-runtime\"\n\n    cachev1alpha1 \"github.com/example/memcached-operator/api/v1alpha1\"\n)\n\nfunc (r *MemcachedReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {\n    ...\n\n    mem := &cachev1alpha1.Memcached{}\n    err := r.Get(ctx, request.NamespacedName, mem)\n\n    ...\n\n    // Update\n    mem.Status.Nodes = []string{\"pod1\", \"pod2\"}\n    err := r.Status().Update(ctx, mem)\n\n    ...\n\n    // Patch\n    patch := client.MergeFrom(mem.DeepCopy())\n    mem.Status.Nodes = []string{\"pod1\", \"pod2\", \"pod3\"}\n    err := r.Status().Patch(ctx, mem, patch)\n\n    ...\n}\n```\n\n[status-writer]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#StatusWriter\n\n#### Delete\n\n```Go\n// Delete deletes the given obj from Kubernetes cluster.\nfunc (c Client) Delete(ctx context.Context, obj client.Object, opts ...client.DeleteOption) error\n```\n\nA `client.DeleteOption` is an interface that sets [`client.DeleteOptions`][delete-opts] fields. A `client.DeleteOption` is created by using one of the provided implementations: [`GracePeriodSeconds`][grace-period-seconds], [`Preconditions`][preconditions], [`PropagationPolicy`][propagation-policy].\n\nExample:\n\n```Go\nimport (\n    \"context\"\n\n    \"k8s.io/api/core/v1\"\n    ctrl \"sigs.k8s.io/controller-runtime\"\n    \"sigs.k8s.io/controller-runtime/pkg/client\"\n)\n\nfunc (r *MemcachedReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {\n    ...\n\n    pod := &v1.Pod{}\n    err := r.Get(ctx, request.NamespacedName, pod)\n\n    ...\n\n    if pod.Status.Phase == v1.PodUnknown {\n        // Delete the pod after 5 seconds.\n        err := r.Delete(ctx, pod, client.GracePeriodSeconds(5))\n        ...\n    }\n\n    ...\n}\n```\n\n[delete-opts]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#DeleteOptions\n[grace-period-seconds]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#GracePeriodSeconds\n[preconditions]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#Preconditions\n[propagation-policy]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#PropagationPolicy\n\n#### DeleteAllOf\n\n```Go\n// DeleteAllOf deletes all objects of the given type matching the given options.\nfunc (c Client) DeleteAllOf(ctx context.Context, obj client.Object, opts ...client.DeleteAllOfOption) error\n```\n\nA `client.DeleteAllOfOption` is an interface that sets [`client.DeleteAllOfOptions`][deleteallof-opts] fields. A `client.DeleteAllOfOption` wraps a [`client.ListOption`](#list) and [`client.DeleteOption`](#delete).\n\nExample:\n\n```Go\nimport (\n    \"context\"\n    \"fmt\"\n\n    \"k8s.io/api/core/v1\"\n    ctrl \"sigs.k8s.io/controller-runtime\"\n    \"sigs.k8s.io/controller-runtime/pkg/client\"\n)\n\nfunc (r *MemcachedReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {\n    ...\n\n    // Delete all pods in the request namespace with a label of `instance=<name>`\n    // and phase `Failed`.\n    pod := &v1.Pod{}\n    opts := []client.DeleteAllOfOption{\n        client.InNamespace(request.NamespacedName.Namespace),\n        client.MatchingLabels{\"instance\", request.NamespacedName.Name},\n        client.MatchingFields{\"status.phase\": \"Failed\"},\n        client.GracePeriodSeconds(5),\n    }\n    err := r.DeleteAllOf(ctx, pod, opts...)\n\n    ...\n}\n```\n\n[deleteallof-opts]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#DeleteAllOfOptions\n\n### Example usage\n\n```Go\nimport (\n    \"context\"\n    \"reflect\"\n\n    appsv1 \"k8s.io/api/apps/v1\"\n    corev1 \"k8s.io/api/core/v1\"\n    \"k8s.io/apimachinery/pkg/api/errors\"\n    metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n    \"k8s.io/apimachinery/pkg/labels\"\n    \"k8s.io/apimachinery/pkg/runtime\"\n    \"k8s.io/apimachinery/pkg/types\"\n    ctrl \"sigs.k8s.io/controller-runtime\"\n    \"sigs.k8s.io/controller-runtime/pkg/client\"\n    \"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil\"\n\n    cachev1alpha1 \"github.com/example/memcached-operator/api/v1alpha1\"\n)\n\ntype MemcachedReconciler struct {\n    client.Client\n    Log    logr.Logger\n    Scheme *runtime.Scheme\n}\n\nfunc (r *MemcachedReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {\n\n    // Fetch the Memcached instance.\n    memcached := &cachev1alpha1.Memcached{}\n    err := r.Get(ctx, request.NamespacedName, memcached)\n    if err != nil {\n        if errors.IsNotFound(err) {\n            return ctrl.Result{}, nil\n        }\n        return ctrl.Result{}, err\n    }\n\n    // Check if the deployment already exists, if not create a new deployment.\n    found := &appsv1.Deployment{}\n    err = r.Get(ctx, types.NamespacedName{Name: memcached.Name, Namespace: memcached.Namespace}, found)\n    if err != nil {\n         if errors.IsNotFound(err) {\n            // Define and create a new deployment.\n            dep := r.deploymentForMemcached(memcached)\n            if err = r.Create(ctx, dep); err != nil {\n                return ctrl.Result{}, err\n            }\n            return ctrl.Result{Requeue: true}, nil\n        } else {\n            return ctrl.Result{}, err\n        }\n    }\n\n    // Ensure the deployment size is the same as the spec.\n    size := memcached.Spec.Size\n    if *found.Spec.Replicas != size {\n        found.Spec.Replicas = &size\n        if err = r.Update(ctx, found); err != nil {\n            return ctrl.Result{}, err\n        }\n        return ctrl.Result{Requeue: true}, nil\n    }\n\n    // Update the Memcached status with the pod names.\n    // List the pods for this CR's deployment.\n    podList := &corev1.PodList{}\n    listOpts := []client.ListOption{\n        client.InNamespace(memcached.Namespace),\n        client.MatchingLabels(labelsForApp(memcached.Name)),\n    }\n    if err = r.List(ctx, podList, listOpts...); err != nil {\n        return ctrl.Result{}, err\n    }\n\n    // Update status.Nodes if needed.\n    podNames := getPodNames(podList.Items)\n    if !reflect.DeepEqual(podNames, memcached.Status.Nodes) {\n        memcached.Status.Nodes = podNames\n        if err := r.Status().Update(ctx, memcached); err != nil {\n            return ctrl.Result{}, err\n        }\n    }\n\n    return ctrl.Request{}, nil\n}\n\n// deploymentForMemcached returns a Deployment object for data from m.\nfunc (r *MemcachedReconciler) deploymentForMemcached(m *cachev1alpha1.Memcached) *appsv1.Deployment {\n    lbls := labelsForApp(m.Name)\n    replicas := m.Spec.Size\n\n    dep := &appsv1.Deployment{\n        ObjectMeta: metav1.ObjectMeta{\n            Name:      m.Name,\n            Namespace: m.Namespace,\n        },\n        Spec: appsv1.DeploymentSpec{\n            Replicas: &replicas,\n            Selector: &metav1.LabelSelector{\n                MatchLabels: lbls,\n            },\n            Template: corev1.PodTemplateSpec{\n                ObjectMeta: metav1.ObjectMeta{\n                    Labels: lbls,\n                },\n                Spec: corev1.PodSpec{\n                    Containers: []corev1.Container{{\n                        Image:   \"memcached:alpine\",\n                        Name:    \"memcached\",\n                        Command: []string{\"memcached\", \"-a=64\", \"-b\"},\n                        Ports: []corev1.ContainerPort{{\n                            ContainerPort: 10000,\n                            Name:          \"memcached\",\n                        }},\n                    }},\n                },\n            },\n        },\n    }\n\n    // Set Memcached instance as the owner and controller.memcac\n    // NOTE: calling SetControllerReference, and setting owner references in\n    // general, is important as it allows deleted objects to be garbage collected.\n    controllerutil.SetControllerReference(m, dep, r.Scheme)\n    return dep\n}\n\n// labelsForApp creates a simple set of labels for Memcached.\nfunc labelsForApp(name string) map[string]string {\n    return map[string]string{\"cr_name\": name}\n}\n```\n\n[memcached-testdata]:https://github.com/operator-framework/operator-sdk/tree/master/testdata/go/v4/memcached-operator\n[repo-controller-runtime]:https://github.com/kubernetes-sigs/controller-runtime\n[doc-client]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#Client\n[doc-split-client]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#DelegatingClient\n[doc-client-constr]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#New\n[code-scheme-default]:https://github.com/kubernetes-sigs/controller-runtime/blob/master/pkg/client/client.go#L51\n[doc-k8s-core]:https://pkg.go.dev/k8s.io/api/core/v1\n[doc-reconcile-reconciler]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/reconcile#Reconciler\n[doc-osdk-handle]:https://github.com/operator-framework/operator-sdk/blob/master/design/milestone-0.0.2/action-api.md#handler\n[doc-types-nsname]:https://pkg.go.dev/k8s.io/apimachinery/pkg/types#NamespacedName\n[cr-status-subresource]:https://kubernetes.io/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definitions/#status-subresource\n","website/content/en/docs/building-operators/golang/references/event-filtering.md":"---\ntitle: Using Predicates for Event Filtering with Operator SDK\nlinkTitle: Using Predicates for Event Filtering\nweight: 30\n---\n\n[Events][doc_event] are produced by [Sources][doc_source] assigned to resources a controller is watching. These events are transformed into Requests by [EventHandlers][doc_eventhandler] and passed to `Reconcile()`. [Predicates][doc_predicate] allow controllers to filter events before they are provided to EventHandlers. Filtering is useful because your controller may only want to handle specific types of events. Filtering also helps reduce chattiness with the API server, as `Reconcile()` is only called for events transformed by EventHandlers.\n\n## Predicate types\n\nA Predicate implements the following methods that take an event of a particular type and return true if the event should be processed by `Reconcile()`:\n\n```Go\n// Predicate filters events before enqueuing the keys.\ntype Predicate interface {\n  Create(event.CreateEvent) bool\n  Delete(event.DeleteEvent) bool\n  Update(event.UpdateEvent) bool\n  Generic(event.GenericEvent) bool\n}\n\n// Funcs implements Predicate.\ntype Funcs struct {\n  CreateFunc func(event.CreateEvent) bool\n  DeleteFunc func(event.DeleteEvent) bool\n  UpdateFunc func(event.UpdateEvent) bool\n  GenericFunc func(event.GenericEvent) bool\n}\n```\n\nFor example, all Create events for any watched resource will be passed to `Funcs.Create()` and filtered out if the method evaluates to `false`. If you do not register a Predicate method for a particular type, events of that type will not be filtered.\n\nAll event types contain Kubernetes [metadata][doc_object_metadata] about the object that triggered the event, and the object itself. Predicate logic uses these data to make decisions about what should be filtered. Some event types include other fields pertaining to the semantics of that event. For example, `event.UpdateEvent` includes both old and new metadata and objects:\n\n```Go\ntype UpdateEvent struct {\n  // ObjectOld is the object from the event.\n  ObjectOld runtime.Object\n\n  // ObjectNew is the object from the event.\n  ObjectNew runtime.Object\n}\n```\n\nYou can find all type definitions in the `event` package [documentation][doc_event].\n\n## Using Predicates\n\nAny number of Predicates can be set for a controller via the builder method `WithEventFilter()`, which will filter an event if any of those Predicates evaluates to `false`. This first example is an implementation of a `memcached-operator` controller that simply filters Delete events on Pods that have been confirmed deleted; the controller receives all Delete events that occur, and we may only care about resources that have not been completely deleted:\n\n```Go\nimport (\n\t\"context\"\n\n\t\"github.com/go-logr/logr\"\n\tcorev1 \"k8s.io/api/core/v1\"\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\tctrl \"sigs.k8s.io/controller-runtime\"\n\t\"sigs.k8s.io/controller-runtime/pkg/client\"\n\t\"sigs.k8s.io/controller-runtime/pkg/event\"\n\t\"sigs.k8s.io/controller-runtime/pkg/predicate\"\n\n\tcachev1alpha1 \"github.com/example/app-operator/api/v1alpha1\"\n)\n\n...\n\nfunc ignoreDeletionPredicate() predicate.Predicate {\n\treturn predicate.Funcs{\n\t\tUpdateFunc: func(e event.UpdateEvent) bool {\n\t\t\t// Ignore updates to CR status in which case metadata.Generation does not change\n\t\t\treturn e.ObjectOld.GetGeneration() != e.ObjectNew.GetGeneration()\n\t\t},\n\t\tDeleteFunc: func(e event.DeleteEvent) bool {\n\t\t\t// Evaluates to false if the object has been confirmed deleted.\n\t\t\treturn !e.DeleteStateUnknown\n\t\t},\n\t}\n}\n\nfunc (r *MemcachedReconciler) SetupWithManager(mgr ctrl.Manager) error {\n\treturn ctrl.NewControllerManagedBy(mgr).\n\t\tFor(&cachev1alpha1.Memcached{}).\n\t\tOwns(&corev1.Pod{}).\n\t\tWithEventFilter(ignoreDeletionPredicate()).\n\t\tComplete(r)\n}\n  ...\n}\n```\n\n## Use cases\n\nPredicates are not necessary for many operators, although filtering reduces the amount of chatter to the API server from `Reconcile()`. They are particularly useful for controllers that watch resources cluster-wide, i.e. without a namespace.\n\n[doc_event]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/event\n[doc_source]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/source#Source\n[doc_eventhandler]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/handler#EventHandler\n[doc_predicate]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/predicate\n[doc_object_metadata]:https://pkg.go.dev/k8s.io/apimachinery/pkg/apis/meta/v1#Object\n","website/content/en/docs/building-operators/golang/references/logging.md":"---\ntitle: Logging\nlinkTitle: Logging\nweight: 20\n---\n\n# Overview\n\nOperator SDK-generated operators use the [`logr`][godoc_logr] interface to log. This log interface has several backends such as [`zap`][repo_zapr], which the SDK uses in generated code by default. [`logr.Logger`][godoc_logr_logger] exposes structured logging methods that help create machine-readable logs and adding a wealth of information to log records.\n\n## Default zap logger\n\nOperator SDK uses a `zap`-based `logr` backend when scaffolding new projects. To assist with configuring and using this logger, the SDK includes several helper functions.\n\nIn the simple example below, we add the zap flagset to the operator's command line flags with `BindFlags()`, and then set the controller-runtime logger with `zap.Options{}`.\n\nBy default, `zap.Options{}` will return a logger that is ready for production use. It uses a JSON encoder, logs starting at the `info` level. To customize the default behavior, users can use the zap flagset and specify flags on the command line. The zap flagset includes the following flags that can be used to configure the logger:\n\n* `--zap-devel`: Development Mode defaults(encoder=consoleEncoder,logLevel=Debug,stackTraceLevel=Warn)\n\t\t\t  Production Mode defaults(encoder=jsonEncoder,logLevel=Info,stackTraceLevel=Error)\n* `--zap-encoder`: Zap log encoding ('json' or 'console')\n* `--zap-log-level`: Zap Level to configure the verbosity of logging. Can be one of 'debug', 'info', 'error',\n\t\t\t       or any integer value > 0 which corresponds to custom debug levels of increasing verbosity\")\n* `--zap-stacktrace-level`: Zap Level at and above which stacktraces are captured (one of 'info' or 'error')\n\nConsult the controller-runtime [godocs][logging_godocs] for more detailed flag information.\n\n### A simple example\n\nOperators set the logger for all operator logging in `main.go`. To illustrate how this works, try out this simple example:\n\n```Go\npackage main\n\nimport (\n\t\"sigs.k8s.io/controller-runtime/pkg/log/zap\"\n\tlogf \"sigs.k8s.io/controller-runtime/pkg/log\"\n)\n\nvar globalLog = logf.Log.WithName(\"global\")\nfunc main() {\n\t// Add the zap logger flag set to the CLI. The flag set must\n\t// be added before calling flag.Parse().\n\topts := zap.Options{}\n\topts.BindFlags(flag.CommandLine)\n\tflag.Parse()\n\n\tlogger := zap.New(zap.UseFlagOptions(&opts))\n\tlogf.SetLogger(logger)\n\n\tscopedLog := logf.Log.WithName(\"scoped\")\n\n\tglobalLog.Info(\"Printing at INFO level\")\n\tglobalLog.V(1).Info(\"Printing at DEBUG level\")\n\tscopedLog.Info(\"Printing at INFO level\")\n\tscopedLog.V(1).Info(\"Printing at DEBUG level\")\n}\n```\n\n#### Output using the defaults\n```console\n$ go run main.go\nINFO[0000] Running the operator locally in namespace default.\n{\"level\":\"info\",\"ts\":1587741740.407766,\"logger\":\"global\",\"msg\":\"Printing at INFO level\"}\n{\"level\":\"info\",\"ts\":1587741740.407855,\"logger\":\"scoped\",\"msg\":\"Printing at INFO level\"}\n```\n\n#### Output overriding the log level to 1 (debug)\n```console\n$ go run main.go --zap-log-level=debug\nINFO[0000] Running the operator locally in namespace default.\n{\"level\":\"info\",\"ts\":1587741837.602911,\"logger\":\"global\",\"msg\":\"Printing at INFO level\"}\n{\"level\":\"debug\",\"ts\":1587741837.602964,\"logger\":\"global\",\"msg\":\"Printing at DEBUG level\"}\n{\"level\":\"info\",\"ts\":1587741837.6029708,\"logger\":\"scoped\",\"msg\":\"Printing at INFO level\"}\n{\"level\":\"debug\",\"ts\":1587741837.602973,\"logger\":\"scoped\",\"msg\":\"Printing at DEBUG level\"}\n```\n## Custom zap logger\n\nIn order to use a custom zap logger, [`zap`][controller_runtime_zap] from controller-runtime can be utilized to wrap it in a `logr` implementation.\n\nBelow is an example illustrating the use of [`zap-logfmt`][logfmt_repo] in logging.\n\n### Example\n\nIn your `main.go` file, replace the current implementation for logs inside the `main` function:\n\n```Go\n...\n// Add the zap logger flag set to the CLI. The flag set must\n// be added before calling flag.Parse().\n\topts := zap.Options{}\n\topts.BindFlags(flag.CommandLine)\n\tflag.Parse()\n\n\tlogger := zap.New(zap.UseFlagOptions(&opts))\n\tlogf.SetLogger(logger)\n...\n```\n\nWith:\n\n```Go\n\timport(\n\t...\n\tzaplogfmt \"github.com/sykesm/zap-logfmt\"\n\tuzap \"go.uber.org/zap\"\n\t\"go.uber.org/zap/zapcore\"\n\tlogf \"sigs.k8s.io/controller-runtime/pkg/log\"\n\t\"sigs.k8s.io/controller-runtime/pkg/log/zap\"\n\t...\n)\n\tconfigLog := uzap.NewProductionEncoderConfig()\n\tconfigLog.EncodeTime = func(ts time.Time, encoder zapcore.PrimitiveArrayEncoder) {\n\t\tencoder.AppendString(ts.UTC().Format(time.RFC3339Nano))\n\t}\n\tlogfmtEncoder := zaplogfmt.NewEncoder(configLog)\n\n\t// Construct a new logr.logger.\n\tlogger := zap.New(zap.UseDevMode(true), zap.WriteTo(os.Stdout), zap.Encoder(logfmtEncoder))\n\tlogf.SetLogger(logger)\n```\n\n**NOTE**: For this example, you will need to add the module `\"github.com/sykesm/zap-logfmt\"` to your project. Run `go get -u github.com/sykesm/zap-logfmt`.\n\n#### Output using custom zap logger\n\n```console\n$ go run main.go\nts=2020-04-30T20:35:59.551268Z level=info logger=global msg=\"Printing at INFO level\"\nts=2020-04-30T20:35:59.551314Z level=debug logger=global msg=\"Printing at DEBUG level\"\nts=2020-04-30T20:35:59.551318Z level=info logger=scoped msg=\"Printing at INFO level\"\nts=2020-04-30T20:35:59.55132Z level=debug logger=scoped msg=\"Printing at DEBUG level\"\n```\n\nBy using `sigs.k8s.io/controller-runtime/pkg/log`, your logger is propagated through `controller-runtime`. Any logs produced by `controller-runtime` code will be through your logger, and therefore have the same formatting and destination.\n\n### Setting flags when running locally\n\nWhen running locally with `make run ENABLE_WEBHOOKS=false`, you can use the `ARGS` var to pass additional flags to your operator, including the zap flags. For example:\n\n```console\n$ make run ARGS=\"--zap-encoder=console\" ENABLE_WEBHOOKS=false\n```\nMake sure to have your `run` target to take `ARGS` as shown below in `Makefile`.\n\n```makefile\n# Run against the configured Kubernetes cluster in ~/.kube/config\nrun: manifests generate fmt vet\n\tgo run ./main.go $(ARGS)\n```\n\n### Setting flags when deploying to a cluster\n\nWhen deploying your operator to a cluster you can set additional flags using an `args` array in your operator's `container` spec in the file `config/default/manager_metrics_patch.yaml` For example:\n\n```yaml\n- op: add\n  path: /spec/template/spec/containers/0/args/0\n  value: --zap-log-level=debug \n- op: add\n  path: /spec/template/spec/containers/0/args/0\n  value: --zap-encoder=console\n```\n\n## Creating a structured log statement\n\nThere are two ways to create structured logs with `logr`. You can create new loggers using `log.WithValues(keyValues)` that include `keyValues`, a list of key-value pair `interface{}`'s, in each log record. Alternatively you can include `keyValues` directly in a log statement, as all `logr` log statements take some message and `keyValues`. The signature of `logr.Error()` has an `error`-type parameter, which can be `nil`.\n\nAn example from [`memcached_controller.go`][code_memcached_controller]:\n\n```Go\npackage memcached\n\nimport (\n  ctrllog \"sigs.k8s.io/controller-runtime/pkg/log\"\n)\n\n\n// MemcachedReconciler reconciles a Memcached object\ntype MemcachedReconciler struct {\n\tclient.Client\n\tLog    logr.Logger\n\tScheme *runtime.Scheme\n}\n\nfunc (r *MemcachedReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {\n\tlog := ctrllog.FromContext(ctx)\n\n\t// Fetch the Memcached instance\n\tmemcached := &cachev1alpha1.Memcached{}\n\terr := r.Get(ctx, req.NamespacedName, memcached)\n\tif err != nil {\n\t\tif errors.IsNotFound(err) {\n\t\t\t// Request object not found, could have been deleted after reconcile request.\n\t\t\t// Owned objects are automatically garbage collected. For additional cleanup logic use finalizers.\n\t\t\t// Return and don't requeue\n\t\t\tlog.Info(\"Memcached resource not found. Ignoring since object must be deleted\")\n\t\t\treturn ctrl.Result{}, nil\n\t\t}\n\t\t// Error reading the object - requeue the request.\n\t\tlog.Error(err, \"Failed to get Memcached\")\n\t\treturn ctrl.Result{}, err\n\t}\n\n\t// Check if the deployment already exists, if not create a new one\n\tfound := &appsv1.Deployment{}\n\terr = r.Get(ctx, types.NamespacedName{Name: memcached.Name, Namespace: memcached.Namespace}, found)\n\tif err != nil && errors.IsNotFound(err) {\n\t\t// Define a new deployment\n\t\tdep := r.deploymentForMemcached(memcached)\n\t\tlog.Info(\"Creating a new Deployment\", \"Deployment.Namespace\", dep.Namespace, \"Deployment.Name\", dep.Name)\n\t\terr = r.Create(ctx, dep)\n\t\tif err != nil {\n\t\t\tlog.Error(err, \"Failed to create new Deployment\", \"Deployment.Namespace\", dep.Namespace, \"Deployment.Name\", dep.Name)\n\t\t\treturn ctrl.Result{}, err\n\t\t}\n\t\t// Deployment created successfully - return and requeue\n\t\treturn ctrl.Result{Requeue: true}, nil\n\t} else if err != nil {\n\t\tlog.Error(err, \"Failed to get Deployment\")\n\t\treturn ctrl.Result{}, err\n\t}\n\n\t...\n}\n```\n\nLog records will look like the following (from `log.Error()` above):\n\n```\n2020-04-27T09:14:15.939-0400\tERROR\tcontrollers.Memcached\tFailed to create new Deployment\t{\"memcached\": \"default/memcached-sample\", \"Deployment.Namespace\": \"default\", \"Deployment.Name\": \"memcached-sample\"}\n```\n\n## Non-default logging\n\nIf you do not want to use `logr` as your logging tool, you can remove `logr`-specific statements without issue from your operator's code, including the `logr` setup code in `main.go`, and add your own. Note that removing `logr` setup code will prevent `controller-runtime` from logging.\n\n\n[godoc_logr]:https://pkg.go.dev/github.com/go-logr/logr\n[repo_zapr]:https://pkg.go.dev/github.com/go-logr/zapr\n[godoc_logr_logger]:https://pkg.go.dev/github.com/go-logr/logr#Logger\n[code_memcached_controller]: https://github.com/operator-framework/operator-sdk/blob/v1.2.0/testdata/go/memcached-operator/controllers/memcached_controller.go\n[logfmt_repo]:https://github.com/jsternberg/zap-logfmt\n[controller_runtime_zap]:https://github.com/kubernetes-sigs/controller-runtime/tree/master/pkg/log/zap\n[logging_godocs]: https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/log/zap#Options.BindFlags\n","website/content/en/docs/building-operators/golang/references/markers.md":"---\ntitle: API Markers\nlinkTitle: API Markers\nweight: 40\n---\n\nThis document describes [code markers][markers] supported by the SDK.\n\n## ClusterServiceVersion markers\n\nThis section details ClusterServiceVersion (CSV) code markers and lists available markers.\n\n**Note:** CSV markers can only be used in Go Operator projects. Annotations for Ansible and Helm Operator projects will be added in the future.\n\n### Usage\n\nAll CSV markers have the prefix `+operator-sdk:csv`.\n\n#### `+operator-sdk:csv:customresourcedefinitions`\n\nThese markers populate [owned `customresourcedefinitions`][csv-crds] in your CSV.\n\nPossible type-level markers:\n- `+operator-sdk:csv:customresourcedefinitions:displayName=\"some display name\"`\n\t- Configures the kind's display name.\n- `+operator-sdk:csv:customresourcedefinitions:resources={{Kind1,v1alpha1,dns-name-1},{Kind2,v1,\"dns-name-2\"},...}`\n\t- Configures the kind's resources.\n- `+operator-sdk:csv:customresourcedefinitions:order=1`\n\t- Configures the order of this type in the list. Markers with order omitted have the highest order, i.e. are at the end of the list. If more than one marker has the same order, the corresponding descriptions will be sorted alphabetically and placed above others with higher orders. Pre-existing list elements in the CSV will be appended to the set of other elements in the order corresponding to its index.\n\nPossible field-level markers, all of which must contain the `type=[spec,status]` key-value pair:\n- `+operator-sdk:csv:customresourcedefinitions:type=[spec,status],displayName=\"some field display name\"`\n\t- Configures the field's display name.\n- `+operator-sdk:csv:customresourcedefinitions:type=[spec,status],xDescriptors={\"urn:alm:descriptor:com.tectonic.ui:podCount\",\"urn:alm:descriptor:io.kubernetes:custom\"}`\n\t- Configures the field's x-descriptors.\n- `+operator-sdk:csv:customresourcedefinitions:type=[spec,status],order=1`\n\t- Configures the order of this type in the list. Markers with order omitted have the highest order, i.e. are at the end of the list. If more than one marker has the same order, the corresponding descriptions will be sorted alphabetically and placed above others with higher orders.\n\nTop-level `kind`, `name`, and `version` fields are parsed from API code.\nAll `description` fields are parsed from type declaration and `struct` type field comments.\nAll `path` fields are parsed from a field's JSON tag and merged with parent\nfield path's in dot-hierarchy notation.\n\n##### x-descriptors\n\nCheck out the [descriptor reference][csv-x-desc] for available `x-descriptors` paths.\n\n#### Examples\n\nThese examples assume `Memcached`, `MemcachedSpec`, and `MemcachedStatus` are the example projects' kind, spec, and status.\n\n1. Set a `displayName` and `resources` for a `customresourcedefinitions` kind entry:\n\n\t```go\n\t//+operator-sdk:csv:customresourcedefinitions:displayName=\"Memcached App\",resources={{Pod,v1,memcached-runner},{Deployment,v1,memcached-deployment}}\n\ttype Memcached struct {\n\t\tmetav1.TypeMeta   `json:\",inline\"`\n\t\tmetav1.ObjectMeta `json:\"metadata,omitempty\"`\n\n\t\tSpec   MemcachedSpec   `json:\"spec,omitempty\"`\n\t\tStatus MemcachedStatus `json:\"status,omitempty\"`\n\t}\n\t```\n\n2. Set `displayName`, `path`, `xDescriptors`, and `description` on a field for a `customresourcedefinitions.specDescriptors` entry:\n\n\t```go\n\ttype MemcachedSpec struct {\n\t\t// Size is the size of the memcached deployment. <-- This will become Size's specDescriptors.description.\n\t\t//+operator-sdk:csv:customresourcedefinitions:type=spec,displayName=\"Number of pods\",xDescriptors={\"urn:alm:descriptor:com.tectonic.ui:podCount\",\"urn:alm:descriptor:io.kubernetes:custom\"}\n\t\tSize int32 `json:\"size\"` // <-- Size's specDescriptors.path is inferred from this JSON tag.\n\t}\n\t```\n\n3. Let the SDK infer all unmarked paths on a field for a `customresourcedefinitions.specDescriptors` entry:\n\n\t```go\n\ttype MemcachedSpec struct {\n\t\t// Size is the size of the memcached deployment.\n\t\t//+operator-sdk:csv:customresourcedefinitions:type=spec\n\t\tSize int32 `json:\"size\"`\n\t}\n\t```\n\n\tThe SDK uses the `Size` fields' `json` tag name as `path`, `Size` as `displayName`, and field comments as `description`.\n\n4. A comprehensive example:\n\t- Infer `path`, `description`, `displayName`, and `x-descriptors` for `specDescriptors` and `statusDescriptors` entries.\n\t- Create three `resources` entries each with `kind`, `version`, and `name` values.\n\n\t```go\n\t// Represents a cluster of Memcached apps\n\t//+operator-sdk:csv:customresourcedefinitions:displayName=\"Memcached App\",resources={{Pod,v1,memcached-runner},{Deployment,v1,memcached-deployment}}\n\ttype Memcached struct {\n\t\tmetav1.TypeMeta   `json:\",inline\"`\n\t\tmetav1.ObjectMeta `json:\"metadata,omitempty\"`\n\n\t\tSpec   MemcachedSpec   `json:\"spec,omitempty\"`\n\t\tStatus MemcachedStatus `json:\"status,omitempty\"`\n\t}\n\n\ttype MemcachedSpec struct {\n\t\tPods MemcachedPods `json:\"pods\"`\n\t}\n\n\ttype MemcachedStatus struct {\n\t\tPods \t\t MemcachedPods `json:\"podStatuses\"`\n\t\t//+operator-sdk:csv:customresourcedefinitions:type=status,displayName=\"Pod Count\",xDescriptors=\"urn:alm:descriptor:com.tectonic.ui:podCount\"\n\t\tPodCount int \t\t\t\t\t `json:\"podCount\"`\n\t}\n\n\ttype MemcachedPods struct {\n\t\t// Size is the size of the memcached deployment.\n\t\t//+operator-sdk:csv:customresourcedefinitions:type=spec\n\t\t//+operator-sdk:csv:customresourcedefinitions:type=status\n\t\tSize int32 `json:\"size\"`\n\t}\n\t```\n\n\tThe generated `customresourcedefinitions` will look like:\n\n\t```yaml\n\tcustomresourcedefinitions:\n\t  owned:\n\t  - description: Represents a cluster of Memcached apps\n\t    displayName: Memcached App\n\t    kind: Memcached\n\t    name: memcacheds.cache.example.com\n\t    version: v1alpha1\n\t    resources:\n\t    - kind: Deployment\n\t      name: memcached-deployment\n\t      version: v1\n\t    - kind: Pod\n\t      name: memcached-runner\n\t      version: v1\n\t    specDescriptors:\n\t    - description: The desired number of member Pods for the deployment.\n\t      displayName: Size\n\t      path: pods.size\n\t    statusDescriptors:\n\t    - description: The desired number of member Pods for the deployment.\n\t      displayName: Size\n\t      path: podStatuses.size\n\t    - displayName: Size\n\t      path: podCount\n\t      x-descriptors:\n\t      - 'urn:alm:descriptor:com.tectonic.ui:podCount'\n\t```\n\n\n## Deprecated markers\n\nMarkers supported by `operator-sdk` prior to v1.0.0 are deprecated.\nYou can migrate to the new marker system by running the following script:\n\n```console\n$ curl -sSLo migrate-markers.sh https://raw.githubusercontent.com/operator-framework/operator-sdk/master/hack/generate/migrate-markers.sh\n$ chmod +x ./migrate-markers.sh\n$ ./migrate-markers.sh path/to/*_types.go\n```\n\n\n[markers]:https://pkg.go.dev/sigs.k8s.io/controller-tools/pkg/markers\n[cli-gen-kustomize-manifests]:/docs/cli/operator-sdk_generate_kustomize_manifests\n[csv-x-desc]:https://github.com/openshift/console/blob/master/frontend/packages/operator-lifecycle-manager/src/components/descriptors/reference/reference.md\n[csv-spec]:https://github.com/operator-framework/operator-lifecycle-manager/blob/e0eea22/doc/design/building-your-csv.md\n[csv-crds]:https://github.com/operator-framework/operator-lifecycle-manager/blob/master/doc/design/building-your-csv.md#your-custom-resource-definitions\n","website/content/en/docs/building-operators/golang/references/openapi-validation.md":"---\ntitle: OpenAPI validation\nlinkTitle: OpenAPI validation\nweight: 70\n---\n\nOpenAPIv3 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.\n\n[Markers][markers] (annotations) are available to configure validations for your API. These markers will always have a `+kubebuilder:validation` prefix.\n\nUsage of markers in API code is discussed in the kubebuilder [CRD generation][generating-crd] and [marker][markers] documentation. A full list of OpenAPIv3 validation markers can be found [here][crd-markers].\n\nTo learn more about OpenAPI v3.0 validation schemas in CRDs, refer to the [Kubernetes Documentation][doc-validation-schema].\n\n[markers]: https://book.kubebuilder.io/reference/markers.html\n[crd-markers]: https://book.kubebuilder.io/reference/markers/crd-validation.html\n[generating-crd]: https://book.kubebuilder.io/reference/generating-crd.html\n[doc-validation-schema]: https://kubernetes.io/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definitions/#specifying-a-structural-schema\n","website/content/en/docs/building-operators/golang/references/proxy-vars.md":"---\ntitle: Proxy Friendly Operators\nlinkTitle: Proxy Vars\nweight: 20\n---\n\nProxy-friendly Operators should inspect their environment for the\nstandard proxy variables (`HTTPS_PROXY`, `HTTP_PROXY`, and `NO_PROXY`)\nand pass the values to Operands.\n\nOperator-lib provides a helper function `proxy.ReadProxyVarsFromEnv`\nthat does this inspection, all you need to do is append the\nresults to the Operand environments.\n\nUsing the memcached tutorial as an example, add the following to the\nReconcile loop in `controllers/memcached_controller.go`:\n\n\n```go\nimport (\n  ...\n   \"github.com/operator-framework/operator-lib/proxy\"\n)\n\n\nfor i, container := range dep.Spec.Template.Spec.Containers {\n\t\tdep.Spec.Template.Spec.Containers[i].Env = append(container.Env, proxy.ReadProxyVarsFromEnv()...)\n}\n```\n\nYou can set the environment variable on the Operator deployment. Using the memcached tutorial, edit config/manager/manager.yaml:\n\n```yaml\ncontainers:\n - args:\n   - --leader-elect\n   - --leader-election-id=go-proxy-demo\n   image: controller:latest\n   name: manager\n   env:\n     - name: \"HTTP_PROXY\"\n       value: \"http_proxy_test\"\n```\n"},"files":{"website/content/en/docs/building-operators/golang/references/_index.md":"---\ntitle: Go-based Operator Reference\nlinkTitle: Reference\nweight: 100\n---","website/content/en/docs/building-operators/golang/references/client.md":"---\ntitle: Controller Runtime Client API\nlinkTitle: Controller Runtime Client API\nweight: 10\n---\n\n## Overview\n\nThe [`controller-runtime`][repo-controller-runtime] library provides various abstractions to watch and reconcile resources in a Kubernetes cluster via CRUD (Create, Update, Delete, as well as Get and List in this case) operations. Operators use at least one controller to perform a coherent set of tasks within a cluster, usually through a combination of CRUD operations. The Operator SDK uses controller-runtime's [Client][doc-client] interface, which provides the interface for these operations.\n\ncontroller-runtime defines several interfaces used for cluster interaction:\n- `client.Client`: implementers perform CRUD operations on a Kubernetes cluster.\n- `manager.Manager`: manages shared dependencies, such as Caches and Clients.\n- `reconcile.Reconciler`: compares provided state with actual cluster state and updates the cluster on finding state differences using a Client.\n\nClients are the focus of this document. A separate document will discuss Managers.\n\n**Note:** this document uses parts of the sample [`memcached-operator`][memcached-testdata] for example code.\nImport paths may be different for brevity.\n\n## Client Usage\n\n### Default Client\n\nThe SDK relies on a `manager.Manager` to create a `client.Client` interface that performs Create, Update, Delete, Get, and List operations within a `reconcile.Reconciler`'s Reconcile function. The SDK will generate code to create a Manager, which holds a Cache and a Client to be used in CRUD operations and communicate with the API server. By default a Controller's Reconciler will be populated with the Manager's Client which is a [split-client][doc-split-client].\n\nThe following code, found in `controllers/memcached_controller.go`, demonstrates how the Manager's client is passed to a reconciler.\n\n```Go\nimport (\n\tappsv1 \"k8s.io/api/apps/v1\"\n\tctrl \"sigs.k8s.io/controller-runtime\"\n\n\tcachev1alpha1 \"github.com/example/memcached-operator/api/v1alpha1\"\n)\n\nfunc (r *MemcachedReconciler) SetupWithManager(mgr ctrl.Manager) error {\n\treturn ctrl.NewControllerManagedBy(mgr). // mgr's Client is passed to r.\n\t\tFor(&cachev1alpha1.Memcached{}).\n\t\tOwns(&appsv1.Deployment{}).\n\t\tComplete(r)\n}\n\ntype MemcachedReconciler struct {\n    client.Client // Populated above from a manager.Manager.\n\n    Log    logr.Logger\n    Scheme *runtime.Scheme\n}\n```\n\nA split client reads (Get and List) from the Cache and writes (Create, Update, Delete) to the API server. Reading from the Cache significantly reduces request load on the API server; as long as the Cache is updated by the API server, read operations are eventually consistent.\n\n### Non-default Client\n\nAn operator developer may wish to create their own Client that serves read requests(Get List) from the API server instead of the cache, for example. controller-runtime provides a [constructor][doc-client-constr] for Clients:\n\n```Go\n// New returns a new Client using the provided config and Options.\nfunc New(config *rest.Config, options client.Options) (client.Client, error)\n```\n\n`client.Options` allow the caller to specify how the new Client should communicate with the API server.\n\n```Go\n// Options are creation options for a Client\ntype Options struct {\n    // Scheme, if provided, will be used to map go structs to GroupVersionKinds\n    Scheme *runtime.Scheme\n\n    // Mapper, if provided, will be used to map GroupVersionKinds to Resources\n    Mapper meta.RESTMapper\n}\n```\n\nExample:\n\n```Go\nimport (\n    \"sigs.k8s.io/controller-runtime/pkg/client/config\"\n    \"sigs.k8s.io/controller-runtime/pkg/client\"\n)\n\ncfg, err := config.GetConfig()\n...\nc, err := client.New(cfg, client.Options{})\n...\n```\n\n**Note**: defaults are set by `client.New` when Options are empty. The default [scheme][code-scheme-default] will have the [core][doc-k8s-core] Kubernetes resource types registered. The caller *must* set a scheme that has custom operator types registered for the new Client to recognize these types.\n\nCreating a new Client is not usually necessary nor advised, as the default Client is sufficient for most use cases.\n\n### Reconcile and the Client API\n\nA Reconciler implements the [`reconcile.Reconciler`][doc-reconcile-reconciler] interface, which exposes the Reconcile method. Reconcilers are added to a corresponding Controller for a Kind; Reconcile is called in response to cluster or external Events, with a `reconcile.Request` object argument, to read and write cluster state by the Controller, and returns a `ctrl.Result`. SDK Reconcilers have access to a Client in order to make Kubernetes API calls.\n\n```Go\n// MemcachedReconciler reconciles a Memcached object\ntype MemcachedReconciler struct {\n    // client, initialized using mgr.Client() above, is a split client\n    // that reads objects from the cache and writes to the apiserver\n    client.Client\n\n    Log    logr.Logger\n\n    // scheme defines methods for serializing and deserializing API objects,\n    // a type registry for converting group, version, and kind information\n    // to and from Go schemas, and mappings between Go schemas of different\n    // versions. A scheme is the foundation for a versioned API and versioned\n    // configuration over time.\n    Scheme *runtime.Scheme\n}\n\n// Reconcile watches for Events and reconciles cluster state with desired\n// state defined in the method body.\n// The Controller will requeue the Request to be processed again if an error\n// is non-nil or Result.Requeue is true, otherwise upon completion it will\n// remove the work from the queue.\nfunc (r *MemcachedReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error)\n```\n\nReconcile is where Controller business logic lives, i.e. where Client API calls are made via `MemcachedReconciler.client`. A `client.Client` implementer performs the following operations:\n\n#### Get\n\n```Go\n// Get retrieves an API object for a given object key from the Kubernetes cluster\n// and stores it in obj.\nfunc (c Client) Get(ctx context.Context, key client.ObjectKey, obj client.Object) error\n```\n\n**Note**: A `client.ObjectKey` is simply an alias for [`types.NamespacedName`][doc-types-nsname].\n\nExample:\n\n```Go\nimport (\n    \"context\"\n\n    ctrl \"sigs.k8s.io/controller-runtime\"\n\n    cachev1alpha1 \"github.com/example/memcached-operator/api/v1alpha1\"\n)\n\nfunc (r *MemcachedReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {\n    ...\n\n    memcached := &cachev1alpha1.Memcached{}\n    err := r.Get(ctx, request.NamespacedName, memcached)\n\n    ...\n}\n```\n\n#### List\n\n```Go\n// List retrieves a list of objects for a given namespace and list options\n// and stores the list in obj.\nfunc (c Client) List(ctx context.Context, list client.Object, opts ...client.ListOption) error\n```\n\nA `client.ListOption` is an interface that sets [`client.ListOptions`][list-options] fields. A `client.ListOption` is created by using one of the provided implementations: [`MatchingLabels`][matching-labels], [`MatchingFields`][matching-fields], [`InNamespace`][in-namespace].\n\nExample:\n\n```Go\nimport (\n    \"context\"\n    \"fmt\"\n\n    \"k8s.io/api/core/v1\"\n    ctrl \"sigs.k8s.io/controller-runtime\"\n    \"sigs.k8s.io/controller-runtime/pkg/client\"\n)\n\nfunc (r *MemcachedReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {\n    ...\n\n    // Return all pods in the request namespace with a label of `instance=<name>`\n    // and phase `Running`.\n    podList := &v1.PodList{}\n    opts := []client.ListOption{\n        client.InNamespace(request.NamespacedName.Namespace),\n        client.MatchingLabels{\"instance\": request.NamespacedName.Name},\n        client.MatchingFields{\"status.phase\": \"Running\"},\n    }\n    err := r.List(ctx, podList, opts...)\n\n    ...\n}\n```\n\n[list-options]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#ListOptions\n[matching-labels]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#MatchingLabels\n[matching-fields]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#MatchingFields\n[in-namespace]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#InNamespace\n\n#### Create\n\n```Go\n// Create saves the object obj in the Kubernetes cluster.\n// Returns an error\nfunc (c Client) Create(ctx context.Context, obj client.Object, opts ...client.CreateOption) error\n```\n\nA `client.CreateOption` is an interface that sets [`client.CreateOptions`][create-options] fields. A `client.CreateOption` is created by using one of the provided implementations: [`DryRunAll`][dry-run-all], [`ForceOwnership`][force-ownership]. Generally these options are not needed.\n\nExample:\n\n```Go\nimport (\n    \"context\"\n\n    \"k8s.io/api/apps/v1\"\n    ctrl \"sigs.k8s.io/controller-runtime\"\n)\n\nfunc (r *MemcachedReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {\n    ...\n\n    dep := &v1.Deployment{ // Any cluster object you want to create.\n        ...\n    }\n    err := r.Create(ctx, dep)\n\n    ...\n}\n```\n\n[create-options]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#CreateOptions\n\n#### Update\n\n```Go\n// Update updates the given obj in the Kubernetes cluster. obj must be a\n// struct pointer so that obj can be updated with the content returned\n// by the API server. Update does *not* update the resource's status\n// subresource\nfunc (c Client) Update(ctx context.Context, obj client.Object, opts ...client.UpdateOption) error\n```\n\nA `client.UpdateOption` is an interface that sets [`client.UpdateOptions`][update-options] fields. A `client.UpdateOption` is created by using one of the provided implementations: [`DryRunAll`][dry-run-all], [`ForceOwnership`][force-ownership]. Generally these options are not needed.\n\nExample:\n\n```Go\nimport (\n    \"context\"\n\n    \"k8s.io/api/apps/v1\"\n    ctrl \"sigs.k8s.io/controller-runtime\"\n)\n\nfunc (r *MemcachedReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {\n    ...\n\n    dep := &v1.Deployment{}\n    err := r.Get(ctx, request.NamespacedName, dep)\n\n    ...\n\n    dep.Spec.Selector.MatchLabels[\"is_running\"] = \"true\"\n    err := r.Update(ctx, dep)\n\n    ...\n}\n```\n\n[update-options]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#UpdateOptions\n\n#### Patch\n\n```Go\n// Patch patches the given obj in the Kubernetes cluster. obj must be a\n// struct pointer so that obj can be updated with the content returned by the Server.\nfunc (c Client) Patch(ctx context.Context, obj client.Object, patch client.Patch, opts ...client.PatchOption) error\n```\n\nA `client.PatchOption` is an interface that sets [`client.PatchOptions`][patch-options] fields. A `client.PatchOption` is created by using one of the provided implementations: [`DryRunAll`][dry-run-all], [`ForceOwnership`][force-ownership]. Generally these options are not needed.\n\nExample:\n\n```Go\nimport (\n    \"context\"\n\n    \"k8s.io/api/apps/v1\"\n    ctrl \"sigs.k8s.io/controller-runtime\"\n    \"sigs.k8s.io/controller-runtime/pkg/client\"\n)\n\nfunc (r *MemcachedReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {\n    ...\n\n    dep := &v1.Deployment{}\n    err := r.Get(ctx, request.NamespacedName, dep)\n\n    ...\n\n    // A merge patch will preserve other fields modified at runtime.\n    patch := client.MergeFrom(dep.DeepCopy())\n    dep.Spec.Selector.MatchLabels[\"is_running\"] = \"true\"\n    err := r.Patch(ctx, dep, patch)\n\n    ...\n}\n```\n\n[patch-options]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#PatchOption\n[dry-run-all]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#DryRunAll\n[force-ownership]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#ForceOwnership\n\n##### Updating Status Subresource\n\nWhen updating the [status subresource][cr-status-subresource] from the client, the [`StatusWriter`][status-writer] must be used. The status subresource is retrieved with `Status()` and updated with `Update()` or patched with `Patch()`.\n\n`Update()` takes variadic `client.UpdateOption`'s, and `Patch()` takes variadic `client.PatchOption`'s. See [`Client.Update()`](#update) and [`Client.Patch()`](#patch) for more details. Generally these options are not needed.\n\n##### Status\n\n```Go\n// Status() returns a StatusWriter object that can be used to update the\n// object's status subresource\nfunc (c Client) Status() (client.StatusWriter, error)\n```\n\nExample:\n```Go\nimport (\n    \"context\"\n\n    ctrl \"sigs.k8s.io/controller-runtime\"\n\n    cachev1alpha1 \"github.com/example/memcached-operator/api/v1alpha1\"\n)\n\nfunc (r *MemcachedReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {\n    ...\n\n    mem := &cachev1alpha1.Memcached{}\n    err := r.Get(ctx, request.NamespacedName, mem)\n\n    ...\n\n    // Update\n    mem.Status.Nodes = []string{\"pod1\", \"pod2\"}\n    err := r.Status().Update(ctx, mem)\n\n    ...\n\n    // Patch\n    patch := client.MergeFrom(mem.DeepCopy())\n    mem.Status.Nodes = []string{\"pod1\", \"pod2\", \"pod3\"}\n    err := r.Status().Patch(ctx, mem, patch)\n\n    ...\n}\n```\n\n[status-writer]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#StatusWriter\n\n#### Delete\n\n```Go\n// Delete deletes the given obj from Kubernetes cluster.\nfunc (c Client) Delete(ctx context.Context, obj client.Object, opts ...client.DeleteOption) error\n```\n\nA `client.DeleteOption` is an interface that sets [`client.DeleteOptions`][delete-opts] fields. A `client.DeleteOption` is created by using one of the provided implementations: [`GracePeriodSeconds`][grace-period-seconds], [`Preconditions`][preconditions], [`PropagationPolicy`][propagation-policy].\n\nExample:\n\n```Go\nimport (\n    \"context\"\n\n    \"k8s.io/api/core/v1\"\n    ctrl \"sigs.k8s.io/controller-runtime\"\n    \"sigs.k8s.io/controller-runtime/pkg/client\"\n)\n\nfunc (r *MemcachedReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {\n    ...\n\n    pod := &v1.Pod{}\n    err := r.Get(ctx, request.NamespacedName, pod)\n\n    ...\n\n    if pod.Status.Phase == v1.PodUnknown {\n        // Delete the pod after 5 seconds.\n        err := r.Delete(ctx, pod, client.GracePeriodSeconds(5))\n        ...\n    }\n\n    ...\n}\n```\n\n[delete-opts]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#DeleteOptions\n[grace-period-seconds]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#GracePeriodSeconds\n[preconditions]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#Preconditions\n[propagation-policy]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#PropagationPolicy\n\n#### DeleteAllOf\n\n```Go\n// DeleteAllOf deletes all objects of the given type matching the given options.\nfunc (c Client) DeleteAllOf(ctx context.Context, obj client.Object, opts ...client.DeleteAllOfOption) error\n```\n\nA `client.DeleteAllOfOption` is an interface that sets [`client.DeleteAllOfOptions`][deleteallof-opts] fields. A `client.DeleteAllOfOption` wraps a [`client.ListOption`](#list) and [`client.DeleteOption`](#delete).\n\nExample:\n\n```Go\nimport (\n    \"context\"\n    \"fmt\"\n\n    \"k8s.io/api/core/v1\"\n    ctrl \"sigs.k8s.io/controller-runtime\"\n    \"sigs.k8s.io/controller-runtime/pkg/client\"\n)\n\nfunc (r *MemcachedReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {\n    ...\n\n    // Delete all pods in the request namespace with a label of `instance=<name>`\n    // and phase `Failed`.\n    pod := &v1.Pod{}\n    opts := []client.DeleteAllOfOption{\n        client.InNamespace(request.NamespacedName.Namespace),\n        client.MatchingLabels{\"instance\", request.NamespacedName.Name},\n        client.MatchingFields{\"status.phase\": \"Failed\"},\n        client.GracePeriodSeconds(5),\n    }\n    err := r.DeleteAllOf(ctx, pod, opts...)\n\n    ...\n}\n```\n\n[deleteallof-opts]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#DeleteAllOfOptions\n\n### Example usage\n\n```Go\nimport (\n    \"context\"\n    \"reflect\"\n\n    appsv1 \"k8s.io/api/apps/v1\"\n    corev1 \"k8s.io/api/core/v1\"\n    \"k8s.io/apimachinery/pkg/api/errors\"\n    metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n    \"k8s.io/apimachinery/pkg/labels\"\n    \"k8s.io/apimachinery/pkg/runtime\"\n    \"k8s.io/apimachinery/pkg/types\"\n    ctrl \"sigs.k8s.io/controller-runtime\"\n    \"sigs.k8s.io/controller-runtime/pkg/client\"\n    \"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil\"\n\n    cachev1alpha1 \"github.com/example/memcached-operator/api/v1alpha1\"\n)\n\ntype MemcachedReconciler struct {\n    client.Client\n    Log    logr.Logger\n    Scheme *runtime.Scheme\n}\n\nfunc (r *MemcachedReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {\n\n    // Fetch the Memcached instance.\n    memcached := &cachev1alpha1.Memcached{}\n    err := r.Get(ctx, request.NamespacedName, memcached)\n    if err != nil {\n        if errors.IsNotFound(err) {\n            return ctrl.Result{}, nil\n        }\n        return ctrl.Result{}, err\n    }\n\n    // Check if the deployment already exists, if not create a new deployment.\n    found := &appsv1.Deployment{}\n    err = r.Get(ctx, types.NamespacedName{Name: memcached.Name, Namespace: memcached.Namespace}, found)\n    if err != nil {\n         if errors.IsNotFound(err) {\n            // Define and create a new deployment.\n            dep := r.deploymentForMemcached(memcached)\n            if err = r.Create(ctx, dep); err != nil {\n                return ctrl.Result{}, err\n            }\n            return ctrl.Result{Requeue: true}, nil\n        } else {\n            return ctrl.Result{}, err\n        }\n    }\n\n    // Ensure the deployment size is the same as the spec.\n    size := memcached.Spec.Size\n    if *found.Spec.Replicas != size {\n        found.Spec.Replicas = &size\n        if err = r.Update(ctx, found); err != nil {\n            return ctrl.Result{}, err\n        }\n        return ctrl.Result{Requeue: true}, nil\n    }\n\n    // Update the Memcached status with the pod names.\n    // List the pods for this CR's deployment.\n    podList := &corev1.PodList{}\n    listOpts := []client.ListOption{\n        client.InNamespace(memcached.Namespace),\n        client.MatchingLabels(labelsForApp(memcached.Name)),\n    }\n    if err = r.List(ctx, podList, listOpts...); err != nil {\n        return ctrl.Result{}, err\n    }\n\n    // Update status.Nodes if needed.\n    podNames := getPodNames(podList.Items)\n    if !reflect.DeepEqual(podNames, memcached.Status.Nodes) {\n        memcached.Status.Nodes = podNames\n        if err := r.Status().Update(ctx, memcached); err != nil {\n            return ctrl.Result{}, err\n        }\n    }\n\n    return ctrl.Request{}, nil\n}\n\n// deploymentForMemcached returns a Deployment object for data from m.\nfunc (r *MemcachedReconciler) deploymentForMemcached(m *cachev1alpha1.Memcached) *appsv1.Deployment {\n    lbls := labelsForApp(m.Name)\n    replicas := m.Spec.Size\n\n    dep := &appsv1.Deployment{\n        ObjectMeta: metav1.ObjectMeta{\n            Name:      m.Name,\n            Namespace: m.Namespace,\n        },\n        Spec: appsv1.DeploymentSpec{\n            Replicas: &replicas,\n            Selector: &metav1.LabelSelector{\n                MatchLabels: lbls,\n            },\n            Template: corev1.PodTemplateSpec{\n                ObjectMeta: metav1.ObjectMeta{\n                    Labels: lbls,\n                },\n                Spec: corev1.PodSpec{\n                    Containers: []corev1.Container{{\n                        Image:   \"memcached:alpine\",\n                        Name:    \"memcached\",\n                        Command: []string{\"memcached\", \"-a=64\", \"-b\"},\n                        Ports: []corev1.ContainerPort{{\n                            ContainerPort: 10000,\n                            Name:          \"memcached\",\n                        }},\n                    }},\n                },\n            },\n        },\n    }\n\n    // Set Memcached instance as the owner and controller.memcac\n    // NOTE: calling SetControllerReference, and setting owner references in\n    // general, is important as it allows deleted objects to be garbage collected.\n    controllerutil.SetControllerReference(m, dep, r.Scheme)\n    return dep\n}\n\n// labelsForApp creates a simple set of labels for Memcached.\nfunc labelsForApp(name string) map[string]string {\n    return map[string]string{\"cr_name\": name}\n}\n```\n\n[memcached-testdata]:https://github.com/operator-framework/operator-sdk/tree/master/testdata/go/v4/memcached-operator\n[repo-controller-runtime]:https://github.com/kubernetes-sigs/controller-runtime\n[doc-client]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#Client\n[doc-split-client]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#DelegatingClient\n[doc-client-constr]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#New\n[code-scheme-default]:https://github.com/kubernetes-sigs/controller-runtime/blob/master/pkg/client/client.go#L51\n[doc-k8s-core]:https://pkg.go.dev/k8s.io/api/core/v1\n[doc-reconcile-reconciler]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/reconcile#Reconciler\n[doc-osdk-handle]:https://github.com/operator-framework/operator-sdk/blob/master/design/milestone-0.0.2/action-api.md#handler\n[doc-types-nsname]:https://pkg.go.dev/k8s.io/apimachinery/pkg/types#NamespacedName\n[cr-status-subresource]:https://kubernetes.io/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definitions/#status-subresource\n","website/content/en/docs/building-operators/golang/references/event-filtering.md":"---\ntitle: Using Predicates for Event Filtering with Operator SDK\nlinkTitle: Using Predicates for Event Filtering\nweight: 30\n---\n\n[Events][doc_event] are produced by [Sources][doc_source] assigned to resources a controller is watching. These events are transformed into Requests by [EventHandlers][doc_eventhandler] and passed to `Reconcile()`. [Predicates][doc_predicate] allow controllers to filter events before they are provided to EventHandlers. Filtering is useful because your controller may only want to handle specific types of events. Filtering also helps reduce chattiness with the API server, as `Reconcile()` is only called for events transformed by EventHandlers.\n\n## Predicate types\n\nA Predicate implements the following methods that take an event of a particular type and return true if the event should be processed by `Reconcile()`:\n\n```Go\n// Predicate filters events before enqueuing the keys.\ntype Predicate interface {\n  Create(event.CreateEvent) bool\n  Delete(event.DeleteEvent) bool\n  Update(event.UpdateEvent) bool\n  Generic(event.GenericEvent) bool\n}\n\n// Funcs implements Predicate.\ntype Funcs struct {\n  CreateFunc func(event.CreateEvent) bool\n  DeleteFunc func(event.DeleteEvent) bool\n  UpdateFunc func(event.UpdateEvent) bool\n  GenericFunc func(event.GenericEvent) bool\n}\n```\n\nFor example, all Create events for any watched resource will be passed to `Funcs.Create()` and filtered out if the method evaluates to `false`. If you do not register a Predicate method for a particular type, events of that type will not be filtered.\n\nAll event types contain Kubernetes [metadata][doc_object_metadata] about the object that triggered the event, and the object itself. Predicate logic uses these data to make decisions about what should be filtered. Some event types include other fields pertaining to the semantics of that event. For example, `event.UpdateEvent` includes both old and new metadata and objects:\n\n```Go\ntype UpdateEvent struct {\n  // ObjectOld is the object from the event.\n  ObjectOld runtime.Object\n\n  // ObjectNew is the object from the event.\n  ObjectNew runtime.Object\n}\n```\n\nYou can find all type definitions in the `event` package [documentation][doc_event].\n\n## Using Predicates\n\nAny number of Predicates can be set for a controller via the builder method `WithEventFilter()`, which will filter an event if any of those Predicates evaluates to `false`. This first example is an implementation of a `memcached-operator` controller that simply filters Delete events on Pods that have been confirmed deleted; the controller receives all Delete events that occur, and we may only care about resources that have not been completely deleted:\n\n```Go\nimport (\n\t\"context\"\n\n\t\"github.com/go-logr/logr\"\n\tcorev1 \"k8s.io/api/core/v1\"\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\tctrl \"sigs.k8s.io/controller-runtime\"\n\t\"sigs.k8s.io/controller-runtime/pkg/client\"\n\t\"sigs.k8s.io/controller-runtime/pkg/event\"\n\t\"sigs.k8s.io/controller-runtime/pkg/predicate\"\n\n\tcachev1alpha1 \"github.com/example/app-operator/api/v1alpha1\"\n)\n\n...\n\nfunc ignoreDeletionPredicate() predicate.Predicate {\n\treturn predicate.Funcs{\n\t\tUpdateFunc: func(e event.UpdateEvent) bool {\n\t\t\t// Ignore updates to CR status in which case metadata.Generation does not change\n\t\t\treturn e.ObjectOld.GetGeneration() != e.ObjectNew.GetGeneration()\n\t\t},\n\t\tDeleteFunc: func(e event.DeleteEvent) bool {\n\t\t\t// Evaluates to false if the object has been confirmed deleted.\n\t\t\treturn !e.DeleteStateUnknown\n\t\t},\n\t}\n}\n\nfunc (r *MemcachedReconciler) SetupWithManager(mgr ctrl.Manager) error {\n\treturn ctrl.NewControllerManagedBy(mgr).\n\t\tFor(&cachev1alpha1.Memcached{}).\n\t\tOwns(&corev1.Pod{}).\n\t\tWithEventFilter(ignoreDeletionPredicate()).\n\t\tComplete(r)\n}\n  ...\n}\n```\n\n## Use cases\n\nPredicates are not necessary for many operators, although filtering reduces the amount of chatter to the API server from `Reconcile()`. They are particularly useful for controllers that watch resources cluster-wide, i.e. without a namespace.\n\n[doc_event]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/event\n[doc_source]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/source#Source\n[doc_eventhandler]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/handler#EventHandler\n[doc_predicate]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/predicate\n[doc_object_metadata]:https://pkg.go.dev/k8s.io/apimachinery/pkg/apis/meta/v1#Object\n","website/content/en/docs/building-operators/golang/references/logging.md":"---\ntitle: Logging\nlinkTitle: Logging\nweight: 20\n---\n\n# Overview\n\nOperator SDK-generated operators use the [`logr`][godoc_logr] interface to log. This log interface has several backends such as [`zap`][repo_zapr], which the SDK uses in generated code by default. [`logr.Logger`][godoc_logr_logger] exposes structured logging methods that help create machine-readable logs and adding a wealth of information to log records.\n\n## Default zap logger\n\nOperator SDK uses a `zap`-based `logr` backend when scaffolding new projects. To assist with configuring and using this logger, the SDK includes several helper functions.\n\nIn the simple example below, we add the zap flagset to the operator's command line flags with `BindFlags()`, and then set the controller-runtime logger with `zap.Options{}`.\n\nBy default, `zap.Options{}` will return a logger that is ready for production use. It uses a JSON encoder, logs starting at the `info` level. To customize the default behavior, users can use the zap flagset and specify flags on the command line. The zap flagset includes the following flags that can be used to configure the logger:\n\n* `--zap-devel`: Development Mode defaults(encoder=consoleEncoder,logLevel=Debug,stackTraceLevel=Warn)\n\t\t\t  Production Mode defaults(encoder=jsonEncoder,logLevel=Info,stackTraceLevel=Error)\n* `--zap-encoder`: Zap log encoding ('json' or 'console')\n* `--zap-log-level`: Zap Level to configure the verbosity of logging. Can be one of 'debug', 'info', 'error',\n\t\t\t       or any integer value > 0 which corresponds to custom debug levels of increasing verbosity\")\n* `--zap-stacktrace-level`: Zap Level at and above which stacktraces are captured (one of 'info' or 'error')\n\nConsult the controller-runtime [godocs][logging_godocs] for more detailed flag information.\n\n### A simple example\n\nOperators set the logger for all operator logging in `main.go`. To illustrate how this works, try out this simple example:\n\n```Go\npackage main\n\nimport (\n\t\"sigs.k8s.io/controller-runtime/pkg/log/zap\"\n\tlogf \"sigs.k8s.io/controller-runtime/pkg/log\"\n)\n\nvar globalLog = logf.Log.WithName(\"global\")\nfunc main() {\n\t// Add the zap logger flag set to the CLI. The flag set must\n\t// be added before calling flag.Parse().\n\topts := zap.Options{}\n\topts.BindFlags(flag.CommandLine)\n\tflag.Parse()\n\n\tlogger := zap.New(zap.UseFlagOptions(&opts))\n\tlogf.SetLogger(logger)\n\n\tscopedLog := logf.Log.WithName(\"scoped\")\n\n\tglobalLog.Info(\"Printing at INFO level\")\n\tglobalLog.V(1).Info(\"Printing at DEBUG level\")\n\tscopedLog.Info(\"Printing at INFO level\")\n\tscopedLog.V(1).Info(\"Printing at DEBUG level\")\n}\n```\n\n#### Output using the defaults\n```console\n$ go run main.go\nINFO[0000] Running the operator locally in namespace default.\n{\"level\":\"info\",\"ts\":1587741740.407766,\"logger\":\"global\",\"msg\":\"Printing at INFO level\"}\n{\"level\":\"info\",\"ts\":1587741740.407855,\"logger\":\"scoped\",\"msg\":\"Printing at INFO level\"}\n```\n\n#### Output overriding the log level to 1 (debug)\n```console\n$ go run main.go --zap-log-level=debug\nINFO[0000] Running the operator locally in namespace default.\n{\"level\":\"info\",\"ts\":1587741837.602911,\"logger\":\"global\",\"msg\":\"Printing at INFO level\"}\n{\"level\":\"debug\",\"ts\":1587741837.602964,\"logger\":\"global\",\"msg\":\"Printing at DEBUG level\"}\n{\"level\":\"info\",\"ts\":1587741837.6029708,\"logger\":\"scoped\",\"msg\":\"Printing at INFO level\"}\n{\"level\":\"debug\",\"ts\":1587741837.602973,\"logger\":\"scoped\",\"msg\":\"Printing at DEBUG level\"}\n```\n## Custom zap logger\n\nIn order to use a custom zap logger, [`zap`][controller_runtime_zap] from controller-runtime can be utilized to wrap it in a `logr` implementation.\n\nBelow is an example illustrating the use of [`zap-logfmt`][logfmt_repo] in logging.\n\n### Example\n\nIn your `main.go` file, replace the current implementation for logs inside the `main` function:\n\n```Go\n...\n// Add the zap logger flag set to the CLI. The flag set must\n// be added before calling flag.Parse().\n\topts := zap.Options{}\n\topts.BindFlags(flag.CommandLine)\n\tflag.Parse()\n\n\tlogger := zap.New(zap.UseFlagOptions(&opts))\n\tlogf.SetLogger(logger)\n...\n```\n\nWith:\n\n```Go\n\timport(\n\t...\n\tzaplogfmt \"github.com/sykesm/zap-logfmt\"\n\tuzap \"go.uber.org/zap\"\n\t\"go.uber.org/zap/zapcore\"\n\tlogf \"sigs.k8s.io/controller-runtime/pkg/log\"\n\t\"sigs.k8s.io/controller-runtime/pkg/log/zap\"\n\t...\n)\n\tconfigLog := uzap.NewProductionEncoderConfig()\n\tconfigLog.EncodeTime = func(ts time.Time, encoder zapcore.PrimitiveArrayEncoder) {\n\t\tencoder.AppendString(ts.UTC().Format(time.RFC3339Nano))\n\t}\n\tlogfmtEncoder := zaplogfmt.NewEncoder(configLog)\n\n\t// Construct a new logr.logger.\n\tlogger := zap.New(zap.UseDevMode(true), zap.WriteTo(os.Stdout), zap.Encoder(logfmtEncoder))\n\tlogf.SetLogger(logger)\n```\n\n**NOTE**: For this example, you will need to add the module `\"github.com/sykesm/zap-logfmt\"` to your project. Run `go get -u github.com/sykesm/zap-logfmt`.\n\n#### Output using custom zap logger\n\n```console\n$ go run main.go\nts=2020-04-30T20:35:59.551268Z level=info logger=global msg=\"Printing at INFO level\"\nts=2020-04-30T20:35:59.551314Z level=debug logger=global msg=\"Printing at DEBUG level\"\nts=2020-04-30T20:35:59.551318Z level=info logger=scoped msg=\"Printing at INFO level\"\nts=2020-04-30T20:35:59.55132Z level=debug logger=scoped msg=\"Printing at DEBUG level\"\n```\n\nBy using `sigs.k8s.io/controller-runtime/pkg/log`, your logger is propagated through `controller-runtime`. Any logs produced by `controller-runtime` code will be through your logger, and therefore have the same formatting and destination.\n\n### Setting flags when running locally\n\nWhen running locally with `make run ENABLE_WEBHOOKS=false`, you can use the `ARGS` var to pass additional flags to your operator, including the zap flags. For example:\n\n```console\n$ make run ARGS=\"--zap-encoder=console\" ENABLE_WEBHOOKS=false\n```\nMake sure to have your `run` target to take `ARGS` as shown below in `Makefile`.\n\n```makefile\n# Run against the configured Kubernetes cluster in ~/.kube/config\nrun: manifests generate fmt vet\n\tgo run ./main.go $(ARGS)\n```\n\n### Setting flags when deploying to a cluster\n\nWhen deploying your operator to a cluster you can set additional flags using an `args` array in your operator's `container` spec in the file `config/default/manager_metrics_patch.yaml` For example:\n\n```yaml\n- op: add\n  path: /spec/template/spec/containers/0/args/0\n  value: --zap-log-level=debug \n- op: add\n  path: /spec/template/spec/containers/0/args/0\n  value: --zap-encoder=console\n```\n\n## Creating a structured log statement\n\nThere are two ways to create structured logs with `logr`. You can create new loggers using `log.WithValues(keyValues)` that include `keyValues`, a list of key-value pair `interface{}`'s, in each log record. Alternatively you can include `keyValues` directly in a log statement, as all `logr` log statements take some message and `keyValues`. The signature of `logr.Error()` has an `error`-type parameter, which can be `nil`.\n\nAn example from [`memcached_controller.go`][code_memcached_controller]:\n\n```Go\npackage memcached\n\nimport (\n  ctrllog \"sigs.k8s.io/controller-runtime/pkg/log\"\n)\n\n\n// MemcachedReconciler reconciles a Memcached object\ntype MemcachedReconciler struct {\n\tclient.Client\n\tLog    logr.Logger\n\tScheme *runtime.Scheme\n}\n\nfunc (r *MemcachedReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {\n\tlog := ctrllog.FromContext(ctx)\n\n\t// Fetch the Memcached instance\n\tmemcached := &cachev1alpha1.Memcached{}\n\terr := r.Get(ctx, req.NamespacedName, memcached)\n\tif err != nil {\n\t\tif errors.IsNotFound(err) {\n\t\t\t// Request object not found, could have been deleted after reconcile request.\n\t\t\t// Owned objects are automatically garbage collected. For additional cleanup logic use finalizers.\n\t\t\t// Return and don't requeue\n\t\t\tlog.Info(\"Memcached resource not found. Ignoring since object must be deleted\")\n\t\t\treturn ctrl.Result{}, nil\n\t\t}\n\t\t// Error reading the object - requeue the request.\n\t\tlog.Error(err, \"Failed to get Memcached\")\n\t\treturn ctrl.Result{}, err\n\t}\n\n\t// Check if the deployment already exists, if not create a new one\n\tfound := &appsv1.Deployment{}\n\terr = r.Get(ctx, types.NamespacedName{Name: memcached.Name, Namespace: memcached.Namespace}, found)\n\tif err != nil && errors.IsNotFound(err) {\n\t\t// Define a new deployment\n\t\tdep := r.deploymentForMemcached(memcached)\n\t\tlog.Info(\"Creating a new Deployment\", \"Deployment.Namespace\", dep.Namespace, \"Deployment.Name\", dep.Name)\n\t\terr = r.Create(ctx, dep)\n\t\tif err != nil {\n\t\t\tlog.Error(err, \"Failed to create new Deployment\", \"Deployment.Namespace\", dep.Namespace, \"Deployment.Name\", dep.Name)\n\t\t\treturn ctrl.Result{}, err\n\t\t}\n\t\t// Deployment created successfully - return and requeue\n\t\treturn ctrl.Result{Requeue: true}, nil\n\t} else if err != nil {\n\t\tlog.Error(err, \"Failed to get Deployment\")\n\t\treturn ctrl.Result{}, err\n\t}\n\n\t...\n}\n```\n\nLog records will look like the following (from `log.Error()` above):\n\n```\n2020-04-27T09:14:15.939-0400\tERROR\tcontrollers.Memcached\tFailed to create new Deployment\t{\"memcached\": \"default/memcached-sample\", \"Deployment.Namespace\": \"default\", \"Deployment.Name\": \"memcached-sample\"}\n```\n\n## Non-default logging\n\nIf you do not want to use `logr` as your logging tool, you can remove `logr`-specific statements without issue from your operator's code, including the `logr` setup code in `main.go`, and add your own. Note that removing `logr` setup code will prevent `controller-runtime` from logging.\n\n\n[godoc_logr]:https://pkg.go.dev/github.com/go-logr/logr\n[repo_zapr]:https://pkg.go.dev/github.com/go-logr/zapr\n[godoc_logr_logger]:https://pkg.go.dev/github.com/go-logr/logr#Logger\n[code_memcached_controller]: https://github.com/operator-framework/operator-sdk/blob/v1.2.0/testdata/go/memcached-operator/controllers/memcached_controller.go\n[logfmt_repo]:https://github.com/jsternberg/zap-logfmt\n[controller_runtime_zap]:https://github.com/kubernetes-sigs/controller-runtime/tree/master/pkg/log/zap\n[logging_godocs]: https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/log/zap#Options.BindFlags\n","website/content/en/docs/building-operators/golang/references/markers.md":"---\ntitle: API Markers\nlinkTitle: API Markers\nweight: 40\n---\n\nThis document describes [code markers][markers] supported by the SDK.\n\n## ClusterServiceVersion markers\n\nThis section details ClusterServiceVersion (CSV) code markers and lists available markers.\n\n**Note:** CSV markers can only be used in Go Operator projects. Annotations for Ansible and Helm Operator projects will be added in the future.\n\n### Usage\n\nAll CSV markers have the prefix `+operator-sdk:csv`.\n\n#### `+operator-sdk:csv:customresourcedefinitions`\n\nThese markers populate [owned `customresourcedefinitions`][csv-crds] in your CSV.\n\nPossible type-level markers:\n- `+operator-sdk:csv:customresourcedefinitions:displayName=\"some display name\"`\n\t- Configures the kind's display name.\n- `+operator-sdk:csv:customresourcedefinitions:resources={{Kind1,v1alpha1,dns-name-1},{Kind2,v1,\"dns-name-2\"},...}`\n\t- Configures the kind's resources.\n- `+operator-sdk:csv:customresourcedefinitions:order=1`\n\t- Configures the order of this type in the list. Markers with order omitted have the highest order, i.e. are at the end of the list. If more than one marker has the same order, the corresponding descriptions will be sorted alphabetically and placed above others with higher orders. Pre-existing list elements in the CSV will be appended to the set of other elements in the order corresponding to its index.\n\nPossible field-level markers, all of which must contain the `type=[spec,status]` key-value pair:\n- `+operator-sdk:csv:customresourcedefinitions:type=[spec,status],displayName=\"some field display name\"`\n\t- Configures the field's display name.\n- `+operator-sdk:csv:customresourcedefinitions:type=[spec,status],xDescriptors={\"urn:alm:descriptor:com.tectonic.ui:podCount\",\"urn:alm:descriptor:io.kubernetes:custom\"}`\n\t- Configures the field's x-descriptors.\n- `+operator-sdk:csv:customresourcedefinitions:type=[spec,status],order=1`\n\t- Configures the order of this type in the list. Markers with order omitted have the highest order, i.e. are at the end of the list. If more than one marker has the same order, the corresponding descriptions will be sorted alphabetically and placed above others with higher orders.\n\nTop-level `kind`, `name`, and `version` fields are parsed from API code.\nAll `description` fields are parsed from type declaration and `struct` type field comments.\nAll `path` fields are parsed from a field's JSON tag and merged with parent\nfield path's in dot-hierarchy notation.\n\n##### x-descriptors\n\nCheck out the [descriptor reference][csv-x-desc] for available `x-descriptors` paths.\n\n#### Examples\n\nThese examples assume `Memcached`, `MemcachedSpec`, and `MemcachedStatus` are the example projects' kind, spec, and status.\n\n1. Set a `displayName` and `resources` for a `customresourcedefinitions` kind entry:\n\n\t```go\n\t//+operator-sdk:csv:customresourcedefinitions:displayName=\"Memcached App\",resources={{Pod,v1,memcached-runner},{Deployment,v1,memcached-deployment}}\n\ttype Memcached struct {\n\t\tmetav1.TypeMeta   `json:\",inline\"`\n\t\tmetav1.ObjectMeta `json:\"metadata,omitempty\"`\n\n\t\tSpec   MemcachedSpec   `json:\"spec,omitempty\"`\n\t\tStatus MemcachedStatus `json:\"status,omitempty\"`\n\t}\n\t```\n\n2. Set `displayName`, `path`, `xDescriptors`, and `description` on a field for a `customresourcedefinitions.specDescriptors` entry:\n\n\t```go\n\ttype MemcachedSpec struct {\n\t\t// Size is the size of the memcached deployment. <-- This will become Size's specDescriptors.description.\n\t\t//+operator-sdk:csv:customresourcedefinitions:type=spec,displayName=\"Number of pods\",xDescriptors={\"urn:alm:descriptor:com.tectonic.ui:podCount\",\"urn:alm:descriptor:io.kubernetes:custom\"}\n\t\tSize int32 `json:\"size\"` // <-- Size's specDescriptors.path is inferred from this JSON tag.\n\t}\n\t```\n\n3. Let the SDK infer all unmarked paths on a field for a `customresourcedefinitions.specDescriptors` entry:\n\n\t```go\n\ttype MemcachedSpec struct {\n\t\t// Size is the size of the memcached deployment.\n\t\t//+operator-sdk:csv:customresourcedefinitions:type=spec\n\t\tSize int32 `json:\"size\"`\n\t}\n\t```\n\n\tThe SDK uses the `Size` fields' `json` tag name as `path`, `Size` as `displayName`, and field comments as `description`.\n\n4. A comprehensive example:\n\t- Infer `path`, `description`, `displayName`, and `x-descriptors` for `specDescriptors` and `statusDescriptors` entries.\n\t- Create three `resources` entries each with `kind`, `version`, and `name` values.\n\n\t```go\n\t// Represents a cluster of Memcached apps\n\t//+operator-sdk:csv:customresourcedefinitions:displayName=\"Memcached App\",resources={{Pod,v1,memcached-runner},{Deployment,v1,memcached-deployment}}\n\ttype Memcached struct {\n\t\tmetav1.TypeMeta   `json:\",inline\"`\n\t\tmetav1.ObjectMeta `json:\"metadata,omitempty\"`\n\n\t\tSpec   MemcachedSpec   `json:\"spec,omitempty\"`\n\t\tStatus MemcachedStatus `json:\"status,omitempty\"`\n\t}\n\n\ttype MemcachedSpec struct {\n\t\tPods MemcachedPods `json:\"pods\"`\n\t}\n\n\ttype MemcachedStatus struct {\n\t\tPods \t\t MemcachedPods `json:\"podStatuses\"`\n\t\t//+operator-sdk:csv:customresourcedefinitions:type=status,displayName=\"Pod Count\",xDescriptors=\"urn:alm:descriptor:com.tectonic.ui:podCount\"\n\t\tPodCount int \t\t\t\t\t `json:\"podCount\"`\n\t}\n\n\ttype MemcachedPods struct {\n\t\t// Size is the size of the memcached deployment.\n\t\t//+operator-sdk:csv:customresourcedefinitions:type=spec\n\t\t//+operator-sdk:csv:customresourcedefinitions:type=status\n\t\tSize int32 `json:\"size\"`\n\t}\n\t```\n\n\tThe generated `customresourcedefinitions` will look like:\n\n\t```yaml\n\tcustomresourcedefinitions:\n\t  owned:\n\t  - description: Represents a cluster of Memcached apps\n\t    displayName: Memcached App\n\t    kind: Memcached\n\t    name: memcacheds.cache.example.com\n\t    version: v1alpha1\n\t    resources:\n\t    - kind: Deployment\n\t      name: memcached-deployment\n\t      version: v1\n\t    - kind: Pod\n\t      name: memcached-runner\n\t      version: v1\n\t    specDescriptors:\n\t    - description: The desired number of member Pods for the deployment.\n\t      displayName: Size\n\t      path: pods.size\n\t    statusDescriptors:\n\t    - description: The desired number of member Pods for the deployment.\n\t      displayName: Size\n\t      path: podStatuses.size\n\t    - displayName: Size\n\t      path: podCount\n\t      x-descriptors:\n\t      - 'urn:alm:descriptor:com.tectonic.ui:podCount'\n\t```\n\n\n## Deprecated markers\n\nMarkers supported by `operator-sdk` prior to v1.0.0 are deprecated.\nYou can migrate to the new marker system by running the following script:\n\n```console\n$ curl -sSLo migrate-markers.sh https://raw.githubusercontent.com/operator-framework/operator-sdk/master/hack/generate/migrate-markers.sh\n$ chmod +x ./migrate-markers.sh\n$ ./migrate-markers.sh path/to/*_types.go\n```\n\n\n[markers]:https://pkg.go.dev/sigs.k8s.io/controller-tools/pkg/markers\n[cli-gen-kustomize-manifests]:/docs/cli/operator-sdk_generate_kustomize_manifests\n[csv-x-desc]:https://github.com/openshift/console/blob/master/frontend/packages/operator-lifecycle-manager/src/components/descriptors/reference/reference.md\n[csv-spec]:https://github.com/operator-framework/operator-lifecycle-manager/blob/e0eea22/doc/design/building-your-csv.md\n[csv-crds]:https://github.com/operator-framework/operator-lifecycle-manager/blob/master/doc/design/building-your-csv.md#your-custom-resource-definitions\n","website/content/en/docs/building-operators/golang/references/openapi-validation.md":"---\ntitle: OpenAPI validation\nlinkTitle: OpenAPI validation\nweight: 70\n---\n\nOpenAPIv3 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.\n\n[Markers][markers] (annotations) are available to configure validations for your API. These markers will always have a `+kubebuilder:validation` prefix.\n\nUsage of markers in API code is discussed in the kubebuilder [CRD generation][generating-crd] and [marker][markers] documentation. A full list of OpenAPIv3 validation markers can be found [here][crd-markers].\n\nTo learn more about OpenAPI v3.0 validation schemas in CRDs, refer to the [Kubernetes Documentation][doc-validation-schema].\n\n[markers]: https://book.kubebuilder.io/reference/markers.html\n[crd-markers]: https://book.kubebuilder.io/reference/markers/crd-validation.html\n[generating-crd]: https://book.kubebuilder.io/reference/generating-crd.html\n[doc-validation-schema]: https://kubernetes.io/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definitions/#specifying-a-structural-schema\n","website/content/en/docs/building-operators/golang/references/proxy-vars.md":"---\ntitle: Proxy Friendly Operators\nlinkTitle: Proxy Vars\nweight: 20\n---\n\nProxy-friendly Operators should inspect their environment for the\nstandard proxy variables (`HTTPS_PROXY`, `HTTP_PROXY`, and `NO_PROXY`)\nand pass the values to Operands.\n\nOperator-lib provides a helper function `proxy.ReadProxyVarsFromEnv`\nthat does this inspection, all you need to do is append the\nresults to the Operand environments.\n\nUsing the memcached tutorial as an example, add the following to the\nReconcile loop in `controllers/memcached_controller.go`:\n\n\n```go\nimport (\n  ...\n   \"github.com/operator-framework/operator-lib/proxy\"\n)\n\n\nfor i, container := range dep.Spec.Template.Spec.Containers {\n\t\tdep.Spec.Template.Spec.Containers[i].Env = append(container.Env, proxy.ReadProxyVarsFromEnv()...)\n}\n```\n\nYou can set the environment variable on the Operator deployment. Using the memcached tutorial, edit config/manager/manager.yaml:\n\n```yaml\ncontainers:\n - args:\n   - --leader-elect\n   - --leader-election-id=go-proxy-demo\n   image: controller:latest\n   name: manager\n   env:\n     - name: \"HTTP_PROXY\"\n       value: \"http_proxy_test\"\n```\n"},"items":[{"name":"_index.md","path":"website/content/en/docs/building-operators/golang/references/_index.md","rawUrl":"https://raw.githubusercontent.com/operator-framework/operator-sdk/HEAD/website/content/en/docs/building-operators/golang/references/_index.md","title":"References Skill","category":"anthropic-skill","format":"markdown","content":"---\ntitle: Go-based Operator Reference\nlinkTitle: Reference\nweight: 100\n---","frontmatter":{"title":"Go-based Operator Reference","linkTitle":"Reference","weight":100},"isInternal":false,"tokens":19,"sizeBytes":75},{"name":"client.md","path":"website/content/en/docs/building-operators/golang/references/client.md","rawUrl":"https://raw.githubusercontent.com/operator-framework/operator-sdk/HEAD/website/content/en/docs/building-operators/golang/references/client.md","title":"References Skill","category":"anthropic-skill","format":"markdown","content":"---\ntitle: Controller Runtime Client API\nlinkTitle: Controller Runtime Client API\nweight: 10\n---\n\n## Overview\n\nThe [`controller-runtime`][repo-controller-runtime] library provides various abstractions to watch and reconcile resources in a Kubernetes cluster via CRUD (Create, Update, Delete, as well as Get and List in this case) operations. Operators use at least one controller to perform a coherent set of tasks within a cluster, usually through a combination of CRUD operations. The Operator SDK uses controller-runtime's [Client][doc-client] interface, which provides the interface for these operations.\n\ncontroller-runtime defines several interfaces used for cluster interaction:\n- `client.Client`: implementers perform CRUD operations on a Kubernetes cluster.\n- `manager.Manager`: manages shared dependencies, such as Caches and Clients.\n- `reconcile.Reconciler`: compares provided state with actual cluster state and updates the cluster on finding state differences using a Client.\n\nClients are the focus of this document. A separate document will discuss Managers.\n\n**Note:** this document uses parts of the sample [`memcached-operator`][memcached-testdata] for example code.\nImport paths may be different for brevity.\n\n## Client Usage\n\n### Default Client\n\nThe SDK relies on a `manager.Manager` to create a `client.Client` interface that performs Create, Update, Delete, Get, and List operations within a `reconcile.Reconciler`'s Reconcile function. The SDK will generate code to create a Manager, which holds a Cache and a Client to be used in CRUD operations and communicate with the API server. By default a Controller's Reconciler will be populated with the Manager's Client which is a [split-client][doc-split-client].\n\nThe following code, found in `controllers/memcached_controller.go`, demonstrates how the Manager's client is passed to a reconciler.\n\n```Go\nimport (\n\tappsv1 \"k8s.io/api/apps/v1\"\n\tctrl \"sigs.k8s.io/controller-runtime\"\n\n\tcachev1alpha1 \"github.com/example/memcached-operator/api/v1alpha1\"\n)\n\nfunc (r *MemcachedReconciler) SetupWithManager(mgr ctrl.Manager) error {\n\treturn ctrl.NewControllerManagedBy(mgr). // mgr's Client is passed to r.\n\t\tFor(&cachev1alpha1.Memcached{}).\n\t\tOwns(&appsv1.Deployment{}).\n\t\tComplete(r)\n}\n\ntype MemcachedReconciler struct {\n    client.Client // Populated above from a manager.Manager.\n\n    Log    logr.Logger\n    Scheme *runtime.Scheme\n}\n```\n\nA split client reads (Get and List) from the Cache and writes (Create, Update, Delete) to the API server. Reading from the Cache significantly reduces request load on the API server; as long as the Cache is updated by the API server, read operations are eventually consistent.\n\n### Non-default Client\n\nAn operator developer may wish to create their own Client that serves read requests(Get List) from the API server instead of the cache, for example. controller-runtime provides a [constructor][doc-client-constr] for Clients:\n\n```Go\n// New returns a new Client using the provided config and Options.\nfunc New(config *rest.Config, options client.Options) (client.Client, error)\n```\n\n`client.Options` allow the caller to specify how the new Client should communicate with the API server.\n\n```Go\n// Options are creation options for a Client\ntype Options struct {\n    // Scheme, if provided, will be used to map go structs to GroupVersionKinds\n    Scheme *runtime.Scheme\n\n    // Mapper, if provided, will be used to map GroupVersionKinds to Resources\n    Mapper meta.RESTMapper\n}\n```\n\nExample:\n\n```Go\nimport (\n    \"sigs.k8s.io/controller-runtime/pkg/client/config\"\n    \"sigs.k8s.io/controller-runtime/pkg/client\"\n)\n\ncfg, err := config.GetConfig()\n...\nc, err := client.New(cfg, client.Options{})\n...\n```\n\n**Note**: defaults are set by `client.New` when Options are empty. The default [scheme][code-scheme-default] will have the [core][doc-k8s-core] Kubernetes resource types registered. The caller *must* set a scheme that has custom operator types registered for the new Client to recognize these types.\n\nCreating a new Client is not usually necessary nor advised, as the default Client is sufficient for most use cases.\n\n### Reconcile and the Client API\n\nA Reconciler implements the [`reconcile.Reconciler`][doc-reconcile-reconciler] interface, which exposes the Reconcile method. Reconcilers are added to a corresponding Controller for a Kind; Reconcile is called in response to cluster or external Events, with a `reconcile.Request` object argument, to read and write cluster state by the Controller, and returns a `ctrl.Result`. SDK Reconcilers have access to a Client in order to make Kubernetes API calls.\n\n```Go\n// MemcachedReconciler reconciles a Memcached object\ntype MemcachedReconciler struct {\n    // client, initialized using mgr.Client() above, is a split client\n    // that reads objects from the cache and writes to the apiserver\n    client.Client\n\n    Log    logr.Logger\n\n    // scheme defines methods for serializing and deserializing API objects,\n    // a type registry for converting group, version, and kind information\n    // to and from Go schemas, and mappings between Go schemas of different\n    // versions. A scheme is the foundation for a versioned API and versioned\n    // configuration over time.\n    Scheme *runtime.Scheme\n}\n\n// Reconcile watches for Events and reconciles cluster state with desired\n// state defined in the method body.\n// The Controller will requeue the Request to be processed again if an error\n// is non-nil or Result.Requeue is true, otherwise upon completion it will\n// remove the work from the queue.\nfunc (r *MemcachedReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error)\n```\n\nReconcile is where Controller business logic lives, i.e. where Client API calls are made via `MemcachedReconciler.client`. A `client.Client` implementer performs the following operations:\n\n#### Get\n\n```Go\n// Get retrieves an API object for a given object key from the Kubernetes cluster\n// and stores it in obj.\nfunc (c Client) Get(ctx context.Context, key client.ObjectKey, obj client.Object) error\n```\n\n**Note**: A `client.ObjectKey` is simply an alias for [`types.NamespacedName`][doc-types-nsname].\n\nExample:\n\n```Go\nimport (\n    \"context\"\n\n    ctrl \"sigs.k8s.io/controller-runtime\"\n\n    cachev1alpha1 \"github.com/example/memcached-operator/api/v1alpha1\"\n)\n\nfunc (r *MemcachedReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {\n    ...\n\n    memcached := &cachev1alpha1.Memcached{}\n    err := r.Get(ctx, request.NamespacedName, memcached)\n\n    ...\n}\n```\n\n#### List\n\n```Go\n// List retrieves a list of objects for a given namespace and list options\n// and stores the list in obj.\nfunc (c Client) List(ctx context.Context, list client.Object, opts ...client.ListOption) error\n```\n\nA `client.ListOption` is an interface that sets [`client.ListOptions`][list-options] fields. A `client.ListOption` is created by using one of the provided implementations: [`MatchingLabels`][matching-labels], [`MatchingFields`][matching-fields], [`InNamespace`][in-namespace].\n\nExample:\n\n```Go\nimport (\n    \"context\"\n    \"fmt\"\n\n    \"k8s.io/api/core/v1\"\n    ctrl \"sigs.k8s.io/controller-runtime\"\n    \"sigs.k8s.io/controller-runtime/pkg/client\"\n)\n\nfunc (r *MemcachedReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {\n    ...\n\n    // Return all pods in the request namespace with a label of `instance=<name>`\n    // and phase `Running`.\n    podList := &v1.PodList{}\n    opts := []client.ListOption{\n        client.InNamespace(request.NamespacedName.Namespace),\n        client.MatchingLabels{\"instance\": request.NamespacedName.Name},\n        client.MatchingFields{\"status.phase\": \"Running\"},\n    }\n    err := r.List(ctx, podList, opts...)\n\n    ...\n}\n```\n\n[list-options]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#ListOptions\n[matching-labels]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#MatchingLabels\n[matching-fields]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#MatchingFields\n[in-namespace]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#InNamespace\n\n#### Create\n\n```Go\n// Create saves the object obj in the Kubernetes cluster.\n// Returns an error\nfunc (c Client) Create(ctx context.Context, obj client.Object, opts ...client.CreateOption) error\n```\n\nA `client.CreateOption` is an interface that sets [`client.CreateOptions`][create-options] fields. A `client.CreateOption` is created by using one of the provided implementations: [`DryRunAll`][dry-run-all], [`ForceOwnership`][force-ownership]. Generally these options are not needed.\n\nExample:\n\n```Go\nimport (\n    \"context\"\n\n    \"k8s.io/api/apps/v1\"\n    ctrl \"sigs.k8s.io/controller-runtime\"\n)\n\nfunc (r *MemcachedReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {\n    ...\n\n    dep := &v1.Deployment{ // Any cluster object you want to create.\n        ...\n    }\n    err := r.Create(ctx, dep)\n\n    ...\n}\n```\n\n[create-options]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#CreateOptions\n\n#### Update\n\n```Go\n// Update updates the given obj in the Kubernetes cluster. obj must be a\n// struct pointer so that obj can be updated with the content returned\n// by the API server. Update does *not* update the resource's status\n// subresource\nfunc (c Client) Update(ctx context.Context, obj client.Object, opts ...client.UpdateOption) error\n```\n\nA `client.UpdateOption` is an interface that sets [`client.UpdateOptions`][update-options] fields. A `client.UpdateOption` is created by using one of the provided implementations: [`DryRunAll`][dry-run-all], [`ForceOwnership`][force-ownership]. Generally these options are not needed.\n\nExample:\n\n```Go\nimport (\n    \"context\"\n\n    \"k8s.io/api/apps/v1\"\n    ctrl \"sigs.k8s.io/controller-runtime\"\n)\n\nfunc (r *MemcachedReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {\n    ...\n\n    dep := &v1.Deployment{}\n    err := r.Get(ctx, request.NamespacedName, dep)\n\n    ...\n\n    dep.Spec.Selector.MatchLabels[\"is_running\"] = \"true\"\n    err := r.Update(ctx, dep)\n\n    ...\n}\n```\n\n[update-options]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#UpdateOptions\n\n#### Patch\n\n```Go\n// Patch patches the given obj in the Kubernetes cluster. obj must be a\n// struct pointer so that obj can be updated with the content returned by the Server.\nfunc (c Client) Patch(ctx context.Context, obj client.Object, patch client.Patch, opts ...client.PatchOption) error\n```\n\nA `client.PatchOption` is an interface that sets [`client.PatchOptions`][patch-options] fields. A `client.PatchOption` is created by using one of the provided implementations: [`DryRunAll`][dry-run-all], [`ForceOwnership`][force-ownership]. Generally these options are not needed.\n\nExample:\n\n```Go\nimport (\n    \"context\"\n\n    \"k8s.io/api/apps/v1\"\n    ctrl \"sigs.k8s.io/controller-runtime\"\n    \"sigs.k8s.io/controller-runtime/pkg/client\"\n)\n\nfunc (r *MemcachedReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {\n    ...\n\n    dep := &v1.Deployment{}\n    err := r.Get(ctx, request.NamespacedName, dep)\n\n    ...\n\n    // A merge patch will preserve other fields modified at runtime.\n    patch := client.MergeFrom(dep.DeepCopy())\n    dep.Spec.Selector.MatchLabels[\"is_running\"] = \"true\"\n    err := r.Patch(ctx, dep, patch)\n\n    ...\n}\n```\n\n[patch-options]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#PatchOption\n[dry-run-all]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#DryRunAll\n[force-ownership]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#ForceOwnership\n\n##### Updating Status Subresource\n\nWhen updating the [status subresource][cr-status-subresource] from the client, the [`StatusWriter`][status-writer] must be used. The status subresource is retrieved with `Status()` and updated with `Update()` or patched with `Patch()`.\n\n`Update()` takes variadic `client.UpdateOption`'s, and `Patch()` takes variadic `client.PatchOption`'s. See [`Client.Update()`](#update) and [`Client.Patch()`](#patch) for more details. Generally these options are not needed.\n\n##### Status\n\n```Go\n// Status() returns a StatusWriter object that can be used to update the\n// object's status subresource\nfunc (c Client) Status() (client.StatusWriter, error)\n```\n\nExample:\n```Go\nimport (\n    \"context\"\n\n    ctrl \"sigs.k8s.io/controller-runtime\"\n\n    cachev1alpha1 \"github.com/example/memcached-operator/api/v1alpha1\"\n)\n\nfunc (r *MemcachedReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {\n    ...\n\n    mem := &cachev1alpha1.Memcached{}\n    err := r.Get(ctx, request.NamespacedName, mem)\n\n    ...\n\n    // Update\n    mem.Status.Nodes = []string{\"pod1\", \"pod2\"}\n    err := r.Status().Update(ctx, mem)\n\n    ...\n\n    // Patch\n    patch := client.MergeFrom(mem.DeepCopy())\n    mem.Status.Nodes = []string{\"pod1\", \"pod2\", \"pod3\"}\n    err := r.Status().Patch(ctx, mem, patch)\n\n    ...\n}\n```\n\n[status-writer]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#StatusWriter\n\n#### Delete\n\n```Go\n// Delete deletes the given obj from Kubernetes cluster.\nfunc (c Client) Delete(ctx context.Context, obj client.Object, opts ...client.DeleteOption) error\n```\n\nA `client.DeleteOption` is an interface that sets [`client.DeleteOptions`][delete-opts] fields. A `client.DeleteOption` is created by using one of the provided implementations: [`GracePeriodSeconds`][grace-period-seconds], [`Preconditions`][preconditions], [`PropagationPolicy`][propagation-policy].\n\nExample:\n\n```Go\nimport (\n    \"context\"\n\n    \"k8s.io/api/core/v1\"\n    ctrl \"sigs.k8s.io/controller-runtime\"\n    \"sigs.k8s.io/controller-runtime/pkg/client\"\n)\n\nfunc (r *MemcachedReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {\n    ...\n\n    pod := &v1.Pod{}\n    err := r.Get(ctx, request.NamespacedName, pod)\n\n    ...\n\n    if pod.Status.Phase == v1.PodUnknown {\n        // Delete the pod after 5 seconds.\n        err := r.Delete(ctx, pod, client.GracePeriodSeconds(5))\n        ...\n    }\n\n    ...\n}\n```\n\n[delete-opts]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#DeleteOptions\n[grace-period-seconds]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#GracePeriodSeconds\n[preconditions]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#Preconditions\n[propagation-policy]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#PropagationPolicy\n\n#### DeleteAllOf\n\n```Go\n// DeleteAllOf deletes all objects of the given type matching the given options.\nfunc (c Client) DeleteAllOf(ctx context.Context, obj client.Object, opts ...client.DeleteAllOfOption) error\n```\n\nA `client.DeleteAllOfOption` is an interface that sets [`client.DeleteAllOfOptions`][deleteallof-opts] fields. A `client.DeleteAllOfOption` wraps a [`client.ListOption`](#list) and [`client.DeleteOption`](#delete).\n\nExample:\n\n```Go\nimport (\n    \"context\"\n    \"fmt\"\n\n    \"k8s.io/api/core/v1\"\n    ctrl \"sigs.k8s.io/controller-runtime\"\n    \"sigs.k8s.io/controller-runtime/pkg/client\"\n)\n\nfunc (r *MemcachedReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {\n    ...\n\n    // Delete all pods in the request namespace with a label of `instance=<name>`\n    // and phase `Failed`.\n    pod := &v1.Pod{}\n    opts := []client.DeleteAllOfOption{\n        client.InNamespace(request.NamespacedName.Namespace),\n        client.MatchingLabels{\"instance\", request.NamespacedName.Name},\n        client.MatchingFields{\"status.phase\": \"Failed\"},\n        client.GracePeriodSeconds(5),\n    }\n    err := r.DeleteAllOf(ctx, pod, opts...)\n\n    ...\n}\n```\n\n[deleteallof-opts]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#DeleteAllOfOptions\n\n### Example usage\n\n```Go\nimport (\n    \"context\"\n    \"reflect\"\n\n    appsv1 \"k8s.io/api/apps/v1\"\n    corev1 \"k8s.io/api/core/v1\"\n    \"k8s.io/apimachinery/pkg/api/errors\"\n    metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n    \"k8s.io/apimachinery/pkg/labels\"\n    \"k8s.io/apimachinery/pkg/runtime\"\n    \"k8s.io/apimachinery/pkg/types\"\n    ctrl \"sigs.k8s.io/controller-runtime\"\n    \"sigs.k8s.io/controller-runtime/pkg/client\"\n    \"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil\"\n\n    cachev1alpha1 \"github.com/example/memcached-operator/api/v1alpha1\"\n)\n\ntype MemcachedReconciler struct {\n    client.Client\n    Log    logr.Logger\n    Scheme *runtime.Scheme\n}\n\nfunc (r *MemcachedReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {\n\n    // Fetch the Memcached instance.\n    memcached := &cachev1alpha1.Memcached{}\n    err := r.Get(ctx, request.NamespacedName, memcached)\n    if err != nil {\n        if errors.IsNotFound(err) {\n            return ctrl.Result{}, nil\n        }\n        return ctrl.Result{}, err\n    }\n\n    // Check if the deployment already exists, if not create a new deployment.\n    found := &appsv1.Deployment{}\n    err = r.Get(ctx, types.NamespacedName{Name: memcached.Name, Namespace: memcached.Namespace}, found)\n    if err != nil {\n         if errors.IsNotFound(err) {\n            // Define and create a new deployment.\n            dep := r.deploymentForMemcached(memcached)\n            if err = r.Create(ctx, dep); err != nil {\n                return ctrl.Result{}, err\n            }\n            return ctrl.Result{Requeue: true}, nil\n        } else {\n            return ctrl.Result{}, err\n        }\n    }\n\n    // Ensure the deployment size is the same as the spec.\n    size := memcached.Spec.Size\n    if *found.Spec.Replicas != size {\n        found.Spec.Replicas = &size\n        if err = r.Update(ctx, found); err != nil {\n            return ctrl.Result{}, err\n        }\n        return ctrl.Result{Requeue: true}, nil\n    }\n\n    // Update the Memcached status with the pod names.\n    // List the pods for this CR's deployment.\n    podList := &corev1.PodList{}\n    listOpts := []client.ListOption{\n        client.InNamespace(memcached.Namespace),\n        client.MatchingLabels(labelsForApp(memcached.Name)),\n    }\n    if err = r.List(ctx, podList, listOpts...); err != nil {\n        return ctrl.Result{}, err\n    }\n\n    // Update status.Nodes if needed.\n    podNames := getPodNames(podList.Items)\n    if !reflect.DeepEqual(podNames, memcached.Status.Nodes) {\n        memcached.Status.Nodes = podNames\n        if err := r.Status().Update(ctx, memcached); err != nil {\n            return ctrl.Result{}, err\n        }\n    }\n\n    return ctrl.Request{}, nil\n}\n\n// deploymentForMemcached returns a Deployment object for data from m.\nfunc (r *MemcachedReconciler) deploymentForMemcached(m *cachev1alpha1.Memcached) *appsv1.Deployment {\n    lbls := labelsForApp(m.Name)\n    replicas := m.Spec.Size\n\n    dep := &appsv1.Deployment{\n        ObjectMeta: metav1.ObjectMeta{\n            Name:      m.Name,\n            Namespace: m.Namespace,\n        },\n        Spec: appsv1.DeploymentSpec{\n            Replicas: &replicas,\n            Selector: &metav1.LabelSelector{\n                MatchLabels: lbls,\n            },\n            Template: corev1.PodTemplateSpec{\n                ObjectMeta: metav1.ObjectMeta{\n                    Labels: lbls,\n                },\n                Spec: corev1.PodSpec{\n                    Containers: []corev1.Container{{\n                        Image:   \"memcached:alpine\",\n                        Name:    \"memcached\",\n                        Command: []string{\"memcached\", \"-a=64\", \"-b\"},\n                        Ports: []corev1.ContainerPort{{\n                            ContainerPort: 10000,\n                            Name:          \"memcached\",\n                        }},\n                    }},\n                },\n            },\n        },\n    }\n\n    // Set Memcached instance as the owner and controller.memcac\n    // NOTE: calling SetControllerReference, and setting owner references in\n    // general, is important as it allows deleted objects to be garbage collected.\n    controllerutil.SetControllerReference(m, dep, r.Scheme)\n    return dep\n}\n\n// labelsForApp creates a simple set of labels for Memcached.\nfunc labelsForApp(name string) map[string]string {\n    return map[string]string{\"cr_name\": name}\n}\n```\n\n[memcached-testdata]:https://github.com/operator-framework/operator-sdk/tree/master/testdata/go/v4/memcached-operator\n[repo-controller-runtime]:https://github.com/kubernetes-sigs/controller-runtime\n[doc-client]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#Client\n[doc-split-client]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#DelegatingClient\n[doc-client-constr]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#New\n[code-scheme-default]:https://github.com/kubernetes-sigs/controller-runtime/blob/master/pkg/client/client.go#L51\n[doc-k8s-core]:https://pkg.go.dev/k8s.io/api/core/v1\n[doc-reconcile-reconciler]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/reconcile#Reconciler\n[doc-osdk-handle]:https://github.com/operator-framework/operator-sdk/blob/master/design/milestone-0.0.2/action-api.md#handler\n[doc-types-nsname]:https://pkg.go.dev/k8s.io/apimachinery/pkg/types#NamespacedName\n[cr-status-subresource]:https://kubernetes.io/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definitions/#status-subresource\n","frontmatter":{"title":"Controller Runtime Client API","linkTitle":"Controller Runtime Client API","weight":10},"isInternal":false,"tokens":5115,"sizeBytes":21213},{"name":"event-filtering.md","path":"website/content/en/docs/building-operators/golang/references/event-filtering.md","rawUrl":"https://raw.githubusercontent.com/operator-framework/operator-sdk/HEAD/website/content/en/docs/building-operators/golang/references/event-filtering.md","title":"References Skill","category":"anthropic-skill","format":"markdown","content":"---\ntitle: Using Predicates for Event Filtering with Operator SDK\nlinkTitle: Using Predicates for Event Filtering\nweight: 30\n---\n\n[Events][doc_event] are produced by [Sources][doc_source] assigned to resources a controller is watching. These events are transformed into Requests by [EventHandlers][doc_eventhandler] and passed to `Reconcile()`. [Predicates][doc_predicate] allow controllers to filter events before they are provided to EventHandlers. Filtering is useful because your controller may only want to handle specific types of events. Filtering also helps reduce chattiness with the API server, as `Reconcile()` is only called for events transformed by EventHandlers.\n\n## Predicate types\n\nA Predicate implements the following methods that take an event of a particular type and return true if the event should be processed by `Reconcile()`:\n\n```Go\n// Predicate filters events before enqueuing the keys.\ntype Predicate interface {\n  Create(event.CreateEvent) bool\n  Delete(event.DeleteEvent) bool\n  Update(event.UpdateEvent) bool\n  Generic(event.GenericEvent) bool\n}\n\n// Funcs implements Predicate.\ntype Funcs struct {\n  CreateFunc func(event.CreateEvent) bool\n  DeleteFunc func(event.DeleteEvent) bool\n  UpdateFunc func(event.UpdateEvent) bool\n  GenericFunc func(event.GenericEvent) bool\n}\n```\n\nFor example, all Create events for any watched resource will be passed to `Funcs.Create()` and filtered out if the method evaluates to `false`. If you do not register a Predicate method for a particular type, events of that type will not be filtered.\n\nAll event types contain Kubernetes [metadata][doc_object_metadata] about the object that triggered the event, and the object itself. Predicate logic uses these data to make decisions about what should be filtered. Some event types include other fields pertaining to the semantics of that event. For example, `event.UpdateEvent` includes both old and new metadata and objects:\n\n```Go\ntype UpdateEvent struct {\n  // ObjectOld is the object from the event.\n  ObjectOld runtime.Object\n\n  // ObjectNew is the object from the event.\n  ObjectNew runtime.Object\n}\n```\n\nYou can find all type definitions in the `event` package [documentation][doc_event].\n\n## Using Predicates\n\nAny number of Predicates can be set for a controller via the builder method `WithEventFilter()`, which will filter an event if any of those Predicates evaluates to `false`. This first example is an implementation of a `memcached-operator` controller that simply filters Delete events on Pods that have been confirmed deleted; the controller receives all Delete events that occur, and we may only care about resources that have not been completely deleted:\n\n```Go\nimport (\n\t\"context\"\n\n\t\"github.com/go-logr/logr\"\n\tcorev1 \"k8s.io/api/core/v1\"\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\tctrl \"sigs.k8s.io/controller-runtime\"\n\t\"sigs.k8s.io/controller-runtime/pkg/client\"\n\t\"sigs.k8s.io/controller-runtime/pkg/event\"\n\t\"sigs.k8s.io/controller-runtime/pkg/predicate\"\n\n\tcachev1alpha1 \"github.com/example/app-operator/api/v1alpha1\"\n)\n\n...\n\nfunc ignoreDeletionPredicate() predicate.Predicate {\n\treturn predicate.Funcs{\n\t\tUpdateFunc: func(e event.UpdateEvent) bool {\n\t\t\t// Ignore updates to CR status in which case metadata.Generation does not change\n\t\t\treturn e.ObjectOld.GetGeneration() != e.ObjectNew.GetGeneration()\n\t\t},\n\t\tDeleteFunc: func(e event.DeleteEvent) bool {\n\t\t\t// Evaluates to false if the object has been confirmed deleted.\n\t\t\treturn !e.DeleteStateUnknown\n\t\t},\n\t}\n}\n\nfunc (r *MemcachedReconciler) SetupWithManager(mgr ctrl.Manager) error {\n\treturn ctrl.NewControllerManagedBy(mgr).\n\t\tFor(&cachev1alpha1.Memcached{}).\n\t\tOwns(&corev1.Pod{}).\n\t\tWithEventFilter(ignoreDeletionPredicate()).\n\t\tComplete(r)\n}\n  ...\n}\n```\n\n## Use cases\n\nPredicates are not necessary for many operators, although filtering reduces the amount of chatter to the API server from `Reconcile()`. They are particularly useful for controllers that watch resources cluster-wide, i.e. without a namespace.\n\n[doc_event]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/event\n[doc_source]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/source#Source\n[doc_eventhandler]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/handler#EventHandler\n[doc_predicate]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/predicate\n[doc_object_metadata]:https://pkg.go.dev/k8s.io/apimachinery/pkg/apis/meta/v1#Object\n","frontmatter":{"title":"Using Predicates for Event Filtering with Operator SDK","linkTitle":"Using Predicates for Event Filtering","weight":30},"isInternal":false,"tokens":998,"sizeBytes":4404},{"name":"logging.md","path":"website/content/en/docs/building-operators/golang/references/logging.md","rawUrl":"https://raw.githubusercontent.com/operator-framework/operator-sdk/HEAD/website/content/en/docs/building-operators/golang/references/logging.md","title":"References Skill","category":"anthropic-skill","format":"markdown","content":"---\ntitle: Logging\nlinkTitle: Logging\nweight: 20\n---\n\n# Overview\n\nOperator SDK-generated operators use the [`logr`][godoc_logr] interface to log. This log interface has several backends such as [`zap`][repo_zapr], which the SDK uses in generated code by default. [`logr.Logger`][godoc_logr_logger] exposes structured logging methods that help create machine-readable logs and adding a wealth of information to log records.\n\n## Default zap logger\n\nOperator SDK uses a `zap`-based `logr` backend when scaffolding new projects. To assist with configuring and using this logger, the SDK includes several helper functions.\n\nIn the simple example below, we add the zap flagset to the operator's command line flags with `BindFlags()`, and then set the controller-runtime logger with `zap.Options{}`.\n\nBy default, `zap.Options{}` will return a logger that is ready for production use. It uses a JSON encoder, logs starting at the `info` level. To customize the default behavior, users can use the zap flagset and specify flags on the command line. The zap flagset includes the following flags that can be used to configure the logger:\n\n* `--zap-devel`: Development Mode defaults(encoder=consoleEncoder,logLevel=Debug,stackTraceLevel=Warn)\n\t\t\t  Production Mode defaults(encoder=jsonEncoder,logLevel=Info,stackTraceLevel=Error)\n* `--zap-encoder`: Zap log encoding ('json' or 'console')\n* `--zap-log-level`: Zap Level to configure the verbosity of logging. Can be one of 'debug', 'info', 'error',\n\t\t\t       or any integer value > 0 which corresponds to custom debug levels of increasing verbosity\")\n* `--zap-stacktrace-level`: Zap Level at and above which stacktraces are captured (one of 'info' or 'error')\n\nConsult the controller-runtime [godocs][logging_godocs] for more detailed flag information.\n\n### A simple example\n\nOperators set the logger for all operator logging in `main.go`. To illustrate how this works, try out this simple example:\n\n```Go\npackage main\n\nimport (\n\t\"sigs.k8s.io/controller-runtime/pkg/log/zap\"\n\tlogf \"sigs.k8s.io/controller-runtime/pkg/log\"\n)\n\nvar globalLog = logf.Log.WithName(\"global\")\nfunc main() {\n\t// Add the zap logger flag set to the CLI. The flag set must\n\t// be added before calling flag.Parse().\n\topts := zap.Options{}\n\topts.BindFlags(flag.CommandLine)\n\tflag.Parse()\n\n\tlogger := zap.New(zap.UseFlagOptions(&opts))\n\tlogf.SetLogger(logger)\n\n\tscopedLog := logf.Log.WithName(\"scoped\")\n\n\tglobalLog.Info(\"Printing at INFO level\")\n\tglobalLog.V(1).Info(\"Printing at DEBUG level\")\n\tscopedLog.Info(\"Printing at INFO level\")\n\tscopedLog.V(1).Info(\"Printing at DEBUG level\")\n}\n```\n\n#### Output using the defaults\n```console\n$ go run main.go\nINFO[0000] Running the operator locally in namespace default.\n{\"level\":\"info\",\"ts\":1587741740.407766,\"logger\":\"global\",\"msg\":\"Printing at INFO level\"}\n{\"level\":\"info\",\"ts\":1587741740.407855,\"logger\":\"scoped\",\"msg\":\"Printing at INFO level\"}\n```\n\n#### Output overriding the log level to 1 (debug)\n```console\n$ go run main.go --zap-log-level=debug\nINFO[0000] Running the operator locally in namespace default.\n{\"level\":\"info\",\"ts\":1587741837.602911,\"logger\":\"global\",\"msg\":\"Printing at INFO level\"}\n{\"level\":\"debug\",\"ts\":1587741837.602964,\"logger\":\"global\",\"msg\":\"Printing at DEBUG level\"}\n{\"level\":\"info\",\"ts\":1587741837.6029708,\"logger\":\"scoped\",\"msg\":\"Printing at INFO level\"}\n{\"level\":\"debug\",\"ts\":1587741837.602973,\"logger\":\"scoped\",\"msg\":\"Printing at DEBUG level\"}\n```\n## Custom zap logger\n\nIn order to use a custom zap logger, [`zap`][controller_runtime_zap] from controller-runtime can be utilized to wrap it in a `logr` implementation.\n\nBelow is an example illustrating the use of [`zap-logfmt`][logfmt_repo] in logging.\n\n### Example\n\nIn your `main.go` file, replace the current implementation for logs inside the `main` function:\n\n```Go\n...\n// Add the zap logger flag set to the CLI. The flag set must\n// be added before calling flag.Parse().\n\topts := zap.Options{}\n\topts.BindFlags(flag.CommandLine)\n\tflag.Parse()\n\n\tlogger := zap.New(zap.UseFlagOptions(&opts))\n\tlogf.SetLogger(logger)\n...\n```\n\nWith:\n\n```Go\n\timport(\n\t...\n\tzaplogfmt \"github.com/sykesm/zap-logfmt\"\n\tuzap \"go.uber.org/zap\"\n\t\"go.uber.org/zap/zapcore\"\n\tlogf \"sigs.k8s.io/controller-runtime/pkg/log\"\n\t\"sigs.k8s.io/controller-runtime/pkg/log/zap\"\n\t...\n)\n\tconfigLog := uzap.NewProductionEncoderConfig()\n\tconfigLog.EncodeTime = func(ts time.Time, encoder zapcore.PrimitiveArrayEncoder) {\n\t\tencoder.AppendString(ts.UTC().Format(time.RFC3339Nano))\n\t}\n\tlogfmtEncoder := zaplogfmt.NewEncoder(configLog)\n\n\t// Construct a new logr.logger.\n\tlogger := zap.New(zap.UseDevMode(true), zap.WriteTo(os.Stdout), zap.Encoder(logfmtEncoder))\n\tlogf.SetLogger(logger)\n```\n\n**NOTE**: For this example, you will need to add the module `\"github.com/sykesm/zap-logfmt\"` to your project. Run `go get -u github.com/sykesm/zap-logfmt`.\n\n#### Output using custom zap logger\n\n```console\n$ go run main.go\nts=2020-04-30T20:35:59.551268Z level=info logger=global msg=\"Printing at INFO level\"\nts=2020-04-30T20:35:59.551314Z level=debug logger=global msg=\"Printing at DEBUG level\"\nts=2020-04-30T20:35:59.551318Z level=info logger=scoped msg=\"Printing at INFO level\"\nts=2020-04-30T20:35:59.55132Z level=debug logger=scoped msg=\"Printing at DEBUG level\"\n```\n\nBy using `sigs.k8s.io/controller-runtime/pkg/log`, your logger is propagated through `controller-runtime`. Any logs produced by `controller-runtime` code will be through your logger, and therefore have the same formatting and destination.\n\n### Setting flags when running locally\n\nWhen running locally with `make run ENABLE_WEBHOOKS=false`, you can use the `ARGS` var to pass additional flags to your operator, including the zap flags. For example:\n\n```console\n$ make run ARGS=\"--zap-encoder=console\" ENABLE_WEBHOOKS=false\n```\nMake sure to have your `run` target to take `ARGS` as shown below in `Makefile`.\n\n```makefile\n# Run against the configured Kubernetes cluster in ~/.kube/config\nrun: manifests generate fmt vet\n\tgo run ./main.go $(ARGS)\n```\n\n### Setting flags when deploying to a cluster\n\nWhen deploying your operator to a cluster you can set additional flags using an `args` array in your operator's `container` spec in the file `config/default/manager_metrics_patch.yaml` For example:\n\n```yaml\n- op: add\n  path: /spec/template/spec/containers/0/args/0\n  value: --zap-log-level=debug \n- op: add\n  path: /spec/template/spec/containers/0/args/0\n  value: --zap-encoder=console\n```\n\n## Creating a structured log statement\n\nThere are two ways to create structured logs with `logr`. You can create new loggers using `log.WithValues(keyValues)` that include `keyValues`, a list of key-value pair `interface{}`'s, in each log record. Alternatively you can include `keyValues` directly in a log statement, as all `logr` log statements take some message and `keyValues`. The signature of `logr.Error()` has an `error`-type parameter, which can be `nil`.\n\nAn example from [`memcached_controller.go`][code_memcached_controller]:\n\n```Go\npackage memcached\n\nimport (\n  ctrllog \"sigs.k8s.io/controller-runtime/pkg/log\"\n)\n\n\n// MemcachedReconciler reconciles a Memcached object\ntype MemcachedReconciler struct {\n\tclient.Client\n\tLog    logr.Logger\n\tScheme *runtime.Scheme\n}\n\nfunc (r *MemcachedReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {\n\tlog := ctrllog.FromContext(ctx)\n\n\t// Fetch the Memcached instance\n\tmemcached := &cachev1alpha1.Memcached{}\n\terr := r.Get(ctx, req.NamespacedName, memcached)\n\tif err != nil {\n\t\tif errors.IsNotFound(err) {\n\t\t\t// Request object not found, could have been deleted after reconcile request.\n\t\t\t// Owned objects are automatically garbage collected. For additional cleanup logic use finalizers.\n\t\t\t// Return and don't requeue\n\t\t\tlog.Info(\"Memcached resource not found. Ignoring since object must be deleted\")\n\t\t\treturn ctrl.Result{}, nil\n\t\t}\n\t\t// Error reading the object - requeue the request.\n\t\tlog.Error(err, \"Failed to get Memcached\")\n\t\treturn ctrl.Result{}, err\n\t}\n\n\t// Check if the deployment already exists, if not create a new one\n\tfound := &appsv1.Deployment{}\n\terr = r.Get(ctx, types.NamespacedName{Name: memcached.Name, Namespace: memcached.Namespace}, found)\n\tif err != nil && errors.IsNotFound(err) {\n\t\t// Define a new deployment\n\t\tdep := r.deploymentForMemcached(memcached)\n\t\tlog.Info(\"Creating a new Deployment\", \"Deployment.Namespace\", dep.Namespace, \"Deployment.Name\", dep.Name)\n\t\terr = r.Create(ctx, dep)\n\t\tif err != nil {\n\t\t\tlog.Error(err, \"Failed to create new Deployment\", \"Deployment.Namespace\", dep.Namespace, \"Deployment.Name\", dep.Name)\n\t\t\treturn ctrl.Result{}, err\n\t\t}\n\t\t// Deployment created successfully - return and requeue\n\t\treturn ctrl.Result{Requeue: true}, nil\n\t} else if err != nil {\n\t\tlog.Error(err, \"Failed to get Deployment\")\n\t\treturn ctrl.Result{}, err\n\t}\n\n\t...\n}\n```\n\nLog records will look like the following (from `log.Error()` above):\n\n```\n2020-04-27T09:14:15.939-0400\tERROR\tcontrollers.Memcached\tFailed to create new Deployment\t{\"memcached\": \"default/memcached-sample\", \"Deployment.Namespace\": \"default\", \"Deployment.Name\": \"memcached-sample\"}\n```\n\n## Non-default logging\n\nIf you do not want to use `logr` as your logging tool, you can remove `logr`-specific statements without issue from your operator's code, including the `logr` setup code in `main.go`, and add your own. Note that removing `logr` setup code will prevent `controller-runtime` from logging.\n\n\n[godoc_logr]:https://pkg.go.dev/github.com/go-logr/logr\n[repo_zapr]:https://pkg.go.dev/github.com/go-logr/zapr\n[godoc_logr_logger]:https://pkg.go.dev/github.com/go-logr/logr#Logger\n[code_memcached_controller]: https://github.com/operator-framework/operator-sdk/blob/v1.2.0/testdata/go/memcached-operator/controllers/memcached_controller.go\n[logfmt_repo]:https://github.com/jsternberg/zap-logfmt\n[controller_runtime_zap]:https://github.com/kubernetes-sigs/controller-runtime/tree/master/pkg/log/zap\n[logging_godocs]: https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/log/zap#Options.BindFlags\n","frontmatter":{"title":"Logging","linkTitle":"Logging","weight":20},"isInternal":false,"tokens":2541,"sizeBytes":10005},{"name":"markers.md","path":"website/content/en/docs/building-operators/golang/references/markers.md","rawUrl":"https://raw.githubusercontent.com/operator-framework/operator-sdk/HEAD/website/content/en/docs/building-operators/golang/references/markers.md","title":"References Skill","category":"anthropic-skill","format":"markdown","content":"---\ntitle: API Markers\nlinkTitle: API Markers\nweight: 40\n---\n\nThis document describes [code markers][markers] supported by the SDK.\n\n## ClusterServiceVersion markers\n\nThis section details ClusterServiceVersion (CSV) code markers and lists available markers.\n\n**Note:** CSV markers can only be used in Go Operator projects. Annotations for Ansible and Helm Operator projects will be added in the future.\n\n### Usage\n\nAll CSV markers have the prefix `+operator-sdk:csv`.\n\n#### `+operator-sdk:csv:customresourcedefinitions`\n\nThese markers populate [owned `customresourcedefinitions`][csv-crds] in your CSV.\n\nPossible type-level markers:\n- `+operator-sdk:csv:customresourcedefinitions:displayName=\"some display name\"`\n\t- Configures the kind's display name.\n- `+operator-sdk:csv:customresourcedefinitions:resources={{Kind1,v1alpha1,dns-name-1},{Kind2,v1,\"dns-name-2\"},...}`\n\t- Configures the kind's resources.\n- `+operator-sdk:csv:customresourcedefinitions:order=1`\n\t- Configures the order of this type in the list. Markers with order omitted have the highest order, i.e. are at the end of the list. If more than one marker has the same order, the corresponding descriptions will be sorted alphabetically and placed above others with higher orders. Pre-existing list elements in the CSV will be appended to the set of other elements in the order corresponding to its index.\n\nPossible field-level markers, all of which must contain the `type=[spec,status]` key-value pair:\n- `+operator-sdk:csv:customresourcedefinitions:type=[spec,status],displayName=\"some field display name\"`\n\t- Configures the field's display name.\n- `+operator-sdk:csv:customresourcedefinitions:type=[spec,status],xDescriptors={\"urn:alm:descriptor:com.tectonic.ui:podCount\",\"urn:alm:descriptor:io.kubernetes:custom\"}`\n\t- Configures the field's x-descriptors.\n- `+operator-sdk:csv:customresourcedefinitions:type=[spec,status],order=1`\n\t- Configures the order of this type in the list. Markers with order omitted have the highest order, i.e. are at the end of the list. If more than one marker has the same order, the corresponding descriptions will be sorted alphabetically and placed above others with higher orders.\n\nTop-level `kind`, `name`, and `version` fields are parsed from API code.\nAll `description` fields are parsed from type declaration and `struct` type field comments.\nAll `path` fields are parsed from a field's JSON tag and merged with parent\nfield path's in dot-hierarchy notation.\n\n##### x-descriptors\n\nCheck out the [descriptor reference][csv-x-desc] for available `x-descriptors` paths.\n\n#### Examples\n\nThese examples assume `Memcached`, `MemcachedSpec`, and `MemcachedStatus` are the example projects' kind, spec, and status.\n\n1. Set a `displayName` and `resources` for a `customresourcedefinitions` kind entry:\n\n\t```go\n\t//+operator-sdk:csv:customresourcedefinitions:displayName=\"Memcached App\",resources={{Pod,v1,memcached-runner},{Deployment,v1,memcached-deployment}}\n\ttype Memcached struct {\n\t\tmetav1.TypeMeta   `json:\",inline\"`\n\t\tmetav1.ObjectMeta `json:\"metadata,omitempty\"`\n\n\t\tSpec   MemcachedSpec   `json:\"spec,omitempty\"`\n\t\tStatus MemcachedStatus `json:\"status,omitempty\"`\n\t}\n\t```\n\n2. Set `displayName`, `path`, `xDescriptors`, and `description` on a field for a `customresourcedefinitions.specDescriptors` entry:\n\n\t```go\n\ttype MemcachedSpec struct {\n\t\t// Size is the size of the memcached deployment. <-- This will become Size's specDescriptors.description.\n\t\t//+operator-sdk:csv:customresourcedefinitions:type=spec,displayName=\"Number of pods\",xDescriptors={\"urn:alm:descriptor:com.tectonic.ui:podCount\",\"urn:alm:descriptor:io.kubernetes:custom\"}\n\t\tSize int32 `json:\"size\"` // <-- Size's specDescriptors.path is inferred from this JSON tag.\n\t}\n\t```\n\n3. Let the SDK infer all unmarked paths on a field for a `customresourcedefinitions.specDescriptors` entry:\n\n\t```go\n\ttype MemcachedSpec struct {\n\t\t// Size is the size of the memcached deployment.\n\t\t//+operator-sdk:csv:customresourcedefinitions:type=spec\n\t\tSize int32 `json:\"size\"`\n\t}\n\t```\n\n\tThe SDK uses the `Size` fields' `json` tag name as `path`, `Size` as `displayName`, and field comments as `description`.\n\n4. A comprehensive example:\n\t- Infer `path`, `description`, `displayName`, and `x-descriptors` for `specDescriptors` and `statusDescriptors` entries.\n\t- Create three `resources` entries each with `kind`, `version`, and `name` values.\n\n\t```go\n\t// Represents a cluster of Memcached apps\n\t//+operator-sdk:csv:customresourcedefinitions:displayName=\"Memcached App\",resources={{Pod,v1,memcached-runner},{Deployment,v1,memcached-deployment}}\n\ttype Memcached struct {\n\t\tmetav1.TypeMeta   `json:\",inline\"`\n\t\tmetav1.ObjectMeta `json:\"metadata,omitempty\"`\n\n\t\tSpec   MemcachedSpec   `json:\"spec,omitempty\"`\n\t\tStatus MemcachedStatus `json:\"status,omitempty\"`\n\t}\n\n\ttype MemcachedSpec struct {\n\t\tPods MemcachedPods `json:\"pods\"`\n\t}\n\n\ttype MemcachedStatus struct {\n\t\tPods \t\t MemcachedPods `json:\"podStatuses\"`\n\t\t//+operator-sdk:csv:customresourcedefinitions:type=status,displayName=\"Pod Count\",xDescriptors=\"urn:alm:descriptor:com.tectonic.ui:podCount\"\n\t\tPodCount int \t\t\t\t\t `json:\"podCount\"`\n\t}\n\n\ttype MemcachedPods struct {\n\t\t// Size is the size of the memcached deployment.\n\t\t//+operator-sdk:csv:customresourcedefinitions:type=spec\n\t\t//+operator-sdk:csv:customresourcedefinitions:type=status\n\t\tSize int32 `json:\"size\"`\n\t}\n\t```\n\n\tThe generated `customresourcedefinitions` will look like:\n\n\t```yaml\n\tcustomresourcedefinitions:\n\t  owned:\n\t  - description: Represents a cluster of Memcached apps\n\t    displayName: Memcached App\n\t    kind: Memcached\n\t    name: memcacheds.cache.example.com\n\t    version: v1alpha1\n\t    resources:\n\t    - kind: Deployment\n\t      name: memcached-deployment\n\t      version: v1\n\t    - kind: Pod\n\t      name: memcached-runner\n\t      version: v1\n\t    specDescriptors:\n\t    - description: The desired number of member Pods for the deployment.\n\t      displayName: Size\n\t      path: pods.size\n\t    statusDescriptors:\n\t    - description: The desired number of member Pods for the deployment.\n\t      displayName: Size\n\t      path: podStatuses.size\n\t    - displayName: Size\n\t      path: podCount\n\t      x-descriptors:\n\t      - 'urn:alm:descriptor:com.tectonic.ui:podCount'\n\t```\n\n\n## Deprecated markers\n\nMarkers supported by `operator-sdk` prior to v1.0.0 are deprecated.\nYou can migrate to the new marker system by running the following script:\n\n```console\n$ curl -sSLo migrate-markers.sh https://raw.githubusercontent.com/operator-framework/operator-sdk/master/hack/generate/migrate-markers.sh\n$ chmod +x ./migrate-markers.sh\n$ ./migrate-markers.sh path/to/*_types.go\n```\n\n\n[markers]:https://pkg.go.dev/sigs.k8s.io/controller-tools/pkg/markers\n[cli-gen-kustomize-manifests]:/docs/cli/operator-sdk_generate_kustomize_manifests\n[csv-x-desc]:https://github.com/openshift/console/blob/master/frontend/packages/operator-lifecycle-manager/src/components/descriptors/reference/reference.md\n[csv-spec]:https://github.com/operator-framework/operator-lifecycle-manager/blob/e0eea22/doc/design/building-your-csv.md\n[csv-crds]:https://github.com/operator-framework/operator-lifecycle-manager/blob/master/doc/design/building-your-csv.md#your-custom-resource-definitions\n","frontmatter":{"title":"API Markers","linkTitle":"API Markers","weight":40},"isInternal":false,"tokens":1821,"sizeBytes":7216},{"name":"openapi-validation.md","path":"website/content/en/docs/building-operators/golang/references/openapi-validation.md","rawUrl":"https://raw.githubusercontent.com/operator-framework/operator-sdk/HEAD/website/content/en/docs/building-operators/golang/references/openapi-validation.md","title":"References Skill","category":"anthropic-skill","format":"markdown","content":"---\ntitle: OpenAPI validation\nlinkTitle: OpenAPI validation\nweight: 70\n---\n\nOpenAPIv3 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.\n\n[Markers][markers] (annotations) are available to configure validations for your API. These markers will always have a `+kubebuilder:validation` prefix.\n\nUsage of markers in API code is discussed in the kubebuilder [CRD generation][generating-crd] and [marker][markers] documentation. A full list of OpenAPIv3 validation markers can be found [here][crd-markers].\n\nTo learn more about OpenAPI v3.0 validation schemas in CRDs, refer to the [Kubernetes Documentation][doc-validation-schema].\n\n[markers]: https://book.kubebuilder.io/reference/markers.html\n[crd-markers]: https://book.kubebuilder.io/reference/markers/crd-validation.html\n[generating-crd]: https://book.kubebuilder.io/reference/generating-crd.html\n[doc-validation-schema]: https://kubernetes.io/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definitions/#specifying-a-structural-schema\n","frontmatter":{"title":"OpenAPI validation","linkTitle":"OpenAPI validation","weight":70},"isInternal":false,"tokens":270,"sizeBytes":1178},{"name":"proxy-vars.md","path":"website/content/en/docs/building-operators/golang/references/proxy-vars.md","rawUrl":"https://raw.githubusercontent.com/operator-framework/operator-sdk/HEAD/website/content/en/docs/building-operators/golang/references/proxy-vars.md","title":"References Skill","category":"anthropic-skill","format":"markdown","content":"---\ntitle: Proxy Friendly Operators\nlinkTitle: Proxy Vars\nweight: 20\n---\n\nProxy-friendly Operators should inspect their environment for the\nstandard proxy variables (`HTTPS_PROXY`, `HTTP_PROXY`, and `NO_PROXY`)\nand pass the values to Operands.\n\nOperator-lib provides a helper function `proxy.ReadProxyVarsFromEnv`\nthat does this inspection, all you need to do is append the\nresults to the Operand environments.\n\nUsing the memcached tutorial as an example, add the following to the\nReconcile loop in `controllers/memcached_controller.go`:\n\n\n```go\nimport (\n  ...\n   \"github.com/operator-framework/operator-lib/proxy\"\n)\n\n\nfor i, container := range dep.Spec.Template.Spec.Containers {\n\t\tdep.Spec.Template.Spec.Containers[i].Env = append(container.Env, proxy.ReadProxyVarsFromEnv()...)\n}\n```\n\nYou can set the environment variable on the Operator deployment. Using the memcached tutorial, edit config/manager/manager.yaml:\n\n```yaml\ncontainers:\n - args:\n   - --leader-elect\n   - --leader-election-id=go-proxy-demo\n   image: controller:latest\n   name: manager\n   env:\n     - name: \"HTTP_PROXY\"\n       value: \"http_proxy_test\"\n```\n","frontmatter":{"title":"Proxy Friendly Operators","linkTitle":"Proxy Vars","weight":20},"isInternal":false,"tokens":259,"sizeBytes":1122}],"systemPromptSnippet":"<yakaai_skills repo=\"operator-framework/operator-sdk\">\n<!-- File: website/content/en/docs/building-operators/golang/references/_index.md (Tokens: ~19 | Category: anthropic-skill) -->\n---\ntitle: Go-based Operator Reference\nlinkTitle: Reference\nweight: 100\n---\n\n<!-- File: website/content/en/docs/building-operators/golang/references/client.md (Tokens: ~5115 | Category: anthropic-skill) -->\n---\ntitle: Controller Runtime Client API\nlinkTitle: Controller Runtime Client API\nweight: 10\n---\n\n## Overview\n\nThe [`controller-runtime`][repo-controller-runtime] library provides various abstractions to watch and reconcile resources in a Kubernetes cluster via CRUD (Create, Update, Delete, as well as Get and List in this case) operations. Operators use at least one controller to perform a coherent set of tasks within a cluster, usually through a combination of CRUD operations. The Operator SDK uses controller-runtime's [Client][doc-client] interface, which provides the interface for these operations.\n\ncontroller-runtime defines several interfaces used for cluster interaction:\n- `client.Client`: implementers perform CRUD operations on a Kubernetes cluster.\n- `manager.Manager`: manages shared dependencies, such as Caches and Clients.\n- `reconcile.Reconciler`: compares provided state with actual cluster state and updates the cluster on finding state differences using a Client.\n\nClients are the focus of this document. A separate document will discuss Managers.\n\n**Note:** this document uses parts of the sample [`memcached-operator`][memcached-testdata] for example code.\nImport paths may be different for brevity.\n\n## Client Usage\n\n### Default Client\n\nThe SDK relies on a `manager.Manager` to create a `client.Client` interface that performs Create, Update, Delete, Get, and List operations within a `reconcile.Reconciler`'s Reconcile function. The SDK will generate code to create a Manager, which holds a Cache and a Client to be used in CRUD operations and communicate with the API server. By default a Controller's Reconciler will be populated with the Manager's Client which is a [split-client][doc-split-client].\n\nThe following code, found in `controllers/memcached_controller.go`, demonstrates how the Manager's client is passed to a reconciler.\n\n```Go\nimport (\n\tappsv1 \"k8s.io/api/apps/v1\"\n\tctrl \"sigs.k8s.io/controller-runtime\"\n\n\tcachev1alpha1 \"github.com/example/memcached-operator/api/v1alpha1\"\n)\n\nfunc (r *MemcachedReconciler) SetupWithManager(mgr ctrl.Manager) error {\n\treturn ctrl.NewControllerManagedBy(mgr). // mgr's Client is passed to r.\n\t\tFor(&cachev1alpha1.Memcached{}).\n\t\tOwns(&appsv1.Deployment{}).\n\t\tComplete(r)\n}\n\ntype MemcachedReconciler struct {\n    client.Client // Populated above from a manager.Manager.\n\n    Log    logr.Logger\n    Scheme *runtime.Scheme\n}\n```\n\nA split client reads (Get and List) from the Cache and writes (Create, Update, Delete) to the API server. Reading from the Cache significantly reduces request load on the API server; as long as the Cache is updated by the API server, read operations are eventually consistent.\n\n### Non-default Client\n\nAn operator developer may wish to create their own Client that serves read requests(Get List) from the API server instead of the cache, for example. controller-runtime provides a [constructor][doc-client-constr] for Clients:\n\n```Go\n// New returns a new Client using the provided config and Options.\nfunc New(config *rest.Config, options client.Options) (client.Client, error)\n```\n\n`client.Options` allow the caller to specify how the new Client should communicate with the API server.\n\n```Go\n// Options are creation options for a Client\ntype Options struct {\n    // Scheme, if provided, will be used to map go structs to GroupVersionKinds\n    Scheme *runtime.Scheme\n\n    // Mapper, if provided, will be used to map GroupVersionKinds to Resources\n    Mapper meta.RESTMapper\n}\n```\n\nExample:\n\n```Go\nimport (\n    \"sigs.k8s.io/controller-runtime/pkg/client/config\"\n    \"sigs.k8s.io/controller-runtime/pkg/client\"\n)\n\ncfg, err := config.GetConfig()\n...\nc, err := client.New(cfg, client.Options{})\n...\n```\n\n**Note**: defaults are set by `client.New` when Options are empty. The default [scheme][code-scheme-default] will have the [core][doc-k8s-core] Kubernetes resource types registered. The caller *must* set a scheme that has custom operator types registered for the new Client to recognize these types.\n\nCreating a new Client is not usually necessary nor advised, as the default Client is sufficient for most use cases.\n\n### Reconcile and the Client API\n\nA Reconciler implements the [`reconcile.Reconciler`][doc-reconcile-reconciler] interface, which exposes the Reconcile method. Reconcilers are added to a corresponding Controller for a Kind; Reconcile is called in response to cluster or external Events, with a `reconcile.Request` object argument, to read and write cluster state by the Controller, and returns a `ctrl.Result`. SDK Reconcilers have access to a Client in order to make Kubernetes API calls.\n\n```Go\n// MemcachedReconciler reconciles a Memcached object\ntype MemcachedReconciler struct {\n    // client, initialized using mgr.Client() above, is a split client\n    // that reads objects from the cache and writes to the apiserver\n    client.Client\n\n    Log    logr.Logger\n\n    // scheme defines methods for serializing and deserializing API objects,\n    // a type registry for converting group, version, and kind information\n    // to and from Go schemas, and mappings between Go schemas of different\n    // versions. A scheme is the foundation for a versioned API and versioned\n    // configuration over time.\n    Scheme *runtime.Scheme\n}\n\n// Reconcile watches for Events and reconciles cluster state with desired\n// state defined in the method body.\n// The Controller will requeue the Request to be processed again if an error\n// is non-nil or Result.Requeue is true, otherwise upon completion it will\n// remove the work from the queue.\nfunc (r *MemcachedReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error)\n```\n\nReconcile is where Controller business logic lives, i.e. where Client API calls are made via `MemcachedReconciler.client`. A `client.Client` implementer performs the following operations:\n\n#### Get\n\n```Go\n// Get retrieves an API object for a given object key from the Kubernetes cluster\n// and stores it in obj.\nfunc (c Client) Get(ctx context.Context, key client.ObjectKey, obj client.Object) error\n```\n\n**Note**: A `client.ObjectKey` is simply an alias for [`types.NamespacedName`][doc-types-nsname].\n\nExample:\n\n```Go\nimport (\n    \"context\"\n\n    ctrl \"sigs.k8s.io/controller-runtime\"\n\n    cachev1alpha1 \"github.com/example/memcached-operator/api/v1alpha1\"\n)\n\nfunc (r *MemcachedReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {\n    ...\n\n    memcached := &cachev1alpha1.Memcached{}\n    err := r.Get(ctx, request.NamespacedName, memcached)\n\n    ...\n}\n```\n\n#### List\n\n```Go\n// List retrieves a list of objects for a given namespace and list options\n// and stores the list in obj.\nfunc (c Client) List(ctx context.Context, list client.Object, opts ...client.ListOption) error\n```\n\nA `client.ListOption` is an interface that sets [`client.ListOptions`][list-options] fields. A `client.ListOption` is created by using one of the provided implementations: [`MatchingLabels`][matching-labels], [`MatchingFields`][matching-fields], [`InNamespace`][in-namespace].\n\nExample:\n\n```Go\nimport (\n    \"context\"\n    \"fmt\"\n\n    \"k8s.io/api/core/v1\"\n    ctrl \"sigs.k8s.io/controller-runtime\"\n    \"sigs.k8s.io/controller-runtime/pkg/client\"\n)\n\nfunc (r *MemcachedReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {\n    ...\n\n    // Return all pods in the request namespace with a label of `instance=<name>`\n    // and phase `Running`.\n    podList := &v1.PodList{}\n    opts := []client.ListOption{\n        client.InNamespace(request.NamespacedName.Namespace),\n        client.MatchingLabels{\"instance\": request.NamespacedName.Name},\n        client.MatchingFields{\"status.phase\": \"Running\"},\n    }\n    err := r.List(ctx, podList, opts...)\n\n    ...\n}\n```\n\n[list-options]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#ListOptions\n[matching-labels]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#MatchingLabels\n[matching-fields]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#MatchingFields\n[in-namespace]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#InNamespace\n\n#### Create\n\n```Go\n// Create saves the object obj in the Kubernetes cluster.\n// Returns an error\nfunc (c Client) Create(ctx context.Context, obj client.Object, opts ...client.CreateOption) error\n```\n\nA `client.CreateOption` is an interface that sets [`client.CreateOptions`][create-options] fields. A `client.CreateOption` is created by using one of the provided implementations: [`DryRunAll`][dry-run-all], [`ForceOwnership`][force-ownership]. Generally these options are not needed.\n\nExample:\n\n```Go\nimport (\n    \"context\"\n\n    \"k8s.io/api/apps/v1\"\n    ctrl \"sigs.k8s.io/controller-runtime\"\n)\n\nfunc (r *MemcachedReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {\n    ...\n\n    dep := &v1.Deployment{ // Any cluster object you want to create.\n        ...\n    }\n    err := r.Create(ctx, dep)\n\n    ...\n}\n```\n\n[create-options]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#CreateOptions\n\n#### Update\n\n```Go\n// Update updates the given obj in the Kubernetes cluster. obj must be a\n// struct pointer so that obj can be updated with the content returned\n// by the API server. Update does *not* update the resource's status\n// subresource\nfunc (c Client) Update(ctx context.Context, obj client.Object, opts ...client.UpdateOption) error\n```\n\nA `client.UpdateOption` is an interface that sets [`client.UpdateOptions`][update-options] fields. A `client.UpdateOption` is created by using one of the provided implementations: [`DryRunAll`][dry-run-all], [`ForceOwnership`][force-ownership]. Generally these options are not needed.\n\nExample:\n\n```Go\nimport (\n    \"context\"\n\n    \"k8s.io/api/apps/v1\"\n    ctrl \"sigs.k8s.io/controller-runtime\"\n)\n\nfunc (r *MemcachedReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {\n    ...\n\n    dep := &v1.Deployment{}\n    err := r.Get(ctx, request.NamespacedName, dep)\n\n    ...\n\n    dep.Spec.Selector.MatchLabels[\"is_running\"] = \"true\"\n    err := r.Update(ctx, dep)\n\n    ...\n}\n```\n\n[update-options]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#UpdateOptions\n\n#### Patch\n\n```Go\n// Patch patches the given obj in the Kubernetes cluster. obj must be a\n// struct pointer so that obj can be updated with the content returned by the Server.\nfunc (c Client) Patch(ctx context.Context, obj client.Object, patch client.Patch, opts ...client.PatchOption) error\n```\n\nA `client.PatchOption` is an interface that sets [`client.PatchOptions`][patch-options] fields. A `client.PatchOption` is created by using one of the provided implementations: [`DryRunAll`][dry-run-all], [`ForceOwnership`][force-ownership]. Generally these options are not needed.\n\nExample:\n\n```Go\nimport (\n    \"context\"\n\n    \"k8s.io/api/apps/v1\"\n    ctrl \"sigs.k8s.io/controller-runtime\"\n    \"sigs.k8s.io/controller-runtime/pkg/client\"\n)\n\nfunc (r *MemcachedReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {\n    ...\n\n    dep := &v1.Deployment{}\n    err := r.Get(ctx, request.NamespacedName, dep)\n\n    ...\n\n    // A merge patch will preserve other fields modified at runtime.\n    patch := client.MergeFrom(dep.DeepCopy())\n    dep.Spec.Selector.MatchLabels[\"is_running\"] = \"true\"\n    err := r.Patch(ctx, dep, patch)\n\n    ...\n}\n```\n\n[patch-options]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#PatchOption\n[dry-run-all]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#DryRunAll\n[force-ownership]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#ForceOwnership\n\n##### Updating Status Subresource\n\nWhen updating the [status subresource][cr-status-subresource] from the client, the [`StatusWriter`][status-writer] must be used. The status subresource is retrieved with `Status()` and updated with `Update()` or patched with `Patch()`.\n\n`Update()` takes variadic `client.UpdateOption`'s, and `Patch()` takes variadic `client.PatchOption`'s. See [`Client.Update()`](#update) and [`Client.Patch()`](#patch) for more details. Generally these options are not needed.\n\n##### Status\n\n```Go\n// Status() returns a StatusWriter object that can be used to update the\n// object's status subresource\nfunc (c Client) Status() (client.StatusWriter, error)\n```\n\nExample:\n```Go\nimport (\n    \"context\"\n\n    ctrl \"sigs.k8s.io/controller-runtime\"\n\n    cachev1alpha1 \"github.com/example/memcached-operator/api/v1alpha1\"\n)\n\nfunc (r *MemcachedReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {\n    ...\n\n    mem := &cachev1alpha1.Memcached{}\n    err := r.Get(ctx, request.NamespacedName, mem)\n\n    ...\n\n    // Update\n    mem.Status.Nodes = []string{\"pod1\", \"pod2\"}\n    err := r.Status().Update(ctx, mem)\n\n    ...\n\n    // Patch\n    patch := client.MergeFrom(mem.DeepCopy())\n    mem.Status.Nodes = []string{\"pod1\", \"pod2\", \"pod3\"}\n    err := r.Status().Patch(ctx, mem, patch)\n\n    ...\n}\n```\n\n[status-writer]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#StatusWriter\n\n#### Delete\n\n```Go\n// Delete deletes the given obj from Kubernetes cluster.\nfunc (c Client) Delete(ctx context.Context, obj client.Object, opts ...client.DeleteOption) error\n```\n\nA `client.DeleteOption` is an interface that sets [`client.DeleteOptions`][delete-opts] fields. A `client.DeleteOption` is created by using one of the provided implementations: [`GracePeriodSeconds`][grace-period-seconds], [`Preconditions`][preconditions], [`PropagationPolicy`][propagation-policy].\n\nExample:\n\n```Go\nimport (\n    \"context\"\n\n    \"k8s.io/api/core/v1\"\n    ctrl \"sigs.k8s.io/controller-runtime\"\n    \"sigs.k8s.io/controller-runtime/pkg/client\"\n)\n\nfunc (r *MemcachedReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {\n    ...\n\n    pod := &v1.Pod{}\n    err := r.Get(ctx, request.NamespacedName, pod)\n\n    ...\n\n    if pod.Status.Phase == v1.PodUnknown {\n        // Delete the pod after 5 seconds.\n        err := r.Delete(ctx, pod, client.GracePeriodSeconds(5))\n        ...\n    }\n\n    ...\n}\n```\n\n[delete-opts]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#DeleteOptions\n[grace-period-seconds]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#GracePeriodSeconds\n[preconditions]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#Preconditions\n[propagation-policy]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#PropagationPolicy\n\n#### DeleteAllOf\n\n```Go\n// DeleteAllOf deletes all objects of the given type matching the given options.\nfunc (c Client) DeleteAllOf(ctx context.Context, obj client.Object, opts ...client.DeleteAllOfOption) error\n```\n\nA `client.DeleteAllOfOption` is an interface that sets [`client.DeleteAllOfOptions`][deleteallof-opts] fields. A `client.DeleteAllOfOption` wraps a [`client.ListOption`](#list) and [`client.DeleteOption`](#delete).\n\nExample:\n\n```Go\nimport (\n    \"context\"\n    \"fmt\"\n\n    \"k8s.io/api/core/v1\"\n    ctrl \"sigs.k8s.io/controller-runtime\"\n    \"sigs.k8s.io/controller-runtime/pkg/client\"\n)\n\nfunc (r *MemcachedReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {\n    ...\n\n    // Delete all pods in the request namespace with a label of `instance=<name>`\n    // and phase `Failed`.\n    pod := &v1.Pod{}\n    opts := []client.DeleteAllOfOption{\n        client.InNamespace(request.NamespacedName.Namespace),\n        client.MatchingLabels{\"instance\", request.NamespacedName.Name},\n        client.MatchingFields{\"status.phase\": \"Failed\"},\n        client.GracePeriodSeconds(5),\n    }\n    err := r.DeleteAllOf(ctx, pod, opts...)\n\n    ...\n}\n```\n\n[deleteallof-opts]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#DeleteAllOfOptions\n\n### Example usage\n\n```Go\nimport (\n    \"context\"\n    \"reflect\"\n\n    appsv1 \"k8s.io/api/apps/v1\"\n    corev1 \"k8s.io/api/core/v1\"\n    \"k8s.io/apimachinery/pkg/api/errors\"\n    metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\"\n    \"k8s.io/apimachinery/pkg/labels\"\n    \"k8s.io/apimachinery/pkg/runtime\"\n    \"k8s.io/apimachinery/pkg/types\"\n    ctrl \"sigs.k8s.io/controller-runtime\"\n    \"sigs.k8s.io/controller-runtime/pkg/client\"\n    \"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil\"\n\n    cachev1alpha1 \"github.com/example/memcached-operator/api/v1alpha1\"\n)\n\ntype MemcachedReconciler struct {\n    client.Client\n    Log    logr.Logger\n    Scheme *runtime.Scheme\n}\n\nfunc (r *MemcachedReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {\n\n    // Fetch the Memcached instance.\n    memcached := &cachev1alpha1.Memcached{}\n    err := r.Get(ctx, request.NamespacedName, memcached)\n    if err != nil {\n        if errors.IsNotFound(err) {\n            return ctrl.Result{}, nil\n        }\n        return ctrl.Result{}, err\n    }\n\n    // Check if the deployment already exists, if not create a new deployment.\n    found := &appsv1.Deployment{}\n    err = r.Get(ctx, types.NamespacedName{Name: memcached.Name, Namespace: memcached.Namespace}, found)\n    if err != nil {\n         if errors.IsNotFound(err) {\n            // Define and create a new deployment.\n            dep := r.deploymentForMemcached(memcached)\n            if err = r.Create(ctx, dep); err != nil {\n                return ctrl.Result{}, err\n            }\n            return ctrl.Result{Requeue: true}, nil\n        } else {\n            return ctrl.Result{}, err\n        }\n    }\n\n    // Ensure the deployment size is the same as the spec.\n    size := memcached.Spec.Size\n    if *found.Spec.Replicas != size {\n        found.Spec.Replicas = &size\n        if err = r.Update(ctx, found); err != nil {\n            return ctrl.Result{}, err\n        }\n        return ctrl.Result{Requeue: true}, nil\n    }\n\n    // Update the Memcached status with the pod names.\n    // List the pods for this CR's deployment.\n    podList := &corev1.PodList{}\n    listOpts := []client.ListOption{\n        client.InNamespace(memcached.Namespace),\n        client.MatchingLabels(labelsForApp(memcached.Name)),\n    }\n    if err = r.List(ctx, podList, listOpts...); err != nil {\n        return ctrl.Result{}, err\n    }\n\n    // Update status.Nodes if needed.\n    podNames := getPodNames(podList.Items)\n    if !reflect.DeepEqual(podNames, memcached.Status.Nodes) {\n        memcached.Status.Nodes = podNames\n        if err := r.Status().Update(ctx, memcached); err != nil {\n            return ctrl.Result{}, err\n        }\n    }\n\n    return ctrl.Request{}, nil\n}\n\n// deploymentForMemcached returns a Deployment object for data from m.\nfunc (r *MemcachedReconciler) deploymentForMemcached(m *cachev1alpha1.Memcached) *appsv1.Deployment {\n    lbls := labelsForApp(m.Name)\n    replicas := m.Spec.Size\n\n    dep := &appsv1.Deployment{\n        ObjectMeta: metav1.ObjectMeta{\n            Name:      m.Name,\n            Namespace: m.Namespace,\n        },\n        Spec: appsv1.DeploymentSpec{\n            Replicas: &replicas,\n            Selector: &metav1.LabelSelector{\n                MatchLabels: lbls,\n            },\n            Template: corev1.PodTemplateSpec{\n                ObjectMeta: metav1.ObjectMeta{\n                    Labels: lbls,\n                },\n                Spec: corev1.PodSpec{\n                    Containers: []corev1.Container{{\n                        Image:   \"memcached:alpine\",\n                        Name:    \"memcached\",\n                        Command: []string{\"memcached\", \"-a=64\", \"-b\"},\n                        Ports: []corev1.ContainerPort{{\n                            ContainerPort: 10000,\n                            Name:          \"memcached\",\n                        }},\n                    }},\n                },\n            },\n        },\n    }\n\n    // Set Memcached instance as the owner and controller.memcac\n    // NOTE: calling SetControllerReference, and setting owner references in\n    // general, is important as it allows deleted objects to be garbage collected.\n    controllerutil.SetControllerReference(m, dep, r.Scheme)\n    return dep\n}\n\n// labelsForApp creates a simple set of labels for Memcached.\nfunc labelsForApp(name string) map[string]string {\n    return map[string]string{\"cr_name\": name}\n}\n```\n\n[memcached-testdata]:https://github.com/operator-framework/operator-sdk/tree/master/testdata/go/v4/memcached-operator\n[repo-controller-runtime]:https://github.com/kubernetes-sigs/controller-runtime\n[doc-client]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#Client\n[doc-split-client]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#DelegatingClient\n[doc-client-constr]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/client#New\n[code-scheme-default]:https://github.com/kubernetes-sigs/controller-runtime/blob/master/pkg/client/client.go#L51\n[doc-k8s-core]:https://pkg.go.dev/k8s.io/api/core/v1\n[doc-reconcile-reconciler]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/reconcile#Reconciler\n[doc-osdk-handle]:https://github.com/operator-framework/operator-sdk/blob/master/design/milestone-0.0.2/action-api.md#handler\n[doc-types-nsname]:https://pkg.go.dev/k8s.io/apimachinery/pkg/types#NamespacedName\n[cr-status-subresource]:https://kubernetes.io/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definitions/#status-subresource\n\n<!-- File: website/content/en/docs/building-operators/golang/references/event-filtering.md (Tokens: ~998 | Category: anthropic-skill) -->\n---\ntitle: Using Predicates for Event Filtering with Operator SDK\nlinkTitle: Using Predicates for Event Filtering\nweight: 30\n---\n\n[Events][doc_event] are produced by [Sources][doc_source] assigned to resources a controller is watching. These events are transformed into Requests by [EventHandlers][doc_eventhandler] and passed to `Reconcile()`. [Predicates][doc_predicate] allow controllers to filter events before they are provided to EventHandlers. Filtering is useful because your controller may only want to handle specific types of events. Filtering also helps reduce chattiness with the API server, as `Reconcile()` is only called for events transformed by EventHandlers.\n\n## Predicate types\n\nA Predicate implements the following methods that take an event of a particular type and return true if the event should be processed by `Reconcile()`:\n\n```Go\n// Predicate filters events before enqueuing the keys.\ntype Predicate interface {\n  Create(event.CreateEvent) bool\n  Delete(event.DeleteEvent) bool\n  Update(event.UpdateEvent) bool\n  Generic(event.GenericEvent) bool\n}\n\n// Funcs implements Predicate.\ntype Funcs struct {\n  CreateFunc func(event.CreateEvent) bool\n  DeleteFunc func(event.DeleteEvent) bool\n  UpdateFunc func(event.UpdateEvent) bool\n  GenericFunc func(event.GenericEvent) bool\n}\n```\n\nFor example, all Create events for any watched resource will be passed to `Funcs.Create()` and filtered out if the method evaluates to `false`. If you do not register a Predicate method for a particular type, events of that type will not be filtered.\n\nAll event types contain Kubernetes [metadata][doc_object_metadata] about the object that triggered the event, and the object itself. Predicate logic uses these data to make decisions about what should be filtered. Some event types include other fields pertaining to the semantics of that event. For example, `event.UpdateEvent` includes both old and new metadata and objects:\n\n```Go\ntype UpdateEvent struct {\n  // ObjectOld is the object from the event.\n  ObjectOld runtime.Object\n\n  // ObjectNew is the object from the event.\n  ObjectNew runtime.Object\n}\n```\n\nYou can find all type definitions in the `event` package [documentation][doc_event].\n\n## Using Predicates\n\nAny number of Predicates can be set for a controller via the builder method `WithEventFilter()`, which will filter an event if any of those Predicates evaluates to `false`. This first example is an implementation of a `memcached-operator` controller that simply filters Delete events on Pods that have been confirmed deleted; the controller receives all Delete events that occur, and we may only care about resources that have not been completely deleted:\n\n```Go\nimport (\n\t\"context\"\n\n\t\"github.com/go-logr/logr\"\n\tcorev1 \"k8s.io/api/core/v1\"\n\t\"k8s.io/apimachinery/pkg/runtime\"\n\tctrl \"sigs.k8s.io/controller-runtime\"\n\t\"sigs.k8s.io/controller-runtime/pkg/client\"\n\t\"sigs.k8s.io/controller-runtime/pkg/event\"\n\t\"sigs.k8s.io/controller-runtime/pkg/predicate\"\n\n\tcachev1alpha1 \"github.com/example/app-operator/api/v1alpha1\"\n)\n\n...\n\nfunc ignoreDeletionPredicate() predicate.Predicate {\n\treturn predicate.Funcs{\n\t\tUpdateFunc: func(e event.UpdateEvent) bool {\n\t\t\t// Ignore updates to CR status in which case metadata.Generation does not change\n\t\t\treturn e.ObjectOld.GetGeneration() != e.ObjectNew.GetGeneration()\n\t\t},\n\t\tDeleteFunc: func(e event.DeleteEvent) bool {\n\t\t\t// Evaluates to false if the object has been confirmed deleted.\n\t\t\treturn !e.DeleteStateUnknown\n\t\t},\n\t}\n}\n\nfunc (r *MemcachedReconciler) SetupWithManager(mgr ctrl.Manager) error {\n\treturn ctrl.NewControllerManagedBy(mgr).\n\t\tFor(&cachev1alpha1.Memcached{}).\n\t\tOwns(&corev1.Pod{}).\n\t\tWithEventFilter(ignoreDeletionPredicate()).\n\t\tComplete(r)\n}\n  ...\n}\n```\n\n## Use cases\n\nPredicates are not necessary for many operators, although filtering reduces the amount of chatter to the API server from `Reconcile()`. They are particularly useful for controllers that watch resources cluster-wide, i.e. without a namespace.\n\n[doc_event]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/event\n[doc_source]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/source#Source\n[doc_eventhandler]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/handler#EventHandler\n[doc_predicate]:https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/predicate\n[doc_object_metadata]:https://pkg.go.dev/k8s.io/apimachinery/pkg/apis/meta/v1#Object\n\n<!-- File: website/content/en/docs/building-operators/golang/references/logging.md (Tokens: ~2541 | Category: anthropic-skill) -->\n---\ntitle: Logging\nlinkTitle: Logging\nweight: 20\n---\n\n# Overview\n\nOperator SDK-generated operators use the [`logr`][godoc_logr] interface to log. This log interface has several backends such as [`zap`][repo_zapr], which the SDK uses in generated code by default. [`logr.Logger`][godoc_logr_logger] exposes structured logging methods that help create machine-readable logs and adding a wealth of information to log records.\n\n## Default zap logger\n\nOperator SDK uses a `zap`-based `logr` backend when scaffolding new projects. To assist with configuring and using this logger, the SDK includes several helper functions.\n\nIn the simple example below, we add the zap flagset to the operator's command line flags with `BindFlags()`, and then set the controller-runtime logger with `zap.Options{}`.\n\nBy default, `zap.Options{}` will return a logger that is ready for production use. It uses a JSON encoder, logs starting at the `info` level. To customize the default behavior, users can use the zap flagset and specify flags on the command line. The zap flagset includes the following flags that can be used to configure the logger:\n\n* `--zap-devel`: Development Mode defaults(encoder=consoleEncoder,logLevel=Debug,stackTraceLevel=Warn)\n\t\t\t  Production Mode defaults(encoder=jsonEncoder,logLevel=Info,stackTraceLevel=Error)\n* `--zap-encoder`: Zap log encoding ('json' or 'console')\n* `--zap-log-level`: Zap Level to configure the verbosity of logging. Can be one of 'debug', 'info', 'error',\n\t\t\t       or any integer value > 0 which corresponds to custom debug levels of increasing verbosity\")\n* `--zap-stacktrace-level`: Zap Level at and above which stacktraces are captured (one of 'info' or 'error')\n\nConsult the controller-runtime [godocs][logging_godocs] for more detailed flag information.\n\n### A simple example\n\nOperators set the logger for all operator logging in `main.go`. To illustrate how this works, try out this simple example:\n\n```Go\npackage main\n\nimport (\n\t\"sigs.k8s.io/controller-runtime/pkg/log/zap\"\n\tlogf \"sigs.k8s.io/controller-runtime/pkg/log\"\n)\n\nvar globalLog = logf.Log.WithName(\"global\")\nfunc main() {\n\t// Add the zap logger flag set to the CLI. The flag set must\n\t// be added before calling flag.Parse().\n\topts := zap.Options{}\n\topts.BindFlags(flag.CommandLine)\n\tflag.Parse()\n\n\tlogger := zap.New(zap.UseFlagOptions(&opts))\n\tlogf.SetLogger(logger)\n\n\tscopedLog := logf.Log.WithName(\"scoped\")\n\n\tglobalLog.Info(\"Printing at INFO level\")\n\tglobalLog.V(1).Info(\"Printing at DEBUG level\")\n\tscopedLog.Info(\"Printing at INFO level\")\n\tscopedLog.V(1).Info(\"Printing at DEBUG level\")\n}\n```\n\n#### Output using the defaults\n```console\n$ go run main.go\nINFO[0000] Running the operator locally in namespace default.\n{\"level\":\"info\",\"ts\":1587741740.407766,\"logger\":\"global\",\"msg\":\"Printing at INFO level\"}\n{\"level\":\"info\",\"ts\":1587741740.407855,\"logger\":\"scoped\",\"msg\":\"Printing at INFO level\"}\n```\n\n#### Output overriding the log level to 1 (debug)\n```console\n$ go run main.go --zap-log-level=debug\nINFO[0000] Running the operator locally in namespace default.\n{\"level\":\"info\",\"ts\":1587741837.602911,\"logger\":\"global\",\"msg\":\"Printing at INFO level\"}\n{\"level\":\"debug\",\"ts\":1587741837.602964,\"logger\":\"global\",\"msg\":\"Printing at DEBUG level\"}\n{\"level\":\"info\",\"ts\":1587741837.6029708,\"logger\":\"scoped\",\"msg\":\"Printing at INFO level\"}\n{\"level\":\"debug\",\"ts\":1587741837.602973,\"logger\":\"scoped\",\"msg\":\"Printing at DEBUG level\"}\n```\n## Custom zap logger\n\nIn order to use a custom zap logger, [`zap`][controller_runtime_zap] from controller-runtime can be utilized to wrap it in a `logr` implementation.\n\nBelow is an example illustrating the use of [`zap-logfmt`][logfmt_repo] in logging.\n\n### Example\n\nIn your `main.go` file, replace the current implementation for logs inside the `main` function:\n\n```Go\n...\n// Add the zap logger flag set to the CLI. The flag set must\n// be added before calling flag.Parse().\n\topts := zap.Options{}\n\topts.BindFlags(flag.CommandLine)\n\tflag.Parse()\n\n\tlogger := zap.New(zap.UseFlagOptions(&opts))\n\tlogf.SetLogger(logger)\n...\n```\n\nWith:\n\n```Go\n\timport(\n\t...\n\tzaplogfmt \"github.com/sykesm/zap-logfmt\"\n\tuzap \"go.uber.org/zap\"\n\t\"go.uber.org/zap/zapcore\"\n\tlogf \"sigs.k8s.io/controller-runtime/pkg/log\"\n\t\"sigs.k8s.io/controller-runtime/pkg/log/zap\"\n\t...\n)\n\tconfigLog := uzap.NewProductionEncoderConfig()\n\tconfigLog.EncodeTime = func(ts time.Time, encoder zapcore.PrimitiveArrayEncoder) {\n\t\tencoder.AppendString(ts.UTC().Format(time.RFC3339Nano))\n\t}\n\tlogfmtEncoder := zaplogfmt.NewEncoder(configLog)\n\n\t// Construct a new logr.logger.\n\tlogger := zap.New(zap.UseDevMode(true), zap.WriteTo(os.Stdout), zap.Encoder(logfmtEncoder))\n\tlogf.SetLogger(logger)\n```\n\n**NOTE**: For this example, you will need to add the module `\"github.com/sykesm/zap-logfmt\"` to your project. Run `go get -u github.com/sykesm/zap-logfmt`.\n\n#### Output using custom zap logger\n\n```console\n$ go run main.go\nts=2020-04-30T20:35:59.551268Z level=info logger=global msg=\"Printing at INFO level\"\nts=2020-04-30T20:35:59.551314Z level=debug logger=global msg=\"Printing at DEBUG level\"\nts=2020-04-30T20:35:59.551318Z level=info logger=scoped msg=\"Printing at INFO level\"\nts=2020-04-30T20:35:59.55132Z level=debug logger=scoped msg=\"Printing at DEBUG level\"\n```\n\nBy using `sigs.k8s.io/controller-runtime/pkg/log`, your logger is propagated through `controller-runtime`. Any logs produced by `controller-runtime` code will be through your logger, and therefore have the same formatting and destination.\n\n### Setting flags when running locally\n\nWhen running locally with `make run ENABLE_WEBHOOKS=false`, you can use the `ARGS` var to pass additional flags to your operator, including the zap flags. For example:\n\n```console\n$ make run ARGS=\"--zap-encoder=console\" ENABLE_WEBHOOKS=false\n```\nMake sure to have your `run` target to take `ARGS` as shown below in `Makefile`.\n\n```makefile\n# Run against the configured Kubernetes cluster in ~/.kube/config\nrun: manifests generate fmt vet\n\tgo run ./main.go $(ARGS)\n```\n\n### Setting flags when deploying to a cluster\n\nWhen deploying your operator to a cluster you can set additional flags using an `args` array in your operator's `container` spec in the file `config/default/manager_metrics_patch.yaml` For example:\n\n```yaml\n- op: add\n  path: /spec/template/spec/containers/0/args/0\n  value: --zap-log-level=debug \n- op: add\n  path: /spec/template/spec/containers/0/args/0\n  value: --zap-encoder=console\n```\n\n## Creating a structured log statement\n\nThere are two ways to create structured logs with `logr`. You can create new loggers using `log.WithValues(keyValues)` that include `keyValues`, a list of key-value pair `interface{}`'s, in each log record. Alternatively you can include `keyValues` directly in a log statement, as all `logr` log statements take some message and `keyValues`. The signature of `logr.Error()` has an `error`-type parameter, which can be `nil`.\n\nAn example from [`memcached_controller.go`][code_memcached_controller]:\n\n```Go\npackage memcached\n\nimport (\n  ctrllog \"sigs.k8s.io/controller-runtime/pkg/log\"\n)\n\n\n// MemcachedReconciler reconciles a Memcached object\ntype MemcachedReconciler struct {\n\tclient.Client\n\tLog    logr.Logger\n\tScheme *runtime.Scheme\n}\n\nfunc (r *MemcachedReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {\n\tlog := ctrllog.FromContext(ctx)\n\n\t// Fetch the Memcached instance\n\tmemcached := &cachev1alpha1.Memcached{}\n\terr := r.Get(ctx, req.NamespacedName, memcached)\n\tif err != nil {\n\t\tif errors.IsNotFound(err) {\n\t\t\t// Request object not found, could have been deleted after reconcile request.\n\t\t\t// Owned objects are automatically garbage collected. For additional cleanup logic use finalizers.\n\t\t\t// Return and don't requeue\n\t\t\tlog.Info(\"Memcached resource not found. Ignoring since object must be deleted\")\n\t\t\treturn ctrl.Result{}, nil\n\t\t}\n\t\t// Error reading the object - requeue the request.\n\t\tlog.Error(err, \"Failed to get Memcached\")\n\t\treturn ctrl.Result{}, err\n\t}\n\n\t// Check if the deployment already exists, if not create a new one\n\tfound := &appsv1.Deployment{}\n\terr = r.Get(ctx, types.NamespacedName{Name: memcached.Name, Namespace: memcached.Namespace}, found)\n\tif err != nil && errors.IsNotFound(err) {\n\t\t// Define a new deployment\n\t\tdep := r.deploymentForMemcached(memcached)\n\t\tlog.Info(\"Creating a new Deployment\", \"Deployment.Namespace\", dep.Namespace, \"Deployment.Name\", dep.Name)\n\t\terr = r.Create(ctx, dep)\n\t\tif err != nil {\n\t\t\tlog.Error(err, \"Failed to create new Deployment\", \"Deployment.Namespace\", dep.Namespace, \"Deployment.Name\", dep.Name)\n\t\t\treturn ctrl.Result{}, err\n\t\t}\n\t\t// Deployment created successfully - return and requeue\n\t\treturn ctrl.Result{Requeue: true}, nil\n\t} else if err != nil {\n\t\tlog.Error(err, \"Failed to get Deployment\")\n\t\treturn ctrl.Result{}, err\n\t}\n\n\t...\n}\n```\n\nLog records will look like the following (from `log.Error()` above):\n\n```\n2020-04-27T09:14:15.939-0400\tERROR\tcontrollers.Memcached\tFailed to create new Deployment\t{\"memcached\": \"default/memcached-sample\", \"Deployment.Namespace\": \"default\", \"Deployment.Name\": \"memcached-sample\"}\n```\n\n## Non-default logging\n\nIf you do not want to use `logr` as your logging tool, you can remove `logr`-specific statements without issue from your operator's code, including the `logr` setup code in `main.go`, and add your own. Note that removing `logr` setup code will prevent `controller-runtime` from logging.\n\n\n[godoc_logr]:https://pkg.go.dev/github.com/go-logr/logr\n[repo_zapr]:https://pkg.go.dev/github.com/go-logr/zapr\n[godoc_logr_logger]:https://pkg.go.dev/github.com/go-logr/logr#Logger\n[code_memcached_controller]: https://github.com/operator-framework/operator-sdk/blob/v1.2.0/testdata/go/memcached-operator/controllers/memcached_controller.go\n[logfmt_repo]:https://github.com/jsternberg/zap-logfmt\n[controller_runtime_zap]:https://github.com/kubernetes-sigs/controller-runtime/tree/master/pkg/log/zap\n[logging_godocs]: https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/log/zap#Options.BindFlags\n\n<!-- File: website/content/en/docs/building-operators/golang/references/markers.md (Tokens: ~1821 | Category: anthropic-skill) -->\n---\ntitle: API Markers\nlinkTitle: API Markers\nweight: 40\n---\n\nThis document describes [code markers][markers] supported by the SDK.\n\n## ClusterServiceVersion markers\n\nThis section details ClusterServiceVersion (CSV) code markers and lists available markers.\n\n**Note:** CSV markers can only be used in Go Operator projects. Annotations for Ansible and Helm Operator projects will be added in the future.\n\n### Usage\n\nAll CSV markers have the prefix `+operator-sdk:csv`.\n\n#### `+operator-sdk:csv:customresourcedefinitions`\n\nThese markers populate [owned `customresourcedefinitions`][csv-crds] in your CSV.\n\nPossible type-level markers:\n- `+operator-sdk:csv:customresourcedefinitions:displayName=\"some display name\"`\n\t- Configures the kind's display name.\n- `+operator-sdk:csv:customresourcedefinitions:resources={{Kind1,v1alpha1,dns-name-1},{Kind2,v1,\"dns-name-2\"},...}`\n\t- Configures the kind's resources.\n- `+operator-sdk:csv:customresourcedefinitions:order=1`\n\t- Configures the order of this type in the list. Markers with order omitted have the highest order, i.e. are at the end of the list. If more than one marker has the same order, the corresponding descriptions will be sorted alphabetically and placed above others with higher orders. Pre-existing list elements in the CSV will be appended to the set of other elements in the order corresponding to its index.\n\nPossible field-level markers, all of which must contain the `type=[spec,status]` key-value pair:\n- `+operator-sdk:csv:customresourcedefinitions:type=[spec,status],displayName=\"some field display name\"`\n\t- Configures the field's display name.\n- `+operator-sdk:csv:customresourcedefinitions:type=[spec,status],xDescriptors={\"urn:alm:descriptor:com.tectonic.ui:podCount\",\"urn:alm:descriptor:io.kubernetes:custom\"}`\n\t- Configures the field's x-descriptors.\n- `+operator-sdk:csv:customresourcedefinitions:type=[spec,status],order=1`\n\t- Configures the order of this type in the list. Markers with order omitted have the highest order, i.e. are at the end of the list. If more than one marker has the same order, the corresponding descriptions will be sorted alphabetically and placed above others with higher orders.\n\nTop-level `kind`, `name`, and `version` fields are parsed from API code.\nAll `description` fields are parsed from type declaration and `struct` type field comments.\nAll `path` fields are parsed from a field's JSON tag and merged with parent\nfield path's in dot-hierarchy notation.\n\n##### x-descriptors\n\nCheck out the [descriptor reference][csv-x-desc] for available `x-descriptors` paths.\n\n#### Examples\n\nThese examples assume `Memcached`, `MemcachedSpec`, and `MemcachedStatus` are the example projects' kind, spec, and status.\n\n1. Set a `displayName` and `resources` for a `customresourcedefinitions` kind entry:\n\n\t```go\n\t//+operator-sdk:csv:customresourcedefinitions:displayName=\"Memcached App\",resources={{Pod,v1,memcached-runner},{Deployment,v1,memcached-deployment}}\n\ttype Memcached struct {\n\t\tmetav1.TypeMeta   `json:\",inline\"`\n\t\tmetav1.ObjectMeta `json:\"metadata,omitempty\"`\n\n\t\tSpec   MemcachedSpec   `json:\"spec,omitempty\"`\n\t\tStatus MemcachedStatus `json:\"status,omitempty\"`\n\t}\n\t```\n\n2. Set `displayName`, `path`, `xDescriptors`, and `description` on a field for a `customresourcedefinitions.specDescriptors` entry:\n\n\t```go\n\ttype MemcachedSpec struct {\n\t\t// Size is the size of the memcached deployment. <-- This will become Size's specDescriptors.description.\n\t\t//+operator-sdk:csv:customresourcedefinitions:type=spec,displayName=\"Number of pods\",xDescriptors={\"urn:alm:descriptor:com.tectonic.ui:podCount\",\"urn:alm:descriptor:io.kubernetes:custom\"}\n\t\tSize int32 `json:\"size\"` // <-- Size's specDescriptors.path is inferred from this JSON tag.\n\t}\n\t```\n\n3. Let the SDK infer all unmarked paths on a field for a `customresourcedefinitions.specDescriptors` entry:\n\n\t```go\n\ttype MemcachedSpec struct {\n\t\t// Size is the size of the memcached deployment.\n\t\t//+operator-sdk:csv:customresourcedefinitions:type=spec\n\t\tSize int32 `json:\"size\"`\n\t}\n\t```\n\n\tThe SDK uses the `Size` fields' `json` tag name as `path`, `Size` as `displayName`, and field comments as `description`.\n\n4. A comprehensive example:\n\t- Infer `path`, `description`, `displayName`, and `x-descriptors` for `specDescriptors` and `statusDescriptors` entries.\n\t- Create three `resources` entries each with `kind`, `version`, and `name` values.\n\n\t```go\n\t// Represents a cluster of Memcached apps\n\t//+operator-sdk:csv:customresourcedefinitions:displayName=\"Memcached App\",resources={{Pod,v1,memcached-runner},{Deployment,v1,memcached-deployment}}\n\ttype Memcached struct {\n\t\tmetav1.TypeMeta   `json:\",inline\"`\n\t\tmetav1.ObjectMeta `json:\"metadata,omitempty\"`\n\n\t\tSpec   MemcachedSpec   `json:\"spec,omitempty\"`\n\t\tStatus MemcachedStatus `json:\"status,omitempty\"`\n\t}\n\n\ttype MemcachedSpec struct {\n\t\tPods MemcachedPods `json:\"pods\"`\n\t}\n\n\ttype MemcachedStatus struct {\n\t\tPods \t\t MemcachedPods `json:\"podStatuses\"`\n\t\t//+operator-sdk:csv:customresourcedefinitions:type=status,displayName=\"Pod Count\",xDescriptors=\"urn:alm:descriptor:com.tectonic.ui:podCount\"\n\t\tPodCount int \t\t\t\t\t `json:\"podCount\"`\n\t}\n\n\ttype MemcachedPods struct {\n\t\t// Size is the size of the memcached deployment.\n\t\t//+operator-sdk:csv:customresourcedefinitions:type=spec\n\t\t//+operator-sdk:csv:customresourcedefinitions:type=status\n\t\tSize int32 `json:\"size\"`\n\t}\n\t```\n\n\tThe generated `customresourcedefinitions` will look like:\n\n\t```yaml\n\tcustomresourcedefinitions:\n\t  owned:\n\t  - description: Represents a cluster of Memcached apps\n\t    displayName: Memcached App\n\t    kind: Memcached\n\t    name: memcacheds.cache.example.com\n\t    version: v1alpha1\n\t    resources:\n\t    - kind: Deployment\n\t      name: memcached-deployment\n\t      version: v1\n\t    - kind: Pod\n\t      name: memcached-runner\n\t      version: v1\n\t    specDescriptors:\n\t    - description: The desired number of member Pods for the deployment.\n\t      displayName: Size\n\t      path: pods.size\n\t    statusDescriptors:\n\t    - description: The desired number of member Pods for the deployment.\n\t      displayName: Size\n\t      path: podStatuses.size\n\t    - displayName: Size\n\t      path: podCount\n\t      x-descriptors:\n\t      - 'urn:alm:descriptor:com.tectonic.ui:podCount'\n\t```\n\n\n## Deprecated markers\n\nMarkers supported by `operator-sdk` prior to v1.0.0 are deprecated.\nYou can migrate to the new marker system by running the following script:\n\n```console\n$ curl -sSLo migrate-markers.sh https://raw.githubusercontent.com/operator-framework/operator-sdk/master/hack/generate/migrate-markers.sh\n$ chmod +x ./migrate-markers.sh\n$ ./migrate-markers.sh path/to/*_types.go\n```\n\n\n[markers]:https://pkg.go.dev/sigs.k8s.io/controller-tools/pkg/markers\n[cli-gen-kustomize-manifests]:/docs/cli/operator-sdk_generate_kustomize_manifests\n[csv-x-desc]:https://github.com/openshift/console/blob/master/frontend/packages/operator-lifecycle-manager/src/components/descriptors/reference/reference.md\n[csv-spec]:https://github.com/operator-framework/operator-lifecycle-manager/blob/e0eea22/doc/design/building-your-csv.md\n[csv-crds]:https://github.com/operator-framework/operator-lifecycle-manager/blob/master/doc/design/building-your-csv.md#your-custom-resource-definitions\n\n<!-- File: website/content/en/docs/building-operators/golang/references/openapi-validation.md (Tokens: ~270 | Category: anthropic-skill) -->\n---\ntitle: OpenAPI validation\nlinkTitle: OpenAPI validation\nweight: 70\n---\n\nOpenAPIv3 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.\n\n[Markers][markers] (annotations) are available to configure validations for your API. These markers will always have a `+kubebuilder:validation` prefix.\n\nUsage of markers in API code is discussed in the kubebuilder [CRD generation][generating-crd] and [marker][markers] documentation. A full list of OpenAPIv3 validation markers can be found [here][crd-markers].\n\nTo learn more about OpenAPI v3.0 validation schemas in CRDs, refer to the [Kubernetes Documentation][doc-validation-schema].\n\n[markers]: https://book.kubebuilder.io/reference/markers.html\n[crd-markers]: https://book.kubebuilder.io/reference/markers/crd-validation.html\n[generating-crd]: https://book.kubebuilder.io/reference/generating-crd.html\n[doc-validation-schema]: https://kubernetes.io/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definitions/#specifying-a-structural-schema\n\n<!-- File: website/content/en/docs/building-operators/golang/references/proxy-vars.md (Tokens: ~259 | Category: anthropic-skill) -->\n---\ntitle: Proxy Friendly Operators\nlinkTitle: Proxy Vars\nweight: 20\n---\n\nProxy-friendly Operators should inspect their environment for the\nstandard proxy variables (`HTTPS_PROXY`, `HTTP_PROXY`, and `NO_PROXY`)\nand pass the values to Operands.\n\nOperator-lib provides a helper function `proxy.ReadProxyVarsFromEnv`\nthat does this inspection, all you need to do is append the\nresults to the Operand environments.\n\nUsing the memcached tutorial as an example, add the following to the\nReconcile loop in `controllers/memcached_controller.go`:\n\n\n```go\nimport (\n  ...\n   \"github.com/operator-framework/operator-lib/proxy\"\n)\n\n\nfor i, container := range dep.Spec.Template.Spec.Containers {\n\t\tdep.Spec.Template.Spec.Containers[i].Env = append(container.Env, proxy.ReadProxyVarsFromEnv()...)\n}\n```\n\nYou can set the environment variable on the Operator deployment. Using the memcached tutorial, edit config/manager/manager.yaml:\n\n```yaml\ncontainers:\n - args:\n   - --leader-elect\n   - --leader-election-id=go-proxy-demo\n   image: controller:latest\n   name: manager\n   env:\n     - name: \"HTTP_PROXY\"\n       value: \"http_proxy_test\"\n```\n</yakaai_skills>"}