| 1 |
/* |
| 2 |
Copyright 2021 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 ephemeral provides code that supports the usual pattern |
| 18 |
// for accessing the PVC that provides a generic ephemeral inline volume: |
| 19 |
// |
| 20 |
// - determine the PVC name that corresponds to the inline volume source |
| 21 |
// - retrieve the PVC |
| 22 |
// - verify that the PVC is owned by the pod |
| 23 |
// - use the PVC |
| 24 |
package ephemeral |
| 25 |
|
| 26 |
import ( |
| 27 |
"fmt" |
| 28 |
|
| 29 |
v1 "k8s.io/api/core/v1" |
| 30 |
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
| 31 |
) |
| 32 |
|
| 33 |
// VolumeClaimName returns the name of the PersistentVolumeClaim |
| 34 |
// object that gets created for the generic ephemeral inline volume. The |
| 35 |
// name is deterministic and therefore this function does not need any |
| 36 |
// additional information besides the Pod name and volume name and it |
| 37 |
// will never fail. |
| 38 |
// |
| 39 |
// Before using the PVC for the Pod, the caller must check that it is |
| 40 |
// indeed the PVC that was created for the Pod by calling IsUsable. |
| 41 |
func VolumeClaimName(pod *v1.Pod, volume *v1.Volume) string { |
| 42 |
return pod.Name + "-" + volume.Name |
| 43 |
} |
| 44 |
|
| 45 |
// VolumeIsForPod checks that the PVC is the ephemeral volume that |
| 46 |
// was created for the Pod. It returns an error that is informative |
| 47 |
// enough to be returned by the caller without adding further details |
| 48 |
// about the Pod or PVC. |
| 49 |
func VolumeIsForPod(pod *v1.Pod, pvc *v1.PersistentVolumeClaim) error { |
| 50 |
// Checking the namespaces is just a precaution. The caller should |
| 51 |
// never pass in a PVC that isn't from the same namespace as the |
| 52 |
// Pod. |
| 53 |
if pvc.Namespace != pod.Namespace || !metav1.IsControlledBy(pvc, pod) { |
| 54 |
return fmt.Errorf("PVC %s/%s was not created for pod %s/%s (pod is not owner)", pvc.Namespace, pvc.Name, pod.Namespace, pod.Name) |
| 55 |
} |
| 56 |
return nil |
| 57 |
} |