attacher.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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 gcepd
  14. import (
  15. "encoding/json"
  16. "errors"
  17. "fmt"
  18. "os"
  19. "path"
  20. "path/filepath"
  21. "runtime"
  22. "strconv"
  23. "time"
  24. "k8s.io/api/core/v1"
  25. "k8s.io/apimachinery/pkg/types"
  26. "k8s.io/apimachinery/pkg/util/sets"
  27. "k8s.io/klog"
  28. "k8s.io/kubernetes/pkg/util/mount"
  29. "k8s.io/kubernetes/pkg/volume"
  30. volumeutil "k8s.io/kubernetes/pkg/volume/util"
  31. "k8s.io/legacy-cloud-providers/gce"
  32. )
  33. type gcePersistentDiskAttacher struct {
  34. host volume.VolumeHost
  35. gceDisks gce.Disks
  36. }
  37. var _ volume.Attacher = &gcePersistentDiskAttacher{}
  38. var _ volume.DeviceMounter = &gcePersistentDiskAttacher{}
  39. var _ volume.AttachableVolumePlugin = &gcePersistentDiskPlugin{}
  40. var _ volume.DeviceMountableVolumePlugin = &gcePersistentDiskPlugin{}
  41. func (plugin *gcePersistentDiskPlugin) NewAttacher() (volume.Attacher, error) {
  42. gceCloud, err := getCloudProvider(plugin.host.GetCloudProvider())
  43. if err != nil {
  44. return nil, err
  45. }
  46. return &gcePersistentDiskAttacher{
  47. host: plugin.host,
  48. gceDisks: gceCloud,
  49. }, nil
  50. }
  51. func (plugin *gcePersistentDiskPlugin) NewDeviceMounter() (volume.DeviceMounter, error) {
  52. return plugin.NewAttacher()
  53. }
  54. func (plugin *gcePersistentDiskPlugin) GetDeviceMountRefs(deviceMountPath string) ([]string, error) {
  55. mounter := plugin.host.GetMounter(plugin.GetPluginName())
  56. return mounter.GetMountRefs(deviceMountPath)
  57. }
  58. // Attach checks with the GCE cloud provider if the specified volume is already
  59. // attached to the node with the specified Name.
  60. // If the volume is attached, it succeeds (returns nil).
  61. // If it is not, Attach issues a call to the GCE cloud provider to attach it.
  62. // Callers are responsible for retrying on failure.
  63. // Callers are responsible for thread safety between concurrent attach and
  64. // detach operations.
  65. func (attacher *gcePersistentDiskAttacher) Attach(spec *volume.Spec, nodeName types.NodeName) (string, error) {
  66. volumeSource, readOnly, err := getVolumeSource(spec)
  67. if err != nil {
  68. return "", err
  69. }
  70. pdName := volumeSource.PDName
  71. attached, err := attacher.gceDisks.DiskIsAttached(pdName, nodeName)
  72. if err != nil {
  73. // Log error and continue with attach
  74. klog.Errorf(
  75. "Error checking if PD (%q) is already attached to current node (%q). Will continue and try attach anyway. err=%v",
  76. pdName, nodeName, err)
  77. }
  78. if err == nil && attached {
  79. // Volume is already attached to node.
  80. klog.Infof("Attach operation is successful. PD %q is already attached to node %q.", pdName, nodeName)
  81. } else {
  82. if err := attacher.gceDisks.AttachDisk(pdName, nodeName, readOnly, isRegionalPD(spec)); err != nil {
  83. klog.Errorf("Error attaching PD %q to node %q: %+v", pdName, nodeName, err)
  84. return "", err
  85. }
  86. }
  87. return filepath.Join(diskByIDPath, diskGooglePrefix+pdName), nil
  88. }
  89. func (attacher *gcePersistentDiskAttacher) VolumesAreAttached(specs []*volume.Spec, nodeName types.NodeName) (map[*volume.Spec]bool, error) {
  90. volumesAttachedCheck := make(map[*volume.Spec]bool)
  91. volumePdNameMap := make(map[string]*volume.Spec)
  92. pdNameList := []string{}
  93. for _, spec := range specs {
  94. volumeSource, _, err := getVolumeSource(spec)
  95. // If error is occurred, skip this volume and move to the next one
  96. if err != nil {
  97. klog.Errorf("Error getting volume (%q) source : %v", spec.Name(), err)
  98. continue
  99. }
  100. pdNameList = append(pdNameList, volumeSource.PDName)
  101. volumesAttachedCheck[spec] = true
  102. volumePdNameMap[volumeSource.PDName] = spec
  103. }
  104. attachedResult, err := attacher.gceDisks.DisksAreAttached(pdNameList, nodeName)
  105. if err != nil {
  106. // Log error and continue with attach
  107. klog.Errorf(
  108. "Error checking if PDs (%v) are already attached to current node (%q). err=%v",
  109. pdNameList, nodeName, err)
  110. return volumesAttachedCheck, err
  111. }
  112. for pdName, attached := range attachedResult {
  113. if !attached {
  114. spec := volumePdNameMap[pdName]
  115. volumesAttachedCheck[spec] = false
  116. klog.V(2).Infof("VolumesAreAttached: check volume %q (specName: %q) is no longer attached", pdName, spec.Name())
  117. }
  118. }
  119. return volumesAttachedCheck, nil
  120. }
  121. func (attacher *gcePersistentDiskAttacher) BulkVerifyVolumes(volumesByNode map[types.NodeName][]*volume.Spec) (map[types.NodeName]map[*volume.Spec]bool, error) {
  122. volumesAttachedCheck := make(map[types.NodeName]map[*volume.Spec]bool)
  123. diskNamesByNode := make(map[types.NodeName][]string)
  124. volumeSpecToDiskName := make(map[*volume.Spec]string)
  125. for nodeName, volumeSpecs := range volumesByNode {
  126. diskNames := []string{}
  127. for _, spec := range volumeSpecs {
  128. volumeSource, _, err := getVolumeSource(spec)
  129. if err != nil {
  130. klog.Errorf("Error getting volume (%q) source : %v", spec.Name(), err)
  131. continue
  132. }
  133. diskNames = append(diskNames, volumeSource.PDName)
  134. volumeSpecToDiskName[spec] = volumeSource.PDName
  135. }
  136. diskNamesByNode[nodeName] = diskNames
  137. }
  138. attachedDisksByNode, err := attacher.gceDisks.BulkDisksAreAttached(diskNamesByNode)
  139. if err != nil {
  140. return nil, err
  141. }
  142. for nodeName, volumeSpecs := range volumesByNode {
  143. volumesAreAttachedToNode := make(map[*volume.Spec]bool)
  144. for _, spec := range volumeSpecs {
  145. diskName := volumeSpecToDiskName[spec]
  146. volumesAreAttachedToNode[spec] = attachedDisksByNode[nodeName][diskName]
  147. }
  148. volumesAttachedCheck[nodeName] = volumesAreAttachedToNode
  149. }
  150. return volumesAttachedCheck, nil
  151. }
  152. // search Windows disk number by LUN
  153. func getDiskID(pdName string, exec mount.Exec) (string, error) {
  154. // TODO: replace Get-GcePdName with native windows support of Get-Disk, see issue #74674
  155. cmd := `Get-GcePdName | select Name, DeviceId | ConvertTo-Json`
  156. output, err := exec.Run("powershell", "/c", cmd)
  157. if err != nil {
  158. klog.Errorf("Get-GcePdName failed, error: %v, output: %q", err, string(output))
  159. err = errors.New(err.Error() + " " + string(output))
  160. return "", err
  161. }
  162. var data []map[string]interface{}
  163. if err = json.Unmarshal(output, &data); err != nil {
  164. klog.Errorf("Get-Disk output is not a json array, output: %q", string(output))
  165. return "", err
  166. }
  167. for _, pd := range data {
  168. if jsonName, ok := pd["Name"]; ok {
  169. if name, ok := jsonName.(string); ok {
  170. if name == pdName {
  171. klog.Infof("found the disk %q", name)
  172. if diskNum, ok := pd["DeviceId"]; ok {
  173. switch v := diskNum.(type) {
  174. case int:
  175. return strconv.Itoa(v), nil
  176. case float64:
  177. return strconv.Itoa(int(v)), nil
  178. case string:
  179. return v, nil
  180. default:
  181. // diskNum isn't one of the types above
  182. klog.Warningf("Disk %q found, but disknumber (%q) is not in one of the recongnized type", name, diskNum)
  183. }
  184. }
  185. }
  186. }
  187. }
  188. }
  189. return "", fmt.Errorf("Could not found disk number for disk %q", pdName)
  190. }
  191. func (attacher *gcePersistentDiskAttacher) WaitForAttach(spec *volume.Spec, devicePath string, _ *v1.Pod, timeout time.Duration) (string, error) {
  192. ticker := time.NewTicker(checkSleepDuration)
  193. defer ticker.Stop()
  194. timer := time.NewTimer(timeout)
  195. defer timer.Stop()
  196. volumeSource, _, err := getVolumeSource(spec)
  197. if err != nil {
  198. return "", err
  199. }
  200. pdName := volumeSource.PDName
  201. if runtime.GOOS == "windows" {
  202. exec := attacher.host.GetExec(gcePersistentDiskPluginName)
  203. id, err := getDiskID(pdName, exec)
  204. if err != nil {
  205. klog.Errorf("WaitForAttach (windows) failed with error %s", err)
  206. }
  207. return id, err
  208. }
  209. partition := ""
  210. if volumeSource.Partition != 0 {
  211. partition = strconv.Itoa(int(volumeSource.Partition))
  212. }
  213. sdBefore, err := filepath.Glob(diskSDPattern)
  214. if err != nil {
  215. klog.Errorf("Error filepath.Glob(\"%s\"): %v\r\n", diskSDPattern, err)
  216. }
  217. sdBeforeSet := sets.NewString(sdBefore...)
  218. devicePaths := getDiskByIDPaths(pdName, partition)
  219. for {
  220. select {
  221. case <-ticker.C:
  222. klog.V(5).Infof("Checking GCE PD %q is attached.", pdName)
  223. path, err := verifyDevicePath(devicePaths, sdBeforeSet, pdName)
  224. if err != nil {
  225. // Log error, if any, and continue checking periodically. See issue #11321
  226. klog.Errorf("Error verifying GCE PD (%q) is attached: %v", pdName, err)
  227. } else if path != "" {
  228. // A device path has successfully been created for the PD
  229. klog.Infof("Successfully found attached GCE PD %q.", pdName)
  230. return path, nil
  231. }
  232. case <-timer.C:
  233. return "", fmt.Errorf("could not find attached GCE PD %q. Timeout waiting for mount paths to be created", pdName)
  234. }
  235. }
  236. }
  237. func (attacher *gcePersistentDiskAttacher) GetDeviceMountPath(
  238. spec *volume.Spec) (string, error) {
  239. volumeSource, _, err := getVolumeSource(spec)
  240. if err != nil {
  241. return "", err
  242. }
  243. return makeGlobalPDName(attacher.host, volumeSource.PDName), nil
  244. }
  245. func (attacher *gcePersistentDiskAttacher) MountDevice(spec *volume.Spec, devicePath string, deviceMountPath string) error {
  246. // Only mount the PD globally once.
  247. mounter := attacher.host.GetMounter(gcePersistentDiskPluginName)
  248. notMnt, err := mounter.IsLikelyNotMountPoint(deviceMountPath)
  249. if err != nil {
  250. if os.IsNotExist(err) {
  251. dir := deviceMountPath
  252. if runtime.GOOS == "windows" {
  253. // in windows, as we use mklink, only need to MkdirAll for parent directory
  254. dir = filepath.Dir(deviceMountPath)
  255. }
  256. if err := os.MkdirAll(dir, 0750); err != nil {
  257. return fmt.Errorf("MountDevice:CreateDirectory failed with %s", err)
  258. }
  259. notMnt = true
  260. } else {
  261. return err
  262. }
  263. }
  264. volumeSource, readOnly, err := getVolumeSource(spec)
  265. if err != nil {
  266. return err
  267. }
  268. options := []string{}
  269. if readOnly {
  270. options = append(options, "ro")
  271. }
  272. if notMnt {
  273. diskMounter := volumeutil.NewSafeFormatAndMountFromHost(gcePersistentDiskPluginName, attacher.host)
  274. mountOptions := volumeutil.MountOptionFromSpec(spec, options...)
  275. err = diskMounter.FormatAndMount(devicePath, deviceMountPath, volumeSource.FSType, mountOptions)
  276. if err != nil {
  277. os.Remove(deviceMountPath)
  278. return err
  279. }
  280. klog.V(4).Infof("formatting spec %v devicePath %v deviceMountPath %v fs %v with options %+v", spec.Name(), devicePath, deviceMountPath, volumeSource.FSType, options)
  281. }
  282. return nil
  283. }
  284. type gcePersistentDiskDetacher struct {
  285. host volume.VolumeHost
  286. gceDisks gce.Disks
  287. }
  288. var _ volume.Detacher = &gcePersistentDiskDetacher{}
  289. var _ volume.DeviceUnmounter = &gcePersistentDiskDetacher{}
  290. func (plugin *gcePersistentDiskPlugin) NewDetacher() (volume.Detacher, error) {
  291. gceCloud, err := getCloudProvider(plugin.host.GetCloudProvider())
  292. if err != nil {
  293. return nil, err
  294. }
  295. return &gcePersistentDiskDetacher{
  296. host: plugin.host,
  297. gceDisks: gceCloud,
  298. }, nil
  299. }
  300. func (plugin *gcePersistentDiskPlugin) NewDeviceUnmounter() (volume.DeviceUnmounter, error) {
  301. return plugin.NewDetacher()
  302. }
  303. // Detach checks with the GCE cloud provider if the specified volume is already
  304. // attached to the specified node. If the volume is not attached, it succeeds
  305. // (returns nil). If it is attached, Detach issues a call to the GCE cloud
  306. // provider to attach it.
  307. // Callers are responsible for retrying on failure.
  308. // Callers are responsible for thread safety between concurrent attach and detach
  309. // operations.
  310. func (detacher *gcePersistentDiskDetacher) Detach(volumeName string, nodeName types.NodeName) error {
  311. pdName := path.Base(volumeName)
  312. attached, err := detacher.gceDisks.DiskIsAttached(pdName, nodeName)
  313. if err != nil {
  314. // Log error and continue with detach
  315. klog.Errorf(
  316. "Error checking if PD (%q) is already attached to current node (%q). Will continue and try detach anyway. err=%v",
  317. pdName, nodeName, err)
  318. }
  319. if err == nil && !attached {
  320. // Volume is not attached to node. Success!
  321. klog.Infof("Detach operation is successful. PD %q was not attached to node %q.", pdName, nodeName)
  322. return nil
  323. }
  324. if err = detacher.gceDisks.DetachDisk(pdName, nodeName); err != nil {
  325. klog.Errorf("Error detaching PD %q from node %q: %v", pdName, nodeName, err)
  326. return err
  327. }
  328. return nil
  329. }
  330. func (detacher *gcePersistentDiskDetacher) UnmountDevice(deviceMountPath string) error {
  331. return mount.CleanupMountPoint(deviceMountPath, detacher.host.GetMounter(gcePersistentDiskPluginName), false)
  332. }
  333. func (plugin *gcePersistentDiskPlugin) CanAttach(spec *volume.Spec) (bool, error) {
  334. return true, nil
  335. }
  336. func (plugin *gcePersistentDiskPlugin) CanDeviceMount(spec *volume.Spec) (bool, error) {
  337. return true, nil
  338. }