Skip to content

MG-56: Flag based deletion of must-gather job and CR - #259

Merged
openshift-merge-bot[bot] merged 4 commits into
openshift:masterfrom
rausingh-rh:MG-56
Oct 24, 2025
Merged

openshift-merge-bot[bot] merged 4 commits into
openshift:masterfrom
rausingh-rh:MG-56

Conversation

@rausingh-rh

@rausingh-rh rausingh-rh commented Aug 13, 2025 •

Copy link
Copy Markdown
Contributor

This PR implements the change to prevent the immediate deletion of must-gather CR and its associated job upon completion and gives the user visibility into the final status of the operation and the ability to review the logs and resource state before the cleanup process. This behavior will be flag based.

  1. retainResourcesOnCompletion field should be set to true in the spec for the resources to be retained. Default behavior will be to delete all the resources.
  2. MustGather CR will be retained irrespective of the retainResourcesOnCompletion field.

@openshift-ci-robot openshift-ci-robot added the jira/valid-reference Indicates that this PR references a valid Jira ticket of any type. label Aug 13, 2025
@openshift-ci-robot

openshift-ci-robot commented Aug 13, 2025 •

Copy link
Copy Markdown

@rausingh-rh: This pull request references MG-56 which is a valid jira issue.

Warning: The referenced jira issue has an invalid target version for the target branch this PR targets: expected the story to target the "4.20.0" version, but no target version was set.

Details

In response to this:

This PR implements the change to prevent the immediate deletion of must-gather CR and its associated job upon completion and gives the user visibility into the final status of the operation and the ability to review the logs and resource state before the cleanup process.

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the openshift-eng/jira-lifecycle-plugin repository.

@codecov-commenter

codecov-commenter commented Aug 13, 2025 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.93103% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 74.60%. Comparing base (e1efbd3) to head (238da2f).
⚠️ Report is 84 commits behind head on master.

Files with missing lines Patch % Lines
controllers/mustgather/mustgather_controller.go 97.93% 3 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff             @@
##           master     #259       +/-   ##
===========================================
+ Coverage   38.05%   74.60%   +36.55%     
===========================================
  Files           7        7               
  Lines         473      512       +39     
===========================================
+ Hits          180      382      +202     
+ Misses        289      128      -161     
+ Partials        4        2        -2     
Files with missing lines Coverage Δ
api/v1alpha1/mustgather_types.go 100.00% <ø> (+66.66%) ⬆️
controllers/mustgather/mustgather_controller.go 91.96% <97.93%> (+82.77%) ⬆️

... and 1 file with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@rausingh-rh
rausingh-rh force-pushed the MG-56 branch 3 times, most recently from f1ea410 to c461945 Compare August 14, 2025 13:33
@rausingh-rh
rausingh-rh force-pushed the MG-56 branch 3 times, most recently from 87a1e86 to d53fdc0 Compare August 23, 2025 06:45
@rausingh-rh

Copy link
Copy Markdown
Contributor Author

/test test

@openshift-ci-robot

openshift-ci-robot commented Aug 23, 2025 •

Copy link
Copy Markdown

@rausingh-rh: This pull request references MG-56 which is a valid jira issue.

Warning: The referenced jira issue has an invalid target version for the target branch this PR targets: expected the story to target the "4.20.0" version, but no target version was set.

Details

In response to this:

This PR implements the change to prevent the immediate deletion of must-gather CR and its associated job upon completion and gives the user visibility into the final status of the operation and the ability to review the logs and resource state before the cleanup process. This behavior will be flag based.

  1. retainResourcesOnCompletion field should be set to true in the spec for the resources to be retained. Default behavior will be to delete all the resources.
  2. MustGather CR will be retained irrespective of the retainResourcesOnCompletion filed.

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the openshift-eng/jira-lifecycle-plugin repository.

@rausingh-rh
rausingh-rh force-pushed the MG-56 branch 4 times, most recently from 7e83bfe to a964044 Compare August 24, 2025 17:24
@rausingh-rh rausingh-rh changed the title MG-56: Avoid immediate deletion of must-gather job and CR MG-56: Flag based deletion of must-gather job and CR Aug 24, 2025
@rausingh-rh
rausingh-rh force-pushed the MG-56 branch 8 times, most recently from b1080ee to 6b2c03f Compare August 29, 2025 09:13
Comment thread api/v1alpha1/mustgather_types.go Resolved
@openshift-ci-robot

openshift-ci-robot commented Aug 30, 2025 •

Copy link
Copy Markdown

@rausingh-rh: This pull request references MG-56 which is a valid jira issue.

Warning: The referenced jira issue has an invalid target version for the target branch this PR targets: expected the story to target the "4.20.0" version, but no target version was set.

Details

In response to this:

This PR implements the change to prevent the immediate deletion of must-gather CR and its associated job upon completion and gives the user visibility into the final status of the operation and the ability to review the logs and resource state before the cleanup process. This behavior will be flag based.

  1. retainResourcesOnCompletion field should be set to true in the spec for the resources to be retained. Default behavior will be to delete all the resources.
  2. MustGather CR will be retained irrespective of the retainResourcesOnCompletion field.

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the openshift-eng/jira-lifecycle-plugin repository.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

♻️ Duplicate comments (7)
deploy/crds/managed.openshift.io_mustgathers.yaml (2)

99-104: *Bool vs bool for API forward‑compatibility

Using bool prevents distinguishing “unset” vs “false.” Consider switching to *bool for future defaulting without breaking existing clients. Acknowledge that this may require an API‑wide pass.


99-104: Retention flag must not affect CR deletion; fix description accordingly

The description conflates post-completion retention with CR deletion. On CR deletion, the operator must always clean up to avoid credential leaks. Please update the schema text.

Apply this diff:

-                description: |-
-                  A flag to specify if resources (secret, job, pods) should be retained when the MustGather completes.
-                  If set to true, resources will be retained. If false or not set, resources will be deleted (default behavior).
+                description: |-
+                  If true, retain resources (secret, job, pods) after the MustGather completes so users can inspect them.
+                  This flag does not affect CR deletion: when the MustGather CR is deleted, the operator will always
+                  clean up all associated resources.
controllers/mustgather/mustgather_controller_test.go (2)

405-410: Env restoration bug when simulating unset OPERATOR_IMAGE

This restores OPERATOR_IMAGE to empty string even if it was originally unset, leaking state to subsequent subtests.

-setupEnv: func(t *testing.T) {
-    osUnset := os.Getenv("OPERATOR_IMAGE")
-    _ = os.Unsetenv("OPERATOR_IMAGE")
-    t.Cleanup(func() { os.Setenv("OPERATOR_IMAGE", osUnset) })
-},
+setupEnv: func(t *testing.T) {
+    old, wasSet := os.LookupEnv("OPERATOR_IMAGE")
+    _ = os.Unsetenv("OPERATOR_IMAGE")
+    t.Cleanup(func() {
+        if wasSet {
+            _ = os.Setenv("OPERATOR_IMAGE", old)
+        } else {
+            _ = os.Unsetenv("OPERATOR_IMAGE")
+        }
+    })
+},

340-404: Missing coverage: CR deletion with retain=true must not orphan copied secret

Please add a test for DeletionTimestamp set and Spec.RetainResourcesOnCompletion=true ensuring the copied Secret in operatorNs is deleted (or owner‑referenced).

Sketch to add to the TestReconcile table near other deletion cases:

+{
+  name: "reconcile_deletion_retain_true_still_cleans_copied_secret",
+  setupEnv: func(t *testing.T) {},
+  setupObjects: func() []client.Object {
+    mg := &mustgatherv1alpha1.MustGather{
+      ObjectMeta: metav1.ObjectMeta{
+        Name: "mg", Namespace: operatorNs,
+        Finalizers: []string{mustgatherFinalizer}, DeletionTimestamp: &metav1.Time{Time: time.Now()},
+      },
+      Spec: mustgatherv1alpha1.MustGatherSpec{
+        CaseManagementAccountSecretRef: corev1.LocalObjectReference{Name: "sec"},
+        ServiceAccountRef:              corev1.LocalObjectReference{Name: "default"},
+        RetainResourcesOnCompletion:    true,
+      },
+    }
+    opSec := &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: "sec", Namespace: operatorNs}}
+    return []client.Object{mg, opSec}
+  },
+  interceptors: func() interceptClient { return interceptClient{} },
+  expectError:  false,
+  expectResult: reconcile.Result{},
+  postTestChecks: func(t *testing.T, cl client.Client) {
+    got := &corev1.Secret{}
+    err := cl.Get(context.TODO(), types.NamespacedName{Namespace: operatorNs, Name: "sec"}, got)
+    if err == nil {
+      t.Fatalf("expected copied secret to be removed on CR deletion even with retain=true")
+    }
+  },
+},

I can wire this for you if helpful.

controllers/mustgather/mustgather_controller.go (3)

285-289: Nil dereference: job.Status.CompletionTime is a pointer

This will panic when CompletionTime is nil.

-func (r *MustGatherReconciler) updateStatus(ctx context.Context, instance *mustgatherv1alpha1.MustGather, job *batchv1.Job) (reconcile.Result, error) {
-    instance.Status.Completed = !job.Status.CompletionTime.IsZero()
-    return r.ManageSuccess(ctx, instance)
-}
+func (r *MustGatherReconciler) updateStatus(ctx context.Context, instance *mustgatherv1alpha1.MustGather, job *batchv1.Job) (reconcile.Result, error) {
+    if job.Status.CompletionTime != nil && !job.Status.CompletionTime.IsZero() {
+        instance.Status.Completed = true
+    } else {
+        instance.Status.Completed = false
+    }
+    return r.ManageSuccess(ctx, instance)
+}

419-423: Go range address bug: taking address of loop variable

All entries in podObjs point to the same tmpPod due to the range variable reuse, causing incorrect deletions.

- podObjs := make([]client.Object, len(podList.Items))
- for i, tmpPod := range podList.Items {
-     podObjs[i] = &tmpPod
- }
+ podObjs := make([]client.Object, len(podList.Items))
+ for i := range podList.Items {
+     podObjs[i] = &podList.Items[i]
+ }

127-135: Finalizer must always clean up to avoid credential leak

Skipping cleanup when retainResourcesOnCompletion=true can orphan the copied Secret in operator namespace on CR deletion.

Apply this diff:

-            // Clean up resources if RetainResourcesOnCompletion is false (default behavior)
-            if !instance.Spec.RetainResourcesOnCompletion {
-                reqLogger.V(4).Info("running finalization logic for mustGatherFinalizer")
-                err := r.cleanupMustGatherResources(ctx, reqLogger, instance, operatorNs)
-                if err != nil {
-                    reqLogger.Error(err, "failed to cleanup MustGather resources during deletion")
-                    return reconcile.Result{}, err
-                }
-            }
+            // Always clean up on CR deletion
+            reqLogger.V(4).Info("running finalization logic for mustgather finalizer")
+            if err := r.cleanupMustGatherResources(ctx, reqLogger, instance, operatorNs); err != nil {
+                reqLogger.Error(err, "failed to cleanup mustgather resources during deletion")
+                return reconcile.Result{}, err
+            }
🧹 Nitpick comments (9)
deploy/crds/managed.openshift.io_mustgathers.yaml (2)

106-109: Remove kubebuilder directive from description; set default via schema or controller

The “+kubebuilder:default:="{Name:default}"” string in description is misleading in generated CRD and isn’t enforced. Either:

  • encode a real default in the schema, or
  • rely on controller defaulting (you already do) and keep description clean.

Proposed description tweak:

-                  the service account to use to run the must gather job pod, defaults to default
-                  +kubebuilder:default:="{Name:default}"
+                  The service account to use for the must-gather job pod. Defaults to "default".

49-55: Typos/grammar

  • “The is of the case” → “The ID of the case”
  • “the secret container a username and password” → “the secret containing username and password”
controllers/mustgather/mustgather_controller_test.go (3)

87-93: Add Patch to failingStatusWriter to avoid nil-interface panic

If Status().Patch is called, the embedded nil StatusWriter will panic. Implement Patch explicitly.

 type failingStatusWriter struct{ client.StatusWriter }

 func (w failingStatusWriter) Update(ctx context.Context, obj client.Object, opts ...client.SubResourceUpdateOption) error {
   return errors.New("forced status update error")
 }
+
+func (w failingStatusWriter) Patch(ctx context.Context, obj client.Object, patch client.Patch, opts ...client.SubResourcePatchOption) error {
+  return errors.New("forced status patch error")
+}

426-429: Use t.Setenv for per‑test env isolation

Prefer t.Setenv over os.Setenv to avoid cross‑test leakage.

Example:

- os.Setenv("OPERATOR_IMAGE", "img")
+ t.Setenv("OPERATOR_IMAGE", "img")

Please apply to all occurrences in this file.

Also applies to: 446-449, 512-514, 693-694, 726-727, 826-827, 863-864, 900-902, 938-940


134-156: Test name doesn’t match expectation

The case is named “continues_successfully” but expectError is true.

- name: "cleanup_job_get_error_continues_successfully",
+ name: "cleanup_job_get_error_returns_error",
controllers/mustgather/mustgather_controller.go (4)

397-405: Log severity and messaging for job Get errors

Non‑NotFound errors should be logged at Error level with accurate message; the current Info log is misleading.

-    if !errors.IsNotFound(err) {
-        reqLogger.Info(fmt.Sprintf("failed to get %s job", instance.Name))
-        return err
-    }
-    reqLogger.Info(fmt.Sprintf("job %s not found", instance.Name))
+    if !errors.IsNotFound(err) {
+        reqLogger.Error(err, fmt.Sprintf("failed to get job %s", instance.Name))
+        return err
+    }
+    reqLogger.Info(fmt.Sprintf("job %s not found", instance.Name))

189-211: “Secret already exists” log is unconditional and misleading

This logs “already exists” even when the secret was just created. Log creation vs existence distinctly.

-        if err != nil {
-            if !errors.IsNotFound(err) {
-                log.Error(err, fmt.Sprintf("Error getting new secret %s", secretName))
-                return reconcile.Result{}, err
-            }
-            newSecret.Name = secretName
-            newSecret.Namespace = operatorNs
-            newSecret.Data = userSecret.Data
-            newSecret.Type = userSecret.Type
-            err = r.GetClient().Create(ctx, newSecret)
-            if err != nil {
-                log.Error(err, fmt.Sprintf("Error creating new secret %s", secretName))
-                return reconcile.Result{}, err
-            }
-        }
-        log.Info(fmt.Sprintf("Secret %s already exists in the %s namespace", secretName, operatorNs))
+        if err != nil {
+            if !errors.IsNotFound(err) {
+                log.Error(err, fmt.Sprintf("error getting operator secret %s", secretName))
+                return reconcile.Result{}, err
+            }
+            newSecret.Name = secretName
+            newSecret.Namespace = operatorNs
+            newSecret.Data = userSecret.Data
+            newSecret.Type = userSecret.Type
+            if err := r.GetClient().Create(ctx, newSecret); err != nil {
+                log.Error(err, fmt.Sprintf("error creating operator secret %s", secretName))
+                return reconcile.Result{}, err
+            }
+            log.Info(fmt.Sprintf("created operator secret %s", secretName))
+        } else {
+            log.Info(fmt.Sprintf("operator secret %s already exists in %s", secretName, operatorNs))
+        }

325-331: Consistent lower‑case logs; prefer structured fields

Minor polish for log consistency.

- reqLogger.Info("Adding Finalizer for the MustGather")
+ reqLogger.Info("adding finalizer for mustgather")

200-208: Optional: ownerRef on copied secret as defense‑in‑depth

If you ever reintroduce conditional finalizer cleanup, set the copied secret’s OwnerReference to the MustGather CR so GC removes it on deletion.

Example:

newSecret.OwnerReferences = []metav1.OwnerReference{{
    APIVersion: mustgatherv1alpha1.GroupVersion.String(),
    Kind:       "MustGather",
    Name:       instance.Name,
    UID:        instance.UID,
}}
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

Cache: Disabled due to data retention organization setting

Knowledge base: Disabled due to Reviews -> Disable Knowledge Base setting

📥 Commits

Reviewing files that changed from the base of the PR and between d402fb7 and 0309ea6.

📒 Files selected for processing (9)
  • api/v1alpha1/mustgather_types.go (1 hunks)
  • api/v1alpha1/zz_generated.openapi.go (2 hunks)
  • build/Dockerfile (1 hunks)
  • build/Dockerfile.olm-registry (1 hunks)
  • bundle/manifests/tech-preview/managed.openshift.io_mustgathers.yaml (1 hunks)
  • controllers/mustgather/mustgather_controller.go (8 hunks)
  • controllers/mustgather/mustgather_controller_test.go (1 hunks)
  • deploy/crds/managed.openshift.io_mustgathers.yaml (2 hunks)
  • examples/mustgather_retain_resources.yaml (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (6)
  • examples/mustgather_retain_resources.yaml
  • api/v1alpha1/mustgather_types.go
  • build/Dockerfile.olm-registry
  • build/Dockerfile
  • bundle/manifests/tech-preview/managed.openshift.io_mustgathers.yaml
  • api/v1alpha1/zz_generated.openapi.go
🔇 Additional comments (2)
deploy/crds/managed.openshift.io_mustgathers.yaml (1)

80-98: Requiring both httpProxy and httpsProxy may be too strict

Many environments set only HTTPS proxy. Confirm this requirement is intentional and compatible with existing users; otherwise, drop the required list or require only httpsProxy.

controllers/mustgather/mustgather_controller_test.go (1)

511-538: Either assert status for ‘active’ or rename the test

The test name suggests status is set to Running, but no assertion exists and controller doesn’t set Status on Active. Either:

  • add an assertion aligned with implementation (e.g., Completed=false; leave Status unchanged), or
  • update controller to set Status="Running" and assert it.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (4)
api/v1alpha1/mustgather_types.go (1)

62-66: *Use bool for API booleans (compatibility and tri-state semantics).

Per Kubernetes API conventions, booleans in external APIs should be pointers to distinguish unset vs explicitly false and to avoid marshaling pitfalls with omitempty on value bools. Please change to *bool and keep defaulting via CRD.

Example:

-// +kubebuilder:default:=false
-RetainResourcesOnCompletion bool `json:"retainResourcesOnCompletion,omitempty"`
+// +kubebuilder:default:=false
+RetainResourcesOnCompletion *bool `json:"retainResourcesOnCompletion,omitempty"`

Adjust controller checks using a local deref:

retain := instance.Spec.RetainResourcesOnCompletion != nil && *instance.Spec.RetainResourcesOnCompletion
controllers/mustgather/mustgather_controller.go (3)

285-289: Nil-pointer deref on job.Status.CompletionTime.

CompletionTime is a pointer; guard before IsZero.

-func (r *MustGatherReconciler) updateStatus(ctx context.Context, instance *mustgatherv1alpha1.MustGather, job *batchv1.Job) (reconcile.Result, error) {
-    instance.Status.Completed = !job.Status.CompletionTime.IsZero()
+func (r *MustGatherReconciler) updateStatus(ctx context.Context, instance *mustgatherv1alpha1.MustGather, job *batchv1.Job) (reconcile.Result, error) {
+    if job.Status.CompletionTime != nil && !job.Status.CompletionTime.IsZero() {
+        instance.Status.Completed = true
+    } else {
+        instance.Status.Completed = false
+    }
     return r.ManageSuccess(ctx, instance)
 }

419-423: Range-address pitfall: deleting wrong Pods.

Taking &tmpPod in a range loop captures the address of the loop variable, not the slice item. Use index to take the address of the slice element.

- for i, tmpPod := range podList.Items {
-     podObjs[i] = &tmpPod
- }
+ for i := range podList.Items {
+     podObjs[i] = &podList.Items[i]
+ }

127-135: Always clean up on CR deletion (avoid credential leak).

Finalizer skips cleanup when retain=true, orphaning the copied Secret in operator namespace. Run cleanup unconditionally during deletion.

-            // Clean up resources if RetainResourcesOnCompletion is false (default behavior)
-            if !instance.Spec.RetainResourcesOnCompletion {
-                reqLogger.V(4).Info("running finalization logic for mustGatherFinalizer")
-                err := r.cleanupMustGatherResources(ctx, reqLogger, instance, operatorNs)
-                if err != nil {
-                    reqLogger.Error(err, "failed to cleanup MustGather resources during deletion")
-                    return reconcile.Result{}, err
-                }
-            }
+            reqLogger.V(4).Info("running finalization logic for mustgather finalizer")
+            if err := r.cleanupMustGatherResources(ctx, reqLogger, instance, operatorNs); err != nil {
+                reqLogger.Error(err, "failed to cleanup mustgather resources during deletion")
+                return reconcile.Result{}, err
+            }
🧹 Nitpick comments (8)
bundle/manifests/tech-preview/operator.openshift.io_mustgathers.yaml (1)

99-104: Clarify retention vs deletion semantics (avoid orphaned resources).

Explicitly state that CR deletion always triggers cleanup regardless of this flag.

               description: |-
-                  A flag to specify if resources (secret, job, pods) should be retained when the MustGather completes.
-                  If set to true, resources will be retained. If false or not set, resources will be deleted (default behavior).
+                  If true, retain resources (secret, job, pods) after the MustGather completes so users can inspect them.
+                  This flag does not affect CR deletion: when the MustGather CR is deleted, the operator will always
+                  clean up all associated resources. Default is false (delete resources on completion).
deploy/crds/operator.openshift.io_mustgathers.yaml (1)

99-104: Keep CRD docs consistent with deletion behavior.

Mirror the same clarification here to avoid ambiguity across CRDs.

               description: |-
-                  A flag to specify if resources (secret, job, pods) should be retained when the MustGather completes.
-                  If set to true, resources will be retained. If false or not set, resources will be deleted (default behavior).
+                  If true, retain resources (secret, job, pods) after the MustGather completes so users can inspect them.
+                  This flag does not affect CR deletion: when the MustGather CR is deleted, the operator will always
+                  clean up all associated resources. Default is false (delete resources on completion).
controllers/mustgather/mustgather_controller_test.go (5)

87-92: Add Status().Patch stub to avoid nil-interface panics.

Tests may call Status().Patch in the future; current writer embeds a nil StatusWriter and only overrides Update.

 type failingStatusWriter struct{ client.StatusWriter }

 func (w failingStatusWriter) Update(ctx context.Context, obj client.Object, opts ...client.SubResourceUpdateOption) error {
   return errors.New("forced status update error")
 }
+
+func (w failingStatusWriter) Patch(ctx context.Context, obj client.Object, patch client.Patch, opts ...client.SubResourcePatchOption) error {
+  return errors.New("forced status patch error")
+}

511-538: Assert status when Job is active (test name claims it).

Verify Status is “Running” (or equivalent) and Completed=false.

- postTestChecks: func(t *testing.T, cl client.Client) {},
+ postTestChecks: func(t *testing.T, cl client.Client) {
+   out := &mustgatherv1alpha1.MustGather{}
+   if err := cl.Get(context.TODO(), types.NamespacedName{Name: "example-mustgather", Namespace: "ns"}, out); err != nil {
+     t.Fatalf("get mustgather: %v", err)
+   }
+   if out.Status.Completed {
+     t.Fatalf("expected Completed=false when job active")
+   }
+   if out.Status.Status != "Running" {
+     t.Fatalf("expected Status=Running, got %q", out.Status.Status)
+   }
+ },

342-369: Add coverage: CR deletion with retain=true must not orphan copied Secret.

Please add a test where DeletionTimestamp is set and Spec.RetainResourcesOnCompletion=true; assert the operator-namespace Secret is deleted (or owner-referenced). I can wire the provided snippet into your table suite if helpful.


134-156: Rename test for accuracy.

Name says “continues successfully” but expectError=true. Consider renaming to “…returns_error”.


426-430: Use t.Setenv to isolate environment per subtest.

All identified os.Setenv calls at lines 428, 448, 487, 513, 542, 579, 618, 656, 693, 726, 826, 863, 901, 939 are setting environment variables without test-level isolation. Replace each with t.Setenv to prevent state leakage:

- os.Setenv("OPERATOR_IMAGE", "img")
+ t.Setenv("OPERATOR_IMAGE", "img")

This automatically cleans up after the subtest completes, matching the intent shown at line 409's manual cleanup pattern.

controllers/mustgather/mustgather_controller.go (1)

190-211: Avoid misleading “already exists” log after secret creation.

Log “created” when you create; only log “already exists” if Get found it.

-        if err != nil {
-            if !errors.IsNotFound(err) {
-                log.Error(err, fmt.Sprintf("Error getting new secret %s", secretName))
-                return reconcile.Result{}, err
-            }
-            newSecret.Name = secretName
-            newSecret.Namespace = operatorNs
-            newSecret.Data = userSecret.Data
-            newSecret.Type = userSecret.Type
-            err = r.GetClient().Create(ctx, newSecret)
-            if err != nil {
-                log.Error(err, fmt.Sprintf("Error creating new secret %s", secretName))
-                return reconcile.Result{}, err
-            }
-        }
-        log.Info(fmt.Sprintf("Secret %s already exists in the %s namespace", secretName, operatorNs))
+        if err != nil {
+            if !errors.IsNotFound(err) {
+                log.Error(err, fmt.Sprintf("error getting new secret %s", secretName))
+                return reconcile.Result{}, err
+            }
+            newSecret.Name = secretName
+            newSecret.Namespace = operatorNs
+            newSecret.Data = userSecret.Data
+            newSecret.Type = userSecret.Type
+            if err = r.GetClient().Create(ctx, newSecret); err != nil {
+                log.Error(err, fmt.Sprintf("error creating new secret %s", secretName))
+                return reconcile.Result{}, err
+            }
+            log.Info(fmt.Sprintf("created secret %s in %s", secretName, operatorNs))
+        } else {
+            log.Info(fmt.Sprintf("secret %s already exists in %s", secretName, operatorNs))
+        }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

Cache: Disabled due to data retention organization setting

Knowledge base: Disabled due to Reviews -> Disable Knowledge Base setting

📥 Commits

Reviewing files that changed from the base of the PR and between 0309ea6 and 0e97d9a.

📒 Files selected for processing (6)
  • api/v1alpha1/mustgather_types.go (1 hunks)
  • bundle/manifests/tech-preview/operator.openshift.io_mustgathers.yaml (1 hunks)
  • controllers/mustgather/mustgather_controller.go (8 hunks)
  • controllers/mustgather/mustgather_controller_test.go (1 hunks)
  • deploy/crds/operator.openshift.io_mustgathers.yaml (1 hunks)
  • examples/mustgather_retain_resources.yaml (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • examples/mustgather_retain_resources.yaml

@swghosh

swghosh commented Oct 23, 2025

Copy link
Copy Markdown
Member

/cherry-pick release-4.20

@openshift-cherrypick-robot

Copy link
Copy Markdown

@swghosh: once the present PR merges, I will cherry-pick it on top of release-4.20 in a new PR and assign it to you.

Details

In response to this:

/cherry-pick release-4.20

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository.

@KeenonLee

Copy link
Copy Markdown
Contributor

only rebase
/verified bypass

@openshift-merge-robot openshift-merge-robot added the needs-rebase Indicates a PR cannot be merged because it has merge conflicts with HEAD. label Oct 23, 2025
@openshift-ci-robot openshift-ci-robot added the verified Signifies that the PR passed pre-merge verification criteria label Oct 23, 2025
@openshift-ci-robot

Copy link
Copy Markdown

@KeenonLee: The verified label has been added.

Details

In response to this:

only rebase
/verified bypass

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the openshift-eng/jira-lifecycle-plugin repository.

@openshift-ci-robot openshift-ci-robot removed the verified Signifies that the PR passed pre-merge verification criteria label Oct 24, 2025
@openshift-merge-robot openshift-merge-robot removed the needs-rebase Indicates a PR cannot be merged because it has merge conflicts with HEAD. label Oct 24, 2025

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

♻️ Duplicate comments (5)
controllers/mustgather/mustgather_controller_test.go (2)

88-93: Add Patch method to failingStatusWriter to prevent nil-pointer panic.

The failingStatusWriter embeds client.StatusWriter but only overrides Update. If any controller code calls Status().Patch(), it will attempt to call the method on the nil embedded interface, causing a panic.

Apply this diff to add the missing method:

 func (w failingStatusWriter) Update(ctx context.Context, obj client.Object, opts ...client.SubResourceUpdateOption) error {
   return errors.New("forced status update error")
 }
+
+func (w failingStatusWriter) Patch(ctx context.Context, obj client.Object, patch client.Patch, opts ...client.SubResourcePatchOption) error {
+  return errors.New("forced status patch error")
+}

141-161: Fix misleading test case name.

The test case is named "cleanup_job_get_error_continues_successfully" but expectError is true (line 159), meaning it expects failure not success. The name should reflect the actual behavior.

Apply this diff:

 {
-    name: "cleanup_job_get_error_continues_successfully",
+    name: "cleanup_job_get_error_returns_error",
     setupObjects: func() []client.Object {
controllers/mustgather/mustgather_controller.go (3)

291-295: Fix nil-pointer panic on CompletionTime.

Line 292 calls job.Status.CompletionTime.IsZero() but CompletionTime is a *metav1.Time pointer that will be nil when the job hasn't completed yet. This will cause a panic.

Apply this diff:

 func (r *MustGatherReconciler) updateStatus(ctx context.Context, instance *mustgatherv1alpha1.MustGather, job *batchv1.Job) (reconcile.Result, error) {
-    instance.Status.Completed = !job.Status.CompletionTime.IsZero()
+    instance.Status.Completed = job.Status.CompletionTime != nil && !job.Status.CompletionTime.IsZero()
 
     return r.ManageSuccess(ctx, instance)
 }

406-414: Use Error log level for non-NotFound job Get failures.

Line 408 logs non-NotFound errors (like API server failures) at Info level. These are actual errors that should be logged with Error level including the error details.

Apply this diff:

     if err != nil {
-        if !errors.IsNotFound(err) {
-            reqLogger.Info(fmt.Sprintf("failed to get %s job", instance.Name))
-            return err
-        }
-        reqLogger.Info(fmt.Sprintf("job %s not found", instance.Name))
+        if errors.IsNotFound(err) {
+            reqLogger.Info(fmt.Sprintf("job %s not found", instance.Name))
+            reqLogger.V(4).Info("successfully cleaned up mustgather resources")
+            return nil
+        }
+        reqLogger.Error(err, fmt.Sprintf("failed to get %s job", instance.Name))
+        return err
-        reqLogger.V(4).Info("successfully cleaned up mustgather resources")
-        return nil
     }

127-135: Consider always cleaning up secrets in finalizer to prevent credential leaks.

When RetainResourcesOnCompletion=true and the CR is deleted, cleanup is skipped (line 128). The Job and Pods may be garbage-collected via ownerRefs, but the copied Secret in the operator namespace (created at lines 194-216) typically has no ownerRef and will be orphaned, creating a potential credential leak.

Options to consider:

  1. Always invoke cleanup in the finalizer regardless of the flag (the flag controls retention during normal completion while CR exists, not during CR deletion)
  2. Add an OwnerReference from the copied Secret to the MustGather CR so it's GC'd automatically

Minimal fix—always clean up on CR deletion:

-        // Clean up resources if RetainResourcesOnCompletion is false (default behavior)
-        if !instance.Spec.RetainResourcesOnCompletion {
-            reqLogger.V(4).Info("running finalization logic for mustGatherFinalizer")
-            err := r.cleanupMustGatherResources(ctx, reqLogger, instance, operatorNs)
-            if err != nil {
-                reqLogger.Error(err, "failed to cleanup MustGather resources during deletion")
-                return reconcile.Result{}, err
-            }
+        // Always clean up on CR deletion to prevent orphaning credentials
+        reqLogger.V(4).Info("running finalization logic for mustGatherFinalizer")
+        if err := r.cleanupMustGatherResources(ctx, reqLogger, instance, operatorNs); err != nil {
+            reqLogger.Error(err, "failed to cleanup MustGather resources during deletion")
+            return reconcile.Result{}, err
         }
🧹 Nitpick comments (1)
controllers/mustgather/mustgather_controller_test.go (1)

536-562: Add status assertion for job-active test case.

The test is named "reconcile_job_active_updates_status_running" but postTestChecks is empty (line 561). Without asserting the status was updated, the test doesn't verify what its name claims.

Apply this diff to add the assertion:

-            postTestChecks: func(t *testing.T, cl client.Client) {},
+            postTestChecks: func(t *testing.T, cl client.Client) {
+                out := &mustgatherv1alpha1.MustGather{}
+                if err := cl.Get(context.TODO(), types.NamespacedName{
+                    Name: "example-mustgather", Namespace: "ns",
+                }, out); err != nil {
+                    t.Fatalf("failed to get mustgather: %v", err)
+                }
+                if out.Status.Completed {
+                    t.Fatalf("expected Completed=false when job is active, got true")
+                }
+                // Verify status reflects running state if controller sets a specific status string
+            },
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

Cache: Disabled due to data retention organization setting

Knowledge base: Disabled due to Reviews -> Disable Knowledge Base setting

📥 Commits

Reviewing files that changed from the base of the PR and between 0e97d9a and 9df39a8.

📒 Files selected for processing (6)
  • api/v1alpha1/mustgather_types.go (1 hunks)
  • bundle/manifests/tech-preview/operator.openshift.io_mustgathers.yaml (1 hunks)
  • controllers/mustgather/mustgather_controller.go (8 hunks)
  • controllers/mustgather/mustgather_controller_test.go (7 hunks)
  • deploy/crds/operator.openshift.io_mustgathers.yaml (1 hunks)
  • examples/mustgather_retain_resources.yaml (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • bundle/manifests/tech-preview/operator.openshift.io_mustgathers.yaml
  • api/v1alpha1/mustgather_types.go
  • deploy/crds/operator.openshift.io_mustgathers.yaml
  • examples/mustgather_retain_resources.yaml

@openshift-ci

openshift-ci Bot commented Oct 24, 2025

Copy link
Copy Markdown
Contributor

@rausingh-rh: all tests passed!

Full PR test history. Your PR dashboard.

Details

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository. I understand the commands that are listed here.

@shivprakashmuley

Copy link
Copy Markdown
Contributor

/lgtm

@openshift-ci openshift-ci Bot added the lgtm Indicates that a PR is ready to be merged. label Oct 24, 2025
@shivprakashmuley

Copy link
Copy Markdown
Contributor

/verified bypass

@openshift-ci-robot openshift-ci-robot added the verified Signifies that the PR passed pre-merge verification criteria label Oct 24, 2025
@openshift-ci-robot

Copy link
Copy Markdown

@shivprakashmuley: The verified label has been added.

Details

In response to this:

/verified bypass

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the openshift-eng/jira-lifecycle-plugin repository.

@openshift-merge-bot
openshift-merge-bot Bot merged commit 5915b0a into openshift:master Oct 24, 2025
@openshift-cherrypick-robot

Copy link
Copy Markdown

@swghosh: new pull request created: #292

Details

In response to this:

/cherry-pick release-4.20

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository.

@swghosh

swghosh commented Oct 29, 2025

Copy link
Copy Markdown
Member

@coderabbitai What is the t.Setenv("OSDK_FORCE_RUN_MODE", "local") used for in the "reconcile_job_succeeded_cleanup_error_returns_error" unit test case of TestReconcile? Explain.

@coderabbitai

coderabbitai Bot commented Oct 29, 2025

Copy link
Copy Markdown

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Read the test file to find the specific test case
cat controllers/mustgather/mustgather_controller_test.go | grep -A 50 "reconcile_job_succeeded_cleanup_error_returns_error"

Length of output: 2155


🏁 Script executed:

#!/bin/bash
# Search for other uses of OSDK_FORCE_RUN_MODE in the codebase
rg -n "OSDK_FORCE_RUN_MODE" -C 3

Length of output: 4540


🏁 Script executed:

#!/bin/bash
# Look for the getOperatorNamespace function which likely uses this env var
ast-grep --pattern 'func getOperatorNamespace() string {
  $$$
}'

Length of output: 0


🏁 Script executed:

#!/bin/bash
# Search for getOperatorNamespace function
rg -n "func getOperatorNamespace" -A 15

Length of output: 0


🏁 Script executed:

#!/bin/bash
# Look at the k8sutil package to understand how OSDK_FORCE_RUN_MODE is used
cat pkg/k8sutil/k8sutil.go

Length of output: 1914


🏁 Script executed:

#!/bin/bash
# Check main.go to see how the environment variable is used
cat main.go | grep -A 20 "OSDK_FORCE_RUN_MODE"

Length of output: 454


@swghosh: The t.Setenv("OSDK_FORCE_RUN_MODE", "local") line forces the operator to run in local mode during the unit test.

Here's why this is necessary:

Problem: When the operator runs in a Kubernetes cluster (normal/production mode), the GetOperatorNamespace() function reads the operator's namespace from /var/run/secrets/kubernetes.io/serviceaccount/namespace — a file that's automatically mounted by Kubernetes into every pod. However, during unit tests, your code isn't running in an actual pod, so this file doesn't exist.

Solution: By setting OSDK_FORCE_RUN_MODE=local, the operator's GetOperatorNamespace() function (in pkg/k8sutil/k8sutil.go) detects it's in local mode via isRunModeLocal() and immediately returns ErrRunLocal instead of attempting to read the non-existent service account file. This allows the controller logic to handle the local environment gracefully.

In this specific test case ("reconcile_job_succeeded_cleanup_error_returns_error"):

  • The test is verifying that when a MustGather job succeeds but cleanup fails (due to an injected delete error), the reconciler properly returns an error
  • Setting local mode ensures the controller can operate in the test environment without trying to access Kubernetes service account mounts
  • The test can then focus on validating the cleanup error handling behavior

This is a common Operator SDK pattern that allows the same operator code to run both in-cluster and in local/test environments without modifications.

KeenonLee pushed a commit to KeenonLee/must-gather-operator that referenced this pull request Mar 27, 2026
MG-56: Flag based deletion of must-gather job and CR
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

approved Indicates a PR has been approved by an approver from all required OWNERS files. jira/valid-reference Indicates that this PR references a valid Jira ticket of any type. lgtm Indicates that a PR is ready to be merged. qe-approved Signifies that QE has signed off on this PR verified Signifies that the PR passed pre-merge verification criteria

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants