qubesvm.py 62 KB

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