New Saltstack Salt formula
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

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