github.com/kubewharf/katalyst-core@v0.5.3/pkg/webhook/validating/vpa/policy_validator.go (about)

     1  /*
     2  Copyright 2022 The Katalyst Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package vpa
    18  
    19  import (
    20  	"fmt"
    21  
    22  	v1 "k8s.io/api/core/v1"
    23  
    24  	apis "github.com/kubewharf/katalyst-api/pkg/apis/autoscaling/v1alpha1"
    25  	katalystutil "github.com/kubewharf/katalyst-core/pkg/util/native"
    26  )
    27  
    28  // todo: make this configurable to support other resource types
    29  var valuableControlledResourceMap = map[v1.ResourceName]bool{
    30  	v1.ResourceMemory: true,
    31  	v1.ResourceCPU:    true,
    32  }
    33  
    34  // WebhookVPAPolicyValidator validate:
    35  // 1. if controlled resource are valid in vpa by checking if resource name in valuableControlledResourceMap
    36  // 2. if MinAllowed <= MaxAllowed
    37  type WebhookVPAPolicyValidator struct{}
    38  
    39  func NewWebhookVPAPolicyValidator() *WebhookVPAPolicyValidator {
    40  	return &WebhookVPAPolicyValidator{}
    41  }
    42  
    43  func (vp *WebhookVPAPolicyValidator) ValidateVPA(vpa *apis.KatalystVerticalPodAutoscaler) (valid bool, message string, err error) {
    44  	if vpa == nil {
    45  		err := fmt.Errorf("vpa is nil")
    46  		return false, err.Error(), err
    47  	}
    48  
    49  	for _, containerPolicy := range vpa.Spec.ResourcePolicy.ContainerPolicies {
    50  		for _, resource := range containerPolicy.ControlledResources {
    51  			if !valuableControlledResourceMap[resource] {
    52  				return false, fmt.Sprintf("%s is not a supported controlled resource", string(resource)), nil
    53  			}
    54  		}
    55  
    56  		for validResource := range valuableControlledResourceMap {
    57  			minAllowed, minExist := containerPolicy.MinAllowed[validResource]
    58  			maxAllowed, maxExist := containerPolicy.MaxAllowed[validResource]
    59  			if minExist && maxExist && katalystutil.IsResourceGreaterThan(minAllowed, maxAllowed) {
    60  				return false, fmt.Sprintf("minAllowed > maxAllowed in container policy"), nil
    61  			}
    62  		}
    63  	}
    64  
    65  	return true, "", nil
    66  }