qubesvm.py 74 KB

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