qubesvm.py 64 KB

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