qubesvm.py 54 KB

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