New Saltstack Salt formula
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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