qubesvm.py 67 KB

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