qubesvm.py 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015
  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 errno
  26. import grp
  27. import os
  28. import os.path
  29. import shutil
  30. import string
  31. import subprocess
  32. import uuid
  33. import warnings
  34. import libvirt # pylint: disable=import-error
  35. import lxml
  36. import qubes
  37. import qubes.config
  38. import qubes.exc
  39. import qubes.storage
  40. import qubes.storage.file
  41. import qubes.utils
  42. import qubes.vm
  43. import qubes.vm.mix.net
  44. qmemman_present = False
  45. try:
  46. import qubes.qmemman.client # pylint: disable=wrong-import-position
  47. qmemman_present = True
  48. except ImportError:
  49. pass
  50. MEM_OVERHEAD_BASE = (3 + 1) * 1024 * 1024
  51. MEM_OVERHEAD_PER_VCPU = 3 * 1024 * 1024 / 2
  52. def _setter_kernel(self, prop, value):
  53. ''' Helper for setting the domain kernel and running sanity checks on it.
  54. ''' # pylint: disable=unused-argument
  55. if not value:
  56. return ''
  57. value = str(value)
  58. if '/' in value:
  59. raise qubes.exc.QubesPropertyValueError(self, prop, value,
  60. 'Kernel name cannot contain \'/\'')
  61. return value
  62. def _setter_positive_int(self, prop, value):
  63. ''' Helper for setting a positive int. Checks that the int is >= 0 '''
  64. # pylint: disable=unused-argument
  65. value = int(value)
  66. if value <= 0:
  67. raise ValueError('Value must be positive')
  68. return value
  69. def _setter_default_user(self, prop, value):
  70. ''' Helper for setting default user '''
  71. value = str(value)
  72. # specifically forbid: ':', ' ', ''', '"'
  73. allowed_chars = string.ascii_letters + string.digits + '_-+,.'
  74. if not all(c in allowed_chars for c in value):
  75. raise qubes.exc.QubesPropertyValueError(self, prop, value,
  76. 'Username can contain only those characters: ' + allowed_chars)
  77. return value
  78. def _setter_virt_mode(self, prop, value):
  79. value = str(value)
  80. value = value.lower()
  81. if value not in ('hvm', 'pv', 'pvh'):
  82. raise qubes.exc.QubesPropertyValueError(self, prop, value,
  83. 'Invalid virtualization mode, supported values: hvm, pv, pvh')
  84. if value == 'pvh' and list(self.devices['pci'].persistent()):
  85. raise qubes.exc.QubesPropertyValueError(self, prop, value,
  86. "pvh mode can't be set if pci devices are attached")
  87. return value
  88. def _default_virt_mode(self):
  89. if self.devices['pci'].persistent():
  90. return 'hvm'
  91. try:
  92. return self.template.virt_mode
  93. except AttributeError:
  94. return 'pvh'
  95. def _default_with_template(prop, default):
  96. '''Return a callable for 'default' argument of a property. Use a value
  97. from a template (if any), otherwise *default*
  98. '''
  99. def _func(self):
  100. try:
  101. return getattr(self.template, prop)
  102. except AttributeError:
  103. if callable(default):
  104. return default(self)
  105. return default
  106. return _func
  107. class QubesVM(qubes.vm.mix.net.NetVMMixin, qubes.vm.BaseVM):
  108. '''Base functionality of Qubes VM shared between all VMs.
  109. The following events are raised on this class or its subclasses:
  110. .. event:: domain-init (subject, event)
  111. Fired at the end of class' constructor.
  112. :param subject: Event emitter (the qube object)
  113. :param event: Event name (``'domain-init'``)
  114. .. event:: domain-load (subject, event)
  115. Fired after the qube was loaded from :file:`qubes.xml`
  116. :param subject: Event emitter (the qube object)
  117. :param event: Event name (``'domain-loaded'``)
  118. .. event:: domain-pre-start \
  119. (subject, event, start_guid, mem_required)
  120. Fired at the beginning of :py:meth:`start` method.
  121. Handler for this event can be asynchronous (a coroutine).
  122. :param subject: Event emitter (the qube object)
  123. :param event: Event name (``'domain-pre-start'``)
  124. *other arguments are as in :py:meth:`start`*
  125. .. event:: domain-spawn (subject, event, start_guid)
  126. Fired after creating libvirt domain.
  127. :param subject: Event emitter (the qube object)
  128. :param event: Event name (``'domain-spawn'``)
  129. Handler for this event can be asynchronous (a coroutine).
  130. *other arguments are as in :py:meth:`start`*
  131. .. event:: domain-start (subject, event, start_guid)
  132. Fired at the end of :py:meth:`start` method.
  133. Handler for this event can be asynchronous (a coroutine).
  134. :param subject: Event emitter (the qube object)
  135. :param event: Event name (``'domain-start'``)
  136. *other arguments are as in :py:meth:`start`*
  137. .. event:: domain-start-failed (subject, event, reason)
  138. Fired when :py:meth:`start` method fails.
  139. *reason* argument is a textual error message.
  140. Handler for this event can be asynchronous (a coroutine).
  141. :param subject: Event emitter (the qube object)
  142. :param event: Event name (``'domain-start'``)
  143. *other arguments are as in :py:meth:`start`*
  144. .. event:: domain-paused (subject, event)
  145. Fired when the domain has been paused.
  146. :param subject: Event emitter (the qube object)
  147. :param event: Event name (``'domain-paused'``)
  148. .. event:: domain-unpaused (subject, event)
  149. Fired when the domain has been unpaused.
  150. :param subject: Event emitter (the qube object)
  151. :param event: Event name (``'domain-unpaused'``)
  152. .. event:: domain-stopped (subject, event)
  153. Fired when domain has been stopped.
  154. This event is emitted before ``'domain-shutdown'`` and will trigger
  155. the cleanup in QubesVM. So if you require that the cleanup has
  156. already run use ``'domain-shutdown'``.
  157. Note that you can receive this event as soon as you received
  158. ``'domain-pre-start'``. This also can be emitted in case of a
  159. startup failure, before or after ``'domain-start-failed'``.
  160. Handler for this event can be asynchronous (a coroutine).
  161. :param subject: Event emitter (the qube object)
  162. :param event: Event name (``'domain-stopped'``)
  163. .. event:: domain-shutdown (subject, event)
  164. Fired when domain has been shut down. It is generated after
  165. ``'domain-stopped'``.
  166. Note that you can receive this event as soon as you received
  167. ``'domain-pre-start'``. This also can be emitted in case of a
  168. startup failure, before or after ``'domain-start-failed'``.
  169. Handler for this event can be asynchronous (a coroutine).
  170. :param subject: Event emitter (the qube object)
  171. :param event: Event name (``'domain-shutdown'``)
  172. .. event:: domain-pre-shutdown (subject, event, force)
  173. Fired at the beginning of :py:meth:`shutdown` method.
  174. Handler for this event can be asynchronous (a coroutine).
  175. :param subject: Event emitter (the qube object)
  176. :param event: Event name (``'domain-pre-shutdown'``)
  177. :param force: If the shutdown is to be forceful
  178. .. event:: domain-cmd-pre-run (subject, event, start_guid)
  179. Fired at the beginning of :py:meth:`run_service` method.
  180. Handler for this event can be asynchronous (a coroutine).
  181. :param subject: Event emitter (the qube object)
  182. :param event: Event name (``'domain-cmd-pre-run'``)
  183. :param start_guid: If the gui daemon can be started
  184. .. event:: domain-create-on-disk (subject, event)
  185. Fired at the end of :py:meth:`create_on_disk` method.
  186. Handler for this event can be asynchronous (a coroutine).
  187. :param subject: Event emitter (the qube object)
  188. :param event: Event name (``'domain-create-on-disk'``)
  189. .. event:: domain-remove-from-disk (subject, event)
  190. Fired at the beginning of :py:meth:`remove_from_disk` method, before
  191. the qube directory is removed.
  192. Handler for this event can be asynchronous (a coroutine).
  193. :param subject: Event emitter (the qube object)
  194. :param event: Event name (``'domain-remove-from-disk'``)
  195. .. event:: domain-clone-files (subject, event, src)
  196. Fired at the end of :py:meth:`clone_disk_files` method.
  197. Handler for this event can be asynchronous (a coroutine).
  198. :param subject: Event emitter (the qube object)
  199. :param event: Event name (``'domain-clone-files'``)
  200. :param src: source qube
  201. .. event:: domain-verify-files (subject, event)
  202. Fired at the end of :py:meth:`clone_disk_files` method.
  203. :param subject: Event emitter (the qube object)
  204. :param event: Event name (``'domain-verify-files'``)
  205. If you think some files are missing or damaged, raise an exception.
  206. .. event:: domain-is-fully-usable (subject, event)
  207. Fired at the end of :py:meth:`clone_disk_files` method.
  208. :param subject: Event emitter (the qube object)
  209. :param event: Event name (``'domain-is-fully-usable'``)
  210. You may ``yield False`` from the handler if you think the qube is
  211. not fully usable. This will cause the domain to be in "transient"
  212. state in the domain lifecycle.
  213. .. event:: domain-qdb-create (subject, event)
  214. Fired at the end of :py:meth:`create_qdb_entries` method.
  215. :param subject: Event emitter (the qube object)
  216. :param event: Event name (``'domain-qdb-create'``)
  217. This event is a good place to add your custom entries to the qdb.
  218. .. event:: domain-qdb-change:watched-path (subject, event, path)
  219. Fired when watched QubesDB entry is changed. See
  220. :py:meth:`watch_qdb_path`. *watched-path* part of event name is
  221. what path was registered for watching, *path* in event argument
  222. is what actually have changed (which may be different if watching a
  223. directory, i.e. a path with `/` at the end).
  224. :param subject: Event emitter (the qube object)
  225. :param event: Event name (``'domain-qdb-change'``)
  226. :param path: changed QubesDB path
  227. .. event:: backup-get-files (subject, event)
  228. Collects additional file to be included in a backup.
  229. :param subject: Event emitter (the qube object)
  230. :param event: Event name (``'backup-get-files'``)
  231. Handlers should yield paths of the files.
  232. .. event:: domain-restore (subject, event)
  233. Domain was just restored from backup, although the storage was not
  234. yet verified and the app object was not yet saved.
  235. :param subject: Event emitter (the qube object)
  236. :param event: Event name (``'domain-restore'``)
  237. .. event:: domain-feature-set:feature (subject, event, feature, value
  238. [, oldvalue])
  239. A feature was changed. This event is fired before bare
  240. `domain-feature-set` event.
  241. *oldvalue* is present only when there was any.
  242. :param subject: Event emitter (the qube object)
  243. :param event: Event name (``'domain-feature-set:' feature``)
  244. :param feature: feature name
  245. :param value: new value
  246. :param oldvalue: old value, if any
  247. .. event:: domain-feature-delete:feature (subject, event, feature)
  248. A feature was removed. This event is fired before bare
  249. `domain-feature-delete` event.
  250. :param subject: Event emitter (the qube object)
  251. :param event: Event name (``'domain-feature-delete:' feature``)
  252. :param feature: feature name
  253. .. event:: domain-tag-add:tag (subject, event, tag)
  254. A tag was added.
  255. :param subject: Event emitter (the qube object)
  256. :param event: Event name (``'domain-tag-add:' tag``)
  257. :param tag: tag name
  258. .. event:: domain-tag-delete:tag (subject, event, tag)
  259. A feature was removed.
  260. :param subject: Event emitter (the qube object)
  261. :param event: Event name (``'domain-tag-delete:' tag``)
  262. :param tag: tag name
  263. .. event:: features-request (subject, event, *, untrusted_features)
  264. The domain is performing a features request.
  265. :param subject: Event emitter (the qube object)
  266. :param event: Event name (``'features-request'``)
  267. :param untrusted_features: :py:class:`dict` containing the feature \
  268. request
  269. The content of the `untrusted_features` variable is, as the name
  270. implies, **UNTRUSTED**. The remind this to programmer, the variable
  271. name has to be exactly as provided.
  272. It is up to the extensions to decide, what to do with request,
  273. ranging from plainly ignoring the request to verbatim copy into
  274. :py:attr:`features` with only minimal sanitisation.
  275. Handler for this event can be asynchronous (a coroutine).
  276. .. event:: firewall-changed (subject, event)
  277. Firewall was changed.
  278. :param subject: Event emitter (the qube object)
  279. :param event: Event name (``'firewall-changed'``)
  280. .. event:: net-domain-connect (subject, event, vm)
  281. Fired after connecting a domiain to this vm.
  282. :param subject: Event emitter (the qube object)
  283. :param event: Event name (``'net-domain-connect'``)
  284. :param vm: The domain that was just connected.
  285. On the `vm` object there was probably ``property-set:netvm`` fired
  286. earlier.
  287. '''
  288. #
  289. # per-class properties
  290. #
  291. #: directory in which domains of this class will reside
  292. dir_path_prefix = qubes.config.system_path['qubes_appvms_dir']
  293. #
  294. # properties loaded from XML
  295. #
  296. virt_mode = qubes.property('virt_mode',
  297. type=str, setter=_setter_virt_mode,
  298. default=_default_virt_mode,
  299. doc='''Virtualisation mode: full virtualisation ("HVM"),
  300. or paravirtualisation ("PV"), or hybrid ("PVH"). TemplateBasedVMs use its '
  301. 'template\'s value by default.''')
  302. installed_by_rpm = qubes.property('installed_by_rpm',
  303. type=bool, setter=qubes.property.bool,
  304. default=False,
  305. doc='''If this domain's image was installed from package tracked by
  306. package manager.''')
  307. memory = qubes.property('memory', type=int,
  308. setter=_setter_positive_int,
  309. default=_default_with_template('memory', lambda self:
  310. qubes.config.defaults[
  311. 'hvm_memory' if self.virt_mode == 'hvm' else 'memory']),
  312. doc='Memory currently available for this VM. TemplateBasedVMs use its '
  313. 'template\'s value by default.')
  314. maxmem = qubes.property('maxmem', type=int,
  315. setter=_setter_positive_int,
  316. default=_default_with_template('maxmem', (lambda self:
  317. int(min(self.app.host.memory_total / 1024 / 2, 4000)))),
  318. doc='''Maximum amount of memory available for this VM (for the purpose
  319. of the memory balancer). TemplateBasedVMs use its '
  320. 'template\'s value by default.''')
  321. stubdom_mem = qubes.property('stubdom_mem', type=int,
  322. setter=_setter_positive_int,
  323. default=None,
  324. doc='Memory ammount allocated for the stubdom')
  325. vcpus = qubes.property('vcpus',
  326. type=int,
  327. setter=_setter_positive_int,
  328. default=_default_with_template('vcpus', 2),
  329. doc='Number of virtual CPUs for a qube. TemplateBasedVMs use its '
  330. 'template\'s value by default.')
  331. # CORE2: swallowed uses_default_kernel
  332. kernel = qubes.property('kernel', type=str,
  333. setter=_setter_kernel,
  334. default=_default_with_template('kernel',
  335. lambda self: self.app.default_kernel),
  336. doc='Kernel used by this domain. TemplateBasedVMs use its '
  337. 'template\'s value by default.')
  338. # CORE2: swallowed uses_default_kernelopts
  339. # pylint: disable=no-member
  340. kernelopts = qubes.property('kernelopts', type=str, load_stage=4,
  341. default=(lambda self: qubes.config.defaults['kernelopts_pcidevs']
  342. # pylint: disable=no-member
  343. if list(self.devices['pci'].persistent())
  344. else self.template.kernelopts if hasattr(self, 'template')
  345. else qubes.config.defaults['kernelopts']),
  346. doc='Kernel command line passed to domain. TemplateBasedVMs use its '
  347. 'template\'s value by default.')
  348. debug = qubes.property('debug', type=bool, default=False,
  349. setter=qubes.property.bool,
  350. doc='Turns on debugging features.')
  351. # XXX what this exactly does?
  352. # XXX shouldn't this go to standalone VM and TemplateVM, and leave here
  353. # only plain property?
  354. default_user = qubes.property('default_user', type=str,
  355. # pylint: disable=no-member
  356. default=_default_with_template('default_user', 'user'),
  357. setter=_setter_default_user,
  358. doc='Default user to start applications as. TemplateBasedVMs use its '
  359. 'template\'s value by default.')
  360. # pylint: enable=no-member
  361. # @property
  362. # def default_user(self):
  363. # if self.template is not None:
  364. # return self.template.default_user
  365. # else:
  366. # return self._default_user
  367. qrexec_timeout = qubes.property('qrexec_timeout', type=int,
  368. default=_default_with_template('qrexec_timeout', 60),
  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 OSError as e:
  1132. if e.errno == errno.ENOENT:
  1133. pass
  1134. else:
  1135. raise
  1136. yield from self.storage.remove()
  1137. @asyncio.coroutine
  1138. def clone_disk_files(self, src, pool=None, pools=None, ):
  1139. '''Clone files from other vm.
  1140. :param qubes.vm.qubesvm.QubesVM src: source VM
  1141. '''
  1142. # If the current vm name is not a part of `self.app.domains.keys()`,
  1143. # then the current vm is in creation process. Calling
  1144. # `self.is_halted()` at this point, would instantiate libvirt, we want
  1145. # avoid that.
  1146. if self.name in self.app.domains.keys() and not self.is_halted():
  1147. raise qubes.exc.QubesVMNotHaltedError(
  1148. self, 'Cannot clone a running domain {!r}'.format(self.name))
  1149. msg = "Destination {!s} already exists".format(self.dir_path)
  1150. assert not os.path.exists(self.dir_path), msg
  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. yield from self.storage.clone(src)
  1159. self.storage.verify()
  1160. assert self.volumes != {}
  1161. if src.icon_path is not None \
  1162. and os.path.exists(src.icon_path) \
  1163. and self.icon_path is not None:
  1164. if os.path.islink(src.icon_path):
  1165. icon_path = os.readlink(src.icon_path)
  1166. self.log.info(
  1167. 'Creating icon symlink {} -> {}'.format(
  1168. self.icon_path, icon_path))
  1169. os.symlink(icon_path, self.icon_path)
  1170. else:
  1171. self.log.info(
  1172. 'Copying icon {} -> {}'.format(
  1173. src.icon_path, self.icon_path))
  1174. shutil.copy(src.icon_path, self.icon_path)
  1175. # fire hooks
  1176. yield from self.fire_event_async('domain-clone-files', src=src)
  1177. #
  1178. # methods for querying domain state
  1179. #
  1180. # state of the machine
  1181. def get_power_state(self):
  1182. '''Return power state description string.
  1183. Return value may be one of those:
  1184. =============== ========================================================
  1185. return value meaning
  1186. =============== ========================================================
  1187. ``'Halted'`` Machine is not active.
  1188. ``'Transient'`` Machine is running, but does not have :program:`guid`
  1189. or :program:`qrexec` available.
  1190. ``'Running'`` Machine is ready and running.
  1191. ``'Paused'`` Machine is paused.
  1192. ``'Suspended'`` Machine is S3-suspended.
  1193. ``'Halting'`` Machine is in process of shutting down.
  1194. ``'Dying'`` Machine is still in process of shutting down.
  1195. ``'Crashed'`` Machine crashed and is unusable, probably because of
  1196. bug in dom0.
  1197. ``'NA'`` Machine is in unknown state (most likely libvirt domain
  1198. is undefined).
  1199. =============== ========================================================
  1200. FIXME: graph below may be incomplete and wrong. Click on method name to
  1201. see its documentation.
  1202. .. graphviz::
  1203. digraph {
  1204. node [fontname="sans-serif"];
  1205. edge [fontname="mono"];
  1206. Halted;
  1207. NA;
  1208. Dying;
  1209. Crashed;
  1210. Transient;
  1211. Halting;
  1212. Running;
  1213. Paused [color=gray75 fontcolor=gray75];
  1214. Suspended;
  1215. NA -> Halted;
  1216. Halted -> NA [constraint=false];
  1217. Halted -> Transient
  1218. [xlabel="start()" URL="#qubes.vm.qubesvm.QubesVM.start"];
  1219. Transient -> Running;
  1220. Running -> Halting
  1221. [xlabel="shutdown()"
  1222. URL="#qubes.vm.qubesvm.QubesVM.shutdown"
  1223. constraint=false];
  1224. Halting -> Dying -> Halted [constraint=false];
  1225. /* cosmetic, invisible edges to put rank constraint */
  1226. Dying -> Halting [style="invis"];
  1227. Halting -> Transient [style="invis"];
  1228. Running -> Halted
  1229. [label="force_shutdown()"
  1230. URL="#qubes.vm.qubesvm.QubesVM.force_shutdown"
  1231. constraint=false];
  1232. Running -> Crashed [constraint=false];
  1233. Crashed -> Halted [constraint=false];
  1234. Running -> Paused
  1235. [label="pause()" URL="#qubes.vm.qubesvm.QubesVM.pause"
  1236. color=gray75 fontcolor=gray75];
  1237. Running -> Suspended
  1238. [label="suspend()" URL="#qubes.vm.qubesvm.QubesVM.suspend"
  1239. color=gray50 fontcolor=gray50];
  1240. Paused -> Running
  1241. [label="unpause()" URL="#qubes.vm.qubesvm.QubesVM.unpause"
  1242. color=gray75 fontcolor=gray75];
  1243. Suspended -> Running
  1244. [label="resume()" URL="#qubes.vm.qubesvm.QubesVM.resume"
  1245. color=gray50 fontcolor=gray50];
  1246. Running -> Suspended
  1247. [label="suspend()" URL="#qubes.vm.qubesvm.QubesVM.suspend"];
  1248. Suspended -> Running
  1249. [label="resume()" URL="#qubes.vm.qubesvm.QubesVM.resume"];
  1250. { rank=source; Halted NA };
  1251. { rank=same; Transient Halting };
  1252. { rank=same; Crashed Dying };
  1253. { rank=sink; Paused Suspended };
  1254. }
  1255. .. seealso::
  1256. http://wiki.libvirt.org/page/VM_lifecycle
  1257. Description of VM life cycle from the point of view of libvirt.
  1258. https://libvirt.org/html/libvirt-libvirt-domain.html#virDomainState
  1259. Libvirt's enum describing precise state of a domain.
  1260. ''' # pylint: disable=too-many-return-statements
  1261. # don't try to define libvirt domain, if it isn't there, VM surely
  1262. # isn't running
  1263. # reason for this "if": allow vm.is_running() in PCI (or other
  1264. # device) extension while constructing libvirt XML
  1265. if self.app.vmm.offline_mode:
  1266. return 'Halted'
  1267. if self._libvirt_domain is None:
  1268. try:
  1269. self._libvirt_domain = self.app.vmm.libvirt_conn.lookupByUUID(
  1270. self.uuid.bytes)
  1271. except libvirt.libvirtError as e:
  1272. if e.get_error_code() == libvirt.VIR_ERR_NO_DOMAIN:
  1273. return 'Halted'
  1274. raise
  1275. libvirt_domain = self.libvirt_domain
  1276. if libvirt_domain is None:
  1277. return 'Halted'
  1278. try:
  1279. if libvirt_domain.isActive():
  1280. # pylint: disable=line-too-long
  1281. if libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_PAUSED:
  1282. return "Paused"
  1283. if libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_CRASHED:
  1284. return "Crashed"
  1285. if libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_SHUTDOWN:
  1286. return "Halting"
  1287. if libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_SHUTOFF:
  1288. return "Dying"
  1289. if libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_PMSUSPENDED: # nopep8
  1290. return "Suspended"
  1291. if not self.is_fully_usable():
  1292. return "Transient"
  1293. return "Running"
  1294. return 'Halted'
  1295. except libvirt.libvirtError as e:
  1296. if e.get_error_code() == libvirt.VIR_ERR_NO_DOMAIN:
  1297. return 'Halted'
  1298. raise
  1299. assert False
  1300. def is_halted(self):
  1301. ''' Check whether this domain's state is 'Halted'
  1302. :returns: :py:obj:`True` if this domain is halted, \
  1303. :py:obj:`False` otherwise.
  1304. :rtype: bool
  1305. '''
  1306. return self.get_power_state() == 'Halted'
  1307. def is_running(self):
  1308. '''Check whether this domain is running.
  1309. :returns: :py:obj:`True` if this domain is started, \
  1310. :py:obj:`False` otherwise.
  1311. :rtype: bool
  1312. '''
  1313. if self.app.vmm.offline_mode:
  1314. return False
  1315. # don't try to define libvirt domain, if it isn't there, VM surely
  1316. # isn't running
  1317. # reason for this "if": allow vm.is_running() in PCI (or other
  1318. # device) extension while constructing libvirt XML
  1319. if self._libvirt_domain is None:
  1320. try:
  1321. self._libvirt_domain = self.app.vmm.libvirt_conn.lookupByUUID(
  1322. self.uuid.bytes)
  1323. except libvirt.libvirtError as e:
  1324. if e.get_error_code() == libvirt.VIR_ERR_NO_DOMAIN:
  1325. return False
  1326. raise
  1327. return bool(self.libvirt_domain.isActive())
  1328. def is_paused(self):
  1329. '''Check whether this domain is paused.
  1330. :returns: :py:obj:`True` if this domain is paused, \
  1331. :py:obj:`False` otherwise.
  1332. :rtype: bool
  1333. '''
  1334. return self.libvirt_domain \
  1335. and self.libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_PAUSED
  1336. def is_qrexec_running(self):
  1337. '''Check whether qrexec for this domain is available.
  1338. :returns: :py:obj:`True` if qrexec is running, \
  1339. :py:obj:`False` otherwise.
  1340. :rtype: bool
  1341. '''
  1342. if self.xid < 0: # pylint: disable=comparison-with-callable
  1343. return False
  1344. return os.path.exists('/var/run/qubes/qrexec.%s' % self.name)
  1345. def is_fully_usable(self):
  1346. return all(self.fire_event('domain-is-fully-usable'))
  1347. @qubes.events.handler('domain-is-fully-usable')
  1348. def on_domain_is_fully_usable(self, event):
  1349. '''Check whether domain is running and sane.
  1350. Currently this checks for running qrexec.
  1351. ''' # pylint: disable=unused-argument
  1352. # Running gui-daemon implies also VM running
  1353. if not self.is_qrexec_running():
  1354. yield False
  1355. # memory and disk
  1356. def get_mem(self):
  1357. '''Get current memory usage from VM.
  1358. :returns: Memory usage [FIXME unit].
  1359. :rtype: FIXME
  1360. '''
  1361. if self.libvirt_domain is None:
  1362. return 0
  1363. try:
  1364. if not self.libvirt_domain.isActive():
  1365. return 0
  1366. return self.libvirt_domain.info()[1]
  1367. except libvirt.libvirtError as e:
  1368. if e.get_error_code() in (
  1369. # qube no longer exists
  1370. libvirt.VIR_ERR_NO_DOMAIN,
  1371. # libxl_domain_info failed (race condition from isActive)
  1372. libvirt.VIR_ERR_INTERNAL_ERROR):
  1373. return 0
  1374. self.log.exception(
  1375. 'libvirt error code: {!r}'.format(e.get_error_code()))
  1376. raise
  1377. def get_mem_static_max(self):
  1378. '''Get maximum memory available to VM.
  1379. :returns: Memory limit [FIXME unit].
  1380. :rtype: FIXME
  1381. '''
  1382. if self.libvirt_domain is None:
  1383. return 0
  1384. try:
  1385. return self.libvirt_domain.maxMemory()
  1386. except libvirt.libvirtError as e:
  1387. if e.get_error_code() in (
  1388. # qube no longer exists
  1389. libvirt.VIR_ERR_NO_DOMAIN,
  1390. # libxl_domain_info failed (race condition from isActive)
  1391. libvirt.VIR_ERR_INTERNAL_ERROR):
  1392. return 0
  1393. self.log.exception(
  1394. 'libvirt error code: {!r}'.format(e.get_error_code()))
  1395. raise
  1396. def get_cputime(self):
  1397. '''Get total CPU time burned by this domain since start.
  1398. :returns: CPU time usage [FIXME unit].
  1399. :rtype: FIXME
  1400. '''
  1401. if self.libvirt_domain is None:
  1402. return 0
  1403. if self.libvirt_domain is None:
  1404. return 0
  1405. if not self.libvirt_domain.isActive():
  1406. return 0
  1407. try:
  1408. if not self.libvirt_domain.isActive():
  1409. return 0
  1410. # this does not work, because libvirt
  1411. # return self.libvirt_domain.getCPUStats(
  1412. # libvirt.VIR_NODE_CPU_STATS_ALL_CPUS, 0)[0]['cpu_time']/10**9
  1413. return self.libvirt_domain.info()[4]
  1414. except libvirt.libvirtError as e:
  1415. if e.get_error_code() in (
  1416. # qube no longer exists
  1417. libvirt.VIR_ERR_NO_DOMAIN,
  1418. # libxl_domain_info failed (race condition from isActive)
  1419. libvirt.VIR_ERR_INTERNAL_ERROR):
  1420. return 0
  1421. self.log.exception(
  1422. 'libvirt error code: {!r}'.format(e.get_error_code()))
  1423. raise
  1424. # miscellanous
  1425. @qubes.stateless_property
  1426. def start_time(self):
  1427. '''Tell when machine was started.
  1428. :rtype: float or None
  1429. '''
  1430. if not self.is_running():
  1431. return None
  1432. # TODO shouldn't this be qubesdb?
  1433. start_time = self.app.vmm.xs.read('',
  1434. '/vm/{}/start_time'.format(self.uuid))
  1435. if start_time != '':
  1436. return float(start_time)
  1437. return None
  1438. #
  1439. # helper methods
  1440. #
  1441. def relative_path(self, path):
  1442. '''Return path relative to py:attr:`dir_path`.
  1443. :param str path: Path in question.
  1444. :returns: Relative path.
  1445. '''
  1446. return os.path.relpath(path, self.dir_path)
  1447. def create_qdb_entries(self):
  1448. '''Create entries in Qubes DB.
  1449. '''
  1450. # pylint: disable=no-member
  1451. self.untrusted_qdb.write('/name', self.name)
  1452. self.untrusted_qdb.write('/type', self.__class__.__name__)
  1453. self.untrusted_qdb.write('/default-user', self.default_user)
  1454. self.untrusted_qdb.write('/qubes-vm-updateable', str(self.updateable))
  1455. self.untrusted_qdb.write('/qubes-vm-persistence',
  1456. 'full' if self.updateable else 'rw-only')
  1457. self.untrusted_qdb.write('/qubes-debug-mode', str(int(self.debug)))
  1458. try:
  1459. self.untrusted_qdb.write('/qubes-base-template', self.template.name)
  1460. except AttributeError:
  1461. self.untrusted_qdb.write('/qubes-base-template', '')
  1462. self.untrusted_qdb.write('/qubes-random-seed',
  1463. base64.b64encode(qubes.utils.urandom(64)))
  1464. if self.provides_network:
  1465. # '/qubes-netvm-network' value is only checked for being non empty
  1466. self.untrusted_qdb.write('/qubes-netvm-network', str(self.gateway))
  1467. self.untrusted_qdb.write('/qubes-netvm-gateway', str(self.gateway))
  1468. if self.gateway6:
  1469. self.untrusted_qdb.write('/qubes-netvm-gateway6',
  1470. str(self.gateway6))
  1471. self.untrusted_qdb.write('/qubes-netvm-netmask', str(self.netmask))
  1472. for i, addr in zip(('primary', 'secondary'), self.dns):
  1473. self.untrusted_qdb.write('/qubes-netvm-{}-dns'.format(i), addr)
  1474. if self.netvm is not None:
  1475. self.untrusted_qdb.write('/qubes-ip', str(self.visible_ip))
  1476. self.untrusted_qdb.write('/qubes-netmask',
  1477. str(self.visible_netmask))
  1478. self.untrusted_qdb.write('/qubes-gateway',
  1479. str(self.visible_gateway))
  1480. for i, addr in zip(('primary', 'secondary'), self.dns):
  1481. self.untrusted_qdb.write('/qubes-{}-dns'.format(i), str(addr))
  1482. if self.visible_ip6:
  1483. self.untrusted_qdb.write('/qubes-ip6', str(self.visible_ip6))
  1484. if self.visible_gateway6:
  1485. self.untrusted_qdb.write('/qubes-gateway6',
  1486. str(self.visible_gateway6))
  1487. tzname = qubes.utils.get_timezone()
  1488. if tzname:
  1489. self.untrusted_qdb.write('/qubes-timezone', tzname)
  1490. self.untrusted_qdb.write('/qubes-block-devices', '')
  1491. self.untrusted_qdb.write('/qubes-usb-devices', '')
  1492. # TODO: Currently the whole qmemman is quite Xen-specific, so stay with
  1493. # xenstore for it until decided otherwise
  1494. if qmemman_present:
  1495. self.app.vmm.xs.set_permissions('',
  1496. '/local/domain/{}/memory'.format(self.xid),
  1497. [{'dom': self.xid}])
  1498. self.fire_event('domain-qdb-create')
  1499. # TODO async; update this in constructor
  1500. def _update_libvirt_domain(self):
  1501. '''Re-initialise :py:attr:`libvirt_domain`.'''
  1502. domain_config = self.create_config_file()
  1503. try:
  1504. self._libvirt_domain = self.app.vmm.libvirt_conn.defineXML(
  1505. domain_config)
  1506. except libvirt.libvirtError as e:
  1507. if e.get_error_code() == libvirt.VIR_ERR_OS_TYPE \
  1508. and e.get_str2() == 'hvm':
  1509. raise qubes.exc.QubesVMError(self,
  1510. 'HVM qubes are not supported on this machine. '
  1511. 'Check BIOS settings for VT-x/AMD-V extensions.')
  1512. else:
  1513. raise
  1514. #
  1515. # workshop -- those are to be reworked later
  1516. #
  1517. def get_prefmem(self):
  1518. # TODO: qmemman is still xen specific
  1519. untrusted_meminfo_key = self.app.vmm.xs.read('',
  1520. '/local/domain/{}/memory/meminfo'.format(self.xid))
  1521. if untrusted_meminfo_key is None or untrusted_meminfo_key == '':
  1522. return 0
  1523. domain = qubes.qmemman.DomainState(self.xid)
  1524. qubes.qmemman.algo.refresh_meminfo_for_domain(
  1525. domain, untrusted_meminfo_key)
  1526. if domain.mem_used is None:
  1527. # apparently invalid xenstore content
  1528. return 0
  1529. domain.memory_maximum = self.get_mem_static_max() * 1024
  1530. return qubes.qmemman.algo.prefmem(domain) / 1024
  1531. def _clean_volume_config(config):
  1532. common_attributes = ['name', 'pool', 'size',
  1533. 'revisions_to_keep', 'rw', 'snap_on_start',
  1534. 'save_on_stop', 'source']
  1535. return {k: v for k, v in config.items() if k in common_attributes}
  1536. def _patch_pool_config(config, pool=None, pools=None):
  1537. assert pool is not None or pools is not None
  1538. is_snapshot = config['snap_on_start']
  1539. is_rw = config['rw']
  1540. name = config['name']
  1541. if pool and not is_snapshot and is_rw:
  1542. config['pool'] = str(pool)
  1543. elif pool:
  1544. pass
  1545. elif pools and name in pools.keys():
  1546. if not is_snapshot:
  1547. config['pool'] = str(pools[name])
  1548. else:
  1549. msg = "Can't clone a snapshot volume {!s} to pool {!s} " \
  1550. .format(name, pools[name])
  1551. raise qubes.exc.QubesException(msg)
  1552. return config
  1553. def _patch_volume_config(volume_config, pool=None, pools=None):
  1554. assert not (pool and pools), \
  1555. 'You can not pass pool & pools parameter at same time'
  1556. assert pool or pools
  1557. result = {}
  1558. for name, config in volume_config.items():
  1559. # copy only the subset of volume_config key/values
  1560. dst_config = _clean_volume_config(config)
  1561. if pool is not None or pools is not None:
  1562. dst_config = _patch_pool_config(dst_config, pool, pools)
  1563. result[name] = dst_config
  1564. return result