qubesvm.py 76 KB

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