qubesvm.py 83 KB

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