host.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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 ucloud
  15. import (
  16. "encoding/base64"
  17. "fmt"
  18. "strconv"
  19. "strings"
  20. "yunion.io/x/jsonutils"
  21. "yunion.io/x/log"
  22. "yunion.io/x/pkg/errors"
  23. "yunion.io/x/pkg/util/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 SHost struct {
  29. multicloud.SHostBase
  30. zone *SZone
  31. projectId string
  32. }
  33. func (self *SHost) GetId() string {
  34. return fmt.Sprintf("%s-%s", self.zone.region.client.cpcfg.Id, self.zone.GetId())
  35. }
  36. func (self *SHost) GetName() string {
  37. return fmt.Sprintf("%s-%s", self.zone.region.client.cpcfg.Name, self.zone.GetId())
  38. }
  39. func (self *SHost) GetGlobalId() string {
  40. return self.GetId()
  41. }
  42. func (self *SHost) GetStatus() string {
  43. return api.HOST_STATUS_RUNNING
  44. }
  45. func (self *SHost) Refresh() error {
  46. return nil
  47. }
  48. func (self *SHost) IsEmulated() bool {
  49. return true
  50. }
  51. func (self *SHost) GetIVMs() ([]cloudprovider.ICloudVM, error) {
  52. vms, err := self.zone.GetInstances()
  53. if err != nil {
  54. return nil, err
  55. }
  56. ivms := make([]cloudprovider.ICloudVM, len(vms))
  57. for i := 0; i < len(vms); i += 1 {
  58. vms[i].host = self
  59. ivms[i] = &vms[i]
  60. }
  61. return ivms, nil
  62. }
  63. func (self *SHost) GetIVMById(id string) (cloudprovider.ICloudVM, error) {
  64. vm, err := self.zone.region.GetInstanceByID(id)
  65. if err != nil {
  66. return nil, err
  67. }
  68. vm.host = self
  69. return &vm, nil
  70. }
  71. func (self *SHost) GetIStorages() ([]cloudprovider.ICloudStorage, error) {
  72. return self.zone.GetIStorages()
  73. }
  74. func (self *SHost) GetIStorageById(id string) (cloudprovider.ICloudStorage, error) {
  75. return self.zone.GetIStorageById(id)
  76. }
  77. func (self *SHost) GetEnabled() bool {
  78. return true
  79. }
  80. func (self *SHost) GetHostStatus() string {
  81. return api.HOST_ONLINE
  82. }
  83. func (self *SHost) GetAccessIp() string {
  84. return ""
  85. }
  86. func (self *SHost) GetAccessMac() string {
  87. return ""
  88. }
  89. func (self *SHost) GetSysInfo() jsonutils.JSONObject {
  90. info := jsonutils.NewDict()
  91. info.Add(jsonutils.NewString(CLOUD_PROVIDER_UCLOUD), "manufacture")
  92. return info
  93. }
  94. func (self *SHost) GetSN() string {
  95. return ""
  96. }
  97. func (self *SHost) GetCpuCount() int {
  98. return 0
  99. }
  100. func (self *SHost) GetNodeCount() int8 {
  101. return 0
  102. }
  103. func (self *SHost) GetCpuDesc() string {
  104. return ""
  105. }
  106. func (self *SHost) GetCpuMhz() int {
  107. return 0
  108. }
  109. func (self *SHost) GetMemSizeMB() int {
  110. return 0
  111. }
  112. func (self *SHost) GetStorageSizeMB() int64 {
  113. return 0
  114. }
  115. func (self *SHost) GetStorageType() string {
  116. return api.DISK_TYPE_HYBRID
  117. }
  118. func (self *SHost) GetHostType() string {
  119. return api.HOST_TYPE_UCLOUD
  120. }
  121. func (self *SHost) GetIsMaintenance() bool {
  122. return false
  123. }
  124. func (self *SHost) GetVersion() string {
  125. return UCLOUD_API_VERSION
  126. }
  127. // 不支持user data
  128. // 不支持指定keypair
  129. func (self *SHost) CreateVM(desc *cloudprovider.SManagedVMCreateConfig) (cloudprovider.ICloudVM, error) {
  130. vmId, err := self._createVM(desc.Name, desc.ExternalImageId, desc.SysDisk, desc.Cpu, desc.MemoryMB, desc.InstanceType, desc.ExternalNetworkId, desc.IpAddr, desc.Description, desc.Password, desc.DataDisks, desc.ExternalSecgroupIds, desc.BillingCycle)
  131. if err != nil {
  132. return nil, err
  133. }
  134. vm, err := self.zone.region.GetInstanceByID(vmId)
  135. if err != nil {
  136. return nil, err
  137. }
  138. vm.host = self
  139. return &vm, err
  140. }
  141. func (host *SHost) GetIHostNics() ([]cloudprovider.ICloudHostNetInterface, error) {
  142. wires, err := host.zone.GetIWires()
  143. if err != nil {
  144. return nil, errors.Wrap(err, "getIWires")
  145. }
  146. return cloudprovider.GetHostNetifs(host, wires), nil
  147. }
  148. type SInstanceType struct {
  149. UHostType string
  150. CPU int
  151. MemoryMB int
  152. GPU int
  153. }
  154. func ParseInstanceType(instanceType string) (SInstanceType, error) {
  155. i := SInstanceType{}
  156. segs := strings.Split(instanceType, ".")
  157. if len(segs) < 3 {
  158. return i, fmt.Errorf("invalid instance type %s", instanceType)
  159. } else if len(segs) >= 4 {
  160. gpu, err := strconv.Atoi(strings.TrimLeft(segs[3], "g"))
  161. if err != nil {
  162. return i, err
  163. }
  164. i.GPU = gpu
  165. }
  166. cpu, err := strconv.Atoi(strings.TrimLeft(segs[1], "c"))
  167. if err != nil {
  168. return i, err
  169. }
  170. mem, err := strconv.Atoi(strings.TrimLeft(segs[2], "m"))
  171. if err != nil {
  172. return i, err
  173. }
  174. i.UHostType = segs[0]
  175. i.CPU = cpu
  176. i.MemoryMB = mem * 1024
  177. return i, nil
  178. }
  179. func (self *SHost) _createVM(name, imgId string, sysDisk cloudprovider.SDiskInfo, cpu, memMB int, instanceType string,
  180. networkId, ipAddr, desc, passwd string,
  181. dataDisks []cloudprovider.SDiskInfo, secgroupIds []string, bc *billing.SBillingCycle) (string, error) {
  182. // 网络配置及安全组绑定
  183. net, _ := self.zone.region.getNetwork(networkId)
  184. if net == nil {
  185. return "", fmt.Errorf("invalid network ID %s", networkId)
  186. }
  187. if net.wire == nil {
  188. log.Errorf("network's wire is empty")
  189. return "", fmt.Errorf("network's wire is empty")
  190. }
  191. if net.wire.vpc == nil {
  192. log.Errorf("wire's vpc is empty")
  193. return "", fmt.Errorf("wire's vpc is empty")
  194. }
  195. if len(passwd) == 0 {
  196. return "", fmt.Errorf("CreateVM password should not be emtpty")
  197. }
  198. // 镜像及硬盘配置
  199. img, err := self.zone.region.GetImage(imgId)
  200. if err != nil {
  201. log.Errorf("GetImage %s fail %s", imgId, err)
  202. return "", err
  203. }
  204. if img.GetStatus() != api.CACHED_IMAGE_STATUS_ACTIVE {
  205. log.Errorf("image %s status %s, expect %s", imgId, img.GetStatus(), api.CACHED_IMAGE_STATUS_ACTIVE)
  206. return "", fmt.Errorf("image not ready")
  207. }
  208. disks := make([]SDisk, len(dataDisks)+1)
  209. disks[0].SizeGB = int(img.ImageSizeGB)
  210. if sysDisk.SizeGB > 0 && sysDisk.SizeGB > int(img.ImageSizeGB) {
  211. disks[0].SizeGB = sysDisk.SizeGB
  212. }
  213. disks[0].DiskType = sysDisk.StorageType
  214. for i, dataDisk := range dataDisks {
  215. disks[i+1].SizeGB = dataDisk.SizeGB
  216. disks[i+1].DiskType = dataDisk.StorageType
  217. }
  218. // 创建实例
  219. // https://docs.ucloud.cn/api/uhost-api/uhost_type
  220. // https://docs.ucloud.cn/compute/uhost/introduction/uhost/type
  221. var vmId string
  222. i, err := ParseInstanceType(instanceType)
  223. if err != nil {
  224. if cpu <= 0 || memMB <= 0 {
  225. return "", err
  226. } else {
  227. i.UHostType = "N2"
  228. i.CPU = cpu
  229. i.MemoryMB = memMB
  230. }
  231. }
  232. vmId, err = self.zone.region.CreateInstance(name, imgId, i.UHostType, passwd, net.wire.vpc.GetId(), networkId, secgroupIds, self.zone.ZoneId, desc, ipAddr, i.CPU, i.MemoryMB, i.GPU, disks, bc)
  233. if err != nil {
  234. return "", fmt.Errorf("Failed to create: %v", err)
  235. }
  236. return vmId, nil
  237. }
  238. // https://docs.ucloud.cn/api/uhost-api/create_uhost_instance
  239. // https://docs.ucloud.cn/api/uhost-api/specification
  240. // 支持8-30位字符, 不能包含[A-Z],[a-z],[0-9]和[()`~!@#$%^&*-+=_|{}[]:;'<>,.?/]之外的非法字符
  241. func (self *SRegion) CreateInstance(name, imageId, hostType, password, vpcId, SubnetId string, securityGroupId []string,
  242. zoneId, desc, ipAddr string, cpu, memMB, gpu int, disks []SDisk, bc *billing.SBillingCycle) (string, error) {
  243. params := NewUcloudParams()
  244. params.Set("Zone", zoneId)
  245. params.Set("ImageId", imageId)
  246. params.Set("Password", base64.StdEncoding.EncodeToString([]byte(password)))
  247. params.Set("LoginMode", "Password")
  248. params.Set("Name", name)
  249. params.Set("UHostType", hostType)
  250. params.Set("CPU", cpu)
  251. params.Set("Memory", memMB)
  252. params.Set("VPCId", vpcId)
  253. params.Set("SubnetId", SubnetId)
  254. for _, id := range securityGroupId {
  255. params.Set("SecurityGroupId", id)
  256. }
  257. if gpu > 0 {
  258. params.Set("GPU", gpu)
  259. }
  260. if bc != nil && bc.GetMonths() >= 1 && bc.GetMonths() < 10 {
  261. params.Set("ChargeType", "Month")
  262. params.Set("Quantity", bc.GetMonths())
  263. } else if bc != nil && bc.GetMonths() >= 10 && bc.GetMonths() < 12 {
  264. params.Set("ChargeType", "Year")
  265. params.Set("Quantity", 1)
  266. } else if bc != nil && bc.GetYears() >= 1 {
  267. params.Set("ChargeType", "Year")
  268. params.Set("Quantity", bc.GetYears())
  269. } else {
  270. params.Set("ChargeType", "Dynamic")
  271. }
  272. // boot disk
  273. params.Set("Disks.0.IsBoot", "True")
  274. params.Set("Disks.0.Type", disks[0].DiskType)
  275. params.Set("Disks.0.Size", disks[0].SizeGB)
  276. // data disk
  277. for i, disk := range disks[1:] {
  278. N := i + 1
  279. params.Set(fmt.Sprintf("Disks.%d.IsBoot", N), "False")
  280. params.Set(fmt.Sprintf("Disks.%d.Type", N), disk.DiskType)
  281. params.Set(fmt.Sprintf("Disks.%d.Size", N), disk.SizeGB)
  282. }
  283. type Ret struct {
  284. UHostIds []string
  285. }
  286. ret := Ret{}
  287. err := self.DoAction("CreateUHostInstance", params, &ret)
  288. if err != nil {
  289. return "", err
  290. }
  291. if len(ret.UHostIds) == 1 {
  292. return ret.UHostIds[0], nil
  293. }
  294. return "", fmt.Errorf("CreateInstance %d instance created. %s", len(ret.UHostIds), ret.UHostIds)
  295. }