Skip to content

refactor: Optimize FleetMode checks and improve code clarity#239

Open
TheUndeadKing wants to merge 1 commit intoopenshift:masterfrom
TheUndeadKing:code-review
Open

refactor: Optimize FleetMode checks and improve code clarity#239
TheUndeadKing wants to merge 1 commit intoopenshift:masterfrom
TheUndeadKing:code-review

Conversation

@TheUndeadKing
Copy link
Copy Markdown
Contributor

@TheUndeadKing TheUndeadKing commented Apr 14, 2026

What type of PR is this?

(bug/feature/cleanup/documentation/test/refactor)

What this PR does / why we need it?

Minor optimizations and code clarity improvements in OCM Agent handler.

  1. Skip cluster version fetch in FleetMode (ocmagenthandler_configmap.go)
  • Fleet mode doesn't use cluster ID, so skip the cluster version API call
  • Reduces unnecessary API calls in fleet mode scenarios
  1. Extract namespace logic to helper function (ocmagenthandler_networkpolicy.go)
  • Removed code duplication by extracting getNetworkPolicyNamespaces()
  • Improves maintainability
  1. Clarify mutually exclusive conditions (ocmagenthandler_deployment.go)
  • Changed two separate if statements to if-else
  • Makes it explicit that FleetMode and non-FleetMode are mutually exclusive

Which Jira/Github issue(s) this PR fixes?

Fixes # N/A

Special notes for your reviewer:

Pre-checks (if applicable):

  • Tested latest changes against a cluster
  • Ran make generate command locally to validate code changes
  • Included documentation changes with PR

Summary by CodeRabbit

  • Improvements
    • Optimized cluster detection and config behavior when FleetMode is enabled vs disabled
    • Refined agent startup flag selection to ensure mutually exclusive mode flags
    • Unified network-policy namespace selection for consistent behavior across modes
  • Tests
    • Updated unit tests to reflect FleetMode-specific behavior and error paths
  • Chores
    • Updated runtime base image tag used for container builds

@openshift-ci openshift-ci Bot requested review from Tafhim and bmeng April 14, 2026 14:40
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 14, 2026

Walkthrough

Cluster version fetch and cluster ID usage were made conditional on OCM Agent FleetMode: when FleetMode is true, cluster version is not fetched and ConfigMap is built with an empty cluster ID. Deployment arg logic was changed to if/else for mutually exclusive flags. NetworkPolicy namespace selection was extracted to a helper; tests updated.

Changes

Cohort / File(s) Summary
ConfigMap & Tests
pkg/ocmagenthandler/ocmagenthandler_configmap.go, pkg/ocmagenthandler/ocmagenthandler_configmap_test.go
ensureAllConfigMaps fetches ClusterVersion only when ocmAgent.Spec.FleetMode is false; in FleetMode the ConfigMap uses an empty cluster ID. Test adjusted to not expect cluster version fetch in FleetMode and to exercise non-fleet error path.
Deployment args
pkg/ocmagenthandler/ocmagenthandler_deployment.go
buildOCMAgentArgs refactored from two if statements into an if/else: non-fleet adds --cluster-id/--access-token, fleet adds --fleet-mode.
NetworkPolicy helper
pkg/ocmagenthandler/ocmagenthandler_networkpolicy.go
Added unexported helper getNetworkPolicyNamespaces(ocmAgent) and replaced duplicated FleetMode-based namespace slice construction in ensureAllNetworkPolicies and ensureAllNetworkPoliciesDeleted.
Build images
build/Dockerfile, build/Dockerfile.olm-registry
Updated runtime stage base image tag from ...9.7-1775623882 to ...9.7-1776104705 in both Dockerfiles only.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

🚥 Pre-merge checks | ✅ 8 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Test Structure And Quality ⚠️ Warning Test violates single responsibility, lacks meaningful assertion messages, missing mock cleanup, and uses overly broad gomock.Any() matchers. Split test into two separate tests, add diagnostic messages to assertions, add AfterEach block for mock cleanup, replace gomock.Any() with specific matchers.
✅ Passed checks (8 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately reflects the main changes: conditional FleetMode optimizations, code extraction for clarity, and refactoring of mutually exclusive conditions across multiple files.
Stable And Deterministic Test Names ✅ Passed All Ginkgo test names in ocmagenthandler_configmap_test.go are static and deterministic with no dynamic values, generated suffixes, timestamps, UUIDs, or variable content.
Microshift Test Compatibility ✅ Passed This PR does not add any new Ginkgo e2e tests. The files modified are implementation code, unit tests using mocks, and Docker build files. The e2e test files in test/e2e/ directory are not modified.
Single Node Openshift (Sno) Test Compatibility ✅ Passed The custom check for SNO compatibility applies only to new Ginkgo e2e tests. This PR modifies unit tests using mocking frameworks only, with no e2e test changes.
Topology-Aware Scheduling Compatibility ✅ Passed PR does not introduce scheduling constraints assuming standard HA topology; changes are operational optimizations for FleetMode and refactoring.
Ote Binary Stdout Contract ✅ Passed PR changes contain only handler business logic and unit tests with no process-level entry points that could write non-JSON stdout.
Ipv6 And Disconnected Network Test Compatibility ✅ Passed PR modifications only affect unit tests in pkg/ocmagenthandler/ using mocked Kubernetes clients via gomock with no hardcoded IPv4 addresses or external connectivity requirements.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@TheUndeadKing
Copy link
Copy Markdown
Contributor Author

/retest

@codecov-commenter
Copy link
Copy Markdown

codecov-commenter commented Apr 15, 2026

Codecov Report

❌ Patch coverage is 83.33333% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 66.49%. Comparing base (1274d91) to head (1c3798a).

Files with missing lines Patch % Lines
pkg/ocmagenthandler/ocmagenthandler_configmap.go 83.33% 1 Missing ⚠️
...g/ocmagenthandler/ocmagenthandler_networkpolicy.go 80.00% 1 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##           master     #239      +/-   ##
==========================================
+ Coverage   66.25%   66.49%   +0.23%     
==========================================
  Files          23       23              
  Lines        1544     1543       -1     
==========================================
+ Hits         1023     1026       +3     
+ Misses        445      442       -3     
+ Partials       76       75       -1     
Files with missing lines Coverage Δ
pkg/ocmagenthandler/ocmagenthandler_deployment.go 86.42% <100.00%> (ø)
pkg/ocmagenthandler/ocmagenthandler_configmap.go 87.39% <83.33%> (ø)
...g/ocmagenthandler/ocmagenthandler_networkpolicy.go 78.21% <80.00%> (+3.70%) ⬆️
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@openshift-ci openshift-ci Bot added the needs-rebase Indicates a PR cannot be merged because it has merge conflicts with HEAD. label Apr 15, 2026
@openshift-ci
Copy link
Copy Markdown
Contributor

openshift-ci Bot commented Apr 15, 2026

@TheUndeadKing: Failed to re-open PR: state cannot be changed. There are no new commits on the TheUndeadKing:code-review branch.

Details

In response to this:

/reopen

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.

@openshift-ci
Copy link
Copy Markdown
Contributor

openshift-ci Bot commented Apr 15, 2026

@TheUndeadKing: Failed to re-open PR: state cannot be changed. There are no new commits on the TheUndeadKing:code-review branch.

Details

In response to this:

/reopen

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.

@TheUndeadKing
Copy link
Copy Markdown
Contributor Author

/reopen

@openshift-ci openshift-ci Bot reopened this Apr 15, 2026
@openshift-ci
Copy link
Copy Markdown
Contributor

openshift-ci Bot commented Apr 15, 2026

@TheUndeadKing: Reopened this PR.

Details

In response to this:

/reopen

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.

@openshift-ci openshift-ci Bot removed the needs-rebase Indicates a PR cannot be merged because it has merge conflicts with HEAD. label Apr 15, 2026
@openshift-ci
Copy link
Copy Markdown
Contributor

openshift-ci Bot commented Apr 15, 2026

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by: TheUndeadKing
Once this PR has been reviewed and has the lgtm label, please assign smarthall for approval. For more information see the Code Review Process.

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

1 similar comment
@openshift-ci
Copy link
Copy Markdown
Contributor

openshift-ci Bot commented Apr 15, 2026

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by: TheUndeadKing
Once this PR has been reviewed and has the lgtm label, please assign smarthall for approval. For more information see the Code Review Process.

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@TheUndeadKing
Copy link
Copy Markdown
Contributor Author

/retest

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@pkg/ocmagenthandler/ocmagenthandler_configmap_test.go`:
- Around line 279-283: The test uses
mockClient.EXPECT().Get(...).Return(...).Times(2) and
mockClient.EXPECT().Create(...).Return(nil).Times(2) with gomock.Any(), which
only verifies call counts and can miss wrong resources; update the expectations
to assert the actual ConfigMap objects created by ensureAllConfigMaps: replace
gomock.Any() for the object arg with a matcher like
gomock.AssignableToTypeOf(&corev1.ConfigMap{}) and/or capture the created
argument using gomock.Do or a custom gomock.Matcher, then assert the ConfigMap
metadata (Name, Namespace) and Data keys/values for the OCM Agent ConfigMap and
the Trusted CA ConfigMap; keep ctx param as gomock.Any() but verify the second
argument (the object) against expected names and contents when setting up
mockClient.EXPECT().Create and similarly tighten Get expectations to match the
correct names.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository: openshift/coderabbit/.coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 381606b4-3cd1-4967-bf77-663b992b3319

📥 Commits

Reviewing files that changed from the base of the PR and between c6f20b5 and 1c3798a.

📒 Files selected for processing (6)
  • build/Dockerfile
  • build/Dockerfile.olm-registry
  • pkg/ocmagenthandler/ocmagenthandler_configmap.go
  • pkg/ocmagenthandler/ocmagenthandler_configmap_test.go
  • pkg/ocmagenthandler/ocmagenthandler_deployment.go
  • pkg/ocmagenthandler/ocmagenthandler_networkpolicy.go
✅ Files skipped from review due to trivial changes (3)
  • build/Dockerfile.olm-registry
  • build/Dockerfile
  • pkg/ocmagenthandler/ocmagenthandler_deployment.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • pkg/ocmagenthandler/ocmagenthandler_configmap.go

Comment on lines +279 to 283
// FleetMode creates: OCM Agent ConfigMap + Trusted CA ConfigMap (not CAMO)
mockClient.EXPECT().Get(gomock.Any(), gomock.Any(), gomock.Any()).Return(k8serrs.NewNotFound(schema.GroupResource{}, "")).Times(2)
mockClient.EXPECT().Create(gomock.Any(), gomock.Any()).Return(nil).Times(2)
err := testOcmAgentHandler.ensureAllConfigMaps(testOcmAgent)
Expect(err).ToNot(HaveOccurred())
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Fleet-mode test is under-asserted for created resources.

Line 280-Line 281 only check call counts with gomock.Any(). This can miss regressions where the wrong ConfigMaps are created (or expected data is wrong) while counts still equal 2.

Proposed assertion-tightening diff
 		It("ensureAllConfigMaps handles fleet mode and errors", func() {
 			// Test fleet mode (no cluster version fetch, no CAMO, no cluster ID)
 			testOcmAgent.Spec.FleetMode = true
 			// FleetMode creates: OCM Agent ConfigMap + Trusted CA ConfigMap (not CAMO)
-			mockClient.EXPECT().Get(gomock.Any(), gomock.Any(), gomock.Any()).Return(k8serrs.NewNotFound(schema.GroupResource{}, "")).Times(2)
-			mockClient.EXPECT().Create(gomock.Any(), gomock.Any()).Return(nil).Times(2)
+			notFound := k8serrs.NewNotFound(schema.GroupResource{}, "")
+			created := map[string]*corev1.ConfigMap{}
+			mockClient.EXPECT().Get(gomock.Any(), gomock.Any(), gomock.Any()).Return(notFound).Times(2)
+			mockClient.EXPECT().Create(gomock.Any(), gomock.Any()).DoAndReturn(
+				func(_ context.Context, d *corev1.ConfigMap, _ ...client.CreateOptions) error {
+					created[d.Name] = d
+					return nil
+				}).Times(2)
 			err := testOcmAgentHandler.ensureAllConfigMaps(testOcmAgent)
 			Expect(err).ToNot(HaveOccurred())
+			Expect(created).To(HaveKey(testOcmAgent.Name + testconst.TestConfigMapSuffix))
+			Expect(created).To(HaveKey("trusted-ca-bundle"))
+			Expect(created).ToNot(HaveKey(oahconst.CAMOConfigMapNamespacedName.Name))
+			Expect(created[testOcmAgent.Name+testconst.TestConfigMapSuffix].Data).ToNot(HaveKey(oahconst.OCMAgentConfigClusterID))
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/ocmagenthandler/ocmagenthandler_configmap_test.go` around lines 279 -
283, The test uses mockClient.EXPECT().Get(...).Return(...).Times(2) and
mockClient.EXPECT().Create(...).Return(nil).Times(2) with gomock.Any(), which
only verifies call counts and can miss wrong resources; update the expectations
to assert the actual ConfigMap objects created by ensureAllConfigMaps: replace
gomock.Any() for the object arg with a matcher like
gomock.AssignableToTypeOf(&corev1.ConfigMap{}) and/or capture the created
argument using gomock.Do or a custom gomock.Matcher, then assert the ConfigMap
metadata (Name, Namespace) and Data keys/values for the OCM Agent ConfigMap and
the Trusted CA ConfigMap; keep ctx param as gomock.Any() but verify the second
argument (the object) against expected names and contents when setting up
mockClient.EXPECT().Create and similarly tighten Get expectations to match the
correct names.

@openshift-ci
Copy link
Copy Markdown
Contributor

openshift-ci Bot commented Apr 15, 2026

@TheUndeadKing: 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants