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