aws_util.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. // +build !providerless
  2. /*
  3. Copyright 2014 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 awsebs
  15. import (
  16. "fmt"
  17. "os"
  18. "path/filepath"
  19. "strconv"
  20. "strings"
  21. "time"
  22. "k8s.io/klog"
  23. "k8s.io/utils/mount"
  24. v1 "k8s.io/api/core/v1"
  25. "k8s.io/apimachinery/pkg/api/resource"
  26. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  27. "k8s.io/apimachinery/pkg/util/sets"
  28. cloudprovider "k8s.io/cloud-provider"
  29. volumehelpers "k8s.io/cloud-provider/volume/helpers"
  30. "k8s.io/kubernetes/pkg/volume"
  31. volumeutil "k8s.io/kubernetes/pkg/volume/util"
  32. "k8s.io/legacy-cloud-providers/aws"
  33. )
  34. const (
  35. diskPartitionSuffix = ""
  36. checkSleepDuration = time.Second
  37. )
  38. // AWSDiskUtil provides operations for EBS volume.
  39. type AWSDiskUtil struct{}
  40. // DeleteVolume deletes an AWS EBS volume.
  41. func (util *AWSDiskUtil) DeleteVolume(d *awsElasticBlockStoreDeleter) error {
  42. cloud, err := getCloudProvider(d.awsElasticBlockStore.plugin.host.GetCloudProvider())
  43. if err != nil {
  44. return err
  45. }
  46. deleted, err := cloud.DeleteDisk(d.volumeID)
  47. if err != nil {
  48. // AWS cloud provider returns volume.deletedVolumeInUseError when
  49. // necessary, no handling needed here.
  50. klog.V(2).Infof("Error deleting EBS Disk volume %s: %v", d.volumeID, err)
  51. return err
  52. }
  53. if deleted {
  54. klog.V(2).Infof("Successfully deleted EBS Disk volume %s", d.volumeID)
  55. } else {
  56. klog.V(2).Infof("Successfully deleted EBS Disk volume %s (actually already deleted)", d.volumeID)
  57. }
  58. return nil
  59. }
  60. // CreateVolume creates an AWS EBS volume.
  61. // Returns: volumeID, volumeSizeGB, labels, fstype, error
  62. func (util *AWSDiskUtil) CreateVolume(c *awsElasticBlockStoreProvisioner, node *v1.Node, allowedTopologies []v1.TopologySelectorTerm) (aws.KubernetesVolumeID, int, map[string]string, string, error) {
  63. cloud, err := getCloudProvider(c.awsElasticBlockStore.plugin.host.GetCloudProvider())
  64. if err != nil {
  65. return "", 0, nil, "", err
  66. }
  67. // AWS volumes don't have Name field, store the name in Name tag
  68. var tags map[string]string
  69. if c.options.CloudTags == nil {
  70. tags = make(map[string]string)
  71. } else {
  72. tags = *c.options.CloudTags
  73. }
  74. tags["Name"] = volumeutil.GenerateVolumeName(c.options.ClusterName, c.options.PVName, 255) // AWS tags can have 255 characters
  75. capacity := c.options.PVC.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)]
  76. zonesWithNodes, err := getCandidateZones(cloud, node)
  77. if err != nil {
  78. return "", 0, nil, "", fmt.Errorf("error finding candidate zone for pvc: %v", err)
  79. }
  80. volumeOptions, err := populateVolumeOptions(c.plugin.GetPluginName(), c.options.PVC.Name, capacity, tags, c.options.Parameters, node, allowedTopologies, zonesWithNodes)
  81. if err != nil {
  82. klog.V(2).Infof("Error populating EBS options: %v", err)
  83. return "", 0, nil, "", err
  84. }
  85. // TODO: implement PVC.Selector parsing
  86. if c.options.PVC.Spec.Selector != nil {
  87. return "", 0, nil, "", fmt.Errorf("claim.Spec.Selector is not supported for dynamic provisioning on AWS")
  88. }
  89. name, err := cloud.CreateDisk(volumeOptions)
  90. if err != nil {
  91. klog.V(2).Infof("Error creating EBS Disk volume: %v", err)
  92. return "", 0, nil, "", err
  93. }
  94. klog.V(2).Infof("Successfully created EBS Disk volume %s", name)
  95. labels, err := cloud.GetVolumeLabels(name)
  96. if err != nil {
  97. // We don't really want to leak the volume here...
  98. klog.Errorf("error building labels for new EBS volume %q: %v", name, err)
  99. }
  100. fstype := ""
  101. for k, v := range c.options.Parameters {
  102. if strings.ToLower(k) == volume.VolumeParameterFSType {
  103. fstype = v
  104. }
  105. }
  106. return name, volumeOptions.CapacityGB, labels, fstype, nil
  107. }
  108. // getCandidateZones finds possible zones that a volume can be created in
  109. func getCandidateZones(cloud *aws.Cloud, selectedNode *v1.Node) (sets.String, error) {
  110. if selectedNode != nil {
  111. // For topology aware volume provisioning, node is already selected so we use the zone from
  112. // selected node directly instead of candidate zones.
  113. // We can assume the information is always available as node controller shall maintain it.
  114. return sets.NewString(), nil
  115. }
  116. // For non-topology-aware volumes (those that binds immediately), we fall back to original logic to query
  117. // cloud provider for possible zones
  118. return cloud.GetCandidateZonesForDynamicVolume()
  119. }
  120. // returns volumeOptions for EBS based on storageclass parameters and node configuration
  121. func populateVolumeOptions(pluginName, pvcName string, capacityGB resource.Quantity, tags map[string]string, storageParams map[string]string, node *v1.Node, allowedTopologies []v1.TopologySelectorTerm, zonesWithNodes sets.String) (*aws.VolumeOptions, error) {
  122. requestGiB, err := volumehelpers.RoundUpToGiBInt(capacityGB)
  123. if err != nil {
  124. return nil, err
  125. }
  126. volumeOptions := &aws.VolumeOptions{
  127. CapacityGB: requestGiB,
  128. Tags: tags,
  129. }
  130. // Apply Parameters (case-insensitive). We leave validation of
  131. // the values to the cloud provider.
  132. zonePresent := false
  133. zonesPresent := false
  134. var zone string
  135. var zones sets.String
  136. for k, v := range storageParams {
  137. switch strings.ToLower(k) {
  138. case "type":
  139. volumeOptions.VolumeType = v
  140. case "zone":
  141. zonePresent = true
  142. zone = v
  143. case "zones":
  144. zonesPresent = true
  145. zones, err = volumehelpers.ZonesToSet(v)
  146. if err != nil {
  147. return nil, fmt.Errorf("error parsing zones %s, must be strings separated by commas: %v", zones, err)
  148. }
  149. case "iopspergb":
  150. volumeOptions.IOPSPerGB, err = strconv.Atoi(v)
  151. if err != nil {
  152. return nil, fmt.Errorf("invalid iopsPerGB value %q, must be integer between 1 and 30: %v", v, err)
  153. }
  154. case "encrypted":
  155. volumeOptions.Encrypted, err = strconv.ParseBool(v)
  156. if err != nil {
  157. return nil, fmt.Errorf("invalid encrypted boolean value %q, must be true or false: %v", v, err)
  158. }
  159. case "kmskeyid":
  160. volumeOptions.KmsKeyID = v
  161. case volume.VolumeParameterFSType:
  162. // Do nothing but don't make this fail
  163. default:
  164. return nil, fmt.Errorf("invalid option %q for volume plugin %s", k, pluginName)
  165. }
  166. }
  167. volumeOptions.AvailabilityZone, err = volumehelpers.SelectZoneForVolume(zonePresent, zonesPresent, zone, zones, zonesWithNodes, node, allowedTopologies, pvcName)
  168. if err != nil {
  169. return nil, err
  170. }
  171. return volumeOptions, nil
  172. }
  173. // Returns the first path that exists, or empty string if none exist.
  174. func verifyDevicePath(devicePaths []string) (string, error) {
  175. for _, path := range devicePaths {
  176. if pathExists, err := mount.PathExists(path); err != nil {
  177. return "", fmt.Errorf("Error checking if path exists: %v", err)
  178. } else if pathExists {
  179. return path, nil
  180. }
  181. }
  182. return "", nil
  183. }
  184. // Returns list of all paths for given EBS mount
  185. // This is more interesting on GCE (where we are able to identify volumes under /dev/disk-by-id)
  186. // Here it is mostly about applying the partition path
  187. func getDiskByIDPaths(volumeID aws.KubernetesVolumeID, partition string, devicePath string) []string {
  188. devicePaths := []string{}
  189. if devicePath != "" {
  190. devicePaths = append(devicePaths, devicePath)
  191. }
  192. if partition != "" {
  193. for i, path := range devicePaths {
  194. devicePaths[i] = path + diskPartitionSuffix + partition
  195. }
  196. }
  197. // We need to find NVME volumes, which are mounted on a "random" nvme path ("/dev/nvme0n1"),
  198. // and we have to get the volume id from the nvme interface
  199. awsVolumeID, err := volumeID.MapToAWSVolumeID()
  200. if err != nil {
  201. klog.Warningf("error mapping volume %q to AWS volume: %v", volumeID, err)
  202. } else {
  203. // This is the magic name on which AWS presents NVME devices under /dev/disk/by-id/
  204. // For example, vol-0fab1d5e3f72a5e23 creates a symlink at /dev/disk/by-id/nvme-Amazon_Elastic_Block_Store_vol0fab1d5e3f72a5e23
  205. nvmeName := "nvme-Amazon_Elastic_Block_Store_" + strings.Replace(string(awsVolumeID), "-", "", -1)
  206. nvmePath, err := findNvmeVolume(nvmeName)
  207. if err != nil {
  208. klog.Warningf("error looking for nvme volume %q: %v", volumeID, err)
  209. } else if nvmePath != "" {
  210. devicePaths = append(devicePaths, nvmePath)
  211. }
  212. }
  213. return devicePaths
  214. }
  215. // Return cloud provider
  216. func getCloudProvider(cloudProvider cloudprovider.Interface) (*aws.Cloud, error) {
  217. awsCloudProvider, ok := cloudProvider.(*aws.Cloud)
  218. if !ok || awsCloudProvider == nil {
  219. return nil, fmt.Errorf("Failed to get AWS Cloud Provider. GetCloudProvider returned %v instead", cloudProvider)
  220. }
  221. return awsCloudProvider, nil
  222. }
  223. // findNvmeVolume looks for the nvme volume with the specified name
  224. // It follows the symlink (if it exists) and returns the absolute path to the device
  225. func findNvmeVolume(findName string) (device string, err error) {
  226. p := filepath.Join("/dev/disk/by-id/", findName)
  227. stat, err := os.Lstat(p)
  228. if err != nil {
  229. if os.IsNotExist(err) {
  230. klog.V(6).Infof("nvme path not found %q", p)
  231. return "", nil
  232. }
  233. return "", fmt.Errorf("error getting stat of %q: %v", p, err)
  234. }
  235. if stat.Mode()&os.ModeSymlink != os.ModeSymlink {
  236. klog.Warningf("nvme file %q found, but was not a symlink", p)
  237. return "", nil
  238. }
  239. // Find the target, resolving to an absolute path
  240. // For example, /dev/disk/by-id/nvme-Amazon_Elastic_Block_Store_vol0fab1d5e3f72a5e23 -> ../../nvme2n1
  241. resolved, err := filepath.EvalSymlinks(p)
  242. if err != nil {
  243. return "", fmt.Errorf("error reading target of symlink %q: %v", p, err)
  244. }
  245. if !strings.HasPrefix(resolved, "/dev") {
  246. return "", fmt.Errorf("resolved symlink for %q was unexpected: %q", p, resolved)
  247. }
  248. return resolved, nil
  249. }
  250. func formatVolumeID(volumeID string) (string, error) {
  251. // This is a workaround to fix the issue in converting aws volume id from globalPDPath and globalMapPath
  252. // There are three formats for AWSEBSVolumeSource.VolumeID and they are stored on disk in paths like so:
  253. // VolumeID mountPath mapPath
  254. // aws:///vol-1234 aws/vol-1234 aws:/vol-1234
  255. // aws://us-east-1/vol-1234 aws/us-east-1/vol-1234 aws:/us-east-1/vol-1234
  256. // vol-1234 vol-1234 vol-1234
  257. // This code is for converting volume ids from paths back to AWS style VolumeIDs
  258. sourceName := volumeID
  259. if strings.HasPrefix(volumeID, "aws/") || strings.HasPrefix(volumeID, "aws:/") {
  260. names := strings.Split(volumeID, "/")
  261. length := len(names)
  262. if length < 2 || length > 3 {
  263. return "", fmt.Errorf("invalid volume name format %q", volumeID)
  264. }
  265. volName := names[length-1]
  266. if !strings.HasPrefix(volName, "vol-") {
  267. return "", fmt.Errorf("Invalid volume name format for AWS volume (%q)", volName)
  268. }
  269. if length == 2 {
  270. sourceName = awsURLNamePrefix + "" + "/" + volName // empty zone label
  271. }
  272. if length == 3 {
  273. sourceName = awsURLNamePrefix + names[1] + "/" + volName // names[1] is the zone label
  274. }
  275. klog.V(4).Infof("Convert aws volume name from %q to %q ", volumeID, sourceName)
  276. }
  277. return sourceName, nil
  278. }
  279. func newAWSVolumeSpec(volumeName, volumeID string, mode v1.PersistentVolumeMode) *volume.Spec {
  280. awsVolume := &v1.PersistentVolume{
  281. ObjectMeta: metav1.ObjectMeta{
  282. Name: volumeName,
  283. },
  284. Spec: v1.PersistentVolumeSpec{
  285. PersistentVolumeSource: v1.PersistentVolumeSource{
  286. AWSElasticBlockStore: &v1.AWSElasticBlockStoreVolumeSource{
  287. VolumeID: volumeID,
  288. },
  289. },
  290. VolumeMode: &mode,
  291. },
  292. }
  293. return volume.NewSpecFromPersistentVolume(awsVolume, false)
  294. }