sigs.k8s.io/kueue@v0.6.2/pkg/controller/jobframework/workload_names.go (about)

     1  /*
     2  Copyright 2023 The Kubernetes 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 jobframework
    18  
    19  import (
    20  	"crypto/sha1"
    21  	"encoding/hex"
    22  	"fmt"
    23  	"strings"
    24  
    25  	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    26  	"k8s.io/apimachinery/pkg/runtime/schema"
    27  )
    28  
    29  const (
    30  	hashLength = 5
    31  	// 253 is the maximal length for a CRD name. We need to subtract one for '-', and the hash length.
    32  	maxPrefixLength = 252 - hashLength
    33  )
    34  
    35  func GetWorkloadNameForOwnerRef(owner *metav1.OwnerReference) (string, error) {
    36  	gv, err := schema.ParseGroupVersion(owner.APIVersion)
    37  	if err != nil {
    38  		return "", err
    39  	}
    40  	gvk := gv.WithKind(owner.Kind)
    41  	return GetWorkloadNameForOwnerWithGVK(owner.Name, gvk), nil
    42  }
    43  
    44  func GetWorkloadNameForOwnerWithGVK(ownerName string, ownerGVK schema.GroupVersionKind) string {
    45  	prefixedName := strings.ToLower(ownerGVK.Kind) + "-" + ownerName
    46  	if len(prefixedName) > maxPrefixLength {
    47  		prefixedName = prefixedName[:maxPrefixLength]
    48  	}
    49  	return prefixedName + "-" + getHash(ownerName, ownerGVK)[:hashLength]
    50  }
    51  
    52  func getHash(ownerName string, gvk schema.GroupVersionKind) string {
    53  	h := sha1.New()
    54  	h.Write([]byte(gvk.Kind))
    55  	h.Write([]byte("\n"))
    56  	h.Write([]byte(gvk.Group))
    57  	h.Write([]byte("\n"))
    58  	h.Write([]byte(ownerName))
    59  	return hex.EncodeToString(h.Sum(nil))
    60  }
    61  
    62  func GetOwnerKey(ownerGVK schema.GroupVersionKind) string {
    63  	return fmt.Sprintf(".metadata.ownerReferences[%s.%s]", ownerGVK.Group, ownerGVK.Kind)
    64  }