volcano.sh/volcano@v1.9.0/pkg/webhooks/admission/pods/mutate/annotation.go (about)

     1  /*
     2  Copyright 2021 The Volcano 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 mutate
    18  
    19  import (
    20  	"github.com/imdario/mergo"
    21  	"gopkg.in/yaml.v2"
    22  	v1 "k8s.io/api/core/v1"
    23  	"k8s.io/klog/v2"
    24  
    25  	wkconfig "volcano.sh/volcano/pkg/webhooks/config"
    26  )
    27  
    28  type annotationResGroup struct{}
    29  
    30  const (
    31  	// defaultAnnotationKey: default annotation key
    32  	defaultAnnotationKey = "volcano.sh/resource-group"
    33  )
    34  
    35  // NewAnnotationResGroup create a new structure
    36  func NewAnnotationResGroup() ResGroup {
    37  	return &annotationResGroup{}
    38  }
    39  
    40  // getAnnotation get annotations from the resource group
    41  func getAnnotation(resGroupConfig wkconfig.ResGroupConfig) map[string]string {
    42  	annotations := make(map[string]string)
    43  	for _, val := range resGroupConfig.Object.Value {
    44  		tmp := make(map[string]string)
    45  		err := yaml.Unmarshal([]byte(val), &tmp)
    46  		if err != nil {
    47  			continue
    48  		}
    49  
    50  		if err := mergo.Merge(&annotations, &tmp); err != nil {
    51  			klog.Errorf("annotations merge failed, err=%v", err)
    52  			continue
    53  		}
    54  	}
    55  
    56  	return annotations
    57  }
    58  
    59  // IsBelongResGroup adjust whether pod is belong to the resource group
    60  func (resGroup *annotationResGroup) IsBelongResGroup(pod *v1.Pod, resGroupConfig wkconfig.ResGroupConfig) bool {
    61  	if resGroupConfig.Object.Key != "" && resGroupConfig.Object.Key != "annotation" {
    62  		return false
    63  	}
    64  
    65  	annotations := getAnnotation(resGroupConfig)
    66  	klog.V(3).Infof("annotations : %v", annotations)
    67  	for key, annotation := range annotations {
    68  		if pod.Annotations[key] == annotation {
    69  			return true
    70  		}
    71  	}
    72  
    73  	if resGroupConfig.Object.Key == "" && pod.Annotations[defaultAnnotationKey] == resGroupConfig.ResourceGroup {
    74  		return true
    75  	}
    76  
    77  	return false
    78  }