1/* 2Copyright 2020 The Kubernetes Authors. 3 4Licensed under the Apache License, Version 2.0 (the "License"); 5you may not use this file except in compliance with the License. 6You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10Unless required by applicable law or agreed to in writing, software 11distributed under the License is distributed on an "AS IS" BASIS, 12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13See the License for the specific language governing permissions and 14limitations under the License. 15*/ 16 17package common 18 19import ( 20 "fmt" 21 22 v1 "k8s.io/api/core/v1" 23 utilfeature "k8s.io/apiserver/pkg/util/feature" 24 "k8s.io/client-go/tools/cache" 25 "k8s.io/kubernetes/pkg/features" 26) 27 28const ( 29 // PodPVCIndex is the lookup name for the index function, which is to index by pod pvcs. 30 PodPVCIndex = "pod-pvc-index" 31) 32 33// PodPVCIndexFunc creates an index function that returns PVC keys (= 34// namespace/name) for given pod. If enabled, this includes the PVCs 35// that might be created for generic ephemeral volumes. 36func PodPVCIndexFunc(genericEphemeralVolumeFeatureEnabled bool) func(obj interface{}) ([]string, error) { 37 return func(obj interface{}) ([]string, error) { 38 pod, ok := obj.(*v1.Pod) 39 if !ok { 40 return []string{}, nil 41 } 42 keys := []string{} 43 for _, podVolume := range pod.Spec.Volumes { 44 claimName := "" 45 if pvcSource := podVolume.VolumeSource.PersistentVolumeClaim; pvcSource != nil { 46 claimName = pvcSource.ClaimName 47 } 48 if ephemeralSource := podVolume.VolumeSource.Ephemeral; genericEphemeralVolumeFeatureEnabled && ephemeralSource != nil { 49 claimName = pod.Name + "-" + podVolume.Name 50 } 51 if claimName != "" { 52 keys = append(keys, fmt.Sprintf("%s/%s", pod.Namespace, claimName)) 53 } 54 } 55 return keys, nil 56 } 57} 58 59// AddPodPVCIndexerIfNotPresent adds the PodPVCIndexFunc with the current global setting for GenericEphemeralVolume. 60func AddPodPVCIndexerIfNotPresent(indexer cache.Indexer) error { 61 return AddIndexerIfNotPresent(indexer, PodPVCIndex, 62 PodPVCIndexFunc(utilfeature.DefaultFeatureGate.Enabled(features.GenericEphemeralVolume))) 63} 64 65// AddIndexerIfNotPresent adds the index function with the name into the cache indexer if not present 66func AddIndexerIfNotPresent(indexer cache.Indexer, indexName string, indexFunc cache.IndexFunc) error { 67 indexers := indexer.GetIndexers() 68 if _, ok := indexers[indexName]; ok { 69 return nil 70 } 71 return indexer.AddIndexers(cache.Indexers{indexName: indexFunc}) 72} 73