qubesvm.py 69 KB

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