disk.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. // Copyright 2019 Yunion
  2. //
  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. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package aws
  15. import (
  16. "context"
  17. "fmt"
  18. "strings"
  19. "time"
  20. "yunion.io/x/jsonutils"
  21. "yunion.io/x/pkg/errors"
  22. "yunion.io/x/pkg/utils"
  23. "yunion.io/x/cloudmux/pkg/apis/billing"
  24. api "yunion.io/x/cloudmux/pkg/apis/compute"
  25. "yunion.io/x/cloudmux/pkg/cloudprovider"
  26. "yunion.io/x/cloudmux/pkg/multicloud"
  27. )
  28. type SMountInstances struct {
  29. MountInstance []string
  30. }
  31. type VolumeAttachment struct {
  32. AttachTime time.Time `xml:"attachTime"`
  33. DeleteOnTermination bool `xml:"deleteOnTermination"`
  34. Device string `xml:"device"`
  35. InstanceId string `xml:"instanceId"`
  36. State string `xml:"status"`
  37. VolumeId string `xml:"volumeId"`
  38. }
  39. type SDisk struct {
  40. storage *SStorage
  41. multicloud.SDisk
  42. AwsTags
  43. AvailabilityZone string `xml:"availabilityZone"`
  44. VolumeId string `xml:"volumeId"`
  45. Size int `xml:"size"`
  46. VolumeType string `xml:"volumeType"`
  47. State string `xml:"status"`
  48. Encrypted bool `xml:"encrypted"`
  49. SnapshotId string `xml:"snapshotId"`
  50. Iops int `xml:"iops"`
  51. Throughput int `xml:"throughput"`
  52. CreateTime time.Time `xml:"createTime"`
  53. Attachments []VolumeAttachment `xml:"attachmentSet>item"`
  54. }
  55. func (self *SDisk) GetId() string {
  56. return self.VolumeId
  57. }
  58. func (self *SDisk) GetName() string {
  59. name := self.AwsTags.GetName()
  60. if len(name) > 0 {
  61. return name
  62. }
  63. return self.VolumeId
  64. }
  65. func (self *SDisk) GetIops() int {
  66. return self.Iops
  67. }
  68. func (self *SDisk) GetGlobalId() string {
  69. return self.VolumeId
  70. }
  71. func (self *SDisk) GetStatus() string {
  72. // creating | available | in-use | deleting | deleted | error
  73. switch self.State {
  74. case "creating":
  75. return api.DISK_ALLOCATING
  76. case "deleting":
  77. return api.DISK_DEALLOC
  78. case "error":
  79. return api.DISK_ALLOC_FAILED
  80. default:
  81. return api.DISK_READY
  82. }
  83. }
  84. func (self *SDisk) Refresh() error {
  85. disk, err := self.storage.zone.region.GetDisk(self.VolumeId)
  86. if err != nil {
  87. return err
  88. }
  89. return jsonutils.Update(self, disk)
  90. }
  91. func (self *SDisk) GetBillingType() string {
  92. return billing.BILLING_TYPE_POSTPAID
  93. }
  94. func (self *SDisk) GetCreatedAt() time.Time {
  95. return self.CreateTime
  96. }
  97. func (self *SDisk) GetExpiredAt() time.Time {
  98. return time.Time{}
  99. }
  100. func (self *SDisk) GetIStorage() (cloudprovider.ICloudStorage, error) {
  101. return self.storage, nil
  102. }
  103. func (self *SDisk) GetDiskFormat() string {
  104. return "vhd"
  105. }
  106. func (self *SDisk) GetDiskSizeMB() int {
  107. return self.Size * 1024
  108. }
  109. func (self *SDisk) GetIsAutoDelete() bool {
  110. for _, attach := range self.Attachments {
  111. if attach.DeleteOnTermination == true {
  112. return true
  113. }
  114. }
  115. return false
  116. }
  117. func (self *SDisk) getInstanceId() string {
  118. for _, attach := range self.Attachments {
  119. if len(attach.InstanceId) > 0 {
  120. return attach.InstanceId
  121. }
  122. }
  123. return ""
  124. }
  125. func (self *SDisk) GetTemplateId() string {
  126. instanceId := self.getInstanceId()
  127. if len(instanceId) > 0 {
  128. ins, err := self.storage.zone.region.GetInstance(instanceId)
  129. if err == nil {
  130. return ins.ImageId
  131. }
  132. }
  133. return ""
  134. }
  135. func (self *SDisk) GetDeviceName() string {
  136. return self.getDevice()
  137. }
  138. func (self *SDisk) getDevice() string {
  139. for _, dev := range self.Attachments {
  140. if len(dev.Device) > 0 {
  141. return dev.Device
  142. }
  143. }
  144. return ""
  145. }
  146. func (self *SDisk) GetDiskType() string {
  147. device := self.getDevice()
  148. if strings.HasSuffix(device, "a") || strings.HasSuffix(device, "1") {
  149. return api.DISK_TYPE_SYS
  150. }
  151. return api.DISK_TYPE_DATA
  152. }
  153. func (self *SDisk) GetFsFormat() string {
  154. return ""
  155. }
  156. func (self *SDisk) GetIsNonPersistent() bool {
  157. return false
  158. }
  159. func (self *SDisk) GetDriver() string {
  160. return "scsi"
  161. }
  162. func (self *SDisk) GetCacheMode() string {
  163. return "none"
  164. }
  165. func (self *SDisk) GetMountpoint() string {
  166. return ""
  167. }
  168. func (self *SDisk) Delete(ctx context.Context) error {
  169. return self.storage.zone.region.DeleteDisk(self.VolumeId)
  170. }
  171. func (self *SDisk) SetTags(tags map[string]string, replace bool) error {
  172. return self.storage.zone.region.setTags("volume", self.VolumeId, tags, replace)
  173. }
  174. func (self *SDisk) CreateISnapshot(ctx context.Context, name string, desc string) (cloudprovider.ICloudSnapshot, error) {
  175. snapshot, err := self.storage.zone.region.CreateSnapshot(self.VolumeId, name, desc)
  176. if err != nil {
  177. return nil, errors.Wrapf(err, "CreateSnapshot")
  178. }
  179. return snapshot, nil
  180. }
  181. func (self *SDisk) GetISnapshot(snapshotId string) (cloudprovider.ICloudSnapshot, error) {
  182. snapshot, err := self.storage.zone.region.GetSnapshot(snapshotId)
  183. if err != nil {
  184. return nil, errors.Wrap(err, "GetSnapshot")
  185. }
  186. snapshot.region = self.storage.zone.region
  187. return snapshot, nil
  188. }
  189. func (self *SDisk) GetISnapshots() ([]cloudprovider.ICloudSnapshot, error) {
  190. snapshots, err := self.storage.zone.region.GetSnapshots(self.VolumeId, "", nil)
  191. if err != nil {
  192. return nil, err
  193. }
  194. ret := []cloudprovider.ICloudSnapshot{}
  195. for i := 0; i < len(snapshots); i++ {
  196. snapshots[i].region = self.storage.zone.region
  197. ret = append(ret, &snapshots[i])
  198. }
  199. return ret, nil
  200. }
  201. func (self *SDisk) Resize(ctx context.Context, newSizeMb int64) error {
  202. err := self.storage.zone.region.ResizeDisk(self.VolumeId, newSizeMb/1024)
  203. if err != nil {
  204. return err
  205. }
  206. return cloudprovider.WaitStatusWithDelay(self, api.DISK_READY, 5*time.Second, 5*time.Second, 90*time.Second)
  207. }
  208. func (self *SDisk) Reset(ctx context.Context, snapshotId string) (string, error) {
  209. if self.State != "available" {
  210. return "", errors.Wrapf(cloudprovider.ErrInvalidStatus, "invalid status %s", self.State)
  211. }
  212. opts := &cloudprovider.DiskCreateConfig{
  213. Name: self.GetName(),
  214. SizeGb: self.GetDiskSizeMB() / 1024,
  215. Iops: self.Iops,
  216. Throughput: self.Throughput,
  217. SnapshotId: snapshotId,
  218. }
  219. disk, err := self.storage.zone.region.CreateDisk(self.AvailabilityZone, self.VolumeType, opts)
  220. if err != nil {
  221. return "", errors.Wrapf(err, "CreateDisk")
  222. }
  223. err = self.storage.zone.region.DeleteDisk(self.VolumeId)
  224. if err != nil {
  225. self.storage.zone.region.DeleteDisk(disk.VolumeId)
  226. return "", err
  227. }
  228. return disk.VolumeId, nil
  229. }
  230. func (self *SRegion) GetDisks(instanceId string, zoneId string, storageType string, diskIds []string) ([]SDisk, error) {
  231. params := map[string]string{}
  232. for i, diskId := range diskIds {
  233. params[fmt.Sprintf("VolumeId.%d", i+1)] = diskId
  234. }
  235. idx := 1
  236. if len(instanceId) > 0 {
  237. params[fmt.Sprintf("Filter.%d.Name", idx)] = "attachment.instance-id"
  238. params[fmt.Sprintf("Filter.%d.Value.1", idx)] = instanceId
  239. idx++
  240. }
  241. if len(zoneId) > 0 {
  242. params[fmt.Sprintf("Filter.%d.Name", idx)] = "availability-zone"
  243. params[fmt.Sprintf("Filter.%d.Value.1", idx)] = zoneId
  244. idx++
  245. }
  246. if len(storageType) > 0 {
  247. params[fmt.Sprintf("Filter.%d.Name", idx)] = "volume-type"
  248. params[fmt.Sprintf("Filter.%d.Value.1", idx)] = storageType
  249. idx++
  250. }
  251. disks := []SDisk{}
  252. for {
  253. part := struct {
  254. VolumeSet []SDisk `xml:"volumeSet>item"`
  255. NextToken string `xml:"nextToken"`
  256. }{}
  257. err := self.ec2Request("DescribeVolumes", params, &part)
  258. if err != nil {
  259. return nil, errors.Wrapf(err, "DescribeVolumes")
  260. }
  261. disks = append(disks, part.VolumeSet...)
  262. if len(part.VolumeSet) == 0 || len(part.NextToken) == 0 {
  263. break
  264. }
  265. params["NextToken"] = part.NextToken
  266. }
  267. return disks, nil
  268. }
  269. func (self *SRegion) GetDisk(diskId string) (*SDisk, error) {
  270. if len(diskId) == 0 {
  271. return nil, errors.Wrap(cloudprovider.ErrNotFound, "empty disk id")
  272. }
  273. disks, err := self.GetDisks("", "", "", []string{diskId})
  274. if err != nil {
  275. if strings.Contains(err.Error(), "InvalidVolume.NotFound") {
  276. return nil, errors.Wrap(cloudprovider.ErrNotFound, "GetDisks")
  277. }
  278. return nil, errors.Wrap(err, "GetDisks")
  279. }
  280. for i := range disks {
  281. if disks[i].VolumeId == diskId {
  282. return &disks[i], nil
  283. }
  284. }
  285. return nil, errors.Wrapf(cloudprovider.ErrNotFound, "%s", diskId)
  286. }
  287. func (self *SRegion) DeleteDisk(diskId string) error {
  288. params := map[string]string{
  289. "VolumeId": diskId,
  290. }
  291. ret := struct{}{}
  292. return self.ec2Request("DeleteVolume", params, &ret)
  293. }
  294. func (self *SRegion) ResizeDisk(diskId string, sizeGb int64) error {
  295. // https://docs.aws.amazon.com/zh_cn/AWSEC2/latest/UserGuide/volume_constraints.html
  296. // MBR -> 2 TiB
  297. // GPT -> 16 TiB
  298. // size unit GiB
  299. params := map[string]string{
  300. "Size": fmt.Sprintf("%d", sizeGb),
  301. "VolumeId": diskId,
  302. }
  303. ret := struct{}{}
  304. return self.ec2Request("ModifyVolume", params, &ret)
  305. }
  306. // io1类型的卷需要指定IOPS参数,最大不超过32000。这里根据aws网站的建议值进行设置
  307. // io2类型的卷需要指定IOPS参数,最大不超过64000。
  308. // GenDiskIops Base 100, 卷每增加2G。IOPS增加1。最多到3000 iops
  309. func GenDiskIops(diskType string, sizeGB int) int64 {
  310. switch diskType {
  311. case api.STORAGE_IO1_SSD, api.STORAGE_IO2_SSD:
  312. iops := int64(100 + sizeGB/2)
  313. if iops < 32000 {
  314. return iops
  315. }
  316. return 100
  317. case api.STORAGE_GP3_SSD:
  318. return 3000
  319. }
  320. return 0
  321. }
  322. func (self *SRegion) CreateDisk(zoneId string, volumeType string, opts *cloudprovider.DiskCreateConfig) (*SDisk, error) {
  323. params := map[string]string{
  324. "AvailabilityZone": zoneId,
  325. "ClientToken": utils.GenRequestId(20),
  326. "Size": fmt.Sprintf("%d", opts.SizeGb),
  327. "VolumeType": volumeType,
  328. }
  329. tagIdx := 1
  330. if len(opts.Name) > 0 {
  331. params["TagSpecification.1.ResourceType"] = "volume"
  332. params[fmt.Sprintf("TagSpecification.1.Tag.%d.Key", tagIdx)] = "Name"
  333. params[fmt.Sprintf("TagSpecification.1.Tag.%d.Value", tagIdx)] = opts.Name
  334. tagIdx++
  335. if len(opts.Desc) > 0 {
  336. params[fmt.Sprintf("TagSpecification.1.Tag.%d.Key", tagIdx)] = "Description"
  337. params[fmt.Sprintf("TagSpecification.1.Tag.%d.Value", tagIdx)] = opts.Desc
  338. }
  339. }
  340. for k, v := range opts.Tags {
  341. params["TagSpecification.1.ResourceType"] = "volume"
  342. params[fmt.Sprintf("TagSpecification.1.Tag.%d.Key", tagIdx)] = k
  343. params[fmt.Sprintf("TagSpecification.1.Tag.%d.Value", tagIdx)] = v
  344. tagIdx++
  345. }
  346. if len(opts.SnapshotId) > 0 {
  347. params["SnapshotId"] = opts.SnapshotId
  348. }
  349. if opts.Throughput >= 125 && opts.Throughput <= 1000 && volumeType == api.STORAGE_GP3_SSD {
  350. params["Throughput"] = fmt.Sprintf("%d", opts.Throughput)
  351. }
  352. if opts.Iops == 0 {
  353. opts.Iops = int(GenDiskIops(volumeType, opts.SizeGb))
  354. }
  355. if utils.IsInStringArray(volumeType, []string{
  356. api.STORAGE_IO1_SSD,
  357. api.STORAGE_IO2_SSD,
  358. api.STORAGE_GP3_SSD,
  359. }) {
  360. params["Iops"] = fmt.Sprintf("%d", opts.Iops)
  361. }
  362. ret := &SDisk{}
  363. return ret, self.ec2Request("CreateVolume", params, ret)
  364. }
  365. func (disk *SDisk) GetAccessPath() string {
  366. return ""
  367. }
  368. func (self *SDisk) Rebuild(ctx context.Context) error {
  369. return cloudprovider.ErrNotSupported
  370. }
  371. func (self *SDisk) GetProjectId() string {
  372. return ""
  373. }
  374. func (self *SDisk) GetDescription() string {
  375. return self.AwsTags.GetDescription()
  376. }