New Saltstack Salt formula
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

1849 lines
50KB

  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.shell']('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.shell']('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. if 'img_dest' in kwargs:
  298. ret['pool'] = kwargs['img_dest']
  299. else:
  300. ret['pool'] = __salt__['config.option']('virt.images')
  301. return ret
  302. def _disk_profile(profile, hypervisor, **kwargs):
  303. '''
  304. Gather the disk profile from the config or apply the default based
  305. on the active hypervisor
  306. This is the ``default`` profile for KVM/QEMU, which can be
  307. overridden in the configuration:
  308. .. code-block:: yaml
  309. virt:
  310. disk:
  311. default:
  312. - system:
  313. size: 8192
  314. format: qcow2
  315. model: virtio
  316. Example profile for KVM/QEMU with two disks, first is created
  317. from specified image, the second is empty:
  318. .. code-block:: yaml
  319. virt:
  320. disk:
  321. two_disks:
  322. - system:
  323. size: 8192
  324. format: qcow2
  325. model: virtio
  326. image: http://path/to/image.qcow2
  327. - lvm:
  328. size: 32768
  329. format: qcow2
  330. model: virtio
  331. The ``format`` and ``model`` parameters are optional, and will
  332. default to whatever is best suitable for the active hypervisor.
  333. '''
  334. default = [
  335. {'system':
  336. {'size': '8192'}
  337. }
  338. ]
  339. if hypervisor in ['esxi', 'vmware']:
  340. overlay = {'format': 'vmdk',
  341. 'model': 'scsi',
  342. 'pool': '[{0}] '.format(kwargs.get('pool', '0'))
  343. }
  344. elif hypervisor in ['qemu', 'kvm']:
  345. if 'img_dest' in kwargs:
  346. pool = kwargs['img_dest']
  347. else:
  348. pool = __salt__['config.option']('virt.images')
  349. overlay = {'format': 'qcow2', 'model': 'virtio', 'pool': pool}
  350. else:
  351. overlay = {}
  352. disklist = copy.deepcopy(__salt__['config.get']('virt:disk', {}).get(profile, default))
  353. for key, val in overlay.items():
  354. for i, disks in enumerate(disklist):
  355. for disk in disks:
  356. if key not in disks[disk]:
  357. disklist[i][disk][key] = val
  358. return disklist
  359. def _nic_profile(profile_name, hypervisor, **kwargs):
  360. default = [{'eth0': {}}]
  361. vmware_overlay = {'type': 'bridge', 'source': 'DEFAULT', 'model': 'e1000'}
  362. kvm_overlay = {'type': 'bridge', 'source': 'br0', 'model': 'virtio'}
  363. overlays = {
  364. 'kvm': kvm_overlay,
  365. 'qemu': kvm_overlay,
  366. 'esxi': vmware_overlay,
  367. 'vmware': vmware_overlay,
  368. }
  369. # support old location
  370. config_data = __salt__['config.option']('virt.nic', {}).get(
  371. profile_name, None
  372. )
  373. if config_data is None:
  374. config_data = __salt__['config.get']('virt:nic', {}).get(
  375. profile_name, default
  376. )
  377. interfaces = []
  378. def append_dict_profile_to_interface_list(profile_dict):
  379. for interface_name, attributes in profile_dict.items():
  380. attributes['name'] = interface_name
  381. interfaces.append(attributes)
  382. # old style dicts (top-level dicts)
  383. #
  384. # virt:
  385. # nic:
  386. # eth0:
  387. # bridge: br0
  388. # eth1:
  389. # network: test_net
  390. if isinstance(config_data, dict):
  391. append_dict_profile_to_interface_list(config_data)
  392. # new style lists (may contain dicts)
  393. #
  394. # virt:
  395. # nic:
  396. # - eth0:
  397. # bridge: br0
  398. # - eth1:
  399. # network: test_net
  400. #
  401. # virt:
  402. # nic:
  403. # - name: eth0
  404. # bridge: br0
  405. # - name: eth1
  406. # network: test_net
  407. elif isinstance(config_data, list):
  408. for interface in config_data:
  409. if isinstance(interface, dict):
  410. if len(interface) == 1:
  411. append_dict_profile_to_interface_list(interface)
  412. else:
  413. interfaces.append(interface)
  414. def _normalize_net_types(attributes):
  415. '''
  416. Guess which style of definition:
  417. bridge: br0
  418. or
  419. network: net0
  420. or
  421. type: network
  422. source: net0
  423. '''
  424. for type_ in ['bridge', 'network']:
  425. if type_ in attributes:
  426. attributes['type'] = type_
  427. # we want to discard the original key
  428. attributes['source'] = attributes.pop(type_)
  429. attributes['type'] = attributes.get('type', None)
  430. attributes['source'] = attributes.get('source', None)
  431. def _apply_default_overlay(attributes):
  432. for key, value in overlays[hypervisor].items():
  433. if key not in attributes or not attributes[key]:
  434. attributes[key] = value
  435. def _assign_mac(attributes):
  436. dmac = '{0}_mac'.format(attributes['name'])
  437. if dmac in kwargs:
  438. dmac = kwargs[dmac]
  439. if salt.utils.validate.net.mac(dmac):
  440. attributes['mac'] = dmac
  441. else:
  442. msg = 'Malformed MAC address: {0}'.format(dmac)
  443. raise CommandExecutionError(msg)
  444. else:
  445. attributes['mac'] = salt.utils.gen_mac()
  446. for interface in interfaces:
  447. _normalize_net_types(interface)
  448. _assign_mac(interface)
  449. if hypervisor in overlays:
  450. _apply_default_overlay(interface)
  451. return interfaces
  452. def init(name,
  453. cpu,
  454. mem,
  455. image=None,
  456. nic='default',
  457. hypervisor=VIRT_DEFAULT_HYPER,
  458. start=True, # pylint: disable=redefined-outer-name
  459. disk='default',
  460. saltenv='base',
  461. rng={},
  462. **kwargs):
  463. '''
  464. Initialize a new vm
  465. CLI Example:
  466. .. code-block:: bash
  467. salt 'hypervisor' virt.init vm_name 4 512 salt://path/to/image.raw
  468. salt 'hypervisor' virt.init vm_name 4 512 nic=profile disk=profile
  469. '''
  470. hypervisor = __salt__['config.get']('libvirt:hypervisor', hypervisor)
  471. nicp = _nic_profile(nic, hypervisor, **kwargs)
  472. diskp = _disk_profile(disk, hypervisor, **kwargs)
  473. if image:
  474. # Backward compatibility: if 'image' is specified in the VMs arguments
  475. # instead of a disk arguments. In this case, 'image' will be assigned
  476. # to the first disk for the VM.
  477. disk_name = next(diskp[0].iterkeys())
  478. if not diskp[0][disk_name].get('image', None):
  479. diskp[0][disk_name]['image'] = image
  480. # Create multiple disks, empty or from specified images.
  481. for disk in diskp:
  482. log.debug("Creating disk for VM [ {0} ]: {1}".format(name, disk))
  483. for disk_name, args in disk.items():
  484. if hypervisor in ['esxi', 'vmware']:
  485. if 'image' in args:
  486. # TODO: we should be copying the image file onto the ESX host
  487. raise SaltInvocationError('virt.init does not support image '
  488. 'template template in conjunction '
  489. 'with esxi hypervisor')
  490. else:
  491. # assume libvirt manages disks for us
  492. xml = _gen_vol_xml(name,
  493. disk_name,
  494. args['size'],
  495. hypervisor,
  496. **kwargs)
  497. define_vol_xml_str(xml)
  498. elif hypervisor in ['qemu', 'kvm']:
  499. disk_type = args['format']
  500. disk_file_name = '{0}.{1}'.format(disk_name, disk_type)
  501. # disk size TCP cloud
  502. disk_size = args['size']
  503. if 'img_dest' in kwargs:
  504. img_dir = kwargs['img_dest']
  505. else:
  506. img_dir = __salt__['config.option']('virt.images')
  507. img_dest = os.path.join(
  508. img_dir,
  509. name,
  510. disk_file_name
  511. )
  512. img_dir = os.path.dirname(img_dest)
  513. if not os.path.isdir(img_dir):
  514. os.makedirs(img_dir)
  515. if 'image' in args:
  516. # Create disk from specified image
  517. sfn = __salt__['cp.cache_file'](args['image'], saltenv)
  518. try:
  519. salt.utils.files.copyfile(sfn, img_dest)
  520. mask = os.umask(0)
  521. os.umask(mask)
  522. # Apply umask and remove exec bit
  523. # Resizing image TCP cloud
  524. cmd = 'qemu-img resize ' + img_dest + ' ' + str(disk_size) + 'M'
  525. subprocess.call(cmd, shell=True)
  526. mode = (0o0777 ^ mask) & 0o0666
  527. os.chmod(img_dest, mode)
  528. except (IOError, OSError) as e:
  529. raise CommandExecutionError('problem while copying image. {0} - {1}'.format(args['image'], e))
  530. if kwargs.get('seed'):
  531. install = kwargs.get('install', True)
  532. seed_cmd = kwargs.get('seed_cmd', 'seedng.apply')
  533. __salt__[seed_cmd](img_dest,
  534. id_=name,
  535. config=kwargs.get('config'),
  536. install=install)
  537. else:
  538. # Create empty disk
  539. try:
  540. mask = os.umask(0)
  541. os.umask(mask)
  542. # Apply umask and remove exec bit
  543. # Create empty image
  544. cmd = 'qemu-img create -f ' + disk_type + ' ' + img_dest + ' ' + str(disk_size) + 'M'
  545. subprocess.call(cmd, shell=True)
  546. mode = (0o0777 ^ mask) & 0o0666
  547. os.chmod(img_dest, mode)
  548. except (IOError, OSError) as e:
  549. raise CommandExecutionError('problem while creating volume {0} - {1}'.format(img_dest, e))
  550. else:
  551. # Unknown hypervisor
  552. raise SaltInvocationError('Unsupported hypervisor when handling disk image: {0}'
  553. .format(hypervisor))
  554. xml = _gen_xml(name, cpu, mem, diskp, nicp, hypervisor, **kwargs)
  555. # TODO: Remove this code and refactor module, when salt-common would have updated libvirt_domain.jinja template
  556. if rng:
  557. rng_model = rng.get('model', 'random')
  558. rng_backend = rng.get('backend', '/dev/urandom')
  559. xml_doc = minidom.parseString(xml)
  560. rng_xml = xml_doc.createElement("rng")
  561. rng_xml.setAttribute("model", "virtio")
  562. backend = xml_doc.createElement("backend")
  563. backend.setAttribute("model", rng_model)
  564. backend.appendChild(xml_doc.createTextNode(rng_backend))
  565. rng_xml.appendChild(backend)
  566. if 'rate' in rng:
  567. rng_rate_period = rng['rate'].get('period', '2000')
  568. rng_rate_bytes = rng['rate'].get('bytes', '1234')
  569. rate = xml_doc.createElement("rate")
  570. rate.setAttribute("period", rng_rate_period)
  571. rate.setAttribute("bytes", rng_rate_bytes)
  572. rng_xml.appendChild(rate)
  573. xml_doc.getElementsByTagName("domain")[0].getElementsByTagName("devices")[0].appendChild(rng_xml)
  574. xml = xml_doc.toxml()
  575. define_xml_str(xml)
  576. if start:
  577. create(name)
  578. return True
  579. def list_vms():
  580. '''
  581. Return a list of virtual machine names on the minion
  582. CLI Example:
  583. .. code-block:: bash
  584. salt '*' virtng.list_vms
  585. '''
  586. vms = []
  587. vms.extend(list_active_vms())
  588. vms.extend(list_inactive_vms())
  589. return vms
  590. def list_active_vms():
  591. '''
  592. Return a list of names for active virtual machine on the minion
  593. CLI Example:
  594. .. code-block:: bash
  595. salt '*' virtng.list_active_vms
  596. '''
  597. conn = __get_conn()
  598. vms = []
  599. for id_ in conn.listDomainsID():
  600. vms.append(conn.lookupByID(id_).name())
  601. return vms
  602. def list_inactive_vms():
  603. '''
  604. Return a list of names for inactive virtual machine on the minion
  605. CLI Example:
  606. .. code-block:: bash
  607. salt '*' virtng.list_inactive_vms
  608. '''
  609. conn = __get_conn()
  610. vms = []
  611. for id_ in conn.listDefinedDomains():
  612. vms.append(id_)
  613. return vms
  614. def vm_info(vm_=None):
  615. '''
  616. Return detailed information about the vms on this hyper in a
  617. list of dicts:
  618. .. code-block:: python
  619. [
  620. 'your-vm': {
  621. 'cpu': <int>,
  622. 'maxMem': <int>,
  623. 'mem': <int>,
  624. 'state': '<state>',
  625. 'cputime' <int>
  626. },
  627. ...
  628. ]
  629. If you pass a VM name in as an argument then it will return info
  630. for just the named VM, otherwise it will return all VMs.
  631. CLI Example:
  632. .. code-block:: bash
  633. salt '*' virtng.vm_info
  634. '''
  635. def _info(vm_):
  636. dom = _get_dom(vm_)
  637. raw = dom.info()
  638. return {'cpu': raw[3],
  639. 'cputime': int(raw[4]),
  640. 'disks': get_disks(vm_),
  641. 'graphics': get_graphics(vm_),
  642. 'nics': get_nics(vm_),
  643. 'maxMem': int(raw[1]),
  644. 'mem': int(raw[2]),
  645. 'state': VIRT_STATE_NAME_MAP.get(raw[0], 'unknown')}
  646. info = {}
  647. if vm_:
  648. info[vm_] = _info(vm_)
  649. else:
  650. for vm_ in list_vms():
  651. info[vm_] = _info(vm_)
  652. return info
  653. def vm_state(vm_=None):
  654. '''
  655. Return list of all the vms and their state.
  656. If you pass a VM name in as an argument then it will return info
  657. for just the named VM, otherwise it will return all VMs.
  658. CLI Example:
  659. .. code-block:: bash
  660. salt '*' virtng.vm_state <vm name>
  661. '''
  662. def _info(vm_):
  663. state = ''
  664. dom = _get_dom(vm_)
  665. raw = dom.info()
  666. state = VIRT_STATE_NAME_MAP.get(raw[0], 'unknown')
  667. return state
  668. info = {}
  669. if vm_:
  670. info[vm_] = _info(vm_)
  671. else:
  672. for vm_ in list_vms():
  673. info[vm_] = _info(vm_)
  674. return info
  675. def node_info():
  676. '''
  677. Return a dict with information about this node
  678. CLI Example:
  679. .. code-block:: bash
  680. salt '*' virtng.node_info
  681. '''
  682. conn = __get_conn()
  683. raw = conn.getInfo()
  684. info = {'cpucores': raw[6],
  685. 'cpumhz': raw[3],
  686. 'cpumodel': str(raw[0]),
  687. 'cpus': raw[2],
  688. 'cputhreads': raw[7],
  689. 'numanodes': raw[4],
  690. 'phymemory': raw[1],
  691. 'sockets': raw[5]}
  692. return info
  693. def get_nics(vm_):
  694. '''
  695. Return info about the network interfaces of a named vm
  696. CLI Example:
  697. .. code-block:: bash
  698. salt '*' virtng.get_nics <vm name>
  699. '''
  700. nics = {}
  701. doc = minidom.parse(_StringIO(get_xml(vm_)))
  702. for node in doc.getElementsByTagName('devices'):
  703. i_nodes = node.getElementsByTagName('interface')
  704. for i_node in i_nodes:
  705. nic = {}
  706. nic['type'] = i_node.getAttribute('type')
  707. for v_node in i_node.getElementsByTagName('*'):
  708. if v_node.tagName == 'mac':
  709. nic['mac'] = v_node.getAttribute('address')
  710. if v_node.tagName == 'model':
  711. nic['model'] = v_node.getAttribute('type')
  712. if v_node.tagName == 'target':
  713. nic['target'] = v_node.getAttribute('dev')
  714. # driver, source, and match can all have optional attributes
  715. if re.match('(driver|source|address)', v_node.tagName):
  716. temp = {}
  717. for key, value in v_node.attributes.items():
  718. temp[key] = value
  719. nic[str(v_node.tagName)] = temp
  720. # virtualport needs to be handled separately, to pick up the
  721. # type attribute of the virtualport itself
  722. if v_node.tagName == 'virtualport':
  723. temp = {}
  724. temp['type'] = v_node.getAttribute('type')
  725. for key, value in v_node.attributes.items():
  726. temp[key] = value
  727. nic['virtualport'] = temp
  728. if 'mac' not in nic:
  729. continue
  730. nics[nic['mac']] = nic
  731. return nics
  732. def get_macs(vm_):
  733. '''
  734. Return a list off MAC addresses from the named vm
  735. CLI Example:
  736. .. code-block:: bash
  737. salt '*' virtng.get_macs <vm name>
  738. '''
  739. macs = []
  740. doc = minidom.parse(_StringIO(get_xml(vm_)))
  741. for node in doc.getElementsByTagName('devices'):
  742. i_nodes = node.getElementsByTagName('interface')
  743. for i_node in i_nodes:
  744. for v_node in i_node.getElementsByTagName('mac'):
  745. macs.append(v_node.getAttribute('address'))
  746. return macs
  747. def get_graphics(vm_):
  748. '''
  749. Returns the information on vnc for a given vm
  750. CLI Example:
  751. .. code-block:: bash
  752. salt '*' virtng.get_graphics <vm name>
  753. '''
  754. out = {'autoport': 'None',
  755. 'keymap': 'None',
  756. 'listen': 'None',
  757. 'port': 'None',
  758. 'type': 'vnc'}
  759. xml = get_xml(vm_)
  760. ssock = _StringIO(xml)
  761. doc = minidom.parse(ssock)
  762. for node in doc.getElementsByTagName('domain'):
  763. g_nodes = node.getElementsByTagName('graphics')
  764. for g_node in g_nodes:
  765. for key, value in g_node.attributes.items():
  766. out[key] = value
  767. return out
  768. def get_disks(vm_):
  769. '''
  770. Return the disks of a named vm
  771. CLI Example:
  772. .. code-block:: bash
  773. salt '*' virtng.get_disks <vm name>
  774. '''
  775. disks = {}
  776. doc = minidom.parse(_StringIO(get_xml(vm_)))
  777. for elem in doc.getElementsByTagName('disk'):
  778. sources = elem.getElementsByTagName('source')
  779. targets = elem.getElementsByTagName('target')
  780. if len(sources) > 0:
  781. source = sources[0]
  782. else:
  783. continue
  784. if len(targets) > 0:
  785. target = targets[0]
  786. else:
  787. continue
  788. if target.hasAttribute('dev'):
  789. qemu_target = ''
  790. if source.hasAttribute('file'):
  791. qemu_target = source.getAttribute('file')
  792. elif source.hasAttribute('dev'):
  793. qemu_target = source.getAttribute('dev')
  794. elif source.hasAttribute('protocol') and \
  795. source.hasAttribute('name'): # For rbd network
  796. qemu_target = '{0}:{1}'.format(
  797. source.getAttribute('protocol'),
  798. source.getAttribute('name'))
  799. if qemu_target:
  800. disks[target.getAttribute('dev')] = {
  801. 'file': qemu_target}
  802. for dev in disks:
  803. try:
  804. hypervisor = __salt__['config.get']('libvirt:hypervisor', 'kvm')
  805. if hypervisor not in ['qemu', 'kvm']:
  806. break
  807. output = []
  808. qemu_output = subprocess.Popen(['qemu-img', 'info',
  809. disks[dev]['file']],
  810. shell=False,
  811. stdout=subprocess.PIPE).communicate()[0]
  812. snapshots = False
  813. columns = None
  814. lines = qemu_output.strip().split('\n')
  815. for line in lines:
  816. if line.startswith('Snapshot list:'):
  817. snapshots = True
  818. continue
  819. # If this is a copy-on-write image, then the backing file
  820. # represents the base image
  821. #
  822. # backing file: base.qcow2 (actual path: /var/shared/base.qcow2)
  823. elif line.startswith('backing file'):
  824. matches = re.match(r'.*\(actual path: (.*?)\)', line)
  825. if matches:
  826. output.append('backing file: {0}'.format(matches.group(1)))
  827. continue
  828. elif snapshots:
  829. if line.startswith('ID'): # Do not parse table headers
  830. line = line.replace('VM SIZE', 'VMSIZE')
  831. line = line.replace('VM CLOCK', 'TIME VMCLOCK')
  832. columns = re.split(r'\s+', line)
  833. columns = [c.lower() for c in columns]
  834. output.append('snapshots:')
  835. continue
  836. fields = re.split(r'\s+', line)
  837. for i, field in enumerate(fields):
  838. sep = ' '
  839. if i == 0:
  840. sep = '-'
  841. output.append(
  842. '{0} {1}: "{2}"'.format(
  843. sep, columns[i], field
  844. )
  845. )
  846. continue
  847. output.append(line)
  848. output = '\n'.join(output)
  849. disks[dev].update(yaml.safe_load(output))
  850. except TypeError:
  851. disks[dev].update(yaml.safe_load('image: Does not exist'))
  852. return disks
  853. def setmem(vm_, memory, config=False):
  854. '''
  855. Changes the amount of memory allocated to VM. The VM must be shutdown
  856. for this to work.
  857. memory is to be specified in MB
  858. If config is True then we ask libvirt to modify the config as well
  859. CLI Example:
  860. .. code-block:: bash
  861. salt '*' virtng.setmem myvm 768
  862. '''
  863. if vm_state(vm_) != 'shutdown':
  864. return False
  865. dom = _get_dom(vm_)
  866. # libvirt has a funny bitwise system for the flags in that the flag
  867. # to affect the "current" setting is 0, which means that to set the
  868. # current setting we have to call it a second time with just 0 set
  869. flags = libvirt.VIR_DOMAIN_MEM_MAXIMUM
  870. if config:
  871. flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG
  872. ret1 = dom.setMemoryFlags(memory * 1024, flags)
  873. ret2 = dom.setMemoryFlags(memory * 1024, libvirt.VIR_DOMAIN_AFFECT_CURRENT)
  874. # return True if both calls succeeded
  875. return ret1 == ret2 == 0
  876. def setvcpus(vm_, vcpus, config=False):
  877. '''
  878. Changes the amount of vcpus allocated to VM. The VM must be shutdown
  879. for this to work.
  880. vcpus is an int representing the number to be assigned
  881. If config is True then we ask libvirt to modify the config as well
  882. CLI Example:
  883. .. code-block:: bash
  884. salt '*' virtng.setvcpus myvm 2
  885. '''
  886. if vm_state(vm_) != 'shutdown':
  887. return False
  888. dom = _get_dom(vm_)
  889. # see notes in setmem
  890. flags = libvirt.VIR_DOMAIN_VCPU_MAXIMUM
  891. if config:
  892. flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG
  893. ret1 = dom.setVcpusFlags(vcpus, flags)
  894. ret2 = dom.setVcpusFlags(vcpus, libvirt.VIR_DOMAIN_AFFECT_CURRENT)
  895. return ret1 == ret2 == 0
  896. def freemem():
  897. '''
  898. Return an int representing the amount of memory that has not been given
  899. to virtual machines on this node
  900. CLI Example:
  901. .. code-block:: bash
  902. salt '*' virtng.freemem
  903. '''
  904. conn = __get_conn()
  905. mem = conn.getInfo()[1]
  906. # Take off just enough to sustain the hypervisor
  907. mem -= 256
  908. for vm_ in list_vms():
  909. dom = _get_dom(vm_)
  910. if dom.ID() > 0:
  911. mem -= dom.info()[2] / 1024
  912. return mem
  913. def freecpu():
  914. '''
  915. Return an int representing the number of unallocated cpus on this
  916. hypervisor
  917. CLI Example:
  918. .. code-block:: bash
  919. salt '*' virtng.freecpu
  920. '''
  921. conn = __get_conn()
  922. cpus = conn.getInfo()[2]
  923. for vm_ in list_vms():
  924. dom = _get_dom(vm_)
  925. if dom.ID() > 0:
  926. cpus -= dom.info()[3]
  927. return cpus
  928. def full_info():
  929. '''
  930. Return the node_info, vm_info and freemem
  931. CLI Example:
  932. .. code-block:: bash
  933. salt '*' virtng.full_info
  934. '''
  935. return {'freecpu': freecpu(),
  936. 'freemem': freemem(),
  937. 'node_info': node_info(),
  938. 'vm_info': vm_info()}
  939. def get_xml(vm_):
  940. '''
  941. Returns the XML for a given vm
  942. CLI Example:
  943. .. code-block:: bash
  944. salt '*' virtng.get_xml <vm name>
  945. '''
  946. dom = _get_dom(vm_)
  947. return dom.XMLDesc(0)
  948. def get_profiles(hypervisor=None):
  949. '''
  950. Return the virt profiles for hypervisor.
  951. Currently there are profiles for:
  952. - nic
  953. - disk
  954. CLI Example:
  955. .. code-block:: bash
  956. salt '*' virtng.get_profiles
  957. salt '*' virtng.get_profiles hypervisor=esxi
  958. '''
  959. ret = {}
  960. if hypervisor:
  961. hypervisor = hypervisor
  962. else:
  963. hypervisor = __salt__['config.get']('libvirt:hypervisor', VIRT_DEFAULT_HYPER)
  964. virtconf = __salt__['config.get']('virt', {})
  965. for typ in ['disk', 'nic']:
  966. _func = getattr(sys.modules[__name__], '_{0}_profile'.format(typ))
  967. ret[typ] = {'default': _func('default', hypervisor)}
  968. if typ in virtconf:
  969. ret.setdefault(typ, {})
  970. for prf in virtconf[typ]:
  971. ret[typ][prf] = _func(prf, hypervisor)
  972. return ret
  973. def shutdown(vm_):
  974. '''
  975. Send a soft shutdown signal to the named vm
  976. CLI Example:
  977. .. code-block:: bash
  978. salt '*' virtng.shutdown <vm name>
  979. '''
  980. dom = _get_dom(vm_)
  981. return dom.shutdown() == 0
  982. def pause(vm_):
  983. '''
  984. Pause the named vm
  985. CLI Example:
  986. .. code-block:: bash
  987. salt '*' virtng.pause <vm name>
  988. '''
  989. dom = _get_dom(vm_)
  990. return dom.suspend() == 0
  991. def resume(vm_):
  992. '''
  993. Resume the named vm
  994. CLI Example:
  995. .. code-block:: bash
  996. salt '*' virtng.resume <vm name>
  997. '''
  998. dom = _get_dom(vm_)
  999. return dom.resume() == 0
  1000. def create(vm_):
  1001. '''
  1002. Start a defined domain
  1003. CLI Example:
  1004. .. code-block:: bash
  1005. salt '*' virtng.create <vm name>
  1006. '''
  1007. dom = _get_dom(vm_)
  1008. return dom.create() == 0
  1009. def start(vm_):
  1010. '''
  1011. Alias for the obscurely named 'create' function
  1012. CLI Example:
  1013. .. code-block:: bash
  1014. salt '*' virtng.start <vm name>
  1015. '''
  1016. return create(vm_)
  1017. def stop(vm_):
  1018. '''
  1019. Alias for the obscurely named 'destroy' function
  1020. CLI Example:
  1021. .. code-block:: bash
  1022. salt '*' virtng.stop <vm name>
  1023. '''
  1024. return destroy(vm_)
  1025. def reboot(vm_):
  1026. '''
  1027. Reboot a domain via ACPI request
  1028. CLI Example:
  1029. .. code-block:: bash
  1030. salt '*' virtng.reboot <vm name>
  1031. '''
  1032. dom = _get_dom(vm_)
  1033. # reboot has a few modes of operation, passing 0 in means the
  1034. # hypervisor will pick the best method for rebooting
  1035. return dom.reboot(0) == 0
  1036. def reset(vm_):
  1037. '''
  1038. Reset a VM by emulating the reset button on a physical machine
  1039. CLI Example:
  1040. .. code-block:: bash
  1041. salt '*' virtng.reset <vm name>
  1042. '''
  1043. dom = _get_dom(vm_)
  1044. # reset takes a flag, like reboot, but it is not yet used
  1045. # so we just pass in 0
  1046. # see: http://libvirt.org/html/libvirt-libvirt.html#virDomainReset
  1047. return dom.reset(0) == 0
  1048. def ctrl_alt_del(vm_):
  1049. '''
  1050. Sends CTRL+ALT+DEL to a VM
  1051. CLI Example:
  1052. .. code-block:: bash
  1053. salt '*' virtng.ctrl_alt_del <vm name>
  1054. '''
  1055. dom = _get_dom(vm_)
  1056. return dom.sendKey(0, 0, [29, 56, 111], 3, 0) == 0
  1057. def create_xml_str(xml):
  1058. '''
  1059. Start a domain based on the XML passed to the function
  1060. CLI Example:
  1061. .. code-block:: bash
  1062. salt '*' virtng.create_xml_str <XML in string format>
  1063. '''
  1064. conn = __get_conn()
  1065. return conn.createXML(xml, 0) is not None
  1066. def create_xml_path(path):
  1067. '''
  1068. Start a domain based on the XML-file path passed to the function
  1069. CLI Example:
  1070. .. code-block:: bash
  1071. salt '*' virtng.create_xml_path <path to XML file on the node>
  1072. '''
  1073. if not os.path.isfile(path):
  1074. return False
  1075. return create_xml_str(salt.utils.fopen(path, 'r').read())
  1076. def define_xml_str(xml):
  1077. '''
  1078. Define a domain based on the XML passed to the function
  1079. CLI Example:
  1080. .. code-block:: bash
  1081. salt '*' virtng.define_xml_str <XML in string format>
  1082. '''
  1083. conn = __get_conn()
  1084. return conn.defineXML(xml) is not None
  1085. def define_xml_path(path):
  1086. '''
  1087. Define a domain based on the XML-file path passed to the function
  1088. CLI Example:
  1089. .. code-block:: bash
  1090. salt '*' virtng.define_xml_path <path to XML file on the node>
  1091. '''
  1092. if not os.path.isfile(path):
  1093. return False
  1094. return define_xml_str(salt.utils.fopen(path, 'r').read())
  1095. def define_vol_xml_str(xml):
  1096. '''
  1097. Define a volume based on the XML passed to the function
  1098. CLI Example:
  1099. .. code-block:: bash
  1100. salt '*' virtng.define_vol_xml_str <XML in string format>
  1101. '''
  1102. poolname = __salt__['config.get']('libvirt:storagepool', 'default')
  1103. conn = __get_conn()
  1104. pool = conn.storagePoolLookupByName(str(poolname))
  1105. return pool.createXML(xml, 0) is not None
  1106. def define_vol_xml_path(path):
  1107. '''
  1108. Define a volume based on the XML-file path passed to the function
  1109. CLI Example:
  1110. .. code-block:: bash
  1111. salt '*' virtng.define_vol_xml_path <path to XML file on the node>
  1112. '''
  1113. if not os.path.isfile(path):
  1114. return False
  1115. return define_vol_xml_str(salt.utils.fopen(path, 'r').read())
  1116. def migrate_non_shared(vm_, target, ssh=False):
  1117. '''
  1118. Attempt to execute non-shared storage "all" migration
  1119. CLI Example:
  1120. .. code-block:: bash
  1121. salt '*' virtng.migrate_non_shared <vm name> <target hypervisor>
  1122. '''
  1123. cmd = _get_migrate_command() + ' --copy-storage-all ' + vm_\
  1124. + _get_target(target, ssh)
  1125. return subprocess.Popen(cmd,
  1126. shell=True,
  1127. stdout=subprocess.PIPE).communicate()[0]
  1128. def migrate_non_shared_inc(vm_, target, ssh=False):
  1129. '''
  1130. Attempt to execute non-shared storage "all" migration
  1131. CLI Example:
  1132. .. code-block:: bash
  1133. salt '*' virtng.migrate_non_shared_inc <vm name> <target hypervisor>
  1134. '''
  1135. cmd = _get_migrate_command() + ' --copy-storage-inc ' + vm_\
  1136. + _get_target(target, ssh)
  1137. return subprocess.Popen(cmd,
  1138. shell=True,
  1139. stdout=subprocess.PIPE).communicate()[0]
  1140. def migrate(vm_, target, ssh=False):
  1141. '''
  1142. Shared storage migration
  1143. CLI Example:
  1144. .. code-block:: bash
  1145. salt '*' virtng.migrate <vm name> <target hypervisor>
  1146. '''
  1147. cmd = _get_migrate_command() + ' ' + vm_\
  1148. + _get_target(target, ssh)
  1149. return subprocess.Popen(cmd,
  1150. shell=True,
  1151. stdout=subprocess.PIPE).communicate()[0]
  1152. def seed_non_shared_migrate(disks, force=False):
  1153. '''
  1154. Non shared migration requires that the disks be present on the migration
  1155. destination, pass the disks information via this function, to the
  1156. migration destination before executing the migration.
  1157. CLI Example:
  1158. .. code-block:: bash
  1159. salt '*' virtng.seed_non_shared_migrate <disks>
  1160. '''
  1161. for _, data in disks.items():
  1162. fn_ = data['file']
  1163. form = data['file format']
  1164. size = data['virtual size'].split()[1][1:]
  1165. if os.path.isfile(fn_) and not force:
  1166. # the target exists, check to see if it is compatible
  1167. pre = yaml.safe_load(subprocess.Popen('qemu-img info arch',
  1168. shell=True,
  1169. stdout=subprocess.PIPE).communicate()[0])
  1170. if pre['file format'] != data['file format']\
  1171. and pre['virtual size'] != data['virtual size']:
  1172. return False
  1173. if not os.path.isdir(os.path.dirname(fn_)):
  1174. os.makedirs(os.path.dirname(fn_))
  1175. if os.path.isfile(fn_):
  1176. os.remove(fn_)
  1177. cmd = 'qemu-img create -f ' + form + ' ' + fn_ + ' ' + size
  1178. subprocess.call(cmd, shell=True)
  1179. creds = _libvirt_creds()
  1180. cmd = 'chown ' + creds['user'] + ':' + creds['group'] + ' ' + fn_
  1181. subprocess.call(cmd, shell=True)
  1182. return True
  1183. def set_autostart(vm_, state='on'):
  1184. '''
  1185. Set the autostart flag on a VM so that the VM will start with the host
  1186. system on reboot.
  1187. CLI Example:
  1188. .. code-block:: bash
  1189. salt "*" virt.set_autostart <vm name> <on | off>
  1190. '''
  1191. dom = _get_dom(vm_)
  1192. if state == 'on':
  1193. return dom.setAutostart(1) == 0
  1194. elif state == 'off':
  1195. return dom.setAutostart(0) == 0
  1196. else:
  1197. # return False if state is set to something other then on or off
  1198. return False
  1199. def destroy(vm_):
  1200. '''
  1201. Hard power down the virtual machine, this is equivalent to pulling the
  1202. power
  1203. CLI Example:
  1204. .. code-block:: bash
  1205. salt '*' virtng.destroy <vm name>
  1206. '''
  1207. dom = _get_dom(vm_)
  1208. return dom.destroy() == 0
  1209. def undefine(vm_):
  1210. '''
  1211. Remove a defined vm, this does not purge the virtual machine image, and
  1212. this only works if the vm is powered down
  1213. CLI Example:
  1214. .. code-block:: bash
  1215. salt '*' virtng.undefine <vm name>
  1216. '''
  1217. dom = _get_dom(vm_)
  1218. return dom.undefine() == 0
  1219. def purge(vm_, dirs=False):
  1220. '''
  1221. Recursively destroy and delete a virtual machine, pass True for dir's to
  1222. also delete the directories containing the virtual machine disk images -
  1223. USE WITH EXTREME CAUTION!
  1224. CLI Example:
  1225. .. code-block:: bash
  1226. salt '*' virtng.purge <vm name>
  1227. '''
  1228. disks = get_disks(vm_)
  1229. try:
  1230. if not destroy(vm_):
  1231. return False
  1232. except libvirt.libvirtError:
  1233. # This is thrown if the machine is already shut down
  1234. pass
  1235. directories = set()
  1236. for disk in disks:
  1237. os.remove(disks[disk]['file'])
  1238. directories.add(os.path.dirname(disks[disk]['file']))
  1239. if dirs:
  1240. for dir_ in directories:
  1241. shutil.rmtree(dir_)
  1242. undefine(vm_)
  1243. return True
  1244. def virt_type():
  1245. '''
  1246. Returns the virtual machine type as a string
  1247. CLI Example:
  1248. .. code-block:: bash
  1249. salt '*' virtng.virt_type
  1250. '''
  1251. return __grains__['virtual']
  1252. def is_kvm_hyper():
  1253. '''
  1254. Returns a bool whether or not this node is a KVM hypervisor
  1255. CLI Example:
  1256. .. code-block:: bash
  1257. salt '*' virtng.is_kvm_hyper
  1258. '''
  1259. try:
  1260. if 'kvm_' not in salt.utils.fopen('/proc/modules').read():
  1261. return False
  1262. except IOError:
  1263. # No /proc/modules? Are we on Windows? Or Solaris?
  1264. return False
  1265. return 'libvirtd' in __salt__['cmd.shell'](__grains__['ps'])
  1266. def is_xen_hyper():
  1267. '''
  1268. Returns a bool whether or not this node is a XEN hypervisor
  1269. CLI Example:
  1270. .. code-block:: bash
  1271. salt '*' virtng.is_xen_hyper
  1272. '''
  1273. try:
  1274. if __grains__['virtual_subtype'] != 'Xen Dom0':
  1275. return False
  1276. except KeyError:
  1277. # virtual_subtype isn't set everywhere.
  1278. return False
  1279. try:
  1280. if 'xen_' not in salt.utils.fopen('/proc/modules').read():
  1281. return False
  1282. except IOError:
  1283. # No /proc/modules? Are we on Windows? Or Solaris?
  1284. return False
  1285. return 'libvirtd' in __salt__['cmd.shell'](__grains__['ps'])
  1286. def is_hyper():
  1287. '''
  1288. Returns a bool whether or not this node is a hypervisor of any kind
  1289. CLI Example:
  1290. .. code-block:: bash
  1291. salt '*' virtng.is_hyper
  1292. '''
  1293. try:
  1294. import libvirt # pylint: disable=import-error
  1295. except ImportError:
  1296. # not a usable hypervisor without libvirt module
  1297. return False
  1298. return is_xen_hyper() or is_kvm_hyper()
  1299. def vm_cputime(vm_=None):
  1300. '''
  1301. Return cputime used by the vms on this hyper in a
  1302. list of dicts:
  1303. .. code-block:: python
  1304. [
  1305. 'your-vm': {
  1306. 'cputime' <int>
  1307. 'cputime_percent' <int>
  1308. },
  1309. ...
  1310. ]
  1311. If you pass a VM name in as an argument then it will return info
  1312. for just the named VM, otherwise it will return all VMs.
  1313. CLI Example:
  1314. .. code-block:: bash
  1315. salt '*' virtng.vm_cputime
  1316. '''
  1317. host_cpus = __get_conn().getInfo()[2]
  1318. def _info(vm_):
  1319. dom = _get_dom(vm_)
  1320. raw = dom.info()
  1321. vcpus = int(raw[3])
  1322. cputime = int(raw[4])
  1323. cputime_percent = 0
  1324. if cputime:
  1325. # Divide by vcpus to always return a number between 0 and 100
  1326. cputime_percent = (1.0e-7 * cputime / host_cpus) / vcpus
  1327. return {
  1328. 'cputime': int(raw[4]),
  1329. 'cputime_percent': int('{0:.0f}'.format(cputime_percent))
  1330. }
  1331. info = {}
  1332. if vm_:
  1333. info[vm_] = _info(vm_)
  1334. else:
  1335. for vm_ in list_vms():
  1336. info[vm_] = _info(vm_)
  1337. return info
  1338. def vm_netstats(vm_=None):
  1339. '''
  1340. Return combined network counters used by the vms on this hyper in a
  1341. list of dicts:
  1342. .. code-block:: python
  1343. [
  1344. 'your-vm': {
  1345. 'rx_bytes' : 0,
  1346. 'rx_packets' : 0,
  1347. 'rx_errs' : 0,
  1348. 'rx_drop' : 0,
  1349. 'tx_bytes' : 0,
  1350. 'tx_packets' : 0,
  1351. 'tx_errs' : 0,
  1352. 'tx_drop' : 0
  1353. },
  1354. ...
  1355. ]
  1356. If you pass a VM name in as an argument then it will return info
  1357. for just the named VM, otherwise it will return all VMs.
  1358. CLI Example:
  1359. .. code-block:: bash
  1360. salt '*' virtng.vm_netstats
  1361. '''
  1362. def _info(vm_):
  1363. dom = _get_dom(vm_)
  1364. nics = get_nics(vm_)
  1365. ret = {
  1366. 'rx_bytes': 0,
  1367. 'rx_packets': 0,
  1368. 'rx_errs': 0,
  1369. 'rx_drop': 0,
  1370. 'tx_bytes': 0,
  1371. 'tx_packets': 0,
  1372. 'tx_errs': 0,
  1373. 'tx_drop': 0
  1374. }
  1375. for attrs in six.itervalues(nics):
  1376. if 'target' in attrs:
  1377. dev = attrs['target']
  1378. stats = dom.interfaceStats(dev)
  1379. ret['rx_bytes'] += stats[0]
  1380. ret['rx_packets'] += stats[1]
  1381. ret['rx_errs'] += stats[2]
  1382. ret['rx_drop'] += stats[3]
  1383. ret['tx_bytes'] += stats[4]
  1384. ret['tx_packets'] += stats[5]
  1385. ret['tx_errs'] += stats[6]
  1386. ret['tx_drop'] += stats[7]
  1387. return ret
  1388. info = {}
  1389. if vm_:
  1390. info[vm_] = _info(vm_)
  1391. else:
  1392. for vm_ in list_vms():
  1393. info[vm_] = _info(vm_)
  1394. return info
  1395. def vm_diskstats(vm_=None):
  1396. '''
  1397. Return disk usage counters used by the vms on this hyper in a
  1398. list of dicts:
  1399. .. code-block:: python
  1400. [
  1401. 'your-vm': {
  1402. 'rd_req' : 0,
  1403. 'rd_bytes' : 0,
  1404. 'wr_req' : 0,
  1405. 'wr_bytes' : 0,
  1406. 'errs' : 0
  1407. },
  1408. ...
  1409. ]
  1410. If you pass a VM name in as an argument then it will return info
  1411. for just the named VM, otherwise it will return all VMs.
  1412. CLI Example:
  1413. .. code-block:: bash
  1414. salt '*' virtng.vm_blockstats
  1415. '''
  1416. def get_disk_devs(vm_):
  1417. doc = minidom.parse(_StringIO(get_xml(vm_)))
  1418. disks = []
  1419. for elem in doc.getElementsByTagName('disk'):
  1420. targets = elem.getElementsByTagName('target')
  1421. target = targets[0]
  1422. disks.append(target.getAttribute('dev'))
  1423. return disks
  1424. def _info(vm_):
  1425. dom = _get_dom(vm_)
  1426. # Do not use get_disks, since it uses qemu-img and is very slow
  1427. # and unsuitable for any sort of real time statistics
  1428. disks = get_disk_devs(vm_)
  1429. ret = {'rd_req': 0,
  1430. 'rd_bytes': 0,
  1431. 'wr_req': 0,
  1432. 'wr_bytes': 0,
  1433. 'errs': 0
  1434. }
  1435. for disk in disks:
  1436. stats = dom.blockStats(disk)
  1437. ret['rd_req'] += stats[0]
  1438. ret['rd_bytes'] += stats[1]
  1439. ret['wr_req'] += stats[2]
  1440. ret['wr_bytes'] += stats[3]
  1441. ret['errs'] += stats[4]
  1442. return ret
  1443. info = {}
  1444. if vm_:
  1445. info[vm_] = _info(vm_)
  1446. else:
  1447. # Can not run function blockStats on inactive VMs
  1448. for vm_ in list_active_vms():
  1449. info[vm_] = _info(vm_)
  1450. return info