Skip to content

fix(webhook): process InitContainers during admission and quota checks - #2560

Closed
Rickydama3 wants to merge 1 commit into
Project-HAMi:masterfrom
Rickydama3:fix-initcontainer-webhook
Closed

fix(webhook): process InitContainers during admission and quota checks#2560
Rickydama3 wants to merge 1 commit into
Project-HAMi:masterfrom
Rickydama3:fix-initcontainer-webhook

Conversation

@Rickydama3

@Rickydama3 Rickydama3 commented Aug 10, 2026

Copy link
Copy Markdown
Contributor

What type of PR is this?

/kind bug

What this PR does / why we need it:
This PR fixes a critical bug where the mutating admission webhook (pkg/scheduler/webhook.go) completely ignored InitContainers, leading to GPU quota bypasses and pod scheduling failures.

The Problem

Previously, the Handle() function and the fitResourceQuota() function in the webhook only iterated through pod.Spec.Containers. This caused two major issues:

  1. Scheduling Failures (Bypassing HAMi): If a pod requested HAMi GPUs exclusively inside an InitContainer, the webhook's hasResource flag remained false. As a result, the webhook did not mutate pod.Spec.SchedulerName to hami-scheduler, causing the pod to be scheduled by the default Kubernetes scheduler without proper GPU allocation.
  2. Quota Bypass: The fitResourceQuota function never parsed the requests of InitContainers. A malicious or unaware user could request GPUs inside an InitContainer and bypass the configured HAMi cluster resource quotas entirely.

Note: This was strictly an admission webhook issue; the scheduler backend (pkg/device/devices.go) was already correctly parsing and allocating resources for InitContainers.

The Solution

  1. Admission Mutation: Updated the Handle() loop to iterate over pod.Spec.InitContainers in addition to pod.Spec.Containers. This ensures that the webhook executes MutateAdmission for each InitContainer, correctly setting hasResource = true, and mutating the SchedulerName to use HAMi.
  2. Quota Validation: Updated fitResourceQuota() to calculate resource quotas for InitContainers. Since InitContainers run sequentially and complete before regular containers start, the effective resource limit for a Pod is MAX(max(initContainers), sum(regularContainers)).
    • The webhook now calculates the maximum GPU memory/core requirement across all InitContainers.
    • It then calculates the sum of the GPU memory/core requirements across all Containers.
    • It enforces quota limits using the maximum of these two values, perfectly matching standard Kubernetes resource allocation logic.
  3. Tests: Added TestInitContainersWebhook to webhook_test.go to explicitly verify that pods requesting resources only in an InitContainer are properly mutated, have their scheduler changed, and are verified against quotas.

Which issue(s) this PR fixes:
Fixes #2558

Special notes for your reviewer:
N/A

Does this PR introduce a user-facing change?:

Fix: Mutating admission webhook now correctly parses InitContainers, preventing GPU resource quota bypasses and ensuring proper scheduler routing.

Summary by CodeRabbit

  • New Features

    • Added a validated configuration schema for scheduler, device, topology, service, scaling, and feature settings.
    • Added support for detecting and mutating device resources requested by init containers.
    • Improved resource quota calculations to follow Kubernetes init-container resource semantics.
  • Bug Fixes

    • Pods requesting GPU resources in init containers are now admitted and scheduled correctly.
  • Tests

    • Added coverage for init-container GPU scheduling behavior.

@hami-robot hami-robot Bot added kind/bug Something isn't working dco-signoff: yes labels Aug 10, 2026
@hami-robot
hami-robot Bot requested a review from DSFans2014 August 10, 2026 23:00
@hami-robot

hami-robot Bot commented Aug 10, 2026

Copy link
Copy Markdown
Contributor

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by: leodon33
Once this PR has been reviewed and has the lgtm label, please assign wawa0210 for approval. For more information see the Kubernetes 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

@hami-robot
hami-robot Bot requested a review from FouoF August 10, 2026 23:00
@hami-robot hami-robot Bot added the size/L label Aug 10, 2026
@coderabbitai

coderabbitai Bot commented Aug 10, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Adds a Draft-07 Helm values schema for HAMI charts. Updates the admission webhook to mutate init containers and apply Kubernetes init-container resource semantics during quota checks. Adds regression coverage for GPU requests in init containers.

Changes

Helm values schema

Layer / File(s) Summary
Chart values validation
charts/hami/values.schema.json
Adds validation for scheduler, device-plugin, service, scaling, topology, feature-toggle, and device-specific configuration values.

Init-container admission handling

Layer / File(s) Summary
Init-container device mutation
pkg/scheduler/webhook.go
Mutates init containers before regular containers. Mutation failures return an internal-server-error response. Init-container resources set the resource-detection flag.
Init-container quota accounting
pkg/scheduler/webhook.go, pkg/scheduler/webhook_test.go
Uses the greater of init-container requirements and regular-container totals for quota validation. Adds admission coverage for GPU resources in init containers.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Possibly related issues

Possibly related PRs

Suggested reviewers: archlitchi

Poem

A rabbit checks the chart by moonlit light,
Then hops through init containers in flight.
GPU requests now join the queue,
Quotas count their max values too.
The scheduler patch lands bright and true.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning The HAMI chart values schema is unrelated to the linked issue and the webhook objectives. Remove charts/hami/values.schema.json from this pull request or link it to a separate objective.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the webhook changes for init-container admission and quota processing.
Linked Issues check ✅ Passed The changes address issue #2558 by mutating init containers, selecting hami-scheduler, and applying the required quota formula.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches 💡 2
⚔️ Resolve merge conflicts 💡
  • Resolve merge conflict in branch fix-initcontainer-webhook
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch
🧪 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.

@coderabbitai
coderabbitai Bot requested a review from archlitchi August 10, 2026 23:01
This fixes a bug where the mutating admission webhook completely ignored
InitContainers, which allowed users to bypass the HAMi scheduler and
GPU resource quotas if they only requested GPUs in an InitContainer.

The webhook now correctly parses InitContainers, mutates the Pod scheduler
name, and validates quotas using MAX(max(init_reqs), sum(container_reqs)).

Fixes Project-HAMi#2558

Signed-off-by: Ricky Dama <rickydama2006@gmail.com>

@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: 1

🧹 Nitpick comments (1)
pkg/scheduler/webhook_test.go (1)

1099-1107: 📐 Maintainability & Code Quality | 🔵 Trivial | 🏗️ Heavy lift

Add a quota-rejection case for init-container resources.

This init container requests only hami.io/gpu. The configured default memory and core values are zero. GenerateResourceRequests therefore produces zero memory and core demand, and fitResourceQuota skips FitQuota.

The test verifies scheduler mutation only. It will still pass if init-container quota aggregation is removed. Configure non-zero init memory or cores, set a rejecting quota, and assert that admission is denied.

🤖 Prompt for 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.

In `@pkg/scheduler/webhook_test.go` around lines 1099 - 1107, Extend the
init-container resource test around GenerateResourceRequests and
fitResourceQuota with non-zero memory or core requests, configure the resource
quota to reject that demand, and assert admission is denied. Keep the existing
GPU mutation coverage while ensuring quota rejection depends on init-container
resource aggregation rather than zero-valued defaults.
🤖 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 `@charts/hami/values.schema.json`:
- Around line 46-48: Update the customURL.port schema property to validate TCP
ports from 1 through 65535 by adding the appropriate minimum and maximum
constraints alongside its integer type.

---

Nitpick comments:
In `@pkg/scheduler/webhook_test.go`:
- Around line 1099-1107: Extend the init-container resource test around
GenerateResourceRequests and fitResourceQuota with non-zero memory or core
requests, configure the resource quota to reject that demand, and assert
admission is denied. Keep the existing GPU mutation coverage while ensuring
quota rejection depends on init-container resource aggregation rather than
zero-valued defaults.
🪄 Autofix

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: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 230a196b-7cf4-4a25-bd2c-02869354fa9f

📥 Commits

Reviewing files that changed from the base of the PR and between 91f0248 and 1c9605f.

📒 Files selected for processing (3)
  • charts/hami/values.schema.json
  • pkg/scheduler/webhook.go
  • pkg/scheduler/webhook_test.go

Comment thread charts/hami/values.schema.json Outdated
Comment on lines +46 to +48
"port": {
"type": "integer"
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Constrain customURL.port to the valid TCP port range.

Line 47 accepts negative values, zero, and values above 65535. The webhook template renders this value directly into clientConfig.url. Reject invalid ports before Helm renders an unusable webhook endpoint.

Proposed fix
 "port": {
-  "type": "integer"
+  "type": "integer",
+  "minimum": 1,
+  "maximum": 65535
 }
📝 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.

Suggested change
"port": {
"type": "integer"
}
"port": {
"type": "integer",
"minimum": 1,
"maximum": 65535
}
🤖 Prompt for 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.

In `@charts/hami/values.schema.json` around lines 46 - 48, Update the
customURL.port schema property to validate TCP ports from 1 through 65535 by
adding the appropriate minimum and maximum constraints alongside its integer
type.

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] Mutating admission webhook ignores InitContainers, causing quota bypass and scheduling failures

1 participant