qubesvm.py 81 KB

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