csi_util.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. /*
  2. Copyright 2018 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package csi
  14. import (
  15. "context"
  16. "encoding/json"
  17. "errors"
  18. "fmt"
  19. "os"
  20. "path/filepath"
  21. "time"
  22. api "k8s.io/api/core/v1"
  23. meta "k8s.io/apimachinery/pkg/apis/meta/v1"
  24. utilfeature "k8s.io/apiserver/pkg/util/feature"
  25. "k8s.io/client-go/kubernetes"
  26. "k8s.io/klog"
  27. "k8s.io/kubernetes/pkg/features"
  28. "k8s.io/kubernetes/pkg/volume"
  29. utilstrings "k8s.io/utils/strings"
  30. )
  31. const (
  32. // TestInformerSyncPeriod is informer sync period duration for testing
  33. TestInformerSyncPeriod = 100 * time.Millisecond
  34. // TestInformerSyncTimeout is informer timeout duration for testing
  35. TestInformerSyncTimeout = 30 * time.Second
  36. )
  37. func getCredentialsFromSecret(k8s kubernetes.Interface, secretRef *api.SecretReference) (map[string]string, error) {
  38. credentials := map[string]string{}
  39. secret, err := k8s.CoreV1().Secrets(secretRef.Namespace).Get(context.TODO(), secretRef.Name, meta.GetOptions{})
  40. if err != nil {
  41. return credentials, errors.New(log("failed to find the secret %s in the namespace %s with error: %v", secretRef.Name, secretRef.Namespace, err))
  42. }
  43. for key, value := range secret.Data {
  44. credentials[key] = string(value)
  45. }
  46. return credentials, nil
  47. }
  48. // saveVolumeData persists parameter data as json file at the provided location
  49. func saveVolumeData(dir string, fileName string, data map[string]string) error {
  50. dataFilePath := filepath.Join(dir, fileName)
  51. klog.V(4).Info(log("saving volume data file [%s]", dataFilePath))
  52. file, err := os.Create(dataFilePath)
  53. if err != nil {
  54. return errors.New(log("failed to save volume data file %s: %v", dataFilePath, err))
  55. }
  56. defer file.Close()
  57. if err := json.NewEncoder(file).Encode(data); err != nil {
  58. return errors.New(log("failed to save volume data file %s: %v", dataFilePath, err))
  59. }
  60. klog.V(4).Info(log("volume data file saved successfully [%s]", dataFilePath))
  61. return nil
  62. }
  63. // loadVolumeData loads volume info from specified json file/location
  64. func loadVolumeData(dir string, fileName string) (map[string]string, error) {
  65. // remove /mount at the end
  66. dataFileName := filepath.Join(dir, fileName)
  67. klog.V(4).Info(log("loading volume data file [%s]", dataFileName))
  68. file, err := os.Open(dataFileName)
  69. if err != nil {
  70. return nil, errors.New(log("failed to open volume data file [%s]: %v", dataFileName, err))
  71. }
  72. defer file.Close()
  73. data := map[string]string{}
  74. if err := json.NewDecoder(file).Decode(&data); err != nil {
  75. return nil, errors.New(log("failed to parse volume data file [%s]: %v", dataFileName, err))
  76. }
  77. return data, nil
  78. }
  79. func getCSISourceFromSpec(spec *volume.Spec) (*api.CSIPersistentVolumeSource, error) {
  80. return getPVSourceFromSpec(spec)
  81. }
  82. func getReadOnlyFromSpec(spec *volume.Spec) (bool, error) {
  83. if spec.PersistentVolume != nil &&
  84. spec.PersistentVolume.Spec.CSI != nil {
  85. return spec.ReadOnly, nil
  86. }
  87. return false, fmt.Errorf("CSIPersistentVolumeSource not defined in spec")
  88. }
  89. // log prepends log string with `kubernetes.io/csi`
  90. func log(msg string, parts ...interface{}) string {
  91. return fmt.Sprintf(fmt.Sprintf("%s: %s", CSIPluginName, msg), parts...)
  92. }
  93. // getVolumePluginDir returns the path where CSI plugin keeps metadata for given volume
  94. func getVolumePluginDir(specVolID string, host volume.VolumeHost) string {
  95. sanitizedSpecVolID := utilstrings.EscapeQualifiedName(specVolID)
  96. return filepath.Join(host.GetVolumeDevicePluginDir(CSIPluginName), sanitizedSpecVolID)
  97. }
  98. // getVolumeDevicePluginDir returns the path where the CSI plugin keeps the
  99. // symlink for a block device associated with a given specVolumeID.
  100. // path: plugins/kubernetes.io/csi/volumeDevices/{specVolumeID}/dev
  101. func getVolumeDevicePluginDir(specVolID string, host volume.VolumeHost) string {
  102. return filepath.Join(getVolumePluginDir(specVolID, host), "dev")
  103. }
  104. // getVolumeDeviceDataDir returns the path where the CSI plugin keeps the
  105. // volume data for a block device associated with a given specVolumeID.
  106. // path: plugins/kubernetes.io/csi/volumeDevices/{specVolumeID}/data
  107. func getVolumeDeviceDataDir(specVolID string, host volume.VolumeHost) string {
  108. return filepath.Join(getVolumePluginDir(specVolID, host), "data")
  109. }
  110. // hasReadWriteOnce returns true if modes contains v1.ReadWriteOnce
  111. func hasReadWriteOnce(modes []api.PersistentVolumeAccessMode) bool {
  112. if modes == nil {
  113. return false
  114. }
  115. for _, mode := range modes {
  116. if mode == api.ReadWriteOnce {
  117. return true
  118. }
  119. }
  120. return false
  121. }
  122. // getSourceFromSpec returns either CSIVolumeSource or CSIPersistentVolumeSource, but not both
  123. func getSourceFromSpec(spec *volume.Spec) (*api.CSIVolumeSource, *api.CSIPersistentVolumeSource, error) {
  124. if spec == nil {
  125. return nil, nil, fmt.Errorf("volume.Spec nil")
  126. }
  127. if spec.Volume != nil && spec.PersistentVolume != nil {
  128. return nil, nil, fmt.Errorf("volume.Spec has both volume and persistent volume sources")
  129. }
  130. if spec.Volume != nil && spec.Volume.CSI != nil && utilfeature.DefaultFeatureGate.Enabled(features.CSIInlineVolume) {
  131. return spec.Volume.CSI, nil, nil
  132. }
  133. if spec.PersistentVolume != nil &&
  134. spec.PersistentVolume.Spec.CSI != nil {
  135. return nil, spec.PersistentVolume.Spec.CSI, nil
  136. }
  137. return nil, nil, fmt.Errorf("volume source not found in volume.Spec")
  138. }
  139. // getPVSourceFromSpec ensures only CSIPersistentVolumeSource is present in volume.Spec
  140. func getPVSourceFromSpec(spec *volume.Spec) (*api.CSIPersistentVolumeSource, error) {
  141. volSrc, pvSrc, err := getSourceFromSpec(spec)
  142. if err != nil {
  143. return nil, err
  144. }
  145. if volSrc != nil {
  146. return nil, fmt.Errorf("unexpected api.CSIVolumeSource found in volume.Spec")
  147. }
  148. return pvSrc, nil
  149. }