qubesvm.py 77 KB

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