attacher.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  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 photon_pd
  14. import (
  15. "context"
  16. "fmt"
  17. "os"
  18. "path"
  19. "path/filepath"
  20. "strings"
  21. "time"
  22. "k8s.io/api/core/v1"
  23. "k8s.io/apimachinery/pkg/types"
  24. "k8s.io/klog"
  25. "k8s.io/kubernetes/pkg/cloudprovider/providers/photon"
  26. "k8s.io/kubernetes/pkg/util/mount"
  27. "k8s.io/kubernetes/pkg/volume"
  28. volumeutil "k8s.io/kubernetes/pkg/volume/util"
  29. )
  30. type photonPersistentDiskAttacher struct {
  31. host volume.VolumeHost
  32. photonDisks photon.Disks
  33. }
  34. var _ volume.Attacher = &photonPersistentDiskAttacher{}
  35. var _ volume.DeviceMounter = &photonPersistentDiskAttacher{}
  36. var _ volume.AttachableVolumePlugin = &photonPersistentDiskPlugin{}
  37. var _ volume.DeviceMountableVolumePlugin = &photonPersistentDiskPlugin{}
  38. func (plugin *photonPersistentDiskPlugin) NewAttacher() (volume.Attacher, error) {
  39. photonCloud, err := getCloudProvider(plugin.host.GetCloudProvider())
  40. if err != nil {
  41. klog.Errorf("Photon Controller attacher: NewAttacher failed to get cloud provider")
  42. return nil, err
  43. }
  44. return &photonPersistentDiskAttacher{
  45. host: plugin.host,
  46. photonDisks: photonCloud,
  47. }, nil
  48. }
  49. func (plugin *photonPersistentDiskPlugin) NewDeviceMounter() (volume.DeviceMounter, error) {
  50. return plugin.NewAttacher()
  51. }
  52. // Attaches the volume specified by the given spec to the given host.
  53. // On success, returns the device path where the device was attached on the
  54. // node.
  55. // Callers are responsible for retryinging on failure.
  56. // Callers are responsible for thread safety between concurrent attach and
  57. // detach operations.
  58. func (attacher *photonPersistentDiskAttacher) Attach(spec *volume.Spec, nodeName types.NodeName) (string, error) {
  59. hostName := string(nodeName)
  60. volumeSource, _, err := getVolumeSource(spec)
  61. if err != nil {
  62. klog.Errorf("Photon Controller attacher: Attach failed to get volume source")
  63. return "", err
  64. }
  65. attached, err := attacher.photonDisks.DiskIsAttached(context.TODO(), volumeSource.PdID, nodeName)
  66. if err != nil {
  67. klog.Warningf("Photon Controller: couldn't check if disk is Attached for host %s, will try attach disk: %+v", hostName, err)
  68. attached = false
  69. }
  70. if !attached {
  71. klog.V(4).Infof("Photon Controller: Attach disk called for host %s", hostName)
  72. err = attacher.photonDisks.AttachDisk(context.TODO(), volumeSource.PdID, nodeName)
  73. if err != nil {
  74. klog.Errorf("Error attaching volume %q to node %q: %+v", volumeSource.PdID, nodeName, err)
  75. return "", err
  76. }
  77. }
  78. PdidWithNoHypens := strings.Replace(volumeSource.PdID, "-", "", -1)
  79. return filepath.Join(diskByIDPath, diskPhotonPrefix+PdidWithNoHypens), nil
  80. }
  81. func (attacher *photonPersistentDiskAttacher) VolumesAreAttached(specs []*volume.Spec, nodeName types.NodeName) (map[*volume.Spec]bool, error) {
  82. volumesAttachedCheck := make(map[*volume.Spec]bool)
  83. volumeSpecMap := make(map[string]*volume.Spec)
  84. pdIDList := []string{}
  85. for _, spec := range specs {
  86. volumeSource, _, err := getVolumeSource(spec)
  87. if err != nil {
  88. klog.Errorf("Error getting volume (%q) source : %v", spec.Name(), err)
  89. continue
  90. }
  91. pdIDList = append(pdIDList, volumeSource.PdID)
  92. volumesAttachedCheck[spec] = true
  93. volumeSpecMap[volumeSource.PdID] = spec
  94. }
  95. attachedResult, err := attacher.photonDisks.DisksAreAttached(context.TODO(), pdIDList, nodeName)
  96. if err != nil {
  97. klog.Errorf(
  98. "Error checking if volumes (%v) are attached to current node (%q). err=%v",
  99. pdIDList, nodeName, err)
  100. return volumesAttachedCheck, err
  101. }
  102. for pdID, attached := range attachedResult {
  103. if !attached {
  104. spec := volumeSpecMap[pdID]
  105. volumesAttachedCheck[spec] = false
  106. klog.V(2).Infof("VolumesAreAttached: check volume %q (specName: %q) is no longer attached", pdID, spec.Name())
  107. }
  108. }
  109. return volumesAttachedCheck, nil
  110. }
  111. func (attacher *photonPersistentDiskAttacher) WaitForAttach(spec *volume.Spec, devicePath string, _ *v1.Pod, timeout time.Duration) (string, error) {
  112. volumeSource, _, err := getVolumeSource(spec)
  113. if err != nil {
  114. klog.Errorf("Photon Controller attacher: WaitForAttach failed to get volume source")
  115. return "", err
  116. }
  117. if devicePath == "" {
  118. return "", fmt.Errorf("WaitForAttach failed for PD %s: devicePath is empty.", volumeSource.PdID)
  119. }
  120. // scan scsi path to discover the new disk
  121. scsiHostScan()
  122. ticker := time.NewTicker(checkSleepDuration)
  123. defer ticker.Stop()
  124. timer := time.NewTimer(timeout)
  125. defer timer.Stop()
  126. for {
  127. select {
  128. case <-ticker.C:
  129. klog.V(4).Infof("Checking PD %s is attached", volumeSource.PdID)
  130. checkPath, err := verifyDevicePath(devicePath)
  131. if err != nil {
  132. // Log error, if any, and continue checking periodically. See issue #11321
  133. klog.Warningf("Photon Controller attacher: WaitForAttach with devicePath %s Checking PD %s Error verify path", devicePath, volumeSource.PdID)
  134. } else if checkPath != "" {
  135. // A device path has successfully been created for the VMDK
  136. klog.V(4).Infof("Successfully found attached PD %s.", volumeSource.PdID)
  137. // map path with spec.Name()
  138. volName := spec.Name()
  139. realPath, _ := filepath.EvalSymlinks(devicePath)
  140. deviceName := path.Base(realPath)
  141. volNameToDeviceName[volName] = deviceName
  142. return devicePath, nil
  143. }
  144. case <-timer.C:
  145. return "", fmt.Errorf("Could not find attached PD %s. Timeout waiting for mount paths to be created.", volumeSource.PdID)
  146. }
  147. }
  148. }
  149. // GetDeviceMountPath returns a path where the device should
  150. // point which should be bind mounted for individual volumes.
  151. func (attacher *photonPersistentDiskAttacher) GetDeviceMountPath(spec *volume.Spec) (string, error) {
  152. volumeSource, _, err := getVolumeSource(spec)
  153. if err != nil {
  154. klog.Errorf("Photon Controller attacher: GetDeviceMountPath failed to get volume source")
  155. return "", err
  156. }
  157. return makeGlobalPDPath(attacher.host, volumeSource.PdID), nil
  158. }
  159. // GetMountDeviceRefs finds all other references to the device referenced
  160. // by deviceMountPath; returns a list of paths.
  161. func (plugin *photonPersistentDiskPlugin) GetDeviceMountRefs(deviceMountPath string) ([]string, error) {
  162. mounter := plugin.host.GetMounter(plugin.GetPluginName())
  163. return mounter.GetMountRefs(deviceMountPath)
  164. }
  165. // MountDevice mounts device to global mount point.
  166. func (attacher *photonPersistentDiskAttacher) MountDevice(spec *volume.Spec, devicePath string, deviceMountPath string) error {
  167. mounter := attacher.host.GetMounter(photonPersistentDiskPluginName)
  168. notMnt, err := mounter.IsLikelyNotMountPoint(deviceMountPath)
  169. if err != nil {
  170. if os.IsNotExist(err) {
  171. if err := os.MkdirAll(deviceMountPath, 0750); err != nil {
  172. klog.Errorf("Failed to create directory at %#v. err: %s", deviceMountPath, err)
  173. return err
  174. }
  175. notMnt = true
  176. } else {
  177. return err
  178. }
  179. }
  180. volumeSource, _, err := getVolumeSource(spec)
  181. if err != nil {
  182. klog.Errorf("Photon Controller attacher: MountDevice failed to get volume source. err: %s", err)
  183. return err
  184. }
  185. options := []string{}
  186. if notMnt {
  187. diskMounter := volumeutil.NewSafeFormatAndMountFromHost(photonPersistentDiskPluginName, attacher.host)
  188. mountOptions := volumeutil.MountOptionFromSpec(spec)
  189. err = diskMounter.FormatAndMount(devicePath, deviceMountPath, volumeSource.FSType, mountOptions)
  190. if err != nil {
  191. os.Remove(deviceMountPath)
  192. return err
  193. }
  194. klog.V(4).Infof("formatting spec %v devicePath %v deviceMountPath %v fs %v with options %+v", spec.Name(), devicePath, deviceMountPath, volumeSource.FSType, options)
  195. }
  196. return nil
  197. }
  198. type photonPersistentDiskDetacher struct {
  199. mounter mount.Interface
  200. photonDisks photon.Disks
  201. }
  202. var _ volume.Detacher = &photonPersistentDiskDetacher{}
  203. var _ volume.DeviceUnmounter = &photonPersistentDiskDetacher{}
  204. func (plugin *photonPersistentDiskPlugin) NewDetacher() (volume.Detacher, error) {
  205. photonCloud, err := getCloudProvider(plugin.host.GetCloudProvider())
  206. if err != nil {
  207. klog.Errorf("Photon Controller attacher: NewDetacher failed to get cloud provider. err: %s", err)
  208. return nil, err
  209. }
  210. return &photonPersistentDiskDetacher{
  211. mounter: plugin.host.GetMounter(plugin.GetPluginName()),
  212. photonDisks: photonCloud,
  213. }, nil
  214. }
  215. func (plugin *photonPersistentDiskPlugin) NewDeviceUnmounter() (volume.DeviceUnmounter, error) {
  216. return plugin.NewDetacher()
  217. }
  218. // Detach the given device from the given host.
  219. func (detacher *photonPersistentDiskDetacher) Detach(volumeName string, nodeName types.NodeName) error {
  220. hostName := string(nodeName)
  221. pdID := volumeName
  222. attached, err := detacher.photonDisks.DiskIsAttached(context.TODO(), pdID, nodeName)
  223. if err != nil {
  224. // Log error and continue with detach
  225. klog.Errorf(
  226. "Error checking if persistent disk (%q) is already attached to current node (%q). Will continue and try detach anyway. err=%v",
  227. pdID, hostName, err)
  228. }
  229. if err == nil && !attached {
  230. // Volume is already detached from node.
  231. klog.V(4).Infof("detach operation was successful. persistent disk %q is already detached from node %q.", pdID, hostName)
  232. return nil
  233. }
  234. if err := detacher.photonDisks.DetachDisk(context.TODO(), pdID, nodeName); err != nil {
  235. klog.Errorf("Error detaching volume %q: %v", pdID, err)
  236. return err
  237. }
  238. return nil
  239. }
  240. func (detacher *photonPersistentDiskDetacher) WaitForDetach(devicePath string, timeout time.Duration) error {
  241. ticker := time.NewTicker(checkSleepDuration)
  242. defer ticker.Stop()
  243. timer := time.NewTimer(timeout)
  244. defer timer.Stop()
  245. for {
  246. select {
  247. case <-ticker.C:
  248. klog.V(4).Infof("Checking device %q is detached.", devicePath)
  249. if pathExists, err := mount.PathExists(devicePath); err != nil {
  250. return fmt.Errorf("Error checking if device path exists: %v", err)
  251. } else if !pathExists {
  252. return nil
  253. }
  254. case <-timer.C:
  255. return fmt.Errorf("Timeout reached; Device %v is still attached", devicePath)
  256. }
  257. }
  258. }
  259. func (detacher *photonPersistentDiskDetacher) UnmountDevice(deviceMountPath string) error {
  260. return mount.CleanupMountPoint(deviceMountPath, detacher.mounter, false)
  261. }
  262. func (plugin *photonPersistentDiskPlugin) CanAttach(spec *volume.Spec) (bool, error) {
  263. return true, nil
  264. }
  265. func (plugin *photonPersistentDiskPlugin) CanDeviceMount(spec *volume.Spec) (bool, error) {
  266. return true, nil
  267. }