csi_block.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  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. /*
  14. This file defines block volume related methods for CSI driver.
  15. CSI driver is responsible for staging/publishing volumes to their staging/publish paths.
  16. Mapping and unmapping of a device in a publish path to its global map path and its
  17. pod device map path are done by operation_executor through MapBlockVolume/UnmapBlockVolume
  18. (MapBlockVolume and UnmapBlockVolume take care for lock, symlink, and bind mount).
  19. Summary of block volume related CSI driver's methods are as follows:
  20. - GetGlobalMapPath returns a global map path,
  21. - GetPodDeviceMapPath returns a pod device map path and filename,
  22. - SetUpDevice calls CSI's NodeStageVolume and stage a volume to its staging path,
  23. - MapPodDevice calls CSI's NodePublishVolume and publish a volume to its publish path,
  24. - UnmapPodDevice calls CSI's NodeUnpublishVolume and unpublish a volume from its publish path,
  25. - TearDownDevice calls CSI's NodeUnstageVolume and unstage a volume from its staging path.
  26. These methods are called by below sequences:
  27. - operation_executor.MountVolume
  28. - csi.GetGlobalMapPath
  29. - csi.SetupDevice
  30. - NodeStageVolume
  31. - ASW.MarkDeviceAsMounted
  32. - csi.GetPodDeviceMapPath
  33. - csi.MapPodDevice
  34. - NodePublishVolume
  35. - util.MapBlockVolume
  36. - ASW.MarkVolumeAsMounted
  37. - operation_executor.UnmountVolume
  38. - csi.GetPodDeviceMapPath
  39. - util.UnmapBlockVolume
  40. - csi.UnmapPodDevice
  41. - NodeUnpublishVolume
  42. - ASW.MarkVolumeAsUnmounted
  43. - operation_executor.UnmountDevice
  44. - csi.TearDownDevice
  45. - NodeUnstageVolume
  46. - ASW.MarkDeviceAsUnmounted
  47. After successful MountVolume for block volume, directory structure will be like below:
  48. /dev/loopX ... Descriptor lock(Loopback device to mapFile under global map path)
  49. /var/lib/kubelet/plugins/kubernetes.io/csi/volumeDevices/{specName}/dev/ ... Global map path
  50. /var/lib/kubelet/plugins/kubernetes.io/csi/volumeDevices/{specName}/dev/{podUID} ... MapFile(Bind mount to publish Path)
  51. /var/lib/kubelet/plugins/kubernetes.io/csi/volumeDevices/staging/{specName} ... Staging path
  52. /var/lib/kubelet/plugins/kubernetes.io/csi/volumeDevices/publish/{specName}/{podUID} ... Publish path
  53. /var/lib/kubelet/pods/{podUID}/volumeDevices/kubernetes.io~csi/ ... Pod device map path
  54. /var/lib/kubelet/pods/{podUID}/volumeDevices/kubernetes.io~csi/{specName} ... MapFile(Symlink to publish path)
  55. */
  56. package csi
  57. import (
  58. "context"
  59. "errors"
  60. "fmt"
  61. "os"
  62. "path/filepath"
  63. "k8s.io/klog"
  64. "k8s.io/api/core/v1"
  65. storage "k8s.io/api/storage/v1"
  66. meta "k8s.io/apimachinery/pkg/apis/meta/v1"
  67. "k8s.io/apimachinery/pkg/types"
  68. "k8s.io/client-go/kubernetes"
  69. "k8s.io/kubernetes/pkg/volume"
  70. utilstrings "k8s.io/utils/strings"
  71. )
  72. type csiBlockMapper struct {
  73. csiClientGetter
  74. k8s kubernetes.Interface
  75. plugin *csiPlugin
  76. driverName csiDriverName
  77. specName string
  78. volumeID string
  79. readOnly bool
  80. spec *volume.Spec
  81. podUID types.UID
  82. volumeInfo map[string]string
  83. }
  84. var _ volume.BlockVolumeMapper = &csiBlockMapper{}
  85. var _ volume.CustomBlockVolumeMapper = &csiBlockMapper{}
  86. // GetGlobalMapPath returns a global map path (on the node) to a device file which will be symlinked to
  87. // Example: plugins/kubernetes.io/csi/volumeDevices/{specName}/dev
  88. func (m *csiBlockMapper) GetGlobalMapPath(spec *volume.Spec) (string, error) {
  89. dir := getVolumeDevicePluginDir(m.specName, m.plugin.host)
  90. klog.V(4).Infof(log("blockMapper.GetGlobalMapPath = %s", dir))
  91. return dir, nil
  92. }
  93. // getStagingPath returns a staging path for a directory (on the node) that should be used on NodeStageVolume/NodeUnstageVolume
  94. // Example: plugins/kubernetes.io/csi/volumeDevices/staging/{specName}
  95. func (m *csiBlockMapper) getStagingPath() string {
  96. return filepath.Join(m.plugin.host.GetVolumeDevicePluginDir(CSIPluginName), "staging", m.specName)
  97. }
  98. // getPublishPath returns a publish path for a file (on the node) that should be used on NodePublishVolume/NodeUnpublishVolume
  99. // Example: plugins/kubernetes.io/csi/volumeDevices/publish/{specName}/{podUID}
  100. func (m *csiBlockMapper) getPublishPath() string {
  101. return filepath.Join(m.plugin.host.GetVolumeDevicePluginDir(CSIPluginName), "publish", m.specName, string(m.podUID))
  102. }
  103. // GetPodDeviceMapPath returns pod's device file which will be mapped to a volume
  104. // returns: pods/{podUID}/volumeDevices/kubernetes.io~csi, {specName}
  105. func (m *csiBlockMapper) GetPodDeviceMapPath() (string, string) {
  106. path := m.plugin.host.GetPodVolumeDeviceDir(m.podUID, utilstrings.EscapeQualifiedName(CSIPluginName))
  107. klog.V(4).Infof(log("blockMapper.GetPodDeviceMapPath [path=%s; name=%s]", path, m.specName))
  108. return path, m.specName
  109. }
  110. // stageVolumeForBlock stages a block volume to stagingPath
  111. func (m *csiBlockMapper) stageVolumeForBlock(
  112. ctx context.Context,
  113. csi csiClient,
  114. accessMode v1.PersistentVolumeAccessMode,
  115. csiSource *v1.CSIPersistentVolumeSource,
  116. attachment *storage.VolumeAttachment,
  117. ) (string, error) {
  118. klog.V(4).Infof(log("blockMapper.stageVolumeForBlock called"))
  119. stagingPath := m.getStagingPath()
  120. klog.V(4).Infof(log("blockMapper.stageVolumeForBlock stagingPath set [%s]", stagingPath))
  121. // Check whether "STAGE_UNSTAGE_VOLUME" is set
  122. stageUnstageSet, err := csi.NodeSupportsStageUnstage(ctx)
  123. if err != nil {
  124. return "", errors.New(log("blockMapper.stageVolumeForBlock failed to check STAGE_UNSTAGE_VOLUME capability: %v", err))
  125. }
  126. if !stageUnstageSet {
  127. klog.Infof(log("blockMapper.stageVolumeForBlock STAGE_UNSTAGE_VOLUME capability not set. Skipping MountDevice..."))
  128. return "", nil
  129. }
  130. publishVolumeInfo := map[string]string{}
  131. if attachment != nil {
  132. publishVolumeInfo = attachment.Status.AttachmentMetadata
  133. }
  134. nodeStageSecrets := map[string]string{}
  135. if csiSource.NodeStageSecretRef != nil {
  136. nodeStageSecrets, err = getCredentialsFromSecret(m.k8s, csiSource.NodeStageSecretRef)
  137. if err != nil {
  138. return "", fmt.Errorf("failed to get NodeStageSecretRef %s/%s: %v",
  139. csiSource.NodeStageSecretRef.Namespace, csiSource.NodeStageSecretRef.Name, err)
  140. }
  141. }
  142. // Creating a stagingPath directory before call to NodeStageVolume
  143. if err := os.MkdirAll(stagingPath, 0750); err != nil {
  144. return "", errors.New(log("blockMapper.stageVolumeForBlock failed to create dir %s: %v", stagingPath, err))
  145. }
  146. klog.V(4).Info(log("blockMapper.stageVolumeForBlock created stagingPath directory successfully [%s]", stagingPath))
  147. // Request to stage a block volume to stagingPath.
  148. // Expected implementation for driver is creating driver specific resource on stagingPath and
  149. // attaching the block volume to the node.
  150. err = csi.NodeStageVolume(ctx,
  151. csiSource.VolumeHandle,
  152. publishVolumeInfo,
  153. stagingPath,
  154. fsTypeBlockName,
  155. accessMode,
  156. nodeStageSecrets,
  157. csiSource.VolumeAttributes,
  158. nil /* MountOptions */)
  159. if err != nil {
  160. return "", errors.New(log("blockMapper.stageVolumeForBlock failed: %v", err))
  161. }
  162. klog.V(4).Infof(log("blockMapper.stageVolumeForBlock successfully requested NodeStageVolume [%s]", stagingPath))
  163. return stagingPath, nil
  164. }
  165. // publishVolumeForBlock publishes a block volume to publishPath
  166. func (m *csiBlockMapper) publishVolumeForBlock(
  167. ctx context.Context,
  168. csi csiClient,
  169. accessMode v1.PersistentVolumeAccessMode,
  170. csiSource *v1.CSIPersistentVolumeSource,
  171. attachment *storage.VolumeAttachment,
  172. ) (string, error) {
  173. klog.V(4).Infof(log("blockMapper.publishVolumeForBlock called"))
  174. publishVolumeInfo := map[string]string{}
  175. if attachment != nil {
  176. publishVolumeInfo = attachment.Status.AttachmentMetadata
  177. }
  178. nodePublishSecrets := map[string]string{}
  179. var err error
  180. if csiSource.NodePublishSecretRef != nil {
  181. nodePublishSecrets, err = getCredentialsFromSecret(m.k8s, csiSource.NodePublishSecretRef)
  182. if err != nil {
  183. return "", errors.New(log("blockMapper.publishVolumeForBlock failed to get NodePublishSecretRef %s/%s: %v",
  184. csiSource.NodePublishSecretRef.Namespace, csiSource.NodePublishSecretRef.Name, err))
  185. }
  186. }
  187. publishPath := m.getPublishPath()
  188. // Setup a parent directory for publishPath before call to NodePublishVolume
  189. publishDir := filepath.Dir(publishPath)
  190. if err := os.MkdirAll(publishDir, 0750); err != nil {
  191. return "", errors.New(log("blockMapper.publishVolumeForBlock failed to create dir %s: %v", publishDir, err))
  192. }
  193. klog.V(4).Info(log("blockMapper.publishVolumeForBlock created directory for publishPath successfully [%s]", publishDir))
  194. // Request to publish a block volume to publishPath.
  195. // Expectation for driver is to place a block volume on the publishPath, by bind-mounting the device file on the publishPath or
  196. // creating device file on the publishPath.
  197. // Parent directory for publishPath is created by k8s, but driver is responsible for creating publishPath itself.
  198. // If driver doesn't implement NodeStageVolume, attaching the block volume to the node may be done, here.
  199. err = csi.NodePublishVolume(
  200. ctx,
  201. m.volumeID,
  202. m.readOnly,
  203. m.getStagingPath(),
  204. publishPath,
  205. accessMode,
  206. publishVolumeInfo,
  207. csiSource.VolumeAttributes,
  208. nodePublishSecrets,
  209. fsTypeBlockName,
  210. []string{},
  211. )
  212. if err != nil {
  213. return "", errors.New(log("blockMapper.publishVolumeForBlock failed: %v", err))
  214. }
  215. return publishPath, nil
  216. }
  217. // SetUpDevice ensures the device is attached returns path where the device is located.
  218. func (m *csiBlockMapper) SetUpDevice() error {
  219. if !m.plugin.blockEnabled {
  220. return errors.New("CSIBlockVolume feature not enabled")
  221. }
  222. klog.V(4).Infof(log("blockMapper.SetUpDevice called"))
  223. // Get csiSource from spec
  224. if m.spec == nil {
  225. return errors.New(log("blockMapper.SetUpDevice spec is nil"))
  226. }
  227. csiSource, err := getCSISourceFromSpec(m.spec)
  228. if err != nil {
  229. return errors.New(log("blockMapper.SetUpDevice failed to get CSI persistent source: %v", err))
  230. }
  231. driverName := csiSource.Driver
  232. skip, err := m.plugin.skipAttach(driverName)
  233. if err != nil {
  234. return errors.New(log("blockMapper.SetupDevice failed to check CSIDriver for %s: %v", driverName, err))
  235. }
  236. var attachment *storage.VolumeAttachment
  237. if !skip {
  238. // Search for attachment by VolumeAttachment.Spec.Source.PersistentVolumeName
  239. nodeName := string(m.plugin.host.GetNodeName())
  240. attachID := getAttachmentName(csiSource.VolumeHandle, csiSource.Driver, nodeName)
  241. attachment, err = m.k8s.StorageV1().VolumeAttachments().Get(context.TODO(), attachID, meta.GetOptions{})
  242. if err != nil {
  243. return errors.New(log("blockMapper.SetupDevice failed to get volume attachment [id=%v]: %v", attachID, err))
  244. }
  245. }
  246. //TODO (vladimirvivien) implement better AccessModes mapping between k8s and CSI
  247. accessMode := v1.ReadWriteOnce
  248. if m.spec.PersistentVolume.Spec.AccessModes != nil {
  249. accessMode = m.spec.PersistentVolume.Spec.AccessModes[0]
  250. }
  251. ctx, cancel := context.WithTimeout(context.Background(), csiTimeout)
  252. defer cancel()
  253. csiClient, err := m.csiClientGetter.Get()
  254. if err != nil {
  255. return errors.New(log("blockMapper.SetUpDevice failed to get CSI client: %v", err))
  256. }
  257. // Call NodeStageVolume
  258. _, err = m.stageVolumeForBlock(ctx, csiClient, accessMode, csiSource, attachment)
  259. if err != nil {
  260. return err
  261. }
  262. return nil
  263. }
  264. func (m *csiBlockMapper) MapPodDevice() (string, error) {
  265. if !m.plugin.blockEnabled {
  266. return "", errors.New("CSIBlockVolume feature not enabled")
  267. }
  268. klog.V(4).Infof(log("blockMapper.MapPodDevice called"))
  269. // Get csiSource from spec
  270. if m.spec == nil {
  271. return "", errors.New(log("blockMapper.MapPodDevice spec is nil"))
  272. }
  273. csiSource, err := getCSISourceFromSpec(m.spec)
  274. if err != nil {
  275. return "", errors.New(log("blockMapper.MapPodDevice failed to get CSI persistent source: %v", err))
  276. }
  277. driverName := csiSource.Driver
  278. skip, err := m.plugin.skipAttach(driverName)
  279. if err != nil {
  280. return "", errors.New(log("blockMapper.MapPodDevice failed to check CSIDriver for %s: %v", driverName, err))
  281. }
  282. var attachment *storage.VolumeAttachment
  283. if !skip {
  284. // Search for attachment by VolumeAttachment.Spec.Source.PersistentVolumeName
  285. nodeName := string(m.plugin.host.GetNodeName())
  286. attachID := getAttachmentName(csiSource.VolumeHandle, csiSource.Driver, nodeName)
  287. attachment, err = m.k8s.StorageV1().VolumeAttachments().Get(context.TODO(), attachID, meta.GetOptions{})
  288. if err != nil {
  289. return "", errors.New(log("blockMapper.MapPodDevice failed to get volume attachment [id=%v]: %v", attachID, err))
  290. }
  291. }
  292. //TODO (vladimirvivien) implement better AccessModes mapping between k8s and CSI
  293. accessMode := v1.ReadWriteOnce
  294. if m.spec.PersistentVolume.Spec.AccessModes != nil {
  295. accessMode = m.spec.PersistentVolume.Spec.AccessModes[0]
  296. }
  297. ctx, cancel := context.WithTimeout(context.Background(), csiTimeout)
  298. defer cancel()
  299. csiClient, err := m.csiClientGetter.Get()
  300. if err != nil {
  301. return "", errors.New(log("blockMapper.MapPodDevice failed to get CSI client: %v", err))
  302. }
  303. // Call NodePublishVolume
  304. publishPath, err := m.publishVolumeForBlock(ctx, csiClient, accessMode, csiSource, attachment)
  305. if err != nil {
  306. return "", err
  307. }
  308. return publishPath, nil
  309. }
  310. var _ volume.BlockVolumeUnmapper = &csiBlockMapper{}
  311. var _ volume.CustomBlockVolumeUnmapper = &csiBlockMapper{}
  312. // unpublishVolumeForBlock unpublishes a block volume from publishPath
  313. func (m *csiBlockMapper) unpublishVolumeForBlock(ctx context.Context, csi csiClient, publishPath string) error {
  314. // Request to unpublish a block volume from publishPath.
  315. // Expectation for driver is to remove block volume from the publishPath, by unmounting bind-mounted device file
  316. // or deleting device file.
  317. // Driver is responsible for deleting publishPath itself.
  318. // If driver doesn't implement NodeUnstageVolume, detaching the block volume from the node may be done, here.
  319. if err := csi.NodeUnpublishVolume(ctx, m.volumeID, publishPath); err != nil {
  320. return errors.New(log("blockMapper.unpublishVolumeForBlock failed: %v", err))
  321. }
  322. klog.V(4).Infof(log("blockMapper.unpublishVolumeForBlock NodeUnpublished successfully [%s]", publishPath))
  323. return nil
  324. }
  325. // unstageVolumeForBlock unstages a block volume from stagingPath
  326. func (m *csiBlockMapper) unstageVolumeForBlock(ctx context.Context, csi csiClient, stagingPath string) error {
  327. // Check whether "STAGE_UNSTAGE_VOLUME" is set
  328. stageUnstageSet, err := csi.NodeSupportsStageUnstage(ctx)
  329. if err != nil {
  330. return errors.New(log("blockMapper.unstageVolumeForBlock failed to check STAGE_UNSTAGE_VOLUME capability: %v", err))
  331. }
  332. if !stageUnstageSet {
  333. klog.Infof(log("blockMapper.unstageVolumeForBlock STAGE_UNSTAGE_VOLUME capability not set. Skipping unstageVolumeForBlock ..."))
  334. return nil
  335. }
  336. // Request to unstage a block volume from stagingPath.
  337. // Expected implementation for driver is removing driver specific resource in stagingPath and
  338. // detaching the block volume from the node.
  339. if err := csi.NodeUnstageVolume(ctx, m.volumeID, stagingPath); err != nil {
  340. return errors.New(log("blockMapper.unstageVolumeForBlock failed: %v", err))
  341. }
  342. klog.V(4).Infof(log("blockMapper.unstageVolumeForBlock NodeUnstageVolume successfully [%s]", stagingPath))
  343. // Remove stagingPath directory and its contents
  344. if err := os.RemoveAll(stagingPath); err != nil {
  345. return errors.New(log("blockMapper.unstageVolumeForBlock failed to remove staging path after NodeUnstageVolume() error [%s]: %v", stagingPath, err))
  346. }
  347. return nil
  348. }
  349. // TearDownDevice removes traces of the SetUpDevice.
  350. func (m *csiBlockMapper) TearDownDevice(globalMapPath, devicePath string) error {
  351. if !m.plugin.blockEnabled {
  352. return errors.New("CSIBlockVolume feature not enabled")
  353. }
  354. ctx, cancel := context.WithTimeout(context.Background(), csiTimeout)
  355. defer cancel()
  356. csiClient, err := m.csiClientGetter.Get()
  357. if err != nil {
  358. return errors.New(log("blockMapper.TearDownDevice failed to get CSI client: %v", err))
  359. }
  360. // Call NodeUnstageVolume
  361. stagingPath := m.getStagingPath()
  362. if _, err := os.Stat(stagingPath); err != nil {
  363. if os.IsNotExist(err) {
  364. klog.V(4).Infof(log("blockMapper.TearDownDevice stagingPath(%s) has already been deleted, skip calling NodeUnstageVolume", stagingPath))
  365. } else {
  366. return err
  367. }
  368. } else {
  369. err := m.unstageVolumeForBlock(ctx, csiClient, stagingPath)
  370. if err != nil {
  371. return err
  372. }
  373. }
  374. return nil
  375. }
  376. // UnmapPodDevice unmaps the block device path.
  377. func (m *csiBlockMapper) UnmapPodDevice() error {
  378. if !m.plugin.blockEnabled {
  379. return errors.New("CSIBlockVolume feature not enabled")
  380. }
  381. publishPath := m.getPublishPath()
  382. csiClient, err := m.csiClientGetter.Get()
  383. if err != nil {
  384. return errors.New(log("blockMapper.UnmapPodDevice failed to get CSI client: %v", err))
  385. }
  386. ctx, cancel := context.WithTimeout(context.Background(), csiTimeout)
  387. defer cancel()
  388. // Call NodeUnpublishVolume
  389. if _, err := os.Stat(publishPath); err != nil {
  390. if os.IsNotExist(err) {
  391. klog.V(4).Infof(log("blockMapper.UnmapPodDevice publishPath(%s) has already been deleted, skip calling NodeUnpublishVolume", publishPath))
  392. } else {
  393. return err
  394. }
  395. } else {
  396. err := m.unpublishVolumeForBlock(ctx, csiClient, publishPath)
  397. if err != nil {
  398. return err
  399. }
  400. }
  401. return nil
  402. }