qubesvm.py 74 KB

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