qubesvm.py 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565
  1. #!/usr/bin/python2 -O
  2. # vim: fileencoding=utf-8
  3. #
  4. # The Qubes OS Project, https://www.qubes-os.org/
  5. #
  6. # Copyright (C) 2010-2015 Joanna Rutkowska <joanna@invisiblethingslab.com>
  7. # Copyright (C) 2013-2015 Marek Marczykowski-Górecki
  8. # <marmarek@invisiblethingslab.com>
  9. # Copyright (C) 2014-2015 Wojtek Porczyk <woju@invisiblethingslab.com>
  10. #
  11. # This program is free software; you can redistribute it and/or modify
  12. # it under the terms of the GNU General Public License as published by
  13. # the Free Software Foundation; either version 2 of the License, or
  14. # (at your option) any later version.
  15. #
  16. # This program is distributed in the hope that it will be useful,
  17. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. # GNU General Public License for more details.
  20. #
  21. # You should have received a copy of the GNU General Public License along
  22. # with this program; if not, write to the Free Software Foundation, Inc.,
  23. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  24. #
  25. from __future__ import absolute_import
  26. import copy
  27. import base64
  28. import datetime
  29. import itertools
  30. import os
  31. import os.path
  32. import re
  33. import shutil
  34. import subprocess
  35. import sys
  36. import time
  37. import uuid
  38. import warnings
  39. import lxml
  40. import libvirt # pylint: disable=import-error
  41. import qubes
  42. import qubes.config
  43. import qubes.exc
  44. import qubes.storage
  45. import qubes.storage.domain
  46. import qubes.storage.file
  47. import qubes.tools.qvm_ls
  48. import qubes.utils
  49. import qubes.vm
  50. import qubes.vm.mix.net
  51. qmemman_present = False
  52. try:
  53. import qubes.qmemman.client # pylint: disable=wrong-import-position
  54. qmemman_present = True
  55. except ImportError:
  56. pass
  57. MEM_OVERHEAD_BASE = (3 + 1) * 1024 * 1024
  58. MEM_OVERHEAD_PER_VCPU = 3 * 1024 * 1024 / 2
  59. def _setter_qid(self, prop, value):
  60. ''' Helper for setting the domain qid '''
  61. # pylint: disable=unused-argument
  62. value = int(value)
  63. if not 0 <= value <= qubes.config.max_qid:
  64. raise ValueError(
  65. '{} value must be between 0 and qubes.config.max_qid'.format(
  66. prop.__name__))
  67. return value
  68. def _setter_name(self, prop, value):
  69. ''' Helper for setting the domain name '''
  70. if not isinstance(value, basestring):
  71. raise TypeError('{} value must be string, {!r} found'.format(
  72. prop.__name__, type(value).__name__))
  73. if len(value) > 31:
  74. raise ValueError('{} value must be shorter than 32 characters'.format(
  75. prop.__name__))
  76. # this regexp does not contain '+'; if it had it, we should specifically
  77. # disallow 'lost+found' #1440
  78. if re.match(r"^[a-zA-Z][a-zA-Z0-9_-]*$", value) is None:
  79. raise ValueError('{} value contains illegal characters'.format(
  80. prop.__name__))
  81. if self.is_running():
  82. raise qubes.exc.QubesVMNotHaltedError(
  83. self, 'Cannot change name of running VM')
  84. try:
  85. if self.installed_by_rpm:
  86. raise qubes.exc.QubesException('Cannot rename VM installed by RPM '
  87. '-- first clone VM and then use yum to remove package.')
  88. except AttributeError:
  89. pass
  90. if value in self.app.domains:
  91. raise qubes.exc.QubesValueError(
  92. 'VM named {} alread exists'.format(value))
  93. return value
  94. def _setter_kernel(self, prop, value):
  95. ''' Helper for setting the domain kernel and running sanity checks on it.
  96. ''' # pylint: disable=unused-argument
  97. if value is None:
  98. return value
  99. value = str(value)
  100. dirname = os.path.join(
  101. qubes.config.system_path['qubes_base_dir'],
  102. qubes.config.system_path['qubes_kernels_base_dir'],
  103. value)
  104. if not os.path.exists(dirname):
  105. raise qubes.exc.QubesPropertyValueError(self, prop, value,
  106. 'Kernel {!r} not installed'.format(value))
  107. for filename in ('vmlinuz', 'initramfs'):
  108. if not os.path.exists(os.path.join(dirname, filename)):
  109. raise qubes.exc.QubesPropertyValueError(self, prop, value,
  110. 'Kernel {!r} not properly installed: missing {!r} file'.format(
  111. value, filename))
  112. return value
  113. def _setter_label(self, prop, value):
  114. ''' Helper for setting the domain label '''
  115. # pylint: disable=unused-argument
  116. if isinstance(value, qubes.Label):
  117. return value
  118. if isinstance(value, basestring) and value.startswith('label-'):
  119. return self.app.labels[int(value.split('-', 1)[1])]
  120. return self.app.get_label(value)
  121. def _setter_positive_int(self, prop, value):
  122. ''' Helper for setting a positive int. Checks that the int is >= 0 '''
  123. # pylint: disable=unused-argument
  124. value = int(value)
  125. if value <= 0:
  126. raise ValueError('Value must be positive')
  127. return value
  128. class QubesVM(qubes.vm.mix.net.NetVMMixin, qubes.vm.BaseVM):
  129. '''Base functionality of Qubes VM shared between all VMs.'''
  130. #
  131. # per-class properties
  132. #
  133. #: directory in which domains of this class will reside
  134. dir_path_prefix = qubes.config.system_path['qubes_appvms_dir']
  135. #
  136. # properties loaded from XML
  137. #
  138. label = qubes.property('label',
  139. setter=_setter_label,
  140. saver=(lambda self, prop, value: 'label-{}'.format(value.index)),
  141. ls_width=14,
  142. doc='''Colourful label assigned to VM. This is where the colour of the
  143. padlock is set.''')
  144. # provides_network = qubes.property('provides_network',
  145. # type=bool, setter=qubes.property.bool,
  146. # doc='`True` if it is NetVM or ProxyVM, false otherwise.')
  147. qid = qubes.property('qid', type=int, write_once=True,
  148. setter=_setter_qid,
  149. clone=False,
  150. ls_width=3,
  151. doc='''Internal, persistent identificator of particular domain. Note
  152. this is different from Xen domid.''')
  153. name = qubes.property('name', type=str,
  154. clone=False,
  155. ls_width=31,
  156. doc='User-specified name of the domain.')
  157. uuid = qubes.property('uuid', type=uuid.UUID, write_once=True,
  158. clone=False,
  159. ls_width=36,
  160. doc='UUID from libvirt.')
  161. hvm = qubes.property('hvm',
  162. type=bool, setter=qubes.property.bool,
  163. default=False,
  164. doc='''Use full virtualisation (HVM) for this qube,
  165. instead of paravirtualisation (PV)''')
  166. # SEE: 1815 this should be part of qubes.xml
  167. firewall_conf = qubes.property('firewall_conf', type=str,
  168. default='firewall.xml')
  169. installed_by_rpm = qubes.property('installed_by_rpm',
  170. type=bool, setter=qubes.property.bool,
  171. default=False,
  172. doc='''If this domain's image was installed from package tracked by
  173. package manager.''')
  174. memory = qubes.property('memory', type=int,
  175. setter=_setter_positive_int,
  176. default=(lambda self:
  177. qubes.config.defaults['hvm_memory' if self.hvm else 'memory']),
  178. doc='Memory currently available for this VM.')
  179. maxmem = qubes.property('maxmem', type=int,
  180. setter=_setter_positive_int,
  181. default=(lambda self: min(self.app.host.memory_total / 1024 / 2, 4000)),
  182. doc='''Maximum amount of memory available for this VM (for the purpose
  183. of the memory balancer).''')
  184. internal = qubes.property('internal', default=False,
  185. type=bool, setter=qubes.property.bool,
  186. doc='''Internal VM (not shown in qubes-manager, don't create appmenus
  187. entries.''')
  188. vcpus = qubes.property('vcpus',
  189. type=int,
  190. setter=_setter_positive_int,
  191. default=(lambda self: self.app.host.no_cpus),
  192. ls_width=2,
  193. doc='FIXME')
  194. pool_name = qubes.property('pool_name',
  195. default='default',
  196. doc='storage pool for this qube devices')
  197. # CORE2: swallowed uses_default_kernel
  198. kernel = qubes.property('kernel', type=str,
  199. setter=_setter_kernel,
  200. default=(lambda self: self.app.default_kernel),
  201. ls_width=12,
  202. doc='Kernel used by this domain.')
  203. # CORE2: swallowed uses_default_kernelopts
  204. kernelopts = qubes.property('kernelopts', type=str, load_stage=4,
  205. default=(lambda self: qubes.config.defaults['kernelopts_pcidevs']
  206. if list(self.devices['pci'].attached(persistent=True))
  207. else self.template.kernelopts if hasattr(self, 'template')
  208. else qubes.config.defaults['kernelopts']),
  209. ls_width=30,
  210. doc='Kernel command line passed to domain.')
  211. debug = qubes.property('debug', type=bool, default=False,
  212. setter=qubes.property.bool,
  213. doc='Turns on debugging features.')
  214. # XXX what this exactly does?
  215. # XXX shouldn't this go to standalone VM and TemplateVM, and leave here
  216. # only plain property?
  217. default_user = qubes.property('default_user', type=str,
  218. default=(lambda self: self.template.default_user
  219. if hasattr(self, 'template') else 'user'),
  220. ls_width=12,
  221. doc='FIXME')
  222. # @property
  223. # def default_user(self):
  224. # if self.template is not None:
  225. # return self.template.default_user
  226. # else:
  227. # return self._default_user
  228. qrexec_timeout = qubes.property('qrexec_timeout', type=int, default=60,
  229. setter=_setter_positive_int,
  230. ls_width=3,
  231. doc='''Time in seconds after which qrexec connection attempt is deemed
  232. failed. Operating system inside VM should be able to boot in this
  233. time.''')
  234. autostart = qubes.property('autostart', default=False,
  235. type=bool, setter=qubes.property.bool,
  236. doc='''Setting this to `True` means that VM should be autostarted on
  237. dom0 boot.''')
  238. include_in_backups = qubes.property('include_in_backups',
  239. default=(lambda self: not self.internal),
  240. type=bool, setter=qubes.property.bool,
  241. doc='If this domain is to be included in default backup.')
  242. # format got changed from %s to str(datetime.datetime)
  243. backup_timestamp = qubes.property('backup_timestamp', default=None,
  244. setter=(lambda self, prop, value:
  245. value if isinstance(value, datetime.datetime) else
  246. datetime.datetime.fromtimestamp(int(value))),
  247. saver=(lambda self, prop, value: value.strftime('%s')),
  248. doc='FIXME')
  249. default_dispvm = qubes.VMProperty('default_dispvm',
  250. load_stage=4,
  251. allow_none=True,
  252. default=(lambda self: self.app.default_dispvm),
  253. doc='Default VM to be used as Disposable VM for service calls.')
  254. #
  255. # static, class-wide properties
  256. #
  257. #
  258. # properties not loaded from XML, calculated at run-time
  259. #
  260. def __str__(self):
  261. return self.name
  262. # VMM-related
  263. @qubes.tools.qvm_ls.column(width=3)
  264. @property
  265. def xid(self):
  266. '''Xen ID.
  267. Or not Xen, but ID.
  268. '''
  269. if self.libvirt_domain is None:
  270. return -1
  271. try:
  272. return self.libvirt_domain.ID()
  273. except libvirt.libvirtError as e:
  274. if e.get_error_code() == libvirt.VIR_ERR_NO_DOMAIN:
  275. return -1
  276. else:
  277. self.log.exception('libvirt error code: {!r}'.format(
  278. e.get_error_code()))
  279. raise
  280. @property
  281. def attached_volumes(self):
  282. result = []
  283. xml_desc = self.libvirt_domain.XMLDesc()
  284. xml = lxml.etree.fromstring(xml_desc)
  285. for disk in xml.xpath("//domain/devices/disk"):
  286. if disk.find('backenddomain') is not None:
  287. pool_name = 'p_%s' % disk.find('backenddomain').get('name')
  288. pool = self.app.pools[pool_name]
  289. vid = disk.find('source').get('dev').split('/dev/')[1]
  290. for volume in pool.volumes:
  291. if volume.vid == vid:
  292. result += [volume]
  293. break
  294. return result + self.volumes.values()
  295. @property
  296. def libvirt_domain(self):
  297. '''Libvirt domain object from libvirt.
  298. May be :py:obj:`None`, if libvirt knows nothing about this domain.
  299. '''
  300. if self._libvirt_domain is not None:
  301. return self._libvirt_domain
  302. # XXX _update_libvirt_domain?
  303. try:
  304. self._libvirt_domain = self.app.vmm.libvirt_conn.lookupByUUID(
  305. self.uuid.bytes)
  306. except libvirt.libvirtError as e:
  307. if e.get_error_code() == libvirt.VIR_ERR_NO_DOMAIN:
  308. self._update_libvirt_domain()
  309. else:
  310. raise
  311. return self._libvirt_domain
  312. @property
  313. def block_devices(self):
  314. ''' Return all :py:class:`qubes.devices.BlockDevice`s for current domain
  315. for serialization in the libvirt XML template as <disk>.
  316. '''
  317. return [v.block_device() for v in self.volumes.values()]
  318. @property
  319. def qdb(self):
  320. '''QubesDB handle for this domain.'''
  321. if self._qdb_connection is None:
  322. if self.is_running():
  323. import qubesdb # pylint: disable=import-error
  324. self._qdb_connection = qubesdb.QubesDB(self.name)
  325. return self._qdb_connection
  326. # XXX shouldn't this go elsewhere?
  327. @property
  328. def updateable(self):
  329. '''True if this machine may be updated on its own.'''
  330. return not hasattr(self, 'template')
  331. @property
  332. def dir_path(self):
  333. '''Root directory for files related to this domain'''
  334. return os.path.join(
  335. qubes.config.system_path['qubes_base_dir'],
  336. self.dir_path_prefix,
  337. self.name)
  338. @property
  339. def icon_path(self):
  340. return os.path.join(self.dir_path, 'icon.png')
  341. @property
  342. def conf_file(self):
  343. return os.path.join(self.dir_path, 'libvirt.xml')
  344. # network-related
  345. #
  346. # constructor
  347. #
  348. def __init__(self, app, xml, volume_config=None, **kwargs):
  349. super(QubesVM, self).__init__(app, xml, **kwargs)
  350. self.volumes = {}
  351. self.storage = None
  352. if volume_config is None:
  353. volume_config = {}
  354. if hasattr(self, 'volume_config'):
  355. if xml is not None:
  356. for node in xml.xpath('volume-config/volume'):
  357. name = node.get('name')
  358. assert name
  359. for key, value in node.items():
  360. # pylint: disable=no-member
  361. if value == 'True':
  362. self.volume_config[name][key] = True
  363. else:
  364. self.volume_config[name][key] = value
  365. for name, conf in volume_config.items():
  366. for key, value in conf.items():
  367. # pylint: disable=no-member
  368. self.volume_config[name][key] = value
  369. elif volume_config:
  370. raise TypeError(
  371. 'volume_config specified, but {} did not expect that.'.format(
  372. self.__class__.__name__))
  373. # Init private attrs
  374. self._libvirt_domain = None
  375. self._qdb_connection = None
  376. if xml is None:
  377. # we are creating new VM and attributes came through kwargs
  378. assert hasattr(self, 'qid')
  379. assert hasattr(self, 'name')
  380. # Linux specific cap: max memory can't scale beyond 10.79*init_mem
  381. # see https://groups.google.com/forum/#!topic/qubes-devel/VRqkFj1IOtA
  382. if self.maxmem > self.memory * 10:
  383. self.maxmem = self.memory * 10
  384. # By default allow use all VCPUs
  385. # if not hasattr(self, 'vcpus') and not self.app.vmm.offline_mode:
  386. # self.vcpus = self.app.host.no_cpus
  387. if xml is None:
  388. # new qube, disable updates check if requested for new qubes
  389. # SEE: 1637 when features are done, migrate to plugin
  390. if not self.app.check_updates_vm:
  391. self.features['check-updates'] = None
  392. # will be initialized after loading all the properties
  393. # fire hooks
  394. if xml is None:
  395. self.events_enabled = True
  396. self.fire_event('domain-init')
  397. def __hash__(self):
  398. return self.qid
  399. def __xml__(self):
  400. element = super(QubesVM, self).__xml__()
  401. if hasattr(self, 'volumes'):
  402. volume_config_node = lxml.etree.Element('volume-config')
  403. for volume in self.volumes.values():
  404. volume_config_node.append(volume.__xml__())
  405. element.append(volume_config_node)
  406. return element
  407. #
  408. # event handlers
  409. #
  410. @qubes.events.handler('domain-init', 'domain-load')
  411. def on_domain_init_loaded(self, event):
  412. # pylint: disable=unused-argument
  413. if not hasattr(self, 'uuid'):
  414. self.uuid = uuid.uuid4()
  415. # Initialize VM image storage class
  416. self.storage = qubes.storage.Storage(self)
  417. vm_pool = qubes.storage.domain.DomainPool(self)
  418. self.app.pools[vm_pool.name] = vm_pool
  419. @qubes.events.handler('property-set:label')
  420. def on_property_set_label(self, event, name, new_label, old_label=None):
  421. # pylint: disable=unused-argument
  422. if self.icon_path:
  423. try:
  424. os.remove(self.icon_path)
  425. except OSError:
  426. pass
  427. if hasattr(os, "symlink"):
  428. os.symlink(new_label.icon_path, self.icon_path)
  429. subprocess.call(['sudo', 'xdg-icon-resource', 'forceupdate'])
  430. else:
  431. shutil.copy(new_label.icon_path, self.icon_path)
  432. @qubes.events.handler('property-pre-set:name')
  433. def on_property_pre_set_name(self, event, name, newvalue, oldvalue=None):
  434. # pylint: disable=unused-argument
  435. try:
  436. self.app.domains[newvalue]
  437. except KeyError:
  438. pass
  439. else:
  440. raise qubes.exc.QubesValueError(
  441. 'VM named {!r} already exists'.format(newvalue))
  442. # TODO not self.is_stopped() would be more appropriate
  443. if self.is_running():
  444. raise qubes.exc.QubesVMNotHaltedError(
  445. 'Cannot change name of running domain {!r}'.format(oldvalue))
  446. if self.autostart:
  447. subprocess.check_call(['sudo', 'systemctl', '-q', 'disable',
  448. 'qubes-vm@{}.service'.format(oldvalue)])
  449. @qubes.events.handler('property-set:name')
  450. def on_property_set_name(self, event, name, new_name, old_name=None):
  451. # pylint: disable=unused-argument
  452. self.init_log()
  453. self.storage.rename(old_name, new_name)
  454. if self._libvirt_domain is not None:
  455. self.libvirt_domain.undefine()
  456. self._libvirt_domain = None
  457. if self._qdb_connection is not None:
  458. self._qdb_connection.close()
  459. self._qdb_connection = None
  460. self._update_libvirt_domain()
  461. if self.autostart:
  462. self.autostart = self.autostart
  463. @qubes.events.handler('property-pre-set:autostart')
  464. def on_property_pre_set_autostart(self, event, prop, value,
  465. oldvalue=None):
  466. # pylint: disable=unused-argument
  467. # workaround https://bugzilla.redhat.com/show_bug.cgi?id=1181922
  468. if value:
  469. retcode = subprocess.call(
  470. ["sudo", "ln", "-sf",
  471. "/usr/lib/systemd/system/qubes-vm@.service",
  472. "/etc/systemd/system/multi-user.target.wants/qubes-vm@{"
  473. "}.service".format(self.name)])
  474. else:
  475. retcode = subprocess.call(
  476. ['sudo', 'systemctl', 'disable',
  477. 'qubes-vm@{}.service'.format(self.name)])
  478. if retcode:
  479. raise qubes.exc.QubesException(
  480. 'Failed to set autostart for VM in systemd')
  481. @qubes.events.handler('property-pre-del:autostart')
  482. def on_property_pre_del_autostart(self, event, prop, oldvalue=None):
  483. # pylint: disable=unused-argument
  484. if oldvalue:
  485. retcode = subprocess.call(
  486. ['sudo', 'systemctl', 'disable',
  487. 'qubes-vm@{}.service'.format(self.name)])
  488. if retcode:
  489. raise qubes.exc.QubesException(
  490. 'Failed to reset autostart for VM in systemd')
  491. #
  492. # methods for changing domain state
  493. #
  494. def start(self, preparing_dvm=False, start_guid=True,
  495. notify_function=None, mem_required=None):
  496. '''Start domain
  497. :param bool preparing_dvm: FIXME
  498. :param bool start_guid: FIXME
  499. :param collections.Callable notify_function: FIXME
  500. :param int mem_required: FIXME
  501. '''
  502. # Intentionally not used is_running(): eliminate also "Paused",
  503. # "Crashed", "Halting"
  504. if self.get_power_state() != 'Halted':
  505. raise qubes.exc.QubesVMNotHaltedError(self)
  506. self.log.info('Starting {}'.format(self.name))
  507. self.fire_event_pre('domain-pre-start', preparing_dvm=preparing_dvm,
  508. start_guid=start_guid, mem_required=mem_required)
  509. self.storage.verify()
  510. if self.netvm is not None:
  511. # pylint: disable = no-member
  512. if self.netvm.qid != 0:
  513. if not self.netvm.is_running():
  514. self.netvm.start(start_guid=start_guid,
  515. notify_function=notify_function)
  516. self.storage.start()
  517. self._update_libvirt_domain()
  518. qmemman_client = self.request_memory(mem_required)
  519. self.libvirt_domain.createWithFlags(libvirt.VIR_DOMAIN_START_PAUSED)
  520. try:
  521. self.fire_event('domain-spawn',
  522. preparing_dvm=preparing_dvm, start_guid=start_guid)
  523. self.log.info('Setting Qubes DB info for the VM')
  524. self.start_qubesdb()
  525. self.create_qdb_entries()
  526. if preparing_dvm:
  527. self.qdb.write('/dvm', '1')
  528. self.log.warning('Activating the {} VM'.format(self.name))
  529. self.libvirt_domain.resume()
  530. # close() is not really needed, because the descriptor is
  531. # close-on-exec anyway, the reason to postpone close() is that
  532. # possibly xl is not done constructing the domain after its main
  533. # process exits so we close() when we know the domain is up the
  534. # successful unpause is some indicator of it
  535. if qmemman_client:
  536. qmemman_client.close()
  537. # if self._start_guid_first and start_guid and not preparing_dvm \
  538. # and os.path.exists('/var/run/shm.id'):
  539. # self.start_guid()
  540. if not preparing_dvm:
  541. self.start_qrexec_daemon()
  542. self.fire_event('domain-start',
  543. preparing_dvm=preparing_dvm, start_guid=start_guid)
  544. except: # pylint: disable=bare-except
  545. if self.is_running() or self.is_paused():
  546. # This avoids losing the exception if an exception is raised in
  547. # self.force_shutdown(), because the vm is not running or paused
  548. self.force_shutdown()
  549. raise
  550. return self
  551. def shutdown(self, force=False, wait=False):
  552. '''Shutdown domain.
  553. :raises qubes.exc.QubesVMNotStartedError: \
  554. when domain is already shut down.
  555. '''
  556. if self.is_halted():
  557. raise qubes.exc.QubesVMNotStartedError(self)
  558. self.fire_event_pre('domain-pre-shutdown', force=force)
  559. self.libvirt_domain.shutdown()
  560. self.storage.stop()
  561. while wait and not self.is_halted():
  562. time.sleep(0.25)
  563. return self
  564. def kill(self):
  565. '''Forcefuly shutdown (destroy) domain.
  566. :raises qubes.exc.QubesVMNotStartedError: \
  567. when domain is already shut down.
  568. '''
  569. if not self.is_running() and not self.is_paused():
  570. raise qubes.exc.QubesVMNotStartedError(self)
  571. self.libvirt_domain.destroy()
  572. self.storage.stop()
  573. return self
  574. def force_shutdown(self, *args, **kwargs):
  575. '''Deprecated alias for :py:meth:`kill`'''
  576. warnings.warn(
  577. 'Call to deprecated function force_shutdown(), use kill() instead',
  578. DeprecationWarning, stacklevel=2)
  579. self.kill(*args, **kwargs)
  580. return self
  581. def suspend(self):
  582. '''Suspend (pause) domain.
  583. :raises qubes.exc.QubesVMNotRunnignError: \
  584. when domain is already shut down.
  585. :raises qubes.exc.QubesNotImplemetedError: \
  586. when domain has PCI devices attached.
  587. '''
  588. if not self.is_running() and not self.is_paused():
  589. raise qubes.exc.QubesVMNotRunningError(self)
  590. if list(self.devices['pci'].attached()):
  591. raise qubes.exc.QubesNotImplementedError(
  592. 'Cannot suspend domain {!r} which has PCI devices attached'
  593. .format(self.name))
  594. else:
  595. self.libvirt_domain.suspend()
  596. return self
  597. def pause(self):
  598. '''Pause (suspend) domain. This currently delegates to \
  599. :py:meth:`suspend`.'''
  600. if not self.is_running():
  601. raise qubes.exc.QubesVMNotRunningError(self)
  602. self.suspend()
  603. return self
  604. def resume(self):
  605. '''Resume suspended domain.
  606. :raises qubes.exc.QubesVMNotSuspendedError: when machine is not paused
  607. :raises qubes.exc.QubesVMError: when machine is suspended
  608. '''
  609. if self.get_power_state() == "Suspended":
  610. raise qubes.exc.QubesVMError(self,
  611. 'Cannot resume suspended domain {!r}'.format(self.name))
  612. else:
  613. self.unpause()
  614. return self
  615. def unpause(self):
  616. '''Resume (unpause) a domain'''
  617. if not self.is_paused():
  618. raise qubes.exc.QubesVMNotPausedError(self)
  619. self.libvirt_domain.resume()
  620. return self
  621. def run(self, command, user=None, autostart=False, notify_function=None,
  622. passio=False, passio_popen=False, passio_stderr=False,
  623. ignore_stderr=False, localcmd=None, wait=False, gui=True,
  624. filter_esc=False):
  625. '''Run specified command inside domain
  626. :param str command: the command to be run
  627. :param str user: user to run the command as
  628. :param bool autostart: if :py:obj:`True`, machine will be started if \
  629. it is not running
  630. :param collections.Callable notify_function: FIXME, may go away
  631. :param bool passio: FIXME
  632. :param bool passio_popen: if :py:obj:`True`, \
  633. :py:class:`subprocess.Popen` object has connected ``stdin`` and \
  634. ``stdout``
  635. :param bool passio_stderr: if :py:obj:`True`, \
  636. :py:class:`subprocess.Popen` has additionaly ``stderr`` connected
  637. :param bool ignore_stderr: if :py:obj:`True`, ``stderr`` is connected \
  638. to :file:`/dev/null`
  639. :param str localcmd: local command to communicate with remote command
  640. :param bool wait: if :py:obj:`True`, wait for command completion
  641. :param bool gui: when autostarting, also start gui daemon
  642. :param bool filter_esc: filter escape sequences to protect terminal \
  643. emulator
  644. '''
  645. if user is None:
  646. user = self.default_user
  647. null = None
  648. if not self.is_running() and not self.is_paused():
  649. if not autostart:
  650. raise qubes.exc.QubesVMNotRunningError(self)
  651. if notify_function is not None:
  652. notify_function('info',
  653. 'Starting the {!r} VM...'.format(self.name))
  654. self.start(start_guid=gui, notify_function=notify_function)
  655. if self.is_paused():
  656. # XXX what about autostart?
  657. raise qubes.exc.QubesVMNotRunningError(
  658. self, 'Domain {!r} is paused'.format(self.name))
  659. if not self.is_qrexec_running():
  660. raise qubes.exc.QubesVMError(
  661. self, 'Domain {!r}: qrexec not connected'.format(self.name))
  662. self.fire_event_pre('domain-cmd-pre-run', start_guid=gui)
  663. args = [qubes.config.system_path['qrexec_client_path'],
  664. '-d', str(self.name),
  665. '{}:{}'.format(user, command)]
  666. if localcmd is not None:
  667. args += ['-l', localcmd]
  668. if filter_esc:
  669. args += ['-t']
  670. if os.isatty(sys.stderr.fileno()):
  671. args += ['-T']
  672. call_kwargs = {}
  673. if ignore_stderr or not passio:
  674. null = open("/dev/null", "r+")
  675. call_kwargs['stderr'] = null
  676. if not passio:
  677. call_kwargs['stdin'] = null
  678. call_kwargs['stdout'] = null
  679. if passio_popen:
  680. popen_kwargs = {
  681. 'stdout': subprocess.PIPE,
  682. 'stdin': subprocess.PIPE
  683. }
  684. if passio_stderr:
  685. popen_kwargs['stderr'] = subprocess.PIPE
  686. else:
  687. popen_kwargs['stderr'] = call_kwargs.get('stderr', None)
  688. p = subprocess.Popen(args, **popen_kwargs)
  689. if null:
  690. null.close()
  691. return p
  692. if not wait and not passio:
  693. args += ["-e"]
  694. retcode = subprocess.call(args, **call_kwargs)
  695. if null:
  696. null.close()
  697. return retcode
  698. def run_service(self, service, source=None, user=None,
  699. passio_popen=False, input=None, localcmd=None, gui=False,
  700. wait=True, passio_stderr=False):
  701. '''Run service on this VM
  702. **passio_popen** and **input** are mutually exclusive.
  703. :param str service: service name
  704. :param qubes.vm.qubesvm.QubesVM: source domain as presented to this VM
  705. :param str user: username to run service as
  706. :param bool passio_popen: passed verbatim to :py:meth:`run`
  707. :param str input: string passed as input to service
  708. ''' # pylint: disable=redefined-builtin
  709. if len([i for i in (input, passio_popen, localcmd) if i]) > 1:
  710. raise TypeError(
  711. 'input, passio_popen and localcmd cannot be used together')
  712. if not wait and (localcmd or input):
  713. raise ValueError("Cannot use wait=False with input or "
  714. "localcmd specified")
  715. if passio_stderr and not passio_popen:
  716. raise TypeError('passio_stderr can be used only with passio_popen')
  717. if input:
  718. # Internally use passio_popen, but do not return POpen object to
  719. # the user - use internally for p.communicate()
  720. passio_popen = True
  721. passio_stderr = True
  722. source = 'dom0' if source is None else self.app.domains[source].name
  723. p = self.run('QUBESRPC {} {}'.format(service, source),
  724. localcmd=localcmd, passio_popen=passio_popen, user=user, wait=wait,
  725. gui=gui, passio_stderr=passio_stderr)
  726. if input:
  727. p.communicate(input)
  728. return p.returncode
  729. else:
  730. return p
  731. def request_memory(self, mem_required=None):
  732. # overhead of per-qube/per-vcpu Xen structures,
  733. # taken from OpenStack nova/virt/xenapi/driver.py
  734. # see https://wiki.openstack.org/wiki/XenServer/Overhead
  735. # add an extra MB because Nova rounds up to MBs
  736. if not qmemman_present:
  737. return
  738. if mem_required is None:
  739. mem_required = int(self.memory) * 1024 * 1024
  740. qmemman_client = qubes.qmemman.client.QMemmanClient()
  741. try:
  742. mem_required_with_overhead = mem_required + MEM_OVERHEAD_BASE \
  743. + self.vcpus * MEM_OVERHEAD_PER_VCPU
  744. got_memory = qmemman_client.request_memory(
  745. mem_required_with_overhead)
  746. except IOError as e:
  747. raise IOError('Failed to connect to qmemman: {!s}'.format(e))
  748. if not got_memory:
  749. qmemman_client.close()
  750. raise qubes.exc.QubesMemoryError(self)
  751. return qmemman_client
  752. def start_qrexec_daemon(self):
  753. '''Start qrexec daemon.
  754. :raises OSError: when starting fails.
  755. '''
  756. self.log.debug('Starting the qrexec daemon')
  757. qrexec_args = [str(self.xid), self.name, self.default_user]
  758. if not self.debug:
  759. qrexec_args.insert(0, "-q")
  760. qrexec_env = os.environ.copy()
  761. if not self.features.check_with_template('qrexec', not self.hvm):
  762. self.log.debug(
  763. 'Starting the qrexec daemon in background, because of features')
  764. qrexec_env['QREXEC_STARTUP_NOWAIT'] = '1'
  765. else:
  766. qrexec_env['QREXEC_STARTUP_TIMEOUT'] = str(self.qrexec_timeout)
  767. try:
  768. subprocess.check_call(
  769. [qubes.config.system_path["qrexec_daemon_path"]] + qrexec_args,
  770. env=qrexec_env)
  771. except subprocess.CalledProcessError:
  772. raise qubes.exc.QubesVMError(self, 'Cannot execute qrexec-daemon!')
  773. def start_qubesdb(self):
  774. '''Start QubesDB daemon.
  775. :raises OSError: when starting fails.
  776. '''
  777. self.log.info('Starting Qubes DB')
  778. # FIXME #1694 #1241
  779. retcode = subprocess.call([
  780. qubes.config.system_path["qubesdb_daemon_path"],
  781. str(self.xid),
  782. self.name])
  783. if retcode != 0:
  784. raise qubes.exc.QubesException('Cannot execute qubesdb-daemon')
  785. def wait_for_session(self):
  786. '''Wait until machine finished boot sequence.
  787. This is done by executing qubes RPC call that checks if dummy system
  788. service (which is started late in standard runlevel) is active.
  789. '''
  790. self.log.info('Waiting for qubes-session')
  791. # Note : User root is redefined to SYSTEM in the Windows agent code
  792. p = self.run('QUBESRPC qubes.WaitForSession none',
  793. user="root", passio_popen=True, gui=False, wait=True)
  794. p.communicate(input=self.default_user)
  795. def create_on_disk(self, pool=None, pools=None):
  796. '''Create files needed for VM.
  797. '''
  798. self.log.info('Creating directory: {0}'.format(self.dir_path))
  799. os.makedirs(self.dir_path, mode=0o775)
  800. if pool or pools:
  801. # pylint: disable=attribute-defined-outside-init
  802. self.volume_config = _patch_volume_config(self.volume_config, pool,
  803. pools)
  804. self.storage = qubes.storage.Storage(self)
  805. self.storage.create()
  806. self.log.info('Creating icon symlink: {} -> {}'.format(
  807. self.icon_path, self.label.icon_path))
  808. if hasattr(os, "symlink"):
  809. os.symlink(self.label.icon_path, self.icon_path)
  810. else:
  811. shutil.copy(self.label.icon_path, self.icon_path)
  812. # fire hooks
  813. self.fire_event('domain-create-on-disk')
  814. def remove_from_disk(self):
  815. '''Remove domain remnants from disk.'''
  816. if not self.is_halted():
  817. raise qubes.exc.QubesVMNotHaltedError(
  818. "Can't remove VM {!s}, beacuse it's in state {!r}.".format(
  819. self, self.get_power_state()))
  820. self.fire_event('domain-remove-from-disk')
  821. shutil.rmtree(self.dir_path)
  822. self.storage.remove()
  823. def clone_disk_files(self, src, pool=None, pools=None, ):
  824. '''Clone files from other vm.
  825. :param qubes.vm.qubesvm.QubesVM src: source VM
  826. '''
  827. # If the current vm name is not a part of `self.app.domains.keys()`,
  828. # then the current vm is in creation process. Calling
  829. # `self.is_halted()` at this point, would instantiate libvirt, we want
  830. # avoid that.
  831. if self.name in self.app.domains.keys() and not self.is_halted():
  832. raise qubes.exc.QubesVMNotHaltedError(
  833. self, 'Cannot clone a running domain {!r}'.format(self.name))
  834. if pool or pools:
  835. # pylint: disable=attribute-defined-outside-init
  836. self.volume_config = _patch_volume_config(self.volume_config, pool,
  837. pools)
  838. self.storage = qubes.storage.Storage(self)
  839. self.storage.clone(src)
  840. self.storage.verify()
  841. assert self.volumes != {}
  842. if src.icon_path is not None \
  843. and os.path.exists(src.dir_path) \
  844. and self.icon_path is not None:
  845. if os.path.islink(src.icon_path):
  846. icon_path = os.readlink(src.icon_path)
  847. self.log.info(
  848. 'Creating icon symlink {} -> {}'.format(
  849. self.icon_path, icon_path))
  850. os.symlink(icon_path, self.icon_path)
  851. else:
  852. self.log.info(
  853. 'Copying icon {} -> {}'.format(
  854. src.icon_path, self.icon_path))
  855. shutil.copy(src.icon_path, self.icon_path)
  856. # fire hooks
  857. self.fire_event('domain-clone-files', src)
  858. #
  859. # methods for querying domain state
  860. #
  861. # state of the machine
  862. def get_power_state(self):
  863. '''Return power state description string.
  864. Return value may be one of those:
  865. =============== ========================================================
  866. return value meaning
  867. =============== ========================================================
  868. ``'Halted'`` Machine is not active.
  869. ``'Transient'`` Machine is running, but does not have :program:`guid`
  870. or :program:`qrexec` available.
  871. ``'Running'`` Machine is ready and running.
  872. ``'Paused'`` Machine is paused (currently not available, see below).
  873. ``'Suspended'`` Machine is S3-suspended.
  874. ``'Halting'`` Machine is in process of shutting down.
  875. ``'Dying'`` Machine crashed and is unusable.
  876. ``'Crashed'`` Machine crashed and is unusable, probably because of
  877. bug in dom0.
  878. ``'NA'`` Machine is in unknown state (most likely libvirt domain
  879. is undefined).
  880. =============== ========================================================
  881. ``Paused`` state is currently unavailable because of missing code in
  882. libvirt/xen glue.
  883. FIXME: graph below may be incomplete and wrong. Click on method name to
  884. see its documentation.
  885. .. graphviz::
  886. digraph {
  887. node [fontname="sans-serif"];
  888. edge [fontname="mono"];
  889. Halted;
  890. NA;
  891. Dying;
  892. Crashed;
  893. Transient;
  894. Halting;
  895. Running;
  896. Paused [color=gray75 fontcolor=gray75];
  897. Suspended;
  898. NA -> Halted;
  899. Halted -> NA [constraint=false];
  900. Halted -> Transient
  901. [xlabel="start()" URL="#qubes.vm.qubesvm.QubesVM.start"];
  902. Transient -> Running;
  903. Running -> Halting
  904. [xlabel="shutdown()"
  905. URL="#qubes.vm.qubesvm.QubesVM.shutdown"
  906. constraint=false];
  907. Halting -> Dying -> Halted [constraint=false];
  908. /* cosmetic, invisible edges to put rank constraint */
  909. Dying -> Halting [style="invis"];
  910. Halting -> Transient [style="invis"];
  911. Running -> Halted
  912. [label="force_shutdown()"
  913. URL="#qubes.vm.qubesvm.QubesVM.force_shutdown"
  914. constraint=false];
  915. Running -> Crashed [constraint=false];
  916. Crashed -> Halted [constraint=false];
  917. Running -> Paused
  918. [label="pause()" URL="#qubes.vm.qubesvm.QubesVM.pause"
  919. color=gray75 fontcolor=gray75];
  920. Running -> Suspended
  921. [label="pause()" URL="#qubes.vm.qubesvm.QubesVM.pause"
  922. color=gray50 fontcolor=gray50];
  923. Paused -> Running
  924. [label="unpause()" URL="#qubes.vm.qubesvm.QubesVM.unpause"
  925. color=gray75 fontcolor=gray75];
  926. Suspended -> Running
  927. [label="unpause()" URL="#qubes.vm.qubesvm.QubesVM.unpause"
  928. color=gray50 fontcolor=gray50];
  929. Running -> Suspended
  930. [label="suspend()" URL="#qubes.vm.qubesvm.QubesVM.suspend"];
  931. Suspended -> Running
  932. [label="resume()" URL="#qubes.vm.qubesvm.QubesVM.resume"];
  933. { rank=source; Halted NA };
  934. { rank=same; Transient Halting };
  935. { rank=same; Crashed Dying };
  936. { rank=sink; Paused Suspended };
  937. }
  938. .. seealso::
  939. http://wiki.libvirt.org/page/VM_lifecycle
  940. Description of VM life cycle from the point of view of libvirt.
  941. https://libvirt.org/html/libvirt-libvirt-domain.html#virDomainState
  942. Libvirt's enum describing precise state of a domain.
  943. ''' # pylint: disable=too-many-return-statements
  944. libvirt_domain = self.libvirt_domain
  945. if libvirt_domain is None:
  946. return 'Halted'
  947. try:
  948. if libvirt_domain.isActive():
  949. # pylint: disable=line-too-long
  950. if libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_PAUSED:
  951. return "Paused"
  952. elif libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_CRASHED:
  953. return "Crashed"
  954. elif libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_SHUTDOWN:
  955. return "Halting"
  956. elif libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_SHUTOFF:
  957. return "Dying"
  958. elif libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_PMSUSPENDED: # nopep8
  959. return "Suspended"
  960. else:
  961. if not self.is_fully_usable():
  962. return "Transient"
  963. else:
  964. return "Running"
  965. else:
  966. return 'Halted'
  967. except libvirt.libvirtError as e:
  968. if e.get_error_code() == libvirt.VIR_ERR_NO_DOMAIN:
  969. return 'Halted'
  970. else:
  971. raise
  972. assert False
  973. def is_halted(self):
  974. ''' Check whether this domain's state is 'Halted'
  975. :returns: :py:obj:`True` if this domain is halted, \
  976. :py:obj:`False` otherwise.
  977. :rtype: bool
  978. '''
  979. return self.get_power_state() == 'Halted'
  980. def is_running(self):
  981. '''Check whether this domain is running.
  982. :returns: :py:obj:`True` if this domain is started, \
  983. :py:obj:`False` otherwise.
  984. :rtype: bool
  985. '''
  986. if self.app.vmm.offline_mode:
  987. return False
  988. # TODO context manager #1693
  989. return self.libvirt_domain and self.libvirt_domain.isActive()
  990. def is_paused(self):
  991. '''Check whether this domain is paused.
  992. :returns: :py:obj:`True` if this domain is paused, \
  993. :py:obj:`False` otherwise.
  994. :rtype: bool
  995. '''
  996. return self.libvirt_domain \
  997. and self.libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_PAUSED
  998. def is_qrexec_running(self):
  999. '''Check whether qrexec for this domain is available.
  1000. :returns: :py:obj:`True` if qrexec is running, \
  1001. :py:obj:`False` otherwise.
  1002. :rtype: bool
  1003. '''
  1004. if self.xid < 0:
  1005. return False
  1006. return os.path.exists('/var/run/qubes/qrexec.%s' % self.name)
  1007. def is_fully_usable(self):
  1008. return all(self.fire_event('domain-is-fully-usable'))
  1009. @qubes.events.handler('domain-is-fully-usable')
  1010. def on_domain_is_fully_usable(self, event):
  1011. '''Check whether domain is running and sane.
  1012. Currently this checks for running qrexec.
  1013. ''' # pylint: disable=unused-argument
  1014. # Running gui-daemon implies also VM running
  1015. if not self.is_qrexec_running():
  1016. yield False
  1017. # memory and disk
  1018. def get_mem(self):
  1019. '''Get current memory usage from VM.
  1020. :returns: Memory usage [FIXME unit].
  1021. :rtype: FIXME
  1022. '''
  1023. if self.libvirt_domain is None:
  1024. return 0
  1025. try:
  1026. if not self.libvirt_domain.isActive():
  1027. return 0
  1028. return self.libvirt_domain.info()[1]
  1029. except libvirt.libvirtError as e:
  1030. if e.get_error_code() in (
  1031. # qube no longer exists
  1032. libvirt.VIR_ERR_NO_DOMAIN,
  1033. # libxl_domain_info failed (race condition from isActive)
  1034. libvirt.VIR_ERR_INTERNAL_ERROR):
  1035. return 0
  1036. else:
  1037. self.log.exception(
  1038. 'libvirt error code: {!r}'.format(e.get_error_code()))
  1039. raise
  1040. def get_mem_static_max(self):
  1041. '''Get maximum memory available to VM.
  1042. :returns: Memory limit [FIXME unit].
  1043. :rtype: FIXME
  1044. '''
  1045. if self.libvirt_domain is None:
  1046. return 0
  1047. try:
  1048. return self.libvirt_domain.maxMemory()
  1049. except libvirt.libvirtError as e:
  1050. if e.get_error_code() in (
  1051. # qube no longer exists
  1052. libvirt.VIR_ERR_NO_DOMAIN,
  1053. # libxl_domain_info failed (race condition from isActive)
  1054. libvirt.VIR_ERR_INTERNAL_ERROR):
  1055. return 0
  1056. else:
  1057. self.log.exception(
  1058. 'libvirt error code: {!r}'.format(e.get_error_code()))
  1059. raise
  1060. def get_cputime(self):
  1061. '''Get total CPU time burned by this domain since start.
  1062. :returns: CPU time usage [FIXME unit].
  1063. :rtype: FIXME
  1064. '''
  1065. if self.libvirt_domain is None:
  1066. return 0
  1067. if self.libvirt_domain is None:
  1068. return 0
  1069. if not self.libvirt_domain.isActive():
  1070. return 0
  1071. try:
  1072. if not self.libvirt_domain.isActive():
  1073. return 0
  1074. # this does not work, because libvirt
  1075. # return self.libvirt_domain.getCPUStats(
  1076. # libvirt.VIR_NODE_CPU_STATS_ALL_CPUS, 0)[0]['cpu_time']/10**9
  1077. return self.libvirt_domain.info()[4]
  1078. except libvirt.libvirtError as e:
  1079. if e.get_error_code() in (
  1080. # qube no longer exists
  1081. libvirt.VIR_ERR_NO_DOMAIN,
  1082. # libxl_domain_info failed (race condition from isActive)
  1083. libvirt.VIR_ERR_INTERNAL_ERROR):
  1084. return 0
  1085. else:
  1086. self.log.exception(
  1087. 'libvirt error code: {!r}'.format(e.get_error_code()))
  1088. raise
  1089. # miscellanous
  1090. def get_start_time(self):
  1091. '''Tell when machine was started.
  1092. :rtype: datetime.datetime
  1093. '''
  1094. if not self.is_running():
  1095. return None
  1096. # TODO shouldn't this be qubesdb?
  1097. start_time = self.app.vmm.xs.read('',
  1098. '/vm/{}/start_time'.format(self.uuid))
  1099. if start_time != '':
  1100. return datetime.datetime.fromtimestamp(float(start_time))
  1101. else:
  1102. return None
  1103. def is_outdated(self):
  1104. '''Check whether domain needs restart to update root image from \
  1105. template.
  1106. :returns: :py:obj:`True` if is outdated, :py:obj:`False` otherwise.
  1107. :rtype: bool
  1108. '''
  1109. # pylint: disable=no-member
  1110. # Makes sense only on VM based on template
  1111. if self.template is None:
  1112. return False
  1113. if not self.is_running():
  1114. return False
  1115. if not hasattr(self.template, 'rootcow_img'):
  1116. return False
  1117. rootimg_inode = os.stat(self.template.root_img)
  1118. try:
  1119. rootcow_inode = os.stat(self.template.rootcow_img)
  1120. except OSError:
  1121. # The only case when rootcow_img doesn't exists is in the middle of
  1122. # commit_changes, so VM is outdated right now
  1123. return True
  1124. current_dmdev = "/dev/mapper/snapshot-{0:x}:{1}-{2:x}:{3}".format(
  1125. rootimg_inode[2], rootimg_inode[1],
  1126. rootcow_inode[2], rootcow_inode[1])
  1127. # FIXME
  1128. # 51712 (0xCA00) is xvda
  1129. # backend node name not available through xenapi :(
  1130. used_dmdev = self.app.vmm.xs.read('',
  1131. '/local/domain/0/backend/vbd/{}/51712/node'.format(self.xid))
  1132. return used_dmdev != current_dmdev
  1133. #
  1134. # helper methods
  1135. #
  1136. def relative_path(self, path):
  1137. '''Return path relative to py:attr:`dir_path`.
  1138. :param str path: Path in question.
  1139. :returns: Relative path.
  1140. '''
  1141. return os.path.relpath(path, self.dir_path)
  1142. def create_qdb_entries(self):
  1143. '''Create entries in Qubes DB.
  1144. '''
  1145. # pylint: disable=no-member
  1146. self.qdb.write('/name', self.name)
  1147. self.qdb.write('/type', self.__class__.__name__)
  1148. self.qdb.write('/updateable', str(self.updateable))
  1149. self.qdb.write('/persistence', 'full' if self.updateable else 'rw-only')
  1150. self.qdb.write('/debug', str(int(self.debug)))
  1151. try:
  1152. self.qdb.write('/template', self.template.name)
  1153. except AttributeError:
  1154. self.qdb.write('/template', '')
  1155. self.qdb.write('/random-seed',
  1156. base64.b64encode(qubes.utils.urandom(64)))
  1157. if self.provides_network:
  1158. self.qdb.write('/network-provider/gateway', self.gateway)
  1159. self.qdb.write('/network-provider/netmask', self.netmask)
  1160. for i, addr in zip(itertools.count(start=1), self.dns):
  1161. self.qdb.write('/network-provider/dns-{}'.format(i), addr)
  1162. if self.netvm is not None:
  1163. self.qdb.write('/network/ip', self.ip)
  1164. self.qdb.write('/network/netmask', self.netvm.netmask)
  1165. self.qdb.write('/network/gateway', self.netvm.gateway)
  1166. for i, addr in zip(itertools.count(start=1), self.dns):
  1167. self.qdb.write('/network/dns-{}'.format(i), addr)
  1168. tzname = qubes.utils.get_timezone()
  1169. if tzname:
  1170. self.qdb.write('/timezone', tzname)
  1171. for feature, value in self.features.items():
  1172. self.qdb.write('/features/{0}'.format(feature),
  1173. str(value) if value else '')
  1174. self.qdb.write('/devices/block', '')
  1175. self.qdb.write('/devices/usb', '')
  1176. # TODO: Currently the whole qmemman is quite Xen-specific, so stay with
  1177. # xenstore for it until decided otherwise
  1178. if qmemman_present:
  1179. self.app.vmm.xs.set_permissions('',
  1180. '/local/domain/{}/memory'.format(self.xid),
  1181. [{'dom': self.xid}])
  1182. self.fire_event('domain-qdb-create')
  1183. def _update_libvirt_domain(self):
  1184. '''Re-initialise :py:attr:`libvirt_domain`.'''
  1185. domain_config = self.create_config_file()
  1186. try:
  1187. self._libvirt_domain = self.app.vmm.libvirt_conn.defineXML(
  1188. domain_config)
  1189. except libvirt.libvirtError as e:
  1190. if e.get_error_code() == libvirt.VIR_ERR_OS_TYPE \
  1191. and e.get_str2() == 'hvm':
  1192. raise qubes.exc.QubesVMError(self,
  1193. 'HVM qubes are not supported on this machine. '
  1194. 'Check BIOS settings for VT-x/AMD-V extensions.')
  1195. else:
  1196. raise
  1197. #
  1198. # workshop -- those are to be reworked later
  1199. #
  1200. def get_prefmem(self):
  1201. # TODO: qmemman is still xen specific
  1202. untrusted_meminfo_key = self.app.vmm.xs.read('',
  1203. '/local/domain/{}/memory/meminfo'.format(self.xid))
  1204. if untrusted_meminfo_key is None or untrusted_meminfo_key == '':
  1205. return 0
  1206. domain = qubes.qmemman.DomainState(self.xid)
  1207. qubes.qmemman.algo.refresh_meminfo_for_domain(
  1208. domain, untrusted_meminfo_key)
  1209. domain.memory_maximum = self.get_mem_static_max() * 1024
  1210. return qubes.qmemman.algo.prefmem(domain) / 1024
  1211. def _clean_volume_config(config):
  1212. common_attributes = ['name', 'pool', 'size', 'internal', 'removable',
  1213. 'revisions_to_keep', 'rw', 'snap_on_start',
  1214. 'save_on_stop', 'source']
  1215. config_copy = copy.deepcopy(config)
  1216. return {k: v for k, v in config_copy.items() if k in common_attributes}
  1217. def _patch_pool_config(config, pool=None, pools=None):
  1218. assert pool is not None or pools is not None
  1219. is_saveable = 'save_on_stop' in config and config['save_on_stop']
  1220. is_resetable = not ('snap_on_start' in config and # volatile
  1221. config['snap_on_start'] and not is_saveable)
  1222. is_exportable = is_saveable or is_resetable
  1223. name = config['name']
  1224. if pool and is_exportable:
  1225. config['pool'] = str(pool)
  1226. elif pool and not is_exportable:
  1227. pass
  1228. elif pools and name in pools.keys():
  1229. if is_exportable:
  1230. config['pool'] = str(pools[name])
  1231. else:
  1232. msg = "Can't clone a snapshot volume {!s} to pool {!s} " \
  1233. .format(name, pools[name])
  1234. raise qubes.exc.QubesException(msg)
  1235. return config
  1236. def _patch_volume_config(volume_config, pool=None, pools=None):
  1237. assert not (pool and pools), \
  1238. 'You can not pass pool & pools parameter at same time'
  1239. assert pool or pools
  1240. result = {}
  1241. for name, config in volume_config.items():
  1242. # copy only the subset of volume_config key/values
  1243. dst_config = _clean_volume_config(config)
  1244. if pool is not None or pools is not None:
  1245. dst_config = _patch_pool_config(dst_config, pool, pools)
  1246. result[name] = dst_config
  1247. return result