csi_util.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  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. // getVolumeDevicePluginDir returns the path where the CSI plugin keeps the
  94. // symlink for a block device associated with a given specVolumeID.
  95. // path: plugins/kubernetes.io/csi/volumeDevices/{specVolumeID}/dev
  96. func getVolumeDevicePluginDir(specVolID string, host volume.VolumeHost) string {
  97. sanitizedSpecVolID := utilstrings.EscapeQualifiedName(specVolID)
  98. return filepath.Join(host.GetVolumeDevicePluginDir(CSIPluginName), sanitizedSpecVolID, "dev")
  99. }
  100. // getVolumeDeviceDataDir returns the path where the CSI plugin keeps the
  101. // volume data for a block device associated with a given specVolumeID.
  102. // path: plugins/kubernetes.io/csi/volumeDevices/{specVolumeID}/data
  103. func getVolumeDeviceDataDir(specVolID string, host volume.VolumeHost) string {
  104. sanitizedSpecVolID := utilstrings.EscapeQualifiedName(specVolID)
  105. return filepath.Join(host.GetVolumeDevicePluginDir(CSIPluginName), sanitizedSpecVolID, "data")
  106. }
  107. // hasReadWriteOnce returns true if modes contains v1.ReadWriteOnce
  108. func hasReadWriteOnce(modes []api.PersistentVolumeAccessMode) bool {
  109. if modes == nil {
  110. return false
  111. }
  112. for _, mode := range modes {
  113. if mode == api.ReadWriteOnce {
  114. return true
  115. }
  116. }
  117. return false
  118. }
  119. // getSourceFromSpec returns either CSIVolumeSource or CSIPersistentVolumeSource, but not both
  120. func getSourceFromSpec(spec *volume.Spec) (*api.CSIVolumeSource, *api.CSIPersistentVolumeSource, error) {
  121. if spec == nil {
  122. return nil, nil, fmt.Errorf("volume.Spec nil")
  123. }
  124. if spec.Volume != nil && spec.PersistentVolume != nil {
  125. return nil, nil, fmt.Errorf("volume.Spec has both volume and persistent volume sources")
  126. }
  127. if spec.Volume != nil && spec.Volume.CSI != nil && utilfeature.DefaultFeatureGate.Enabled(features.CSIInlineVolume) {
  128. return spec.Volume.CSI, nil, nil
  129. }
  130. if spec.PersistentVolume != nil &&
  131. spec.PersistentVolume.Spec.CSI != nil {
  132. return nil, spec.PersistentVolume.Spec.CSI, nil
  133. }
  134. return nil, nil, fmt.Errorf("volume source not found in volume.Spec")
  135. }
  136. // getPVSourceFromSpec ensures only CSIPersistentVolumeSource is present in volume.Spec
  137. func getPVSourceFromSpec(spec *volume.Spec) (*api.CSIPersistentVolumeSource, error) {
  138. volSrc, pvSrc, err := getSourceFromSpec(spec)
  139. if err != nil {
  140. return nil, err
  141. }
  142. if volSrc != nil {
  143. return nil, fmt.Errorf("unexpected api.CSIVolumeSource found in volume.Spec")
  144. }
  145. return pvSrc, nil
  146. }