attacher.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. /*
  2. Copyright 2016 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 azure_dd
  14. import (
  15. "fmt"
  16. "os"
  17. "path/filepath"
  18. "runtime"
  19. "strconv"
  20. "strings"
  21. "time"
  22. "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-03-01/compute"
  23. "k8s.io/klog"
  24. v1 "k8s.io/api/core/v1"
  25. "k8s.io/apimachinery/pkg/types"
  26. "k8s.io/apimachinery/pkg/util/wait"
  27. cloudprovider "k8s.io/cloud-provider"
  28. "k8s.io/kubernetes/pkg/util/mount"
  29. "k8s.io/kubernetes/pkg/volume"
  30. "k8s.io/kubernetes/pkg/volume/util"
  31. "k8s.io/legacy-cloud-providers/azure"
  32. )
  33. type azureDiskDetacher struct {
  34. plugin *azureDataDiskPlugin
  35. cloud *azure.Cloud
  36. }
  37. type azureDiskAttacher struct {
  38. plugin *azureDataDiskPlugin
  39. cloud *azure.Cloud
  40. }
  41. var _ volume.Attacher = &azureDiskAttacher{}
  42. var _ volume.Detacher = &azureDiskDetacher{}
  43. var _ volume.DeviceMounter = &azureDiskAttacher{}
  44. var _ volume.DeviceUnmounter = &azureDiskDetacher{}
  45. // Attach attaches a volume.Spec to an Azure VM referenced by NodeName, returning the disk's LUN
  46. func (a *azureDiskAttacher) Attach(spec *volume.Spec, nodeName types.NodeName) (string, error) {
  47. volumeSource, _, err := getVolumeSource(spec)
  48. if err != nil {
  49. klog.Warningf("failed to get azure disk spec (%v)", err)
  50. return "", err
  51. }
  52. diskController, err := getDiskController(a.plugin.host)
  53. if err != nil {
  54. return "", err
  55. }
  56. lun, err := diskController.GetDiskLun(volumeSource.DiskName, volumeSource.DataDiskURI, nodeName)
  57. if err == cloudprovider.InstanceNotFound {
  58. // Log error and continue with attach
  59. klog.Warningf(
  60. "Error checking if volume is already attached to current node (%q). Will continue and try attach anyway. err=%v",
  61. nodeName, err)
  62. }
  63. if err == nil {
  64. // Volume is already attached to node.
  65. klog.V(2).Infof("Attach operation is successful. volume %q is already attached to node %q at lun %d.", volumeSource.DiskName, nodeName, lun)
  66. } else {
  67. klog.V(2).Infof("GetDiskLun returned: %v. Initiating attaching volume %q to node %q.", err, volumeSource.DataDiskURI, nodeName)
  68. isManagedDisk := (*volumeSource.Kind == v1.AzureManagedDisk)
  69. lun, err = diskController.AttachDisk(isManagedDisk, volumeSource.DiskName, volumeSource.DataDiskURI, nodeName, compute.CachingTypes(*volumeSource.CachingMode))
  70. if err == nil {
  71. klog.V(2).Infof("Attach operation successful: volume %q attached to node %q.", volumeSource.DataDiskURI, nodeName)
  72. } else {
  73. klog.V(2).Infof("Attach volume %q to instance %q failed with %v", volumeSource.DataDiskURI, nodeName, err)
  74. return "", err
  75. }
  76. }
  77. return strconv.Itoa(int(lun)), err
  78. }
  79. func (a *azureDiskAttacher) VolumesAreAttached(specs []*volume.Spec, nodeName types.NodeName) (map[*volume.Spec]bool, error) {
  80. volumesAttachedCheck := make(map[*volume.Spec]bool)
  81. volumeSpecMap := make(map[string]*volume.Spec)
  82. volumeIDList := []string{}
  83. for _, spec := range specs {
  84. volumeSource, _, err := getVolumeSource(spec)
  85. if err != nil {
  86. klog.Errorf("azureDisk - Error getting volume (%q) source : %v", spec.Name(), err)
  87. continue
  88. }
  89. volumeIDList = append(volumeIDList, volumeSource.DiskName)
  90. volumesAttachedCheck[spec] = true
  91. volumeSpecMap[volumeSource.DiskName] = spec
  92. }
  93. diskController, err := getDiskController(a.plugin.host)
  94. if err != nil {
  95. return nil, err
  96. }
  97. attachedResult, err := diskController.DisksAreAttached(volumeIDList, nodeName)
  98. if err != nil {
  99. // Log error and continue with attach
  100. klog.Errorf(
  101. "azureDisk - Error checking if volumes (%v) are attached to current node (%q). err=%v",
  102. volumeIDList, nodeName, err)
  103. return volumesAttachedCheck, err
  104. }
  105. for volumeID, attached := range attachedResult {
  106. if !attached {
  107. spec := volumeSpecMap[volumeID]
  108. volumesAttachedCheck[spec] = false
  109. klog.V(2).Infof("azureDisk - VolumesAreAttached: check volume %q (specName: %q) is no longer attached", volumeID, spec.Name())
  110. }
  111. }
  112. return volumesAttachedCheck, nil
  113. }
  114. func (a *azureDiskAttacher) WaitForAttach(spec *volume.Spec, devicePath string, _ *v1.Pod, timeout time.Duration) (string, error) {
  115. // devicePath could be a LUN number or
  116. // "/dev/disk/azure/scsi1/lunx", "/dev/sdx" on Linux node
  117. // "/dev/diskx" on Windows node
  118. if strings.HasPrefix(devicePath, "/dev/") {
  119. return devicePath, nil
  120. }
  121. volumeSource, _, err := getVolumeSource(spec)
  122. if err != nil {
  123. return "", err
  124. }
  125. nodeName := types.NodeName(a.plugin.host.GetHostName())
  126. diskName := volumeSource.DiskName
  127. lun, err := strconv.Atoi(devicePath)
  128. if err != nil {
  129. return "", fmt.Errorf("parse %s failed with error: %v, diskName: %s, nodeName: %s", devicePath, err, diskName, nodeName)
  130. }
  131. exec := a.plugin.host.GetExec(a.plugin.GetPluginName())
  132. io := &osIOHandler{}
  133. scsiHostRescan(io, exec)
  134. newDevicePath := ""
  135. err = wait.Poll(1*time.Second, timeout, func() (bool, error) {
  136. if newDevicePath, err = findDiskByLun(int(lun), io, exec); err != nil {
  137. return false, fmt.Errorf("azureDisk - WaitForAttach ticker failed node (%s) disk (%s) lun(%v) err(%s)", nodeName, diskName, lun, err)
  138. }
  139. // did we find it?
  140. if newDevicePath != "" {
  141. return true, nil
  142. }
  143. return false, fmt.Errorf("azureDisk - WaitForAttach failed within timeout node (%s) diskId:(%s) lun:(%v)", nodeName, diskName, lun)
  144. })
  145. return newDevicePath, err
  146. }
  147. // to avoid name conflicts (similar *.vhd name)
  148. // we use hash diskUri and we use it as device mount target.
  149. // this is generalized for both managed and blob disks
  150. // we also prefix the hash with m/b based on disk kind
  151. func (a *azureDiskAttacher) GetDeviceMountPath(spec *volume.Spec) (string, error) {
  152. volumeSource, _, err := getVolumeSource(spec)
  153. if err != nil {
  154. return "", err
  155. }
  156. if volumeSource.Kind == nil { // this spec was constructed from info on the node
  157. pdPath := filepath.Join(a.plugin.host.GetPluginDir(azureDataDiskPluginName), util.MountsInGlobalPDPath, volumeSource.DataDiskURI)
  158. return pdPath, nil
  159. }
  160. isManagedDisk := (*volumeSource.Kind == v1.AzureManagedDisk)
  161. return makeGlobalPDPath(a.plugin.host, volumeSource.DataDiskURI, isManagedDisk)
  162. }
  163. func (attacher *azureDiskAttacher) MountDevice(spec *volume.Spec, devicePath string, deviceMountPath string) error {
  164. mounter := attacher.plugin.host.GetMounter(azureDataDiskPluginName)
  165. notMnt, err := mounter.IsLikelyNotMountPoint(deviceMountPath)
  166. if err != nil {
  167. if os.IsNotExist(err) {
  168. dir := deviceMountPath
  169. if runtime.GOOS == "windows" {
  170. // in windows, as we use mklink, only need to MkdirAll for parent directory
  171. dir = filepath.Dir(deviceMountPath)
  172. }
  173. if err := os.MkdirAll(dir, 0750); err != nil {
  174. return fmt.Errorf("azureDisk - mountDevice:CreateDirectory failed with %s", err)
  175. }
  176. notMnt = true
  177. } else {
  178. return fmt.Errorf("azureDisk - mountDevice:IsLikelyNotMountPoint failed with %s", err)
  179. }
  180. }
  181. if !notMnt {
  182. // testing original mount point, make sure the mount link is valid
  183. if _, err := (&osIOHandler{}).ReadDir(deviceMountPath); err != nil {
  184. // mount link is invalid, now unmount and remount later
  185. klog.Warningf("azureDisk - ReadDir %s failed with %v, unmount this directory", deviceMountPath, err)
  186. if err := mounter.Unmount(deviceMountPath); err != nil {
  187. klog.Errorf("azureDisk - Unmount deviceMountPath %s failed with %v", deviceMountPath, err)
  188. return err
  189. }
  190. notMnt = true
  191. }
  192. }
  193. volumeSource, _, err := getVolumeSource(spec)
  194. if err != nil {
  195. return err
  196. }
  197. options := []string{}
  198. if notMnt {
  199. diskMounter := util.NewSafeFormatAndMountFromHost(azureDataDiskPluginName, attacher.plugin.host)
  200. mountOptions := util.MountOptionFromSpec(spec, options...)
  201. if runtime.GOOS == "windows" {
  202. // only parse devicePath on Windows node
  203. diskNum, err := getDiskNum(devicePath)
  204. if err != nil {
  205. return err
  206. }
  207. devicePath = diskNum
  208. }
  209. err = diskMounter.FormatAndMount(devicePath, deviceMountPath, *volumeSource.FSType, mountOptions)
  210. if err != nil {
  211. if cleanErr := os.Remove(deviceMountPath); cleanErr != nil {
  212. return fmt.Errorf("azureDisk - mountDevice:FormatAndMount failed with %s and clean up failed with :%v", err, cleanErr)
  213. }
  214. return fmt.Errorf("azureDisk - mountDevice:FormatAndMount failed with %s", err)
  215. }
  216. }
  217. return nil
  218. }
  219. // Detach detaches disk from Azure VM.
  220. func (d *azureDiskDetacher) Detach(diskURI string, nodeName types.NodeName) error {
  221. if diskURI == "" {
  222. return fmt.Errorf("invalid disk to detach: %q", diskURI)
  223. }
  224. diskController, err := getDiskController(d.plugin.host)
  225. if err != nil {
  226. return err
  227. }
  228. err = diskController.DetachDisk("", diskURI, nodeName)
  229. if err != nil {
  230. klog.Errorf("failed to detach azure disk %q, err %v", diskURI, err)
  231. }
  232. klog.V(2).Infof("azureDisk - disk:%s was detached from node:%v", diskURI, nodeName)
  233. return err
  234. }
  235. // UnmountDevice unmounts the volume on the node
  236. func (detacher *azureDiskDetacher) UnmountDevice(deviceMountPath string) error {
  237. err := mount.CleanupMountPoint(deviceMountPath, detacher.plugin.host.GetMounter(detacher.plugin.GetPluginName()), false)
  238. if err == nil {
  239. klog.V(2).Infof("azureDisk - Device %s was unmounted", deviceMountPath)
  240. } else {
  241. klog.Warningf("azureDisk - Device %s failed to unmount with error: %s", deviceMountPath, err.Error())
  242. }
  243. return err
  244. }