qubesvm.py 67 KB

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