qubesvm.py 73 KB

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