qubesvm.py 81 KB

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