### Quick Start Deployment Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/docs/helm_deploy.md Essential commands to add the repository and install the operator in one go. ```bash helm repo add locust-k8s-operator https://abdelrhmanhamouda.github.io/locust-k8s-operator/ helm repo update helm install locust-operator locust-k8s-operator/locust-k8s-operator \ --namespace locust-system --create-namespace ``` -------------------------------- ### Install development tools Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/CONTRIBUTING.md Installs necessary controller-gen, envtest, and kustomize binaries for development. ```bash make controller-gen envtest kustomize ``` -------------------------------- ### Default Installation Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/docs/helm_deploy.md Installs the chart using default configuration settings into the specified namespace. ```bash helm install locust-operator locust-k8s-operator/locust-k8s-operator \ --namespace locust-system --create-namespace ``` -------------------------------- ### Install and Serve Documentation Locally Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/docs/local-development.md Install MkDocs and Material for MkDocs, then serve the documentation locally for preview or build it for deployment. ```bash # Install MkDocs (if not installed) pip install mkdocs mkdocs-material # Serve documentation locally mkdocs serve # Build documentation mkdocs build --strict ``` -------------------------------- ### Install Prerequisites Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/docs/how-to-guides/validate-with-kind.md Installs kubectl, Helm, and Kind using Homebrew on macOS. Verifies installations. ```bash # macOS (using Homebrew) brew install kubectl helm kind # Verify installations kubectl version --client helm version kind version ``` -------------------------------- ### Install Locust Operator with Webhooks Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/docs/helm_deploy.md Example command to install the operator with webhook support enabled, assuming cert-manager is already configured in the cluster. ```bash # Install cert-manager first (one-time, cluster-wide). v1.14+ required. # See https://cert-manager.io/docs/installation/ for current install instructions. # Install the operator with webhooks on helm install locust-operator locust-k8s-operator/locust-k8s-operator \ --namespace locust-system --create-namespace \ --set webhook.enabled=true \ --set webhook.certManager.enabled=true ``` -------------------------------- ### Install Development Tools Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/docs/local-development.md Download Go dependencies and install necessary development tools like controller-gen, envtest, and kustomize. ```bash # Download Go dependencies make tidy # Install development tools (controller-gen, envtest, etc.) make controller-gen make envtest make kustomize ``` -------------------------------- ### Quick Start Validation Flow Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/docs/how-to-guides/validate-with-kind.md Performs a complete validation flow including cluster creation, operator installation, test script creation, and running a Locust test. ```bash # 1. Create cluster kind create cluster --name locust-test # 2. Install operator helm repo add locust-k8s-operator https://abdelrhmanhamouda.github.io/locust-k8s-operator/ helm repo update helm install locust-operator locust-k8s-operator/locust-k8s-operator --namespace locust-system --create-namespace # 3. Create test kubectl create configmap demo-test --from-literal=demo_test.py=' from locust import HttpUser, task class DemoUser(HttpUser): @task def get_homepage(self): self.client.get("/") ' # 4. Run test kubectl apply -f - < $HOME/.kube/config # Verify connectivity kubectl cluster-info - name: Create/update test ConfigMap run: | # Use --dry-run + kubectl apply for idempotency kubectl create configmap ecommerce-test \ --from-file=tests/locust/ecommerce_test.py \ --dry-run=client -o yaml | kubectl apply -f - - name: Deploy LocustTest with unique name run: | # Generate unique test name with timestamp TEST_NAME="ecommerce-ci-$(date +%Y%m%d-%H%M%S)" kubectl apply -f - <> $GITHUB_ENV - name: Wait for test completion run: | # Timeout accounts for pod scheduling + 5m run time + autoquit grace period TIMEOUT=600 # 10 minutes ELAPSED=0 while true; do PHASE=$(kubectl get locusttest ${TEST_NAME} -o jsonpath='{.status.phase}') case "$PHASE" in Succeeded) echo "Test passed"; break ;; Failed) echo "Test failed"; exit 1 ;; *) echo "Phase: $PHASE -- waiting..."; sleep 10 ;; esac ELAPSED=$((ELAPSED + 10)) if [ $ELAPSED -ge $TIMEOUT ]; then echo "Timed out after ${TIMEOUT}s"; exit 1 fi done - name: Collect test results if: always() # Run even if test fails run: | # Get master pod logs (job/ selector works because master always has exactly 1 pod) kubectl logs job/${TEST_NAME}-master > results.log # Get test status YAML kubectl get locusttest ${TEST_NAME} -o yaml > test-status.yaml # Display summary echo "=== Test Summary ===" kubectl get locusttest ${TEST_NAME} - name: Check for performance regression run: | # Extract final statistics from master logs # NOTE: This grep regex is version-specific to Locust's log format. # For more robust failure detection, consider using --exit-code-on-error # in the Locust command, which makes Locust exit with code 1 on errors. FAILURE_RATE=$(kubectl logs job/${TEST_NAME}-master | \ grep -oP 'Total.*Failures.* K[\d.]+% | tail -1 | sed 's/%//') echo "Failure rate: ${FAILURE_RATE}%" # Fail pipeline if error rate > 1% if (( $(echo "$FAILURE_RATE > 1.0" | bc -l) )); then echo "ERROR: Failure rate ${FAILURE_RATE}% exceeds threshold of 1%" exit 1 fi echo "✓ Performance acceptable: ${FAILURE_RATE}% failures" - name: Upload test artifacts if: always() uses: actions/upload-artifact@v4 with: name: load-test-results-${{ env.TEST_NAME }} path: | results.log test-status.yaml retention-days: 30 - name: Cleanup test resources if: always() run: kubectl delete locusttest ${TEST_NAME} --ignore-not-found ``` -------------------------------- ### Prometheus Query for Request Rate Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/docs/how-to-guides/observability/configure-opentelemetry.md Example PromQL query to retrieve the request rate per minute for a specific service name, assuming your OTel Collector exports metrics to Prometheus. ```promql # Request rate by service rate(locust_requests_total{service_name="my-load-test"}[1m]) ``` -------------------------------- ### Set Global Defaults via Helm Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/docs/how-to-guides/configuration/configure-resources.md Configure default CPU, memory, and ephemeral storage for all Locust pods during operator installation using a values.yaml file. ```yaml # values.yaml locustPods: resources: requests: cpu: "250m" # Guaranteed CPU memory: "128Mi" # Guaranteed memory ephemeralStorage: 30M # Scratch space for logs and temp files limits: cpu: "1000m" # Maximum CPU memory: "1024Mi" # Maximum memory ephemeralStorage: 50M # Prevents runaway disk usage from evicting the pod ``` ```bash helm upgrade --install locust-operator locust-k8s-operator/locust-k8s-operator \ --namespace locust-system \ -f values.yaml ``` -------------------------------- ### Development example with manual cleanup Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/docs/how-to-guides/configuration/configure-ttl.md Disable automatic TTL cleanup during development by setting `locustPods.ttlSecondsAfterFinished` to an empty string. This allows manual inspection of pods and resources after tests complete, with cleanup performed via `kubectl delete` commands. ```yaml # values.yaml locustPods: ttlSecondsAfterFinished: "" # Disable automatic cleanup ``` -------------------------------- ### LocustTest Status Tracking Example Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/docs/how_does_it_work.md This YAML snippet illustrates the status fields maintained by the LocustTest custom resource. It includes the current phase, expected and connected worker counts, start time, and detailed conditions for readiness. ```yaml status: phase: Running expectedWorkers: 5 connectedWorkers: 5 startTime: "2026-01-15T10:00:00Z" conditions: - type: Ready status: "True" lastTransitionTime: "2026-01-15T10:00:05Z" reason: AllWorkersConnected message: "All 5 workers connected to master" ``` -------------------------------- ### Configure Master Command for Spawn Rate Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/docs/how-to-guides/scaling/scale-workers.md Example of setting the user count and spawn rate for the master command in a Locust configuration. Ensure the spawn rate is matched to the worker count and network capacity. ```yaml master: command: - --users - "1000" - --spawn-rate - "100" # 20 workers × 5 users/sec/worker ``` -------------------------------- ### Initialize Kafka Producer in Locust Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/docs/how-to-guides/configuration/configure-kafka.md This Python code initializes a Kafka producer within the `on_start` method of a Locust User. It reads Kafka configuration from environment variables, supporting both authenticated and unauthenticated connections. Ensure the `kafka-python` library is installed. ```python # kafka_test.py import os from locust import User, task, between from kafka import KafkaProducer, KafkaConsumer import json class KafkaUser(User): wait_time = between(1, 3) def on_start(self): """Initialize Kafka producer using operator-injected config.""" bootstrap_servers = os.getenv('KAFKA_BOOTSTRAP_SERVERS').split(',') security_enabled = os.getenv('KAFKA_SECURITY_ENABLED', 'false').lower() == 'true' if security_enabled: # Use authenticated connection # Note: kafka-python uses sasl_plain_username/sasl_plain_password # for all SASL mechanisms (PLAIN, SCRAM-SHA-256, SCRAM-SHA-512), # not just PLAIN. The parameter names are misleading. self.producer = KafkaProducer( bootstrap_servers=bootstrap_servers, security_protocol=os.getenv('KAFKA_SECURITY_PROTOCOL_CONFIG', 'SASL_SSL'), sasl_mechanism=os.getenv('KAFKA_SASL_MECHANISM', 'SCRAM-SHA-512'), sasl_plain_username=os.getenv('KAFKA_USERNAME'), sasl_plain_password=os.getenv('KAFKA_PASSWORD'), value_serializer=lambda v: json.dumps(v).encode('utf-8') ) else: # Use unauthenticated connection self.producer = KafkaProducer( bootstrap_servers=bootstrap_servers, value_serializer=lambda v: json.dumps(v).encode('utf-8') ) @task def produce_message(self): """Send a message to Kafka.""" message = { 'user_id': 12345, 'action': 'view_product', 'timestamp': '2026-02-12T10:30:00Z' } future = self.producer.send('user-events', value=message) try: record_metadata = future.get(timeout=10) # Track success self.environment.events.request.fire( request_type="KAFKA", name="produce_message", response_time=future._elapsed_ms, response_length=len(str(message)), exception=None, context={} ) except Exception as e: # Track failure self.environment.events.request.fire( request_type="KAFKA", name="produce_message", response_time=0, response_length=0, exception=e, context={} ) ``` -------------------------------- ### Clone Repository and Navigate Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/docs/local-development.md Clone the project repository and navigate into the project directory. ```bash git clone https://github.com/AbdelrhmanHamouda/locust-k8s-operator.git cd locust-k8s-operator ``` -------------------------------- ### Test with Sample CR Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/docs/local-development.md Create a ConfigMap with a Locust script, apply a sample LocustTest CR, and watch the created resources. ```bash # Create a test ConfigMap with a simple Locust script kubectl create configmap locust-test --from-literal=locustfile.py=' from locust import HttpUser, task class TestUser(HttpUser): @task def hello(self): self.client.get("/") ' # Apply a sample LocustTest CR kubectl apply -f config/samples/locust_v2_locusttest.yaml # Watch the resources kubectl get locusttests,jobs,pods -w ``` -------------------------------- ### Set TTL via CLI override Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/docs/how-to-guides/configuration/configure-ttl.md Override the default TTL setting at installation time using the `--set` flag with `helm install`. This allows for a specific TTL configuration for a particular installation without modifying the `values.yaml` file. ```bash helm install locust-operator locust-k8s-operator/locust-k8s-operator \ --namespace locust-system \ --set locustPods.ttlSecondsAfterFinished=7200 # 2 hours ``` -------------------------------- ### Apply Production Configuration Sample Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/docs/how-to-guides/validate-with-kind.md Apply a sample Kubernetes manifest to test production-like configurations, including resource limits, node affinity, and autoscaling. ```yaml kubectl apply -f config/samples/locusttest_v2_production.yaml ``` -------------------------------- ### Common development commands Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/CONTRIBUTING.md Standard commands for building, testing, linting, and generating manifests within the project. ```bash # Build the operator binary make build # Run all tests (unit + integration via envtest) make test # Run linter make lint # Generate CRDs, RBAC, and webhook manifests make manifests # Run all CI checks locally make ci ``` -------------------------------- ### Install Operator with OpenTelemetry Collector Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/charts/locust-k8s-operator/README.md Installs the Locust Kubernetes Operator and enables the OpenTelemetry collector sidecar by setting the `otelCollector.enabled` flag to true. ```bash helm install my-locust-operator locust-k8s-operator/locust-k8s-operator \ --set otelCollector.enabled=true ``` -------------------------------- ### Create Sources for Individual Variables Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/docs/how-to-guides/security/inject-secrets.md Prepare a ConfigMap and a Secret containing specific keys that will be referenced individually as environment variables. ```bash kubectl create configmap app-settings --from-literal=api-url=https://api.example.com kubectl create secret generic auth --from-literal=token=secret-token-here ``` -------------------------------- ### Create a Kind cluster Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/CONTRIBUTING.md Initializes a local Kubernetes cluster named locust-dev using Kind. ```bash kind create cluster --name locust-dev ``` -------------------------------- ### Add and Install Locust Kubernetes Operator Helm Repository Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/charts/locust-k8s-operator/README.md Commands to add the Helm repository for the Locust Kubernetes Operator and update the local repository. This is the first step before installing the operator. ```bash helm repo add locust-k8s-operator https://abdelrhmanhamouda.github.io/locust-k8s-operator helm repo update helm install my-locust-operator locust-k8s-operator/locust-k8s-operator ``` -------------------------------- ### Upgrade to v2 with Zero-Downtime Migration Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/charts/locust-k8s-operator/README.md Upgrades an existing Locust Kubernetes Operator installation to v2, enabling conversion webhooks for zero-downtime migration of v1 LocustTest resources. Ensure cert-manager is installed if `webhook.certManager.enabled` is true. ```bash helm upgrade locust-operator locust-k8s-operator/locust-k8s-operator \ --set webhook.enabled=true \ --set webhook.certManager.enabled=true ``` -------------------------------- ### Equivalent Node Affinity Configuration Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/docs/how-to-guides/scaling/use-node-selector.md This demonstrates the equivalent configuration using node affinity, which offers more advanced scheduling options compared to simple node selectors. ```yaml scheduling: affinity: nodeAffinity: requiredDuringSchedulingIgnoredDuringExecution: nodeSelectorTerms: - matchExpressions: - key: disktype operator: In values: - ssd ``` -------------------------------- ### Verify Pod Placement on Tainted Nodes Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/docs/how-to-guides/scaling/configure-tolerations.md Use `kubectl get pods -o wide` to check where pods are scheduled. Verify node taints with `kubectl describe node` and pod tolerations with `kubectl get pod -o jsonpath`. ```bash # Show pod placement kubectl get pods -l performance-test-name=toleration-test -o wide # Check node taints kubectl describe node | grep Taints # Verify pod tolerations kubectl get pod -o jsonpath='{.spec.tolerations}' ``` -------------------------------- ### Monitor Locust test status Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/docs/how-to-guides/scaling/scale-workers.md Watch the status of your LocustTest resource in real-time using `kubectl get locusttest -w`. You can also retrieve the status field directly using `kubectl get locusttest -o jsonpath='{.status}'`. ```bash # Watch test status kubectl get locusttest high-load-test -w # Check status field kubectl get locusttest high-load-test -o jsonpath='{.status}' ``` -------------------------------- ### Generate Manifests and Code Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/docs/local-development.md Generate Kubernetes manifests (CRDs, RBAC, webhooks), DeepCopy implementations, format code, and run go vet. ```bash # Generate CRDs, RBAC, and webhook manifests make manifests # Generate DeepCopy implementations make generate # Format code make fmt # Run go vet make vet ``` -------------------------------- ### Get LocustTest Phase Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/docs/how-to-guides/validate-with-kind.md Retrieve the current phase of the LocustTest custom resource. ```bash kubectl get locusttest demo -o jsonpath='{.status.phase}' ``` -------------------------------- ### Re-download envtest Binaries Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/docs/integration-testing.md Ensures the necessary envtest binaries are downloaded and available in the 'bin/k8s/' directory. Use this if envtest binaries are missing or corrupted. ```bash make setup-envtest ``` -------------------------------- ### Get PodsHealthy Condition Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/docs/how-to-guides/observability/monitor-test-status.md Retrieve the status of the PodsHealthy condition for a specific LocustTest resource. ```bash kubectl get locusttest my-test -o jsonpath='{.status.conditions[?(@.type=="PodsHealthy")]}' ``` -------------------------------- ### Create ConfigMap for LocustTest Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/docs/faq.md Create a ConfigMap from local files to be used by the LocustTest CR. ```bash # Create ConfigMap from local files kubectl create configmap my-test-scripts --from-file=test.py=./test.py # If LocustTest already exists, the operator detects recovery automatically ``` -------------------------------- ### Build and load Docker image Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/CONTRIBUTING.md Builds the operator image and loads it into the local Kind cluster. ```bash # Build the Docker image make docker-build IMG=locust-k8s-operator:dev # Load the image into Kind kind load docker-image locust-k8s-operator:dev --name locust-dev ``` -------------------------------- ### Troubleshoot TLS certificate errors Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/docs/faq.md Example of the error message encountered when the operator fails to locate TLS certificates. ```text ERROR setup problem running manager {"error": "open /tmp/k8s-webhook-server/serving-certs/tls.crt: no such file or directory"} ``` -------------------------------- ### Troubleshoot Conversion Webhook Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/docs/migration.md Verify cert-manager status and ensure the webhook is enabled in the Helm release. ```bash # Check cert-manager kubectl get pods -n cert-manager # Enable webhook in Helm helm upgrade locust-operator locust-k8s-operator/locust-k8s-operator \ --set webhook.enabled=true ``` -------------------------------- ### Unit Test Naming Convention Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/docs/integration-testing.md Example of Go unit test naming convention: 'Test_'. ```go // Unit tests: Test_ func TestBuildMasterJob_WithEnvConfig(t *testing.T) {} ``` -------------------------------- ### Deploy Operator using Kustomize or Helm Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/docs/local-development.md Deploy the operator to the cluster using either kustomize for development or Helm for production-like testing, specifying the Docker image. ```bash Option A: Using kustomize (for development): # Deploy CRDs and operator make deploy IMG=locust-k8s-operator:dev Option B: Using Helm (for production-like testing): # Package the Helm chart helm package ../charts/locust-k8s-operator # Install with local image helm install locust-operator locust-k8s-operator-*.tgz \ --set image.repository=locust-k8s-operator \ --set image.tag=dev \ --set image.pullPolicy=IfNotPresent ``` -------------------------------- ### Create Locust Test ConfigMap Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/docs/tutorials/first-load-test.md Create a Kubernetes ConfigMap to store the Locust test script, making it accessible to the Locust pods. ```bash kubectl create configmap ecommerce-test --from-file=ecommerce_test.py ``` -------------------------------- ### Integrating External Secrets Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/docs/security.md Example of using External Secrets Operator to sync credentials from AWS Secrets Manager for use in a LocustTest. ```yaml # ExternalSecret syncs from AWS Secrets Manager to a K8s Secret apiVersion: external-secrets.io/v1beta1 kind: ExternalSecret metadata: name: load-test-credentials namespace: performance-testing spec: refreshInterval: 1h # Sync every hour secretStoreRef: name: aws-secretsmanager kind: ClusterSecretStore target: name: load-test-credentials # K8s Secret name data: - secretKey: API_TOKEN remoteRef: key: /perf-testing/api-token - secretKey: DB_PASSWORD remoteRef: key: /perf-testing/db-password --- # LocustTest references the synced Secret apiVersion: locust.io/v2 kind: LocustTest metadata: name: my-test spec: image: locustio/locust:2.43.3 master: command: "--locustfile /lotest/src/test.py --host https://api.example.com" worker: command: "--locustfile /lotest/src/test.py" replicas: 5 env: secretRefs: - name: load-test-credentials # Uses synced Secret ``` -------------------------------- ### Describe Locust Test Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/docs/how-to-guides/observability/monitor-test-status.md Get detailed information about a LocustTest resource, including its status and conditions. Useful for diagnosing pod failures. ```bash kubectl describe locusttest my-test ``` -------------------------------- ### Deploy LocustTest CR Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/docs/how-to-guides/observability/configure-opentelemetry.md Apply your configured LocustTest Custom Resource to the cluster to start the load test with OpenTelemetry integration enabled. ```bash kubectl apply -f locusttest.yaml ``` -------------------------------- ### Run All Unit and Integration Tests Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/docs/integration-testing.md Execute all unit and integration tests with coverage reporting. This is the primary command for testing the controller and API logic. ```bash make test ``` -------------------------------- ### Verify Webhook Certificate Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/charts/locust-k8s-operator/templates/NOTES.txt If the webhook is enabled and cert-manager is installed, verify the operator's webhook certificate. This command retrieves the certificate details. ```bash kubectl get certificate {{ include "locust-k8s-operator.fullname" . }}-webhook-cert -n {{ .Release.Namespace }} ``` -------------------------------- ### Create ConfigMap for Environment Variables Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/docs/how-to-guides/security/inject-secrets.md Use kubectl to create a ConfigMap with key-value pairs that will be injected as environment variables. ```bash kubectl create configmap app-config \ --from-literal=TARGET_HOST=https://api.example.com \ --from-literal=LOG_LEVEL=INFO \ --from-literal=TIMEOUT=30 ``` -------------------------------- ### Node Selector Configuration Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/docs/how-to-guides/scaling/use-node-selector.md Example of how to specify a node selector in your LocustTest configuration. This ensures pods are scheduled only on nodes with the 'disktype: ssd' label. ```yaml scheduling: nodeSelector: disktype: ssd ``` -------------------------------- ### Create Kind Cluster Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/docs/how-to-guides/validate-with-kind.md Creates a dedicated Kind cluster for testing. Validates cluster readiness by checking cluster info and node status. ```bash kind create cluster --name locust-test ``` ```bash # Check cluster info kubectl cluster-info --context kind-locust-test # Verify nodes are ready kubectl get nodes ``` -------------------------------- ### Taint Spot Instances for Cost Optimization Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/docs/how-to-guides/scaling/configure-tolerations.md Apply taints to spot or preemptible instances. This is often done automatically by cloud providers but can be manually applied if needed. ```bash # Cloud providers often add this taint automatically kubectl taint nodes spot-node-1 cloud.google.com/gke-preemptible=true:NoSchedule ``` -------------------------------- ### OpenTelemetry Collector Configuration Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/docs/metrics_and_dashboards.md Example configuration for an OpenTelemetry Collector to receive OTLP metrics and traces, exporting metrics to Prometheus and traces to Jaeger. ```yaml # otel-collector-config.yaml receivers: otlp: protocols: grpc: endpoint: 0.0.0.0:4317 http: endpoint: 0.0.0.0:4318 exporters: prometheus: endpoint: 0.0.0.0:8889 otlphttp: endpoint: http://jaeger-collector:4318 tls: insecure: true service: pipelines: metrics: receivers: [otlp] exporters: [prometheus] traces: receivers: [otlp] exporters: [otlphttp] ``` -------------------------------- ### Get Pod Security Context Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/docs/how-to-guides/security/configure-pod-security.md Retrieves the security context of pods matching a specific label. Use `jq` to pretty-print the JSON output. ```bash kubectl get pod -l performance-test-name=my-test -o jsonpath='{.items[0].spec.securityContext}' | jq . ``` -------------------------------- ### Verify Operator Deployment Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/docs/local-development.md Check for running operator pods and follow their logs. Note that `make deploy` creates a namespace based on the project name, while production uses `locust-system`. ```bash # Check pods in the generated namespace kubectl get pods -A | grep locust # Follow operator logs kubectl logs -f -n deployment/ ``` -------------------------------- ### Configure trace sampling Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/docs/how-to-guides/observability/configure-opentelemetry.md Configure trace sampling using environment variables in your OpenTelemetry setup. This is recommended for high-volume tests to reduce overhead. ```yaml extraEnvVars: OTEL_TRACES_SAMPLER: "traceidratio" OTEL_TRACES_SAMPLER_ARG: "0.1" # Sample 10% of traces ``` -------------------------------- ### Check Service Account Permissions Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/docs/how-to-guides/security/configure-pod-security.md Lists the permissions granted to a specified Kubernetes service account. Replace `` and `` with your installation's values. ```bash # Check operator service account permissions # Replace and with your installation's values kubectl auth can-i --list --as=system:serviceaccount:: ``` -------------------------------- ### Verify Pod Resource Configuration Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/docs/how-to-guides/configuration/configure-resources.md Retrieve the master pod name and then use `kubectl describe` to inspect its resource limits and requests. This helps confirm that the configured resource settings are applied to the running pod. ```bash # Get master pod name MASTER_POD=$(kubectl get pod -l performance-test-pod-name=resource-optimized-test-master -o jsonpath='{.items[0].metadata.name}') # Verify resource configuration kubectl describe pod $MASTER_POD | grep -A 10 "Limits: |Requests:" ``` -------------------------------- ### Install/Upgrade Locust Operator with Helm Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/docs/how-to-guides/configuration/configure-kafka.md Use Helm to install or upgrade the Locust operator, applying the custom Kafka configuration defined in your values.yaml file. ```bash helm upgrade --install locust-operator locust-k8s-operator/locust-k8s-operator \ --namespace locust-system \ -f values.yaml ``` -------------------------------- ### Directory Structure for CI/CD Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/docs/tutorials/ci-cd-integration.md Organize your repository to include the GitHub Actions workflow file and the Locust test scripts. ```tree your-repo/ ├── .github/ │ └── workflows/ │ └── load-test.yaml └── tests/ └── locust/ └── ecommerce_test.py ``` -------------------------------- ### Configure Operator Resource Defaults Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/docs/migration.md Recommended resource limits and requests for the Go-based operator controller. ```yaml resources: limits: memory: 256Mi cpu: 500m requests: memory: 64Mi cpu: 10m ``` -------------------------------- ### Get Load Test Pods Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/docs/tutorials/first-load-test.md Use this command to check the status of pods associated with your load test. Ensure master and worker pods are running. ```bash kubectl get pods -l performance-test-name=ecommerce-load ``` -------------------------------- ### Check Service Endpoints Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/docs/how-to-guides/validate-with-kind.md Verify if the demo-master service endpoints are correctly configured. This helps diagnose connectivity issues. ```bash kubectl get endpoints demo-master ``` -------------------------------- ### Create a Simple Locust Test Script Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/docs/getting_started/index.md Defines a basic Locust HttpUser with a single task to request the homepage. This script is saved to a file named demo_test.py. ```python from locust import HttpUser, task class DemoUser(HttpUser): @task # Define a task that users will execute def get_homepage(self): # Simple test that requests the homepage repeatedly self.client.get("/") ``` -------------------------------- ### Run CI Checks Locally Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/docs/integration-testing.md Simulates the CI pipeline locally by running linting and all tests (unit + integration). ```bash make ci ``` -------------------------------- ### Verify NetworkPolicy Activation Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/docs/how-to-guides/security/configure-pod-security.md Check if a NetworkPolicy is active in a specific namespace using `kubectl get networkpolicy`. This command lists all network policies applied to the specified namespace. ```bash kubectl get networkpolicy -n performance-testing ``` -------------------------------- ### Deploy Locust Test Script as ConfigMap Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/docs/getting_started/index.md Creates a Kubernetes ConfigMap named 'demo-test' from the local 'demo_test.py' file, making the test script available to pods. ```bash kubectl create configmap demo-test --from-file=demo_test.py ``` -------------------------------- ### Development Commands for Locust Operator Source: https://github.com/abdelrhmanhamouda/locust-k8s-operator/blob/master/README.md Commands for local development, including installing CRDs, running the operator, executing tests, and building/pushing the operator image. Requires Go 1.24+ and Docker. ```bash # Install CRDs make install # Run operator locally (against configured cluster) make run # Run tests make test # Run E2E tests (requires Kind) make test-e2e # Build and push operator image make docker-build docker-push IMG=/locust-operator:tag ```