attacher.go 13 KB

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