qubesvm.py 83 KB

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