qubesvm.py 54 KB

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