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 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. backup_timestamp = qubes.property('backup_timestamp', default=None,
  344. type=int,
  345. doc='Time of last backup of the qube, in seconds since unix epoch')
  346. default_dispvm = qubes.VMProperty('default_dispvm',
  347. load_stage=4,
  348. allow_none=True,
  349. default=(lambda self: self.app.default_dispvm),
  350. doc='Default VM to be used as Disposable VM for service calls.')
  351. updateable = qubes.property('updateable',
  352. default=(lambda self: not hasattr(self, 'template')),
  353. type=bool,
  354. setter=qubes.property.forbidden,
  355. doc='True if this machine may be updated on its own.')
  356. #
  357. # static, class-wide properties
  358. #
  359. #
  360. # properties not loaded from XML, calculated at run-time
  361. #
  362. def __str__(self):
  363. return self.name
  364. # VMM-related
  365. @qubes.stateless_property
  366. def xid(self):
  367. '''Xen ID.
  368. Or not Xen, but ID.
  369. '''
  370. if self.libvirt_domain is None:
  371. return -1
  372. try:
  373. return self.libvirt_domain.ID()
  374. except libvirt.libvirtError as e:
  375. if e.get_error_code() == libvirt.VIR_ERR_NO_DOMAIN:
  376. return -1
  377. else:
  378. self.log.exception('libvirt error code: {!r}'.format(
  379. e.get_error_code()))
  380. raise
  381. @qubes.stateless_property
  382. def stubdom_xid(self):
  383. if not self.is_running():
  384. return -1
  385. if self.app.vmm.xs is None:
  386. return -1
  387. stubdom_xid_str = self.app.vmm.xs.read('',
  388. '/local/domain/{}/image/device-model-domid'.format(self.xid))
  389. if stubdom_xid_str is None or not stubdom_xid_str.isdigit():
  390. return -1
  391. return int(stubdom_xid_str)
  392. @property
  393. def attached_volumes(self):
  394. result = []
  395. xml_desc = self.libvirt_domain.XMLDesc()
  396. xml = lxml.etree.fromstring(xml_desc)
  397. for disk in xml.xpath("//domain/devices/disk"):
  398. if disk.find('backenddomain') is not None:
  399. pool_name = 'p_%s' % disk.find('backenddomain').get('name')
  400. pool = self.app.pools[pool_name]
  401. vid = disk.find('source').get('dev').split('/dev/')[1]
  402. for volume in pool.volumes:
  403. if volume.vid == vid:
  404. result += [volume]
  405. break
  406. return result + list(self.volumes.values())
  407. @property
  408. def libvirt_domain(self):
  409. '''Libvirt domain object from libvirt.
  410. May be :py:obj:`None`, if libvirt knows nothing about this domain.
  411. '''
  412. if self._libvirt_domain is not None:
  413. return self._libvirt_domain
  414. # XXX _update_libvirt_domain?
  415. try:
  416. self._libvirt_domain = self.app.vmm.libvirt_conn.lookupByUUID(
  417. self.uuid.bytes)
  418. except libvirt.libvirtError as e:
  419. if e.get_error_code() == libvirt.VIR_ERR_NO_DOMAIN:
  420. self._update_libvirt_domain()
  421. else:
  422. raise
  423. return self._libvirt_domain
  424. @property
  425. def block_devices(self):
  426. ''' Return all :py:class:`qubes.storage.BlockDevice` for current domain
  427. for serialization in the libvirt XML template as <disk>.
  428. '''
  429. for v in self.volumes.values():
  430. block_dev = v.block_device()
  431. if block_dev is not None:
  432. yield block_dev
  433. @property
  434. def untrusted_qdb(self):
  435. '''QubesDB handle for this domain.'''
  436. if self._qdb_connection is None:
  437. if self.is_running():
  438. import qubesdb # pylint: disable=import-error
  439. self._qdb_connection = qubesdb.QubesDB(self.name)
  440. return self._qdb_connection
  441. @property
  442. def dir_path(self):
  443. '''Root directory for files related to this domain'''
  444. return os.path.join(
  445. qubes.config.qubes_base_dir,
  446. self.dir_path_prefix,
  447. self.name)
  448. @property
  449. def icon_path(self):
  450. return os.path.join(self.dir_path, 'icon.png')
  451. @property
  452. def conf_file(self):
  453. return os.path.join(self.dir_path, 'libvirt.xml')
  454. # network-related
  455. #
  456. # constructor
  457. #
  458. def __init__(self, app, xml, volume_config=None, **kwargs):
  459. # migrate renamed properties
  460. if xml is not None:
  461. node_hvm = xml.find('./properties/property[@name=\'hvm\']')
  462. if node_hvm is not None:
  463. if qubes.property.bool(None, None, node_hvm.text):
  464. kwargs['virt_mode'] = 'hvm'
  465. else:
  466. kwargs['virt_mode'] = 'pv'
  467. node_hvm.getparent().remove(node_hvm)
  468. super(QubesVM, self).__init__(app, xml, **kwargs)
  469. if volume_config is None:
  470. volume_config = {}
  471. if hasattr(self, 'volume_config'):
  472. if xml is not None:
  473. for node in xml.xpath('volume-config/volume'):
  474. name = node.get('name')
  475. assert name
  476. for key, value in node.items():
  477. # pylint: disable=no-member
  478. if value == 'True':
  479. value = True
  480. try:
  481. self.volume_config[name][key] = value
  482. except KeyError:
  483. self.volume_config[name] = {key: value}
  484. for name, conf in volume_config.items():
  485. for key, value in conf.items():
  486. # pylint: disable=no-member
  487. try:
  488. self.volume_config[name][key] = value
  489. except KeyError:
  490. self.volume_config[name] = {key: value}
  491. elif volume_config:
  492. raise TypeError(
  493. 'volume_config specified, but {} did not expect that.'.format(
  494. self.__class__.__name__))
  495. # Init private attrs
  496. self._libvirt_domain = None
  497. self._qdb_connection = None
  498. # We assume a fully halted VM here. The 'domain-init' handler will
  499. # check if the VM is already running.
  500. self._domain_stopped_event_received = True
  501. self._domain_stopped_event_handled = True
  502. self._domain_stopped_future = None
  503. # Internal lock to ensure ordering between _domain_stopped_coro() and
  504. # start(). This should not be accessed anywhere else.
  505. self._domain_stopped_lock = asyncio.Lock()
  506. if xml is None:
  507. # we are creating new VM and attributes came through kwargs
  508. assert hasattr(self, 'qid')
  509. assert hasattr(self, 'name')
  510. # Linux specific cap: max memory can't scale beyond 10.79*init_mem
  511. # see https://groups.google.com/forum/#!topic/qubes-devel/VRqkFj1IOtA
  512. if self.maxmem > self.memory * 10:
  513. self.maxmem = self.memory * 10
  514. if xml is None:
  515. # new qube, disable updates check if requested for new qubes
  516. # SEE: 1637 when features are done, migrate to plugin
  517. if not self.app.check_updates_vm:
  518. self.features['check-updates'] = False
  519. # will be initialized after loading all the properties
  520. #: operations which shouldn't happen simultaneously with qube startup
  521. # (including another startup of the same qube)
  522. self.startup_lock = asyncio.Lock()
  523. # fire hooks
  524. if xml is None:
  525. self.events_enabled = True
  526. self.fire_event('domain-init')
  527. def close(self):
  528. if self._qdb_connection is not None:
  529. self._qdb_connection.close()
  530. self._qdb_connection = None
  531. if self._libvirt_domain is not None:
  532. self._libvirt_domain = None
  533. super().close()
  534. def __hash__(self):
  535. return self.qid
  536. def __lt__(self, other):
  537. return self.name < other.name
  538. def __xml__(self):
  539. element = super(QubesVM, self).__xml__()
  540. if hasattr(self, 'volumes'):
  541. volume_config_node = lxml.etree.Element('volume-config')
  542. for volume in self.volumes.values():
  543. volume_config_node.append(volume.__xml__())
  544. element.append(volume_config_node)
  545. return element
  546. #
  547. # event handlers
  548. #
  549. @qubes.events.handler('domain-init', 'domain-load')
  550. def on_domain_init_loaded(self, event):
  551. # pylint: disable=unused-argument
  552. if not hasattr(self, 'uuid'):
  553. self.uuid = uuid.uuid4()
  554. # Initialize VM image storage class;
  555. # it might be already initialized by a recursive call from a child VM
  556. if self.storage is None:
  557. self.storage = qubes.storage.Storage(self)
  558. if not self.app.vmm.offline_mode and self.is_running():
  559. self.start_qdb_watch()
  560. self._domain_stopped_event_received = False
  561. self._domain_stopped_event_handled = False
  562. @qubes.events.handler('property-set:label')
  563. def on_property_set_label(self, event, name, newvalue, oldvalue=None):
  564. # pylint: disable=unused-argument
  565. if self.icon_path:
  566. try:
  567. os.remove(self.icon_path)
  568. except OSError:
  569. pass
  570. if hasattr(os, "symlink"):
  571. os.symlink(newvalue.icon_path, self.icon_path)
  572. subprocess.call(['sudo', 'xdg-icon-resource', 'forceupdate'])
  573. else:
  574. shutil.copy(newvalue.icon_path, self.icon_path)
  575. @qubes.events.handler('property-pre-set:kernel')
  576. def on_property_pre_set_kernel(self, event, name, newvalue, oldvalue=None):
  577. # pylint: disable=unused-argument
  578. if not newvalue:
  579. return
  580. dirname = os.path.join(
  581. qubes.config.qubes_base_dir,
  582. qubes.config.system_path['qubes_kernels_base_dir'],
  583. newvalue)
  584. if not os.path.exists(dirname):
  585. raise qubes.exc.QubesPropertyValueError(self,
  586. self.property_get_def(name), newvalue,
  587. 'Kernel {!r} not installed'.format(newvalue))
  588. for filename in ('vmlinuz', 'initramfs'):
  589. if not os.path.exists(os.path.join(dirname, filename)):
  590. raise qubes.exc.QubesPropertyValueError(self,
  591. self.property_get_def(name), newvalue,
  592. 'Kernel {!r} not properly installed: '
  593. 'missing {!r} file'.format(newvalue, filename))
  594. @qubes.events.handler('property-pre-set:autostart')
  595. def on_property_pre_set_autostart(self, event, name, newvalue,
  596. oldvalue=None):
  597. # pylint: disable=unused-argument
  598. # workaround https://bugzilla.redhat.com/show_bug.cgi?id=1181922
  599. if newvalue:
  600. retcode = subprocess.call(
  601. ["sudo", "ln", "-sf",
  602. "/usr/lib/systemd/system/qubes-vm@.service",
  603. "/etc/systemd/system/multi-user.target.wants/qubes-vm@"
  604. "{}.service".format(self.name)])
  605. else:
  606. retcode = subprocess.call(
  607. ['sudo', 'systemctl', 'disable',
  608. 'qubes-vm@{}.service'.format(self.name)])
  609. if retcode:
  610. raise qubes.exc.QubesException(
  611. 'Failed to set autostart for VM in systemd')
  612. @qubes.events.handler('property-pre-del:autostart')
  613. def on_property_pre_del_autostart(self, event, name, oldvalue=None):
  614. # pylint: disable=unused-argument
  615. if oldvalue:
  616. retcode = subprocess.call(
  617. ['sudo', 'systemctl', 'disable',
  618. 'qubes-vm@{}.service'.format(self.name)])
  619. if retcode:
  620. raise qubes.exc.QubesException(
  621. 'Failed to reset autostart for VM in systemd')
  622. #
  623. # methods for changing domain state
  624. #
  625. @asyncio.coroutine
  626. def start(self, start_guid=True, notify_function=None,
  627. mem_required=None):
  628. '''Start domain
  629. :param bool start_guid: FIXME
  630. :param collections.Callable notify_function: FIXME
  631. :param int mem_required: FIXME
  632. '''
  633. with (yield from self.startup_lock):
  634. # Intentionally not used is_running(): eliminate also "Paused",
  635. # "Crashed", "Halting"
  636. if self.get_power_state() != 'Halted':
  637. return self
  638. with (yield from self._domain_stopped_lock):
  639. # Don't accept any new stopped event's till a new VM has been
  640. # created. If we didn't received any stopped event or it wasn't
  641. # handled yet we will handle this in the next lines.
  642. self._domain_stopped_event_received = True
  643. if self._domain_stopped_future is not None:
  644. # Libvirt stopped event was already received, so cancel the
  645. # future. If it didn't generate the Qubes events yet we
  646. # will do it below.
  647. self._domain_stopped_future.cancel()
  648. self._domain_stopped_future = None
  649. if not self._domain_stopped_event_handled:
  650. # No Qubes domain-stopped events have been generated yet.
  651. # So do this now.
  652. # Set this immediately such that we don't generate events
  653. # twice if an exception gets thrown.
  654. self._domain_stopped_event_handled = True
  655. yield from self.fire_event_async('domain-stopped')
  656. yield from self.fire_event_async('domain-shutdown')
  657. self.log.info('Starting {}'.format(self.name))
  658. yield from self.fire_event_async('domain-pre-start',
  659. pre_event=True,
  660. start_guid=start_guid, mem_required=mem_required)
  661. qmemman_client = None
  662. try:
  663. yield from self.storage.verify()
  664. if self.netvm is not None:
  665. # pylint: disable = no-member
  666. if self.netvm.qid != 0:
  667. if not self.netvm.is_running():
  668. yield from self.netvm.start(start_guid=start_guid,
  669. notify_function=notify_function)
  670. qmemman_client = yield from asyncio.get_event_loop().\
  671. run_in_executor(None, self.request_memory, mem_required)
  672. yield from self.storage.start()
  673. except Exception as exc:
  674. # let anyone receiving domain-pre-start know that startup failed
  675. yield from self.fire_event_async('domain-start-failed',
  676. reason=str(exc))
  677. if qmemman_client:
  678. qmemman_client.close()
  679. raise
  680. try:
  681. self._update_libvirt_domain()
  682. self.libvirt_domain.createWithFlags(
  683. libvirt.VIR_DOMAIN_START_PAUSED)
  684. except Exception as exc:
  685. self.log.error('Start failed: %s', str(exc))
  686. # let anyone receiving domain-pre-start know that startup failed
  687. yield from self.fire_event_async('domain-start-failed',
  688. reason=str(exc))
  689. yield from self.storage.stop()
  690. raise
  691. finally:
  692. if qmemman_client:
  693. qmemman_client.close()
  694. self._domain_stopped_event_received = False
  695. self._domain_stopped_event_handled = False
  696. try:
  697. yield from self.fire_event_async('domain-spawn',
  698. start_guid=start_guid)
  699. self.log.info('Setting Qubes DB info for the VM')
  700. yield from self.start_qubesdb()
  701. self.create_qdb_entries()
  702. self.start_qdb_watch()
  703. self.log.warning('Activating the {} VM'.format(self.name))
  704. self.libvirt_domain.resume()
  705. yield from self.start_qrexec_daemon()
  706. yield from self.fire_event_async('domain-start',
  707. start_guid=start_guid)
  708. except Exception as exc: # pylint: disable=bare-except
  709. self.log.error('Start failed: %s', str(exc))
  710. if self.is_running() or self.is_paused():
  711. # This avoids losing the exception if an exception is
  712. # raised in self.force_shutdown(), because the vm is not
  713. # running or paused
  714. yield from self.kill() # pylint: disable=not-an-iterable
  715. # let anyone receiving domain-pre-start know that startup failed
  716. yield from self.fire_event_async('domain-start-failed',
  717. reason=str(exc))
  718. raise
  719. return self
  720. def on_libvirt_domain_stopped(self):
  721. ''' Handle VIR_DOMAIN_EVENT_STOPPED events from libvirt.
  722. This is not a Qubes event handler. Instead we do some sanity checks
  723. and synchronization with start() and then emits Qubes events.
  724. '''
  725. state = self.get_power_state()
  726. if state not in ['Halted', 'Crashed', 'Dying']:
  727. self.log.warning('Stopped event from libvirt received,'
  728. ' but domain is in state {}!'.format(state))
  729. # ignore this unexpected event
  730. return
  731. if self._domain_stopped_event_received:
  732. self.log.warning('Duplicated stopped event from libvirt received!')
  733. # ignore this unexpected event
  734. return
  735. self._domain_stopped_event_received = True
  736. self._domain_stopped_future = \
  737. asyncio.ensure_future(self._domain_stopped_coro())
  738. @asyncio.coroutine
  739. def _domain_stopped_coro(self):
  740. with (yield from self._domain_stopped_lock):
  741. assert not self._domain_stopped_event_handled
  742. # Set this immediately such that we don't generate events twice if
  743. # an exception gets thrown.
  744. self._domain_stopped_event_handled = True
  745. yield from self.fire_event_async('domain-stopped')
  746. yield from self.fire_event_async('domain-shutdown')
  747. @qubes.events.handler('domain-stopped')
  748. @asyncio.coroutine
  749. def on_domain_stopped(self, _event, **_kwargs):
  750. '''Cleanup after domain was stopped'''
  751. try:
  752. yield from self.storage.stop()
  753. except qubes.storage.StoragePoolException:
  754. self.log.exception('Failed to stop storage for domain %s',
  755. self.name)
  756. @asyncio.coroutine
  757. def shutdown(self, force=False, wait=False):
  758. '''Shutdown domain.
  759. :raises qubes.exc.QubesVMNotStartedError: \
  760. when domain is already shut down.
  761. '''
  762. if self.is_halted():
  763. raise qubes.exc.QubesVMNotStartedError(self)
  764. yield from self.fire_event_async('domain-pre-shutdown', pre_event=True,
  765. force=force)
  766. self.libvirt_domain.shutdown()
  767. while wait and not self.is_halted():
  768. yield from asyncio.sleep(0.25)
  769. return self
  770. @asyncio.coroutine
  771. def kill(self):
  772. '''Forcefuly shutdown (destroy) domain.
  773. :raises qubes.exc.QubesVMNotStartedError: \
  774. when domain is already shut down.
  775. '''
  776. if not self.is_running() and not self.is_paused():
  777. raise qubes.exc.QubesVMNotStartedError(self)
  778. self.libvirt_domain.destroy()
  779. return self
  780. def force_shutdown(self, *args, **kwargs):
  781. '''Deprecated alias for :py:meth:`kill`'''
  782. warnings.warn(
  783. 'Call to deprecated function force_shutdown(), use kill() instead',
  784. DeprecationWarning, stacklevel=2)
  785. return self.kill(*args, **kwargs)
  786. @asyncio.coroutine
  787. def suspend(self):
  788. '''Suspend (pause) domain.
  789. :raises qubes.exc.QubesVMNotRunnignError: \
  790. when domain is already shut down.
  791. '''
  792. if not self.is_running() and not self.is_paused():
  793. raise qubes.exc.QubesVMNotRunningError(self)
  794. if list(self.devices['pci'].attached()):
  795. yield from self.run_service_for_stdio('qubes.SuspendPre',
  796. user='root')
  797. self.libvirt_domain.pMSuspendForDuration(
  798. libvirt.VIR_NODE_SUSPEND_TARGET_MEM, 0, 0)
  799. else:
  800. self.libvirt_domain.suspend()
  801. return self
  802. @asyncio.coroutine
  803. def pause(self):
  804. '''Pause (suspend) domain.'''
  805. if not self.is_running():
  806. raise qubes.exc.QubesVMNotRunningError(self)
  807. self.libvirt_domain.suspend()
  808. return self
  809. @asyncio.coroutine
  810. def resume(self):
  811. '''Resume suspended domain.
  812. :raises qubes.exc.QubesVMNotSuspendedError: when machine is not paused
  813. :raises qubes.exc.QubesVMError: when machine is suspended
  814. '''
  815. # pylint: disable=not-an-iterable
  816. if self.get_power_state() == "Suspended":
  817. self.libvirt_domain.pMWakeup()
  818. yield from self.run_service_for_stdio('qubes.SuspendPost',
  819. user='root')
  820. else:
  821. yield from self.unpause()
  822. return self
  823. @asyncio.coroutine
  824. def unpause(self):
  825. '''Resume (unpause) a domain'''
  826. if not self.is_paused():
  827. raise qubes.exc.QubesVMNotPausedError(self)
  828. self.libvirt_domain.resume()
  829. return self
  830. @asyncio.coroutine
  831. def run_service(self, service, source=None, user=None,
  832. filter_esc=False, autostart=False, gui=False, **kwargs):
  833. '''Run service on this VM
  834. :param str service: service name
  835. :param qubes.vm.qubesvm.QubesVM source: source domain as presented to
  836. this VM
  837. :param str user: username to run service as
  838. :param bool filter_esc: filter escape sequences to protect terminal \
  839. emulator
  840. :param bool autostart: if :py:obj:`True`, machine will be started if \
  841. it is not running
  842. :param bool gui: when autostarting, also start gui daemon
  843. :rtype: asyncio.subprocess.Process
  844. .. note::
  845. User ``root`` is redefined to ``SYSTEM`` in the Windows agent code
  846. '''
  847. # UNSUPPORTED from previous incarnation:
  848. # localcmd, wait, passio*, notify_function, `-e` switch
  849. #
  850. # - passio* and friends depend on params to command (like in stdlib)
  851. # - the filter_esc is orthogonal to passio*
  852. # - input: see run_service_for_stdio
  853. # - wait has no purpose since this is asynchronous
  854. # - notify_function is gone
  855. source = 'dom0' if source is None else self.app.domains[source].name
  856. if user is None:
  857. user = self.default_user
  858. if self.is_paused():
  859. # XXX what about autostart?
  860. raise qubes.exc.QubesVMNotRunningError(
  861. self, 'Domain {!r} is paused'.format(self.name))
  862. elif not self.is_running():
  863. if not autostart:
  864. raise qubes.exc.QubesVMNotRunningError(self)
  865. yield from self.start(start_guid=gui)
  866. if not self.is_qrexec_running():
  867. raise qubes.exc.QubesVMError(
  868. self, 'Domain {!r}: qrexec not connected'.format(self.name))
  869. yield from self.fire_event_async('domain-cmd-pre-run', pre_event=True,
  870. start_guid=gui)
  871. return (yield from asyncio.create_subprocess_exec(
  872. qubes.config.system_path['qrexec_client_path'],
  873. '-d', str(self.name),
  874. *(('-t', '-T') if filter_esc else ()),
  875. '{}:QUBESRPC {} {}'.format(user, service, source),
  876. **kwargs))
  877. @asyncio.coroutine
  878. def run_service_for_stdio(self, *args, input=None, **kwargs):
  879. '''Run a service, pass an optional input and return (stdout, stderr).
  880. Raises an exception if return code != 0.
  881. *args* and *kwargs* are passed verbatim to :py:meth:`run_service`.
  882. .. warning::
  883. There are some combinations if stdio-related *kwargs*, which are
  884. not filtered for problems originating between the keyboard and the
  885. chair.
  886. ''' # pylint: disable=redefined-builtin
  887. kwargs.setdefault('stdin', subprocess.PIPE)
  888. kwargs.setdefault('stdout', subprocess.PIPE)
  889. kwargs.setdefault('stderr', subprocess.PIPE)
  890. p = yield from self.run_service(*args, **kwargs)
  891. # this one is actually a tuple, but there is no need to unpack it
  892. stdouterr = yield from p.communicate(input=input)
  893. if p.returncode:
  894. raise subprocess.CalledProcessError(p.returncode,
  895. args[0], *stdouterr)
  896. return stdouterr
  897. @staticmethod
  898. def _prepare_input_for_vmshell(command, input):
  899. '''Prepare shell input for the given command and optional (real) input
  900. ''' # pylint: disable=redefined-builtin
  901. if input is None:
  902. input = b''
  903. return b''.join((command.rstrip('\n').encode('utf-8'), b'\n', input))
  904. def run(self, command, user=None, **kwargs):
  905. '''Run a shell command inside the domain using qrexec.
  906. This method is a coroutine.
  907. ''' # pylint: disable=redefined-builtin
  908. if user is None:
  909. user = self.default_user
  910. return asyncio.create_subprocess_exec(
  911. qubes.config.system_path['qrexec_client_path'],
  912. '-d', str(self.name),
  913. '{}:{}'.format(user, command),
  914. **kwargs)
  915. @asyncio.coroutine
  916. def run_for_stdio(self, *args, input=None, **kwargs):
  917. '''Run a shell command inside the domain using qubes.VMShell qrexec.
  918. This method is a coroutine.
  919. *kwargs* are passed verbatim to :py:meth:`run_service_for_stdio`.
  920. See disclaimer there.
  921. ''' # pylint: disable=redefined-builtin
  922. kwargs.setdefault('stdin', subprocess.PIPE)
  923. kwargs.setdefault('stdout', subprocess.PIPE)
  924. kwargs.setdefault('stderr', subprocess.PIPE)
  925. p = yield from self.run(*args, **kwargs)
  926. stdouterr = yield from p.communicate(input=input)
  927. if p.returncode:
  928. raise subprocess.CalledProcessError(p.returncode,
  929. args[0], *stdouterr)
  930. return stdouterr
  931. def request_memory(self, mem_required=None):
  932. # overhead of per-qube/per-vcpu Xen structures,
  933. # taken from OpenStack nova/virt/xenapi/driver.py
  934. # see https://wiki.openstack.org/wiki/XenServer/Overhead
  935. # add an extra MB because Nova rounds up to MBs
  936. if not qmemman_present:
  937. return None
  938. if mem_required is None:
  939. if self.virt_mode == 'hvm':
  940. if self.stubdom_mem:
  941. stubdom_mem = self.stubdom_mem
  942. else:
  943. if self.features.check_with_template('linux-stubdom', True):
  944. stubdom_mem = 128 # from libxl_create.c
  945. else:
  946. stubdom_mem = 28 # from libxl_create.c
  947. stubdom_mem += 16 # video ram
  948. else:
  949. stubdom_mem = 0
  950. initial_memory = self.memory
  951. if self.virt_mode == 'hvm' and self.devices['pci'].persistent():
  952. # HVM with PCI devices does not support populate-on-demand on
  953. # Xen
  954. initial_memory = self.maxmem
  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)
  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)
  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. def get_start_time(self):
  1368. '''Tell when machine was started.
  1369. :rtype: datetime.datetime
  1370. '''
  1371. if not self.is_running():
  1372. return None
  1373. # TODO shouldn't this be qubesdb?
  1374. start_time = self.app.vmm.xs.read('',
  1375. '/vm/{}/start_time'.format(self.uuid))
  1376. if start_time != '':
  1377. return datetime.datetime.fromtimestamp(float(start_time))
  1378. return None
  1379. #
  1380. # helper methods
  1381. #
  1382. def relative_path(self, path):
  1383. '''Return path relative to py:attr:`dir_path`.
  1384. :param str path: Path in question.
  1385. :returns: Relative path.
  1386. '''
  1387. return os.path.relpath(path, self.dir_path)
  1388. def create_qdb_entries(self):
  1389. '''Create entries in Qubes DB.
  1390. '''
  1391. # pylint: disable=no-member
  1392. self.untrusted_qdb.write('/name', self.name)
  1393. self.untrusted_qdb.write('/type', self.__class__.__name__)
  1394. self.untrusted_qdb.write('/qubes-vm-updateable', str(self.updateable))
  1395. self.untrusted_qdb.write('/qubes-vm-persistence',
  1396. 'full' if self.updateable else 'rw-only')
  1397. self.untrusted_qdb.write('/qubes-debug-mode', str(int(self.debug)))
  1398. try:
  1399. self.untrusted_qdb.write('/qubes-base-template', self.template.name)
  1400. except AttributeError:
  1401. self.untrusted_qdb.write('/qubes-base-template', '')
  1402. self.untrusted_qdb.write('/qubes-random-seed',
  1403. base64.b64encode(qubes.utils.urandom(64)))
  1404. if self.provides_network:
  1405. # '/qubes-netvm-network' value is only checked for being non empty
  1406. self.untrusted_qdb.write('/qubes-netvm-network', str(self.gateway))
  1407. self.untrusted_qdb.write('/qubes-netvm-gateway', str(self.gateway))
  1408. if self.gateway6:
  1409. self.untrusted_qdb.write('/qubes-netvm-gateway6',
  1410. str(self.gateway6))
  1411. self.untrusted_qdb.write('/qubes-netvm-netmask', str(self.netmask))
  1412. for i, addr in zip(('primary', 'secondary'), self.dns):
  1413. self.untrusted_qdb.write('/qubes-netvm-{}-dns'.format(i), addr)
  1414. if self.netvm is not None:
  1415. self.untrusted_qdb.write('/qubes-ip', str(self.visible_ip))
  1416. self.untrusted_qdb.write('/qubes-netmask',
  1417. str(self.visible_netmask))
  1418. self.untrusted_qdb.write('/qubes-gateway',
  1419. str(self.visible_gateway))
  1420. for i, addr in zip(('primary', 'secondary'), self.dns):
  1421. self.untrusted_qdb.write('/qubes-{}-dns'.format(i), str(addr))
  1422. if self.visible_ip6:
  1423. self.untrusted_qdb.write('/qubes-ip6', str(self.visible_ip6))
  1424. if self.visible_gateway6:
  1425. self.untrusted_qdb.write('/qubes-gateway6',
  1426. str(self.visible_gateway6))
  1427. tzname = qubes.utils.get_timezone()
  1428. if tzname:
  1429. self.untrusted_qdb.write('/qubes-timezone', tzname)
  1430. self.untrusted_qdb.write('/qubes-block-devices', '')
  1431. self.untrusted_qdb.write('/qubes-usb-devices', '')
  1432. # TODO: Currently the whole qmemman is quite Xen-specific, so stay with
  1433. # xenstore for it until decided otherwise
  1434. if qmemman_present:
  1435. self.app.vmm.xs.set_permissions('',
  1436. '/local/domain/{}/memory'.format(self.xid),
  1437. [{'dom': self.xid}])
  1438. self.fire_event('domain-qdb-create')
  1439. # TODO async; update this in constructor
  1440. def _update_libvirt_domain(self):
  1441. '''Re-initialise :py:attr:`libvirt_domain`.'''
  1442. domain_config = self.create_config_file()
  1443. try:
  1444. self._libvirt_domain = self.app.vmm.libvirt_conn.defineXML(
  1445. domain_config)
  1446. except libvirt.libvirtError as e:
  1447. if e.get_error_code() == libvirt.VIR_ERR_OS_TYPE \
  1448. and e.get_str2() == 'hvm':
  1449. raise qubes.exc.QubesVMError(self,
  1450. 'HVM qubes are not supported on this machine. '
  1451. 'Check BIOS settings for VT-x/AMD-V extensions.')
  1452. else:
  1453. raise
  1454. #
  1455. # workshop -- those are to be reworked later
  1456. #
  1457. def get_prefmem(self):
  1458. # TODO: qmemman is still xen specific
  1459. untrusted_meminfo_key = self.app.vmm.xs.read('',
  1460. '/local/domain/{}/memory/meminfo'.format(self.xid))
  1461. if untrusted_meminfo_key is None or untrusted_meminfo_key == '':
  1462. return 0
  1463. domain = qubes.qmemman.DomainState(self.xid)
  1464. qubes.qmemman.algo.refresh_meminfo_for_domain(
  1465. domain, untrusted_meminfo_key)
  1466. if domain.mem_used is None:
  1467. # apparently invalid xenstore content
  1468. return 0
  1469. domain.memory_maximum = self.get_mem_static_max() * 1024
  1470. return qubes.qmemman.algo.prefmem(domain) / 1024
  1471. def _clean_volume_config(config):
  1472. common_attributes = ['name', 'pool', 'size',
  1473. 'revisions_to_keep', 'rw', 'snap_on_start',
  1474. 'save_on_stop', 'source']
  1475. return {k: v for k, v in config.items() if k in common_attributes}
  1476. def _patch_pool_config(config, pool=None, pools=None):
  1477. assert pool is not None or pools is not None
  1478. is_snapshot = config['snap_on_start']
  1479. is_rw = config['rw']
  1480. name = config['name']
  1481. if pool and not is_snapshot and is_rw:
  1482. config['pool'] = str(pool)
  1483. elif pool:
  1484. pass
  1485. elif pools and name in pools.keys():
  1486. if not is_snapshot:
  1487. config['pool'] = str(pools[name])
  1488. else:
  1489. msg = "Can't clone a snapshot volume {!s} to pool {!s} " \
  1490. .format(name, pools[name])
  1491. raise qubes.exc.QubesException(msg)
  1492. return config
  1493. def _patch_volume_config(volume_config, pool=None, pools=None):
  1494. assert not (pool and pools), \
  1495. 'You can not pass pool & pools parameter at same time'
  1496. assert pool or pools
  1497. result = {}
  1498. for name, config in volume_config.items():
  1499. # copy only the subset of volume_config key/values
  1500. dst_config = _clean_volume_config(config)
  1501. if pool is not None or pools is not None:
  1502. dst_config = _patch_pool_config(dst_config, pool, pools)
  1503. result[name] = dst_config
  1504. return result