Skip to content

refactor: update DataVolume resource#2480

Merged
myakove merged 11 commits intoRedHatQE:mainfrom
jpeimer:update_dv_resource
Aug 14, 2025
Merged

refactor: update DataVolume resource#2480
myakove merged 11 commits intoRedHatQE:mainfrom
jpeimer:update_dv_resource

Conversation

@jpeimer
Copy link
Copy Markdown
Contributor

@jpeimer jpeimer commented Aug 3, 2025

Summary by CodeRabbit

  • New Features

    • Added checkpoints, final-checkpoint flag, priority class name, explicit source references, and broader source types with optional secret/cert support.
  • Refactor

    • Hardened and clarified DataVolume constructor with explicit typed parameters.
    • Modularized spec construction for clearer, more maintainable resource output.
  • Bug Fixes

    • Removed legacy/deprecated annotation and path handling to avoid misuse.

@redhat-qe-bot1
Copy link
Copy Markdown

Report bugs in Issues

Welcome! 🎉

This pull request will be automatically processed with the following features:

🔄 Automatic Actions

  • Reviewer Assignment: Reviewers are automatically assigned based on the OWNERS file in the repository root
  • Size Labeling: PR size labels (XS, S, M, L, XL, XXL) are automatically applied based on changes
  • Issue Creation: A tracking issue is created for this PR and will be closed when the PR is merged or closed
  • Pre-commit Checks: pre-commit runs automatically if .pre-commit-config.yaml exists
  • Branch Labeling: Branch-specific labels are applied to track the target branch
  • Auto-verification: Auto-verified users have their PRs automatically marked as verified

📋 Available Commands

PR Status Management

  • /wip - Mark PR as work in progress (adds WIP: prefix to title)
  • /wip cancel - Remove work in progress status
  • /hold - Block PR merging (approvers only)
  • /hold cancel - Unblock PR merging
  • /verified - Mark PR as verified
  • /verified cancel - Remove verification status

Review & Approval

  • /lgtm - Approve changes (looks good to me)
  • /approve - Approve PR (approvers only)
  • /automerge - Enable automatic merging when all requirements are met (maintainers and approvers only)
  • /assign-reviewers - Assign reviewers based on OWNERS file
  • /assign-reviewer @username - Assign specific reviewer
  • /check-can-merge - Check if PR meets merge requirements

Testing & Validation

  • /retest tox - Run Python test suite with tox
  • /retest python-module-install - Test Python package installation
  • /retest conventional-title - Validate commit message format
  • /retest all - Run all available tests

Container Operations

  • /build-and-push-container - Build and push container image (tagged with PR number)
    • Supports additional build arguments: /build-and-push-container --build-arg KEY=value

Cherry-pick Operations

  • /cherry-pick <branch> - Schedule cherry-pick to target branch when PR is merged
    • Multiple branches: /cherry-pick branch1 branch2 branch3

Label Management

  • /<label-name> - Add a label to the PR
  • /<label-name> cancel - Remove a label from the PR

✅ Merge Requirements

This PR will be automatically approved when the following conditions are met:

  1. Approval: /approve from at least one approver
  2. LGTM Count: Minimum 0 /lgtm from reviewers
  3. Status Checks: All required status checks must pass
  4. No Blockers: No WIP, hold, or conflict labels
  5. Verified: PR must be marked as verified (if verification is enabled)

📊 Review Process

Approvers and Reviewers

Approvers:

  • myakove
  • rnetser

Reviewers:

  • dbasunag
  • myakove
  • rnetser
Available Labels
  • hold
  • verified
  • wip
  • lgtm
  • approve
  • automerge

💡 Tips

  • WIP Status: Use /wip when your PR is not ready for review
  • Verification: The verified label is automatically removed on each new commit
  • Cherry-picking: Cherry-pick labels are processed when the PR is merged
  • Container Builds: Container images are automatically tagged with the PR number
  • Permission Levels: Some commands require approver permissions
  • Auto-verified Users: Certain users have automatic verification and merge privileges

For more information, please refer to the project documentation or contact the maintainers.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Aug 3, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

DataVolume in ocp_resources/datavolume.py was refactored: constructor replaced by an explicit, typed signature and legacy args removed; to_dict was reworked to build a modular spec, add new top-level fields and api-specific blocks, and unify source, secret, and annotation handling.

Changes

Cohort / File(s) Change Summary
DataVolume class refactor
ocp_resources/datavolume.py
Replaced legacy constructor with a typed signature (adds source_dict, source_ref, checkpoints, final_checkpoint, priority_class_name, and many explicit params; removes name, namespace, client, teardown, yaml_file, delete_timeout, delete_after_completion). __init__ now calls super().__init__(**kwargs) and stores new attributes. Rewrote to_dict to ensure spec exists, add top-level fields (checkpoints, contentType, finalCheckpoint, preallocation, priorityClassName), build an api_name section (default "pvc") only when relevant, support source_dict or per-source blocks (http/registry/upload/blank/pvc) with optional secretRef, certConfigMap, and sourceRef, and use setdefault for annotations. Removed legacy deleteAfterCompletion and prior inline PVC annotation/path logic.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.


📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these settings in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 1f3dc3f and f973d89.

📒 Files selected for processing (1)
  • ocp_resources/datavolume.py (4 hunks)
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

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: 4

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d375115 and 154fe5d.

📒 Files selected for processing (1)
  • ocp_resources/datavolume.py (4 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: rnetser
PR: RedHatQE/openshift-python-wrapper#2387
File: ocp_resources/user.py:45-47
Timestamp: 2025-04-28T12:52:11.677Z
Learning: In the openshift-python-wrapper, resources can be created either through constructor parameters or from YAML files. The `to_dict` method in resource classes typically checks for `self.kind_dict` and `self.yaml_file` to determine if parameters need to be explicitly provided. Parameters that would otherwise be required can be omitted when creating from YAML.
Learnt from: myakove
PR: RedHatQE/openshift-python-wrapper#2171
File: ocp_resources/mariadb_operator.py:90-140
Timestamp: 2024-10-15T13:51:36.142Z
Learning: In `ocp_resources/mariadb_operator.py`, the `to_dict` method in the `MariadbOperator` class is intentionally kept in its current form for better readability, and should not be refactored to reduce repetition.
Learnt from: myakove
PR: RedHatQE/openshift-python-wrapper#2209
File: ocp_resources/volume_snapshot_class.py:0-0
Timestamp: 2024-12-03T08:02:11.880Z
Learning: In generated code files like `ocp_resources/volume_snapshot_class.py`, avoid suggesting adding validation checks or modifications, as generated code should not be manually altered.
Learnt from: myakove
PR: RedHatQE/openshift-python-wrapper#2184
File: ocp_resources/user_defined_network.py:143-168
Timestamp: 2024-10-30T09:40:53.905Z
Learning: In `ocp_resources/user_defined_network.py`, for type hints of parameters like `subnets` that are lists of dictionaries, prefer using `Optional[List[Dict[str, Any]]]` instead of defining a `TypedDict`.
📚 Learning: in generated code files like `ocp_resources/volume_snapshot_class.py`, avoid suggesting adding valid...
Learnt from: myakove
PR: RedHatQE/openshift-python-wrapper#2209
File: ocp_resources/volume_snapshot_class.py:0-0
Timestamp: 2024-12-03T08:02:11.880Z
Learning: In generated code files like `ocp_resources/volume_snapshot_class.py`, avoid suggesting adding validation checks or modifications, as generated code should not be manually altered.

Applied to files:

  • ocp_resources/datavolume.py
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: can-be-merged
  • GitHub Check: can-be-merged
  • GitHub Check: conventional-title
  • GitHub Check: python-module-install
  • GitHub Check: tox
🔇 Additional comments (1)
ocp_resources/datavolume.py (1)

76-150: Constructor refactoring looks good!

The addition of type annotations and the use of **kwargs pattern aligns with the framework's design where resources can be created either through constructor parameters or from YAML files.

Comment thread ocp_resources/datavolume.py Outdated
Comment thread ocp_resources/datavolume.py Outdated
Comment thread ocp_resources/datavolume.py
Comment thread ocp_resources/datavolume.py Outdated
@jpeimer jpeimer changed the title Update DataVolume resource refactor: update DataVolume resource Aug 3, 2025
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: 2

🧹 Nitpick comments (2)
ocp_resources/datavolume.py (2)

105-128: Tighten types and docs for access modes, volume mode, api_name, and source

  • K8s expects accessModes as a list of strings. Current API takes a single str and wraps it into a one-item list. Consider accepting list[str] too.
  • Consider Literal typing for source and api_name to prevent invalid values at type-check time.

Apply these adjustments to signature and docs:

@@
-        access_modes: str | None = None,
-        volume_mode: str | None = None,
+        access_modes: str | list[str] | None = None,
+        volume_mode: str | None = None,
@@
-            access_modes (str, default: None): DataVolume access mode (e.g., "ReadWriteOnce", "ReadWriteMany").
+            access_modes (str | list[str], default: None): DataVolume access mode(s), K8s expects a list.
+                Examples: "ReadWriteOnce" or ["ReadWriteOnce","ReadOnlyMany"].
@@
-            api_name (str, default: "pvc"): api used for DV (e.g., "storage", "pvc").
+            api_name (str, default: "pvc"): API used for DV ("pvc" or "storage").

And in to_dict:

@@
-                if self.access_modes is not None:
-                    _spec[self.api_name]["accessModes"] = [self.access_modes]
+                if self.access_modes is not None:
+                    _spec[self.api_name]["accessModes"] = (
+                        self.access_modes if isinstance(self.access_modes, list) else [self.access_modes]
+                    )

173-189: Avoid creating an empty pvc/storage block when no fields are set

Currently, _spec[self.api_name] = {} is added whenever api_name is not None, even if none of accessModes/volumeMode/storageClass/size are provided. This produces an empty object in the manifest, which is unnecessary and can confuse readers or validators.

Refine to create the block only when needed:

-            if self.api_name is not None:
-                _spec[self.api_name] = {}
+            if any([self.access_modes, self.volume_mode, self.storage_class, self.size]):
+                api_name = self.api_name or "pvc"
+                _spec[api_name] = {}
@@
-                if self.access_modes is not None:
-                    _spec[self.api_name]["accessModes"] = [self.access_modes]
+                if self.access_modes is not None:
+                    _spec[api_name]["accessModes"] = (
+                        self.access_modes if isinstance(self.access_modes, list) else [self.access_modes]
+                    )
@@
-                if self.volume_mode is not None:
-                    _spec[self.api_name]["volumeMode"] = self.volume_mode
+                if self.volume_mode is not None:
+                    _spec[api_name]["volumeMode"] = self.volume_mode
@@
-                if self.storage_class is not None:
-                    _spec[self.api_name]["storageClassName"] = self.storage_class
+                if self.storage_class is not None:
+                    _spec[api_name]["storageClassName"] = self.storage_class
@@
-                if self.size is not None:
-                    _spec[self.api_name]["resources"] = {"requests": {"storage": self.size}}
+                if self.size is not None:
+                    _spec[api_name]["resources"] = {"requests": {"storage": self.size}}
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 657517a and 9d521c9.

📒 Files selected for processing (1)
  • ocp_resources/datavolume.py (4 hunks)
🔇 Additional comments (3)
ocp_resources/datavolume.py (3)

211-212: LGTM: sourceRef support is clearly separated

Using sourceRef as a separate path keeps source and sourceRef orthogonal. No issues spotted.


214-228: LGTM: annotations use setdefault + update safely

  • provisionOnNode, Multus networks, and bind-immediate annotations are set safely with setdefault.
  • Keys are correctly namespaced.

76-100: No backward-compatibility issues detected for DataVolume constructor

I ran the provided script across the repo and found zero calls to DataVolume(...) using positional arguments (or otherwise). Since there are no existing instantiations in the codebase, the refactored __init__ signature poses no breakage risk.

No changes required.

Comment thread ocp_resources/datavolume.py
Comment thread ocp_resources/datavolume.py
@jpeimer
Copy link
Copy Markdown
Contributor Author

jpeimer commented Aug 10, 2025

/verified

@jpeimer
Copy link
Copy Markdown
Contributor Author

jpeimer commented Aug 14, 2025

/verified

@jpeimer
Copy link
Copy Markdown
Contributor Author

jpeimer commented Aug 14, 2025

/verified

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: 0

♻️ Duplicate comments (2)
ocp_resources/datavolume.py (2)

175-190: Avoid emitting an empty pvc/storage block; initialize nested dicts safely.

Currently _spec[self.api_name] = {} is created even when no inner fields are provided, which can lead to an invalid DV spec like pvc: {}. Initialize only when any nested field is set, and use setdefault for resources.

-            # Set api_name spec fields (pvc/storage)
-            if self.api_name is not None:
-                _spec[self.api_name] = {}
+            # Set api_name spec fields (pvc/storage) only when needed
+            if self.api_name is not None and any([self.access_modes, self.volume_mode, self.storage_class, self.size]):
+                _spec[self.api_name] = {}

                 if self.access_modes is not None:
-                    _spec[self.api_name]["accessModes"] = [self.access_modes]
+                    _spec[self.api_name]["accessModes"] = (
+                        [self.access_modes] if isinstance(self.access_modes, str) else list(self.access_modes)
+                    )

                 if self.volume_mode is not None:
                     _spec[self.api_name]["volumeMode"] = self.volume_mode

                 if self.storage_class is not None:
                     _spec[self.api_name]["storageClassName"] = self.storage_class

                 if self.size is not None:
-                    _spec[self.api_name]["resources"] = {"requests": {"storage": self.size}}
+                    _spec[self.api_name].setdefault("resources", {}).setdefault("requests", {})["storage"] = self.size

191-211: Constrain secretRef/certConfigMap to http/registry sources to avoid invalid specs.

Attaching these to pvc/upload/blank produces invalid fields and may be rejected by the API. Also guards against KeyError for unknown sources.

-                if self.secret is not None:
-                    source_spec[self.source]["secretRef"] = self.secret.name
-                if self.cert_configmap is not None:
-                    source_spec[self.source]["certConfigMap"] = self.cert_configmap
+                # Credentials and certs are applicable only for http/registry sources
+                if self.source in ("http", "registry"):
+                    if self.secret is not None:
+                        source_spec[self.source]["secretRef"] = self.secret.name
+                    if self.cert_configmap is not None:
+                        source_spec[self.source]["certConfigMap"] = self.cert_configmap
🧹 Nitpick comments (1)
ocp_resources/datavolume.py (1)

80-102: Constructor refactor and explicit typing improve clarity. Consider supporting multiple access modes.

DV spec allows a list of accessModes. If you want to support both single and multiple values without burdening callers, accept str | list[str] and normalize in to_dict.

Apply this diff to the signature:

-        access_modes: str | None = None,
+        access_modes: str | list[str] | None = None,

And adjust emission (see lines 179-181 change below).

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these settings in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 9d521c9 and 1f3dc3f.

📒 Files selected for processing (1)
  • ocp_resources/datavolume.py (4 hunks)
🧰 Additional context used
🧠 Learnings (3)
📓 Common learnings
Learnt from: jpeimer
PR: RedHatQE/openshift-python-wrapper#2480
File: ocp_resources/datavolume.py:158-172
Timestamp: 2025-08-10T13:55:36.406Z
Learning: In CDI v1beta1 DataVolume resources, the `priorityClassName` field is placed directly under `spec` (i.e., `spec.priorityClassName`), not under `spec.podSettings`. The field `spec.podSettings` does not exist in CDI v1beta1. This applies to the file `ocp_resources/datavolume.py` in the openshift-python-wrapper repository.
📚 Learning: 2025-08-10T13:55:36.406Z
Learnt from: jpeimer
PR: RedHatQE/openshift-python-wrapper#2480
File: ocp_resources/datavolume.py:158-172
Timestamp: 2025-08-10T13:55:36.406Z
Learning: In CDI v1beta1 DataVolume resources, the `priorityClassName` field is placed directly under `spec` (i.e., `spec.priorityClassName`), not under `spec.podSettings`. The field `spec.podSettings` does not exist in CDI v1beta1. This applies to the file `ocp_resources/datavolume.py` in the openshift-python-wrapper repository.

Applied to files:

  • ocp_resources/datavolume.py
📚 Learning: 2025-08-10T13:55:31.630Z
Learnt from: jpeimer
PR: RedHatQE/openshift-python-wrapper#2480
File: ocp_resources/datavolume.py:189-209
Timestamp: 2025-08-10T13:55:31.630Z
Learning: The openshift-python-wrapper project is designed as a thin wrapper around the Kubernetes/OpenShift API and intentionally does not perform input validation. Validation is left to the API server itself. Do not suggest adding ValueError exceptions or input validation checks in resource classes like DataVolume, VirtualMachine, etc.

Applied to files:

  • ocp_resources/datavolume.py
🧬 Code Graph Analysis (1)
ocp_resources/datavolume.py (2)
ocp_resources/secret.py (1)
  • Secret (5-73)
ocp_resources/resource.py (5)
  • to_dict (734-738)
  • to_dict (1641-1643)
  • update (1069-1087)
  • update (1689-1736)
  • NamespacedResource (1533-1643)
🔇 Additional comments (8)
ocp_resources/datavolume.py (8)

1-2: Good call using postponed evaluation of annotations.

This avoids runtime imports for type hints and plays well with TYPE_CHECKING.


15-19: TYPE_CHECKING import for Secret is correct and lightweight.

Keeps runtime deps minimal while preserving type safety.


107-130: Docstring updates are clear and helpful.

Coverage of new fields (source_dict, source_ref, checkpoints, final_checkpoint, priority_class_name) looks accurate.


131-153: **Switch to super().init(kwargs) is appropriate.

Keeps the wrapper thin and consistent with other resources.


154-159: Spec init only when building from params is correct.

The guard with kind_dict/yaml_file aligns with project conventions.


160-174: Top-level spec fields LGTM; priorityClassName placement is correct for CDI v1beta1.

Setting checkpoints, contentType, finalCheckpoint, preallocation, and priorityClassName directly under spec matches the DV schema. The priorityClassName location aligns with our retrieved learning for CDI v1beta1.


213-214: sourceRef handling is clean and non-intrusive.

Coexists nicely with source/source_dict for consumers that prefer indirect references.


216-229: Annotation handling looks correct.

  • provisionOnNode under kubevirt.io is properly keyed
  • multus networks annotation is right
  • bind.immediate.requested uses the CDI api_group prefix as expected

@jpeimer
Copy link
Copy Markdown
Contributor Author

jpeimer commented Aug 14, 2025

/verified

@myakove
Copy link
Copy Markdown
Collaborator

myakove commented Aug 14, 2025

/approve

@myakove myakove enabled auto-merge (squash) August 14, 2025 09:42
@myakove myakove merged commit 8f80932 into RedHatQE:main Aug 14, 2025
6 of 7 checks passed
@ema-aka-young
Copy link
Copy Markdown
Contributor

/cherry-pick v4.19

@redhat-qe-bot
Copy link
Copy Markdown
Contributor

Cherry-pick branch created, but PR creation failed
Branch CherryPicked-update_dv_resource-THzcJ was pushed to the repository.
Create the PR manually:

gh pr create --repo RedHatQE/openshift-python-wrapper --base v4.19 --head CherryPicked-update_dv_resource-THzcJ --label CherryPicked-from-main --title 'CherryPicked: [v4.19] refactor: update DataVolume resource' --body 'Cherry-pick from `main` branch, original PR: https://github.com/RedHatQE/openshift-python-wrapper/pull/2480, PR owner: jpeimer'

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants