qubesvm.py 81 KB

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