qubesvm.py 76 KB

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