### Install Valkey Chart with Helm Source: https://github.com/sap/valkey-operator/blob/main/pkg/operator/data/charts/valkey/README.md Install the Valkey Helm chart using the `helm install` command with `--set` arguments to configure parameters. Remember to replace placeholders with your registry details. ```bash helm install my-release \ --set auth.password=secretpassword \ oci://REGISTRY_NAME/REPOSITORY_NAME/valkey ``` -------------------------------- ### Install Valkey Chart with values.yaml Source: https://github.com/sap/valkey-operator/blob/main/pkg/operator/data/charts/valkey/README.md Install the Valkey Helm chart by providing a YAML file with parameter values using the `-f` flag with `helm install`. Replace placeholders with your registry details. ```bash helm install my-release -f values.yaml oci://REGISTRY_NAME/REPOSITORY_NAME/valkey ``` -------------------------------- ### Complete Valkey Client Example Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/client-library.md Demonstrates creating, listing, and watching Valkey resources using the client library. This example assumes in-cluster configuration. ```go package main import ( "context" "fmt" "log" "time" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/rest" v1alpha1 "github.com/sap/valkey-operator/api/v1alpha1" clientset "github.com/sap/valkey-operator/pkg/client/clientset/versioned" informers "github.com/sap/valkey-operator/pkg/client/informers/externalversions" ) func main() { // Get in-cluster config config, err := rest.InClusterConfig() if err != nil { log.Fatal(err) } // Create clientset cs, err := clientset.NewForConfig(config) if err != nil { log.Fatal(err) } // Get namespace-scoped client valkeyClient := cs.CacheV1alpha1().Valkey("default") // Create a Valkey resource valkey := &v1alpha1.Valkey{ ObjectMeta: metav1.ObjectMeta{ Name: "my-cache", }, Spec: v1alpha1.ValkeySpec{ Replicas: 3, Sentinel: &v1alpha1.SentinelProperties{ Enabled: true, }, }, } created, err := valkeyClient.Create(context.Background(), valkey, metav1.CreateOptions{}) if err != nil { log.Fatal(err) } fmt.Printf("Created: %s\n", created.Name) // List resources list, err := valkeyClient.List(context.Background(), metav1.ListOptions{}) if err != nil { log.Fatal(err) } for _, v := range list.Items { fmt.Printf("Found: %s\n", v.Name) } // Watch for changes watcher, err := valkeyClient.Watch(context.Background(), metav1.ListOptions{}) if err != nil { log.Fatal(err) } go func() { for event := range watcher.ResultChan() { v := event.Object.(*v1alpha1.Valkey) fmt.Printf("Event: %s %s\n", event.Type, v.Name) } }() time.Sleep(time.Second * 30) watcher.Stop() } ``` -------------------------------- ### SetupWithManager() Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/api-reference-webhook.md Registers the webhook with a controller manager. This is called by the operator during setup to install the admission webhook HTTP handler. ```APIDOC ## SetupWithManager() ### Description Registers the webhook with a controller manager. Called by the operator during setup to install the admission webhook HTTP handler. ### Method (Not specified, likely internal Go method) ### Endpoint `/admission/cache.cs.sap.com/v1alpha1/valkey/validate` ### Parameters #### Path Parameters (None) #### Query Parameters (None) #### Request Body (None) ### Webhook Registration Details - **Operations**: `CREATE`, `UPDATE` - **Failure policy**: `Fail` (rejects invalid requests) - **Side effects**: `Unknown` - **Admission review versions**: `v1` ### Request Example ```go webhook := v1alpha1.NewWebhook() webhook.SetupWithManager(mgr) ``` ### Response #### Success Response (None) #### Response Example (None) ``` -------------------------------- ### Install Valkey with Helm Source: https://github.com/sap/valkey-operator/blob/main/pkg/operator/data/charts/valkey/README.md Basic command to install the Valkey chart using Helm. Replace `my-release` with your desired release name. ```console helm install my-release oci://registry-1.docker.io/bitnamicharts/valkey ``` -------------------------------- ### PersistenceProperties Example Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/types.md An example of how to configure persistence settings. This enables AOF persistence with a specified size and storage class. ```yaml persistence: enabled: true size: 10Gi storageClass: fast-ssd ``` -------------------------------- ### Setup() Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/api-reference-operator.md Sets up the operator with a controller manager. This initializes various components including resource generation, controllers, and webhooks. ```APIDOC ## Setup(mgr ctrl.Manager) ### Description Sets up the operator with a controller manager. This initializes: - Helm-based resource generator from embedded charts - Parameter transformer for customizing chart values - Object transformer for topology spread constraint logic - Controller reconciliation for Valkey resources - Validating webhooks - Post-reconciliation hook for binding secret generation ### Parameters #### Path Parameters - `mgr` (ctrl.Manager) - Required - The controller-runtime manager to set up with ### Returns - `error` — An error if setup fails. ### Throws/Errors - `"error initializing parameter transformer"` - Failed to load `data/parameters.yaml` from embedded FS - `"error initializing resource generator"` - Failed to initialize Helm generator from embedded chart - `"unable to create controller"` - Failed to register controller with manager ### Example ```go mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{}) if err != nil { log.Fatal(err) } if err := operator.Setup(mgr); err != nil { log.Fatal(err) } ``` ``` -------------------------------- ### Setup(mgr ctrl.Manager) error Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/api-reference-operator.md Sets up the operator with a controller manager, serving as the main integration point. ```APIDOC ## Setup(mgr ctrl.Manager) error ### Description Sets up the operator with a controller manager. This is the main entry point for integrating the operator into a controller manager. ### Parameters #### Path Parameters - `mgr` (ctrl.Manager) - Required - The controller-runtime manager ### Returns - `error` — An error if setup fails. ### Throws/Errors - `error initializing parameter transformer` - Chart parameters file not found - `error initializing resource generator` - Helm chart not found or invalid - `unable to create controller` - Controller registration failed ### Example ```go package main import ( "github.com/sap/valkey-operator/pkg/operator" ctrl "sigs.k8s.io/controller-runtime" ) func main() { mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{}) if err != nil { panic(err) } if err := operator.Setup(mgr); err != nil { panic(err) } if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil { panic(err) } } ``` ``` -------------------------------- ### Install Valkey with Helm (Custom Registry) Source: https://github.com/sap/valkey-operator/blob/main/pkg/operator/data/charts/valkey/README.md Command to install the Valkey chart from a custom Helm registry. Ensure you replace `REGISTRY_NAME` and `REPOSITORY_NAME` with your specific registry details. ```console helm install my-release oci://REGISTRY_NAME/REPOSITORY_NAME/valkey ``` -------------------------------- ### Install Valkey with Existing PersistentVolumeClaim Source: https://github.com/sap/valkey-operator/blob/main/pkg/operator/data/charts/valkey/README.md Install the Valkey chart using an existing Persistent Volume Claim (PVC). Replace `PVC_NAME`, `REGISTRY_NAME`, and `REPOSITORY_NAME` with your specific values. ```bash helm install my-release --set primary.persistence.existingClaim=PVC_NAME oci://REGISTRY_NAME/REPOSITORY_NAME/valkey ``` -------------------------------- ### Custom Binding Template Example Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/types.md Provides an example of a custom Go template string for generating a Redis URL and TLS configuration in the binding secret. ```go template: &stringValue{ V: ` { "url": "redis://:{{ .password }}@{{ .host }}:{{ .port }}", "tlsEnabled": {{ .tlsEnabled }}, "ca": {{ .caData | quote }} } `, } ``` -------------------------------- ### Operator Type and Methods Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/MANIFEST.txt Details the Operator type, its methods, options configuration, and package-level functions. Includes a guide for setup, initialization, and integration patterns. ```APIDOC ## Operator API ### Description This section documents the `Operator` type, its associated methods, configuration options, and package-level functions. It serves as a comprehensive guide for setting up and initializing the operator, as well as understanding integration patterns. ### Methods - **Operator.New()**: Constructor for the Operator. - **Operator.NewWithOptions(options Options)**: Constructor for the Operator with custom options. - **Operator.GetName()**: Returns the name of the operator. - **Operator.InitScheme()**: Initializes the operator's scheme. - **Operator.InitFlags()**: Initializes operator command-line flags. - **Operator.ValidateFlags()**: Validates the operator's command-line flags. - **Operator.GetUncacheableTypes()**: Returns a list of uncacheable types. - **Operator.Setup()**: Sets up the operator. ### Package-Level Functions - **GetName()**: Returns the package name. - **InitScheme()**: Initializes the scheme for the package. - **InitFlags()**: Initializes command-line flags for the package. - **ValidateFlags()**: Validates command-line flags for the package. - **GetUncacheableTypes()**: Returns a list of uncacheable types for the package. - **Setup()**: Sets up the package. ### Options Configuration - **Options**: Structure for configuring operator options. ``` -------------------------------- ### Registering Webhook in Operator Setup Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/api-reference-webhook.md This Go code snippet shows the `Setup` method of the `Operator` struct, where the webhook is registered with the controller manager. It's part of the operator's initialization process. ```go func (o *Operator) Setup(mgr ctrl.Manager) error { // ... initialize resource generator ... // Register controller if err := component.NewReconciler[*operatorv1alpha1.Valkey]( // ... ).SetupWithManager(mgr); err != nil { return errors.Wrapf(err, "unable to create controller") } // Register webhook operatorv1alpha1.NewWebhook().SetupWithManager(mgr) return nil } ``` -------------------------------- ### SentinelProperties Configuration Example Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/types.md An example of how to configure SentinelProperties, enabling Sentinel mode and specifying resource requests for the Sentinel container. This configuration is used within the ValkeySpec. ```yaml sentinel: &SentinelProperties{ Enabled: true, KubernetesContainerProperties: component.KubernetesContainerProperties{ Resources: corev1.ResourceRequirements{ Requests: corev1.ResourceList{ corev1.ResourceCPU: resource.MustParse("100m"), corev1.ResourceMemory: resource.MustParse("128Mi"), }, }, }, } ``` -------------------------------- ### Example Valkey Resource Definition Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/api-reference-valkey-resource.md An example YAML definition for a Valkey resource, showcasing various configuration options including version, replicas, sentinel, metrics, TLS, persistence, and resource requests/limits. ```yaml apiVersion: cache.cs.sap.com/v1alpha1 kind: Valkey metadata: name: my-cache namespace: default spec: version: "7.2" replicas: 3 sentinel: enabled: true resources: requests: cpu: 100m memory: 128Mi metrics: enabled: true resources: requests: cpu: 50m memory: 64Mi tls: enabled: true certManager: {} persistence: enabled: true size: 10Gi storageClass: fast binding: secretName: my-cache-binding resources: requests: cpu: 250m memory: 512Mi limits: cpu: 500m memory: 1Gi nodeSelector: workload: cache podAnnotations: prometheus.io/scrape: "true" ``` -------------------------------- ### Install Valkey Cluster for PVC Creation Source: https://github.com/sap/valkey-operator/blob/main/pkg/operator/data/charts/valkey/README.md Install the Valkey cluster with specific configurations to create the necessary Persistent Volume Claims (PVCs) for data restoration. ```bash helm install new-valkey -f values.yaml . --set cluster.enabled=true --set cluster.replicaCount=3 ``` -------------------------------- ### Example: Add Valkey API to Scheme Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/api-group-version.md Demonstrates how to create a new Kubernetes runtime scheme and add the Valkey API types to it using the AddToScheme function. ```go import ( "github.com/sap/valkey-operator/api/v1alpha1" "k8s.io/apimachinery/pkg/runtime" ) scheme := runtime.NewScheme() if err := v1alpha1.AddToScheme(scheme); err != nil { panic(err) } ``` -------------------------------- ### SetupWithManager Webhook Registration Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/api-reference-webhook.md Registers the webhook with a controller manager. This is called by the operator during setup to install the admission webhook HTTP handler. ```go func (w *Webhook) SetupWithManager(mgr manager.Manager) ``` ```go webhook := v1alpha1.NewWebhook() webhook.SetupWithManager(mgr) ``` -------------------------------- ### Valkey Informer Setup Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/api-group-version.md Create a shared informer factory and obtain a specific informer for Valkey resources using the Cache().V1alpha1().Valkeys() method. ```go import "github.com/sap/valkey-operator/pkg/client/informers/externalversions" factory := externalversions.NewSharedInformerFactory(clientset, time.Minute*10) valkeyInformer := factory.Cache().V1alpha1().Valkeys() ``` -------------------------------- ### ObjectReference Example Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/types.md An example of how to define an ObjectReference for a cert-manager ClusterIssuer. This specifies the API group, kind, and name of the desired Kubernetes object. ```go issuer: &ObjectReference{ Group: "cert-manager.io", Kind: "ClusterIssuer", Name: "letsencrypt-prod", } ``` -------------------------------- ### Example Operator Deployment Configuration Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/configuration.md This YAML manifest demonstrates how to deploy the Valkey operator. It includes arguments for configuring metrics, health probes, webhooks, leader election, and logging levels. ```yaml apiVersion: apps/v1 kind: Deployment metadata: name: valkey-operator namespace: valkey-operator-system spec: template: spec: containers: - name: controller image: valkey-operator:latest args: - --metrics-bind-address=:8080 - --health-probe-bind-address=:8081 - --webhook-bind-address=:2443 - --leader-elect=true - --zap-log-level=info ports: - name: metrics containerPort: 8080 - name: health containerPort: 8081 - name: webhook containerPort: 2443 ``` -------------------------------- ### Valid Binding Template Example Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/errors.md This YAML shows a correctly formatted binding template using Go template syntax for host, port, and password. ```yaml spec: binding: template: | { "host": "{{ .host }}", "port": {{ .port }}, "password": "{{ .password }}" } ``` -------------------------------- ### Valkey Entrypoint Scripts Source: https://github.com/sap/valkey-operator/blob/main/pkg/operator/data/charts/valkey/templates/NOTES.txt These commands show the entrypoint scripts for starting Valkey and Valkey Sentinel in diagnostic mode. They are used to replicate container startup behavior. ```bash /opt/bitnami/scripts/valkey/entrypoint.sh /opt/bitnami/scripts/valkey/run.sh ``` ```bash /opt/bitnami/scripts/valkey-sentinel/entrypoint.sh /opt/bitnami/scripts/valkey-sentinel/run.sh ``` -------------------------------- ### Create Clientset from REST Client Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/client-library.md Initializes a Valkey clientset using a pre-configured raw REST client interface. This is useful when you have a custom REST client setup. ```go restClient, _ := rest.RESTClientFor(config) clientset := versioned.New(restClient) ``` -------------------------------- ### Example ConfigMap Usage Source: https://github.com/sap/valkey-operator/blob/main/pkg/operator/data/charts/valkey/charts/common/README.md This ConfigMap demonstrates how to use the `common.names.fullname` helper to generate a unique name for resources within your Helm chart. ```yaml apiVersion: v1 kind: ConfigMap metadata: name: {{ include "common.names.fullname" . }} data: myvalue: "Hello World" ``` -------------------------------- ### Example: Invalid Binding Template Syntax Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/api-reference-webhook.md This example shows a Valkey resource with an invalid syntax in its binding template. The webhook will reject such resources, returning a detailed parse error. ```yaml apiVersion: cache.cs.sap.com/v1alpha1 kind: Valkey metadata: name: my-cache spec: binding: template: "{{ invalid syntax }}" ``` -------------------------------- ### Create New Operator Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/api-reference-operator.md Instantiates a new Valkey operator with default configurations. Use this for basic operator setup. ```go op := operator.New() ``` -------------------------------- ### Example: Attempting Immutable Update Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/api-reference-webhook.md This example demonstrates an attempt to update an immutable field (`spec.sentinel.enabled`) in a Valkey resource. Such attempts will result in an HTTP 422 Unprocessable Entity error. ```yaml # Original resource apiVersion: cache.cs.sap.com/v1alpha1 kind: Valkey metadata: name: my-cache spec: sentinel: enabled: false --- # Attempting to update apiVersion: cache.cs.sap.com/v1alpha1 kind: Valkey metadata: name: my-cache spec: sentinel: enabled: true ``` -------------------------------- ### Setup Operator with Controller Manager Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/api-reference-operator.md Configures the operator with a controller manager, initializing necessary components like resource generators, transformers, controllers, and webhooks. This is a crucial step before running the operator. ```go mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{}) if err != nil { log.Fatal(err) } if err := operator.Setup(mgr); err != nil { log.Fatal(err) } ``` -------------------------------- ### Get a Valkey Resource using Go Client Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/INDEX.md Initializes the Valkey Go client and retrieves a specific Valkey resource from the 'default' namespace. Requires the 'github.com/sap/valkey-operator/pkg/client/clientset/versioned' package. ```go import "github.com/sap/valkey-operator/pkg/client/clientset/versioned" clientset, err := versioned.NewForConfig(config) valkeyClient := clientset.CacheV1alpha1().Valkey("default") valkey, err := valkeyClient.Get(ctx, "my-cache", metav1.GetOptions{}) ``` -------------------------------- ### Configure PrometheusRule for Alerting Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/configuration.md Define Prometheus alerting rules for Valkey. This example sets up an alert for when the Valkey service is down. ```yaml spec: metrics: enabled: true prometheusRule: enabled: true additionalLabels: prometheus: kube-prometheus rules: - alert: ValkeyDown expr: up{job="valkey"} == 0 for: 5m annotations: summary: "Valkey is down" ``` -------------------------------- ### Enable TLS with cert-manager (empty config) Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/types.md Example of enabling TLS with cert-manager, relying on default auto-generated self-signing issuer. ```yaml tls: enabled: true certManager: {} # Use cert-manager with auto-generated self-signing issuer ``` -------------------------------- ### Default Binding Template Example Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/types.md Illustrates the default YAML structure generated for a service binding secret when no custom template is provided. ```yaml host: valkey-myapp.default.svc.cluster.local port: "6379" password: generated-password tlsEnabled: "true" sentinelEnabled: "true" caData: | -----BEGIN CERTIFICATE----- ... -----END CERTIFICATE----- ``` -------------------------------- ### Scheme Registration Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/api-group-version.md Demonstrates how to register Valkey types into a Kubernetes runtime scheme, both manually and as used within the operator's setup. ```APIDOC ## Scheme Registration ### Manual Registration To register Valkey types in a runtime scheme: ```go import ( "k8s.io/apimachinery/pkg/runtime" "github.com/sap/valkey-operator/api/v1alpha1" ) var scheme = runtime.NewScheme() func init() { v1alpha1.AddToScheme(scheme) } ``` ### Used in Operator Setup The operator's main.go registers the scheme: ```go func init() { utilruntime.Must(clientgoscheme.AddToScheme(scheme)) utilruntime.Must(apiextensionsv1.AddToScheme(scheme)) utilruntime.Must(apiregistrationv1.AddToScheme(scheme)) operator.InitScheme(scheme) // Registers v1alpha1 types } ``` ``` -------------------------------- ### Setup Valkey Operator with Controller Manager Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/api-reference-operator.md Sets up the Valkey operator with a controller manager. This is the primary integration point for the operator within a Kubernetes controller runtime environment. Ensure configuration and dependencies are correctly handled before calling. ```go package main import ( "github.com/sap/valkey-operator/pkg/operator" ctrl "sigs.k8s.io/controller-runtime" ) func main() { mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{}) if err != nil { panic(err) } if err := operator.Setup(mgr); err != nil { panic(err) } if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil { panic(err) } } ``` -------------------------------- ### Environment Variable Binding Template Example Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/api-reference-binding.md Format binding information as environment variables for easy consumption by applications. Includes host, port, password, and TLS status. ```yaml spec: binding: template: | REDIS_HOST={{ .host }} REDIS_PORT={{ .port }} REDIS_PASSWORD={{ .password }} REDIS_TLS={{ .tlsEnabled }} ``` -------------------------------- ### Enable ExternalDNS Integration Source: https://github.com/sap/valkey-operator/blob/main/pkg/operator/data/charts/valkey/README.md Configure the chart to leverage the ExternalDNS project for publishing FQDNs. Set 'useExternalDNS.enabled' to true and provide a 'suffix'. This requires a working installation of external-dns. ```yaml useExternalDNS: enabled: true suffix: prod.example.org additionalAnnotations: ttl: 10 ``` -------------------------------- ### Configure Pod Tolerations Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/configuration.md Apply tolerations to pods to allow them to be scheduled on nodes with matching taints. This example includes tolerations for control-plane nodes and custom taints. ```yaml spec: tolerations: - key: node-role.kubernetes.io/control-plane operator: Exists effect: NoSchedule - key: custom-taint operator: Equal value: true effect: NoExecute tolerationSeconds: 3600 ``` -------------------------------- ### JSON Binding Template Example Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/api-reference-binding.md Use this template to format binding information as a JSON object. It includes host, port, password, TLS status, and CA data if available. ```yaml spec: binding: secretName: valkey-config template: | { "host": "{{ .host }}", "port": {{ .port }}, "password": "{{ .password }}", "tls": {{ .tlsEnabled }}, "ca": {{ if .caData }}{{ .caData | quote }}{{ else }}null{{ end }} } ``` -------------------------------- ### Using Existing Secrets in a Deployment Source: https://github.com/sap/valkey-operator/blob/main/pkg/operator/data/charts/valkey/charts/common/README.md Example demonstrating how to use an existing secret for sensitive data like passwords in a Kubernetes deployment. It utilizes `common.secrets.name` and `common.secrets.key` helpers. ```yaml # templates/secret.yaml --- apiVersion: v1 kind: Secret metadata: name: {{ include "common.names.fullname" . }} labels: app: {{ include "common.names.fullname" . }} type: Opaque data: password: {{ .Values.password | b64enc | quote }} # templates/dpl.yaml --- ... env: - name: PASSWORD valueFrom: secretKeyRef: name: {{ include "common.secrets.name" (dict "existingSecret" .Values.existingSecret "context" $) }} key: {{ include "common.secrets.key" (dict "existingSecret" .Values.existingSecret "key" "password") }} ... ``` ```yaml # values.yaml --- name: mySecret keyMapping: password: myPasswordKey ``` -------------------------------- ### Read Connection Details from Mounted Secret Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/api-reference-binding.md Example of how an application can read connection details like host, port, and password from files within the mounted secret directory. ```bash # Sentinel mode HOST=$(cat /etc/binding/host) SENTINEL_PORT=$(cat /etc/binding/sentinelPort) PASSWORD=$(cat /etc/binding/password) # Connect to Sentinel first to discover primary redis-cli -h $HOST -p $SENTINEL_PORT SENTINEL masters ``` -------------------------------- ### Template Rendering Example Data Transformation Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/api-reference-binding.md Demonstrates the conversion of rendered YAML template output into stored secret data. String and non-string values are handled differently. ```yaml host: redis.default.svc.cluster.local port: 6379 metrics: enabled: true ``` ```yaml host: "redis.default.svc.cluster.local" port: "6379" metrics: "{\"enabled\":true}" ``` -------------------------------- ### Main Valkey Operator Execution Flow Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/api-reference-operator.md The main function orchestrates the Valkey operator's lifecycle, including flag parsing, validation, manager creation, controller setup, and starting the manager. It handles errors during these critical steps by logging and exiting. ```go func main() { // Parse flags operator.InitFlags(flag.CommandLine) flag.Parse() // Validate flags if err := operator.ValidateFlags(); err != nil { setupLog.Error(err, "error validating flags") os.Exit(1) } // Create and configure manager mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{ Scheme: scheme, // ... other options }) if err != nil { setupLog.Error(err, "unable to start manager") os.Exit(1) } // Set up operator if err := operator.Setup(mgr); err != nil { setupLog.Error(err, "error registering controller") os.Exit(1) } // Start manager if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil { setupLog.Error(err, "problem running manager") os.Exit(1) } } ``` -------------------------------- ### Run Valkey Client Pod Source: https://github.com/sap/valkey-operator/blob/main/pkg/operator/data/charts/valkey/templates/NOTES.txt Launches a client pod for interacting with the Valkey deployment. Includes environment variables for authentication if enabled. ```bash kubectl run --namespace {{ include "common.names.namespace" . }} valkey-client --restart='Never' {{ if .Values.auth.enabled }} --env VALKEY_PASSWORD=$VALKEY_PASSWORD {{ end }} --image {{ template "valkey.image" . }} --command -- sleep infinity ``` -------------------------------- ### Create Clientset from Config (Panic on Error) Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/client-library.md Constructs a new Valkey clientset from a Kubernetes REST config, panicking if an error occurs during creation. Use this when failure is not an option. ```go clientset := versioned.NewForConfigOrDie(rest.InClusterConfig()) ``` -------------------------------- ### Valkey Binding Secret Example Source: https://github.com/sap/valkey-operator/blob/main/README.md An example of a generated binding secret containing connection details for a Valkey instance. This secret is used by clients to connect to the cache. ```yaml apiVersion: v1 kind: Secret metadata: name: valkey-test-binding type: Opaque stringData: caData: | -----BEGIN CERTIFICATE----- ... -----END CERTIFICATE----- host: valkey-test.testns.svc.cluster.local primaryName: myprimary password: BM5vR1ziGE port: "6379" sentinelEnabled: "true" sentinelHost: valkey-test.testns.svc.cluster.local sentinelPort: "26379" tlsEnabled: "true" ``` -------------------------------- ### Configure Main Valkey Container Resources Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/configuration.md Set CPU and memory requests and limits for the main Valkey container. Ensure these values align with your expected workload and cluster capacity. ```yaml spec: resources: requests: cpu: 250m memory: 512Mi limits: cpu: 1000m memory: 2Gi ``` -------------------------------- ### Get() Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/client-library.md Retrieves a specific Valkey resource by its name. This method fetches the details of a single Valkey resource. ```APIDOC ## Get() ### Description Retrieves a specific Valkey resource by its name. ### Method ```go func (v *valkey) Get(ctx context.Context, name string, opts metav1.GetOptions) (*Valkey, error) ``` ### Parameters #### Path Parameters - **ctx** (context.Context) - Required - Context for the operation - **name** (string) - Required - The name of the Valkey resource to retrieve - **opts** (metav1.GetOptions) - Required - Options for retrieving the resource ``` -------------------------------- ### Create New Webhook Instance Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/api-reference-webhook.md Instantiates a new Webhook validator. No specific setup is required before calling this function. ```go webhook := v1alpha1.NewWebhook() ``` -------------------------------- ### Operator Package Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/INDEX.md Details the core Operator type, its configuration options, and associated functions for initialization, setup, and management. ```APIDOC ## Operator Package ### Description This section describes the main `Operator` type and its related functionalities for managing Valkey clusters. ### Types - `Operator`: The main operator struct. - `Options`: Configuration options for the operator. ### Constants - `Name`: The name of the operator. ### Functions - `New()`: Creates a new operator instance. - `NewWithOptions(opts Options)`: Creates a new operator instance with specified options. - `GetName()`: Returns the operator's name. - `InitScheme()`: Initializes the operator's scheme. - `InitFlags()`: Initializes operator flags. - `ValidateFlags()`: Validates operator flags. - `GetUncacheableTypes()`: Retrieves uncacheable types. - `Setup()`: Sets up the operator. ``` -------------------------------- ### Connect to Valkey CLI (Replication with Sentinel) Source: https://github.com/sap/valkey-operator/blob/main/pkg/operator/data/charts/valkey/templates/NOTES.txt Connects to the Valkey cluster using the Valkey CLI. Supports authentication and TLS. Provides commands for read-only operations and Sentinel access. ```bash {{ if .Values.auth.enabled }}REDISCLI_AUTH="$VALKEY_PASSWORD" {{ end }}valkey-cli -h {{ template "common.names.fullname" . }} -p {{ .Values.sentinel.service.ports.valkey }}{{ if .Values.tls.enabled }} --tls --cert /tmp/client.cert --key /tmp/client.key --cacert /tmp/CA.cert{{ end }} # Read only operations ``` ```bash {{ if .Values.auth.enabled }}REDISCLI_AUTH="$VALKEY_PASSWORD" {{ end }}valkey-cli -h {{ template "common.names.fullname" . }} -p {{ .Values.sentinel.service.ports.sentinel }}{{ if .Values.tls.enabled }} --tls --cert /tmp/client.cert --key /tmp/client.key --cacert /tmp/CA.cert{{ end }} # Sentinel access ``` -------------------------------- ### Initialize Valkey Operator Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/INDEX.md Initializes the operator's scheme, parses command-line flags, and sets up the manager. Ensure necessary imports are present. ```go import "github.com/sap/valkey-operator/pkg/operator" // Initialize scheme operator.InitScheme(scheme) // Parse flags operator.InitFlags(flag.CommandLine) flag.Parse() // Setup with manager if err := operator.Setup(mgr); err != nil { log.Fatal(err) } ``` -------------------------------- ### Enable TLS with cert-manager (existing ClusterIssuer) Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/types.md Example of enabling TLS with cert-manager, specifying an existing ClusterIssuer for certificate management. ```yaml tls: enabled: true certManager: issuer: kind: ClusterIssuer name: letsencrypt-prod ``` -------------------------------- ### InitScheme() Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/api-reference-operator.md Adds the Valkey API types to the Kubernetes runtime scheme. Must be called before using the operator. ```APIDOC ## InitScheme(scheme *runtime.Scheme) ### Description Adds the Valkey API types to the Kubernetes runtime scheme. Must be called before using the operator. ### Parameters #### Path Parameters - `scheme` (*runtime.Scheme) - Required - The runtime scheme to add types to ### Example ```go scheme := runtime.NewScheme() operator.InitScheme(scheme) ``` ``` -------------------------------- ### Create Clientset from Config Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/client-library.md Constructs a new Valkey clientset using an existing Kubernetes REST configuration. Ensure the configuration is valid and includes proper authentication. ```go import "github.com/sap/valkey-operator/pkg/client/clientset/versioned" config := rest.InClusterConfig() clientset, err := versioned.NewForConfig(config) if err != nil { panic(err) } ``` -------------------------------- ### Get Discovery Client Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/client-library.md Obtains the discovery client, which allows for API group and resource discovery within the Kubernetes cluster. ```go func (c *Clientset) Discovery() discovery.DiscoveryInterface ``` -------------------------------- ### Connect to Valkey CLI (Single Primary) Source: https://github.com/sap/valkey-operator/blob/main/pkg/operator/data/charts/valkey/templates/NOTES.txt Connects to a single primary Valkey instance. Supports authentication and TLS. ```bash {{ if .Values.auth.enabled }}REDISCLI_AUTH="$VALKEY_PASSWORD" {{ end }}valkey-cli -h {{ template "common.names.fullname" . }}-primary{{ if .Values.tls.enabled }} --tls --cert /tmp/client.cert --key /tmp/client.key --cacert /tmp/CA.cert{{ end }} ``` -------------------------------- ### New Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/client-library.md Constructs a new clientset from a raw REST client interface. This is useful when you need more control over the underlying REST client. ```APIDOC ## Function New ### Description Creates a clientset from a raw REST client. ### Signature ```go func New(c rest.Interface) *Clientset ``` ### Parameters #### Path Parameters - `c` (rest.Interface) - Raw REST client interface ### Returns - `*Clientset` - A new clientset. ### Example ```go restClient, _ := rest.RESTClientFor(config) clientset := versioned.New(restClient) ``` ``` -------------------------------- ### Invalid Binding Template Example Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/errors.md This YAML demonstrates an invalid binding template with an unclosed Go template action, leading to an error. ```yaml spec: binding: template: | host: {{ .host port: {{ .port }} ``` -------------------------------- ### InitScheme(scheme *runtime.Scheme) Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/api-reference-operator.md Adds Valkey API types to a given runtime scheme. ```APIDOC ## InitScheme(scheme *runtime.Scheme) ### Description Adds Valkey API types to the provided runtime scheme. ### Parameters #### Path Parameters - `scheme` (*runtime.Scheme) - Required - The runtime scheme to add types to ### Example ```go var scheme = runtime.NewScheme() func init() { utilruntime.Must(clientgoscheme.AddToScheme(scheme)) utilruntime.Must(operator.InitScheme(scheme)) } ``` ``` -------------------------------- ### Connect to Valkey CLI (Replication without Sentinel) Source: https://github.com/sap/valkey-operator/blob/main/pkg/operator/data/charts/valkey/templates/NOTES.txt Connects to the Valkey cluster in replication mode without Sentinel. Supports authentication and TLS for primary and replica connections. ```bash {{ if .Values.auth.enabled }}REDISCLI_AUTH="$VALKEY_PASSWORD" {{ end }}valkey-cli -h {{ printf "%s-primary" (include "common.names.fullname" .) }}{{ if .Values.tls.enabled }} --tls --cert /tmp/client.cert --key /tmp/client.key --cacert /tmp/CA.cert{{ end }} ``` ```bash {{ if .Values.auth.enabled }}REDISCLI_AUTH="$VALKEY_PASSWORD" {{ end }}valkey-cli -h {{ printf "%s-replicas" (include "common.names.fullname" .) }}{{ if .Values.tls.enabled }} --tls --cert /tmp/client.cert --key /tmp/client.key --cacert /tmp/CA.cert{{ end }} ``` -------------------------------- ### Backup Valkey Data using valkey-cli Source: https://github.com/sap/valkey-operator/blob/main/pkg/operator/data/charts/valkey/README.md Execute valkey-cli commands to authenticate and save the current dataset to a dump file. ```text $ kubectl exec -it my-release-primary-0 bash $ valkey-cli 127.0.0.1:6379> auth your_current_valkey_password OK 127.0.0.1:6379> save OK ``` -------------------------------- ### Get Valkey Resource by Name Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/client-library.md Retrieves a single Valkey resource by its name within a specific namespace. Requires a namespace-scoped lister. ```go func (v *valkeyNamespaceLister) Get(name string) (*Valkey, error) ``` ```go namespaceLister := lister.Valkeys("default") valkey, err := namespaceLister.Get("my-cache") ``` -------------------------------- ### Get Valkey Resource Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/client-library.md Retrieves a single Valkey resource by its name. Returns the resource if found, or an error (e.g., NotFound) if it does not exist. ```APIDOC ## Get() Valkey Resource ### Description Retrieves a single Valkey resource by name. ### Method Signature ```go func (v *valkey) Get(ctx context.Context, name string, opts metav1.GetOptions) (*Valkey, error) ``` ### Parameters #### Path Parameters - **name** (string) - Required - The resource name. - **opts** (metav1.GetOptions) - Required - Get options (ResourceVersion, etc.). ### Returns - `(*Valkey, error)` - The requested resource or error (NotFound if missing). ### Example ```go valkey, err := valkeyClient.Get(context.Background(), "my-cache", metav1.GetOptions{}) if err != nil { if apierrors.IsNotFound(err) { fmt.Println("Valkey not found") } } ``` ``` -------------------------------- ### Watch() Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/client-library.md Starts watching for changes to Valkey resources. This method returns an interface that can be used to receive events related to Valkey resources. ```APIDOC ## Watch() ### Description Starts watching for changes to Valkey resources. ### Method ```go func (v *valkey) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) ``` ### Parameters #### Path Parameters - **ctx** (context.Context) - Required - Context for the operation - **opts** (metav1.ListOptions) - Required - Options for watching the resources ``` -------------------------------- ### Create() Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/client-library.md Creates a new Valkey resource. This method allows for the instantiation of a new Valkey custom resource within the cluster. ```APIDOC ## Create() ### Description Creates a new Valkey resource. ### Method ```go func (v *valkey) Create(ctx context.Context, valkey *Valkey, opts metav1.CreateOptions) (*Valkey, error) ``` ### Parameters #### Path Parameters - **ctx** (context.Context) - Required - Context for the operation - **valkey** (*Valkey) - Required - The Valkey resource to create - **opts** (metav1.CreateOptions) - Required - Creation options (FieldManager, DryRun, etc.) ### Response #### Success Response (200) - **Valkey** (*Valkey) - The created resource - **error** (error) - An error if the creation failed ``` -------------------------------- ### Custom Binding Template (YAML) Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/api-reference-binding.md An example of a custom template provided by users via spec.binding.template. This template generates a JSON URL string. ```yaml spec: binding: template: | { "url": "redis://:{{ .password }}@{{ .host }}:{{ .port }}", "tls": {{ .tlsEnabled }}, "caBundle": {{ .caData | quote }} } ``` -------------------------------- ### NewForConfigOrDie Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/client-library.md Constructs a new clientset for the given Kubernetes REST config, panicking if there is an error. This is a convenience function for cases where an error is unrecoverable. ```APIDOC ## Function NewForConfigOrDie ### Description Creates a clientset or panics if there's an error. ### Signature ```go func NewForConfigOrDie(c *rest.Config) *Clientset ``` ### Parameters #### Path Parameters - `c` (*rest.Config) - Kubernetes REST configuration ### Returns - `*Clientset` - A new clientset, or panics. ### Example ```go clientset := versioned.NewForConfigOrDie(rest.InClusterConfig()) ``` ``` -------------------------------- ### Configure Pod Priority Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/configuration.md Assign a priority class to pods to influence their scheduling order. This example sets the 'high-priority' class for critical workloads. ```yaml spec: priorityClassName: high-priority ``` -------------------------------- ### Create Valkey Instance Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/INDEX.md Defines a Valkey custom resource with specified replicas, persistence, metrics, and TLS settings. This is used to provision a new Valkey cluster. ```go valkey := &v1alpha1.Valkey{ ObjectMeta: metav1.ObjectMeta{ Name: "prod-cache", Namespace: "production", }, Spec: v1alpha1.ValkeySpec{ Replicas: 5, Sentinel: &v1alpha1.SentinelProperties{ Enabled: true, }, Metrics: &v1alpha1.MetricsProperties{ Enabled: true, }, TLS: &v1alpha1.TLSProperties{ Enabled: true, CertManager: &v1alpha1.CertManagerProperties{ Issuer: &v1alpha1.ObjectReference{ Kind: "ClusterIssuer", Name: "letsencrypt-prod", }, }, }, Persistence: &v1alpha1.PersistenceProperties{ Enabled: true, Size: resource.NewQuantity(50*1024*1024*1024, resource.BinarySI), StorageClass: "fast-ssd", }, }, } ``` -------------------------------- ### Get v1alpha1 Cache Client Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/client-library.md Retrieves the typed client specifically for interacting with v1alpha1 Valkey resources within the cache API group. ```go func (c *Clientset) CacheV1alpha1() cachev1alpha1.CacheV1alpha1Interface ``` -------------------------------- ### List Valkey Resources with Selector Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/client-library.md Lists all Valkey resources that match a given label selector. Ensure you have a valid labels.Selector object. ```go func (s *valkeyLister) List(selector labels.Selector) ([]*Valkey, error) ``` ```go lister := informerFactory.Cache().V1alpha1().Valkeys().Lister() selector, _ := labels.Parse("app=cache") valkeyList, err := lister.List(selector) ``` -------------------------------- ### versioned.Interface Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/client-library.md The main clientset interface provides access to resource clients and discovery for Valkey resources. ```APIDOC ## Interface versioned.Interface ### Description Main clientset interface providing access to resource clients and discovery. ### Methods - `Discovery() discovery.DiscoveryInterface` - `CacheV1alpha1() cachev1alpha1.CacheV1alpha1Interface` ``` -------------------------------- ### ValkeyNamespaceLister.Get Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/client-library.md Gets a single Valkey resource by name within a specific namespace. This method is part of the ValkeyNamespaceLister interface for accessing namespace-scoped Valkey resources. ```APIDOC ## ValkeyNamespaceLister.Get ### Description Gets a single Valkey resource by name. ### Method Get ### Parameters #### Path Parameters - **name** (string) - Required - The name of the Valkey resource to retrieve. ### Response #### Success Response (200) - **Valkey** (*Valkey) - A pointer to the requested Valkey resource. - **err** (error) - An error if the retrieval fails. ``` -------------------------------- ### Create a Valkey Resource Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/INDEX.md Defines a Valkey custom resource with specified replicas, sentinel, metrics, TLS, and persistence settings. Ensure the namespace is correctly set. ```yaml apiVersion: cache.cs.sap.com/v1alpha1 kind: Valkey metadata: name: my-cache namespace: default spec: replicas: 3 sentinel: enabled: true metrics: enabled: true tls: enabled: true persistence: enabled: true size: 10Gi ``` -------------------------------- ### Get Valkey Resource Source: https://github.com/sap/valkey-operator/blob/main/_autodocs/client-library.md Retrieves a single Valkey resource by name. Use this to fetch a specific Valkey instance. Handles 'NotFound' errors gracefully. ```go valkey, err := valkeyClient.Get(context.Background(), "my-cache", metav1.GetOptions{}) ```