### Install Development Tools Source: https://github.com/giantswarm/silence-operator/blob/main/CONTRIBUTING.md Run this command to install necessary development tools for the project. ```bash make install-tools ``` -------------------------------- ### Mock Alertmanager Usage Example Source: https://github.com/giantswarm/silence-operator/blob/main/docs/testing.md Shows how to use a mock Alertmanager for testing purposes. This includes starting and stopping the mock server, configuring responses, and verifying incoming requests. ```go // Create and start mock mockAM := testutils.NewMockAlertmanager() mockAM.Start() defer mockAM.Stop() // Configure responses mockAM.SetResponse("/api/v2/silences", http.StatusOK, silenceList) // Verify calls Expect(mockAM.GetRequestCount("POST", "/api/v2/silences")).To(Equal(1)) ``` -------------------------------- ### Install Testing Tools Source: https://github.com/giantswarm/silence-operator/blob/main/docs/testing.md Install necessary tools required for development and testing. This command ensures all dependencies are met. ```bash # Verify tools are installed make install-tools ``` -------------------------------- ### Complete Configuration Example Source: https://github.com/giantswarm/silence-operator/blob/main/README.md A full example of the values.yaml configuration for the silence-operator. This includes alertmanager connection details and selectors for silences and namespaces. ```yaml # values.yaml alertmanagerAddress: "http://alertmanager.monitoring.svc.cluster.local:9093" alertmanagerAuthentication: true alertmanagerDefaultTenant: "my-tenant" # Only process silences for production workloads silenceSelector: "environment=production" # Only watch namespaces managed by the platform team namespaceSelector: "team=platform,environment in (production,staging)" ``` -------------------------------- ### Install Helm Chart from OCI Registry Source: https://github.com/giantswarm/silence-operator/blob/main/README.md Use this command to install the silence-operator chart from the OCI registry. Replace [RELEASE_NAME] and [VERSION] with your specific values. ```console helm install [RELEASE_NAME] oci://gsoci.azurecr.io/charts/giantswarm/silence-operator --version [VERSION] ``` -------------------------------- ### Install envtest Binaries Source: https://github.com/giantswarm/silence-operator/blob/main/docs/testing.md Install the necessary envtest binaries, which are required for running Kubernetes integration tests. This is a common solution for missing Kubernetes binaries. ```bash # Solution: Install envtest binaries make setup-envtest ``` -------------------------------- ### Install Helm Chart from Repository Source: https://github.com/giantswarm/silence-operator/blob/main/README.md Install the silence-operator chart using the Helm repository. This command assumes you have already added and updated the giantswarm repository. ```console helm install [RELEASE_NAME] giantswarm/silence-operator ``` -------------------------------- ### Namespace Selector Examples Source: https://github.com/giantswarm/silence-operator/blob/main/README.md Examples of how to use the namespaceSelector to filter which namespaces the operator monitors. This can be used to target specific environments or teams. ```yaml namespaceSelector: "environment=production" ``` ```yaml namespaceSelector: "team=platform,environment in (production,staging)" ``` -------------------------------- ### v1alpha2 Silence Resource Example Source: https://github.com/giantswarm/silence-operator/blob/main/MIGRATION.md Example of a Silence resource in the v1alpha2 API version. This is used to define silences for alerts. ```yaml apiVersion: observability.giantswarm.io/v1alpha2 kind: Silence metadata: name: silence-non-critical-alerts namespace: production spec: matchers: - name: "severity" value: "critical" matchType: "!=" ``` -------------------------------- ### List Available envtest Binaries Source: https://github.com/giantswarm/silence-operator/blob/main/docs/testing.md Check which envtest binaries are available in the environment. This helps in diagnosing issues related to the test environment setup. ```bash # Check envtest binary availability bin/setup-envtest list ``` -------------------------------- ### Check Tool Versions Source: https://github.com/giantswarm/silence-operator/blob/main/docs/testing.md Verify the installed versions of essential testing tools. This is a common debugging step to ensure the environment is correctly configured. ```bash # Check tool versions bin/setup-envtest version bin/ginkgo version bin/golangci-lint version ``` -------------------------------- ### Install Silence Operator via Helm (OCI Registry) Source: https://context7.com/giantswarm/silence-operator/llms.txt Install the operator using the Helm chart from the OCI registry. Ensure Alertmanager is accessible at the specified address. The chart automatically creates CRDs unless disabled. ```bash helm install silence-operator oci://gsoci.azurecr.io/charts/giantswarm/silence-operator \ --version 0.20.1 \ --namespace monitoring \ --create-namespace \ --set alertmanagerAddress="http://alertmanager.monitoring.svc.cluster.local:9093" ``` ```bash helm repo add giantswarm https://giantswarm.github.io/control-plane-catalog/ helm repo update helm install silence-operator giantswarm/silence-operator \ --namespace monitoring \ --create-namespace \ --set alertmanagerAddress="http://alertmanager.monitoring.svc.cluster.local:9093" \ --set silenceSelector="environment=production" \ --set namespaceSelector="team=platform" ``` ```bash kubectl get pods -n monitoring -l app=silence-operator # NAME READY STATUS RESTARTS AGE # silence-operator-6d8f9b4c7-xkp2t 1/1 Running 0 30s ``` -------------------------------- ### Apply and Get Silence Resources Source: https://context7.com/giantswarm/silence-operator/llms.txt Commands to apply a Silence resource definition and then retrieve all Silence resources. Useful for verifying creation. ```bash kubectl apply -f legacy-silence.yaml # silence.monitoring.giantswarm.io/my-sample-silence created kubectl get silences.monitoring.giantswarm.io # NAME AGE # my-sample-silence 3s ``` -------------------------------- ### v1alpha1 Silence CR Example Source: https://github.com/giantswarm/silence-operator/blob/main/README.md Example of a cluster-scoped Silence Custom Resource (CR) for v1alpha1 API. Use this for legacy configurations. ```yaml apiVersion: monitoring.giantswarm.io/v1alpha1 kind: Silence metadata: name: test-silence1 spec: matchers: - name: cluster value: test isRegex: false isEqual: true - name: severity value: critical isRegex: false isEqual: true owner: example-user issue_url: https://github.com/example/issue/123 ``` -------------------------------- ### Silence Selector Configuration Example Source: https://github.com/giantswarm/silence-operator/blob/main/README.md Example of how to configure the silenceSelector in values.yaml to filter which Silence custom resources the operator processes based on labels. Supports various label matching syntaxes. ```yaml # values.yaml silenceSelector: "environment=production,tier=frontend" ``` -------------------------------- ### Install Helm Chart with Custom Values Source: https://github.com/giantswarm/silence-operator/blob/main/README.md Install the silence-operator chart with custom values for Alertmanager address, silence selector, and namespace selector. This allows for fine-grained control over the operator's behavior. ```console helm install [RELEASE_NAME] giantswarm/silence-operator \ --set alertmanagerAddress="http://my-alertmanager:9093" \ --set silenceSelector="environment=production" \ --set namespaceSelector="team=platform" ``` -------------------------------- ### Controller Tests for Silence Operator (Go) Source: https://github.com/giantswarm/silence-operator/blob/main/docs/testing.md Demonstrates the structure for testing the Silence controller and SilenceV2 controller using Go's testing framework. Includes setup for mock Alertmanager and context, and specific tests for creating silences and handling v1alpha2 API resources. ```go var _ = Describe("Silence Controller", func() { var ( mockServer *testutils.MockAlertmanagerServer mockAlertmanager *alertmanager.Alertmanager reconciler *SilenceReconciler ctx context.Context ) BeforeEach(func() { // Set up mock Alertmanager server mockServer = testutils.NewMockAlertmanagerServer() var err error mockAlertmanager, err = mockServer.GetAlertmanager() Expect(err).NotTo(HaveOccurred()) // Create service and reconciler silenceService := service.NewSilenceService(mockAlertmanager) reconciler = &SilenceReconciler{ client: k8sClient, silenceService: silenceService, } ctx = context.Background() }) AfterEach(func() { // Clean up mock server if mockServer != nil { mockServer.Close() } }) Context("When creating a Silence", func() { It("Should create silence in Alertmanager", func() { // Test implementation }) }) }) var _ = Describe("SilenceV2 Controller", func() { Context("When reconciling a resource", func() { It("should successfully reconcile the resource", func() { // Test implementation for v1alpha2 API }) It("should handle deletion with finalizer", func() { // Test finalizer logic for v1alpha2 }) }) Context("MatchType Conversion", func() { It("should convert MatchType enum to correct boolean values", func() { testCases := []struct { matchType observabilityv1alpha2.MatchType expectedIsRegex bool expectedIsEqual bool description string }{ {observabilityv1alpha2.MatchEqual, false, true, "exact match (=)"}, {observabilityv1alpha2.MatchNotEqual, false, false, "exact non-match (!=)"}, {observabilityv1alpha2.MatchRegexMatch, true, true, "regex match (=~)"}, {observabilityv1alpha2.MatchRegexNotMatch, true, false, "regex non-match (!~)"}, {"". false, true, "empty/default should be exact match"}, } for _, tc := range testCases { // Test the conversion logic for each match type silence := createTestSilenceWithMatchType(tc.matchType) result, err := reconciler.getSilenceFromCR(silence) Expect(err).NotTo(HaveOccurred()) Expect(result.Matchers[0].IsRegex).To(Equal(tc.expectedIsRegex)) Expect(result.Matchers[0].IsEqual).To(Equal(tc.expectedIsEqual)) } }) }) }) ``` -------------------------------- ### Create v1alpha2 Silence in Target Namespace Source: https://github.com/giantswarm/silence-operator/blob/main/MIGRATION.md Example of creating a v1alpha2 Silence resource in a specific namespace, demonstrating the new namespace-scoped nature and matchType field. ```bash # List existing v1alpha1 silences kubectl get silences.monitoring.giantswarm.io example-silence # Create v1alpha2 equivalent in target namespace kubectl apply -f - <&1 | grep "controller" ``` -------------------------------- ### Update silence-operator via Helm Source: https://github.com/giantswarm/silence-operator/blob/main/MIGRATION.md Example command to update the silence-operator to a version supporting both APIs (v0.17.0+) using Helm. ```bash # Check current version kubectl get deployment silence-operator -n monitoring -o jsonpath='{.spec.template.spec.containers[0].image}' # Update via Helm (example) helm upgrade silence-operator giantswarm/silence-operator --version 0.17.0 -n monitoring ``` -------------------------------- ### Migrated v1alpha2 Silence Metadata Source: https://github.com/giantswarm/silence-operator/blob/main/MIGRATION.md Example of the migrated v1alpha2 Silence resource metadata, demonstrating how user-defined annotations and labels are preserved while system metadata is filtered out. ```yaml metadata: name: common-jobscrapingfailure namespace: production annotations: motivation: "We did a review of jobs failing everywhere, let's give teams time to manage them." valid-until: "2025-07-29" labels: app.example.com/component: monitoring ``` -------------------------------- ### Silence Operator Helm Configuration Source: https://context7.com/giantswarm/silence-operator/llms.txt Example `values.yaml` file for configuring the Silence Operator via Helm. Covers Alertmanager connection, multi-tenancy, selectors, resource limits, and security contexts. ```yaml # values.yaml — complete configuration example alertmanagerAddress: "http://alertmanager.monitoring.svc.cluster.local:9093" alertmanagerAuthentication: false # set true to attach k8s Service Account bearer token # Multi-tenancy (Mimir Alertmanager) tenancy: enabled: true labelKey: "observability.giantswarm.io/tenant" # label key on Silence CRs defaultTenant: "default" # fallback when label is absent # Deprecated single-tenant shorthand (maps to tenancy.defaultTenant automatically) # alertmanagerDefaultTenant: "legacy-tenant" # Filter which Silence CRs are processed (both APIs) silenceSelector: "environment=production,tier=monitoring" # Restrict which namespaces the v2 controller watches (v1alpha2 only) namespaceSelector: "team=platform" # Resource limits resources: requests: cpu: 50m memory: 50Mi limits: cpu: 50m memory: 100Mi # Security contexts (hardened defaults) podSecurityContext: runAsNonRoot: true runAsUser: 65534 seccompProfile: type: RuntimeDefault containerSecurityContext: allowPrivilegeEscalation: false readOnlyRootFilesystem: true capabilities: drop: [ALL] # Network policy networkPolicy: enabled: true flavor: "kubernetes" # or "cilium" # CRD installation crds: install: true # set false to manage CRDs externally # Replica count and strategy replicas: 1 strategy: type: RollingUpdate ``` -------------------------------- ### Silence CR with Tenant Label Source: https://github.com/giantswarm/silence-operator/blob/main/README.md Example of a v1alpha2 Silence CR that includes a tenant label for multi-tenancy. This CR will be processed by the tenant specified in the label. ```yaml apiVersion: observability.giantswarm.io/v1alpha2 kind: Silence metadata: name: team-alpha-silence namespace: team-alpha labels: observability.giantswarm.io/tenant: "team-alpha" spec: matchers: - name: team value: alpha matchType: "=" ``` -------------------------------- ### v1alpha1 Silence: Exclude Specific Values Source: https://github.com/giantswarm/silence-operator/blob/main/MIGRATION.md An example of a v1alpha1 Silence resource configured to exclude a specific value ('critical') for the 'severity' matcher. ```yaml apiVersion: monitoring.giantswarm.io/v1alpha1 kind: Silence metadata: name: silence-non-critical-alerts spec: matchers: - name: "severity" value: "critical" isRegex: false isEqual: false ``` -------------------------------- ### Silence CR without Tenant Label Source: https://github.com/giantswarm/silence-operator/blob/main/README.md Example of a v1alpha2 Silence CR without a tenant label. This CR will be processed using the default tenant configuration. ```yaml apiVersion: observability.giantswarm.io/v1alpha2 kind: Silence metadata: name: shared-silence namespace: monitoring spec: matchers: - name: severity value: warning matchType: "=" ``` -------------------------------- ### Silence Operator CLI Flags Configuration Source: https://context7.com/giantswarm/silence-operator/llms.txt Example of configuring the Silence Operator using command-line flags when running the binary directly. These flags correspond to Helm values. ```bash ./silence-operator \ --alertmanager-address="http://alertmanager.monitoring.svc.cluster.local:9093" \ --alertmanager-authentication=true \ --silence-selector="environment=production" \ --namespace-selector="team=platform" \ --tenancy-enabled=true \ --tenancy-label-key="observability.giantswarm.io/tenant" \ --tenancy-default-tenant="default" \ --leader-elect=true \ --health-probe-bind-address=":8081" \ --metrics-bind-address=":8080" \ --metrics-secure=false ``` -------------------------------- ### Generate Code and Manifests Source: https://github.com/giantswarm/silence-operator/blob/main/CONTRIBUTING.md Execute this command to generate all necessary code and Helm manifests. ```bash make generate-all-with-helm ``` -------------------------------- ### Service Layer Testing for Silence Operator (Go) Source: https://github.com/giantswarm/silence-operator/blob/main/docs/testing.md Illustrates how to test the service layer of the silence-operator directly, bypassing Kubernetes dependencies. This allows for focused testing of business logic using mock clients. ```go // Test the service layer directly func TestSilenceService_CreateOrUpdateSilence(t *testing.T) { // Setup mock Alertmanager client mockClient := &MockAlertmanagerClient{} service := NewSilenceService(mockClient) // Test business logic without Kubernetes dependencies err := service.CreateOrUpdateSilence(ctx, "test-comment", silence) assert.NoError(t, err) // Verify expected Alertmanager operations mockClient.AssertCreateSilenceCalled(t, silence) } ``` -------------------------------- ### Run Specific Test Suites with Ginkgo Source: https://github.com/giantswarm/silence-operator/blob/main/docs/testing.md Directly uses the Ginkgo binary to run specific test suites by providing focus or skip arguments. This offers more granular control over test execution. ```bash bin/ginkgo -focus='Controller' ./... ``` ```bash bin/ginkgo -skip='Integration' ./... ``` ```bash bin/ginkgo -v ./... ``` -------------------------------- ### Run Tests and Linting Source: https://github.com/giantswarm/silence-operator/blob/main/CONTRIBUTING.md Execute these commands to run all project tests and perform linting checks. ```bash make test ``` ```bash make lint ``` -------------------------------- ### Install CRDs Manually for Silence Operator Source: https://context7.com/giantswarm/silence-operator/llms.txt Manually apply the Custom Resource Definitions (CRDs) for the silence-operator. The namespace-scoped v1alpha2 CRD is recommended for new installations. ```bash kubectl apply --server-side \ -f https://raw.githubusercontent.com/giantswarm/silence-operator/refs/heads/main/config/crd/bases/observability.giantswarm.io_silences.yaml ``` ```bash kubectl apply --server-side \ -f https://raw.githubusercontent.com/giantswarm/silence-operator/refs/heads/main/config/crd/bases/monitoring.giantswarm.io_silences.yaml ``` ```bash kubectl get crd | grep silences # silences.monitoring.giantswarm.io 2026-01-01T00:00:00Z # silences.observability.giantswarm.io 2026-01-01T00:00:00Z ``` -------------------------------- ### Run Silence Migration Script Source: https://github.com/giantswarm/silence-operator/blob/main/MIGRATION.md Execute the migration script to convert v1alpha1 silences to v1alpha2 in a specified target namespace. The target namespace argument is required. ```bash ./hack/migrate-silences.sh production ``` -------------------------------- ### Run Tests with Ginkgo Arguments Source: https://github.com/giantswarm/silence-operator/blob/main/docs/testing.md Allows running tests with specific Ginkgo arguments, such as focusing on a particular test suite or enabling verbose output. Modify the focus or other arguments as needed. ```bash $(GINKGO) -focus='Silence Controller' ./... ``` ```bash $(GINKGO) -v ./... ``` ```bash $(GINKGO) -skip='Should fail' ./... ``` -------------------------------- ### Dry-Run Testing of Migration Script (Bash) Source: https://github.com/giantswarm/silence-operator/blob/main/docs/testing.md Demonstrates how to perform a dry-run of the silence-operator migration script to test migration without making actual changes. It also shows how to target a specific namespace. ```bash # Test migration without making changes ./hack/migrate-silences.sh --dry-run # Test migration to specific namespace ./hack/migrate-silences.sh production --dry-run ``` -------------------------------- ### Run All Tests Source: https://github.com/giantswarm/silence-operator/blob/main/docs/testing.md Executes all tests within the project. This is the primary command for a full test suite run. ```bash make test ``` -------------------------------- ### Verify KUBEBUILDER_ASSETS Detection Source: https://github.com/giantswarm/silence-operator/blob/main/docs/testing.md Run tests while specifying a Kubernetes version to ensure KUBEBUILDER_ASSETS are detected correctly. This is useful for compatibility testing. ```bash # Verify KUBEBUILDER_ASSETS detection make test ENVTEST_K8S_VERSION="1.30" ``` -------------------------------- ### Command-line Tenancy Configuration Source: https://github.com/giantswarm/silence-operator/blob/main/README.md Configuration for enabling multi-tenancy in the silence-operator using command-line flags. This provides an alternative to Helm configuration for enabling tenancy. ```bash --tenancy-enabled=true --tenancy-label-key="observability.giantswarm.io/tenant" --tenancy-default-tenant="default" # Legacy flag (deprecated but supported) --alertmanager-default-tenant-id="legacy-tenant" ``` -------------------------------- ### Run Bulk Migration Script Source: https://github.com/giantswarm/silence-operator/blob/main/MIGRATION.md Executes the provided migration script to automatically convert v1alpha1 silences to v1alpha2 format, including a dry-run option for testing. ```bash # Run the migration script (located in hack/migrate-silences.sh) ./hack/migrate-silences.sh [--dry-run] # Example: Test migration to production namespace (dry-run) ./hack/migrate-silences.sh production --dry-run ``` -------------------------------- ### Verify Silence Resources and Finalizers Source: https://github.com/giantswarm/silence-operator/blob/main/MIGRATION.md Commands to verify the existence of Silence resources across both API versions and check if finalizers are correctly set. This is crucial for ensuring proper resource management during migration. ```bash # Check both resources exist kubectl get silences.monitoring.giantswarm.io kubectl get silences.observability.giantswarm.io --all-namespaces # Verify finalizers are properly set kubectl get silences.monitoring.giantswarm.io test-v1alpha1 -o jsonpath='{.metadata.finalizers}' kubectl get silences.observability.giantswarm.io test-v1alpha2 -n default -o jsonpath='{.metadata.finalizers}' # Check controller logs for both APIs kubectl logs -f deployment/silence-operator -n monitoring ``` -------------------------------- ### View Coverage Summary Source: https://github.com/giantswarm/silence-operator/blob/main/docs/testing.md Display a summary of the test coverage, showing the percentage of covered lines for each function. This provides a quick overview of test coverage. ```bash # View coverage summary go tool cover -func=coverprofile.out ``` -------------------------------- ### Direct Alertmanager API Access with Client Interface Source: https://context7.com/giantswarm/silence-operator/llms.txt Wraps Alertmanager's /api/v2/silences REST API for direct access. Use alertmanager.New(cfg) for production. The `tenant` string adds the `X-Scope-OrgID` header for Mimir multi-tenancy when non-empty. ```go import ( "fmt" "github.com/giantswarm/silence-operator/pkg/alertmanager" "github.com/giantswarm/silence-operator/pkg/config" "time" ) cfg := config.Config{ Address: "http://alertmanager.monitoring.svc.cluster.local:9093", Authentication: false, } am, _ := alertmanager.New(cfg) // List all active (non-expired) silences silences, err := am.ListSilences("") // "" = no tenant header if err != nil { panic(err) } for _, s := range silences { fmt.Printf("ID: %s Comment: %s State: %s\n", s.ID, s.Comment, s.Status.State) } // Create a silence newSilence := &alertmanager.Silence{ Comment: "silence-operator-my-silence", CreatedBy: alertmanager.CreatedBy, StartsAt: time.Now(), EndsAt: time.Now().Add(4 * time.Hour), Matchers: []alertmanager.Matcher{ {Name: "alertname", Value: "Watchdog", IsRegex: false, IsEqual: true}, }, } if err := am.CreateSilence(newSilence, ""); err != nil { panic(err) } // Retrieve by comment found, err := am.GetSilenceByComment("silence-operator-my-silence", "") if err != nil { panic(err) // may be alertmanager.ErrSilenceNotFound } fmt.Println("Found:", found.ID) // Delete by ID if err := am.DeleteSilenceByID(found.ID, ""); err != nil { panic(err) } ``` -------------------------------- ### Migrate v1alpha1 to v1alpha2 Silences Source: https://context7.com/giantswarm/silence-operator/llms.txt This script automates the migration of v1alpha1 cluster-scoped silences to v1alpha2 namespace-scoped silences. It converts match type enums, preserves annotations/labels, and strips system metadata. Requires kubectl and jq. ```bash # Prerequisites: kubectl and jq must be on PATH # 1. Dry run — see what would be migrated without creating anything ./hack/migrate-silences.sh production --dry-run # 🔍 DRY RUN MODE: No resources will be created # 🔄 Migrating v1alpha1 silences to v1alpha2 in namespace: production # 📝 Found 3 v1alpha1 silence(s) to migrate # 🔄 Processing silence: my-sample-silence # 📝 alertname: isRegex=false, isEqual=true → matchType='=' # 📝 alertname: isRegex=false, isEqual=false → matchType='!=' # 📎 Copying 1 user annotation(s): valid-until # 🔍 DRY RUN: Would create v1alpha2 silence in namespace production # 2. Run the actual migration ./hack/migrate-silences.sh production # ✅ Successfully created v1alpha2 silence: my-sample-silence # 3. Verify the result kubectl get silences.observability.giantswarm.io -n production # NAME AGE # my-sample-silence 5s # 4. Check both API versions are in sync before removing old silences echo "v1alpha1: $(kubectl get silences.monitoring.giantswarm.io --no-headers | wc -l)" echo "v1alpha2: $(kubectl get silences.observability.giantswarm.io -n production --no-headers | wc -l)" # 5. Remove old v1alpha1 silences once verified kubectl delete silences.monitoring.giantswarm.io --all ``` -------------------------------- ### Upgrade Helm Chart from OCI Registry Source: https://github.com/giantswarm/silence-operator/blob/main/README.md Command to upgrade the silence-operator chart from the OCI registry. Replace [RELEASE_NAME] and [VERSION] with your specific values. ```console helm upgrade [RELEASE_NAME] oci://gsoci.azurecr.io/charts/giantswarm/silence-operator --version [VERSION] ``` -------------------------------- ### Detect Kubernetes Binaries Source: https://github.com/giantswarm/silence-operator/blob/main/docs/testing.md This Go function automatically detects Kubernetes testing binaries in the 'bin/k8s/' directory. It falls back to using the KUBEBUILDER_ASSETS environment variable if the binaries are not found locally. ```go func getKubeBuilderAssets() string { // Automatically detects k8s binaries in bin/k8s/ directory // Falls back to environment variable if needed } ``` -------------------------------- ### Upgrade Helm Chart from Repository Source: https://github.com/giantswarm/silence-operator/blob/main/README.md Command to upgrade the silence-operator chart from the Helm repository. This assumes the giantswarm repository is already added and updated. ```console helm upgrade [RELEASE_NAME] giantswarm/silence-operator ``` -------------------------------- ### v1alpha1 to v1alpha2 MatchType Conversion Source: https://context7.com/giantswarm/silence-operator/llms.txt Illustrates the conversion from v1alpha1's boolean `isRegex`/`isEqual` fields to v1alpha2's `matchType` enum. Use this for understanding equivalent configurations. ```yaml # v1alpha1 — boolean approach spec: matchers: - name: severity value: "critical" isRegex: false isEqual: true # v1alpha2 — enum approach (equivalent) spec: matchers: - name: severity value: "critical" matchType: "=" ``` -------------------------------- ### List Silences Across API Versions Source: https://github.com/giantswarm/silence-operator/blob/main/MIGRATION.md Commands to list Silence resources using both the v1alpha1 (cluster-scoped) and v1alpha2 (namespace-scoped) API versions. Useful for comparing counts during migration. ```bash # List all v1alpha1 silences (cluster-scoped) kubectl get silences.monitoring.giantswarm.io # List all v1alpha2 silences (all namespaces) kubectl get silences.observability.giantswarm.io --all-namespaces # Compare counts echo "v1alpha1 count: $(kubectl get silences.monitoring.giantswarm.io --no-headers | wc -l)" echo "v1alpha2 count: $(kubectl get silences.observability.giantswarm.io --all-namespaces --no-headers | wc -l)" ``` -------------------------------- ### Run Tests with Coverage Collection Source: https://github.com/giantswarm/silence-operator/blob/main/docs/testing.md Execute the test suite, which includes coverage collection. This command is part of the standard development workflow to ensure code quality. ```bash # Run tests (includes coverage) make test ``` -------------------------------- ### alertmanager.Client Interface Source: https://context7.com/giantswarm/silence-operator/llms.txt Provides direct access to Alertmanager's `/api/v2/silences` REST API. Use `alertmanager.New(cfg)` to instantiate. Methods can accept a tenant string to add the `X-Scope-OrgID` header for Mimir multi-tenancy. ```APIDOC ## `alertmanager.Client` interface — direct Alertmanager API access The `Client` interface wraps Alertmanager's `/api/v2/silences` REST API. Use `alertmanager.New(cfg)` for the production implementation. All methods accept a `tenant` string that, when non-empty, adds the `X-Scope-OrgID` header for Mimir multi-tenancy. ```go import ( "fmt" "github.com/giantswarm/silence-operator/pkg/alertmanager" "github.com/giantswarm/silence-operator/pkg/config" "time" ) cfg := config.Config{ Address: "http://alertmanager.monitoring.svc.cluster.local:9093", Authentication: false, } am, _ := alertmanager.New(cfg) // List all active (non-expired) silences silences, err := am.ListSilences("") // "" = no tenant header if err != nil { panic(err) } for _, s := range silences { fmt.Printf("ID: %s Comment: %s State: %s\n", s.ID, s.Comment, s.Status.State) } // Create a silence newSilence := &alertmanager.Silence{ Comment: "silence-operator-my-silence", CreatedBy: alertmanager.CreatedBy, StartsAt: time.Now(), EndsAt: time.Now().Add(4 * time.Hour), Matchers: []alertmanager.Matcher{ {Name: "alertname", Value: "Watchdog", IsRegex: false, IsEqual: true}, }, } if err := am.CreateSilence(newSilence, ""); err != nil { panic(err) } // Retrieve by comment found, err := am.GetSilenceByComment("silence-operator-my-silence", "") if err != nil { panic(err) // may be alertmanager.ErrSilenceNotFound } fmt.Println("Found:", found.ID) // Delete by ID if err := am.DeleteSilenceByID(found.ID, ""); err != nil { panic(err) } ``` ``` -------------------------------- ### Apply and Verify Silence CR Source: https://context7.com/giantswarm/silence-operator/llms.txt Apply the Silence CR using kubectl and verify its creation. Check for the presence of the finalizer, which ensures clean Alertmanager deletion upon CR removal. ```bash kubectl apply -f silence.yaml # silence.observability.giantswarm.io/deployment-rollout-silence created ``` ```bash kubectl get silences.observability.giantswarm.io -n platform-team # NAME AGE # deployment-rollout-silence 5s ``` ```bash kubectl get silence deployment-rollout-silence -n platform-team \ -o jsonpath='{.metadata.finalizers}' # ["observability.giantswarm.io/silence-protection"] ``` -------------------------------- ### Create Cluster-Scoped Silence (v1alpha1) Source: https://context7.com/giantswarm/silence-operator/llms.txt Use this to create a cluster-scoped Silence resource using the legacy v1alpha1 API. It utilizes boolean `isRegex` and `isEqual` fields for matching. ```yaml apiVersion: monitoring.giantswarm.io/v1alpha1 kind: Silence metadata: name: my-sample-silence annotations: valid-until: "2025-06-30" spec: matchers: - name: alertname value: MyPagingAlert isRegex: false # literal string match isEqual: true # must equal (use false for !=) - name: alertname value: Heartbeat isRegex: false isEqual: false # isEqual: false → != (exclude Heartbeat alerts) - name: cluster value: "prod-.*" isRegex: true # regex isEqual: true # must match regex owner: "alice" issue_url: "https://github.com/example/issues/42" ``` -------------------------------- ### Apply Namespace-Scoped Silence CRD (Recommended) Source: https://github.com/giantswarm/silence-operator/blob/main/README.md Manually apply the namespace-scoped CRD for silences. This is the recommended approach for new deployments using the observability API. ```bash # For new namespace-scoped silences (recommended) kubectl apply --server-side -f https://raw.githubusercontent.com/giantswarm/silence-operator/refs/heads/main/config/crd/bases/observability.giantswarm.io_silences.yaml ``` -------------------------------- ### Generate HTML Coverage Report Source: https://github.com/giantswarm/silence-operator/blob/main/docs/testing.md Generate an HTML visualization of the test coverage report. This is useful for identifying areas of the codebase that are not adequately tested. ```bash # Generate HTML coverage report go tool cover -html=coverprofile.out -o coverage.html ``` -------------------------------- ### Increase Test Timeout with Ginkgo Args Source: https://github.com/giantswarm/silence-operator/blob/main/docs/testing.md Increase the timeout for Ginkgo tests by passing a custom timeout value. This is a solution for test timeout issues. ```bash # Solution: Increase timeout with Ginkgo args make test GINKGO_ARGS="-timeout=15m" ``` -------------------------------- ### Apply and Test v1alpha1 Silence Migration Source: https://github.com/giantswarm/silence-operator/blob/main/docs/testing.md Apply a v1alpha1 Silence manifest and then test the migration script with the --dry-run flag. This is useful for verifying the migration process without making actual changes. ```bash # Create test v1alpha1 silence kubectl apply -f - <