qubesvm.py 85 KB

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