qubesvm.py 81 KB

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