qubesvm.py 68 KB

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