instance.go 26 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016
  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 proxmox
  15. import (
  16. "context"
  17. "fmt"
  18. "net/url"
  19. "regexp"
  20. "strconv"
  21. "strings"
  22. "yunion.io/x/jsonutils"
  23. "yunion.io/x/log"
  24. "yunion.io/x/pkg/errors"
  25. "yunion.io/x/pkg/util/osprofile"
  26. "yunion.io/x/pkg/utils"
  27. "yunion.io/x/cloudmux/pkg/apis"
  28. api "yunion.io/x/cloudmux/pkg/apis/compute"
  29. "yunion.io/x/cloudmux/pkg/cloudprovider"
  30. "yunion.io/x/cloudmux/pkg/multicloud"
  31. )
  32. var (
  33. rxIso = regexp.MustCompile(`(.*?),media`)
  34. rxDeviceID = regexp.MustCompile(`\d+`)
  35. rxDiskName = regexp.MustCompile(`(virtio|scsi|sata|ide)\d+`)
  36. rxDiskType = regexp.MustCompile(`\D+`)
  37. rxUnusedDiskName = regexp.MustCompile(`^(unused)\d+`)
  38. rxNicName = regexp.MustCompile(`net\d+`)
  39. rxSerialName = regexp.MustCompile(`serial\d+`)
  40. rxUsbName = regexp.MustCompile(`usb\d+`)
  41. )
  42. type (
  43. QemuDevices map[string]map[string]interface{}
  44. QemuDevice map[string]interface{}
  45. QemuDeviceParam []string
  46. )
  47. type Intermediate struct {
  48. HardwareAddress string `json:"hardware-address"`
  49. IPAddresses []struct {
  50. IPAddress string `json:"ip-address"`
  51. IPAddressType string `json:"ip-address-type"`
  52. Prefix int `json:"prefix"`
  53. } `json:"ip-addresses"`
  54. Name string `json:"name"`
  55. Statistics map[string]int64 `json:"statistics"`
  56. }
  57. type VmBase struct {
  58. Name string `json:"name"`
  59. Description string `json:"Description"`
  60. Tags string `json:"tags"`
  61. Args string `json:"args"`
  62. Bios string `json:"bios"`
  63. OnBoot int `json:"onboot"`
  64. Startup string `json:"startup"`
  65. Tablet int `json:"tablet"`
  66. Ostype string `json:"ostype"`
  67. Memory int64 `json:"memory"`
  68. Balloon int64 `json:"balloon"`
  69. Cores int64 `json:"cores"`
  70. Vcpus int64 `json:"vcpus"`
  71. Sockets int64 `json:"sockets"`
  72. Cpu string `json:"cpu"`
  73. Numa int `json:"numa"`
  74. Hotplug string `json:"hotplug"`
  75. Boot string `json:"boot"`
  76. Bootdisk string `json:"bootdisk"`
  77. Kvm int `json:"kvm"`
  78. Scsihw string `json:"scsihw"`
  79. Hookscript string `json:"hookscript"`
  80. Machine string `json:"machine"`
  81. Ide2 string `json:"ide2,omitempty"`
  82. Ciuser string `json:"ciuser"`
  83. Cipassword string `json:"cipassword"`
  84. Cicustom string `json:"cicustom"`
  85. Searchdomain string `json:"searchdomain"`
  86. Nameserver string `json:"nameserver"`
  87. Sshkeys string `json:"sshkeys"`
  88. }
  89. type SInstanceDisk struct {
  90. Storage string
  91. VolId string
  92. }
  93. type SInstance struct {
  94. multicloud.SInstanceBase
  95. ProxmoxTags
  96. host *SHost
  97. QemuNetworks []SInstanceNic
  98. PowerState string
  99. Node string
  100. VmID int `json:"vmid"`
  101. Name string `json:"name"`
  102. Description string `json:"desc"`
  103. Pool string `json:"pool,omitempty"`
  104. Bios string `json:"bios"`
  105. EFIDisk QemuDevice `json:"efidisk,omitempty"`
  106. Machine string `json:"machine,omitempty"`
  107. Onboot bool `json:"onboot"`
  108. Startup string `json:"startup,omitempty"`
  109. Tablet bool `json:"tablet"`
  110. Memory int `json:"memory"`
  111. Balloon int `json:"balloon"`
  112. QemuOs string `json:"ostype"`
  113. QemuCores int `json:"cores"`
  114. QemuSockets int `json:"sockets"`
  115. QemuVcpus int `json:"vcpus"`
  116. QemuCpu string `json:"cpu"`
  117. QemuNuma bool `json:"numa"`
  118. QemuKVM bool `json:"kvm"`
  119. Hotplug string `json:"hotplug"`
  120. QemuIso string `json:"iso"`
  121. QemuPxe bool `json:"pxe"`
  122. FullClone *int `json:"fullclone"`
  123. Boot string `json:"boot"`
  124. BootDisk string `json:"bootdisk,omitempty"`
  125. Scsihw string `json:"scsihw,omitempty"`
  126. QemuDisks map[string][]struct {
  127. Driver string
  128. DiskId string
  129. } `json:"disk"`
  130. QemuUnusedDisks QemuDevices `json:"unused_disk"`
  131. QemuVga QemuDevice `json:"vga,omitempty"`
  132. QemuSerials QemuDevices `json:"serial,omitempty"`
  133. QemuUsbs QemuDevices `json:"usb,omitempty"`
  134. Hookscript string `json:"hookscript,omitempty"`
  135. Tags string `json:"tags"`
  136. Args string `json:"args"`
  137. // Deprecated single disk.
  138. DiskSize float64 `json:"diskGB"`
  139. Storage string `json:"storage"`
  140. StorageType string `json:"storageType"` // virtio|scsi (cloud-init defaults to scsi)
  141. // Deprecated single nic.
  142. QemuNicModel string `json:"nic"`
  143. QemuBridge string `json:"bridge"`
  144. QemuVlanTag int `json:"vlan"`
  145. QemuMacAddr string `json:"mac"`
  146. // cloud-init options
  147. CIuser string `json:"ciuser"`
  148. CIpassword string `json:"cipassword"`
  149. CIcustom string `json:"cicustom"`
  150. Searchdomain string `json:"searchdomain"`
  151. Nameserver string `json:"nameserver"`
  152. Sshkeys string `json:"sshkeys"`
  153. }
  154. func (self *SInstance) GetName() string {
  155. if len(self.Name) > 0 {
  156. return self.Name
  157. }
  158. return self.GetId()
  159. }
  160. func (self *SInstance) GetId() string {
  161. return strconv.Itoa(self.VmID)
  162. }
  163. func (self *SInstance) GetGlobalId() string {
  164. return self.GetId()
  165. }
  166. func (self *SInstance) Refresh() error {
  167. id := strconv.Itoa(int(self.VmID))
  168. ins, err := self.host.zone.region.GetInstance(id)
  169. if err != nil {
  170. return err
  171. }
  172. self.QemuDisks = ins.QemuDisks
  173. return jsonutils.Update(self, ins)
  174. }
  175. func (self *SInstance) AttachDisk(ctx context.Context, diskId string) error {
  176. return cloudprovider.ErrNotSupported
  177. }
  178. func (self *SInstance) CreateDisk(ctx context.Context, opts *cloudprovider.GuestDiskCreateOptions) (string, error) {
  179. body := map[string]string{}
  180. params := url.Values{}
  181. storage, err := self.host.zone.region.GetStorage(opts.StorageId)
  182. if err != nil {
  183. return "", err
  184. }
  185. driver := fmt.Sprintf("scsi%d", opts.Idx)
  186. body[driver] = fmt.Sprintf("%s:%d", storage.Storage, opts.SizeMb/1024)
  187. res := fmt.Sprintf("/nodes/%s/qemu/%d/config", self.Node, self.VmID)
  188. err = self.host.zone.region.put(res, params, jsonutils.Marshal(body))
  189. if err != nil {
  190. return "", err
  191. }
  192. err = self.Refresh()
  193. if err != nil {
  194. return "", err
  195. }
  196. for storageName, disks := range self.QemuDisks {
  197. if storageName != storage.Storage {
  198. continue
  199. }
  200. for i := range disks {
  201. if disks[i].Driver != driver {
  202. continue
  203. }
  204. volumes, err := self.host.zone.region.GetDisks(self.Node, storage.Storage)
  205. if err != nil {
  206. return "", err
  207. }
  208. for i := range volumes {
  209. volumes[i].storage = storage
  210. if strings.HasSuffix(volumes[i].GetGlobalId(), "|"+volumes[i].VolId) {
  211. return volumes[i].GetGlobalId(), nil
  212. }
  213. }
  214. }
  215. }
  216. return "", errors.Wrapf(cloudprovider.ErrNotFound, "after created")
  217. }
  218. func (self *SInstance) ChangeConfig(ctx context.Context, opts *cloudprovider.SManagedVMChangeConfig) error {
  219. return self.host.zone.region.ChangeConfig(self.VmID, opts.Cpu, opts.MemoryMB)
  220. }
  221. func (self *SInstance) DeleteVM(ctx context.Context) error {
  222. return self.host.zone.region.DeleteVM(self.VmID)
  223. }
  224. func (self *SInstance) DeployVM(ctx context.Context, opts *cloudprovider.SInstanceDeployOptions) error {
  225. return self.host.zone.region.ResetVmPassword(self.VmID, opts.Username, opts.Password)
  226. }
  227. func (self *SInstance) DetachDisk(ctx context.Context, diskId string) error {
  228. diskInfo := strings.Split(diskId, "|")
  229. storageName, volId := "", ""
  230. if len(diskInfo) == 2 {
  231. storageName, volId = diskInfo[0], diskInfo[1]
  232. } else if len(diskInfo) == 3 {
  233. storageName, volId = diskInfo[1], diskInfo[2]
  234. } else {
  235. return fmt.Errorf("invalid diskId %s", diskId)
  236. }
  237. for _storageName, disks := range self.QemuDisks {
  238. if storageName != _storageName {
  239. continue
  240. }
  241. for _, disk := range disks {
  242. if disk.DiskId == volId {
  243. return self.host.zone.region.DetachDisk(self.Node, self.VmID, disk.Driver)
  244. }
  245. }
  246. }
  247. return nil
  248. }
  249. func (self *SInstance) GetBios() cloudprovider.TBiosType {
  250. return cloudprovider.ToBiosType(self.Bios)
  251. }
  252. func (self *SInstance) GetBootOrder() string {
  253. return "cdn"
  254. }
  255. func (self *SInstance) GetError() error {
  256. return nil
  257. }
  258. func (self *SInstance) GetHostname() string {
  259. return ""
  260. }
  261. func (self *SInstance) GetHypervisor() string {
  262. return api.HYPERVISOR_PROXMOX
  263. }
  264. func (self *SInstance) VMIdExists(vmId int) (bool, error) {
  265. resources, err := self.host.zone.region.GetClusterVmResources()
  266. if err != nil {
  267. return false, err
  268. }
  269. _, res := resources[vmId]
  270. return res, nil
  271. }
  272. func (self *SInstance) GetIDisks() ([]cloudprovider.ICloudDisk, error) {
  273. ret := []cloudprovider.ICloudDisk{}
  274. ins, err := self.host.zone.region.GetInstance(fmt.Sprintf("%d", self.VmID))
  275. if err != nil {
  276. return nil, err
  277. }
  278. for storageName, disks := range ins.QemuDisks {
  279. diskIds := []string{}
  280. for i := range disks {
  281. if strings.HasSuffix(disks[i].DiskId, ".iso") {
  282. continue
  283. }
  284. diskIds = append(diskIds, disks[i].DiskId)
  285. }
  286. disks, err := self.host.zone.region.GetDisks(self.host.Node, storageName)
  287. if err != nil {
  288. return nil, errors.Wrapf(err, "GetDisks")
  289. }
  290. storages, err := self.host.zone.region.GetStoragesByHost(self.Node)
  291. if err != nil {
  292. return nil, err
  293. }
  294. var storage *SStorage
  295. for i := range storages {
  296. if storages[i].Storage == storageName {
  297. storage = &storages[i]
  298. }
  299. }
  300. if storage == nil {
  301. return nil, errors.Wrapf(cloudprovider.ErrNotFound, "search storage %s", storageName)
  302. }
  303. for i := range disks {
  304. if utils.IsInStringArray(disks[i].VolId, diskIds) {
  305. disks[i].storage = storage
  306. ret = append(ret, &disks[i])
  307. }
  308. }
  309. }
  310. return ret, nil
  311. }
  312. func (self *SInstance) GetIEIP() (cloudprovider.ICloudEIP, error) {
  313. return nil, cloudprovider.ErrNotSupported
  314. }
  315. func (self *SInstance) GetIHost() cloudprovider.ICloudHost {
  316. return self.host
  317. }
  318. func (self *SInstance) GetINics() ([]cloudprovider.ICloudNic, error) {
  319. ret := []cloudprovider.ICloudNic{}
  320. for i := range self.QemuNetworks {
  321. self.QemuNetworks[i].ins = self
  322. ret = append(ret, &self.QemuNetworks[i])
  323. }
  324. return ret, nil
  325. }
  326. func (self *SInstance) GetInstanceType() string {
  327. return fmt.Sprintf("ecs.g1.c%dm%d", self.GetVcpuCount(), self.GetVmemSizeMB()/1024)
  328. }
  329. func (self *SInstance) GetMachine() string {
  330. return self.Machine
  331. }
  332. func (self *SInstance) GetStatus() string {
  333. switch strings.ToLower(self.PowerState) {
  334. case "running":
  335. return api.VM_RUNNING
  336. case "stopped":
  337. return api.VM_READY
  338. case "paused":
  339. return api.VM_SUSPEND
  340. }
  341. return api.VM_UNKNOWN
  342. }
  343. func (self *SInstance) GetFullOsName() string {
  344. return ""
  345. }
  346. func (self *SInstance) GetOsType() cloudprovider.TOsType {
  347. isWin, _ := regexp.MatchString("(wxp|w2k|w2k3|w2k8|wvista|win7|win8|win10|win11)", self.QemuOs)
  348. if isWin == true {
  349. return cloudprovider.TOsType(osprofile.OS_TYPE_WINDOWS)
  350. } else {
  351. return cloudprovider.TOsType(osprofile.OS_TYPE_LINUX)
  352. }
  353. }
  354. func (ins *SInstance) GetOsArch() string {
  355. if utils.IsInStringArray(ins.QemuCpu, []string{"neoverse-n1"}) || strings.HasPrefix(ins.QemuCpu, "cortex-a") {
  356. return apis.OS_ARCH_AARCH64
  357. }
  358. return ins.host.GetCpuArchitecture()
  359. }
  360. func (ins *SInstance) GetOsDist() string {
  361. return ""
  362. }
  363. func (ins *SInstance) GetOsVersion() string {
  364. return ""
  365. }
  366. func (ins *SInstance) GetOsLang() string {
  367. return ""
  368. }
  369. func (self *SInstance) GetProjectId() string {
  370. return ""
  371. }
  372. func (self *SInstance) GetVNCInfo(input *cloudprovider.ServerVncInput) (*cloudprovider.ServerVncOutput, error) {
  373. vnc, err := self.host.zone.region.GetVNCInfo(self.Node, self.VmID)
  374. if err != nil {
  375. return nil, err
  376. }
  377. ret := &cloudprovider.ServerVncOutput{}
  378. ret.Protocol = "vnc"
  379. ret.Host = self.host.zone.region.client.host
  380. ret.Port = int64(vnc.Port)
  381. ret.Password = vnc.Ticket
  382. ret.Hypervisor = api.HYPERVISOR_PROXMOX
  383. return ret, nil
  384. }
  385. func (self *SInstance) GetVcpuCount() int {
  386. return int(self.QemuCores * self.QemuSockets)
  387. }
  388. func (self *SInstance) GetVmemSizeMB() int {
  389. return int(self.Memory)
  390. }
  391. func (self *SInstance) GetVga() string {
  392. return "std"
  393. }
  394. func (self *SInstance) GetVdi() string {
  395. return "vnc"
  396. }
  397. func (self *SInstance) RebuildRoot(ctx context.Context, desc *cloudprovider.SManagedVMRebuildRootConfig) (string, error) {
  398. return "", cloudprovider.ErrNotSupported
  399. }
  400. func (self *SInstance) GetSecurityGroupIds() ([]string, error) {
  401. return []string{}, nil
  402. }
  403. func (self *SInstance) SetSecurityGroups(secgroupIds []string) error {
  404. return cloudprovider.ErrNotSupported
  405. }
  406. func (self *SInstance) StartVM(ctx context.Context) error {
  407. return self.host.zone.region.StartVm(self.VmID)
  408. }
  409. func (self *SInstance) StopVM(ctx context.Context, opts *cloudprovider.ServerStopOptions) error {
  410. if self.GetStatus() == api.VM_READY {
  411. return nil
  412. }
  413. return self.host.zone.region.StopVm(self.VmID)
  414. }
  415. func (self *SInstance) UpdateUserData(userData string) error {
  416. return cloudprovider.ErrNotSupported
  417. }
  418. func (self *SInstance) UpdateVM(ctx context.Context, input cloudprovider.SInstanceUpdateOptions) error {
  419. return cloudprovider.ErrNotSupported
  420. }
  421. // readDeviceConfig - get standard sub-conf strings where `key=value` and update conf map.
  422. func (confMap QemuDevice) readDeviceConfig(confList []string) error {
  423. // Add device config.
  424. for _, conf := range confList {
  425. key, value := ParseSubConf(conf, "=")
  426. confMap[key] = value
  427. }
  428. return nil
  429. }
  430. func (self *SRegion) GetVmAgentNetworkInterfaces(node string, VmId int) (map[string]string, error) {
  431. intermediates := []Intermediate{}
  432. ipMap := map[string]string{}
  433. res := fmt.Sprintf("/nodes/%s/qemu/%d/agent/network-get-interfaces", node, VmId)
  434. err := self.getAgent(res, url.Values{}, &intermediates)
  435. if err != nil {
  436. return ipMap, errors.Wrap(err, "GetVmAgentNetworkInterfaces")
  437. }
  438. for _, intermediate := range intermediates {
  439. for _, addr := range intermediate.IPAddresses {
  440. if strings.ToLower(addr.IPAddressType) == "ipv4" {
  441. ipMap[intermediate.HardwareAddress] = addr.IPAddress
  442. }
  443. }
  444. }
  445. return ipMap, nil
  446. }
  447. func (self *SRegion) GetVmPowerStatus(node string, VmId int) string {
  448. current := map[string]string{}
  449. res := fmt.Sprintf("/nodes/%s/qemu/%d/status/current", node, VmId)
  450. err := self.get(res, url.Values{}, &current)
  451. if err != nil {
  452. return "unkown"
  453. }
  454. power := "unkown"
  455. if _, ok := current["qmpstatus"]; ok {
  456. power = current["qmpstatus"]
  457. }
  458. return power
  459. }
  460. func (self *SRegion) GetQemuConfig(node string, VmId int) (*SInstance, error) {
  461. res := fmt.Sprintf("/nodes/%s/qemu/%d/config", node, VmId)
  462. vmConfig := map[string]interface{}{}
  463. vmBase := &VmBase{
  464. Bios: "seabios",
  465. OnBoot: 1,
  466. Tablet: 1,
  467. Ostype: "other",
  468. Memory: 0,
  469. Balloon: 0,
  470. Cores: 0,
  471. Vcpus: 0,
  472. Sockets: 0,
  473. Cpu: "host",
  474. Numa: 0,
  475. Hotplug: "network,disk,usb",
  476. Boot: "cdn",
  477. Kvm: 1,
  478. Scsihw: "lsi",
  479. Machine: "i440fx",
  480. }
  481. err := self.get(res, url.Values{}, &vmConfig)
  482. if err != nil {
  483. return nil, err
  484. }
  485. err = jsonutils.Update(vmBase, vmConfig)
  486. if err != nil {
  487. return nil, err
  488. }
  489. config := SInstance{
  490. VmID: int(VmId),
  491. Name: vmBase.Name,
  492. Description: strings.TrimSpace(vmBase.Description),
  493. Tags: strings.TrimSpace(vmBase.Tags),
  494. Args: strings.TrimSpace(vmBase.Args),
  495. Bios: vmBase.Bios,
  496. EFIDisk: QemuDevice{},
  497. Machine: vmBase.Machine,
  498. Onboot: Itob(vmBase.OnBoot),
  499. Startup: vmBase.Startup,
  500. Tablet: Itob(vmBase.Tablet),
  501. QemuOs: vmBase.Ostype,
  502. Memory: int(vmBase.Memory),
  503. QemuCores: int(vmBase.Cores),
  504. QemuSockets: int(vmBase.Sockets),
  505. QemuCpu: vmBase.Cpu,
  506. QemuNuma: Itob(vmBase.Numa),
  507. QemuKVM: Itob(vmBase.Kvm),
  508. Hotplug: vmBase.Hotplug,
  509. QemuVlanTag: -1,
  510. Boot: vmBase.Boot,
  511. BootDisk: vmBase.Bootdisk,
  512. Scsihw: vmBase.Scsihw,
  513. Hookscript: vmBase.Hookscript,
  514. QemuDisks: map[string][]struct {
  515. Driver string
  516. DiskId string
  517. }{},
  518. QemuUnusedDisks: QemuDevices{},
  519. QemuVga: QemuDevice{},
  520. QemuNetworks: []SInstanceNic{},
  521. QemuSerials: QemuDevices{},
  522. QemuUsbs: QemuDevices{},
  523. Node: node,
  524. CIuser: vmBase.Ciuser,
  525. CIpassword: vmBase.Cipassword,
  526. Searchdomain: vmBase.Searchdomain,
  527. Nameserver: vmBase.Nameserver,
  528. }
  529. // vmConfig Sample: map[ cpu:host
  530. // net0:virtio=62:DF:XX:XX:XX:XX,bridge=vmbr0
  531. // ide2:local:iso/xxx-xx.iso,media=cdrom memory:2048
  532. // smbios1:uuid=8b3bf833-aad8-4545-xxx-xxxxxxx digest:aa6ce5xxxxx1b9ce33e4aaeff564d4 sockets:1
  533. // name:terraform-ubuntu1404-template bootdisk:virtio0
  534. // virtio0:ProxmoxxxxISCSI:vm-1014-disk-2,size=4G
  535. // description:Base image
  536. // cores:2 ostype:l26
  537. if vmConfig["ide2"] != nil {
  538. isoMatch := rxIso.FindStringSubmatch(vmConfig["ide2"].(string))
  539. config.QemuIso = isoMatch[1]
  540. }
  541. if _, ok := vmConfig["sshkeys"]; ok {
  542. config.Sshkeys, _ = url.PathUnescape(vmConfig["sshkeys"].(string))
  543. }
  544. config.PowerState = self.GetVmPowerStatus(node, VmId)
  545. // Add disks.
  546. diskNames := map[string]string{}
  547. for k := range vmConfig {
  548. if diskName := rxDiskName.FindStringSubmatch(k); len(diskName) > 0 {
  549. diskNames[k] = diskName[0]
  550. }
  551. }
  552. for driver, diskName := range diskNames {
  553. diskConfStr := vmConfig[diskName].(string)
  554. diskConfMap := ParsePMConf(diskConfStr, "volume")
  555. if diskConfMap["volume"].(string) == "none" {
  556. continue
  557. }
  558. storageName, _ := ParseSubConf(diskConfMap["volume"].(string), ":")
  559. _, ok := config.QemuDisks[storageName]
  560. if !ok {
  561. config.QemuDisks[storageName] = []struct {
  562. Driver string
  563. DiskId string
  564. }{}
  565. }
  566. config.QemuDisks[storageName] = append(config.QemuDisks[storageName], struct {
  567. Driver string
  568. DiskId string
  569. }{
  570. Driver: driver,
  571. DiskId: diskConfMap["volume"].(string),
  572. })
  573. }
  574. // Add unused disks
  575. // unused0:local:100/vm-100-disk-1.qcow2
  576. unusedDiskNames := []string{}
  577. for k := range vmConfig {
  578. // look for entries from the config in the format "unusedX:<storagepath>" where X is an integer
  579. if unusedDiskName := rxUnusedDiskName.FindStringSubmatch(k); len(unusedDiskName) > 0 {
  580. unusedDiskNames = append(unusedDiskNames, unusedDiskName[0])
  581. }
  582. }
  583. if len(unusedDiskNames) > 0 {
  584. log.Debugf("[DEBUG] unusedDiskNames: %v", unusedDiskNames)
  585. }
  586. for _, unusedDiskName := range unusedDiskNames {
  587. unusedDiskConfStr := vmConfig[unusedDiskName].(string)
  588. finalDiskConfMap := QemuDevice{}
  589. // parse "unused0" to get the id '0' as an int
  590. id := rxDeviceID.FindStringSubmatch(unusedDiskName)
  591. slotID, err := strconv.Atoi(id[0])
  592. if err != nil {
  593. return nil, errors.Errorf("Unable to parse unused disk id from input string '%s' .", unusedDiskName)
  594. }
  595. finalDiskConfMap["slot"] = slotID
  596. // parse the attributes from the unused disk
  597. // extract the storage and file path from the unused disk entry
  598. parsedUnusedDiskMap := ParsePMConf(unusedDiskConfStr, "storage+file")
  599. storageName, fileName := ParseSubConf(parsedUnusedDiskMap["storage+file"].(string), ":")
  600. finalDiskConfMap["storage"] = storageName
  601. finalDiskConfMap["file"] = fileName
  602. volId := parsedUnusedDiskMap["storage+file"].(string)
  603. config.QemuUnusedDisks[volId] = finalDiskConfMap
  604. }
  605. //Display
  606. if vga, ok := vmConfig["vga"]; ok {
  607. vgaList := strings.Split(vga.(string), ",")
  608. vgaMap := QemuDevice{}
  609. // TODO: keep going if error?
  610. err = vgaMap.readDeviceConfig(vgaList)
  611. if err != nil {
  612. log.Debugf("[ERROR] %q", err)
  613. }
  614. if len(vgaMap) > 0 {
  615. config.QemuVga = vgaMap
  616. }
  617. }
  618. // Add networks.
  619. nicNames := []string{}
  620. ipMap := make(map[string]string)
  621. if config.PowerState == "running" {
  622. ipMap, _ = self.GetVmAgentNetworkInterfaces(node, VmId)
  623. }
  624. for k := range vmConfig {
  625. if nicName := rxNicName.FindStringSubmatch(k); len(nicName) > 0 {
  626. nicNames = append(nicNames, nicName[0])
  627. }
  628. }
  629. for _, nicName := range nicNames {
  630. nicConfStr := vmConfig[nicName]
  631. nicConfList := strings.Split(nicConfStr.(string), ",")
  632. //id := rxDeviceID.FindStringSubmatch(nicName)
  633. model, macaddr := ParseSubConf(nicConfList[0], "=")
  634. _, network := ParseSubConf(nicConfList[1], "=")
  635. //nicID := fmt.Sprintf("%d:%s", VmId, nicName)
  636. // Add model and MAC address.
  637. nicConf := SInstanceNic{
  638. NicId: network.(string),
  639. Model: model,
  640. MacAddr: strings.ToLower(macaddr.(string)),
  641. NetworkId: fmt.Sprintf("network/%s/%s", node, network),
  642. }
  643. if ip, ok := ipMap[nicConf.MacAddr]; ok {
  644. nicConf.IpAddr = ip
  645. }
  646. // And device config to networks.
  647. config.QemuNetworks = append(config.QemuNetworks, nicConf)
  648. }
  649. // Add serials
  650. serialNames := []string{}
  651. for k := range vmConfig {
  652. if serialName := rxSerialName.FindStringSubmatch(k); len(serialName) > 0 {
  653. serialNames = append(serialNames, serialName[0])
  654. }
  655. }
  656. for _, serialName := range serialNames {
  657. id := rxDeviceID.FindStringSubmatch(serialName)
  658. serialID, _ := strconv.Atoi(id[0])
  659. serialConfMap := QemuDevice{
  660. "id": serialID,
  661. "type": vmConfig[serialName],
  662. }
  663. // And device config to serials map.
  664. if len(serialConfMap) > 0 {
  665. config.QemuSerials[serialName] = serialConfMap
  666. }
  667. }
  668. // Add usbs
  669. usbNames := []string{}
  670. for k := range vmConfig {
  671. if usbName := rxUsbName.FindStringSubmatch(k); len(usbName) > 0 {
  672. usbNames = append(usbNames, usbName[0])
  673. }
  674. }
  675. for _, usbName := range usbNames {
  676. usbConfStr := vmConfig[usbName]
  677. usbConfList := strings.Split(usbConfStr.(string), ",")
  678. id := rxDeviceID.FindStringSubmatch(usbName)
  679. usbID, _ := strconv.Atoi(id[0])
  680. _, host := ParseSubConf(usbConfList[0], "=")
  681. usbConfMap := QemuDevice{
  682. "id": usbID,
  683. "host": host,
  684. }
  685. err = usbConfMap.readDeviceConfig(usbConfList[1:])
  686. if err != nil {
  687. log.Debugf("[ERROR] %q", err)
  688. }
  689. if usbConfMap["usb3"] == 1 {
  690. usbConfMap["usb3"] = true
  691. }
  692. // And device config to usbs map.
  693. if len(usbConfMap) > 0 {
  694. config.QemuUsbs[usbName] = usbConfMap
  695. }
  696. }
  697. return &config, nil
  698. }
  699. func (self *SRegion) GetInstances(hostId string) ([]SInstance, error) {
  700. ret := []SInstance{}
  701. resources, err := self.GetClusterVmResources()
  702. if err != nil {
  703. return nil, err
  704. }
  705. for _, res := range resources {
  706. if res.NodeId == hostId || len(hostId) == 0 {
  707. instance, err := self.GetQemuConfig(res.Node, res.VmId)
  708. if err != nil {
  709. log.Warningf("get pve vm %s %d error: %v", res.Node, res.VmId, err)
  710. continue
  711. }
  712. ret = append(ret, *instance)
  713. }
  714. }
  715. return ret, nil
  716. }
  717. func (self *SRegion) GetInstance(id string) (*SInstance, error) {
  718. resources, err := self.GetClusterVmResources()
  719. if err != nil {
  720. return nil, err
  721. }
  722. nodeName := ""
  723. vmId, _ := strconv.Atoi(id)
  724. if resource, ok := resources[vmId]; !ok {
  725. return nil, errors.Wrapf(cloudprovider.ErrNotFound, "%s", id)
  726. } else {
  727. nodeName = resource.Node
  728. }
  729. return self.GetQemuConfig(nodeName, vmId)
  730. }
  731. func (self *SRegion) StartVm(vmId int) error {
  732. resources, err := self.GetClusterVmResources()
  733. if err != nil {
  734. return err
  735. }
  736. nodeName := ""
  737. if resource, ok := resources[vmId]; !ok {
  738. return errors.Errorf("start VM id %d", vmId)
  739. } else {
  740. nodeName = resource.Node
  741. }
  742. res := fmt.Sprintf("/nodes/%s/qemu/%d/status/start", nodeName, vmId)
  743. params := url.Values{}
  744. _, err = self.post(res, params)
  745. return err
  746. }
  747. func (self *SRegion) StopVm(vmId int) error {
  748. resources, err := self.GetClusterVmResources()
  749. if err != nil {
  750. return err
  751. }
  752. nodeName := ""
  753. if resource, ok := resources[vmId]; !ok {
  754. return errors.Errorf("start VM id %d", vmId)
  755. } else {
  756. nodeName = resource.Node
  757. }
  758. res := fmt.Sprintf("/nodes/%s/qemu/%d/status/stop", nodeName, vmId)
  759. params := url.Values{}
  760. _, err = self.post(res, params)
  761. return err
  762. }
  763. func (self *SRegion) DetachDisk(node string, vmId int, driver string) error {
  764. body := map[string]string{}
  765. params := url.Values{}
  766. body["delete"] = driver
  767. res := fmt.Sprintf("/nodes/%s/qemu/%d/config", node, vmId)
  768. return self.put(res, params, jsonutils.Marshal(body))
  769. }
  770. func (self *SRegion) ChangeConfig(vmId int, cpu int, memMb int) error {
  771. vm, err := self.GetInstance(strconv.Itoa(int(vmId)))
  772. body := map[string]interface{}{}
  773. if err != nil {
  774. return errors.Wrapf(err, "ChangeConfig(%d)", vmId)
  775. }
  776. changed := false
  777. if cpu > 0 {
  778. vm.QemuCores = 1
  779. vm.QemuSockets = cpu
  780. vm.QemuVcpus = cpu
  781. changed = true
  782. body["cores"] = 1
  783. body["sockets"] = cpu
  784. body["vcpus"] = cpu
  785. }
  786. if memMb > 0 {
  787. vm.Memory = memMb
  788. body["memory"] = memMb
  789. changed = true
  790. }
  791. if !changed {
  792. return nil
  793. }
  794. params := url.Values{}
  795. res := fmt.Sprintf("/nodes/%s/qemu/%d/config", vm.Node, vmId)
  796. return self.put(res, params, jsonutils.Marshal(body))
  797. }
  798. func (self *SRegion) ResetVmPassword(vmId int, username, password string) error {
  799. resources, err := self.GetClusterVmResources()
  800. if err != nil {
  801. return err
  802. }
  803. nodeName := ""
  804. if resource, ok := resources[vmId]; !ok {
  805. return errors.Errorf("failed to ResetVmPassword VM id %d", vmId)
  806. } else {
  807. nodeName = resource.Node
  808. }
  809. params := url.Values{}
  810. body := map[string]interface{}{
  811. "username": username,
  812. "password": password,
  813. }
  814. res := fmt.Sprintf("/nodes/%s/qemu/%d/agent/set-user-password", nodeName, vmId)
  815. return self.put(res, params, jsonutils.Marshal(body))
  816. }
  817. func (self *SRegion) DeleteVM(vmId int) error {
  818. id := strconv.Itoa(int(vmId))
  819. vm1, err := self.GetInstance(id)
  820. if err != nil {
  821. return errors.Wrapf(err, "GetInstance(%d)", vmId)
  822. }
  823. params := url.Values{}
  824. params.Set("purge", "1")
  825. res := fmt.Sprintf("/nodes/%s/qemu/%d", vm1.Node, vmId)
  826. return self.del(res, params, nil)
  827. }
  828. func (self *SRegion) GenVM(name, node string, cores, memMB int) (*SInstance, error) {
  829. vmId := self.GetClusterVmMaxId()
  830. if vmId == -1 {
  831. return nil, errors.Errorf("failed to get vm number by %d", vmId)
  832. } else {
  833. vmId++
  834. }
  835. body := map[string]interface{}{
  836. "vmid": vmId,
  837. "name": name,
  838. "ostype": "other",
  839. "sockets": 1,
  840. "cores": cores,
  841. "cpu": "host",
  842. "kvm": 1,
  843. "hotplug": "network,disk,usb",
  844. "memory": memMB,
  845. "description": "",
  846. "scsihw": "virtio-scsi-pci",
  847. }
  848. res := fmt.Sprintf("/nodes/%s/qemu", node)
  849. _, err := self.post(res, jsonutils.Marshal(body))
  850. if err != nil {
  851. return nil, err
  852. }
  853. vmIdRet := strconv.Itoa(vmId)
  854. vm, err := self.GetInstance(vmIdRet)
  855. if err != nil {
  856. return nil, err
  857. }
  858. return vm, nil
  859. }
  860. type InstanceVnc struct {
  861. Port int
  862. Ticket string
  863. Cert string
  864. }
  865. func (self *SRegion) GetVNCInfo(node string, vmId int) (*InstanceVnc, error) {
  866. res := fmt.Sprintf("/nodes/%s/qemu/%d/vncproxy", node, vmId)
  867. resp, err := self.post(res, map[string]interface{}{
  868. "websocket": "1",
  869. "generate-password": "0",
  870. })
  871. if err != nil {
  872. return nil, err
  873. }
  874. ret := struct {
  875. Data InstanceVnc
  876. }{}
  877. return &ret.Data, resp.Unmarshal(&ret)
  878. }