k8s.io/kubernetes@v1.29.3/pkg/controller/volume/common/common.go (about)

     1  /*
     2  Copyright 2020 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 common
    18  
    19  import (
    20  	"fmt"
    21  
    22  	v1 "k8s.io/api/core/v1"
    23  	"k8s.io/client-go/tools/cache"
    24  	"k8s.io/component-helpers/storage/ephemeral"
    25  )
    26  
    27  const (
    28  	// PodPVCIndex is the lookup name for the index function, which is to index by pod pvcs.
    29  	PodPVCIndex = "pod-pvc-index"
    30  )
    31  
    32  // PodPVCIndexFunc creates an index function that returns PVC keys (=
    33  // namespace/name) for given pod.  This includes the PVCs
    34  // that might be created for generic ephemeral volumes.
    35  func PodPVCIndexFunc() func(obj interface{}) ([]string, error) {
    36  	return func(obj interface{}) ([]string, error) {
    37  		pod, ok := obj.(*v1.Pod)
    38  		if !ok {
    39  			return []string{}, nil
    40  		}
    41  		keys := []string{}
    42  		for _, podVolume := range pod.Spec.Volumes {
    43  			claimName := ""
    44  			if pvcSource := podVolume.VolumeSource.PersistentVolumeClaim; pvcSource != nil {
    45  				claimName = pvcSource.ClaimName
    46  			} else if podVolume.VolumeSource.Ephemeral != nil {
    47  				claimName = ephemeral.VolumeClaimName(pod, &podVolume)
    48  			}
    49  			if claimName != "" {
    50  				keys = append(keys, fmt.Sprintf("%s/%s", pod.Namespace, claimName))
    51  			}
    52  		}
    53  		return keys, nil
    54  	}
    55  }
    56  
    57  // AddPodPVCIndexerIfNotPresent adds the PodPVCIndexFunc.
    58  func AddPodPVCIndexerIfNotPresent(indexer cache.Indexer) error {
    59  	return AddIndexerIfNotPresent(indexer, PodPVCIndex, PodPVCIndexFunc())
    60  }
    61  
    62  // AddIndexerIfNotPresent adds the index function with the name into the cache indexer if not present
    63  func AddIndexerIfNotPresent(indexer cache.Indexer, indexName string, indexFunc cache.IndexFunc) error {
    64  	indexers := indexer.GetIndexers()
    65  	if _, ok := indexers[indexName]; ok {
    66  		return nil
    67  	}
    68  	return indexer.AddIndexers(cache.Indexers{indexName: indexFunc})
    69  }