qubesvm.py 81 KB

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