New version of salt-formula from Saltstack
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

1891 行
52KB

  1. # -*- coding: utf-8 -*-
  2. '''
  3. Work with virtual machines managed by libvirt
  4. :depends: libvirt Python module
  5. '''
  6. # Special Thanks to Michael Dehann, many of the concepts, and a few structures
  7. # of his in the virt func module have been used
  8. # Import python libs
  9. from __future__ import absolute_import
  10. import copy
  11. import os
  12. import re
  13. import sys
  14. import shutil
  15. import subprocess
  16. import string # pylint: disable=deprecated-module
  17. import logging
  18. # Import third party libs
  19. import yaml
  20. import json
  21. import jinja2
  22. import jinja2.exceptions
  23. import salt.ext.six as six
  24. from salt.ext.six.moves import StringIO as _StringIO # pylint: disable=import-error
  25. from xml.dom import minidom
  26. try:
  27. import libvirt # pylint: disable=import-error
  28. HAS_ALL_IMPORTS = True
  29. except ImportError:
  30. HAS_ALL_IMPORTS = False
  31. # Import salt libs
  32. import salt.utils
  33. import salt.utils.files
  34. import salt.utils.templates
  35. import salt.utils.validate.net
  36. from salt.exceptions import CommandExecutionError, SaltInvocationError
  37. log = logging.getLogger(__name__)
  38. # Set up template environment
  39. JINJA = jinja2.Environment(
  40. loader=jinja2.FileSystemLoader(
  41. os.path.join(salt.utils.templates.TEMPLATE_DIRNAME, 'virt')
  42. )
  43. )
  44. VIRT_STATE_NAME_MAP = {0: 'running',
  45. 1: 'running',
  46. 2: 'running',
  47. 3: 'paused',
  48. 4: 'shutdown',
  49. 5: 'shutdown',
  50. 6: 'crashed'}
  51. VIRT_DEFAULT_HYPER = 'kvm'
  52. def __virtual__():
  53. if not HAS_ALL_IMPORTS:
  54. return False
  55. return 'virtng'
  56. def __get_conn():
  57. '''
  58. Detects what type of dom this node is and attempts to connect to the
  59. correct hypervisor via libvirt.
  60. '''
  61. # This has only been tested on kvm and xen, it needs to be expanded to
  62. # support all vm layers supported by libvirt
  63. def __esxi_uri():
  64. '''
  65. Connect to an ESXi host with a configuration like so:
  66. .. code-block:: yaml
  67. libvirt:
  68. hypervisor: esxi
  69. connection: esx01
  70. The connection setting can either be an explicit libvirt URI,
  71. or a libvirt URI alias as in this example. No, it cannot be
  72. just a hostname.
  73. Example libvirt `/etc/libvirt/libvirt.conf`:
  74. .. code-block::
  75. uri_aliases = [
  76. "esx01=esx://10.1.1.101/?no_verify=1&auto_answer=1",
  77. "esx02=esx://10.1.1.102/?no_verify=1&auto_answer=1",
  78. ]
  79. Reference:
  80. - http://libvirt.org/drvesx.html#uriformat
  81. - http://libvirt.org/uri.html#URI_config
  82. '''
  83. connection = __salt__['config.get']('libvirt:connection', 'esx')
  84. return connection
  85. def __esxi_auth():
  86. '''
  87. We rely on that the credentials is provided to libvirt through
  88. its built in mechanisms.
  89. Example libvirt `/etc/libvirt/auth.conf`:
  90. .. code-block::
  91. [credentials-myvirt]
  92. username=user
  93. password=secret
  94. [auth-esx-10.1.1.101]
  95. credentials=myvirt
  96. [auth-esx-10.1.1.102]
  97. credentials=myvirt
  98. Reference:
  99. - http://libvirt.org/auth.html#Auth_client_config
  100. '''
  101. return [[libvirt.VIR_CRED_EXTERNAL], lambda: 0, None]
  102. if 'virt.connect' in __opts__:
  103. conn_str = __opts__['virt.connect']
  104. else:
  105. conn_str = 'qemu:///system'
  106. conn_func = {
  107. 'esxi': [libvirt.openAuth, [__esxi_uri(),
  108. __esxi_auth(),
  109. 0]],
  110. 'qemu': [libvirt.open, [conn_str]],
  111. }
  112. hypervisor = __salt__['config.get']('libvirt:hypervisor', 'qemu')
  113. try:
  114. conn = conn_func[hypervisor][0](*conn_func[hypervisor][1])
  115. except Exception:
  116. raise CommandExecutionError(
  117. 'Sorry, {0} failed to open a connection to the hypervisor '
  118. 'software at {1}'.format(
  119. __grains__['fqdn'],
  120. conn_func[hypervisor][1][0]
  121. )
  122. )
  123. return conn
  124. def _get_dom(vm_):
  125. '''
  126. Return a domain object for the named vm
  127. '''
  128. conn = __get_conn()
  129. if vm_ not in list_vms():
  130. raise CommandExecutionError('The specified vm is not present')
  131. return conn.lookupByName(vm_)
  132. def _libvirt_creds():
  133. '''
  134. Returns the user and group that the disk images should be owned by
  135. '''
  136. g_cmd = 'grep ^\\s*group /etc/libvirt/qemu.conf'
  137. u_cmd = 'grep ^\\s*user /etc/libvirt/qemu.conf'
  138. try:
  139. group = subprocess.Popen(g_cmd,
  140. shell=True,
  141. stdout=subprocess.PIPE).communicate()[0].split('"')[1]
  142. except IndexError:
  143. group = 'root'
  144. try:
  145. user = subprocess.Popen(u_cmd,
  146. shell=True,
  147. stdout=subprocess.PIPE).communicate()[0].split('"')[1]
  148. except IndexError:
  149. user = 'root'
  150. return {'user': user, 'group': group}
  151. def _get_migrate_command():
  152. '''
  153. Returns the command shared by the different migration types
  154. '''
  155. if __salt__['config.option']('virt.tunnel'):
  156. return ('virsh migrate --p2p --tunnelled --live --persistent '
  157. '--undefinesource ')
  158. return 'virsh migrate --live --persistent --undefinesource '
  159. def _get_target(target, ssh):
  160. proto = 'qemu'
  161. if ssh:
  162. proto += '+ssh'
  163. return ' {0}://{1}/{2}'.format(proto, target, 'system')
  164. def _gen_xml(name,
  165. cpu,
  166. mem,
  167. diskp,
  168. nicp,
  169. hypervisor,
  170. **kwargs):
  171. '''
  172. Generate the XML string to define a libvirt vm
  173. '''
  174. hypervisor = 'vmware' if hypervisor == 'esxi' else hypervisor
  175. mem = mem * 1024 # MB
  176. context = {
  177. 'hypervisor': hypervisor,
  178. 'name': name,
  179. 'cpu': str(cpu),
  180. 'mem': str(mem),
  181. }
  182. if hypervisor in ['qemu', 'kvm']:
  183. context['controller_model'] = False
  184. elif hypervisor in ['esxi', 'vmware']:
  185. # TODO: make bus and model parameterized, this works for 64-bit Linux
  186. context['controller_model'] = 'lsilogic'
  187. if 'boot_dev' in kwargs:
  188. context['boot_dev'] = []
  189. for dev in kwargs['boot_dev'].split():
  190. context['boot_dev'].append(dev)
  191. else:
  192. context['boot_dev'] = ['hd']
  193. if 'serial_type' in kwargs:
  194. context['serial_type'] = kwargs['serial_type']
  195. if 'serial_type' in context and context['serial_type'] == 'tcp':
  196. if 'telnet_port' in kwargs:
  197. context['telnet_port'] = kwargs['telnet_port']
  198. else:
  199. context['telnet_port'] = 23023 # FIXME: use random unused port
  200. if 'serial_type' in context:
  201. if 'console' in kwargs:
  202. context['console'] = kwargs['console']
  203. else:
  204. context['console'] = True
  205. context['disks'] = {}
  206. for i, disk in enumerate(diskp):
  207. for disk_name, args in disk.items():
  208. context['disks'][disk_name] = {}
  209. fn_ = '{0}.{1}'.format(disk_name, args['format'])
  210. context['disks'][disk_name]['file_name'] = fn_
  211. context['disks'][disk_name]['source_file'] = os.path.join(args['pool'],
  212. name,
  213. fn_)
  214. if hypervisor in ['qemu', 'kvm']:
  215. context['disks'][disk_name]['target_dev'] = 'vd{0}'.format(string.ascii_lowercase[i])
  216. context['disks'][disk_name]['address'] = False
  217. context['disks'][disk_name]['driver'] = True
  218. elif hypervisor in ['esxi', 'vmware']:
  219. context['disks'][disk_name]['target_dev'] = 'sd{0}'.format(string.ascii_lowercase[i])
  220. context['disks'][disk_name]['address'] = True
  221. context['disks'][disk_name]['driver'] = False
  222. context['disks'][disk_name]['disk_bus'] = args['model']
  223. context['disks'][disk_name]['type'] = args['format']
  224. context['disks'][disk_name]['index'] = str(i)
  225. context['nics'] = nicp
  226. fn_ = 'libvirt_domain.jinja'
  227. try:
  228. template = JINJA.get_template(fn_)
  229. except jinja2.exceptions.TemplateNotFound:
  230. log.error('Could not load template {0}'.format(fn_))
  231. return ''
  232. return template.render(**context)
  233. def _gen_vol_xml(vmname,
  234. diskname,
  235. size,
  236. hypervisor,
  237. **kwargs):
  238. '''
  239. Generate the XML string to define a libvirt storage volume
  240. '''
  241. size = int(size) * 1024 # MB
  242. disk_info = _get_image_info(hypervisor, vmname, **kwargs)
  243. context = {
  244. 'name': vmname,
  245. 'filename': '{0}.{1}'.format(diskname, disk_info['disktype']),
  246. 'volname': diskname,
  247. 'disktype': disk_info['disktype'],
  248. 'size': str(size),
  249. 'pool': disk_info['pool'],
  250. }
  251. fn_ = 'libvirt_volume.jinja'
  252. try:
  253. template = JINJA.get_template(fn_)
  254. except jinja2.exceptions.TemplateNotFound:
  255. log.error('Could not load template {0}'.format(fn_))
  256. return ''
  257. return template.render(**context)
  258. def _qemu_image_info(path):
  259. '''
  260. Detect information for the image at path
  261. '''
  262. ret = {}
  263. out = __salt__['cmd.shell']('qemu-img info {0}'.format(path))
  264. match_map = {'size': r'virtual size: \w+ \((\d+) byte[s]?\)',
  265. 'format': r'file format: (\w+)'}
  266. for info, search in match_map.items():
  267. try:
  268. ret[info] = re.search(search, out).group(1)
  269. except AttributeError:
  270. continue
  271. return ret
  272. # TODO: this function is deprecated, should be replaced with
  273. # _qemu_image_info()
  274. def _image_type(vda):
  275. '''
  276. Detect what driver needs to be used for the given image
  277. '''
  278. out = __salt__['cmd.shell']('qemu-img info {0}'.format(vda))
  279. if 'file format: qcow2' in out:
  280. return 'qcow2'
  281. else:
  282. return 'raw'
  283. # TODO: this function is deprecated, should be merged and replaced
  284. # with _disk_profile()
  285. def _get_image_info(hypervisor, name, **kwargs):
  286. '''
  287. Determine disk image info, such as filename, image format and
  288. storage pool, based on which hypervisor is used
  289. '''
  290. ret = {}
  291. if hypervisor in ['esxi', 'vmware']:
  292. ret['disktype'] = 'vmdk'
  293. ret['filename'] = '{0}{1}'.format(name, '.vmdk')
  294. ret['pool'] = '[{0}] '.format(kwargs.get('pool', '0'))
  295. elif hypervisor in ['kvm', 'qemu']:
  296. ret['disktype'] = 'qcow2'
  297. ret['filename'] = '{0}{1}'.format(name, '.qcow2')
  298. if 'img_dest' in kwargs:
  299. ret['pool'] = kwargs['img_dest']
  300. else:
  301. ret['pool'] = __salt__['config.option']('virt.images')
  302. return ret
  303. def _disk_profile(profile, hypervisor, **kwargs):
  304. '''
  305. Gather the disk profile from the config or apply the default based
  306. on the active hypervisor
  307. This is the ``default`` profile for KVM/QEMU, which can be
  308. overridden in the configuration:
  309. .. code-block:: yaml
  310. virt:
  311. disk:
  312. default:
  313. - system:
  314. size: 8192
  315. format: qcow2
  316. model: virtio
  317. Example profile for KVM/QEMU with two disks, first is created
  318. from specified image, the second is empty:
  319. .. code-block:: yaml
  320. virt:
  321. disk:
  322. two_disks:
  323. - system:
  324. size: 8192
  325. format: qcow2
  326. model: virtio
  327. image: http://path/to/image.qcow2
  328. - lvm:
  329. size: 32768
  330. format: qcow2
  331. model: virtio
  332. The ``format`` and ``model`` parameters are optional, and will
  333. default to whatever is best suitable for the active hypervisor.
  334. '''
  335. default = [
  336. {'system':
  337. {'size': '8192'}
  338. }
  339. ]
  340. if hypervisor in ['esxi', 'vmware']:
  341. overlay = {'format': 'vmdk',
  342. 'model': 'scsi',
  343. 'pool': '[{0}] '.format(kwargs.get('pool', '0'))
  344. }
  345. elif hypervisor in ['qemu', 'kvm']:
  346. if 'img_dest' in kwargs:
  347. pool = kwargs['img_dest']
  348. else:
  349. pool = __salt__['config.option']('virt.images')
  350. overlay = {'format': 'qcow2', 'model': 'virtio', 'pool': pool}
  351. else:
  352. overlay = {}
  353. disklist = copy.deepcopy(__salt__['config.get']('virt:disk', {}).get(profile, default))
  354. for key, val in overlay.items():
  355. for i, disks in enumerate(disklist):
  356. for disk in disks:
  357. if key not in disks[disk]:
  358. disklist[i][disk][key] = val
  359. return disklist
  360. def _nic_profile(profile_name, hypervisor, **kwargs):
  361. def append_dict_profile_to_interface_list(profile_dict):
  362. for interface_name, attributes in profile_dict.items():
  363. attributes['name'] = interface_name
  364. interfaces.append(attributes)
  365. def _normalize_net_types(attributes):
  366. '''
  367. Guess which style of definition:
  368. bridge: br0
  369. or
  370. network: net0
  371. or
  372. type: network
  373. source: net0
  374. '''
  375. for type_ in ['bridge', 'network']:
  376. if type_ in attributes:
  377. attributes['type'] = type_
  378. # we want to discard the original key
  379. attributes['source'] = attributes.pop(type_)
  380. attributes['type'] = attributes.get('type', None)
  381. attributes['source'] = attributes.get('source', None)
  382. attributes['virtualport'] = attributes.get('virtualport', None)
  383. def _apply_default_overlay(attributes):
  384. for key, value in overlays[hypervisor].items():
  385. if key not in attributes or not attributes[key]:
  386. attributes[key] = value
  387. def _assign_mac(attributes):
  388. dmac = '{0}_mac'.format(attributes['name'])
  389. if dmac in kwargs:
  390. dmac = kwargs[dmac]
  391. if salt.utils.validate.net.mac(dmac):
  392. attributes['mac'] = dmac
  393. else:
  394. msg = 'Malformed MAC address: {0}'.format(dmac)
  395. raise CommandExecutionError(msg)
  396. else:
  397. attributes['mac'] = salt.utils.gen_mac()
  398. default = [{'eth0': {}}]
  399. vmware_overlay = {'type': 'bridge', 'source': 'DEFAULT', 'model': 'e1000'}
  400. kvm_overlay = {'type': 'bridge', 'source': 'br0', 'model': 'virtio'}
  401. overlays = {
  402. 'kvm': kvm_overlay,
  403. 'qemu': kvm_overlay,
  404. 'esxi': vmware_overlay,
  405. 'vmware': vmware_overlay,
  406. }
  407. # support old location
  408. config_data = __salt__['config.option']('virt.nic', {}).get(
  409. profile_name, None
  410. )
  411. if config_data is None:
  412. config_data = __salt__['config.get']('virt:nic', {}).get(
  413. profile_name, default
  414. )
  415. interfaces = []
  416. if isinstance(config_data, dict):
  417. append_dict_profile_to_interface_list(config_data)
  418. elif isinstance(config_data, list):
  419. for interface in config_data:
  420. if isinstance(interface, dict):
  421. if len(interface) == 1:
  422. append_dict_profile_to_interface_list(interface)
  423. else:
  424. interfaces.append(interface)
  425. for interface in interfaces:
  426. _normalize_net_types(interface)
  427. _assign_mac(interface)
  428. if hypervisor in overlays:
  429. _apply_default_overlay(interface)
  430. return interfaces
  431. def init(name,
  432. cpu,
  433. mem,
  434. image=None,
  435. nic='default',
  436. hypervisor=VIRT_DEFAULT_HYPER,
  437. start=True, # pylint: disable=redefined-outer-name
  438. disk='default',
  439. saltenv='base',
  440. rng=None,
  441. **kwargs):
  442. '''
  443. Initialize a new vm
  444. CLI Example:
  445. .. code-block:: bash
  446. salt 'hypervisor' virt.init vm_name 4 512 salt://path/to/image.raw
  447. salt 'hypervisor' virt.init vm_name 4 512 nic=profile disk=profile
  448. '''
  449. rng = rng or {'backend':'/dev/urandom'}
  450. hypervisor = __salt__['config.get']('libvirt:hypervisor', hypervisor)
  451. nicp = _nic_profile(nic, hypervisor, **kwargs)
  452. diskp = _disk_profile(disk, hypervisor, **kwargs)
  453. if image:
  454. # Backward compatibility: if 'image' is specified in the VMs arguments
  455. # instead of a disk arguments. In this case, 'image' will be assigned
  456. # to the first disk for the VM.
  457. disk_name = next(diskp[0].iterkeys())
  458. if not diskp[0][disk_name].get('image', None):
  459. diskp[0][disk_name]['image'] = image
  460. # Create multiple disks, empty or from specified images.
  461. cloud_init = None
  462. cfg_drive = None
  463. for disk in diskp:
  464. log.debug("Creating disk for VM [ {0} ]: {1}".format(name, disk))
  465. for disk_name, args in disk.items():
  466. if hypervisor in ['esxi', 'vmware']:
  467. if 'image' in args:
  468. # TODO: we should be copying the image file onto the ESX host
  469. raise SaltInvocationError('virt.init does not support image '
  470. 'template template in conjunction '
  471. 'with esxi hypervisor')
  472. else:
  473. # assume libvirt manages disks for us
  474. xml = _gen_vol_xml(name,
  475. disk_name,
  476. args['size'],
  477. hypervisor,
  478. **kwargs)
  479. define_vol_xml_str(xml)
  480. elif hypervisor in ['qemu', 'kvm']:
  481. disk_type = args['format']
  482. disk_file_name = '{0}.{1}'.format(disk_name, disk_type)
  483. # disk size TCP cloud
  484. disk_size = args['size']
  485. if 'img_dest' in kwargs:
  486. img_dir = kwargs['img_dest']
  487. else:
  488. img_dir = __salt__['config.option']('virt.images')
  489. img_dest = os.path.join(
  490. img_dir,
  491. name,
  492. disk_file_name
  493. )
  494. img_dir = os.path.dirname(img_dest)
  495. if not os.path.isdir(img_dir):
  496. os.makedirs(img_dir)
  497. if 'image' in args:
  498. # Create disk from specified image
  499. sfn = __salt__['cp.cache_file'](args['image'], saltenv)
  500. try:
  501. salt.utils.files.copyfile(sfn, img_dest)
  502. mask = os.umask(0)
  503. os.umask(mask)
  504. # Apply umask and remove exec bit
  505. # Resizing image TCP cloud
  506. cmd = 'qemu-img resize ' + img_dest + ' ' + str(disk_size) + 'M'
  507. subprocess.call(cmd, shell=True)
  508. mode = (0o0777 ^ mask) & 0o0666
  509. os.chmod(img_dest, mode)
  510. except (IOError, OSError) as e:
  511. raise CommandExecutionError('problem while copying image. {0} - {1}'.format(args['image'], e))
  512. if kwargs.get('seed'):
  513. seed_cmd = kwargs.get('seed_cmd', 'seedng.apply')
  514. cloud_init = kwargs.get('cloud_init', None)
  515. master = __salt__['config.option']('master')
  516. cfg_drive = os.path.join(img_dir,'config-2.iso')
  517. if cloud_init:
  518. _tmp = name.split('.')
  519. try:
  520. user_data = json.dumps(cloud_init["user_data"])
  521. except:
  522. user_data = None
  523. try:
  524. network_data = json.dumps(cloud_init["network_data"])
  525. except:
  526. network_data = None
  527. __salt__["cfgdrive.generate"](
  528. dst = cfg_drive,
  529. hostname = _tmp.pop(0),
  530. domainname = '.'.join(_tmp),
  531. user_data = user_data,
  532. network_data = network_data,
  533. saltconfig = { "salt_minion": { "conf": { "master": master, "id": name } } }
  534. )
  535. else:
  536. __salt__[seed_cmd](
  537. path = img_dest,
  538. id_ = name,
  539. config = kwargs.get('config'),
  540. install = kwargs.get('install', True)
  541. )
  542. else:
  543. # Create empty disk
  544. try:
  545. mask = os.umask(0)
  546. os.umask(mask)
  547. # Apply umask and remove exec bit
  548. # Create empty image
  549. cmd = 'qemu-img create -f ' + disk_type + ' ' + img_dest + ' ' + str(disk_size) + 'M'
  550. subprocess.call(cmd, shell=True)
  551. mode = (0o0777 ^ mask) & 0o0666
  552. os.chmod(img_dest, mode)
  553. except (IOError, OSError) as e:
  554. raise CommandExecutionError('problem while creating volume {0} - {1}'.format(img_dest, e))
  555. else:
  556. # Unknown hypervisor
  557. raise SaltInvocationError('Unsupported hypervisor when handling disk image: {0}'
  558. .format(hypervisor))
  559. xml = _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, **kwargs)
  560. if cloud_init and cfg_drive:
  561. xml_doc = minidom.parseString(xml)
  562. iso_xml = xml_doc.createElement("disk")
  563. iso_xml.setAttribute("type", "file")
  564. iso_xml.setAttribute("device", "cdrom")
  565. iso_xml.appendChild(xml_doc.createElement("readonly"))
  566. driver = xml_doc.createElement("driver")
  567. driver.setAttribute("name", "qemu")
  568. driver.setAttribute("type", "raw")
  569. target = xml_doc.createElement("target")
  570. target.setAttribute("dev", "hdc")
  571. target.setAttribute("bus", "ide")
  572. source = xml_doc.createElement("source")
  573. source.setAttribute("file", cfg_drive)
  574. iso_xml.appendChild(driver)
  575. iso_xml.appendChild(target)
  576. iso_xml.appendChild(source)
  577. xml_doc.getElementsByTagName("domain")[0].getElementsByTagName("devices")[0].appendChild(iso_xml)
  578. xml = xml_doc.toxml()
  579. # TODO: Remove this code and refactor module, when salt-common would have updated libvirt_domain.jinja template
  580. for _nic in nicp:
  581. if _nic['virtualport']:
  582. xml_doc = minidom.parseString(xml)
  583. interfaces = xml_doc.getElementsByTagName("domain")[0].getElementsByTagName("devices")[0].getElementsByTagName("interface")
  584. for interface in interfaces:
  585. if interface.getElementsByTagName('mac')[0].getAttribute('address').lower() == _nic['mac'].lower():
  586. vport_xml = xml_doc.createElement("virtualport")
  587. vport_xml.setAttribute("type", _nic['virtualport']['type'])
  588. interface.appendChild(vport_xml)
  589. xml = xml_doc.toxml()
  590. # TODO: Remove this code and refactor module, when salt-common would have updated libvirt_domain.jinja template
  591. if rng:
  592. rng_model = rng.get('model', 'random')
  593. rng_backend = rng.get('backend', '/dev/urandom')
  594. xml_doc = minidom.parseString(xml)
  595. rng_xml = xml_doc.createElement("rng")
  596. rng_xml.setAttribute("model", "virtio")
  597. backend = xml_doc.createElement("backend")
  598. backend.setAttribute("model", rng_model)
  599. backend.appendChild(xml_doc.createTextNode(rng_backend))
  600. rng_xml.appendChild(backend)
  601. if 'rate' in rng:
  602. rng_rate_period = rng['rate'].get('period', '2000')
  603. rng_rate_bytes = rng['rate'].get('bytes', '1234')
  604. rate = xml_doc.createElement("rate")
  605. rate.setAttribute("period", rng_rate_period)
  606. rate.setAttribute("bytes", rng_rate_bytes)
  607. rng_xml.appendChild(rate)
  608. xml_doc.getElementsByTagName("domain")[0].getElementsByTagName("devices")[0].appendChild(rng_xml)
  609. xml = xml_doc.toxml()
  610. define_xml_str(xml)
  611. if start:
  612. create(name)
  613. return True
  614. def list_vms():
  615. '''
  616. Return a list of virtual machine names on the minion
  617. CLI Example:
  618. .. code-block:: bash
  619. salt '*' virtng.list_vms
  620. '''
  621. vms = []
  622. vms.extend(list_active_vms())
  623. vms.extend(list_inactive_vms())
  624. return vms
  625. def list_active_vms():
  626. '''
  627. Return a list of names for active virtual machine on the minion
  628. CLI Example:
  629. .. code-block:: bash
  630. salt '*' virtng.list_active_vms
  631. '''
  632. conn = __get_conn()
  633. vms = []
  634. for id_ in conn.listDomainsID():
  635. vms.append(conn.lookupByID(id_).name())
  636. return vms
  637. def list_inactive_vms():
  638. '''
  639. Return a list of names for inactive virtual machine on the minion
  640. CLI Example:
  641. .. code-block:: bash
  642. salt '*' virtng.list_inactive_vms
  643. '''
  644. conn = __get_conn()
  645. vms = []
  646. for id_ in conn.listDefinedDomains():
  647. vms.append(id_)
  648. return vms
  649. def vm_info(vm_=None):
  650. '''
  651. Return detailed information about the vms on this hyper in a
  652. list of dicts:
  653. .. code-block:: python
  654. [
  655. 'your-vm': {
  656. 'cpu': <int>,
  657. 'maxMem': <int>,
  658. 'mem': <int>,
  659. 'state': '<state>',
  660. 'cputime' <int>
  661. },
  662. ...
  663. ]
  664. If you pass a VM name in as an argument then it will return info
  665. for just the named VM, otherwise it will return all VMs.
  666. CLI Example:
  667. .. code-block:: bash
  668. salt '*' virtng.vm_info
  669. '''
  670. def _info(vm_):
  671. dom = _get_dom(vm_)
  672. raw = dom.info()
  673. return {'cpu': raw[3],
  674. 'cputime': int(raw[4]),
  675. 'disks': get_disks(vm_),
  676. 'graphics': get_graphics(vm_),
  677. 'nics': get_nics(vm_),
  678. 'maxMem': int(raw[1]),
  679. 'mem': int(raw[2]),
  680. 'state': VIRT_STATE_NAME_MAP.get(raw[0], 'unknown')}
  681. info = {}
  682. if vm_:
  683. info[vm_] = _info(vm_)
  684. else:
  685. for vm_ in list_vms():
  686. info[vm_] = _info(vm_)
  687. return info
  688. def vm_state(vm_=None):
  689. '''
  690. Return list of all the vms and their state.
  691. If you pass a VM name in as an argument then it will return info
  692. for just the named VM, otherwise it will return all VMs.
  693. CLI Example:
  694. .. code-block:: bash
  695. salt '*' virtng.vm_state <vm name>
  696. '''
  697. def _info(vm_):
  698. state = ''
  699. dom = _get_dom(vm_)
  700. raw = dom.info()
  701. state = VIRT_STATE_NAME_MAP.get(raw[0], 'unknown')
  702. return state
  703. info = {}
  704. if vm_:
  705. info[vm_] = _info(vm_)
  706. else:
  707. for vm_ in list_vms():
  708. info[vm_] = _info(vm_)
  709. return info
  710. def node_info():
  711. '''
  712. Return a dict with information about this node
  713. CLI Example:
  714. .. code-block:: bash
  715. salt '*' virtng.node_info
  716. '''
  717. conn = __get_conn()
  718. raw = conn.getInfo()
  719. info = {'cpucores': raw[6],
  720. 'cpumhz': raw[3],
  721. 'cpumodel': str(raw[0]),
  722. 'cpus': raw[2],
  723. 'cputhreads': raw[7],
  724. 'numanodes': raw[4],
  725. 'phymemory': raw[1],
  726. 'sockets': raw[5]}
  727. return info
  728. def get_nics(vm_):
  729. '''
  730. Return info about the network interfaces of a named vm
  731. CLI Example:
  732. .. code-block:: bash
  733. salt '*' virtng.get_nics <vm name>
  734. '''
  735. nics = {}
  736. doc = minidom.parse(_StringIO(get_xml(vm_)))
  737. for node in doc.getElementsByTagName('devices'):
  738. i_nodes = node.getElementsByTagName('interface')
  739. for i_node in i_nodes:
  740. nic = {}
  741. nic['type'] = i_node.getAttribute('type')
  742. for v_node in i_node.getElementsByTagName('*'):
  743. if v_node.tagName == 'mac':
  744. nic['mac'] = v_node.getAttribute('address')
  745. if v_node.tagName == 'model':
  746. nic['model'] = v_node.getAttribute('type')
  747. if v_node.tagName == 'target':
  748. nic['target'] = v_node.getAttribute('dev')
  749. # driver, source, and match can all have optional attributes
  750. if re.match('(driver|source|address)', v_node.tagName):
  751. temp = {}
  752. for key, value in v_node.attributes.items():
  753. temp[key] = value
  754. nic[str(v_node.tagName)] = temp
  755. # virtualport needs to be handled separately, to pick up the
  756. # type attribute of the virtualport itself
  757. if v_node.tagName == 'virtualport':
  758. temp = {}
  759. temp['type'] = v_node.getAttribute('type')
  760. for key, value in v_node.attributes.items():
  761. temp[key] = value
  762. nic['virtualport'] = temp
  763. if 'mac' not in nic:
  764. continue
  765. nics[nic['mac']] = nic
  766. return nics
  767. def get_macs(vm_):
  768. '''
  769. Return a list off MAC addresses from the named vm
  770. CLI Example:
  771. .. code-block:: bash
  772. salt '*' virtng.get_macs <vm name>
  773. '''
  774. macs = []
  775. doc = minidom.parse(_StringIO(get_xml(vm_)))
  776. for node in doc.getElementsByTagName('devices'):
  777. i_nodes = node.getElementsByTagName('interface')
  778. for i_node in i_nodes:
  779. for v_node in i_node.getElementsByTagName('mac'):
  780. macs.append(v_node.getAttribute('address'))
  781. return macs
  782. def get_graphics(vm_):
  783. '''
  784. Returns the information on vnc for a given vm
  785. CLI Example:
  786. .. code-block:: bash
  787. salt '*' virtng.get_graphics <vm name>
  788. '''
  789. out = {'autoport': 'None',
  790. 'keymap': 'None',
  791. 'listen': 'None',
  792. 'port': 'None',
  793. 'type': 'vnc'}
  794. xml = get_xml(vm_)
  795. ssock = _StringIO(xml)
  796. doc = minidom.parse(ssock)
  797. for node in doc.getElementsByTagName('domain'):
  798. g_nodes = node.getElementsByTagName('graphics')
  799. for g_node in g_nodes:
  800. for key, value in g_node.attributes.items():
  801. out[key] = value
  802. return out
  803. def get_disks(vm_):
  804. '''
  805. Return the disks of a named vm
  806. CLI Example:
  807. .. code-block:: bash
  808. salt '*' virtng.get_disks <vm name>
  809. '''
  810. disks = {}
  811. doc = minidom.parse(_StringIO(get_xml(vm_)))
  812. for elem in doc.getElementsByTagName('disk'):
  813. sources = elem.getElementsByTagName('source')
  814. targets = elem.getElementsByTagName('target')
  815. if len(sources) > 0:
  816. source = sources[0]
  817. else:
  818. continue
  819. if len(targets) > 0:
  820. target = targets[0]
  821. else:
  822. continue
  823. if target.hasAttribute('dev'):
  824. qemu_target = ''
  825. if source.hasAttribute('file'):
  826. qemu_target = source.getAttribute('file')
  827. elif source.hasAttribute('dev'):
  828. qemu_target = source.getAttribute('dev')
  829. elif source.hasAttribute('protocol') and \
  830. source.hasAttribute('name'): # For rbd network
  831. qemu_target = '{0}:{1}'.format(
  832. source.getAttribute('protocol'),
  833. source.getAttribute('name'))
  834. if qemu_target:
  835. disks[target.getAttribute('dev')] = {
  836. 'file': qemu_target}
  837. for dev in disks:
  838. try:
  839. hypervisor = __salt__['config.get']('libvirt:hypervisor', 'kvm')
  840. if hypervisor not in ['qemu', 'kvm']:
  841. break
  842. output = []
  843. qemu_output = subprocess.Popen(['qemu-img', 'info',
  844. disks[dev]['file']],
  845. shell=False,
  846. stdout=subprocess.PIPE).communicate()[0]
  847. snapshots = False
  848. columns = None
  849. lines = qemu_output.strip().split('\n')
  850. for line in lines:
  851. if line.startswith('Snapshot list:'):
  852. snapshots = True
  853. continue
  854. # If this is a copy-on-write image, then the backing file
  855. # represents the base image
  856. #
  857. # backing file: base.qcow2 (actual path: /var/shared/base.qcow2)
  858. elif line.startswith('backing file'):
  859. matches = re.match(r'.*\(actual path: (.*?)\)', line)
  860. if matches:
  861. output.append('backing file: {0}'.format(matches.group(1)))
  862. continue
  863. elif snapshots:
  864. if line.startswith('ID'): # Do not parse table headers
  865. line = line.replace('VM SIZE', 'VMSIZE')
  866. line = line.replace('VM CLOCK', 'TIME VMCLOCK')
  867. columns = re.split(r'\s+', line)
  868. columns = [c.lower() for c in columns]
  869. output.append('snapshots:')
  870. continue
  871. fields = re.split(r'\s+', line)
  872. for i, field in enumerate(fields):
  873. sep = ' '
  874. if i == 0:
  875. sep = '-'
  876. output.append(
  877. '{0} {1}: "{2}"'.format(
  878. sep, columns[i], field
  879. )
  880. )
  881. continue
  882. output.append(line)
  883. output = '\n'.join(output)
  884. disks[dev].update(yaml.safe_load(output))
  885. except TypeError:
  886. disks[dev].update(yaml.safe_load('image: Does not exist'))
  887. return disks
  888. def setmem(vm_, memory, config=False):
  889. '''
  890. Changes the amount of memory allocated to VM. The VM must be shutdown
  891. for this to work.
  892. memory is to be specified in MB
  893. If config is True then we ask libvirt to modify the config as well
  894. CLI Example:
  895. .. code-block:: bash
  896. salt '*' virtng.setmem myvm 768
  897. '''
  898. if vm_state(vm_) != 'shutdown':
  899. return False
  900. dom = _get_dom(vm_)
  901. # libvirt has a funny bitwise system for the flags in that the flag
  902. # to affect the "current" setting is 0, which means that to set the
  903. # current setting we have to call it a second time with just 0 set
  904. flags = libvirt.VIR_DOMAIN_MEM_MAXIMUM
  905. if config:
  906. flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG
  907. ret1 = dom.setMemoryFlags(memory * 1024, flags)
  908. ret2 = dom.setMemoryFlags(memory * 1024, libvirt.VIR_DOMAIN_AFFECT_CURRENT)
  909. # return True if both calls succeeded
  910. return ret1 == ret2 == 0
  911. def setvcpus(vm_, vcpus, config=False):
  912. '''
  913. Changes the amount of vcpus allocated to VM. The VM must be shutdown
  914. for this to work.
  915. vcpus is an int representing the number to be assigned
  916. If config is True then we ask libvirt to modify the config as well
  917. CLI Example:
  918. .. code-block:: bash
  919. salt '*' virtng.setvcpus myvm 2
  920. '''
  921. if vm_state(vm_) != 'shutdown':
  922. return False
  923. dom = _get_dom(vm_)
  924. # see notes in setmem
  925. flags = libvirt.VIR_DOMAIN_VCPU_MAXIMUM
  926. if config:
  927. flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG
  928. ret1 = dom.setVcpusFlags(vcpus, flags)
  929. ret2 = dom.setVcpusFlags(vcpus, libvirt.VIR_DOMAIN_AFFECT_CURRENT)
  930. return ret1 == ret2 == 0
  931. def freemem():
  932. '''
  933. Return an int representing the amount of memory that has not been given
  934. to virtual machines on this node
  935. CLI Example:
  936. .. code-block:: bash
  937. salt '*' virtng.freemem
  938. '''
  939. conn = __get_conn()
  940. mem = conn.getInfo()[1]
  941. # Take off just enough to sustain the hypervisor
  942. mem -= 256
  943. for vm_ in list_vms():
  944. dom = _get_dom(vm_)
  945. if dom.ID() > 0:
  946. mem -= dom.info()[2] / 1024
  947. return mem
  948. def freecpu():
  949. '''
  950. Return an int representing the number of unallocated cpus on this
  951. hypervisor
  952. CLI Example:
  953. .. code-block:: bash
  954. salt '*' virtng.freecpu
  955. '''
  956. conn = __get_conn()
  957. cpus = conn.getInfo()[2]
  958. for vm_ in list_vms():
  959. dom = _get_dom(vm_)
  960. if dom.ID() > 0:
  961. cpus -= dom.info()[3]
  962. return cpus
  963. def full_info():
  964. '''
  965. Return the node_info, vm_info and freemem
  966. CLI Example:
  967. .. code-block:: bash
  968. salt '*' virtng.full_info
  969. '''
  970. return {'freecpu': freecpu(),
  971. 'freemem': freemem(),
  972. 'node_info': node_info(),
  973. 'vm_info': vm_info()}
  974. def get_xml(vm_):
  975. '''
  976. Returns the XML for a given vm
  977. CLI Example:
  978. .. code-block:: bash
  979. salt '*' virtng.get_xml <vm name>
  980. '''
  981. dom = _get_dom(vm_)
  982. return dom.XMLDesc(0)
  983. def get_profiles(hypervisor=None):
  984. '''
  985. Return the virt profiles for hypervisor.
  986. Currently there are profiles for:
  987. - nic
  988. - disk
  989. CLI Example:
  990. .. code-block:: bash
  991. salt '*' virtng.get_profiles
  992. salt '*' virtng.get_profiles hypervisor=esxi
  993. '''
  994. ret = {}
  995. if hypervisor:
  996. hypervisor = hypervisor
  997. else:
  998. hypervisor = __salt__['config.get']('libvirt:hypervisor', VIRT_DEFAULT_HYPER)
  999. virtconf = __salt__['config.get']('virt', {})
  1000. for typ in ['disk', 'nic']:
  1001. _func = getattr(sys.modules[__name__], '_{0}_profile'.format(typ))
  1002. ret[typ] = {'default': _func('default', hypervisor)}
  1003. if typ in virtconf:
  1004. ret.setdefault(typ, {})
  1005. for prf in virtconf[typ]:
  1006. ret[typ][prf] = _func(prf, hypervisor)
  1007. return ret
  1008. def shutdown(vm_):
  1009. '''
  1010. Send a soft shutdown signal to the named vm
  1011. CLI Example:
  1012. .. code-block:: bash
  1013. salt '*' virtng.shutdown <vm name>
  1014. '''
  1015. dom = _get_dom(vm_)
  1016. return dom.shutdown() == 0
  1017. def pause(vm_):
  1018. '''
  1019. Pause the named vm
  1020. CLI Example:
  1021. .. code-block:: bash
  1022. salt '*' virtng.pause <vm name>
  1023. '''
  1024. dom = _get_dom(vm_)
  1025. return dom.suspend() == 0
  1026. def resume(vm_):
  1027. '''
  1028. Resume the named vm
  1029. CLI Example:
  1030. .. code-block:: bash
  1031. salt '*' virtng.resume <vm name>
  1032. '''
  1033. dom = _get_dom(vm_)
  1034. return dom.resume() == 0
  1035. def create(vm_):
  1036. '''
  1037. Start a defined domain
  1038. CLI Example:
  1039. .. code-block:: bash
  1040. salt '*' virtng.create <vm name>
  1041. '''
  1042. dom = _get_dom(vm_)
  1043. return dom.create() == 0
  1044. def start(vm_):
  1045. '''
  1046. Alias for the obscurely named 'create' function
  1047. CLI Example:
  1048. .. code-block:: bash
  1049. salt '*' virtng.start <vm name>
  1050. '''
  1051. return create(vm_)
  1052. def stop(vm_):
  1053. '''
  1054. Alias for the obscurely named 'destroy' function
  1055. CLI Example:
  1056. .. code-block:: bash
  1057. salt '*' virtng.stop <vm name>
  1058. '''
  1059. return destroy(vm_)
  1060. def reboot(vm_):
  1061. '''
  1062. Reboot a domain via ACPI request
  1063. CLI Example:
  1064. .. code-block:: bash
  1065. salt '*' virtng.reboot <vm name>
  1066. '''
  1067. dom = _get_dom(vm_)
  1068. # reboot has a few modes of operation, passing 0 in means the
  1069. # hypervisor will pick the best method for rebooting
  1070. return dom.reboot(0) == 0
  1071. def reset(vm_):
  1072. '''
  1073. Reset a VM by emulating the reset button on a physical machine
  1074. CLI Example:
  1075. .. code-block:: bash
  1076. salt '*' virtng.reset <vm name>
  1077. '''
  1078. dom = _get_dom(vm_)
  1079. # reset takes a flag, like reboot, but it is not yet used
  1080. # so we just pass in 0
  1081. # see: http://libvirt.org/html/libvirt-libvirt.html#virDomainReset
  1082. return dom.reset(0) == 0
  1083. def ctrl_alt_del(vm_):
  1084. '''
  1085. Sends CTRL+ALT+DEL to a VM
  1086. CLI Example:
  1087. .. code-block:: bash
  1088. salt '*' virtng.ctrl_alt_del <vm name>
  1089. '''
  1090. dom = _get_dom(vm_)
  1091. return dom.sendKey(0, 0, [29, 56, 111], 3, 0) == 0
  1092. def create_xml_str(xml):
  1093. '''
  1094. Start a domain based on the XML passed to the function
  1095. CLI Example:
  1096. .. code-block:: bash
  1097. salt '*' virtng.create_xml_str <XML in string format>
  1098. '''
  1099. conn = __get_conn()
  1100. return conn.createXML(xml, 0) is not None
  1101. def create_xml_path(path):
  1102. '''
  1103. Start a domain based on the XML-file path passed to the function
  1104. CLI Example:
  1105. .. code-block:: bash
  1106. salt '*' virtng.create_xml_path <path to XML file on the node>
  1107. '''
  1108. if not os.path.isfile(path):
  1109. return False
  1110. return create_xml_str(salt.utils.fopen(path, 'r').read())
  1111. def define_xml_str(xml):
  1112. '''
  1113. Define a domain based on the XML passed to the function
  1114. CLI Example:
  1115. .. code-block:: bash
  1116. salt '*' virtng.define_xml_str <XML in string format>
  1117. '''
  1118. conn = __get_conn()
  1119. return conn.defineXML(xml) is not None
  1120. def define_xml_path(path):
  1121. '''
  1122. Define a domain based on the XML-file path passed to the function
  1123. CLI Example:
  1124. .. code-block:: bash
  1125. salt '*' virtng.define_xml_path <path to XML file on the node>
  1126. '''
  1127. if not os.path.isfile(path):
  1128. return False
  1129. return define_xml_str(salt.utils.fopen(path, 'r').read())
  1130. def define_vol_xml_str(xml):
  1131. '''
  1132. Define a volume based on the XML passed to the function
  1133. CLI Example:
  1134. .. code-block:: bash
  1135. salt '*' virtng.define_vol_xml_str <XML in string format>
  1136. '''
  1137. poolname = __salt__['config.get']('libvirt:storagepool', 'default')
  1138. conn = __get_conn()
  1139. pool = conn.storagePoolLookupByName(str(poolname))
  1140. return pool.createXML(xml, 0) is not None
  1141. def define_vol_xml_path(path):
  1142. '''
  1143. Define a volume based on the XML-file path passed to the function
  1144. CLI Example:
  1145. .. code-block:: bash
  1146. salt '*' virtng.define_vol_xml_path <path to XML file on the node>
  1147. '''
  1148. if not os.path.isfile(path):
  1149. return False
  1150. return define_vol_xml_str(salt.utils.fopen(path, 'r').read())
  1151. def migrate_non_shared(vm_, target, ssh=False):
  1152. '''
  1153. Attempt to execute non-shared storage "all" migration
  1154. CLI Example:
  1155. .. code-block:: bash
  1156. salt '*' virtng.migrate_non_shared <vm name> <target hypervisor>
  1157. '''
  1158. cmd = _get_migrate_command() + ' --copy-storage-all ' + vm_\
  1159. + _get_target(target, ssh)
  1160. return subprocess.Popen(cmd,
  1161. shell=True,
  1162. stdout=subprocess.PIPE).communicate()[0]
  1163. def migrate_non_shared_inc(vm_, target, ssh=False):
  1164. '''
  1165. Attempt to execute non-shared storage "all" migration
  1166. CLI Example:
  1167. .. code-block:: bash
  1168. salt '*' virtng.migrate_non_shared_inc <vm name> <target hypervisor>
  1169. '''
  1170. cmd = _get_migrate_command() + ' --copy-storage-inc ' + vm_\
  1171. + _get_target(target, ssh)
  1172. return subprocess.Popen(cmd,
  1173. shell=True,
  1174. stdout=subprocess.PIPE).communicate()[0]
  1175. def migrate(vm_, target, ssh=False):
  1176. '''
  1177. Shared storage migration
  1178. CLI Example:
  1179. .. code-block:: bash
  1180. salt '*' virtng.migrate <vm name> <target hypervisor>
  1181. '''
  1182. cmd = _get_migrate_command() + ' ' + vm_\
  1183. + _get_target(target, ssh)
  1184. return subprocess.Popen(cmd,
  1185. shell=True,
  1186. stdout=subprocess.PIPE).communicate()[0]
  1187. def seed_non_shared_migrate(disks, force=False):
  1188. '''
  1189. Non shared migration requires that the disks be present on the migration
  1190. destination, pass the disks information via this function, to the
  1191. migration destination before executing the migration.
  1192. CLI Example:
  1193. .. code-block:: bash
  1194. salt '*' virtng.seed_non_shared_migrate <disks>
  1195. '''
  1196. for _, data in disks.items():
  1197. fn_ = data['file']
  1198. form = data['file format']
  1199. size = data['virtual size'].split()[1][1:]
  1200. if os.path.isfile(fn_) and not force:
  1201. # the target exists, check to see if it is compatible
  1202. pre = yaml.safe_load(subprocess.Popen('qemu-img info arch',
  1203. shell=True,
  1204. stdout=subprocess.PIPE).communicate()[0])
  1205. if pre['file format'] != data['file format']\
  1206. and pre['virtual size'] != data['virtual size']:
  1207. return False
  1208. if not os.path.isdir(os.path.dirname(fn_)):
  1209. os.makedirs(os.path.dirname(fn_))
  1210. if os.path.isfile(fn_):
  1211. os.remove(fn_)
  1212. cmd = 'qemu-img create -f ' + form + ' ' + fn_ + ' ' + size
  1213. subprocess.call(cmd, shell=True)
  1214. creds = _libvirt_creds()
  1215. cmd = 'chown ' + creds['user'] + ':' + creds['group'] + ' ' + fn_
  1216. subprocess.call(cmd, shell=True)
  1217. return True
  1218. def set_autostart(vm_, state='on'):
  1219. '''
  1220. Set the autostart flag on a VM so that the VM will start with the host
  1221. system on reboot.
  1222. CLI Example:
  1223. .. code-block:: bash
  1224. salt "*" virt.set_autostart <vm name> <on | off>
  1225. '''
  1226. dom = _get_dom(vm_)
  1227. if state == 'on':
  1228. return dom.setAutostart(1) == 0
  1229. elif state == 'off':
  1230. return dom.setAutostart(0) == 0
  1231. else:
  1232. # return False if state is set to something other then on or off
  1233. return False
  1234. def destroy(vm_):
  1235. '''
  1236. Hard power down the virtual machine, this is equivalent to pulling the
  1237. power
  1238. CLI Example:
  1239. .. code-block:: bash
  1240. salt '*' virtng.destroy <vm name>
  1241. '''
  1242. dom = _get_dom(vm_)
  1243. return dom.destroy() == 0
  1244. def undefine(vm_):
  1245. '''
  1246. Remove a defined vm, this does not purge the virtual machine image, and
  1247. this only works if the vm is powered down
  1248. CLI Example:
  1249. .. code-block:: bash
  1250. salt '*' virtng.undefine <vm name>
  1251. '''
  1252. dom = _get_dom(vm_)
  1253. return dom.undefine() == 0
  1254. def purge(vm_, dirs=False):
  1255. '''
  1256. Recursively destroy and delete a virtual machine, pass True for dir's to
  1257. also delete the directories containing the virtual machine disk images -
  1258. USE WITH EXTREME CAUTION!
  1259. CLI Example:
  1260. .. code-block:: bash
  1261. salt '*' virtng.purge <vm name>
  1262. '''
  1263. disks = get_disks(vm_)
  1264. try:
  1265. if not destroy(vm_):
  1266. return False
  1267. except libvirt.libvirtError:
  1268. # This is thrown if the machine is already shut down
  1269. pass
  1270. directories = set()
  1271. for disk in disks:
  1272. os.remove(disks[disk]['file'])
  1273. directories.add(os.path.dirname(disks[disk]['file']))
  1274. if dirs:
  1275. for dir_ in directories:
  1276. shutil.rmtree(dir_)
  1277. undefine(vm_)
  1278. return True
  1279. def virt_type():
  1280. '''
  1281. Returns the virtual machine type as a string
  1282. CLI Example:
  1283. .. code-block:: bash
  1284. salt '*' virtng.virt_type
  1285. '''
  1286. return __grains__['virtual']
  1287. def is_kvm_hyper():
  1288. '''
  1289. Returns a bool whether or not this node is a KVM hypervisor
  1290. CLI Example:
  1291. .. code-block:: bash
  1292. salt '*' virtng.is_kvm_hyper
  1293. '''
  1294. try:
  1295. if 'kvm_' not in salt.utils.fopen('/proc/modules').read():
  1296. return False
  1297. except IOError:
  1298. # No /proc/modules? Are we on Windows? Or Solaris?
  1299. return False
  1300. return 'libvirtd' in __salt__['cmd.shell'](__grains__['ps'])
  1301. def is_xen_hyper():
  1302. '''
  1303. Returns a bool whether or not this node is a XEN hypervisor
  1304. CLI Example:
  1305. .. code-block:: bash
  1306. salt '*' virtng.is_xen_hyper
  1307. '''
  1308. try:
  1309. if __grains__['virtual_subtype'] != 'Xen Dom0':
  1310. return False
  1311. except KeyError:
  1312. # virtual_subtype isn't set everywhere.
  1313. return False
  1314. try:
  1315. if 'xen_' not in salt.utils.fopen('/proc/modules').read():
  1316. return False
  1317. except IOError:
  1318. # No /proc/modules? Are we on Windows? Or Solaris?
  1319. return False
  1320. return 'libvirtd' in __salt__['cmd.shell'](__grains__['ps'])
  1321. def is_hyper():
  1322. '''
  1323. Returns a bool whether or not this node is a hypervisor of any kind
  1324. CLI Example:
  1325. .. code-block:: bash
  1326. salt '*' virtng.is_hyper
  1327. '''
  1328. try:
  1329. import libvirt # pylint: disable=import-error
  1330. except ImportError:
  1331. # not a usable hypervisor without libvirt module
  1332. return False
  1333. return is_xen_hyper() or is_kvm_hyper()
  1334. def vm_cputime(vm_=None):
  1335. '''
  1336. Return cputime used by the vms on this hyper in a
  1337. list of dicts:
  1338. .. code-block:: python
  1339. [
  1340. 'your-vm': {
  1341. 'cputime' <int>
  1342. 'cputime_percent' <int>
  1343. },
  1344. ...
  1345. ]
  1346. If you pass a VM name in as an argument then it will return info
  1347. for just the named VM, otherwise it will return all VMs.
  1348. CLI Example:
  1349. .. code-block:: bash
  1350. salt '*' virtng.vm_cputime
  1351. '''
  1352. host_cpus = __get_conn().getInfo()[2]
  1353. def _info(vm_):
  1354. dom = _get_dom(vm_)
  1355. raw = dom.info()
  1356. vcpus = int(raw[3])
  1357. cputime = int(raw[4])
  1358. cputime_percent = 0
  1359. if cputime:
  1360. # Divide by vcpus to always return a number between 0 and 100
  1361. cputime_percent = (1.0e-7 * cputime / host_cpus) / vcpus
  1362. return {
  1363. 'cputime': int(raw[4]),
  1364. 'cputime_percent': int('{0:.0f}'.format(cputime_percent))
  1365. }
  1366. info = {}
  1367. if vm_:
  1368. info[vm_] = _info(vm_)
  1369. else:
  1370. for vm_ in list_vms():
  1371. info[vm_] = _info(vm_)
  1372. return info
  1373. def vm_netstats(vm_=None):
  1374. '''
  1375. Return combined network counters used by the vms on this hyper in a
  1376. list of dicts:
  1377. .. code-block:: python
  1378. [
  1379. 'your-vm': {
  1380. 'rx_bytes' : 0,
  1381. 'rx_packets' : 0,
  1382. 'rx_errs' : 0,
  1383. 'rx_drop' : 0,
  1384. 'tx_bytes' : 0,
  1385. 'tx_packets' : 0,
  1386. 'tx_errs' : 0,
  1387. 'tx_drop' : 0
  1388. },
  1389. ...
  1390. ]
  1391. If you pass a VM name in as an argument then it will return info
  1392. for just the named VM, otherwise it will return all VMs.
  1393. CLI Example:
  1394. .. code-block:: bash
  1395. salt '*' virtng.vm_netstats
  1396. '''
  1397. def _info(vm_):
  1398. dom = _get_dom(vm_)
  1399. nics = get_nics(vm_)
  1400. ret = {
  1401. 'rx_bytes': 0,
  1402. 'rx_packets': 0,
  1403. 'rx_errs': 0,
  1404. 'rx_drop': 0,
  1405. 'tx_bytes': 0,
  1406. 'tx_packets': 0,
  1407. 'tx_errs': 0,
  1408. 'tx_drop': 0
  1409. }
  1410. for attrs in six.itervalues(nics):
  1411. if 'target' in attrs:
  1412. dev = attrs['target']
  1413. stats = dom.interfaceStats(dev)
  1414. ret['rx_bytes'] += stats[0]
  1415. ret['rx_packets'] += stats[1]
  1416. ret['rx_errs'] += stats[2]
  1417. ret['rx_drop'] += stats[3]
  1418. ret['tx_bytes'] += stats[4]
  1419. ret['tx_packets'] += stats[5]
  1420. ret['tx_errs'] += stats[6]
  1421. ret['tx_drop'] += stats[7]
  1422. return ret
  1423. info = {}
  1424. if vm_:
  1425. info[vm_] = _info(vm_)
  1426. else:
  1427. for vm_ in list_vms():
  1428. info[vm_] = _info(vm_)
  1429. return info
  1430. def vm_diskstats(vm_=None):
  1431. '''
  1432. Return disk usage counters used by the vms on this hyper in a
  1433. list of dicts:
  1434. .. code-block:: python
  1435. [
  1436. 'your-vm': {
  1437. 'rd_req' : 0,
  1438. 'rd_bytes' : 0,
  1439. 'wr_req' : 0,
  1440. 'wr_bytes' : 0,
  1441. 'errs' : 0
  1442. },
  1443. ...
  1444. ]
  1445. If you pass a VM name in as an argument then it will return info
  1446. for just the named VM, otherwise it will return all VMs.
  1447. CLI Example:
  1448. .. code-block:: bash
  1449. salt '*' virtng.vm_blockstats
  1450. '''
  1451. def get_disk_devs(vm_):
  1452. doc = minidom.parse(_StringIO(get_xml(vm_)))
  1453. disks = []
  1454. for elem in doc.getElementsByTagName('disk'):
  1455. targets = elem.getElementsByTagName('target')
  1456. target = targets[0]
  1457. disks.append(target.getAttribute('dev'))
  1458. return disks
  1459. def _info(vm_):
  1460. dom = _get_dom(vm_)
  1461. # Do not use get_disks, since it uses qemu-img and is very slow
  1462. # and unsuitable for any sort of real time statistics
  1463. disks = get_disk_devs(vm_)
  1464. ret = {'rd_req': 0,
  1465. 'rd_bytes': 0,
  1466. 'wr_req': 0,
  1467. 'wr_bytes': 0,
  1468. 'errs': 0
  1469. }
  1470. for disk in disks:
  1471. stats = dom.blockStats(disk)
  1472. ret['rd_req'] += stats[0]
  1473. ret['rd_bytes'] += stats[1]
  1474. ret['wr_req'] += stats[2]
  1475. ret['wr_bytes'] += stats[3]
  1476. ret['errs'] += stats[4]
  1477. return ret
  1478. info = {}
  1479. if vm_:
  1480. info[vm_] = _info(vm_)
  1481. else:
  1482. # Can not run function blockStats on inactive VMs
  1483. for vm_ in list_active_vms():
  1484. info[vm_] = _info(vm_)
  1485. return info