host.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  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 zstack
  15. import (
  16. "fmt"
  17. "net/url"
  18. "strings"
  19. "github.com/pkg/errors"
  20. "yunion.io/x/jsonutils"
  21. "yunion.io/x/log"
  22. api "yunion.io/x/cloudmux/pkg/apis/compute"
  23. "yunion.io/x/cloudmux/pkg/cloudprovider"
  24. "yunion.io/x/cloudmux/pkg/multicloud"
  25. )
  26. type SHost struct {
  27. multicloud.SHostBase
  28. zone *SZone
  29. ZStackBasic
  30. Username string `json:"username"`
  31. SSHPort int `json:"sshPort"`
  32. ZoneUUID string `json:"zoneUuid"`
  33. ClusterUUID string `json:"clusterUuid"`
  34. ManagementIP string `json:"managementIp"`
  35. HypervisorType string `json:"hypervisorType"`
  36. State string `json:"state"`
  37. Status string `json:"status"`
  38. TotalCPUCapacity int `json:"totalCpuCapacity"`
  39. AvailableCPUCapacity int `json:"availableCpuCapacity"`
  40. CPUSockets int `json:"cpuSockets"`
  41. TotalMemoryCapacity int `json:"totalMemoryCapacity"`
  42. AvailableMemoryCapacity int `json:"availableMemoryCapacity"`
  43. CPUNum int `json:"cpuNum"`
  44. ZStackTime
  45. }
  46. func (region *SRegion) GetHosts(zoneId string, hostId string) ([]SHost, error) {
  47. hosts := []SHost{}
  48. params := url.Values{}
  49. if len(zoneId) > 0 {
  50. params.Add("q", "zone.uuid="+zoneId)
  51. }
  52. if len(hostId) > 0 {
  53. params.Add("q", "uuid="+hostId)
  54. }
  55. if SkipEsxi {
  56. params.Add("q", "hypervisorType!=ESX")
  57. }
  58. return hosts, region.client.listAll("hosts", params, &hosts)
  59. }
  60. func (region *SRegion) GetHost(hostId string) (*SHost, error) {
  61. host := &SHost{}
  62. err := region.client.getResource("hosts", hostId, host)
  63. if err != nil {
  64. return nil, err
  65. }
  66. zone, err := region.GetZone(host.ZoneUUID)
  67. if err != nil {
  68. return nil, err
  69. }
  70. host.zone = zone
  71. return host, nil
  72. }
  73. func (host *SHost) getIWires() ([]cloudprovider.ICloudWire, error) {
  74. wires, err := host.zone.region.GetWires(host.ZoneUUID, "", host.ClusterUUID)
  75. if err != nil {
  76. return nil, err
  77. }
  78. iwires := []cloudprovider.ICloudWire{}
  79. for i := 0; i < len(wires); i++ {
  80. iwires = append(iwires, &wires[i])
  81. }
  82. return iwires, nil
  83. }
  84. func (host *SHost) GetIStorages() ([]cloudprovider.ICloudStorage, error) {
  85. storages, err := host.zone.region.GetStorages(host.zone.UUID, host.ClusterUUID, "")
  86. if err != nil {
  87. return nil, err
  88. }
  89. istorages := []cloudprovider.ICloudStorage{}
  90. for i := 0; i < len(storages); i++ {
  91. storages[i].region = host.zone.region
  92. switch storages[i].Type {
  93. case StorageTypeLocal:
  94. localStorages, err := host.zone.region.getILocalStorages(storages[i].UUID, host.UUID)
  95. if err != nil {
  96. return nil, err
  97. }
  98. istorages = append(istorages, localStorages...)
  99. default:
  100. istorages = append(istorages, &storages[i])
  101. }
  102. }
  103. return istorages, nil
  104. }
  105. func (host *SHost) GetIStorageById(id string) (cloudprovider.ICloudStorage, error) {
  106. return host.zone.GetIStorageById(id)
  107. }
  108. func (host *SHost) GetIVMs() ([]cloudprovider.ICloudVM, error) {
  109. instances, err := host.zone.region.GetInstances(host.UUID, "", "")
  110. if err != nil {
  111. return nil, err
  112. }
  113. iInstnace := []cloudprovider.ICloudVM{}
  114. for i := 0; i < len(instances); i++ {
  115. instances[i].host = host
  116. iInstnace = append(iInstnace, &instances[i])
  117. }
  118. return iInstnace, nil
  119. }
  120. func (host *SHost) GetIVMById(instanceId string) (cloudprovider.ICloudVM, error) {
  121. instance, err := host.zone.region.GetInstance(instanceId)
  122. if err != nil {
  123. return nil, err
  124. }
  125. instance.host = host
  126. return instance, nil
  127. }
  128. func (host *SHost) GetId() string {
  129. return host.UUID
  130. }
  131. func (host *SHost) GetName() string {
  132. return host.Name
  133. }
  134. func (host *SHost) GetGlobalId() string {
  135. return host.GetId()
  136. }
  137. func (host *SHost) IsEmulated() bool {
  138. return false
  139. }
  140. func (host *SHost) GetStatus() string {
  141. if host.Status == "Connected" {
  142. return api.HOST_STATUS_RUNNING
  143. }
  144. return api.HOST_STATUS_UNKNOWN
  145. }
  146. func (host *SHost) Refresh() error {
  147. return nil
  148. }
  149. func (host *SHost) GetHostStatus() string {
  150. if host.Status == "Connected" {
  151. return api.HOST_ONLINE
  152. }
  153. return api.HOST_OFFLINE
  154. }
  155. func (host *SHost) GetEnabled() bool {
  156. return host.State == "Enabled"
  157. }
  158. func (host *SHost) GetAccessIp() string {
  159. return host.ManagementIP
  160. }
  161. func (host *SHost) GetAccessMac() string {
  162. return ""
  163. }
  164. func (host *SHost) GetSysInfo() jsonutils.JSONObject {
  165. info := jsonutils.NewDict()
  166. info.Add(jsonutils.NewString(CLOUD_PROVIDER_ZSTACK), "manufacture")
  167. return info
  168. }
  169. func (host *SHost) GetSN() string {
  170. return ""
  171. }
  172. func (host *SHost) GetReservedMemoryMb() int {
  173. host.zone.fetchHostCmtbound()
  174. return host.zone.reservedMemeoryMb
  175. }
  176. func (host *SHost) GetCpuCmtbound() float32 {
  177. host.zone.fetchHostCmtbound()
  178. return host.zone.cpuCmtbound
  179. }
  180. func (host *SHost) GetMemCmtbound() float32 {
  181. host.zone.fetchHostCmtbound()
  182. return host.zone.memCmtbound
  183. }
  184. func (host *SHost) GetCpuCount() int {
  185. cpuCmtBound := host.GetCpuCmtbound()
  186. if cpuCmtBound > 0 {
  187. return int(float32(host.TotalCPUCapacity) / cpuCmtBound)
  188. }
  189. return host.TotalCPUCapacity
  190. }
  191. func (host *SHost) GetNodeCount() int8 {
  192. return int8(host.CPUSockets)
  193. }
  194. func (host *SHost) GetCpuDesc() string {
  195. return ""
  196. }
  197. func (host *SHost) GetCpuMhz() int {
  198. return 0
  199. }
  200. func (host *SHost) GetMemSizeMB() int {
  201. return host.TotalMemoryCapacity / 1024 / 1024
  202. }
  203. func (host *SHost) GetStorageSizeMB() int64 {
  204. storages, err := host.zone.region.GetStorages(host.zone.UUID, host.ClusterUUID, "")
  205. if err != nil {
  206. return 0
  207. }
  208. totalStorage := 0
  209. for _, storage := range storages {
  210. if storage.Type == StorageTypeLocal {
  211. localStorages, err := host.zone.region.GetLocalStorages(storage.UUID, host.UUID)
  212. if err != nil {
  213. return 0
  214. }
  215. for i := 0; i < len(localStorages); i++ {
  216. totalStorage += int(localStorages[i].TotalCapacity)
  217. }
  218. }
  219. }
  220. return int64(totalStorage) / 1024 / 1024
  221. }
  222. func (host *SHost) GetStorageType() string {
  223. return api.DISK_TYPE_HYBRID
  224. }
  225. func (host *SHost) GetHostType() string {
  226. return api.HOST_TYPE_ZSTACK
  227. }
  228. func (region *SRegion) cleanDisks(diskIds []string) {
  229. for i := 0; i < len(diskIds); i++ {
  230. err := region.DeleteDisk(diskIds[i])
  231. if err != nil {
  232. log.Errorf("clean disk %s error: %v", diskIds[i], err)
  233. }
  234. }
  235. }
  236. func (region *SRegion) createDataDisks(disks []cloudprovider.SDiskInfo, hostId string) ([]string, error) {
  237. diskIds := []string{}
  238. storages, err := region.GetStorages("", "", "")
  239. if err != nil {
  240. return nil, errors.Wrapf(err, "createDataDisks.GetStorages")
  241. }
  242. localstorages := []SLocalStorage{}
  243. for _, storage := range storages {
  244. if storage.Type == StorageTypeLocal {
  245. localstorage, _ := region.GetLocalStorage(storage.UUID, hostId)
  246. if localstorage != nil {
  247. localstorages = append(localstorages, *localstorage)
  248. }
  249. }
  250. }
  251. for i := 0; i < len(disks); i++ {
  252. storageInfo := strings.Split(disks[i].StorageExternalId, "/")
  253. if len(storageInfo) == 0 {
  254. return diskIds, fmt.Errorf("invalidate storage externalId: %s", disks[i].StorageExternalId)
  255. }
  256. storage, err := region.GetStorage(storageInfo[0])
  257. if err != nil {
  258. return diskIds, errors.Wrapf(err, "createDataDisks")
  259. }
  260. switch storage.Type {
  261. case StorageTypeCeph:
  262. poolName := ""
  263. for _, pool := range storage.Pools {
  264. if pool.Type == CephPoolTypeData {
  265. poolName = pool.PoolName
  266. }
  267. }
  268. if len(poolName) == 0 {
  269. return diskIds, fmt.Errorf("failed to found ceph data pool for storage %s to createDataDisk", storage.Name)
  270. }
  271. disk, err := region.CreateDisk(disks[i].Name, storage.UUID, "", poolName, disks[i].SizeGB, "")
  272. if err != nil {
  273. return diskIds, err
  274. }
  275. diskIds = append(diskIds, disk.UUID)
  276. case StorageTypeLocal:
  277. if len(localstorages) == 0 {
  278. return nil, fmt.Errorf("No validate localstorage")
  279. }
  280. var disk *SDisk
  281. var err error
  282. for _, localstorage := range localstorages {
  283. disk, err = region.CreateDisk(disks[i].Name, localstorage.primaryStorageID, hostId, "", disks[i].SizeGB, "")
  284. if err != nil {
  285. log.Warningf("createDataDisks error: %v", err)
  286. } else {
  287. diskIds = append(diskIds, disk.UUID)
  288. break
  289. }
  290. }
  291. if err != nil {
  292. return diskIds, err
  293. }
  294. default:
  295. disk, err := region.CreateDisk(disks[i].Name, storage.UUID, "", "", disks[i].SizeGB, "")
  296. if err != nil {
  297. return diskIds, err
  298. }
  299. diskIds = append(diskIds, disk.UUID)
  300. }
  301. }
  302. return diskIds, nil
  303. }
  304. func (host *SHost) CreateVM(desc *cloudprovider.SManagedVMCreateConfig) (cloudprovider.ICloudVM, error) {
  305. instance, err := host.zone.region._createVM(desc, host.ZoneUUID)
  306. if err != nil {
  307. return nil, errors.Wrapf(err, "host.zone.region._createVM")
  308. }
  309. diskIds, err := host.zone.region.createDataDisks(desc.DataDisks, instance.HostUUID)
  310. if err != nil {
  311. defer host.zone.region.cleanDisks(diskIds)
  312. defer host.zone.region.DeleteVM(instance.UUID)
  313. return nil, errors.Wrapf(err, "host.zone.region.createDataDisks")
  314. }
  315. err = host.zone.region.ResizeDisk(instance.RootVolumeUUID, int64(desc.SysDisk.SizeGB)*1024)
  316. if err != nil {
  317. log.Warningf("failed to resize system disk %s error: %v", instance.RootVolumeUUID, err)
  318. }
  319. for i := 0; i < len(diskIds); i++ {
  320. err = host.zone.region.AttachDisk(instance.UUID, diskIds[i])
  321. if err != nil {
  322. log.Errorf("failed to attach disk %s into instance %s error: %v", diskIds[i], instance.Name, err)
  323. }
  324. }
  325. for _, id := range desc.ExternalSecgroupIds {
  326. err = host.zone.region.AssignSecurityGroup(instance.UUID, id)
  327. if err != nil {
  328. return nil, err
  329. }
  330. }
  331. return host.GetIVMById(instance.UUID)
  332. }
  333. func (region *SRegion) _createVM(desc *cloudprovider.SManagedVMCreateConfig, zoneId string) (*SInstance, error) {
  334. l3Id := strings.Split(desc.ExternalNetworkId, "/")[0]
  335. if len(l3Id) == 0 {
  336. return nil, fmt.Errorf("invalid networkid: %s", desc.ExternalNetworkId)
  337. }
  338. _, err := region.GetL3Network(l3Id)
  339. if err != nil {
  340. log.Errorf("failed to found l3network %s error: %v", l3Id, err)
  341. return nil, err
  342. }
  343. offerings := map[string]string{}
  344. if len(desc.InstanceType) > 0 {
  345. offering, err := region.GetInstanceOfferingByType(desc.InstanceType)
  346. if err != nil {
  347. if errors.Cause(err) == cloudprovider.ErrNotFound {
  348. offering, err = region.CreateInstanceOffering(desc.InstanceType, desc.Cpu, desc.MemoryMB, "UserVm")
  349. if err != nil {
  350. return nil, err
  351. }
  352. } else {
  353. return nil, err
  354. }
  355. }
  356. offerings[offering.Name] = offering.UUID
  357. } else {
  358. _offerings, err := region.GetInstanceOfferings("", "", desc.Cpu, desc.MemoryMB)
  359. if err != nil {
  360. return nil, err
  361. }
  362. for _, offering := range _offerings {
  363. offerings[offering.Name] = offering.UUID
  364. }
  365. if len(offerings) == 0 {
  366. return nil, fmt.Errorf("instance type %dC%dMB not avaiable", desc.Cpu, desc.MemoryMB)
  367. }
  368. }
  369. return region.CreateInstance(desc, l3Id, zoneId, offerings)
  370. }
  371. func (region *SRegion) CreateInstance(desc *cloudprovider.SManagedVMCreateConfig, l3Id, zoneId string, offerings map[string]string) (*SInstance, error) {
  372. instance := &SInstance{}
  373. systemTags := []string{
  374. "createWithoutCdRom::true",
  375. "usbRedirect::false",
  376. "vmConsoleMode::vnc",
  377. "cleanTraffic::false",
  378. }
  379. if len(desc.IpAddr) > 0 {
  380. systemTags = append(systemTags, fmt.Sprintf("staticIp::%s::%s", l3Id, desc.IpAddr))
  381. }
  382. if len(desc.UserData) > 0 {
  383. systemTags = append(systemTags, "userdata::"+desc.UserData)
  384. }
  385. if len(desc.PublicKey) > 0 {
  386. systemTags = append(systemTags, "sshkey::"+desc.PublicKey)
  387. }
  388. var err error
  389. for offerName, offerId := range offerings {
  390. params := map[string]interface{}{
  391. "params": map[string]interface{}{
  392. "name": desc.NameEn,
  393. "description": desc.Description,
  394. "instanceOfferingUuid": offerId,
  395. "imageUuid": desc.ExternalImageId,
  396. "l3NetworkUuids": []string{
  397. l3Id,
  398. },
  399. "zoneUuid": zoneId,
  400. "dataVolumeSystemTags": []string{},
  401. "rootVolumeSystemTags": []string{},
  402. "vmMachineType": "",
  403. "tagUuids": []string{},
  404. "defaultL3NetworkUuid": l3Id,
  405. "dataDiskOfferingUuids": []string{},
  406. "systemTags": systemTags,
  407. "vmNicConfig": []string{},
  408. },
  409. }
  410. log.Debugf("Try instanceOffering : %s", offerName)
  411. err = region.client.create("vm-instances", jsonutils.Marshal(params), instance)
  412. if err == nil {
  413. return instance, nil
  414. }
  415. log.Errorf("create %s instance failed error: %v", offerName, err)
  416. }
  417. if err != nil {
  418. return nil, err
  419. }
  420. return nil, fmt.Errorf("instance type %dC%dMB not avaiable", desc.Cpu, desc.MemoryMB)
  421. }
  422. func (host *SHost) GetIHostNics() ([]cloudprovider.ICloudHostNetInterface, error) {
  423. wires, err := host.getIWires()
  424. if err != nil {
  425. return nil, errors.Wrap(err, "getIWires")
  426. }
  427. return cloudprovider.GetHostNetifs(host, wires), nil
  428. }
  429. func (host *SHost) GetIsMaintenance() bool {
  430. return false
  431. }
  432. func (host *SHost) GetVersion() string {
  433. return ""
  434. }