qubesvm.py 71 KB

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