Skip to content

SPLAT-2790: Added new VAP for vSphere infra validation against current cpms and machines#1510

Open
vr4manta wants to merge 3 commits into
openshift:mainfrom
vr4manta:infra-vap
Open

SPLAT-2790: Added new VAP for vSphere infra validation against current cpms and machines#1510
vr4manta wants to merge 3 commits into
openshift:mainfrom
vr4manta:infra-vap

Conversation

@vr4manta

@vr4manta vr4manta commented Jun 15, 2026

Copy link
Copy Markdown
Contributor

SPLAT-2790

Changes

  • Added logic to add new VAP for validating infrastructure (FD) removals against current CPMS and machines

Summary by CodeRabbit

  • New Features
    • Added vSphere failure-domain protection using ValidatingAdmissionPolicies and bindings for Machines, ControlPlaneMachineSets, and MachineSets. Infrastructure updates that remove still-referenced failure domains are blocked for the vSphere platform, gated by Multi–vCenter Day 2.
  • Security / RBAC
    • Extended operator RBAC to manage vSphere ValidatingAdmissionPolicies/Bindings and to read Machines and related machine set resources.
  • Tests
    • Added synchronization tests and expanded VAP/binding unit coverage, including MachineSet behavior and name/link consistency checks.

@openshift-ci-robot openshift-ci-robot added the jira/valid-reference Indicates that this PR references a valid Jira ticket of any type. label Jun 15, 2026
@openshift-ci openshift-ci Bot added the do-not-merge/work-in-progress Indicates that a PR should not merge because it is a work in progress. label Jun 15, 2026
@openshift-ci-robot

openshift-ci-robot commented Jun 15, 2026

Copy link
Copy Markdown
Contributor

@vr4manta: This pull request references SPLAT-2790 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 "5.0.0" version, but no target version was set.

Details

In response to this:

SPLAT-2790

Changes

  • Added logic to add new VAP for validating infrastructure (FD) removals against current CPMS and machines

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.

@openshift-ci

openshift-ci Bot commented Jun 15, 2026

Copy link
Copy Markdown
Contributor

Skipping CI for Draft Pull Request.
If you want CI signal for your change, please convert it to an actual PR.
You can still manually trigger a test run with /test all

@coderabbitai

coderabbitai Bot commented Jun 15, 2026

Copy link
Copy Markdown

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

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

Review profile: CHILL

Plan: Enterprise

Run ID: 083839d1-d6c0-4738-8df9-8fecbf2b2ed9

📥 Commits

Reviewing files that changed from the base of the PR and between cf0bb7c and 7cce8bf.

📒 Files selected for processing (6)
  • install/0000_30_machine-api-operator_09_rbac.yaml
  • pkg/operator/operator_test.go
  • pkg/operator/sync.go
  • pkg/operator/sync_test.go
  • pkg/webhooks/vap.go
  • pkg/webhooks/vap_test.go
🚧 Files skipped from review as they are similar to previous changes (6)
  • install/0000_30_machine-api-operator_09_rbac.yaml
  • pkg/operator/sync_test.go
  • pkg/webhooks/vap.go
  • pkg/operator/sync.go
  • pkg/operator/operator_test.go
  • pkg/webhooks/vap_test.go

Walkthrough

Adds three ValidatingAdmissionPolicy resources and their bindings to prevent vSphere failure domain removal from Infrastructure objects while Machine, ControlPlaneMachineSet, or MachineSet resources still reference those domains. The operator's syncWebhookConfiguration is extended with a vSphere branch that applies these VAPs sequentially when a feature gate is enabled. The machine-api-operator ClusterRole gains the required RBAC verbs on the new resource types.

Changes

vSphere Failure Domain ValidatingAdmissionPolicy Support

Layer / File(s) Summary
VAP contract and constants
pkg/webhooks/vap.go, pkg/webhooks/vap_test.go
Defines exported policy name constants for Machine, ControlPlaneMachineSet, and MachineSet failure domain protection, plus internal shared identifiers and package-level admission action variables. Adds test file imports for VAP webhook tests.
Machine failure domain protection
pkg/webhooks/vap.go, pkg/webhooks/vap_test.go
Implements NewVSphereFailureDomainMachineVAP and NewVSphereFailureDomainMachineVAPBinding constructors. The policy denies Infrastructure UPDATEs that would remove a failure domain referenced by any Machine param via region/zone labels. Tests verify policy name, ParamKind, update-only constraints, is-vsphere-platform condition, CEL variables, validation rules, and ParameterNotFoundAction=Allow.
ControlPlaneMachineSet failure domain protection
pkg/webhooks/vap.go, pkg/webhooks/vap_test.go
Implements NewVSphereFailureDomainCPMSVAP and NewVSphereFailureDomainCPMSVAPBinding constructors. The policy denies Infrastructure UPDATEs that would remove any failure domain name referenced in a ControlPlaneMachineSet param's template. Tests verify policy name, ParamKind, match constraints, CEL variables including template field references, validation rules, and binding configuration.
MachineSet failure domain protection
pkg/webhooks/vap.go, pkg/webhooks/vap_test.go
Implements NewVSphereFailureDomainMachineSetVAP and NewVSphereFailureDomainMachineSetVAPBinding constructors. The policy denies Infrastructure UPDATEs that would remove a failure domain referenced by any MachineSet param via region/zone labels in the template, including MachineSets with zero replicas. Tests verify policy name, ParamKind, match constraints, CEL variables, validation rules, and binding configuration.
VAP name consistency validation
pkg/webhooks/vap_test.go
Cross-validates that all three ValidatingAdmissionPolicyBinding objects correctly link to their corresponding policies by name (Machine, ControlPlaneMachineSet, and MachineSet).
Operator sync integration
pkg/operator/sync.go, pkg/operator/sync_test.go
Extends syncWebhookConfiguration with a vSphere platform branch that calls syncVSphereFailureDomainVAPs. The helper checks the vSphere multi-vCenter day2 feature gate and applies all three VAP/binding pairs sequentially using the operator cache. Unit test verifies zero VAPs for non-vSphere platforms and exactly three policies plus three bindings with correct names and policy references for vSphere.
RBAC permissions
install/0000_30_machine-api-operator_09_rbac.yaml
Extends ClusterRole machine-api-operator with get/list/watch/create/update verbs on validatingadmissionpolicies and validatingadmissionpolicybindings, plus get/list/watch on machines, controlplanemachinesets, and machinesets to support operator VAP management and kube-apiserver parameter resolution.
Test infrastructure updates
pkg/operator/operator_test.go
Introduces a shared disabledFeatureGates slice used across test cases for consistent feature gate setup. Updates mhc-controller-disabled test case to include FeatureGateVSphereMultiVCenterDay2 in the disabled gates list.

Sequence Diagram(s)

sequenceDiagram
    participant Operator as machine-api-operator
    participant k8s as Kubernetes API
    participant MachineVAP as Machine VAP
    participant CPMSVAP as CPMS VAP
    participant MachineSetVAP as MachineSet VAP

    rect rgba(100, 149, 237, 0.5)
        Note over Operator,k8s: syncVSphereFailureDomainVAPs (vSphere only, feature-gated)
        Operator->>k8s: apply NewVSphereFailureDomainMachineVAP
        k8s-->>Operator: ok
        Operator->>k8s: apply NewVSphereFailureDomainMachineVAPBinding
        k8s-->>Operator: ok
        Operator->>k8s: apply NewVSphereFailureDomainCPMSVAP
        k8s-->>Operator: ok
        Operator->>k8s: apply NewVSphereFailureDomainCPMSVAPBinding
        k8s-->>Operator: ok
        Operator->>k8s: apply NewVSphereFailureDomainMachineSetVAP
        k8s-->>Operator: ok
        Operator->>k8s: apply NewVSphereFailureDomainMachineSetVAPBinding
        k8s-->>Operator: ok
    end

    rect rgba(255, 140, 0, 0.5)
        Note over k8s,MachineSetVAP: Infrastructure UPDATE admission
        k8s->>MachineVAP: evaluate per Machine param (region/zone labels)
        MachineVAP-->>k8s: Deny if referenced FD removed
        k8s->>CPMSVAP: evaluate per ControlPlaneMachineSet param (template FD names)
        CPMSVAP-->>k8s: Deny if referenced FD removed
        k8s->>MachineSetVAP: evaluate per MachineSet param (template region/zone labels)
        MachineSetVAP-->>k8s: Deny if referenced FD removed
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~28 minutes

🚥 Pre-merge checks | ✅ 14 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 44.44% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (14 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: adding a new VAP for vSphere infrastructure validation against current machines and CPMS, which matches the core functionality described across all modified files.
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.
Stable And Deterministic Test Names ✅ Passed The PR adds standard Go tests (not Ginkgo) with stable, deterministic test names containing no dynamic content like timestamps, UUIDs, pod names, or generated identifiers.
Test Structure And Quality ✅ Passed The PR contains standard Go tests, not Ginkgo tests. The custom check targets "Ginkgo test code" but this codebase uses testing.T with Gomega. Tests follow existing patterns: single responsibility,...
Microshift Test Compatibility ✅ Passed PR does not add any Ginkgo e2e tests; all new tests are standard Go unit tests (func TestXxx(t *testing.T)) in pkg/operator/sync_test.go, pkg/webhooks/vap_test.go, and pkg/operator/operator_test.go...
Single Node Openshift (Sno) Test Compatibility ✅ Passed No new Ginkgo e2e tests were added in this PR. Changes are limited to unit tests in pkg/ using standard Go testing patterns. The custom check applies only to e2e tests in test/e2e/.
Topology-Aware Scheduling Compatibility ✅ Passed PR introduces ValidatingAdmissionPolicies and RBAC permissions for vSphere infrastructure validation. No pod scheduling constraints, affinity rules, nodeSelectors, or topology-dependent deployments...
Ote Binary Stdout Contract ✅ Passed PR introduces no process-level stdout writes. New vap.go has no logging; syncVSphereFailureDomainVAPs uses events.NewLoggingEventRecorder, not stdout. No init/main/TestMain functions added.
Ipv6 And Disconnected Network Test Compatibility ✅ Passed PR adds only standard Go unit tests (no Ginkgo e2e tests). The check targets Ginkgo e2e tests only, so it does not apply here.
No-Weak-Crypto ✅ Passed PR adds vSphere ValidatingAdmissionPolicy constructors with no weak crypto algorithms (MD5/SHA1/DES/RC4/3DES/Blowfish/ECB), custom crypto implementations, or non-constant-time secret comparisons.
Container-Privileges ✅ Passed PR modifies only RBAC rules and Go code files. No container privilege escalations present: deployment uses restricted-v2 SCC; no privileged: true, hostPID/IPC: true, SYS_ADMIN, or allowPrivilegeEsc...
No-Sensitive-Data-In-Logs ✅ Passed No logging that exposes sensitive data found. Recorder logs only resource apply events; MessageExpressions contain non-sensitive infrastructure labels and resource names.

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

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

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 golangci-lint (2.12.2)

Error: can't load config: unsupported version of the configuration: "" See https://golangci-lint.run/docs/product/migration-guide for migration instructions
The command is terminated due to an error: can't load config: unsupported version of the configuration: "" See https://golangci-lint.run/docs/product/migration-guide for migration instructions


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

@vr4manta

Copy link
Copy Markdown
Contributor Author

/test all

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@install/0000_30_machine-api-operator_09_rbac.yaml`:
- Around line 484-495: The ClusterRole rule at lines 487–495 grants unnecessary
cluster-wide read access to machines and controlplanemachinesets when the VAP
policies scope parameter resolution to the openshift-machine-api namespace only.
Remove this cluster-wide rule from the ClusterRole, and instead add the get verb
to the existing namespaced Role rule at line 363 that already grants list and
watch on all resources in the openshift-machine-api namespace. This narrows
permissions to only the namespace where the operator actually needs access while
maintaining the required authorization for VAP binding creation.

In `@pkg/operator/sync.go`:
- Around line 285-304: The ApplyValidatingAdmissionPolicyV1 and
ApplyValidatingAdmissionPolicyBindingV1 calls are using context.TODO() which
does not provide cancellation or timeout bounds. Replace context.TODO() with a
bounded context that includes proper cancellation and timeout behavior suitable
for the reconcile path. Create or use an existing bounded context with
appropriate timeout values (such as deriving it from the reconciliation context
or creating one with a reasonable timeout) and pass it to all four resourceapply
function calls instead of context.TODO().
🪄 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: Enterprise

Run ID: fa16aa88-d84f-4db6-80ab-a0191fea2bf4

📥 Commits

Reviewing files that changed from the base of the PR and between d7772c6 and b90994e.

📒 Files selected for processing (5)
  • install/0000_30_machine-api-operator_09_rbac.yaml
  • pkg/operator/sync.go
  • pkg/operator/sync_test.go
  • pkg/webhooks/vap.go
  • pkg/webhooks/vap_test.go

Comment thread install/0000_30_machine-api-operator_09_rbac.yaml Outdated
Comment thread pkg/operator/sync.go
@vr4manta

Copy link
Copy Markdown
Contributor Author

/test ?

@vr4manta

Copy link
Copy Markdown
Contributor Author

/test e2e-vsphere-ovn-serial e2e-vsphere-ovn-techpreview-serial

@vr4manta

Copy link
Copy Markdown
Contributor Author

/retest

@vr4manta

Copy link
Copy Markdown
Contributor Author

@CodeRabbit help

@coderabbitai

coderabbitai Bot commented Jun 17, 2026

Copy link
Copy Markdown

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.

CodeRabbit commands

These commands are invoked using PR/Issue comments.

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai rate limit to show your current review rate limit status.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai evaluate custom pre-merge check --instructions <custom-checks-instructions> --name <custom-checks-title> [--mode <error|warning>] to validate the custom pre-merge checks instructions. Defaults to error when --mode is omitted.
  • @coderabbitai ignore pre-merge checks to override pre-merge checks and get an approval on PR.
  • @coderabbitai run pre-merge checks to run pre-merge checks on the pull request.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai emit path instructions to emit generated path-specific review instructions for this repository.
  • @coderabbitai resolve merge conflict to automatically resolve merge conflicts.
  • @coderabbitai autofix to automatically fix issues identified in unresolved review comments.
  • @coderabbitai resolve to resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai generate configuration to create a PR that adds the current resolved configuration as .coderabbit.yaml (or show it if already present).
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit 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, support, documentation and community

  • Visit our status page to check the current availability of CodeRabbit.
  • Create a ticket on our support page for assistance with any issues or questions.
  • Visit our documentation site for detailed information on how to use CodeRabbit.
  • Join our Discord community to connect with other users and get help from the community.
  • Follow us on X/Twitter for updates and announcements.

@vr4manta

Copy link
Copy Markdown
Contributor Author

@coderabbitai summary

@coderabbitai

coderabbitai Bot commented Jun 17, 2026

Copy link
Copy Markdown
✅ Action performed

Summary regeneration triggered.

@vr4manta vr4manta marked this pull request as ready for review June 17, 2026 12:12
@openshift-ci openshift-ci Bot removed the do-not-merge/work-in-progress Indicates that a PR should not merge because it is a work in progress. label Jun 17, 2026
@openshift-ci openshift-ci Bot requested review from damdo and nrb June 17, 2026 12:14
@vr4manta vr4manta force-pushed the infra-vap branch 2 times, most recently from 866177d to cf0bb7c Compare June 17, 2026 13:27
@vr4manta

Copy link
Copy Markdown
Contributor Author

/test ?

@vr4manta

Copy link
Copy Markdown
Contributor Author

/test e2e-vsphere-ovn-techpreview e2e-vsphere-ovn-techpreview-serial e2e-vsphere-ovn e2e-vsphere-ovn-serial

@vr4manta

Copy link
Copy Markdown
Contributor Author

/assign @JoelSpeed
Hi Joel, can you take a look at this PR and let me know if this approach is OK.

@vr4manta

Copy link
Copy Markdown
Contributor Author

/test e2e-vsphere-ovn-techpreview e2e-vsphere-ovn-techpreview-serial e2e-vsphere-ovn e2e-vsphere-ovn-serial

@openshift-ci

openshift-ci Bot commented Jun 17, 2026

Copy link
Copy Markdown
Contributor

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by:
Once this PR has been reviewed and has the lgtm label, please ask for approval from joelspeed. 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

@openshift-ci

openshift-ci Bot commented Jun 17, 2026

Copy link
Copy Markdown
Contributor

@vr4manta: The following tests failed, say /retest to rerun all failed tests or /retest-required to rerun all mandatory failed tests:

Test name Commit Details Required Rerun command
ci/prow/e2e-metal-ipi 7cce8bf link true /test e2e-metal-ipi
ci/prow/e2e-vsphere-ovn-serial 7cce8bf link false /test e2e-vsphere-ovn-serial
ci/prow/e2e-vsphere-ovn 7cce8bf link false /test e2e-vsphere-ovn

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.

@JoelSpeed JoelSpeed left a comment

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.

I've left a couple of examples to make the CEL more concise, they apply to pretty much all of the CEL so PTAL at how you can use the optional orValue pattern across the rules you've got

Comment on lines +484 to +486
# The machine-api-operator service account must be able to read Machines,
# ControlPlaneMachineSets, and MachineSets so the kube-apiserver can resolve
# them as VAP params when validating Infrastructure/cluster updates.

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.

Really? Is that documented somewhere in the upstream docs you can reference?

I can see why it would make sense, but I've never thought about it like that before

Comment thread pkg/operator/sync.go
Comment on lines +286 to +289
featureGates, err := optr.featureGateAccessor.CurrentFeatureGates()
if err != nil {
return fmt.Errorf("failed to get current feature gates: %w", err)
}

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.

Do this earlier. The gates extracted here don't change, or, if they do, the whole bin exits. These can be extracted and held as a global in the optr struct earlier in the construction

Comment thread pkg/operator/sync.go
Comment on lines +297 to +326
if _, _, err := resourceapply.ApplyValidatingAdmissionPolicyV1(context.TODO(),
optr.kubeClient.AdmissionregistrationV1(), recorder,
mapiwebhooks.NewVSphereFailureDomainMachineVAP(), optr.cache); err != nil {
return err
}
if _, _, err := resourceapply.ApplyValidatingAdmissionPolicyBindingV1(context.TODO(),
optr.kubeClient.AdmissionregistrationV1(), recorder,
mapiwebhooks.NewVSphereFailureDomainMachineVAPBinding(), optr.cache); err != nil {
return err
}
if _, _, err := resourceapply.ApplyValidatingAdmissionPolicyV1(context.TODO(),
optr.kubeClient.AdmissionregistrationV1(), recorder,
mapiwebhooks.NewVSphereFailureDomainCPMSVAP(), optr.cache); err != nil {
return err
}
if _, _, err := resourceapply.ApplyValidatingAdmissionPolicyBindingV1(context.TODO(),
optr.kubeClient.AdmissionregistrationV1(), recorder,
mapiwebhooks.NewVSphereFailureDomainCPMSVAPBinding(), optr.cache); err != nil {
return err
}
if _, _, err := resourceapply.ApplyValidatingAdmissionPolicyV1(context.TODO(),
optr.kubeClient.AdmissionregistrationV1(), recorder,
mapiwebhooks.NewVSphereFailureDomainMachineSetVAP(), optr.cache); err != nil {
return err
}
if _, _, err := resourceapply.ApplyValidatingAdmissionPolicyBindingV1(context.TODO(),
optr.kubeClient.AdmissionregistrationV1(), recorder,
mapiwebhooks.NewVSphereFailureDomainMachineSetVAPBinding(), optr.cache); err != nil {
return err
}

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.

Please wrap each err to give us a unique error message per return

Comment thread pkg/webhooks/vap.go
Comment on lines +10 to +30
// VAPMachineFailureDomainName is the name of the ValidatingAdmissionPolicy that guards
// against removing a vSphere failure domain that is still referenced by a Machine.
VAPMachineFailureDomainName = "vsphere-failure-domain-in-use-by-machine"

// VAPCPMSFailureDomainName is the name of the ValidatingAdmissionPolicy that guards
// against removing a vSphere failure domain that is still referenced by a ControlPlaneMachineSet.
VAPCPMSFailureDomainName = "vsphere-failure-domain-in-use-by-cpms"

// VAPMachineSetFailureDomainName is the name of the ValidatingAdmissionPolicy that guards
// against removing a vSphere failure domain that is still referenced by a MachineSet (including
// MachineSets with zero replicas that would have no running Machines to catch the check).
VAPMachineSetFailureDomainName = "vsphere-failure-domain-in-use-by-machineset"

// vapMachineBindingName is the name of the binding for the Machine VAP.
vapMachineBindingName = "vsphere-failure-domain-in-use-by-machine"

// vapCPMSBindingName is the name of the binding for the CPMS VAP.
vapCPMSBindingName = "vsphere-failure-domain-in-use-by-cpms"

// vapMachineSetBindingName is the name of the binding for the MachineSet VAP.
vapMachineSetBindingName = "vsphere-failure-domain-in-use-by-machineset"

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.

Inconsistent casing on VAP here and duplication. Can we consolidate on one set of vars for the names

Comment thread pkg/webhooks/vap.go
Comment on lines +93 to +98
{
Name: "is-vsphere-platform",
Expression: `has(object.spec.platformSpec) &&
object.spec.platformSpec.type == "` + vspherePlatformType + `"`,
},
},

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.

Using status is more reliable for a platform check normally for the infrastructure object

Comment thread pkg/webhooks/vap.go
Comment on lines +104 to +107
Expression: `has(object.spec.platformSpec.vsphere) &&
has(object.spec.platformSpec.vsphere.failureDomains)
? object.spec.platformSpec.vsphere.failureDomains
: []`,

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.

This is equivalent

Suggested change
Expression: `has(object.spec.platformSpec.vsphere) &&
has(object.spec.platformSpec.vsphere.failureDomains)
? object.spec.platformSpec.vsphere.failureDomains
: []`,
Expression: `object.?spec.platformSpec.vsphere.failureDomains.orValue('[]')`,

Comment thread pkg/webhooks/vap.go
Comment on lines +95 to +96
Expression: `has(object.spec.platformSpec) &&
object.spec.platformSpec.type == "` + vspherePlatformType + `"`,

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.

This is equivalent

Suggested change
Expression: `has(object.spec.platformSpec) &&
object.spec.platformSpec.type == "` + vspherePlatformType + `"`,
Expression: `object.?spec.platformSpec.type.orValue("") == "` + vspherePlatformType + `"`,

Comment thread pkg/webhooks/vap.go
{
// machineRegion: the region label of the Machine param (empty string if absent).
Name: "machineRegion",
Expression: `has(params.metadata.labels) && "` + machineRegionLabel + `" in params.metadata.labels ? params.metadata.labels["` + machineRegionLabel + `"] : ""`,

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.

Use the optional pattern as I've shown in the previous examples to tidy this up too

Comment thread pkg/webhooks/vap.go
fd.region == variables.machineRegion && fd.zone == variables.machineZone
)`,
MessageExpression: `"Infrastructure update would remove vSphere failure domain (region=" + variables.machineRegion + ", zone=" + variables.machineZone + ") that is still in use by Machine '" + params.metadata.name + "'"`,
Reason: ptr.To(metav1.StatusReasonForbidden),

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.

Forbidden implies that another user could action this (it's a permissions issue), so use invalid instead

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

Labels

jira/valid-reference Indicates that this PR references a valid Jira ticket of any type.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants