qubesvm.py 68 KB

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