Repository navigation
MG-56: Flag based deletion of must-gather job and CR - #259
Conversation
|
@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. DetailsIn response to this:
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 Report❌ Patch coverage is
Additional details and impacted files@@ 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
🚀 New features to boost your workflow:
|
f1ea410 to
c461945
Compare
87a1e86 to
d53fdc0
Compare
|
/test test |
|
@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. DetailsIn response to this:
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. |
7e83bfe to
a964044
Compare
b1080ee to
6b2c03f
Compare
|
@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. DetailsIn response to this:
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. |
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (7)
deploy/crds/managed.openshift.io_mustgathers.yaml (2)
99-104: *Bool vs bool for API forward‑compatibilityUsing 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 accordinglyThe 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_IMAGEThis 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 secretPlease 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 pointerThis 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 variableAll 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 leakSkipping 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 controllerThe “+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 panicIf 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 isolationPrefer 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 expectationThe 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 errorsNon‑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 misleadingThis 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 fieldsMinor 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‑depthIf 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
📒 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 strictMany 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 testThe 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.
There was a problem hiding this comment.
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.RetainResourcesOnCompletioncontrollers/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
📒 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
|
/cherry-pick release-4.20 |
|
@swghosh: once the present PR merges, I will cherry-pick it on top of DetailsIn response to this:
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. |
|
only rebase |
|
@KeenonLee: The DetailsIn response to this:
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. |
There was a problem hiding this comment.
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.Timepointer 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=trueand 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:
- Always invoke cleanup in the finalizer regardless of the flag (the flag controls retention during normal completion while CR exists, not during CR deletion)
- 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
📒 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
|
@rausingh-rh: all tests passed! Full PR test history. Your PR dashboard. DetailsInstructions 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. |
|
/lgtm |
|
/verified bypass |
|
@shivprakashmuley: The DetailsIn response to this:
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. |
|
@swghosh: new pull request created: #292 DetailsIn response to this:
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. |
|
@coderabbitai What is the |
|
Tip For best results, initiate chat on the files or code changes. 🧩 Analysis chain🏁 Script executed: Length of output: 2155 🏁 Script executed: Length of output: 4540 🏁 Script executed: Length of output: 0 🏁 Script executed: Length of output: 0 🏁 Script executed: Length of output: 1914 🏁 Script executed: Length of output: 454 @swghosh: The Here's why this is necessary: Problem: When the operator runs in a Kubernetes cluster (normal/production mode), the Solution: By setting In this specific test case ("reconcile_job_succeeded_cleanup_error_returns_error"):
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. |
MG-56: Flag based deletion of must-gather job and CR
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.
retainResourcesOnCompletionfield should be set to true in the spec for the resources to be retained. Default behavior will be to delete all the resources.retainResourcesOnCompletionfield.