qubesvm.py 83 KB

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