qubesvm.py 82 KB

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