libvirt.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  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 guestman
  15. import (
  16. "context"
  17. "encoding/xml"
  18. "fmt"
  19. "io/ioutil"
  20. "path"
  21. "strconv"
  22. "strings"
  23. "unicode"
  24. libvirtxml "github.com/libvirt/libvirt-go-xml"
  25. "yunion.io/x/jsonutils"
  26. "yunion.io/x/log"
  27. "yunion.io/x/pkg/errors"
  28. "yunion.io/x/pkg/util/netutils"
  29. "yunion.io/x/onecloud/pkg/apis/compute"
  30. "yunion.io/x/onecloud/pkg/hostman/hostutils"
  31. "yunion.io/x/onecloud/pkg/hostman/storageman"
  32. "yunion.io/x/onecloud/pkg/util/fileutils2"
  33. "yunion.io/x/onecloud/pkg/util/procutils"
  34. "yunion.io/x/onecloud/pkg/util/qemuimg"
  35. )
  36. const defaultLibvirtLiveConfigPath = "/var/run/libvirt/qemu"
  37. func (m *SGuestManager) GuestCreateFromLibvirt(
  38. ctx context.Context, params interface{},
  39. ) (jsonutils.JSONObject, error) {
  40. createConfig, ok := params.(*SGuestCreateFromLibvirt)
  41. if !ok {
  42. return nil, hostutils.ParamsError
  43. }
  44. disks := createConfig.GuestDesc.Disks
  45. disksPath := jsonutils.NewDict()
  46. for _, disk := range disks {
  47. diskPath, err := createConfig.DisksPath.GetString(disk.DiskId)
  48. if err != nil {
  49. return nil, fmt.Errorf("Disks path missing disk %s", disk.DiskId)
  50. }
  51. storage := storageman.GetManager().GetStorage(disk.StorageId)
  52. if storage == nil {
  53. return nil, fmt.Errorf("Host has no stroage %s", disk.StorageId)
  54. }
  55. iDisk := storage.CreateDisk(disk.DiskId)
  56. // use symbol link replace mv, more security
  57. output, err := procutils.NewCommand("ln", "-s", diskPath, iDisk.GetPath()).Output()
  58. if err != nil {
  59. return nil, fmt.Errorf("Symbol link disk from %s to %s error %s", diskPath, iDisk.GetPath(), output)
  60. }
  61. disksPath.Set(disk.DiskId, jsonutils.NewString(iDisk.GetPath()))
  62. }
  63. guest, _ := m.GetKVMServer(createConfig.Sid)
  64. if err := SaveDesc(guest, createConfig.GuestDesc); err != nil {
  65. return nil, err
  66. }
  67. if len(createConfig.MonitorPath) > 0 {
  68. if pid := findGuestProcessPid(guest.getOriginId()); len(pid) > 0 {
  69. fileutils2.FilePutContents(guest.GetPidFilePath(), pid, false)
  70. guest.StartMonitorWithImportGuestSocketFile(ctx, createConfig.MonitorPath, nil)
  71. stopScript := guest.generateStopScript(nil)
  72. if err := fileutils2.FilePutContents(guest.GetStopScriptPath(), stopScript, false); err != nil {
  73. return nil, fmt.Errorf("Save stop script error %s", err)
  74. }
  75. }
  76. }
  77. ret := jsonutils.NewDict()
  78. ret.Set("disks_path", disksPath)
  79. return ret, nil
  80. }
  81. func findGuestProcessPid(originId string) string {
  82. output, err := procutils.NewCommand(
  83. "sh", "-c", fmt.Sprintf("ps -A -o pid,args | grep [q]emu | grep %s", originId)).Output()
  84. if err != nil {
  85. log.Errorf("find guest %s error: %s", originId, output)
  86. return ""
  87. }
  88. var spid string
  89. s1 := strings.Split(strings.TrimSpace(string(output)), "\n")
  90. for i := 0; i < len(s1); i++ {
  91. if len(s1[i]) > 0 {
  92. if len(spid) > 0 {
  93. log.Errorf("can't find guest %s pid, has multi process", originId)
  94. return ""
  95. }
  96. s2 := strings.Fields(s1[i])
  97. if len(s2) > 1 {
  98. spid = s2[0]
  99. }
  100. }
  101. }
  102. if len(spid) > 0 {
  103. _, err := strconv.Atoi(spid)
  104. if err != nil {
  105. log.Errorf("Pid atoi failed %s", err)
  106. return ""
  107. } else {
  108. return spid
  109. }
  110. } else {
  111. return ""
  112. }
  113. }
  114. func (m *SGuestManager) PrepareImportFromLibvirt(
  115. ctx context.Context, params interface{},
  116. ) (jsonutils.JSONObject, error) {
  117. libvirtConfig, ok := params.(*compute.SLibvirtHostConfig)
  118. if !ok {
  119. return nil, hostutils.ParamsError
  120. }
  121. guestDescs, err := m.GenerateDescFromXml(libvirtConfig)
  122. if err != nil {
  123. return nil, err
  124. }
  125. return guestDescs, nil
  126. }
  127. func IsMacInGuestConfig(guestConfig *compute.SImportGuestDesc, mac string) bool {
  128. for _, nic := range guestConfig.Nics {
  129. if netutils.FormatMacAddr(nic.Mac) == netutils.FormatMacAddr(mac) {
  130. return true
  131. }
  132. }
  133. return false
  134. }
  135. func setAttributeFromLibvirtConfig(
  136. guestConfig *compute.SImportGuestDesc,
  137. libvirtConfig *compute.SLibvirtHostConfig,
  138. monitorPath string,
  139. ) (int, error) {
  140. var Matched = true
  141. for i, server := range libvirtConfig.Servers {
  142. macMap := make(map[string]string, 0)
  143. for mac := range server.MacIp {
  144. if !IsMacInGuestConfig(guestConfig, mac) {
  145. Matched = false
  146. break
  147. } else {
  148. macMap[netutils.FormatMacAddr(mac)] = server.MacIp[mac]
  149. Matched = true
  150. }
  151. }
  152. if Matched {
  153. for idx, nic := range guestConfig.Nics {
  154. guestConfig.Nics[idx].Ip = macMap[netutils.FormatMacAddr(nic.Mac)]
  155. }
  156. log.Infof("config monitor path is %s, guest config id %s", libvirtConfig.MonitorPath, guestConfig.Id)
  157. if len(monitorPath) > 0 {
  158. guestConfig.MonitorPath = monitorPath
  159. } else if len(libvirtConfig.MonitorPath) > 0 {
  160. files, _ := ioutil.ReadDir(libvirtConfig.MonitorPath)
  161. for i := 0; i < len(files); i++ {
  162. if files[i].Mode().IsDir() &&
  163. strings.HasPrefix(files[i].Name(), "domain") &&
  164. strings.HasSuffix(files[i].Name(), guestConfig.Name) {
  165. monitorPath := path.Join(libvirtConfig.MonitorPath, files[i].Name(), "monitor.sock")
  166. if fileutils2.Exists(monitorPath) && isServerRunning("[q]emu-kvm", guestConfig.Id) {
  167. guestConfig.MonitorPath = monitorPath
  168. }
  169. break
  170. }
  171. }
  172. }
  173. log.Infof("Import guest %s, monitor is %s", guestConfig.Name, guestConfig.MonitorPath)
  174. return i, nil
  175. }
  176. }
  177. return -1, fmt.Errorf("Config not match guest %s", guestConfig.Id)
  178. }
  179. func isServerRunning(sufix, uuid string) bool {
  180. return procutils.NewCommand("sh", "-c",
  181. fmt.Sprintf("ps -ef | grep [q]emu | grep %s | grep %s", uuid, sufix)).Run() == nil
  182. }
  183. func (m *SGuestManager) GenerateDescFromXml(libvirtConfig *compute.SLibvirtHostConfig) (jsonutils.JSONObject, error) {
  184. out, err := procutils.NewRemoteCommandAsFarAsPossible(
  185. "find", libvirtConfig.XmlFilePath,
  186. "-type", "f", "-maxdepth", "1",
  187. ).Output()
  188. if err != nil {
  189. log.Errorf("failed read dir %s", libvirtConfig.XmlFilePath)
  190. return nil, errors.Wrapf(err, "failed read dir %s", libvirtConfig.XmlFilePath)
  191. }
  192. libvirtServers := []*compute.SImportGuestDesc{}
  193. xmlsPath := strings.Split(string(out), "\n")
  194. for _, xmlPath := range xmlsPath {
  195. if len(xmlPath) == 0 {
  196. continue
  197. }
  198. xmlContent, err := procutils.NewRemoteCommandAsFarAsPossible("cat", xmlPath).Output()
  199. if err != nil {
  200. log.Errorf("Read file %s failed: %s %s", xmlPath, xmlContent, err)
  201. continue
  202. }
  203. // parse libvirt xml file
  204. domain := &libvirtxml.Domain{}
  205. err = domain.Unmarshal(strings.TrimSpace(string(xmlContent)))
  206. if err != nil {
  207. log.Errorf("Unmarshal xml file %s error %s", xmlPath, err)
  208. continue
  209. }
  210. log.Infof("import domain uuid %s", domain.UUID)
  211. var monitorPath string
  212. if len(domain.UUID) > 0 {
  213. domainXmlFileName := fmt.Sprintf("%s.xml", domain.UUID)
  214. domainXmlFilePath := path.Join(defaultLibvirtLiveConfigPath, domainXmlFileName)
  215. if _, err := procutils.RemoteStat(domainXmlFilePath); err == nil {
  216. log.Infof("import domain live xml path %s", domainXmlFilePath)
  217. domStatus, err := m.getLibvirtLiveConfig(domainXmlFilePath)
  218. if err == nil {
  219. monitorPath = domStatus.Monitor.Path
  220. } else {
  221. log.Errorf("failed getLibvirtLiveConfig %s: %s", domainXmlFilePath, err)
  222. }
  223. }
  224. }
  225. guestConfig, err := m.LibvirtDomainToGuestDesc(domain)
  226. if err != nil {
  227. log.Errorf("Parse libvirt domain failed %s", err)
  228. continue
  229. }
  230. if idx, err := setAttributeFromLibvirtConfig(guestConfig, libvirtConfig, monitorPath); err != nil {
  231. log.Errorf("Import guest %s error %s", guestConfig.Id, err)
  232. continue
  233. } else {
  234. libvirtConfig.Servers = append(libvirtConfig.Servers[:idx], libvirtConfig.Servers[idx+1:]...)
  235. libvirtServers = append(libvirtServers, guestConfig)
  236. }
  237. }
  238. ret := jsonutils.NewDict()
  239. ret.Set("servers_not_match", jsonutils.Marshal(libvirtConfig.Servers))
  240. ret.Set("servers_matched", jsonutils.Marshal(libvirtServers))
  241. return ret, nil
  242. }
  243. type SMonitor struct {
  244. XMLName xml.Name `xml:"monitor"`
  245. Path string `xml:"path,attr"`
  246. }
  247. type SDomainStatus struct {
  248. XMLName xml.Name `xml:"domstatus"`
  249. Pid int `xml:"pid,attr"`
  250. Monitor SMonitor `xml:"monitor"`
  251. }
  252. func (m *SGuestManager) getLibvirtLiveConfig(domainXmlFilePath string) (*SDomainStatus, error) {
  253. liveXmlContent, err := procutils.NewRemoteCommandAsFarAsPossible("cat", domainXmlFilePath).Output()
  254. if err != nil {
  255. return nil, errors.Errorf("Read file %s failed: %s %s", domainXmlFilePath, liveXmlContent, err)
  256. }
  257. // guest running
  258. domainLive := &SDomainStatus{}
  259. err = xml.Unmarshal(liveXmlContent, domainLive)
  260. if err != nil {
  261. return nil, errors.Errorf("failed unmarshal live xml")
  262. }
  263. return domainLive, nil
  264. }
  265. // Read key infomation from domain xml
  266. func (m *SGuestManager) LibvirtDomainToGuestDesc(domain *libvirtxml.Domain) (*compute.SImportGuestDesc, error) {
  267. if nil == domain {
  268. return nil, fmt.Errorf("Libvirt domain is nil")
  269. }
  270. if nil == domain.VCPU {
  271. return nil, fmt.Errorf("Libvirt domain missing VCPU config")
  272. }
  273. if nil == domain.CurrentMemory {
  274. return nil, fmt.Errorf("Libvirt domain missing CurrentMemory config")
  275. }
  276. if 0 == len(domain.CurrentMemory.Unit) {
  277. return nil, fmt.Errorf("Libvirt Memory config missing unit")
  278. }
  279. if nil == domain.Devices {
  280. return nil, fmt.Errorf("Libvirt domain missing Devices config")
  281. }
  282. if 0 == len(domain.Devices.Disks) {
  283. return nil, fmt.Errorf("Livbirt domain has no Disks")
  284. }
  285. if 0 == len(domain.Devices.Interfaces) {
  286. return nil, fmt.Errorf("Libvirt domain has no network Interfaces")
  287. }
  288. var memSizeMb uint
  289. switch unicode.ToLower(rune(domain.CurrentMemory.Unit[0])) {
  290. case 'k':
  291. memSizeMb = domain.CurrentMemory.Value / 1024
  292. if domain.CurrentMemory.Value%1024 > 0 {
  293. memSizeMb += 1
  294. }
  295. case 'm':
  296. memSizeMb = domain.CurrentMemory.Value
  297. case 'g':
  298. memSizeMb = domain.CurrentMemory.Value * 1024
  299. case 'b':
  300. memSizeMb = domain.CurrentMemory.Value / 1024 / 1024
  301. if domain.CurrentMemory.Value%(1024*1024) > 0 {
  302. memSizeMb += 1
  303. }
  304. default:
  305. return nil, fmt.Errorf("Unknown memory unit %s", domain.CurrentMemory.Unit)
  306. }
  307. disksConfig, err := m.LibvirtDomainDiskToDiskConfig(domain.Devices.Disks)
  308. if err != nil {
  309. return nil, err
  310. }
  311. nicsConfig, err := m.LibvirtDomainInterfaceToNicConfig(domain.Devices.Interfaces)
  312. if err != nil {
  313. return nil, err
  314. }
  315. return &compute.SImportGuestDesc{
  316. Id: domain.UUID,
  317. Name: domain.Name,
  318. Cpu: domain.VCPU.Value,
  319. MemSizeMb: int(memSizeMb),
  320. Disks: disksConfig,
  321. Nics: nicsConfig,
  322. }, nil
  323. }
  324. func (m *SGuestManager) LibvirtDomainDiskToDiskConfig(
  325. domainDisks []libvirtxml.DomainDisk) ([]compute.SImportDisk, error) {
  326. var diskConfigs = []compute.SImportDisk{}
  327. for _, disk := range domainDisks {
  328. if disk.Device != "disk" {
  329. continue
  330. }
  331. if disk.Source == nil || disk.Source.File == nil {
  332. return nil, fmt.Errorf("Domain disk missing source file ?")
  333. }
  334. if disk.Target == nil {
  335. return nil, fmt.Errorf("Domain disk missing target config")
  336. }
  337. // XXX: Ignore backing file
  338. var diskConfig = compute.SImportDisk{
  339. AccessPath: strings.Trim(disk.Source.File.File, "\""),
  340. Index: int(disk.Source.Index),
  341. }
  342. if disk.Target.Bus != "virtio" {
  343. diskConfig.Driver = "scsi"
  344. } else {
  345. diskConfig.Driver = disk.Target.Bus
  346. }
  347. if img, err := qemuimg.NewQemuImage(diskConfig.AccessPath); err != nil {
  348. return nil, fmt.Errorf("Domain disk %s open failed: %s", diskConfig.AccessPath, err)
  349. } else {
  350. diskConfig.SizeMb = img.GetSizeMB()
  351. diskConfig.Format = img.Format.String()
  352. }
  353. diskConfigs = append(diskConfigs, diskConfig)
  354. }
  355. return diskConfigs, nil
  356. }
  357. func (m *SGuestManager) LibvirtDomainInterfaceToNicConfig(
  358. domainInterfaces []libvirtxml.DomainInterface) ([]compute.SImportNic, error) {
  359. var nicConfigs = []compute.SImportNic{}
  360. for idx, nic := range domainInterfaces {
  361. if nic.MAC == nil {
  362. return nil, fmt.Errorf("Domain interface %#v missing mac address", nic)
  363. }
  364. nicConfigs = append(nicConfigs, compute.SImportNic{
  365. Index: idx,
  366. Mac: nic.MAC.Address,
  367. Driver: "virtio", //default driver
  368. })
  369. }
  370. return nicConfigs, nil
  371. }