qubesvm.py 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645
  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())
  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. @qubes.events.handler('device-pre-attach:pci')
  492. def on_device_pre_attached_pci(self, event, device):
  493. # pylint: disable=unused-argument
  494. if not os.path.exists('/sys/bus/pci/devices/0000:{}'.format(device)):
  495. raise qubes.exc.QubesException(
  496. 'Invalid PCI device: {}'.format(device))
  497. if not self.is_running():
  498. return
  499. try:
  500. self.bind_pci_to_pciback(device)
  501. self.libvirt_domain.attachDevice(
  502. self.app.env.get_template('libvirt/devices/pci.xml').render(
  503. device=device))
  504. except subprocess.CalledProcessError as e:
  505. self.log.exception('Failed to attach PCI device {!r} on the fly,'
  506. ' changes will be seen after VM restart.'.format(device), e)
  507. @qubes.events.handler('device-pre-detach:pci')
  508. def on_device_pre_detached_pci(self, event, device):
  509. # pylint: disable=unused-argument
  510. if not self.is_running():
  511. return
  512. # this cannot be converted to general API, because there is no
  513. # provision in libvirt for extracting device-side BDF; we need it for
  514. # qubes.DetachPciDevice, which unbinds driver, not to oops the kernel
  515. p = subprocess.Popen(['xl', 'pci-list', str(self.xid)],
  516. stdout=subprocess.PIPE)
  517. result = p.communicate()[0]
  518. m = re.search(r'^(\d+.\d+)\s+0000:{}$'.format(device), result,
  519. flags=re.MULTILINE)
  520. if not m:
  521. self.log.error('Device %s already detached', device)
  522. return
  523. vmdev = m.group(1)
  524. try:
  525. self.run_service('qubes.DetachPciDevice',
  526. user='root', input='00:{}'.format(vmdev))
  527. self.libvirt_domain.detachDevice(
  528. self.app.env.get_template('libvirt/devices/pci.xml').render(
  529. device=device))
  530. except (subprocess.CalledProcessError, libvirt.libvirtError) as e:
  531. self.log.exception('Failed to detach PCI device {!r} on the fly,'
  532. ' changes will be seen after VM restart.'.format(device), e)
  533. raise
  534. def bind_pci_to_pciback(self, device):
  535. '''Bind PCI device to pciback driver.
  536. :param qubes.devices.PCIDevice device: device to attach
  537. Devices should be unbound from their normal kernel drivers and bound to
  538. the dummy driver, which allows for attaching them to a domain.
  539. '''
  540. try:
  541. node = self.app.vmm.libvirt_conn.nodeDeviceLookupByName(
  542. device.libvirt_name)
  543. except libvirt.libvirtError as e:
  544. if e.get_error_code() == libvirt.VIR_ERR_NO_NODE_DEVICE:
  545. raise qubes.exc.QubesException(
  546. 'PCI device {!r} does not exist (domain {!r})'.format(
  547. device, self.name))
  548. raise
  549. try:
  550. node.dettach()
  551. except libvirt.libvirtError as e:
  552. if e.get_error_code() == libvirt.VIR_ERR_INTERNAL_ERROR:
  553. # allreaddy dettached
  554. pass
  555. else:
  556. raise
  557. #
  558. # methods for changing domain state
  559. #
  560. def start(self, preparing_dvm=False, start_guid=True,
  561. notify_function=None, mem_required=None):
  562. '''Start domain
  563. :param bool preparing_dvm: FIXME
  564. :param bool start_guid: FIXME
  565. :param collections.Callable notify_function: FIXME
  566. :param int mem_required: FIXME
  567. '''
  568. # Intentionally not used is_running(): eliminate also "Paused",
  569. # "Crashed", "Halting"
  570. if self.get_power_state() != 'Halted':
  571. raise qubes.exc.QubesVMNotHaltedError(self)
  572. self.log.info('Starting {}'.format(self.name))
  573. self.fire_event_pre('domain-pre-start', preparing_dvm=preparing_dvm,
  574. start_guid=start_guid, mem_required=mem_required)
  575. self.storage.verify()
  576. if self.netvm is not None:
  577. # pylint: disable = no-member
  578. if self.netvm.qid != 0:
  579. if not self.netvm.is_running():
  580. self.netvm.start(start_guid=start_guid,
  581. notify_function=notify_function)
  582. self.storage.start()
  583. self._update_libvirt_domain()
  584. qmemman_client = self.request_memory(mem_required)
  585. # Bind pci devices to pciback driver
  586. for pci in self.devices['pci'].attached():
  587. self.bind_pci_to_pciback(pci)
  588. self.libvirt_domain.createWithFlags(libvirt.VIR_DOMAIN_START_PAUSED)
  589. try:
  590. self.fire_event('domain-spawn',
  591. preparing_dvm=preparing_dvm, start_guid=start_guid)
  592. self.log.info('Setting Qubes DB info for the VM')
  593. self.start_qubesdb()
  594. self.create_qdb_entries()
  595. if preparing_dvm:
  596. self.qdb.write('/dvm', '1')
  597. self.log.warning('Activating the {} VM'.format(self.name))
  598. self.libvirt_domain.resume()
  599. # close() is not really needed, because the descriptor is
  600. # close-on-exec anyway, the reason to postpone close() is that
  601. # possibly xl is not done constructing the domain after its main
  602. # process exits so we close() when we know the domain is up the
  603. # successful unpause is some indicator of it
  604. if qmemman_client:
  605. qmemman_client.close()
  606. # if self._start_guid_first and start_guid and not preparing_dvm \
  607. # and os.path.exists('/var/run/shm.id'):
  608. # self.start_guid()
  609. if not preparing_dvm:
  610. self.start_qrexec_daemon()
  611. self.fire_event('domain-start',
  612. preparing_dvm=preparing_dvm, start_guid=start_guid)
  613. except: # pylint: disable=bare-except
  614. if self.is_running() or self.is_paused():
  615. # This avoids losing the exception if an exception is raised in
  616. # self.force_shutdown(), because the vm is not running or paused
  617. self.force_shutdown()
  618. raise
  619. return self
  620. def shutdown(self, force=False, wait=False):
  621. '''Shutdown domain.
  622. :raises qubes.exc.QubesVMNotStartedError: \
  623. when domain is already shut down.
  624. '''
  625. if self.is_halted():
  626. raise qubes.exc.QubesVMNotStartedError(self)
  627. self.fire_event_pre('domain-pre-shutdown', force=force)
  628. self.libvirt_domain.shutdown()
  629. self.storage.stop()
  630. while wait and not self.is_halted():
  631. time.sleep(0.25)
  632. return self
  633. def kill(self):
  634. '''Forcefuly shutdown (destroy) domain.
  635. :raises qubes.exc.QubesVMNotStartedError: \
  636. when domain is already shut down.
  637. '''
  638. if not self.is_running() and not self.is_paused():
  639. raise qubes.exc.QubesVMNotStartedError(self)
  640. self.libvirt_domain.destroy()
  641. self.storage.stop()
  642. return self
  643. def force_shutdown(self, *args, **kwargs):
  644. '''Deprecated alias for :py:meth:`kill`'''
  645. warnings.warn(
  646. 'Call to deprecated function force_shutdown(), use kill() instead',
  647. DeprecationWarning, stacklevel=2)
  648. self.kill(*args, **kwargs)
  649. return self
  650. def suspend(self):
  651. '''Suspend (pause) domain.
  652. :raises qubes.exc.QubesVMNotRunnignError: \
  653. when domain is already shut down.
  654. :raises qubes.exc.QubesNotImplemetedError: \
  655. when domain has PCI devices attached.
  656. '''
  657. if not self.is_running() and not self.is_paused():
  658. raise qubes.exc.QubesVMNotRunningError(self)
  659. if list(self.devices['pci'].attached()):
  660. raise qubes.exc.QubesNotImplementedError(
  661. 'Cannot suspend domain {!r} which has PCI devices attached'
  662. .format(self.name))
  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. passio_stderr = True
  791. source = 'dom0' if source is None else self.app.domains[source].name
  792. p = self.run('QUBESRPC {} {}'.format(service, source),
  793. localcmd=localcmd, passio_popen=passio_popen, user=user, wait=wait,
  794. gui=gui, passio_stderr=passio_stderr)
  795. if input:
  796. p.communicate(input)
  797. return p.returncode
  798. else:
  799. return p
  800. def request_memory(self, mem_required=None):
  801. # overhead of per-qube/per-vcpu Xen structures,
  802. # taken from OpenStack nova/virt/xenapi/driver.py
  803. # see https://wiki.openstack.org/wiki/XenServer/Overhead
  804. # add an extra MB because Nova rounds up to MBs
  805. if not qmemman_present:
  806. return
  807. if mem_required is None:
  808. mem_required = int(self.memory) * 1024 * 1024
  809. qmemman_client = qubes.qmemman.client.QMemmanClient()
  810. try:
  811. mem_required_with_overhead = mem_required + MEM_OVERHEAD_BASE \
  812. + self.vcpus * MEM_OVERHEAD_PER_VCPU
  813. got_memory = qmemman_client.request_memory(
  814. mem_required_with_overhead)
  815. except IOError as e:
  816. raise IOError('Failed to connect to qmemman: {!s}'.format(e))
  817. if not got_memory:
  818. qmemman_client.close()
  819. raise qubes.exc.QubesMemoryError(self)
  820. return qmemman_client
  821. def start_qrexec_daemon(self):
  822. '''Start qrexec daemon.
  823. :raises OSError: when starting fails.
  824. '''
  825. self.log.debug('Starting the qrexec daemon')
  826. qrexec_args = [str(self.xid), self.name, self.default_user]
  827. if not self.debug:
  828. qrexec_args.insert(0, "-q")
  829. qrexec_env = os.environ.copy()
  830. if not self.features.check_with_template('qrexec', not self.hvm):
  831. self.log.debug(
  832. 'Starting the qrexec daemon in background, because of features')
  833. qrexec_env['QREXEC_STARTUP_NOWAIT'] = '1'
  834. else:
  835. qrexec_env['QREXEC_STARTUP_TIMEOUT'] = str(self.qrexec_timeout)
  836. try:
  837. subprocess.check_call(
  838. [qubes.config.system_path["qrexec_daemon_path"]] + qrexec_args,
  839. env=qrexec_env)
  840. except subprocess.CalledProcessError:
  841. raise qubes.exc.QubesVMError(self, 'Cannot execute qrexec-daemon!')
  842. def start_qubesdb(self):
  843. '''Start QubesDB daemon.
  844. :raises OSError: when starting fails.
  845. '''
  846. self.log.info('Starting Qubes DB')
  847. # FIXME #1694 #1241
  848. retcode = subprocess.call([
  849. qubes.config.system_path["qubesdb_daemon_path"],
  850. str(self.xid),
  851. self.name])
  852. if retcode != 0:
  853. raise qubes.exc.QubesException('Cannot execute qubesdb-daemon')
  854. def wait_for_session(self):
  855. '''Wait until machine finished boot sequence.
  856. This is done by executing qubes RPC call that checks if dummy system
  857. service (which is started late in standard runlevel) is active.
  858. '''
  859. self.log.info('Waiting for qubes-session')
  860. # Note : User root is redefined to SYSTEM in the Windows agent code
  861. p = self.run('QUBESRPC qubes.WaitForSession none',
  862. user="root", passio_popen=True, gui=False, wait=True)
  863. p.communicate(input=self.default_user)
  864. def create_on_disk(self, pool=None, pools=None):
  865. '''Create files needed for VM.
  866. '''
  867. self.log.info('Creating directory: {0}'.format(self.dir_path))
  868. os.makedirs(self.dir_path, mode=0o775)
  869. if pool or pools:
  870. # pylint: disable=attribute-defined-outside-init
  871. self.volume_config = _patch_volume_config(self.volume_config, pool,
  872. pools)
  873. self.storage = qubes.storage.Storage(self)
  874. self.storage.create()
  875. self.log.info('Creating icon symlink: {} -> {}'.format(
  876. self.icon_path, self.label.icon_path))
  877. if hasattr(os, "symlink"):
  878. os.symlink(self.label.icon_path, self.icon_path)
  879. else:
  880. shutil.copy(self.label.icon_path, self.icon_path)
  881. # fire hooks
  882. self.fire_event('domain-create-on-disk')
  883. def remove_from_disk(self):
  884. '''Remove domain remnants from disk.'''
  885. if not self.is_halted():
  886. raise qubes.exc.QubesVMNotHaltedError(
  887. "Can't remove VM {!s}, beacuse it's in state {!r}.".format(
  888. self, self.get_power_state()))
  889. self.fire_event('domain-remove-from-disk')
  890. shutil.rmtree(self.dir_path)
  891. self.storage.remove()
  892. def clone_disk_files(self, src, pool=None, pools=None, ):
  893. '''Clone files from other vm.
  894. :param qubes.vm.qubesvm.QubesVM src: source VM
  895. '''
  896. # If the current vm name is not a part of `self.app.domains.keys()`,
  897. # then the current vm is in creation process. Calling
  898. # `self.is_halted()` at this point, would instantiate libvirt, we want
  899. # avoid that.
  900. if self.name in self.app.domains.keys() and not self.is_halted():
  901. raise qubes.exc.QubesVMNotHaltedError(
  902. self, 'Cannot clone a running domain {!r}'.format(self.name))
  903. if pool or pools:
  904. # pylint: disable=attribute-defined-outside-init
  905. self.volume_config = _patch_volume_config(self.volume_config, pool,
  906. pools)
  907. self.storage = qubes.storage.Storage(self)
  908. self.storage.clone(src)
  909. self.storage.verify()
  910. assert self.volumes != {}
  911. if src.icon_path is not None \
  912. and os.path.exists(src.dir_path) \
  913. and self.icon_path is not None:
  914. if os.path.islink(src.icon_path):
  915. icon_path = os.readlink(src.icon_path)
  916. self.log.info(
  917. 'Creating icon symlink {} -> {}'.format(
  918. self.icon_path, icon_path))
  919. os.symlink(icon_path, self.icon_path)
  920. else:
  921. self.log.info(
  922. 'Copying icon {} -> {}'.format(
  923. src.icon_path, self.icon_path))
  924. shutil.copy(src.icon_path, self.icon_path)
  925. # fire hooks
  926. self.fire_event('domain-clone-files', src)
  927. #
  928. # methods for querying domain state
  929. #
  930. # state of the machine
  931. def get_power_state(self):
  932. '''Return power state description string.
  933. Return value may be one of those:
  934. =============== ========================================================
  935. return value meaning
  936. =============== ========================================================
  937. ``'Halted'`` Machine is not active.
  938. ``'Transient'`` Machine is running, but does not have :program:`guid`
  939. or :program:`qrexec` available.
  940. ``'Running'`` Machine is ready and running.
  941. ``'Paused'`` Machine is paused (currently not available, see below).
  942. ``'Suspended'`` Machine is S3-suspended.
  943. ``'Halting'`` Machine is in process of shutting down.
  944. ``'Dying'`` Machine crashed and is unusable.
  945. ``'Crashed'`` Machine crashed and is unusable, probably because of
  946. bug in dom0.
  947. ``'NA'`` Machine is in unknown state (most likely libvirt domain
  948. is undefined).
  949. =============== ========================================================
  950. ``Paused`` state is currently unavailable because of missing code in
  951. libvirt/xen glue.
  952. FIXME: graph below may be incomplete and wrong. Click on method name to
  953. see its documentation.
  954. .. graphviz::
  955. digraph {
  956. node [fontname="sans-serif"];
  957. edge [fontname="mono"];
  958. Halted;
  959. NA;
  960. Dying;
  961. Crashed;
  962. Transient;
  963. Halting;
  964. Running;
  965. Paused [color=gray75 fontcolor=gray75];
  966. Suspended;
  967. NA -> Halted;
  968. Halted -> NA [constraint=false];
  969. Halted -> Transient
  970. [xlabel="start()" URL="#qubes.vm.qubesvm.QubesVM.start"];
  971. Transient -> Running;
  972. Running -> Halting
  973. [xlabel="shutdown()"
  974. URL="#qubes.vm.qubesvm.QubesVM.shutdown"
  975. constraint=false];
  976. Halting -> Dying -> Halted [constraint=false];
  977. /* cosmetic, invisible edges to put rank constraint */
  978. Dying -> Halting [style="invis"];
  979. Halting -> Transient [style="invis"];
  980. Running -> Halted
  981. [label="force_shutdown()"
  982. URL="#qubes.vm.qubesvm.QubesVM.force_shutdown"
  983. constraint=false];
  984. Running -> Crashed [constraint=false];
  985. Crashed -> Halted [constraint=false];
  986. Running -> Paused
  987. [label="pause()" URL="#qubes.vm.qubesvm.QubesVM.pause"
  988. color=gray75 fontcolor=gray75];
  989. Running -> Suspended
  990. [label="pause()" URL="#qubes.vm.qubesvm.QubesVM.pause"
  991. color=gray50 fontcolor=gray50];
  992. Paused -> Running
  993. [label="unpause()" URL="#qubes.vm.qubesvm.QubesVM.unpause"
  994. color=gray75 fontcolor=gray75];
  995. Suspended -> Running
  996. [label="unpause()" URL="#qubes.vm.qubesvm.QubesVM.unpause"
  997. color=gray50 fontcolor=gray50];
  998. Running -> Suspended
  999. [label="suspend()" URL="#qubes.vm.qubesvm.QubesVM.suspend"];
  1000. Suspended -> Running
  1001. [label="resume()" URL="#qubes.vm.qubesvm.QubesVM.resume"];
  1002. { rank=source; Halted NA };
  1003. { rank=same; Transient Halting };
  1004. { rank=same; Crashed Dying };
  1005. { rank=sink; Paused Suspended };
  1006. }
  1007. .. seealso::
  1008. http://wiki.libvirt.org/page/VM_lifecycle
  1009. Description of VM life cycle from the point of view of libvirt.
  1010. https://libvirt.org/html/libvirt-libvirt-domain.html#virDomainState
  1011. Libvirt's enum describing precise state of a domain.
  1012. ''' # pylint: disable=too-many-return-statements
  1013. libvirt_domain = self.libvirt_domain
  1014. if libvirt_domain is None:
  1015. return 'Halted'
  1016. try:
  1017. if libvirt_domain.isActive():
  1018. # pylint: disable=line-too-long
  1019. if libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_PAUSED:
  1020. return "Paused"
  1021. elif libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_CRASHED:
  1022. return "Crashed"
  1023. elif libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_SHUTDOWN:
  1024. return "Halting"
  1025. elif libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_SHUTOFF:
  1026. return "Dying"
  1027. elif libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_PMSUSPENDED: # nopep8
  1028. return "Suspended"
  1029. else:
  1030. if not self.is_fully_usable():
  1031. return "Transient"
  1032. else:
  1033. return "Running"
  1034. else:
  1035. return 'Halted'
  1036. except libvirt.libvirtError as e:
  1037. if e.get_error_code() == libvirt.VIR_ERR_NO_DOMAIN:
  1038. return 'Halted'
  1039. else:
  1040. raise
  1041. assert False
  1042. def is_halted(self):
  1043. ''' Check whether this domain's state is 'Halted'
  1044. :returns: :py:obj:`True` if this domain is halted, \
  1045. :py:obj:`False` otherwise.
  1046. :rtype: bool
  1047. '''
  1048. return self.get_power_state() == 'Halted'
  1049. def is_running(self):
  1050. '''Check whether this domain is running.
  1051. :returns: :py:obj:`True` if this domain is started, \
  1052. :py:obj:`False` otherwise.
  1053. :rtype: bool
  1054. '''
  1055. if self.app.vmm.offline_mode:
  1056. return False
  1057. # TODO context manager #1693
  1058. return self.libvirt_domain and self.libvirt_domain.isActive()
  1059. def is_paused(self):
  1060. '''Check whether this domain is paused.
  1061. :returns: :py:obj:`True` if this domain is paused, \
  1062. :py:obj:`False` otherwise.
  1063. :rtype: bool
  1064. '''
  1065. return self.libvirt_domain \
  1066. and self.libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_PAUSED
  1067. def is_qrexec_running(self):
  1068. '''Check whether qrexec for this domain is available.
  1069. :returns: :py:obj:`True` if qrexec is running, \
  1070. :py:obj:`False` otherwise.
  1071. :rtype: bool
  1072. '''
  1073. if self.xid < 0:
  1074. return False
  1075. return os.path.exists('/var/run/qubes/qrexec.%s' % self.name)
  1076. def is_fully_usable(self):
  1077. return all(self.fire_event('domain-is-fully-usable'))
  1078. @qubes.events.handler('domain-is-fully-usable')
  1079. def on_domain_is_fully_usable(self, event):
  1080. '''Check whether domain is running and sane.
  1081. Currently this checks for running qrexec.
  1082. ''' # pylint: disable=unused-argument
  1083. # Running gui-daemon implies also VM running
  1084. if not self.is_qrexec_running():
  1085. yield False
  1086. # memory and disk
  1087. def get_mem(self):
  1088. '''Get current memory usage from VM.
  1089. :returns: Memory usage [FIXME unit].
  1090. :rtype: FIXME
  1091. '''
  1092. if self.libvirt_domain is None:
  1093. return 0
  1094. try:
  1095. if not self.libvirt_domain.isActive():
  1096. return 0
  1097. return self.libvirt_domain.info()[1]
  1098. except libvirt.libvirtError as e:
  1099. if e.get_error_code() in (
  1100. # qube no longer exists
  1101. libvirt.VIR_ERR_NO_DOMAIN,
  1102. # libxl_domain_info failed (race condition from isActive)
  1103. libvirt.VIR_ERR_INTERNAL_ERROR):
  1104. return 0
  1105. else:
  1106. self.log.exception(
  1107. 'libvirt error code: {!r}'.format(e.get_error_code()))
  1108. raise
  1109. def get_mem_static_max(self):
  1110. '''Get maximum memory available to VM.
  1111. :returns: Memory limit [FIXME unit].
  1112. :rtype: FIXME
  1113. '''
  1114. if self.libvirt_domain is None:
  1115. return 0
  1116. try:
  1117. return self.libvirt_domain.maxMemory()
  1118. except libvirt.libvirtError as e:
  1119. if e.get_error_code() in (
  1120. # qube no longer exists
  1121. libvirt.VIR_ERR_NO_DOMAIN,
  1122. # libxl_domain_info failed (race condition from isActive)
  1123. libvirt.VIR_ERR_INTERNAL_ERROR):
  1124. return 0
  1125. else:
  1126. self.log.exception(
  1127. 'libvirt error code: {!r}'.format(e.get_error_code()))
  1128. raise
  1129. def get_cputime(self):
  1130. '''Get total CPU time burned by this domain since start.
  1131. :returns: CPU time usage [FIXME unit].
  1132. :rtype: FIXME
  1133. '''
  1134. if self.libvirt_domain is None:
  1135. return 0
  1136. if self.libvirt_domain is None:
  1137. return 0
  1138. if not self.libvirt_domain.isActive():
  1139. return 0
  1140. try:
  1141. if not self.libvirt_domain.isActive():
  1142. return 0
  1143. # this does not work, because libvirt
  1144. # return self.libvirt_domain.getCPUStats(
  1145. # libvirt.VIR_NODE_CPU_STATS_ALL_CPUS, 0)[0]['cpu_time']/10**9
  1146. return self.libvirt_domain.info()[4]
  1147. except libvirt.libvirtError as e:
  1148. if e.get_error_code() in (
  1149. # qube no longer exists
  1150. libvirt.VIR_ERR_NO_DOMAIN,
  1151. # libxl_domain_info failed (race condition from isActive)
  1152. libvirt.VIR_ERR_INTERNAL_ERROR):
  1153. return 0
  1154. else:
  1155. self.log.exception(
  1156. 'libvirt error code: {!r}'.format(e.get_error_code()))
  1157. raise
  1158. # miscellanous
  1159. def get_start_time(self):
  1160. '''Tell when machine was started.
  1161. :rtype: datetime.datetime
  1162. '''
  1163. if not self.is_running():
  1164. return None
  1165. # TODO shouldn't this be qubesdb?
  1166. start_time = self.app.vmm.xs.read('',
  1167. '/vm/{}/start_time'.format(self.uuid))
  1168. if start_time != '':
  1169. return datetime.datetime.fromtimestamp(float(start_time))
  1170. else:
  1171. return None
  1172. def is_outdated(self):
  1173. '''Check whether domain needs restart to update root image from \
  1174. template.
  1175. :returns: :py:obj:`True` if is outdated, :py:obj:`False` otherwise.
  1176. :rtype: bool
  1177. '''
  1178. # pylint: disable=no-member
  1179. # Makes sense only on VM based on template
  1180. if self.template is None:
  1181. return False
  1182. if not self.is_running():
  1183. return False
  1184. if not hasattr(self.template, 'rootcow_img'):
  1185. return False
  1186. rootimg_inode = os.stat(self.template.root_img)
  1187. try:
  1188. rootcow_inode = os.stat(self.template.rootcow_img)
  1189. except OSError:
  1190. # The only case when rootcow_img doesn't exists is in the middle of
  1191. # commit_changes, so VM is outdated right now
  1192. return True
  1193. current_dmdev = "/dev/mapper/snapshot-{0:x}:{1}-{2:x}:{3}".format(
  1194. rootimg_inode[2], rootimg_inode[1],
  1195. rootcow_inode[2], rootcow_inode[1])
  1196. # FIXME
  1197. # 51712 (0xCA00) is xvda
  1198. # backend node name not available through xenapi :(
  1199. used_dmdev = self.app.vmm.xs.read('',
  1200. '/local/domain/0/backend/vbd/{}/51712/node'.format(self.xid))
  1201. return used_dmdev != current_dmdev
  1202. #
  1203. # helper methods
  1204. #
  1205. def relative_path(self, path):
  1206. '''Return path relative to py:attr:`dir_path`.
  1207. :param str path: Path in question.
  1208. :returns: Relative path.
  1209. '''
  1210. return os.path.relpath(path, self.dir_path)
  1211. def create_qdb_entries(self):
  1212. '''Create entries in Qubes DB.
  1213. '''
  1214. # pylint: disable=no-member
  1215. self.qdb.write('/name', self.name)
  1216. self.qdb.write('/type', self.__class__.__name__)
  1217. self.qdb.write('/updateable', str(self.updateable))
  1218. self.qdb.write('/persistence', 'full' if self.updateable else 'rw-only')
  1219. self.qdb.write('/debug', str(int(self.debug)))
  1220. try:
  1221. self.qdb.write('/template', self.template.name)
  1222. except AttributeError:
  1223. self.qdb.write('/template', '')
  1224. self.qdb.write('/random-seed',
  1225. base64.b64encode(qubes.utils.urandom(64)))
  1226. if self.provides_network:
  1227. self.qdb.write('/network-provider/gateway', self.gateway)
  1228. self.qdb.write('/network-provider/netmask', self.netmask)
  1229. for i, addr in zip(itertools.count(start=1), self.dns):
  1230. self.qdb.write('/network-provider/dns-{}'.format(i), addr)
  1231. if self.netvm is not None:
  1232. self.qdb.write('/network/ip', self.ip)
  1233. self.qdb.write('/network/netmask', self.netvm.netmask)
  1234. self.qdb.write('/network/gateway', self.netvm.gateway)
  1235. for i, addr in zip(itertools.count(start=1), self.dns):
  1236. self.qdb.write('/network/dns-{}'.format(i), addr)
  1237. tzname = qubes.utils.get_timezone()
  1238. if tzname:
  1239. self.qdb.write('/timezone', tzname)
  1240. for feature, value in self.features.items():
  1241. self.qdb.write('/features/{0}'.format(feature),
  1242. str(value) if value else '')
  1243. self.qdb.write('/devices/block', '')
  1244. self.qdb.write('/devices/usb', '')
  1245. # TODO: Currently the whole qmemman is quite Xen-specific, so stay with
  1246. # xenstore for it until decided otherwise
  1247. if qmemman_present:
  1248. self.app.vmm.xs.set_permissions('',
  1249. '/local/domain/{}/memory'.format(self.xid),
  1250. [{'dom': self.xid}])
  1251. self.fire_event('domain-qdb-create')
  1252. def _update_libvirt_domain(self):
  1253. '''Re-initialise :py:attr:`libvirt_domain`.'''
  1254. domain_config = self.create_config_file()
  1255. try:
  1256. self._libvirt_domain = self.app.vmm.libvirt_conn.defineXML(
  1257. domain_config)
  1258. except libvirt.libvirtError as e:
  1259. if e.get_error_code() == libvirt.VIR_ERR_OS_TYPE \
  1260. and e.get_str2() == 'hvm':
  1261. raise qubes.exc.QubesVMError(self,
  1262. 'HVM qubes are not supported on this machine. '
  1263. 'Check BIOS settings for VT-x/AMD-V extensions.')
  1264. else:
  1265. raise
  1266. #
  1267. # workshop -- those are to be reworked later
  1268. #
  1269. def get_prefmem(self):
  1270. # TODO: qmemman is still xen specific
  1271. untrusted_meminfo_key = self.app.vmm.xs.read('',
  1272. '/local/domain/{}/memory/meminfo'.format(self.xid))
  1273. if untrusted_meminfo_key is None or untrusted_meminfo_key == '':
  1274. return 0
  1275. domain = qubes.qmemman.DomainState(self.xid)
  1276. qubes.qmemman.algo.refresh_meminfo_for_domain(
  1277. domain, untrusted_meminfo_key)
  1278. domain.memory_maximum = self.get_mem_static_max() * 1024
  1279. return qubes.qmemman.algo.prefmem(domain) / 1024
  1280. def _clean_volume_config(config):
  1281. common_attributes = ['name', 'pool', 'size', 'internal', 'removable',
  1282. 'revisions_to_keep', 'rw', 'snap_on_start',
  1283. 'save_on_stop', 'source']
  1284. config_copy = copy.deepcopy(config)
  1285. return {k: v for k, v in config_copy.items() if k in common_attributes}
  1286. def _patch_pool_config(config, pool=None, pools=None):
  1287. assert pool is not None or pools is not None
  1288. is_saveable = 'save_on_stop' in config and config['save_on_stop']
  1289. is_resetable = not ('snap_on_start' in config and # volatile
  1290. config['snap_on_start'] and not is_saveable)
  1291. is_exportable = is_saveable or is_resetable
  1292. name = config['name']
  1293. if pool and is_exportable:
  1294. config['pool'] = str(pool)
  1295. elif pool and not is_exportable:
  1296. pass
  1297. elif pools and name in pools.keys():
  1298. if is_exportable:
  1299. config['pool'] = str(pools[name])
  1300. else:
  1301. msg = "Can't clone a snapshot volume {!s} to pool {!s} " \
  1302. .format(name, pools[name])
  1303. raise qubes.exc.QubesException(msg)
  1304. return config
  1305. def _patch_volume_config(volume_config, pool=None, pools=None):
  1306. assert not (pool and pools), \
  1307. 'You can not pass pool & pools parameter at same time'
  1308. assert pool or pools
  1309. result = {}
  1310. for name, config in volume_config.items():
  1311. # copy only the subset of volume_config key/values
  1312. dst_config = _clean_volume_config(config)
  1313. if pool is not None or pools is not None:
  1314. dst_config = _patch_pool_config(dst_config, pool, pools)
  1315. result[name] = dst_config
  1316. return result