qubesvm.py 83 KB

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