New version of salt-formula from Saltstack
Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

1818 Zeilen
48KB

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