qubesvm.py 81 KB

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