### Install golangci-lint Source: https://github.com/kedacore/keda/blob/main/CONTRIBUTING.md Install the golangci-lint tool using a script or Homebrew. This tool performs static analysis on Go code. ```bash curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin v2.11.4 ``` ```bash brew install golangci/tap/golangci-lint ``` -------------------------------- ### Install pre-commit Tool Source: https://github.com/kedacore/keda/blob/main/CONTRIBUTING.md Install the pre-commit tool using pip or Homebrew to ensure code quality locally. Python 3.6 or newer is required. ```bash pip install pre-commit ``` ```bash brew install pre-commit ``` -------------------------------- ### Customize KEDA Test Setup with YAML Source: https://github.com/kedacore/keda/blob/main/tests/README.md Configure KEDA test setup parameters using a YAML file. This includes options to skip setup/cleanup phases and specify custom image registries and repositories for KEDA deployment during tests. ```yaml keda: # These are the default values. skipSetup: false # If true, the test script will skip the setup phase. skipCleanup: false # If true, the test script will skip the cleanup phase. imageRegistry: "" imageRepo: "" ``` -------------------------------- ### Run All KEDA E2E Tests Source: https://github.com/kedacore/keda/blob/main/tests/README.md Execute all end-to-end tests for KEDA. Ensure you are in the `keda/tests` directory. This command runs setup, all tests, and cleanup. ```bash go test -v -tags e2e ./utils/setup_test.go # Only needs to be run once. go test -v -tags e2e ./scalers/... go test -v -tags e2e ./utils/cleanup_test.go # Skip if you want to keep testing. ``` -------------------------------- ### Run KEDA E2E Tests with Custom Configuration Source: https://github.com/kedacore/keda/blob/main/tests/README.md Execute KEDA end-to-end tests using a custom configuration file. This allows for flexible test setup and execution, such as running tests without deploying KEDA or using custom KEDA images. ```bash E2E_TEST_CONFIG=tests/example-config.yaml go test -v -tags e2e ./tests/run-all.go ``` -------------------------------- ### Run Specific KEDA E2E Test File Source: https://github.com/kedacore/keda/blob/main/tests/README.md Execute a specific end-to-end test file, such as for the Azure Queue scaler. Assumes that the test setup has already been completed. ```bash go test -v -tags e2e ./scalers/azure/azure_queue/azure_queue_test.go # Assumes that setup has been run before ``` -------------------------------- ### E2E Redis Scaler Test in Go Source: https://github.com/kedacore/keda/blob/main/tests/README.md This Go code defines an end-to-end test for the KEDA Redis scaler. It includes setup, resource creation, scale-out testing, and cleanup logic. Ensure the `// +build e2e` tag is present for proper test execution. ```go // +build e2e // ^ This is necessary to ensure the tests don't get run in the GitHub workflow. import ( "context" "fmt" "os" "testing" "github.com/joho/godotenv" "github.com/stretchr/testify/require" // Other required imports ... ... . "github.com/kedacore/keda/v2/tests/helper" // For helper methods ) var _ = godotenv.Load("../../.env") // For loading env variables from .env const ( testName = "redis-test" // Other constants required for your test ... ... ) var ( testNamespace = fmt.Sprintf("%s-ns", testName) // Other variables required for your test ... ... ) // YAML templates for your Kubernetes resources const ( deploymentTemplate = ` apiVersion: apps/v1 kind: Deployment metadata: name: test-deployment labels: app: test-deployment spec: replicas: 0 ... ... ` ... ... ) type templateData struct { // Fields used in your Kubernetes YAML templates ... ... } func TestScaler(t *testing.T) { setupTest(t) kc := GetKubernetesClient(t) data, templates := getTemplateData() CreateKubernetesResources(t, kc, testNamespace, data, templates) testScaleOut(t) // Ensure that this gets run. Using defer is necessary DeleteKubernetesResources(t, testNamespace, data, templates) cleanupTest(t) } func setupTest(t *testing.T) { t.Log("--- setting up ---") _, err := ParseCommand("which helm").Output() assert.NoErrorf(t, err, "redis test requires helm - %s", err) _, err := ParseCommand("helm install redis .....").Output() assert.NoErrorf(t, err, "error while installing redis - %s", err) } func getTemplateData() (templateData, []Template) { return templateData{ // Populate fields required in YAML templates ... ... }, []Template{ {Name: "deploymentTemplate", Config: deploymentTemplate}, {Name: "scaledObjectTemplate", Config: scaledObjectTemplate}, } } func testScaleOut(t *testing.T, kc *kubernetes.Clientset) { t.Log("--- testing scale out ---") // Use Go Redis Library to add stuff to redis to trigger scale out. ... ... // Sleep / poll for replica count using helper method. // Duration should be iterations * intervalSeconds require.True(t, WaitForDeploymentReplicaReadyCount(t, kc, deploymentName, testNamespace, 10, 60, 1), "replica count should be 10 after 1 minute") } func cleanupTest(t *testing.T) { t.Log("--- cleaning up ---") // Cleanup external resources (such as Blob Storage Container, RabbitMQ queue, Redis in this case) ... ... } ``` -------------------------------- ### Run KEDA E2E Tests with Environment Variables Source: https://github.com/kedacore/keda/blob/main/tests/README.md Override configuration file settings for KEDA end-to-end tests using environment variables. For example, `E2E_TEST_REGEX` can override `testCategories` filtering, and `E2E_INSTALL_KEDA=false` can prevent KEDA deployment. ```bash GOOS="darwin" go test -v -tags e2e ... IMAGE_REGISTRY=docker.io IMAGE_REPO=johndoe go test -v -tags e2e ./utils/setup_test.go ``` -------------------------------- ### Build, Publish, and Deploy Custom KEDA Images Source: https://github.com/kedacore/keda/blob/main/BUILD.md Commands to build and publish custom KEDA images to a registry and deploy them to a Kubernetes cluster. Requires setting IMAGE_REGISTRY and IMAGE_REPO environment variables. ```bash IMAGE_REGISTRY=docker.io IMAGE_REPO=johndoe make publish IMAGE_REGISTRY=docker.io IMAGE_REPO=johndoe make deploy ``` -------------------------------- ### Deploy KEDA CRDs and Components Source: https://github.com/kedacore/keda/blob/main/BUILD.md A Makefile command to deploy the necessary Custom Resource Definitions and KEDA components into the Kubernetes cluster. ```bash make deploy ``` -------------------------------- ### Configure VS Code Debugging for KEDA Metrics Server Source: https://github.com/kedacore/keda/blob/main/BUILD.md Defines the launch configuration for the Go debugger in VS Code to run the KEDA metrics adapter locally. It requires setting environment variables and command-line arguments to point to valid kubeconfig files. ```json { "configurations": [ { "name": "Launch metrics-server", "type": "go", "request": "launch", "mode": "auto", "program": "${workspaceFolder}/cmd/adapter/main.go", "env": { "WATCH_NAMESPACE": "", "KEDA_CLUSTER_OBJECT_NAMESPACE": "keda" }, "args": [ "--authentication-kubeconfig=PATH_TO_YOUR_KUBECONFIG", "--authentication-skip-lookup", "--authorization-kubeconfig=PATH_TO_YOUR_KUBECONFIG", "--lister-kubeconfig=PATH_TO_YOUR_KUBECONFIG", "--secure-port=6443", "--v=5" ] } ] } ``` -------------------------------- ### Configure VS Code Debugging for KEDA Operator Source: https://github.com/kedacore/keda/blob/main/BUILD.md Configuration for the .vscode/launch.json file to enable debugging the KEDA operator in Go. Includes environment variables for namespace configuration. ```json { "configurations": [ { "name": "Launch operator", "type": "go", "request": "launch", "mode": "debug", "program": "${workspaceFolder}/cmd/operator/main.go", "env": { "WATCH_NAMESPACE": "", "KEDA_CLUSTER_OBJECT_NAMESPACE": "keda" } } ] } ``` -------------------------------- ### Run Pre-commit Checks on All Files Source: https://github.com/kedacore/keda/blob/main/CONTRIBUTING.md Run all configured pre-commit checks across all files in your repository, regardless of staging status. ```bash pre-commit run --all-files ``` -------------------------------- ### Prepare Cluster for Operator Debugging Source: https://github.com/kedacore/keda/blob/main/BUILD.md Commands to deploy CRDs and scale down the existing KEDA operator deployment to prevent conflicts during local debugging. ```bash make deploy kubectl scale deployment/keda-operator --replicas=0 -n keda ``` -------------------------------- ### Writing Warning Log Messages in Go Source: https://github.com/kedacore/keda/blob/main/CONTRIBUTING.md Prefix warning messages with "Warning: " when using `logger.Info()`. These are for operational teams, indicating potential issues and suggesting next steps. ```go logger.Info("Warning: ...msg") ``` -------------------------------- ### Writing Info Log Messages in Go Source: https://github.com/kedacore/keda/blob/main/CONTRIBUTING.md Use `logger.Info(msg)` for info messages, suitable for engineers familiar with KEDA components. These messages act as status reports. ```go logger.Info(msg) ``` -------------------------------- ### Run Pre-commit Checks on Staged Files Source: https://github.com/kedacore/keda/blob/main/CONTRIBUTING.md Execute all configured pre-commit checks on your currently staged files. ```bash pre-commit run ``` -------------------------------- ### Trigger Specific E2E Tests with Regex Source: https://github.com/kedacore/keda/blob/main/tests/README.md Append a Go-compliant regex to the /run-e2e command to execute a subset of E2E tests. This is useful for reducing execution time and resource usage when changes are localized. ```bash /run-e2e desired-regex ``` ```bash # e.g: /run-e2e azure ``` -------------------------------- ### Enable Git Pre-commit Hooks Source: https://github.com/kedacore/keda/blob/main/CONTRIBUTING.md Enable pre-commit checks for your Git commit operations by running this command in your repository. ```bash pre-commit install ``` -------------------------------- ### Implement GetMetricSpecForScaling in Golang Source: https://github.com/kedacore/keda/blob/main/CREATE-NEW-SCALER.md Demonstrates how to implement the GetMetricSpecForScaling function to return a Kubernetes MetricSpec. It uses the GenerateMetricNameWithIndex helper to ensure unique metric naming conventions required by KEDA. ```golang func (s *artemisScaler) GetMetricSpecForScaling() []v2.MetricSpec { externalMetric := &v2.ExternalMetricSource{ Metric: v2.MetricIdentifier{ Name: GenerateMetricNameWithIndex(s.metadata.triggerIndex, kedautil.NormalizeString(fmt.Sprintf("%s-%s-%s", "artemis", s.metadata.brokerName, s.metadata.queueName))), }, Target: GetMetricTarget(s.metricType, s.metadata.queueLength), } metricSpec := v2.MetricSpec{External: externalMetric, Type: artemisMetricType} return []v2.MetricSpec{metricSpec} } ``` -------------------------------- ### GitHub Release Template for KEDA Source: https://github.com/kedacore/keda/blob/main/RELEASE-PROCESS.md This Markdown template is used when creating a new release on GitHub to ensure consistent communication of features, deprecations, and contributor information. It requires placeholders like 'INSERT-CORRECT-VERSION' to be updated before publication. ```markdown We are happy to release KEDA INSERT-CORRECT-VERSION 🎉 Here are some highlights: - Here are the new deprecation(s) as of this release: - Learn how to deploy KEDA by reading [our documentation](https://keda.sh/docs/INSERT-CORRECT-VERSION/deploy/). 🗓️ The next KEDA release is currently being estimated for , learn more in our [roadmap](https://github.com/kedacore/keda/blob/main/ROADMAP.md#upcoming-release-cycles). ### New - ### Improvements - ### Breaking Changes - ### Other - ### New Contributors ``` -------------------------------- ### Trigger E2E Tests in PR Source: https://github.com/kedacore/keda/blob/main/tests/README.md Use this command in a PR to trigger the full E2E test suite. This comment initiates a workflow that builds Docker images from the latest commit and tests them. ```bash /run-e2e ``` -------------------------------- ### Writing Debug Log Messages in Go Source: https://github.com/kedacore/keda/blob/main/CONTRIBUTING.md Use `logger.V(1).Info(msg)` for debug messages, intended for KEDA project developers. Ensure messages are data-rich and detailed. ```go logger.V(1).Info(msg) ``` -------------------------------- ### Writing Error Log Messages in Go Source: https://github.com/kedacore/keda/blob/main/CONTRIBUTING.md Use `logger.Error(err, msg)` to log errors, indicating a failure within a system component. Include the cause and possible solutions. ```go logger.Error(err, msg) ``` -------------------------------- ### Configure VSCode for E2E Tests with Build Tags Source: https://github.com/kedacore/keda/blob/main/tests/README.md Configure VSCode to use the 'e2e' build tag for Go development. This is necessary to overcome IDE errors when importing packages that rely on this build tag. ```json { "go.buildFlags": [ "-tags=e2e" ], "go.testTags": "e2e", } ``` -------------------------------- ### Verify KEDA Operator Logs Source: https://github.com/kedacore/keda/blob/main/BUILD.md Kubectl commands to stream logs from the KEDA operator and metrics API server pods for troubleshooting. ```bash kubectl logs -l app=keda-operator -n keda -f kubectl logs -l app=keda-metrics-apiserver -n keda -f ``` -------------------------------- ### Implement GetMetricsAndActivity for KEDA Scaler Source: https://github.com/kedacore/keda/blob/main/CREATE-NEW-SCALER.md This function is the core of a KEDA scaler, responsible for returning the current metric value and the active state of the resource. It interacts with external systems to fetch metrics and determines if scaling is required based on configured thresholds. ```golang func (s *artemisScaler) GetMetricsAndActivity(ctx context.Context, metricName string) ([]external_metrics.ExternalMetricValue, bool, error) { messages, err := s.getQueueMessageCount(ctx) if err != nil { s.logger.Error(err, "Unable to access the artemis management endpoint", "managementEndpoint", s.metadata.managementEndpoint) return []external_metrics.ExternalMetricValue{}, false, err } metric := GenerateMetricInMili(metricName, float64(messages)) return []external_metrics.ExternalMetricValue{metric}, messages > s.metadata.activationQueueLength, nil } ``` -------------------------------- ### Sign Commits with DCO Source: https://github.com/kedacore/keda/blob/main/CONTRIBUTING.md Append a 'Signed-off-by' line to your commit messages to certify your contribution adheres to project requirements. Use the '-s' flag with git commit for automatic appending. ```git This is my commit message Signed-off-by: Random J Developer ``` ```bash $ git commit -s -m 'This is my commit message' ``` -------------------------------- ### External Scaler Protocol Definition Source: https://github.com/kedacore/keda/blob/main/CONTRIBUTING.md This is the Protocol Buffers definition for an external scaler. It defines the gRPC service and message types used for communication between KEDA and external scaler implementations. ```proto syntax = "proto3"; package external_scaler; option go_package = "./externalscaler"; // ExternalScaler is the interface that external scalers must implement. service ExternalScaler { // IsActive is called by KEDA to check if the scaler should be activated. rpc IsActive (IsActiveRequest) returns (IsActiveResponse) {} // StreamIsActive is called by KEDA to stream IsActive requests. rpc StreamIsActive (stream IsActiveRequest) returns (stream IsActiveResponse) {} // ScalarMetric is called by KEDA to get the current metric value for a scaler. rpc ScalarMetric (ScalarMetricRequest) returns (ScalarMetricResponse) {} // StreamScalarMetric is called by KEDA to stream ScalarMetric requests. rpc StreamScalarMetric (stream ScalarMetricRequest) returns (stream ScalarMetricResponse) {} } // IsActiveRequest is the request message for the IsActive RPC. message IsActiveRequest { // Scaler is the scaler name. string scaler = 1; // Namespace is the namespace of the scaled object. string namespace = 2; // ScaledObject is the name of the scaled object. string scaledObject = 3; } // IsActiveResponse is the response message for the IsActive RPC. message IsActiveResponse { // Active is true if the scaler should be activated, false otherwise. bool active = 1; } // ScalarMetricRequest is the request message for the ScalarMetric RPC. message ScalarMetricRequest { // Scaler is the scaler name. string scaler = 1; // Namespace is the namespace of the scaled object. string namespace = 2; // ScaledObject is the name of the scaled object. string scaledObject = 3; } // ScalarMetricResponse is the response message for the ScalarMetric RPC. message ScalarMetricResponse { // Metric is the current metric value. double metric = 1; } ``` -------------------------------- ### Filter KEDA E2E Tests with YAML Configuration Source: https://github.com/kedacore/keda/blob/main/tests/README.md Configure KEDA end-to-end test execution using a YAML file. This allows for including or excluding specific test categories and suites. A valid config must have the `testCategories` field with a `mode` (include/exclude) for each category. ```yaml testCategories: # This will run all tests in the scalers category, but exclude the cpu test. scalers: mode: exclude tests: - cpu # Using mode: exclude and omitting the tests list will exclude all tests in the category. internals: mode: exclude secret-providers: mode: exclude sequential: mode: exclude ``` ```yaml testCategories: # This will only run the aws_cloudwatch, cpu, and kafka scaler tests, and exclude the rest. scalers: mode: include tests: - aws/aws_cloudwatch # you can also specify a deeper nested test by it's "directory path" - cpu -kafka # Since the other categories are not specified, all tests in those categories will not be run. ``` ```yaml # This will run all tests in all categories. testCategories: {} ``` ```yaml testCategories: # Error loading test config: testCategories is a required field. Did you mean to set this to an empty map? ``` ```yaml dryRun: true keda: # ...omitted testCategories: # ...omitted ``` -------------------------------- ### Grant Anonymous Access to External Metrics API Source: https://github.com/kedacore/keda/blob/main/BUILD.md A Kubernetes ClusterRoleBinding manifest that grants the system:anonymous user access to the KEDA external metrics reader role. This is intended for local debugging and is considered insecure for production environments. ```yaml apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: grant-anonymous-access-to-external-metrics roleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: keda-external-metrics-reader subjects: - kind: User name: system:anonymous namespace: default ``` -------------------------------- ### Re-sign Commits for Pull Requests Source: https://github.com/kedacore/keda/blob/main/CONTRIBUTING.md If you forgot to sign a commit, you can reset your branch to the merge base, create a new signed commit, and force push. Ensure you replace '' with your actual branch name. ```bash git checkout git reset $(git merge-base main ) git add -A git commit -sm "one commit on " git push --force ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.