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