Skip to content

net, libs: Refactor random ip address helpers#4944

Open
azhivovk wants to merge 1 commit into
RedHatQE:mainfrom
azhivovk:net-ip-cidr-refactor
Open

net, libs: Refactor random ip address helpers#4944
azhivovk wants to merge 1 commit into
RedHatQE:mainfrom
azhivovk:net-ip-cidr-refactor

Conversation

@azhivovk
Copy link
Copy Markdown
Contributor

@azhivovk azhivovk commented May 20, 2026

What this PR does / why we need it:

random_ipv4_address and random_ipv6_address returned plain IPs, forcing every caller to manually append /24 or /64. Since CIDR is the common case (cloud-init, subnet assignments), the helpers now
return CIDR strings directly. Callers that need a plain IP strip the prefix with .split("/")[0]; callers with a non-standard mask strip and reapply it.

Which issue(s) this PR fixes: -
Special notes for reviewer:

Reuested follow-up PR by approvers

jira-ticket: -

Summary by CodeRabbit

Release Notes

  • Refactor
    • Improved network address generation with built-in CIDR formatting support; test suite updated to utilize this new capability for more consistent and maintainable network configuration handling across multiple test scenarios.

Review Change Stack

@openshift-virtualization-qe-bot-3
Copy link
Copy Markdown
Contributor

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
  • Branch Labeling: Branch-specific labels are applied to track the target branch
  • Auto-verification: Auto-verified users have their PRs automatically marked as verified
  • Labels: Enabled categories: branch, can-be-merged, cherry-pick, has-conflicts, hold, needs-rebase, size, verified, wip

📋 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
  • /reprocess - Trigger complete PR workflow reprocessing (useful if webhook failed or configuration changed)
  • /regenerate-welcome - Regenerate this welcome message

Review & Approval

  • /lgtm - Approve changes (looks good to me)
  • /approve - Approve PR (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 build-container - Rebuild and test container image
  • /retest verify-bugs-are-open - verify-bugs-are-open
  • /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 2 /lgtm from reviewers
  3. Status Checks: All required status checks must pass
  4. No Blockers: No wip, hold, has-conflicts labels and PR must be mergeable (no conflicts)
  5. Verified: PR must be marked as verified

📊 Review Process

Approvers and Reviewers

Approvers:

  • EdDev
  • dshchedr
  • myakove
  • rnetser
  • vsibirsk

Reviewers:

  • Anatw
  • EdDev
  • RoniKishner
  • azhivovk
  • dshchedr
  • frenzyfriday
  • hmeir
  • nirdothan
  • orelmisan
  • rlobillo
  • rnetser
  • servolkov
  • vsibirsk
  • yossisegev
Available Labels
  • hold
  • verified
  • wip
  • lgtm
  • approve
AI Features
  • Cherry-Pick Conflict Resolution: Enabled (claude/claude-opus-4-6[1m])

💡 Tips

  • WIP Status: Use /wip when your PR is not ready for review
  • Verification: The verified label is removed on new commits unless the push is detected as a clean rebase
  • 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
Contributor

coderabbitai Bot commented May 20, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: b148c13a-b892-42bf-9806-74e6c99af66f

📥 Commits

Reviewing files that changed from the base of the PR and between cd905b8 and 223c404.

📒 Files selected for processing (28)
  • libs/net/ip.py
  • tests/conftest.py
  • tests/network/bgp/conftest.py
  • tests/network/bgp/evpn/conftest.py
  • tests/network/bgp/evpn/libevpn.py
  • tests/network/bond/test_l2_bridge_over_bond.py
  • tests/network/connectivity/utils.py
  • tests/network/flat_overlay/conftest.py
  • tests/network/flat_overlay/utils.py
  • tests/network/general/test_cnv_tuning_regression.py
  • tests/network/jumbo_frame/test_bond.py
  • tests/network/jumbo_frame/test_bridge.py
  • tests/network/jumbo_frame/utils.py
  • tests/network/kubemacpool/utils.py
  • tests/network/l2_bridge/bandwidth/conftest.py
  • tests/network/l2_bridge/conftest.py
  • tests/network/l2_bridge/libl2bridge.py
  • tests/network/l2_bridge/test_bridge_nic_hot_plug.py
  • tests/network/l2_bridge/vmi_interfaces_stability/lib_helpers.py
  • tests/network/libs/dhcpd.py
  • tests/network/localnet/conftest.py
  • tests/network/localnet/ipam/conftest.py
  • tests/network/macspoof/conftest.py
  • tests/network/migration/test_migration.py
  • tests/network/nmstate/test_connectivity_after_nmstate_changes.py
  • tests/network/sriov/libsriov.py
  • tests/network/upgrade/conftest.py
  • tests/network/user_defined_network/conftest.py

📝 Walkthrough

Walkthrough

IPv4 and IPv6 address generation functions now accept a cidr_required parameter (default True) to unify CIDR formatting. The core functions return either bare IPs or CIDR-formatted strings, and test fixtures are updated to pass cidr_required=False when bare IPs are needed or rely on the new default when CIDR strings are required. The obsolete random_ip_addresses_by_family() is removed; random_cidr_addresses_by_family() now uses the new parameter directly. Over 30 test files are updated accordingly.

Changes

IP Address Generation Contract Refactor

Layer / File(s) Summary
IP address function contract changes
libs/net/ip.py
random_ipv4_address() and random_ipv6_address() are extended with cidr_required: bool = True parameter; when True, they append /24 (IPv4) or /64 (IPv6); when False, they return bare IPs. random_cidr_addresses_by_family() now calls these functions directly. The public random_ip_addresses_by_family() is removed.
Fixtures using cidr_required=False for bare IPs
tests/network/l2_bridge/conftest.py, tests/network/l2_bridge/test_bridge_nic_hot_plug.py, tests/network/kubemacpool/utils.py, tests/network/flat_overlay/conftest.py, tests/network/libs/dhcpd.py, tests/network/upgrade/conftest.py
Test fixtures and constants that require bare IP addresses (MPLS loopback IPs, hot-plug interfaces, kubemacpool network config, DHCP ranges, upgrade tests) explicitly pass cidr_required=False to prevent double-formatting in downstream code.
Fixtures using CIDR output directly
tests/conftest.py, tests/network/bgp/conftest.py, tests/network/bgp/evpn/conftest.py, tests/network/bond/test_l2_bridge_over_bond.py, tests/network/connectivity/utils.py, tests/network/flat_overlay/utils.py, tests/network/general/test_cnv_tuning_regression.py, tests/network/jumbo_frame/test_bond.py, tests/network/jumbo_frame/test_bridge.py, tests/network/jumbo_frame/utils.py, tests/network/localnet/conftest.py, tests/network/localnet/ipam/conftest.py, tests/network/macspoof/conftest.py, tests/network/migration/test_migration.py, tests/network/nmstate/test_connectivity_after_nmstate_changes.py, tests/network/sriov/libsriov.py, tests/network/user_defined_network/conftest.py
Test fixtures that previously manually appended CIDR suffixes now rely on functions returning CIDR-formatted strings by default. Manual suffix appending is removed from cloud-init address lists, endpoint IPs, and NAD/network configuration constants.
Adoption of random_cidr_addresses_by_family() helper
tests/network/l2_bridge/bandwidth/conftest.py, tests/network/l2_bridge/libl2bridge.py, tests/network/l2_bridge/vmi_interfaces_stability/lib_helpers.py
Test modules switch from random_ip_addresses_by_family() plus manual CIDR formatting to random_cidr_addresses_by_family(). Imports are updated to remove the obsolete helper and add the new one. IP-version-dependent CIDR suffixing logic is centralized.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Rationale: The change is a focused refactoring of a shared utility function contract. While the scope is broad (30+ files touched), the pattern is highly repetitive and consistent: either adding cidr_required=False or removing manual CIDR suffixing. Logic density is low (parameter addition, suffix management), and the contract change is straightforward once the core function signature is understood. No new algorithms, complex interactions, or structural changes are introduced.

Possibly related PRs

Suggested reviewers

  • yossisegev
  • rnetser
  • vsibirsk
  • dshchedr
  • RoniKishner
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: refactoring random IP address helper functions to return CIDR strings directly.
Description check ✅ Passed The description covers all required template sections: explains what the PR does (why CIDR refactoring), notes no specific issue (marks with '-'), provides reviewer context about the requested follow-up, and includes jira-ticket field.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Stp Link Required ✅ Passed No new test files or test functions added; only modifications to existing code and helper function refactoring.

✏️ 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.

Comment thread libs/net/ip.py Outdated
"""
third_octets = _random_octets(count=_MAX_NUM_OF_RANDOM_OCTETS_PER_SESSION)
return f"{_IPV4_ADDRESS_SUBNET_PREFIX_VMI}.{third_octets[net_seed]}.{host_address}"
return f"{_IPV4_ADDRESS_SUBNET_PREFIX_VMI}.{third_octets[net_seed]}.{host_address}/24"
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

First - if the caller is now responsible for removing the subnet length suffix if they need a plain IP (instead of a complete CIDR), then it might be worth explaining it in the doctring (just like you did very clearly in the PR description).
Second - looking at places where the plain IP is needed (for example here), it looks a bit hacky, Maybe it's worth to add a flag to this function, which defaults to True, so it will become something like this:

def random_ipv4_address(net_seed: int, host_address: int, cidr_required: bool  = True) -> str:
...
subnet_length = "/24" if  cidr_required else ""
...
    return f"{_IPV4_ADDRESS_SUBNET_PREFIX_VMI}.{third_octets[net_seed]}.{host_address}{subnet_length}"

and then, when the subnet length is not needed, it can be called this way

ip_address=f"{random_ipv4_address(net_seed=0, host_address=123, cidr_required=False)/{SPECIFIC_HOST_MASK}"

and leave out the cidr_required in all other places (which will leave most of the contents of this PR as it is now).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Great idea, thanks!

@openshift-virtualization-qe-bot-3
Copy link
Copy Markdown
Contributor

/retest all

Auto-triggered: Files in this PR were modified by merged PR #4856.

Overlapping files

tests/conftest.py

Return CIDR strings directly from the low-level helpers.
Callers that need a plain IP call the relevant helper with
cidr_required=False.
callers that need a non-standard mask may strip the cidr and
reapply it.

Remove random_ip_addresses_by_family — it became identical to
random_cidr_addresses_by_family after this change.

Signed-off-by: Asia Khromov <azhivovk@redhat.com>
Assisted-by: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>
@azhivovk
Copy link
Copy Markdown
Contributor Author

Change: add optional cidr param

@openshift-virtualization-qe-bot-3
Copy link
Copy Markdown
Contributor

/retest all

Auto-triggered: Files in this PR were modified by merged PR #4896.

Overlapping files

tests/conftest.py

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.

5 participants