Repository navigation
MG-53: Added support for uploadTarget API - #284
openshift-merge-bot[bot] merged 2 commits into
Conversation
|
@shivprakashmuley: This pull request references MG-53 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.21.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. |
|
/assign @swghosh |
WalkthroughMustGatherSpec upload fields moved into an optional Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## master #284 +/- ##
==========================================
+ Coverage 36.38% 38.05% +1.67%
==========================================
Files 7 7
Lines 459 473 +14
==========================================
+ Hits 167 180 +13
Misses 289 289
- Partials 3 4 +1
🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Actionable comments posted: 5
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (3)
controllers/mustgather/template.go (1)
138-146: Secret leakage risk with ShareProcessNamespace + credentials in env.With ShareProcessNamespace=true, other containers can read /proc/$PID/environ and see username/password. Prefer mounting the Secret as a volume (file reads) or disable ShareProcessNamespace.
Also applies to: 181-261, 85-99
controllers/mustgather/template_test.go (1)
176-189: Fix Logf messages to print actual values.The “got” placeholders repeat the expected var. Use env.Value.
Apply this diff:
- if env.Value != tt.httpProxy { - t.Logf("expected httpproxy envar %v but got %v", tt.httpProxy, tt.httpProxy) + if env.Value != tt.httpProxy { + t.Logf("expected httpproxy envar %v but got %v", tt.httpProxy, env.Value) } - if env.Value != tt.httpsProxy { - t.Logf("expected httpsproxy envar %v but got %v", tt.httpsProxy, tt.httpsProxy) + if env.Value != tt.httpsProxy { + t.Logf("expected httpsproxy envar %v but got %v", tt.httpsProxy, env.Value) } - if env.Value != tt.noProxy { - t.Logf("expected noproxy envar %v but got %v", tt.noProxy, tt.noProxy) + if env.Value != tt.noProxy { + t.Logf("expected noproxy envar %v but got %v", tt.noProxy, env.Value) }api/v1alpha1/mustgather_types.go (1)
95-134: CRD requirestypeeven when upload is disabled.The CRD marks
uploadTarget.typeas required, but the spec makesuploadTargetoptional. Users cannot omittypewhenuploadTargetis absent, so resources without an upload config will be rejected. Droptypefrom therequiredlist or makeuploadTargetnon-optional.
🧹 Nitpick comments (5)
bundle/manifests/tech-preview/operator.openshift.io_mustgathers.yaml (1)
75-83: Kubebuilder default note in description is non-functional and misleading.The line “+kubebuilder:default:="{Name:default}"” inside description doesn’t set a default. Either:
- set an actual schema default, or
- clarify doc and rely on Kubernetes defaulting (empty ServiceAccountName → “default” SA).
controllers/mustgather/template.go (1)
41-41: Shell loop uses backticks incorrectly.“while
pgrep -a gather > /dev/null” executes the command output, not the test. Use “while pgrep -a gather >/dev/null; do …” form.Example:
count=0 until [ $count -gt 4 ]; do while pgrep -a gather >/dev/null; do echo "waiting for gathers to complete ..." sleep 120 count=0 done echo "no gather is running ($count / 4)" ((count++)) sleep 30 done /usr/local/bin/uploadapi/v1alpha1/mustgather_types.go (1)
58-64: Fix typo in SFTP spec comment.Likely meant “ID of the case,” not “is of the case.” Please correct the wording.
api/v1alpha1/zz_generated.deepcopy.go (2)
80-81: Avoid shallow copy of UploadTarget specs.
**out = **inis just a shallow copy—fine for the current shape but risky if nested fields become pointers/maps later. Use the deep-copy helper (e.g.(*in).DeepCopyInto(*out)) to future-proof.
149-152: Deep-copy nested SFTP struct.
Sftpis copied by value; if it grows pointer/map fields we’ll miss deep-copying. Callin.Sftp.DeepCopyInto(&out.Sftp)for consistency with other deep-copy code-gen.
📜 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.deepcopy.go(3 hunks)bundle/manifests/tech-preview/operator.openshift.io_mustgathers.yaml(2 hunks)bundle/manifests/tech-preview/support-log-gather-operator.clusterserviceversion.yaml(1 hunks)controllers/mustgather/mustgather_controller.go(3 hunks)controllers/mustgather/mustgather_controller_test.go(4 hunks)controllers/mustgather/template.go(1 hunks)controllers/mustgather/template_test.go(3 hunks)deploy/crds/operator.openshift.io_mustgathers.yaml(2 hunks)
🔇 Additional comments (3)
bundle/manifests/tech-preview/support-log-gather-operator.clusterserviceversion.yaml (1)
164-168: RBAC apiGroup fix LGTM.Switching mustgathers/finalizers to operator.openshift.io matches the CRD group.
controllers/mustgather/mustgather_controller_test.go (1)
68-136: Controller tests for UploadTarget LGTM.Good coverage for with/without UploadTarget; OPERATOR_IMAGE is set; job lookup assertion is clear.
Consider adding a negative case (type=SFTP but missing sftp fields) to assert the controller/template skips adding the upload container after the guard is implemented.
controllers/mustgather/template_test.go (1)
236-250: Proxy fallback tests are solid.Scenarios cover CR-only NoProxy, CR http/https, and CR https-only. Aligns with template logic.
Also applies to: 278-294, 322-337
| caseID: | ||
| description: The is of the case this must gather will be uploaded | ||
| to | ||
| type: string | ||
| caseManagementAccountSecretRef: | ||
| description: the secret container a username and password | ||
| field to be used to authenticate with red hat case management | ||
| systems |
There was a problem hiding this comment.
Fix typos in descriptions.
- “The is of the case…” → “The ID of the case…”
- “the secret container a username and password field” → “the Secret containing a username and password field”
Also applies to: 119-124
| sftp: | ||
| description: SFTPSpec defines the desired state of SFTPSpec | ||
| properties: | ||
| caseID: | ||
| description: The is of the case this must gather will be uploaded | ||
| to | ||
| type: string | ||
| caseManagementAccountSecretRef: | ||
| description: the secret container a username and password | ||
| field to be used to authenticate with red hat case management | ||
| systems | ||
| properties: | ||
| name: | ||
| default: "" | ||
| description: |- | ||
| Name of the referent. | ||
| This field is effectively required, but due to backwards compatibility is | ||
| allowed to be empty. Instances of this type with an empty value here are | ||
| almost certainly wrong. | ||
| More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names | ||
| type: string | ||
| type: object | ||
| x-kubernetes-map-type: atomic | ||
| internalUser: | ||
| default: true | ||
| description: |- | ||
| A flag to specify if the upload user provided in the caseManagementAccountSecret is a RH internal user. | ||
| See documentation for further information. | ||
| type: boolean | ||
| required: | ||
| - caseID | ||
| - caseManagementAccountSecretRef | ||
| type: object | ||
| type: | ||
| enum: | ||
| - SFTP | ||
| type: string | ||
| required: | ||
| - type | ||
| type: object |
There was a problem hiding this comment.
CRD schema contradicts optional UploadTarget.
CRD enforces uploadTarget.type, yet API marks uploadTarget optional. Objects without uploads will fail validation. Remove type (and nested caseID/caseManagementAccountSecretRef) from the required list or require uploadTarget in the API.
|
/assign @swghosh |
| Type string `json:"type"` | ||
|
|
||
| // +kubebuilder:validation:Optional | ||
| Sftp SFTPSpec `json:"sftp,omitempty"` |
There was a problem hiding this comment.
| Sftp SFTPSpec `json:"sftp,omitempty"` | |
| SFTP SFTPSpec `json:"sftp,omitempty"` |
this needs to be CamelCase.
and
per se spec in EP:
| Sftp SFTPSpec `json:"sftp,omitempty"` | |
| // sftp defines the target details for uploading to a valid SFTP server. | |
| // +unionMember | |
| // +optional | |
| SFTP *SFTPUploadTargetConfig `json:"sftp,omitempty"` |
| type UploadTargetSpec struct { | ||
| // +kubebuilder:validation:Enum=SFTP | ||
| // +kubebuilder:validation:Required | ||
| Type string `json:"type"` |
There was a problem hiding this comment.
this needs a unionDiscriminator and // +required too.
There was a problem hiding this comment.
Please add a new type UploadType and we also need to add const UploadTypeSFTP, a good example to refer would be https://github.com/openshift/api/blob/5d856d3e835453391cc5491910e089d2cfbb4752/config/v1/types_node.go#L77-L85.
| err = r.GetClient().Create(context.TODO(), newSecret) | ||
| if err != nil { | ||
| log.Error(err, fmt.Sprintf("Error creating new secret %s", secretName)) | ||
| // create secret in the operator namespace |
There was a problem hiding this comment.
| // create secret in the operator namespace | |
| // copy secret to the operator namespace |
| Namespace: operatorNs, | ||
| Name: secretName, | ||
| }, newSecret) | ||
| if err != nil { |
There was a problem hiding this comment.
can be branched together?
if err != nil && errors.IsNotFound(err)
| err = r.GetClient().Create(context.TODO(), newSecret) | ||
| if err != nil { | ||
| log.Error(err, fmt.Sprintf("Error creating new secret %s", secretName)) | ||
| return reconcile.Result{}, err |
There was a problem hiding this comment.
we need to Requeue if the secret wasn't able to be created.
return reconcile.Result{Requeue: true}
| if !contains(instance.GetFinalizers(), mustGatherFinalizer) { | ||
| if err := r.addFinalizer(reqLogger, instance); err != nil { | ||
| return reconcile.Result{}, err | ||
| if instance.Spec.UploadTarget != nil && instance.Spec.UploadTarget.SFTP != nil && instance.Spec.UploadTarget.SFTP.CaseManagementAccountSecretRef.Name != "" { |
There was a problem hiding this comment.
why is having/adding a finalizer for cleanup related to the sftp secret?
There was a problem hiding this comment.
do we want to remove or keep the copied secret in case of CR deletion?
There was a problem hiding this comment.
in case of copied secret, during CR deletion the secret will need to be deleted.
Parent -> Child dependency.
There was a problem hiding this comment.
https://issues.redhat.com/browse/MG-107 is already taking care of this case. Will remove it from this PR.
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
build/bin/upload (1)
62-66: Add validation for the host variable.The script validates
caseid,username, andpasswordat lines 62-66, but doesn't check ifhostis set. Since the SFTP commands at lines 84 and 89 now use${host}, an empty host will cause connection failures.Apply this diff to add host validation:
-if [ -z "${caseid}" ] || [ -z "${username}" ] || [ -z "${password}" ]; +if [ -z "${caseid}" ] || [ -z "${username}" ] || [ -z "${password}" ] || [ -z "${host}" ]; then echo "Error: Required Parameters have not been provided. Exiting..." exit 1 fi
♻️ Duplicate comments (1)
bundle/manifests/tech-preview/operator.openshift.io_mustgathers.yaml (1)
103-105: Minor: Typo in description.Line 103 contains a typo: "the secret container a username" should be "the secret containing a username".
Apply this diff:
- description: the secret container a username and password + description: the secret containing a username and password field to be used to authenticate with red hat case management systems
🧹 Nitpick comments (1)
controllers/mustgather/mustgather_controller_test.go (1)
155-169: Consider adding negative test cases for invalid UploadTarget.The test covers valid scenarios, but doesn't validate the guards in
template.goline 89. Consider adding test cases for:
- Empty
CaseID- Empty
CaseManagementAccountSecretRef.NameType == SFTPbutSFTPis nilThese would verify that the upload container is correctly skipped for invalid configurations.
📜 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 (7)
api/v1alpha1/mustgather_types.go(2 hunks)build/bin/upload(1 hunks)bundle/manifests/tech-preview/operator.openshift.io_mustgathers.yaml(2 hunks)controllers/mustgather/mustgather_controller_test.go(4 hunks)controllers/mustgather/template.go(4 hunks)controllers/mustgather/template_test.go(9 hunks)deploy/crds/operator.openshift.io_mustgathers.yaml(2 hunks)
🔇 Additional comments (9)
controllers/mustgather/template.go (1)
86-104: LGTM! Conditional upload container injection is well-guarded.The upload container is now properly guarded with multiple checks:
- Verifies
UploadTargetis non-nil- Checks
Type == UploadTypeSFTP- Validates
SFTPis non-nil- Ensures
CaseIDandCaseManagementAccountSecretRef.Nameare non-emptyThis prevents creating invalid Jobs with empty Secret references.
Based on learnings
controllers/mustgather/mustgather_controller_test.go (1)
68-136: Good test coverage for UploadTarget scenarios.The test validates:
- Container count differs based on UploadTarget presence (2 vs 1)
- Upload container is present/absent as expected
- Both scenarios (with and without UploadTarget) are covered
controllers/mustgather/template_test.go (2)
99-210: LGTM! Host field is properly tested.The test cases correctly validate:
- Host environment variable is set to the expected value (lines 173-177)
- Host parameter is passed to
getUploadContainer(line 159)- Test covers both scenarios with and without host value
233-273: Proxy fallback tests properly updated for nested UploadTarget.All three proxy-related test cases correctly use the nested
UploadTargetstructure withSFTPconfiguration, ensuring proxy behavior is tested with the new API shape.api/v1alpha1/mustgather_types.go (3)
50-54: LGTM! UploadTarget field properly documented and marked optional.The field is appropriately marked as optional, allowing MustGather resources without upload functionality.
56-78: LGTM! SFTPSpec validation is comprehensive.The CEL validations at lines 57-58 ensure:
caseIDis non-emptycaseManagementAccountSecretRef.nameis non-emptyThe
Hostfield has a sensible default (sftp.access.redhat.com), andInternalUserdefaults totrue.
88-103: LGTM! Union discriminator pattern correctly implemented.The CEL validation at line 89 enforces:
sftpis required whentype == 'SFTP'sftpis forbidden otherwiseThis follows OpenShift API conventions and prevents invalid configurations.
Based on learnings
deploy/crds/operator.openshift.io_mustgathers.yaml (1)
90-152: LGTM! CRD schema correctly implements the union pattern.The schema properly enforces:
uploadTarget.typeis required (line 146)sftpis required whentype == 'SFTP'and forbidden otherwise (lines 148-152)- Nested validations ensure
caseIDandcaseManagementAccountSecretRef.nameare non-empty (lines 134-138)- Host field has a sensible default (line 119)
This prevents invalid configurations and aligns with OpenShift API conventions.
Based on learnings
bundle/manifests/tech-preview/operator.openshift.io_mustgathers.yaml (1)
90-152: LGTM! Tech-preview CRD is consistent with the main CRD.The schema matches
deploy/crds/operator.openshift.io_mustgathers.yamlwith the same union validation pattern, defaults, and CEL rules.
| { | ||
| Name: uploadEnvHost, | ||
| Value: host, | ||
| }, |
There was a problem hiding this comment.
🧩 Analysis chain
Host field is passed without validation.
The host value from UploadTarget.SFTP.Host is added to the environment without checking if it's empty. While the CRD defines a default value (sftp.access.redhat.com), if the default isn't applied or is overridden with an empty string, the upload will fail.
Verify that the CRD default is always applied and cannot be overridden with an empty value:
🏁 Script executed:
#!/bin/bash
# Check if Host field has proper defaults and validation in the CRD
rg -A 5 -B 2 'host:' deploy/crds/operator.openshift.io_mustgathers.yaml bundle/manifests/tech-preview/operator.openshift.io_mustgathers.yamlLength of output: 1718
I need to check for validation constraints in the CRD and verify the code-level handling. Let me gather more information:Now let me search for more specific information about whether explicit empty string values can override CRD defaults:
Let me check the actual code and verify if there's any validation at the code level:
Based on my verification of the CRD configuration and analysis of Kubernetes defaults behavior:
Host field can be set to empty string, bypassing the CRD default value.
The Go type system allows empty strings to pass required field checks, as OpenAPI schema validation only checks for the non-null presence of the field in the request payload. While the CRD specifies default: sftp.access.redhat.com, this default applies only when the host field is omitted entirely. A user can explicitly set host: "" in the custom resource, which will override the default and pass CRD validation since no minLength or validation constraints prevent empty strings.
At the code level in controllers/mustgather/template.go (lines 241-244), the host value is added to the environment without checking if it's empty, which would result in a malformed upload configuration if an empty host reaches that code path.
Recommendation: Add validation in the Go code to check that host is not empty before using it, or add a minLength: 1 constraint to the CRD schema to prevent empty values at the API server level.
🤖 Prompt for AI Agents
In controllers/mustgather/template.go around lines 241 to 244, the code
unconditionally adds host as an environment variable which allows an explicit
empty string from the CR to override the CRD default and produce a malformed
upload config; update the code to validate that host is non-empty before adding
it (e.g., skip adding the env var and return/emit an error if host == ""), or
normalize it by substituting the intended default when empty; alternatively add
a CRD schema validation (minLength: 1) to prevent empty host values at the API
level.
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
build/bin/upload (1)
3-9: Update documentation to include the newhostvariable.The documentation at the top of the file should list all expected environment variables, including the newly introduced
hostvariable.Apply this diff:
# this shell is responsible for compressing the must gather files and uploading to the case management system # it can count on the following variables to be set # username: the user name for redhat case management system # password: the password for redhat case management system # caseid: the case id to upload to +# host: (optional) the SFTP host to upload to (defaults to sftp.access.redhat.com) # must_gather_output: the directory in which the must gather agents have collected the information # must_gather_upload: a workspace directory that can be used as stage to zip and upload the must gather compressed file
📜 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 (1)
build/bin/upload(1 hunks)
|
/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. |
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (1)
controllers/mustgather/mustgather_controller.go (1)
220-223: CR gets stuck when secret not found (tracked in MG-114).When the referenced secret doesn't exist, the code returns without requeueing, leaving the MustGather CR stuck. This prevents the job from being created even though it might be able to proceed without the secret.
Per past review comments, this is being tracked in https://issues.redhat.com/browse/MG-114.
📜 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 (2)
bundle/manifests/tech-preview/support-log-gather-operator.clusterserviceversion.yaml(1 hunks)controllers/mustgather/mustgather_controller.go(3 hunks)
🔇 Additional comments (2)
bundle/manifests/tech-preview/support-log-gather-operator.clusterserviceversion.yaml (1)
164-164: LGTM: API group update aligns with CRD migration.The update from
managed.openshift.iotooperator.openshift.iocorrectly reflects the API group migration for the MustGather CRD.controllers/mustgather/mustgather_controller.go (1)
126-142: LGTM: Finalization logic correctly handles secret cleanup.The finalization logic appropriately:
- Guards secret deletion with the nested
UploadTarget.SFTP.CaseManagementAccountSecretRef.Namecheck- Logs but continues when the secret Get fails (secret may already be deleted)
- Returns an error only when the Delete operation fails
| } else if err != nil { | ||
| log.Error(err, fmt.Sprintf("Error getting new secret %s", secretName)) | ||
| return reconcile.Result{}, err | ||
| } |
There was a problem hiding this comment.
Inconsistent error handling: should requeue on Get error.
When checking if the secret already exists in the operator namespace fails (line 230), the code returns without requeueing (line 246). This is inconsistent with the earlier error handling at line 225, which requeues on Get errors.
Apply this diff to ensure consistent error handling:
} else if err != nil {
log.Error(err, fmt.Sprintf("Error getting new secret %s", secretName))
- return reconcile.Result{}, err
+ return reconcile.Result{Requeue: true}, err
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| } else if err != nil { | |
| log.Error(err, fmt.Sprintf("Error getting new secret %s", secretName)) | |
| return reconcile.Result{}, err | |
| } | |
| } else if err != nil { | |
| log.Error(err, fmt.Sprintf("Error getting new secret %s", secretName)) | |
| return reconcile.Result{Requeue: true}, err | |
| } |
🤖 Prompt for AI Agents
In controllers/mustgather/mustgather_controller.go around lines 244 to 247, the
error branch that handles failures when getting the secret currently returns
without requeueing; change the error return to requeue like the earlier Get
error path. Replace the current return reconcile.Result{}, err with return
reconcile.Result{Requeue: true}, err so the controller retries on transient Get
errors and maintains consistent error handling.
|
/lgtm |
|
Give me some time to test it, I will add a label tonight |
cdd4318 to
4e432a6
Compare
|
/approve /override ci/prow/validate-boilerplate |
|
[APPROVALNOTIFIER] This PR is APPROVED This pull-request has been approved by: shivprakashmuley, swghosh The full list of commands accepted by this bot can be found here. The pull request process is described here DetailsNeeds approval from an approver in each of these files:
Approvers can indicate their approval by writing |
|
@swghosh: Overrode contexts on behalf of swghosh: ci/prow/validate-boilerplate 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. |
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
controllers/mustgather/mustgather_controller.go (1)
235-243: Fix misleading "already exists" log and add owner reference for GC.
- The "already exists" log prints even after creation. Move it to the else branch.
- Add OwnerReferences to the copied Secret so GC cleans it up if the CR is deleted, reducing reliance on the finalizer path and avoiding leaked credentials.
@@ - if errors.IsNotFound(err) { - newSecret.Name = secretName - newSecret.Namespace = operatorNs - newSecret.Data = userSecret.Data - newSecret.Type = userSecret.Type + if errors.IsNotFound(err) { + newSecret.Name = secretName + newSecret.Namespace = operatorNs + newSecret.Data = userSecret.Data + newSecret.Type = userSecret.Type + // ensure GC on CR deletion + controller := true + block := true + newSecret.OwnerReferences = []metav1.OwnerReference{{ + APIVersion: instance.APIVersion, + Kind: instance.Kind, + Name: instance.Name, + UID: instance.UID, + Controller: &controller, + BlockOwnerDeletion: &block, + }} err = r.GetClient().Create(context.TODO(), newSecret) if err != nil { log.Error(err, fmt.Sprintf("Error creating new secret %s", secretName)) return reconcile.Result{Requeue: true}, err } - } else if err != nil { + } else if err != nil { log.Error(err, fmt.Sprintf("Error getting new secret %s", secretName)) - return reconcile.Result{}, err - } - log.Info(fmt.Sprintf("Secret %s already exists in the %s namespace", secretName, operatorNs)) + return reconcile.Result{Requeue: true}, err + } else { + log.Info(fmt.Sprintf("Secret %s already exists in the %s namespace", secretName, operatorNs)) + }Add import:
@@ - "reflect" + "reflect" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"Optionally, prefer controllerutil.SetControllerReference(instance, newSecret, scheme) if scheme access is available.
Also applies to: 248-249
♻️ Duplicate comments (6)
build/bin/upload (1)
19-19: Critical security issue remains unaddressed: host validation required.The previous review identified that allowing
hostto be set without validation creates a critical data exfiltration risk. This concern has not been addressed in the current changes.bundle/manifests/tech-preview/operator.openshift.io_mustgathers.yaml (3)
121-123: Remove redundant description text.Same redundancy as in deploy/crds file. Lines 121–123 repeat the meaning twice.
90-152:⚠️ DUPLICATE: Same critical validation contradiction as in deploy/crds file.This file is a parallel CRD manifest with the identical schema structure and the same unresolved validation issue. The same fixes recommended for
deploy/crds/operator.openshift.io_mustgathers.yamlapply here.
103-105: Fix grammar in caseManagementAccountSecretRef description.Same typo as in deploy/crds file. Line 103–105: "the secret container a username and password field" should be "the Secret containing a username and password field".
controllers/mustgather/mustgather_controller.go (2)
220-226: Avoid CR getting stuck when source Secret is missing; requeue instead of returning nil.On NotFound, reconcile returns without requeue, so if the Secret is created later the CR won’t progress. Requeue (optionally after a short backoff) and/or set a status condition.
Apply:
@@ - if err != nil { - if errors.IsNotFound(err) { - log.Error(err, fmt.Sprintf("the secret %s was not found in namespace %s", secretName, instance.Namespace)) - return reconcile.Result{}, nil - } + if err != nil { + if errors.IsNotFound(err) { + log.Info(fmt.Sprintf("secret %s not found in namespace %s; requeueing", secretName, instance.Namespace)) + return reconcile.Result{Requeue: true}, nil + } log.Error(err, fmt.Sprintf("Error getting secret (%s)", secretName)) return reconcile.Result{Requeue: true}, err }
244-247: Make operator-namespace Secret Get errors requeue (consistent with earlier Get).Transient API errors should requeue; current path returns without it.
- log.Error(err, fmt.Sprintf("Error getting new secret %s", secretName)) - return reconcile.Result{}, err + log.Error(err, fmt.Sprintf("Error getting new secret %s", secretName)) + return reconcile.Result{Requeue: true}, err
🧹 Nitpick comments (7)
deploy/crds/operator.openshift.io_mustgathers.yaml (1)
121-123: Remove redundant description text.Lines 121–123 repeat the same information twice: "host specifies the SFTP server hostname." and "The host name of the SFTP server" convey the same meaning.
host: default: sftp.access.redhat.com description: |- - host specifies the SFTP server hostname. - The host name of the SFTP server + The SFTP server hostname type: stringcontrollers/mustgather/mustgather_controller.go (2)
126-141: Tighten finalizer cleanup logs for missing Secret.When the Secret isn’t found during deletion, log at Info/Debug instead of Error to avoid noise; deletion should proceed.
- if err != nil { - reqLogger.Error(err, fmt.Sprintf("Failed to get %s secret", tmpSecretName)) + if err != nil { + if errors.IsNotFound(err) { + reqLogger.Info(fmt.Sprintf("Secret %s already absent in %s", tmpSecretName, operatorNs)) + } else { + reqLogger.Error(err, fmt.Sprintf("Failed to get %s secret", tmpSecretName)) + }
203-211: Minor: prefer ctx over context.TODO() and reduce duplicate Get calls.Use the passed ctx for client calls and consider CreateOrUpdate for the Secret to simplify copy logic.
Also applies to: 251-260
controllers/mustgather/mustgather_controller_test.go (3)
68-136: Strengthen test by asserting Job creation and exercising the copy path.Currently validates container count via getJobFromInstance only. Also call Reconcile twice (init then create) and assert Job exists in the fake client; create MustGather in a non-operator namespace and place the source Secret there to cover the copy.
Example sketch:
@@ - t.Setenv("OPERATOR_IMAGE", "test-image") - secObj := createMustGatherSecretObject() - objs := []runtime.Object{tt.mustGather, secObj} + t.Setenv("OPERATOR_IMAGE", "test-image") + // put source secret in user ns to exercise copy + userSec := createMustGatherSecretObject() + userSec.Namespace = tt.mustGather.Namespace + objs := []runtime.Object{tt.mustGather, userSec} @@ - _, err := r.Reconcile(context.TODO(), req) + // 1st reconcile initializes + _, err := r.Reconcile(context.TODO(), req) + if err != nil { t.Fatalf("reconcile init: %v", err) } + // 2nd reconcile creates Job and copies Secret + _, err = r.Reconcile(context.TODO(), req) @@ + // Assert Job created + job := &batchv1.Job{} + if err := cl.Get(context.TODO(), types.NamespacedName{Namespace: "must-gather-operator", Name: tt.mustGather.Name}, job); err != nil { + t.Fatalf("expected job to be created: %v", err) + }
148-152: Avoid early-return path in Reconcile by defaulting SA name in tests.An empty ServiceAccountRef.Name triggers initialization update and returns; set a non-empty name to reach job creation.
- ServiceAccountRef: corev1.LocalObjectReference{ - Name: "", - }, + ServiceAccountRef: corev1.LocalObjectReference{ + Name: "default", + },
155-169: Improve test coverage by using distinct namespaces for Secret copy verification.The controller copies the
CaseManagementAccountSecretReffrom the user's namespace (instance.Namespace) to the operator namespace (operatorNs). Currently, both the MustGather object and Secret are created in the same namespace ("must-gather-operator"), which doesn't exercise this cross-namespace copy path. Setmg.Namespace = "user-ns"and create the source Secret there, while keeping the operator namespace as "must-gather-operator", to ensure the Secret copy logic in the reconciler is properly tested.controllers/mustgather/template_test.go (1)
173-177: Add a negative assertion when host is omitted.For cases without host, assert uploadEnvHost is absent to lock intended behavior.
if tt.host == "" { for _, env := range container.Env { if env.Name == uploadEnvHost { t.Fatalf("%s should be omitted when host is empty", uploadEnvHost) } } }
📜 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 (10)
api/v1alpha1/mustgather_types.go(2 hunks)api/v1alpha1/zz_generated.deepcopy.go(3 hunks)build/bin/upload(1 hunks)bundle/manifests/tech-preview/operator.openshift.io_mustgathers.yaml(2 hunks)bundle/manifests/tech-preview/support-log-gather-operator.clusterserviceversion.yaml(1 hunks)controllers/mustgather/mustgather_controller.go(3 hunks)controllers/mustgather/mustgather_controller_test.go(4 hunks)controllers/mustgather/template.go(4 hunks)controllers/mustgather/template_test.go(9 hunks)deploy/crds/operator.openshift.io_mustgathers.yaml(2 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
- bundle/manifests/tech-preview/support-log-gather-operator.clusterserviceversion.yaml
- api/v1alpha1/mustgather_types.go
- controllers/mustgather/template.go
🔇 Additional comments (13)
build/bin/upload (9)
126-142: Approve finalization logic with UploadTarget.The finalization path correctly:
- Guards access with nil checks for UploadTarget, SFTP, and Name
- Logs Get failures without blocking finalization
- Returns errors only on Delete failures
This is appropriate behavior for cleanup during deletion.
212-226: Approve NotFound handling for missing user secret.Treating a missing user-provided secret (NotFound error) as a non-recoverable condition is appropriate—requeueing would not help if the user hasn't created the secret. The log message clearly indicates the issue, and returning without error prevents unnecessary reconciliation loops.
17-17: LGTM: Correct deep copy for MustGatherSpec.The change from direct assignment to
in.Spec.DeepCopyInto(&out.Spec)correctly implements deep copying for the Spec field, which now contains pointer fields (UploadTarget) that require proper deep copying.
77-81: LGTM: UploadTarget deep copy logic.The conditional deep copy of UploadTarget correctly:
- Checks for nil before copying
- Allocates a new UploadTargetSpec
- Recursively deep copies via DeepCopyInto
132-166: LGTM: Generated deep copy methods for new types.The deep copy implementations for SFTPSpec and UploadTargetSpec are correct:
- SFTPSpec properly copies all fields including CaseManagementAccountSecretRef
- UploadTargetSpec correctly handles the optional SFTP pointer with nil checking
68-136: LGTM: Comprehensive test for UploadTarget behavior.The test correctly validates:
- Container count differs based on UploadTarget presence (2 with, 1 without)
- Upload container is present only when UploadTarget is configured
- Proper reconciliation flow for both scenarios
155-169: LGTM: Test data aligns with new API structure.The helper correctly constructs a MustGather with the new UploadTargetSpec, including:
- Type set to UploadTypeSFTP
- SFTP spec with CaseID, SecretRef, InternalUser, and Host
- Proper nesting under UploadTarget
99-210: LGTM: Test updated for host parameter.The test correctly:
- Adds host field to test cases
- Passes host to getUploadContainer
- Validates uploadEnvHost environment variable is set correctly
- Maintains comprehensive coverage for all upload container fields
243-273: LGTM: Test data migrated to UploadTarget structure.The test correctly constructs MustGather objects with:
- ServiceAccountRef at top level
- UploadTarget with Type = UploadTypeSFTP
- Nested SFTP spec with CaseID and SecretRef
- Validates proxy fallback behavior with new structure
deploy/crds/operator.openshift.io_mustgathers.yaml (1)
90-152: Fix grammar error and remove redundant description; validation logic is correct.Two minor issues identified:
Line 103 — Grammar error: "the secret container a username and password field" should be "the Secret containing a username and password field".
Lines 121–122 — Redundant description: "host specifies the SFTP server hostname. The host name of the SFTP server" repeats the same meaning twice. Simplify to a single clear statement.
The CEL validation logic at lines 151–152 is correct and does not have a contradiction. When
uploadTargetis absent (nil), Kubernetes does not evaluate the CEL rule scoped to that field—this is the expected behavior for optional fields. The controller properly guards access with a nil check, and the pattern matches standard OpenShift union discriminator conventions (+union, +unionDiscriminator markers).Likely an incorrect or invalid review comment.
api/v1alpha1/zz_generated.deepcopy.go (2)
17-19: Deep-copy updates align with new UploadTarget API.Switching to Spec.DeepCopyInto and handling optional UploadTarget is correct.
Also applies to: 77-81
132-166: Verify generated DeepCopy functions are in sync with schema using controller-gen locally.The DeepCopy implementations for
SFTPSpecandUploadTargetSpecappear structurally correct:SFTPSpecuses shallow copy (value types only), whileUploadTargetSpecproperly allocates and deep-copies the nested*SFTPSpecpointer. However, thecontroller-gentool is not available in this environment to verify the generated code matches the current schema.Please run the code generation locally to ensure the output is in sync:
controller-gen object:headerFile="hack/boilerplate.go.txt" paths="./api/..." git diff -- api/v1alpha1/zz_generated.deepcopy.goConfirm no unexpected changes are introduced.
controllers/mustgather/template_test.go (1)
246-257: CR construction updates look good.ServiceAccountRef at top-level and UploadTarget.SFTP nesting align with API changes; proxy fallback tests remain valid.
Also applies to: 294-301, 337-344
| description: the secret container a username and password | ||
| field to be used to authenticate with red hat case management | ||
| systems |
There was a problem hiding this comment.
Fix grammar in caseManagementAccountSecretRef description.
Line 103–105 has a grammatical error: "the secret container a username and password field" should be "the Secret containing a username and password field".
caseManagementAccountSecretRef:
- description: the secret container a username and password
- field to be used to authenticate with red hat case management
+ description: the Secret containing a username and password
+ field to be used to authenticate with Red Hat case managementCommittable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In deploy/crds/operator.openshift.io_mustgathers.yaml around lines 103 to 105,
the description for caseManagementAccountSecretRef has a grammar mistake ("the
secret container a username and password field"); update the text to "the Secret
containing a username and password field" (capitalize Secret per Kubernetes
convention if desired) so the sentence reads correctly and clearly describes
that the referenced Secret includes username and password fields for
authenticating with Red Hat case management systems.
|
@shivprakashmuley: 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. |
KeenonLee
left a comment
There was a problem hiding this comment.
/label qe-approved
/verified bypass
|
@shivprakashmuley: This pull request references MG-53 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.21.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. |
|
/verified bypass |
|
@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. |
|
@swghosh: new pull request created: #291 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. |
MG-53: Added support for uploadTarget API
This PR addresses https://issues.redhat.com/browse/MG-53.
Enhancement proposal for the change is discussed here openshift/enhancements#1831.