Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions api/core/v1alpha2/virtual_machine.go
Original file line number Diff line number Diff line change
Expand Up @@ -165,8 +165,9 @@ type CPUSpec struct {
Cores int `json:"cores"`

// Guaranteed share of CPU that will be allocated to the VM. Specified as a percentage.
// +kubebuilder:default:="100%"
// +kubebuilder:validation:Enum:={"5%", "10%", "25%", "50%", "100%"}
// The range of available values is defined in the VirtualMachineClass sizing policy.
// If not specified, the default value from the VirtualMachineClass will be used.
// +kubebuilder:validation:Pattern=`^(100|[1-9][0-9]?|[1-9])%$`
CoreFraction string `json:"coreFraction,omitempty"`
}

Expand Down
3 changes: 3 additions & 0 deletions api/core/v1alpha2/virtual_machine_class.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,9 @@ type SizingPolicy struct {
Memory *SizingPolicyMemory `json:"memory,omitempty"`
// Allowed values of the `coreFraction` parameter.
CoreFractions []CoreFractionValue `json:"coreFractions,omitempty"`
// Default core fraction value for the VirtualMachineClass.
// This value will be used when creating a VM without an explicitly specified coreFraction.
DefaultCoreFraction *CoreFractionValue `json:"defaultCoreFraction,omitempty"`
// Allowed values of the `dedicatedCores` parameter.
DedicatedCores []bool `json:"dedicatedCores,omitempty"`
// The policy applies for a specified range of the number of CPU cores.
Expand Down
5 changes: 5 additions & 0 deletions api/core/v1alpha2/zz_generated.deepcopy.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions api/core/v1alpha3/virtual_machine_class.go
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,8 @@ type SizingPolicy struct {
Memory *SizingPolicyMemory `json:"memory,omitempty"`
// Allowed values of the `coreFraction` parameter in percentages (e.g., "5%", "10%", "25%", "50%", "100%").
CoreFractions []CoreFractionValue `json:"coreFractions,omitempty"`
// Default core fraction value for the VirtualMachineClass.
DefaultCoreFraction *CoreFractionValue `json:"defaultCoreFraction,omitempty"`
// Allowed values of the `dedicatedCores` parameter.
DedicatedCores []bool `json:"dedicatedCores,omitempty"`
// The policy applies for a specified range of the number of CPU cores.
Expand Down
19 changes: 19 additions & 0 deletions api/core/v1alpha3/virtual_machine_class_conversion.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,20 @@ func convertSpecV3ToV2(v3Spec VirtualMachineClassSpec) (v1alpha2.VirtualMachineC
}
}

if v3Policy.DefaultCoreFraction != nil {
fractionStr := string(*v3Policy.DefaultCoreFraction)
if !regexp.MustCompile(`^([1-9]|[1-9][0-9]|100)%$`).MatchString(fractionStr) {
return v1alpha2.VirtualMachineClassSpec{}, fmt.Errorf("spec.sizingPolicies[%d].defaultCoreFraction: value must be a percentage between 1%% and 100%% (e.g., 5%%, 10%%, 50%%), got %q", i, fractionStr)
}
fractionStr = fractionStr[:len(fractionStr)-1]
fractionInt, err := strconv.Atoi(fractionStr)
if err != nil {
return v1alpha2.VirtualMachineClassSpec{}, fmt.Errorf("failed to parse default core fraction: %w", err)
}
v2Fraction := v1alpha2.CoreFractionValue(fractionInt)
v2Policy.DefaultCoreFraction = &v2Fraction
}

v2Spec.SizingPolicies[i] = v2Policy
}
}
Expand Down Expand Up @@ -191,6 +205,11 @@ func convertSpecV2ToV3(v2Spec v1alpha2.VirtualMachineClassSpec) VirtualMachineCl
}
}

if v2Policy.DefaultCoreFraction != nil {
v3Fraction := CoreFractionValue(fmt.Sprintf("%d%%", *v2Policy.DefaultCoreFraction))
v3Policy.DefaultCoreFraction = &v3Fraction
}

v3Spec.SizingPolicies[i] = v3Policy
}
}
Expand Down
5 changes: 5 additions & 0 deletions api/core/v1alpha3/zz_generated.deepcopy.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions crds/doc-ru-virtualmachineclasses.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,10 @@ spec:
coreFractions:
description: |
Допустимые значения параметра `coreFraction` в процентах (например, "5%", "10%", "25%", "50%", "100%").
defaultCoreFraction:
description: |
Значение coreFraction по умолчанию для VirtualMachineClass.
Это значение будет использовано при создании ВМ без явно указанного coreFraction.
cores:
description: |
Политика применяется для заданного диапазона числа ядер CPU.
Expand Down
2 changes: 1 addition & 1 deletion crds/doc-ru-virtualmachines.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -383,7 +383,7 @@ spec:
properties:
coreFraction:
description: |
Гарантированная доля времени CPU, которая будет выделена ВМ. Указывается в процентах. Диапазон доступных значений задаётся параметром `sizePolicy` в используемом VirtualMachineClass; если он не указан, используйте значения в диапазоне 1–100%.
Гарантированная доля времени CPU, которая будет выделена ВМ. Указывается в процентах. Диапазон доступных значений задаётся параметром `sizePolicy` в используемом VirtualMachineClass; если он не указан, используйте значения в диапазоне 1–100%. Если значение не указано, используется значение по умолчанию, которое задаётся параметром `sizePolicy` в используемом VirtualMachineClass.
cores:
description: |
Количество ядер.
Expand Down
10 changes: 10 additions & 0 deletions crds/virtualmachineclasses.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -281,6 +281,13 @@ spec:
items:
type: boolean
type: array
defaultCoreFraction:
description: |-
Default core fraction value for the VirtualMachineClass.
This value will be used when creating a VM without an explicitly specified coreFraction.
maximum: 100
minimum: 1
type: integer
memory:
description: Memory sizing policy.
properties:
Expand Down Expand Up @@ -775,6 +782,9 @@ spec:
items:
type: boolean
type: array
defaultCoreFraction:
description: Default core fraction value for the VirtualMachineClass.
type: string
memory:
description: Memory sizing policy.
properties:
Expand Down
5 changes: 2 additions & 3 deletions crds/virtualmachines.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ spec:
properties:
spec:
x-kubernetes-validations:
- rule: "self.cpu.coreFraction.endsWith('%') && int(self.cpu.coreFraction.replace('%', '')) >= 1 && int(self.cpu.coreFraction.replace('%', '')) <= 100"
- rule: "!has(self.cpu.coreFraction) || (self.cpu.coreFraction.endsWith('%') && int(self.cpu.coreFraction.replace('%', '')) >= 1 && int(self.cpu.coreFraction.replace('%', '')) <= 100)"
message: "Core fraction must be between 1% and 100%."
type: object
required:
Expand Down Expand Up @@ -888,9 +888,8 @@ spec:
description: Number of cores.
coreFraction:
type: string
default: "100%"
description: |
Guaranteed share of CPU time that will be allocated to the VM. Specified as a percentage. The range of available values is set in the `sizePolicy` parameter of the VirtualMachineClass; if it is not set, use values within the 1–100% range.
Guaranteed share of CPU time that will be allocated to the VM. Specified as a percentage. The range of available values is set in the `sizePolicy` parameter of the VirtualMachineClass. If not specified, the default value from the VirtualMachineClass sizing policy will be used. If no default is set in the class, "100%" will be applied.

memory:
type: object
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
/*
Copyright 2025 Flant JSC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package defaulter

import (
"context"
"fmt"

"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client"

"github.com/deckhouse/virtualization/api/core/v1alpha2"
"github.com/deckhouse/virtualization/api/core/v1alpha3"
)

type CoreFractionDefaulter struct {
client client.Client
}

func NewCoreFractionDefaulter(client client.Client) *CoreFractionDefaulter {
return &CoreFractionDefaulter{
client: client,
}
}

func (d *CoreFractionDefaulter) Default(ctx context.Context, vm *v1alpha2.VirtualMachine) error {
// Skip if coreFraction is already set.
if vm.Spec.CPU.CoreFraction != "" {
return nil
}

// Skip if vmClassName is not set (will be handled by validation later).
if vm.Spec.VirtualMachineClassName == "" {
return nil
}

// Get the VMClass.
vmClass := &v1alpha3.VirtualMachineClass{}
err := d.client.Get(ctx, types.NamespacedName{Name: vm.Spec.VirtualMachineClassName}, vmClass)
if err != nil {
return fmt.Errorf("failed to get VirtualMachineClass %q: %w", vm.Spec.VirtualMachineClassName, err)
}

// Find the matching sizing policy based on CPU cores.
defaultCoreFraction := d.getDefaultCoreFraction(vm, vmClass)
if defaultCoreFraction != "" {
vm.Spec.CPU.CoreFraction = defaultCoreFraction
}

return nil
}

// getDefaultCoreFraction finds the default core fraction from the VMClass sizing policy
// that matches the VM's CPU cores count.
func (d *CoreFractionDefaulter) getDefaultCoreFraction(vm *v1alpha2.VirtualMachine, vmClass *v1alpha3.VirtualMachineClass) string {
const defaultValue = "100%"

if vmClass == nil || len(vmClass.Spec.SizingPolicies) == 0 {
return defaultValue
}

for _, sp := range vmClass.Spec.SizingPolicies {
if sp.Cores == nil {
continue
}

// Check if VM's cores fall within this policy's range.
if vm.Spec.CPU.Cores >= sp.Cores.Min && vm.Spec.CPU.Cores <= sp.Cores.Max {
if sp.DefaultCoreFraction != nil {
return string(*sp.DefaultCoreFraction)
}
return defaultValue
Copy link
Contributor

Choose a reason for hiding this comment

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

defaultValue may not be included in .vmClass.coreFractions. It looks like we should return an error here.

}
}

return defaultValue
}
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,7 @@ func NewDefaulter(client client.Client, vmClassService *service.VirtualMachineCl
return &Defaulter{
defaulters: []VirtualMachineDefaulter{
defaulter.NewVirtualMachineClassNameDefaulter(client, vmClassService),
defaulter.NewCoreFractionDefaulter(client),
},
log: log.With("webhook", "mutating"),
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/*
Copyright 2024 Flant JSC

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package validators

import (
"context"
"fmt"
"slices"

"sigs.k8s.io/controller-runtime/pkg/webhook/admission"

"github.com/deckhouse/virtualization/api/core/v1alpha2"
)

type DefaultCoreFractionValidator struct{}

func NewDefaultCoreFractionValidator() *DefaultCoreFractionValidator {
return &DefaultCoreFractionValidator{}
}

func (v *DefaultCoreFractionValidator) ValidateCreate(_ context.Context, vmclass *v1alpha2.VirtualMachineClass) (admission.Warnings, error) {
return nil, v.validate(vmclass)
}

func (v *DefaultCoreFractionValidator) ValidateUpdate(_ context.Context, _, newVMClass *v1alpha2.VirtualMachineClass) (admission.Warnings, error) {
return nil, v.validate(newVMClass)
}

func (v *DefaultCoreFractionValidator) validate(vmclass *v1alpha2.VirtualMachineClass) error {
for i, policy := range vmclass.Spec.SizingPolicies {
if policy.DefaultCoreFraction == nil {
continue
}

if len(policy.CoreFractions) == 0 {
continue
}

if !slices.Contains(policy.CoreFractions, *policy.DefaultCoreFraction) {
return fmt.Errorf("vmclass %s sizingPolicy[%d]: defaultCoreFraction %d is not in the allowed coreFractions list %v",
vmclass.Name, i, *policy.DefaultCoreFraction, policy.CoreFractions)
}
}

return nil
}
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ func NewValidator(client client.Client, log *log.Logger, recorder eventrecord.Ev
validators.NewSizingPoliciesValidator(client),
validators.NewPolicyChangesValidator(recorder),
validators.NewSingleDefaultClassValidator(client, vmClassService),
validators.NewDefaultCoreFractionValidator(),
},
log: log.With("webhook", "validation"),
}
Expand Down
Loading