qubesvm.py 81 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256
  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. if self.is_running():
  517. return self.libvirt_domain.ID()
  518. return -1
  519. except libvirt.libvirtError as e:
  520. if e.get_error_code() == libvirt.VIR_ERR_NO_DOMAIN:
  521. return -1
  522. self.log.exception('libvirt error code: {!r}'.format(
  523. e.get_error_code()))
  524. raise
  525. @qubes.stateless_property
  526. def stubdom_xid(self):
  527. if not self.is_running():
  528. return -1
  529. if self.app.vmm.xs is None:
  530. return -1
  531. stubdom_xid_str = self.app.vmm.xs.read(
  532. '', '/local/domain/{}/image/device-model-domid'.format(
  533. self.xid))
  534. if stubdom_xid_str is None or not stubdom_xid_str.isdigit():
  535. return -1
  536. return int(stubdom_xid_str)
  537. @property
  538. def attached_volumes(self):
  539. result = []
  540. xml_desc = self.libvirt_domain.XMLDesc()
  541. xml = lxml.etree.fromstring(xml_desc)
  542. for disk in xml.xpath("//domain/devices/disk"):
  543. if disk.find('backenddomain') is not None:
  544. pool_name = 'p_%s' % disk.find('backenddomain').get('name')
  545. pool = self.app.pools[pool_name]
  546. vid = disk.find('source').get('dev').split('/dev/')[1]
  547. for volume in pool.volumes:
  548. if volume.vid == vid:
  549. result += [volume]
  550. break
  551. return result + list(self.volumes.values())
  552. @property
  553. def libvirt_domain(self):
  554. """Libvirt domain object from libvirt.
  555. May be :py:obj:`None`, if libvirt knows nothing about this domain.
  556. """
  557. if self._libvirt_domain is not None:
  558. return self._libvirt_domain
  559. if self.app.vmm.offline_mode:
  560. return None
  561. # XXX _update_libvirt_domain?
  562. try:
  563. self._libvirt_domain = self.app.vmm.libvirt_conn.lookupByUUID(
  564. self.uuid.bytes)
  565. except libvirt.libvirtError as e:
  566. if e.get_error_code() == libvirt.VIR_ERR_NO_DOMAIN:
  567. self._update_libvirt_domain()
  568. else:
  569. raise
  570. return self._libvirt_domain
  571. @property
  572. def block_devices(self):
  573. """ Return all :py:class:`qubes.storage.BlockDevice` for current domain
  574. for serialization in the libvirt XML template as <disk>.
  575. """
  576. for v in self.volumes.values():
  577. block_dev = v.block_device()
  578. if block_dev is not None:
  579. yield block_dev
  580. @property
  581. def untrusted_qdb(self):
  582. """QubesDB handle for this domain."""
  583. if self._qdb_connection is None:
  584. if self.is_running():
  585. import qubesdb # pylint: disable=import-error
  586. self._qdb_connection = qubesdb.QubesDB(self.name)
  587. return self._qdb_connection
  588. @property
  589. def dir_path(self):
  590. """Root directory for files related to this domain"""
  591. return os.path.join(
  592. qubes.config.qubes_base_dir,
  593. self.dir_path_prefix,
  594. self.name)
  595. @property
  596. def icon_path(self):
  597. return os.path.join(self.dir_path, 'icon.png')
  598. @property
  599. def conf_file(self):
  600. return os.path.join(self.dir_path, 'libvirt.xml')
  601. # network-related
  602. #
  603. # constructor
  604. #
  605. def __init__(self, app, xml, volume_config=None, **kwargs):
  606. # migrate renamed properties
  607. if xml is not None:
  608. node_hvm = xml.find('./properties/property[@name=\'hvm\']')
  609. if node_hvm is not None:
  610. if qubes.property.bool(None, None, node_hvm.text):
  611. kwargs['virt_mode'] = 'hvm'
  612. else:
  613. kwargs['virt_mode'] = 'pv'
  614. node_hvm.getparent().remove(node_hvm)
  615. super(QubesVM, self).__init__(app, xml, **kwargs)
  616. if volume_config is None:
  617. volume_config = {}
  618. if hasattr(self, 'volume_config'):
  619. if xml is not None:
  620. for node in xml.xpath('volume-config/volume'):
  621. name = node.get('name')
  622. assert name
  623. for key, value in node.items():
  624. # pylint: disable=no-member
  625. if value == 'True':
  626. value = True
  627. try:
  628. self.volume_config[name][key] = value
  629. except KeyError:
  630. self.volume_config[name] = {key: value}
  631. for name, conf in volume_config.items():
  632. for key, value in conf.items():
  633. # pylint: disable=no-member
  634. try:
  635. self.volume_config[name][key] = value
  636. except KeyError:
  637. self.volume_config[name] = {key: value}
  638. elif volume_config:
  639. raise TypeError(
  640. 'volume_config specified, but {} did not expect that.'.format(
  641. self.__class__.__name__))
  642. # Init private attrs
  643. self._libvirt_domain = None
  644. self._qdb_connection = None
  645. # We assume a fully halted VM here. The 'domain-init' handler will
  646. # check if the VM is already running.
  647. self._domain_stopped_event_received = True
  648. self._domain_stopped_event_handled = True
  649. self._domain_stopped_future = None
  650. # Internal lock to ensure ordering between _domain_stopped_coro() and
  651. # start(). This should not be accessed anywhere else.
  652. self._domain_stopped_lock = asyncio.Lock()
  653. if xml is None:
  654. # we are creating new VM and attributes came through kwargs
  655. assert hasattr(self, 'qid')
  656. assert hasattr(self, 'name')
  657. if xml is None:
  658. # new qube, disable updates check if requested for new qubes
  659. # SEE: 1637 when features are done, migrate to plugin
  660. if not self.app.check_updates_vm:
  661. self.features['check-updates'] = False
  662. # will be initialized after loading all the properties
  663. #: operations which shouldn't happen simultaneously with qube startup
  664. # (including another startup of the same qube)
  665. self.startup_lock = asyncio.Lock()
  666. # fire hooks
  667. if xml is None:
  668. self.events_enabled = True
  669. self.fire_event('domain-init')
  670. def close(self):
  671. if self._qdb_connection is not None:
  672. self._qdb_connection.close()
  673. self._qdb_connection = None
  674. if self._libvirt_domain is not None:
  675. self._libvirt_domain = None
  676. super().close()
  677. def __hash__(self):
  678. return self.qid
  679. def __lt__(self, other):
  680. return self.name < other.name
  681. def __xml__(self):
  682. # pylint: disable=no-member
  683. element = super(QubesVM, self).__xml__()
  684. # pylint: enable=no-member
  685. if hasattr(self, 'volumes'):
  686. volume_config_node = lxml.etree.Element('volume-config')
  687. for volume in self.volumes.values():
  688. volume_config_node.append(volume.__xml__())
  689. element.append(volume_config_node)
  690. return element
  691. #
  692. # event handlers
  693. #
  694. @qubes.events.handler('domain-init', 'domain-load')
  695. def on_domain_init_loaded(self, event):
  696. # pylint: disable=unused-argument
  697. if not hasattr(self, 'uuid'):
  698. # pylint: disable=attribute-defined-outside-init
  699. self.uuid = uuid.uuid4()
  700. # Initialize VM image storage class;
  701. # it might be already initialized by a recursive call from a child VM
  702. if self.storage is None:
  703. self.storage = qubes.storage.Storage(self)
  704. if not self.app.vmm.offline_mode and self.is_running():
  705. self.start_qdb_watch()
  706. self._domain_stopped_event_received = False
  707. self._domain_stopped_event_handled = False
  708. @qubes.events.handler('property-set:label')
  709. def on_property_set_label(self, event, name, newvalue, oldvalue=None):
  710. # pylint: disable=unused-argument
  711. if self.icon_path:
  712. try:
  713. os.remove(self.icon_path)
  714. except OSError:
  715. pass
  716. if hasattr(os, "symlink"):
  717. os.symlink(newvalue.icon_path, self.icon_path)
  718. subprocess.call(['sudo', 'xdg-icon-resource', 'forceupdate'])
  719. else:
  720. shutil.copy(newvalue.icon_path, self.icon_path)
  721. @qubes.events.handler('property-pre-set:kernel')
  722. def on_property_pre_set_kernel(self, event, name, newvalue, oldvalue=None):
  723. # pylint: disable=unused-argument
  724. if not newvalue:
  725. return
  726. dirname = os.path.join(
  727. qubes.config.qubes_base_dir,
  728. qubes.config.system_path['qubes_kernels_base_dir'],
  729. newvalue)
  730. if not os.path.exists(dirname):
  731. raise qubes.exc.QubesPropertyValueError(
  732. self, self.property_get_def(name), newvalue,
  733. 'Kernel {!r} not installed'.format(
  734. newvalue))
  735. for filename in ('vmlinuz', 'initramfs'):
  736. if not os.path.exists(os.path.join(dirname, filename)):
  737. raise qubes.exc.QubesPropertyValueError(
  738. self, self.property_get_def(name), newvalue,
  739. 'Kernel {!r} not properly installed: '
  740. 'missing {!r} file'.format(
  741. newvalue, filename))
  742. @qubes.events.handler('property-pre-set:autostart')
  743. def on_property_pre_set_autostart(self, event, name, newvalue,
  744. oldvalue=None):
  745. # pylint: disable=unused-argument
  746. # workaround https://bugzilla.redhat.com/show_bug.cgi?id=1181922
  747. if newvalue:
  748. retcode = subprocess.call(
  749. ["sudo", "ln", "-sf",
  750. "/usr/lib/systemd/system/qubes-vm@.service",
  751. "/etc/systemd/system/multi-user.target.wants/qubes-vm@"
  752. "{}.service".format(self.name)])
  753. else:
  754. retcode = subprocess.call(
  755. ['sudo', 'systemctl', 'disable',
  756. 'qubes-vm@{}.service'.format(self.name)])
  757. if retcode:
  758. raise qubes.exc.QubesException(
  759. 'Failed to set autostart for VM in systemd')
  760. @qubes.events.handler('property-pre-del:autostart')
  761. def on_property_pre_del_autostart(self, event, name, oldvalue=None):
  762. # pylint: disable=unused-argument
  763. if oldvalue:
  764. retcode = subprocess.call(
  765. ['sudo', 'systemctl', 'disable',
  766. 'qubes-vm@{}.service'.format(self.name)])
  767. if retcode:
  768. raise qubes.exc.QubesException(
  769. 'Failed to reset autostart for VM in systemd')
  770. @qubes.events.handler('domain-remove-from-disk')
  771. def on_remove_from_disk(self, event, **kwargs):
  772. # pylint: disable=unused-argument
  773. if self.autostart:
  774. subprocess.call(
  775. ['sudo', 'systemctl', 'disable',
  776. 'qubes-vm@{}.service'.format(self.name)])
  777. @qubes.events.handler('domain-create-on-disk')
  778. def on_create_on_disk(self, event, **kwargs):
  779. # pylint: disable=unused-argument
  780. if self.autostart:
  781. subprocess.call(
  782. ['sudo', 'systemctl', 'enable',
  783. 'qubes-vm@{}.service'.format(self.name)])
  784. #
  785. # methods for changing domain state
  786. #
  787. @asyncio.coroutine
  788. def _ensure_shutdown_handled(self):
  789. """Make sure previous shutdown is fully handled.
  790. MUST NOT be called when domain is running.
  791. """
  792. with (yield from self._domain_stopped_lock):
  793. # Don't accept any new stopped event's till a new VM has been
  794. # created. If we didn't received any stopped event or it wasn't
  795. # handled yet we will handle this in the next lines.
  796. self._domain_stopped_event_received = True
  797. if self._domain_stopped_future is not None:
  798. # Libvirt stopped event was already received, so cancel the
  799. # future. If it didn't generate the Qubes events yet we
  800. # will do it below.
  801. self._domain_stopped_future.cancel()
  802. self._domain_stopped_future = None
  803. if not self._domain_stopped_event_handled:
  804. # No Qubes domain-stopped events have been generated yet.
  805. # So do this now.
  806. # Set this immediately such that we don't generate events
  807. # twice if an exception gets thrown.
  808. self._domain_stopped_event_handled = True
  809. yield from self.fire_event_async('domain-stopped')
  810. yield from self.fire_event_async('domain-shutdown')
  811. @asyncio.coroutine
  812. def start(self, start_guid=True, notify_function=None,
  813. mem_required=None):
  814. """Start domain
  815. :param bool start_guid: FIXME
  816. :param collections.Callable notify_function: FIXME
  817. :param int mem_required: FIXME
  818. """
  819. with (yield from self.startup_lock):
  820. # check if domain wasn't removed in the meantime
  821. if self not in self.app.domains:
  822. raise qubes.exc.QubesVMNotFoundError(self.name)
  823. # Intentionally not used is_running(): eliminate also "Paused",
  824. # "Crashed", "Halting"
  825. if self.get_power_state() != 'Halted':
  826. return self
  827. yield from self._ensure_shutdown_handled()
  828. self.log.info('Starting {}'.format(self.name))
  829. try:
  830. yield from self.fire_event_async('domain-pre-start',
  831. pre_event=True,
  832. start_guid=start_guid,
  833. mem_required=mem_required)
  834. except Exception as exc:
  835. self.log.error('Start failed: %s', str(exc))
  836. yield from self.fire_event_async('domain-start-failed',
  837. reason=str(exc))
  838. raise
  839. qmemman_client = None
  840. try:
  841. for devclass in self.devices:
  842. for dev in self.devices[devclass].persistent():
  843. if isinstance(dev, qubes.devices.UnknownDevice):
  844. raise qubes.exc.QubesException(
  845. '{} device {} not available'.format(
  846. devclass, dev))
  847. if self.virt_mode == 'pvh' and not self.kernel:
  848. raise qubes.exc.QubesException(
  849. 'virt_mode PVH require kernel to be set')
  850. yield from self.storage.verify()
  851. if self.netvm is not None:
  852. # pylint: disable = no-member
  853. if self.netvm.qid != 0:
  854. if not self.netvm.is_running():
  855. yield from self.netvm.start(
  856. start_guid=start_guid,
  857. notify_function=notify_function)
  858. qmemman_client = yield from asyncio.get_event_loop(). \
  859. run_in_executor(None, self.request_memory, mem_required)
  860. yield from self.storage.start()
  861. except Exception as exc:
  862. self.log.error('Start failed: %s', str(exc))
  863. # let anyone receiving domain-pre-start know that startup failed
  864. yield from self.fire_event_async('domain-start-failed',
  865. reason=str(exc))
  866. if qmemman_client:
  867. qmemman_client.close()
  868. raise
  869. try:
  870. self._update_libvirt_domain()
  871. self.libvirt_domain.createWithFlags(
  872. libvirt.VIR_DOMAIN_START_PAUSED)
  873. except libvirt.libvirtError as exc:
  874. # missing IOMMU?
  875. if self.virt_mode == 'hvm' and \
  876. list(self.devices['pci'].persistent()) and \
  877. not self.app.host.is_iommu_supported():
  878. exc = qubes.exc.QubesException(
  879. 'Failed to start an HVM qube with PCI devices assigned '
  880. '- hardware does not support IOMMU/VT-d/AMD-Vi')
  881. self.log.error('Start failed: %s', str(exc))
  882. yield from self.fire_event_async('domain-start-failed',
  883. reason=str(exc))
  884. yield from self.storage.stop()
  885. raise exc
  886. except Exception as exc:
  887. self.log.error('Start failed: %s', str(exc))
  888. # let anyone receiving domain-pre-start know that startup failed
  889. yield from self.fire_event_async('domain-start-failed',
  890. reason=str(exc))
  891. yield from self.storage.stop()
  892. raise
  893. finally:
  894. if qmemman_client:
  895. qmemman_client.close()
  896. self._domain_stopped_event_received = False
  897. self._domain_stopped_event_handled = False
  898. try:
  899. yield from self.fire_event_async('domain-spawn',
  900. start_guid=start_guid)
  901. self.log.info('Setting Qubes DB info for the VM')
  902. yield from self.start_qubesdb()
  903. self.create_qdb_entries()
  904. self.start_qdb_watch()
  905. self.log.warning('Activating the {} VM'.format(self.name))
  906. self.libvirt_domain.resume()
  907. yield from self.start_qrexec_daemon()
  908. yield from self.fire_event_async('domain-start',
  909. start_guid=start_guid)
  910. except Exception as exc: # pylint: disable=bare-except
  911. self.log.error('Start failed: %s', str(exc))
  912. # This avoids losing the exception if an exception is
  913. # raised in self._kill_locked(), because the vm is not
  914. # running or paused
  915. try:
  916. yield from self._kill_locked()
  917. except qubes.exc.QubesVMNotStartedError:
  918. pass
  919. # let anyone receiving domain-pre-start know that startup failed
  920. yield from self.fire_event_async('domain-start-failed',
  921. reason=str(exc))
  922. raise
  923. return self
  924. def on_libvirt_domain_stopped(self):
  925. """ Handle VIR_DOMAIN_EVENT_STOPPED events from libvirt.
  926. This is not a Qubes event handler. Instead we do some sanity checks
  927. and synchronization with start() and then emits Qubes events.
  928. """
  929. state = self.get_power_state()
  930. if state not in ['Halted', 'Crashed', 'Dying']:
  931. self.log.warning('Stopped event from libvirt received,'
  932. ' but domain is in state {}!'.format(state))
  933. # ignore this unexpected event
  934. return
  935. if self._domain_stopped_event_received:
  936. # ignore this event - already triggered by shutdown(), kill(),
  937. # or subsequent start()
  938. return
  939. self._domain_stopped_event_received = True
  940. self._domain_stopped_future = \
  941. asyncio.ensure_future(self._domain_stopped_coro())
  942. @asyncio.coroutine
  943. def _domain_stopped_coro(self):
  944. with (yield from self._domain_stopped_lock):
  945. assert not self._domain_stopped_event_handled
  946. # Set this immediately such that we don't generate events twice if
  947. # an exception gets thrown.
  948. self._domain_stopped_event_handled = True
  949. while self.get_power_state() == 'Dying':
  950. yield from asyncio.sleep(0.25)
  951. yield from self.fire_event_async('domain-stopped')
  952. yield from self.fire_event_async('domain-shutdown')
  953. @qubes.events.handler('domain-stopped')
  954. @asyncio.coroutine
  955. def on_domain_stopped(self, _event, **_kwargs):
  956. """Cleanup after domain was stopped"""
  957. try:
  958. yield from self.storage.stop()
  959. except qubes.storage.StoragePoolException:
  960. self.log.exception('Failed to stop storage for domain %s',
  961. self.name)
  962. @asyncio.coroutine
  963. def shutdown(self, force=False, wait=False, timeout=None):
  964. """Shutdown domain.
  965. :param force: ignored
  966. :param wait: wait for shutdown to complete
  967. :param timeout: shutdown wait timeout (for *wait*=True), defaults to
  968. :py:attr:`shutdown_timeout`
  969. :raises qubes.exc.QubesVMNotStartedError: \
  970. when domain is already shut down.
  971. """
  972. if self.is_halted():
  973. raise qubes.exc.QubesVMNotStartedError(self)
  974. try:
  975. yield from self.fire_event_async('domain-pre-shutdown',
  976. pre_event=True, force=force)
  977. self.libvirt_domain.shutdown()
  978. if wait:
  979. if timeout is None:
  980. timeout = self.shutdown_timeout
  981. while timeout > 0 and not self.is_halted():
  982. yield from asyncio.sleep(0.25)
  983. timeout -= 0.25
  984. with (yield from self.startup_lock):
  985. if self.is_halted():
  986. # make sure all shutdown tasks are completed
  987. yield from self._ensure_shutdown_handled()
  988. else:
  989. raise qubes.exc.QubesVMShutdownTimeoutError(self)
  990. except Exception as ex:
  991. yield from self.fire_event_async('domain-shutdown-failed',
  992. reason=str(ex))
  993. raise
  994. return self
  995. @asyncio.coroutine
  996. def kill(self):
  997. """Forcefully shutdown (destroy) domain.
  998. :raises qubes.exc.QubesVMNotStartedError: \
  999. when domain is already shut down.
  1000. """
  1001. if not self.is_running() and not self.is_paused():
  1002. raise qubes.exc.QubesVMNotStartedError(self)
  1003. with (yield from self.startup_lock):
  1004. yield from self._kill_locked()
  1005. return self
  1006. @asyncio.coroutine
  1007. def _kill_locked(self):
  1008. """Forcefully shutdown (destroy) domain.
  1009. This function needs to be called with self.startup_lock held."""
  1010. try:
  1011. self.libvirt_domain.destroy()
  1012. except libvirt.libvirtError as e:
  1013. if e.get_error_code() == libvirt.VIR_ERR_OPERATION_INVALID:
  1014. raise qubes.exc.QubesVMNotStartedError(self)
  1015. raise
  1016. # make sure all shutdown tasks are completed
  1017. yield from self._ensure_shutdown_handled()
  1018. @asyncio.coroutine
  1019. def suspend(self):
  1020. """Suspend (pause) domain.
  1021. :raises qubes.exc.QubesVMNotRunnignError: \
  1022. when domain is already shut down.
  1023. """
  1024. if not self.is_running() and not self.is_paused():
  1025. raise qubes.exc.QubesVMNotRunningError(self)
  1026. if list(self.devices['pci'].attached()):
  1027. if self.features.check_with_template('qrexec', False):
  1028. yield from self.run_service_for_stdio('qubes.SuspendPre',
  1029. user='root')
  1030. self.libvirt_domain.pMSuspendForDuration(
  1031. libvirt.VIR_NODE_SUSPEND_TARGET_MEM, 0, 0)
  1032. else:
  1033. self.libvirt_domain.suspend()
  1034. return self
  1035. @asyncio.coroutine
  1036. def pause(self):
  1037. """Pause (suspend) domain."""
  1038. if not self.is_running():
  1039. raise qubes.exc.QubesVMNotRunningError(self)
  1040. self.libvirt_domain.suspend()
  1041. return self
  1042. @asyncio.coroutine
  1043. def resume(self):
  1044. """Resume suspended domain.
  1045. :raises qubes.exc.QubesVMNotSuspendedError: when machine is not paused
  1046. :raises qubes.exc.QubesVMError: when machine is suspended
  1047. """
  1048. # pylint: disable=not-an-iterable
  1049. if self.get_power_state() == "Suspended":
  1050. self.libvirt_domain.pMWakeup()
  1051. if self.features.check_with_template('qrexec', False):
  1052. yield from self.run_service_for_stdio('qubes.SuspendPost',
  1053. user='root')
  1054. else:
  1055. yield from self.unpause()
  1056. return self
  1057. @asyncio.coroutine
  1058. def unpause(self):
  1059. """Resume (unpause) a domain"""
  1060. if not self.is_paused():
  1061. raise qubes.exc.QubesVMNotPausedError(self)
  1062. self.libvirt_domain.resume()
  1063. return self
  1064. @asyncio.coroutine
  1065. def run_service(self, service, source=None, user=None,
  1066. filter_esc=False, autostart=False, gui=False, **kwargs):
  1067. """Run service on this VM
  1068. :param str service: service name
  1069. :param qubes.vm.qubesvm.QubesVM source: source domain as presented to
  1070. this VM
  1071. :param str user: username to run service as
  1072. :param bool filter_esc: filter escape sequences to protect terminal \
  1073. emulator
  1074. :param bool autostart: if :py:obj:`True`, machine will be started if \
  1075. it is not running
  1076. :param bool gui: when autostarting, also start gui daemon
  1077. :rtype: asyncio.subprocess.Process
  1078. .. note::
  1079. User ``root`` is redefined to ``SYSTEM`` in the Windows agent code
  1080. """
  1081. # UNSUPPORTED from previous incarnation:
  1082. # localcmd, wait, passio*, notify_function, `-e` switch
  1083. #
  1084. # - passio* and friends depend on params to command (like in stdlib)
  1085. # - the filter_esc is orthogonal to passio*
  1086. # - input: see run_service_for_stdio
  1087. # - wait has no purpose since this is asynchronous
  1088. # - notify_function is gone
  1089. source = 'dom0' if source is None else self.app.domains[source].name
  1090. if user is None:
  1091. user = self.default_user
  1092. if self.is_paused():
  1093. # XXX what about autostart?
  1094. raise qubes.exc.QubesVMNotRunningError(
  1095. self, 'Domain {!r} is paused'.format(self.name))
  1096. if not self.is_running():
  1097. if not autostart:
  1098. raise qubes.exc.QubesVMNotRunningError(self)
  1099. yield from self.start(start_guid=gui)
  1100. if not self.is_qrexec_running():
  1101. raise qubes.exc.QubesVMError(
  1102. self, 'Domain {!r}: qrexec not connected'.format(self.name))
  1103. yield from self.fire_event_async('domain-cmd-pre-run', pre_event=True,
  1104. start_guid=gui)
  1105. return (yield from asyncio.create_subprocess_exec(
  1106. qubes.config.system_path['qrexec_client_path'],
  1107. '-d', str(self.name),
  1108. *(('-t', '-T') if filter_esc else ()),
  1109. '{}:QUBESRPC {} {}'.format(user, service, source),
  1110. **kwargs))
  1111. @asyncio.coroutine
  1112. def run_service_for_stdio(self, *args, input=None, **kwargs):
  1113. """Run a service, pass an optional input and return (stdout, stderr).
  1114. Raises an exception if return code != 0.
  1115. *args* and *kwargs* are passed verbatim to :py:meth:`run_service`.
  1116. .. warning::
  1117. There are some combinations if stdio-related *kwargs*, which are
  1118. not filtered for problems originating between the keyboard and the
  1119. chair.
  1120. """ # pylint: disable=redefined-builtin
  1121. kwargs.setdefault('stdin', subprocess.PIPE)
  1122. kwargs.setdefault('stdout', subprocess.PIPE)
  1123. kwargs.setdefault('stderr', subprocess.PIPE)
  1124. p = yield from self.run_service(*args, **kwargs)
  1125. # this one is actually a tuple, but there is no need to unpack it
  1126. stdouterr = yield from p.communicate(input=input)
  1127. if p.returncode:
  1128. raise subprocess.CalledProcessError(p.returncode,
  1129. args[0], *stdouterr)
  1130. return stdouterr
  1131. def run(self, command, user=None, **kwargs):
  1132. """Run a shell command inside the domain using qrexec.
  1133. This method is a coroutine.
  1134. """ # pylint: disable=redefined-builtin
  1135. if user is None:
  1136. user = self.default_user
  1137. return asyncio.create_subprocess_exec(
  1138. qubes.config.system_path['qrexec_client_path'],
  1139. '-d', str(self.name),
  1140. '{}:{}'.format(user, command),
  1141. **kwargs)
  1142. @asyncio.coroutine
  1143. def run_for_stdio(self, *args, input=None, **kwargs):
  1144. """Run a shell command inside the domain using qrexec.
  1145. This method is a coroutine.
  1146. """ # pylint: disable=redefined-builtin
  1147. kwargs.setdefault('stdin', subprocess.PIPE)
  1148. kwargs.setdefault('stdout', subprocess.PIPE)
  1149. kwargs.setdefault('stderr', subprocess.PIPE)
  1150. p = yield from self.run(*args, **kwargs)
  1151. stdouterr = yield from p.communicate(input=input)
  1152. if p.returncode:
  1153. raise subprocess.CalledProcessError(p.returncode,
  1154. args[0], *stdouterr)
  1155. return stdouterr
  1156. def is_memory_balancing_possible(self):
  1157. """Check if memory balancing can be enabled.
  1158. Reasons to not enable it:
  1159. - have PCI devices
  1160. - balloon driver not present
  1161. We don't have reliable way to detect the second point, but good
  1162. heuristic is HVM virt_mode (PV and PVH require OS support and it does
  1163. include balloon driver) and lack of qrexec/meminfo-writer service
  1164. support (no qubes tools installed).
  1165. """
  1166. if list(self.devices['pci'].persistent()):
  1167. return False
  1168. if self.virt_mode == 'hvm':
  1169. # if VM announce any supported service
  1170. features_set = set(self.features)
  1171. template = getattr(self, 'template', None)
  1172. while template is not None:
  1173. features_set.update(template.features)
  1174. template = getattr(template, 'template', None)
  1175. supported_services = any(f.startswith('supported-service.')
  1176. for f in features_set)
  1177. if (not self.features.check_with_template('qrexec', False) or
  1178. (supported_services and
  1179. not self.features.check_with_template(
  1180. 'supported-service.meminfo-writer', False))):
  1181. return False
  1182. return True
  1183. def request_memory(self, mem_required=None):
  1184. if not qmemman_present:
  1185. return None
  1186. if mem_required is None:
  1187. if self.virt_mode == 'hvm':
  1188. if self.stubdom_mem:
  1189. stubdom_mem = self.stubdom_mem
  1190. else:
  1191. if self.features.check_with_template('linux-stubdom', True):
  1192. stubdom_mem = 128 # from libxl_create.c
  1193. else:
  1194. stubdom_mem = 28 # from libxl_create.c
  1195. stubdom_mem += 16 # video ram
  1196. else:
  1197. stubdom_mem = 0
  1198. initial_memory = self.memory
  1199. mem_required = int(initial_memory + stubdom_mem) * 1024 * 1024
  1200. qmemman_client = qubes.qmemman.client.QMemmanClient()
  1201. try:
  1202. mem_required_with_overhead = mem_required + MEM_OVERHEAD_BASE \
  1203. + self.vcpus * MEM_OVERHEAD_PER_VCPU
  1204. got_memory = qmemman_client.request_memory(
  1205. mem_required_with_overhead)
  1206. except IOError as e:
  1207. raise IOError('Failed to connect to qmemman: {!s}'.format(e))
  1208. if not got_memory:
  1209. qmemman_client.close()
  1210. raise qubes.exc.QubesMemoryError(self)
  1211. return qmemman_client
  1212. @staticmethod
  1213. @asyncio.coroutine
  1214. def start_daemon(*command, input=None, **kwargs):
  1215. """Start a daemon for the VM
  1216. This function take care to run it as appropriate user.
  1217. :param command: command to run (array for
  1218. :py:meth:`subprocess.check_call`)
  1219. :param kwargs: args for :py:meth:`subprocess.check_call`
  1220. :return: None
  1221. """ # pylint: disable=redefined-builtin
  1222. if os.getuid() == 0:
  1223. # try to always have VM daemons running as normal user, otherwise
  1224. # some files (like clipboard) may be created as root and cause
  1225. # permission problems
  1226. qubes_group = grp.getgrnam('qubes')
  1227. command = ['runuser', '-u', qubes_group.gr_mem[0], '--'] + \
  1228. list(command)
  1229. p = yield from asyncio.create_subprocess_exec(*command, **kwargs)
  1230. stdout, stderr = yield from p.communicate(input=input)
  1231. if p.returncode:
  1232. raise subprocess.CalledProcessError(p.returncode, command,
  1233. output=stdout, stderr=stderr)
  1234. @asyncio.coroutine
  1235. def start_qrexec_daemon(self):
  1236. """Start qrexec daemon.
  1237. :raises OSError: when starting fails.
  1238. """
  1239. self.log.debug('Starting the qrexec daemon')
  1240. qrexec_args = [str(self.xid), self.name, self.default_user]
  1241. if not self.debug:
  1242. qrexec_args.insert(0, "-q")
  1243. qrexec_env = os.environ.copy()
  1244. if not self.features.check_with_template('qrexec', False):
  1245. self.log.debug(
  1246. 'Starting the qrexec daemon in background, because of features')
  1247. qrexec_env['QREXEC_STARTUP_NOWAIT'] = '1'
  1248. else:
  1249. qrexec_env['QREXEC_STARTUP_TIMEOUT'] = str(self.qrexec_timeout)
  1250. try:
  1251. yield from self.start_daemon(
  1252. qubes.config.system_path['qrexec_daemon_path'], *qrexec_args,
  1253. env=qrexec_env, stderr=subprocess.PIPE)
  1254. except subprocess.CalledProcessError as err:
  1255. if err.returncode == 3:
  1256. raise qubes.exc.QubesVMError(
  1257. self,
  1258. 'Cannot connect to qrexec agent for {} seconds, '
  1259. 'see /var/log/xen/console/guest-{}.log for details'.format(
  1260. self.qrexec_timeout, self.name
  1261. ))
  1262. raise qubes.exc.QubesVMError(
  1263. self, 'qrexec-daemon startup failed: ' + err.stderr.decode())
  1264. @asyncio.coroutine
  1265. def start_qubesdb(self):
  1266. """Start QubesDB daemon.
  1267. :raises OSError: when starting fails.
  1268. """
  1269. # drop old connection to QubesDB, if any
  1270. self._qdb_connection = None
  1271. self.log.info('Starting Qubes DB')
  1272. try:
  1273. yield from self.start_daemon(
  1274. qubes.config.system_path['qubesdb_daemon_path'],
  1275. str(self.xid),
  1276. self.name)
  1277. except subprocess.CalledProcessError:
  1278. raise qubes.exc.QubesException('Cannot execute qubesdb-daemon')
  1279. @asyncio.coroutine
  1280. def create_on_disk(self, pool=None, pools=None):
  1281. """Create files needed for VM.
  1282. """
  1283. self.log.info('Creating directory: {0}'.format(self.dir_path))
  1284. os.makedirs(self.dir_path, mode=0o775, exist_ok=True)
  1285. if pool or pools:
  1286. # pylint: disable=attribute-defined-outside-init
  1287. self.volume_config = _patch_volume_config(self.volume_config, pool,
  1288. pools)
  1289. self.storage = qubes.storage.Storage(self)
  1290. try:
  1291. yield from self.storage.create()
  1292. except:
  1293. try:
  1294. yield from self.storage.remove()
  1295. os.rmdir(self.dir_path)
  1296. except: # pylint: disable=bare-except
  1297. self.log.exception('failed to cleanup {} after failed VM '
  1298. 'creation'.format(self.dir_path))
  1299. raise
  1300. if os.path.exists(self.icon_path):
  1301. os.unlink(self.icon_path)
  1302. self.log.info('Creating icon symlink: {} -> {}'.format(
  1303. self.icon_path, self.label.icon_path))
  1304. if hasattr(os, "symlink"):
  1305. os.symlink(self.label.icon_path, self.icon_path)
  1306. else:
  1307. shutil.copy(self.label.icon_path, self.icon_path)
  1308. # fire hooks
  1309. yield from self.fire_event_async('domain-create-on-disk')
  1310. @asyncio.coroutine
  1311. def remove_from_disk(self):
  1312. """Remove domain remnants from disk."""
  1313. if not self.is_halted():
  1314. raise qubes.exc.QubesVMNotHaltedError(
  1315. "Can't remove VM {!s}, because it's in state {!r}.".format(
  1316. self, self.get_power_state()))
  1317. # make sure shutdown is handled before removing anything, but only if
  1318. # handling is pending; if not, we may be called from within
  1319. # domain-shutdown event (DispVM._auto_cleanup), which would deadlock
  1320. if not self._domain_stopped_event_handled:
  1321. yield from self._ensure_shutdown_handled()
  1322. yield from self.fire_event_async('domain-remove-from-disk')
  1323. try:
  1324. yield from self.storage.remove()
  1325. finally:
  1326. try:
  1327. # TODO: make it async?
  1328. shutil.rmtree(self.dir_path)
  1329. except FileNotFoundError:
  1330. pass
  1331. @asyncio.coroutine
  1332. def clone_disk_files(self, src, pool=None, pools=None, ):
  1333. """Clone files from other vm.
  1334. :param qubes.vm.qubesvm.QubesVM src: source VM
  1335. """
  1336. # If the current vm name is not a part of `self.app.domains.keys()`,
  1337. # then the current vm is in creation process. Calling
  1338. # `self.is_halted()` at this point, would instantiate libvirt, we want
  1339. # avoid that.
  1340. if self.name in self.app.domains.keys() and not self.is_halted():
  1341. raise qubes.exc.QubesVMNotHaltedError(
  1342. self, 'Cannot clone a running domain {!r}'.format(self.name))
  1343. msg = "Destination {!s} already exists".format(self.dir_path)
  1344. assert not os.path.exists(self.dir_path), msg
  1345. self.log.info('Creating directory: {0}'.format(self.dir_path))
  1346. os.makedirs(self.dir_path, mode=0o775, exist_ok=True)
  1347. if pool or pools:
  1348. # pylint: disable=attribute-defined-outside-init
  1349. self.volume_config = _patch_volume_config(self.volume_config, pool,
  1350. pools)
  1351. self.storage = qubes.storage.Storage(self)
  1352. yield from self.storage.clone(src)
  1353. self.storage.verify()
  1354. assert self.volumes != {}
  1355. if src.icon_path is not None \
  1356. and os.path.exists(src.icon_path) \
  1357. and self.icon_path is not None:
  1358. if os.path.islink(src.icon_path):
  1359. icon_path = os.readlink(src.icon_path)
  1360. self.log.info(
  1361. 'Creating icon symlink {} -> {}'.format(
  1362. self.icon_path, icon_path))
  1363. os.symlink(icon_path, self.icon_path)
  1364. else:
  1365. self.log.info(
  1366. 'Copying icon {} -> {}'.format(
  1367. src.icon_path, self.icon_path))
  1368. shutil.copy(src.icon_path, self.icon_path)
  1369. # fire hooks
  1370. yield from self.fire_event_async('domain-clone-files', src=src)
  1371. #
  1372. # methods for querying domain state
  1373. #
  1374. # state of the machine
  1375. def get_power_state(self):
  1376. """Return power state description string.
  1377. Return value may be one of those:
  1378. =============== ========================================================
  1379. return value meaning
  1380. =============== ========================================================
  1381. ``'Halted'`` Machine is not active.
  1382. ``'Transient'`` Machine is running, but does not have :program:`guid`
  1383. or :program:`qrexec` available.
  1384. ``'Running'`` Machine is ready and running.
  1385. ``'Paused'`` Machine is paused.
  1386. ``'Suspended'`` Machine is S3-suspended.
  1387. ``'Halting'`` Machine is in process of shutting down.
  1388. ``'Dying'`` Machine is still in process of shutting down.
  1389. ``'Crashed'`` Machine crashed and is unusable, probably because of
  1390. bug in dom0.
  1391. ``'NA'`` Machine is in unknown state (most likely libvirt domain
  1392. is undefined).
  1393. =============== ========================================================
  1394. FIXME: graph below may be incomplete and wrong. Click on method name to
  1395. see its documentation.
  1396. .. graphviz::
  1397. digraph {
  1398. node [fontname="sans-serif"];
  1399. edge [fontname="mono"];
  1400. Halted;
  1401. NA;
  1402. Dying;
  1403. Crashed;
  1404. Transient;
  1405. Halting;
  1406. Running;
  1407. Paused [color=gray75 fontcolor=gray75];
  1408. Suspended;
  1409. NA -> Halted;
  1410. Halted -> NA [constraint=false];
  1411. Halted -> Transient
  1412. [xlabel="start()" URL="#qubes.vm.qubesvm.QubesVM.start"];
  1413. Transient -> Running;
  1414. Running -> Halting
  1415. [xlabel="shutdown()"
  1416. URL="#qubes.vm.qubesvm.QubesVM.shutdown"
  1417. constraint=false];
  1418. Halting -> Dying -> Halted [constraint=false];
  1419. /* cosmetic, invisible edges to put rank constraint */
  1420. Dying -> Halting [style="invis"];
  1421. Halting -> Transient [style="invis"];
  1422. Running -> Halted
  1423. [label="kill()"
  1424. URL="#qubes.vm.qubesvm.QubesVM.kill"
  1425. constraint=false];
  1426. Running -> Crashed [constraint=false];
  1427. Crashed -> Halted [constraint=false];
  1428. Running -> Paused
  1429. [label="pause()" URL="#qubes.vm.qubesvm.QubesVM.pause"
  1430. color=gray75 fontcolor=gray75];
  1431. Running -> Suspended
  1432. [label="suspend()" URL="#qubes.vm.qubesvm.QubesVM.suspend"
  1433. color=gray50 fontcolor=gray50];
  1434. Paused -> Running
  1435. [label="unpause()" URL="#qubes.vm.qubesvm.QubesVM.unpause"
  1436. color=gray75 fontcolor=gray75];
  1437. Suspended -> Running
  1438. [label="resume()" URL="#qubes.vm.qubesvm.QubesVM.resume"
  1439. color=gray50 fontcolor=gray50];
  1440. Running -> Suspended
  1441. [label="suspend()" URL="#qubes.vm.qubesvm.QubesVM.suspend"];
  1442. Suspended -> Running
  1443. [label="resume()" URL="#qubes.vm.qubesvm.QubesVM.resume"];
  1444. { rank=source; Halted NA };
  1445. { rank=same; Transient Halting };
  1446. { rank=same; Crashed Dying };
  1447. { rank=sink; Paused Suspended };
  1448. }
  1449. .. seealso::
  1450. http://wiki.libvirt.org/page/VM_lifecycle
  1451. Description of VM life cycle from the point of view of libvirt.
  1452. https://libvirt.org/html/libvirt-libvirt-domain.html#virDomainState
  1453. Libvirt's enum describing precise state of a domain.
  1454. """ # pylint: disable=too-many-return-statements
  1455. # don't try to define libvirt domain, if it isn't there, VM surely
  1456. # isn't running
  1457. # reason for this "if": allow vm.is_running() in PCI (or other
  1458. # device) extension while constructing libvirt XML
  1459. if self.app.vmm.offline_mode:
  1460. return 'Halted'
  1461. if self._libvirt_domain is None:
  1462. try:
  1463. self._libvirt_domain = self.app.vmm.libvirt_conn.lookupByUUID(
  1464. self.uuid.bytes)
  1465. except libvirt.libvirtError as e:
  1466. if e.get_error_code() == libvirt.VIR_ERR_NO_DOMAIN:
  1467. return 'Halted'
  1468. raise
  1469. libvirt_domain = self.libvirt_domain
  1470. if libvirt_domain is None:
  1471. return 'Halted'
  1472. try:
  1473. if libvirt_domain.isActive():
  1474. # pylint: disable=line-too-long
  1475. if libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_PAUSED:
  1476. return "Paused"
  1477. if libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_CRASHED:
  1478. return "Crashed"
  1479. if libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_SHUTDOWN:
  1480. return "Halting"
  1481. if libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_SHUTOFF:
  1482. return "Dying"
  1483. if libvirt_domain.state()[
  1484. 0] == libvirt.VIR_DOMAIN_PMSUSPENDED: # nopep8
  1485. return "Suspended"
  1486. if not self.is_fully_usable():
  1487. return "Transient"
  1488. return "Running"
  1489. return 'Halted'
  1490. except libvirt.libvirtError as e:
  1491. if e.get_error_code() == libvirt.VIR_ERR_NO_DOMAIN:
  1492. return 'Halted'
  1493. raise
  1494. assert False
  1495. def is_halted(self):
  1496. """ Check whether this domain's state is 'Halted'
  1497. :returns: :py:obj:`True` if this domain is halted, \
  1498. :py:obj:`False` otherwise.
  1499. :rtype: bool
  1500. """
  1501. return self.get_power_state() == 'Halted'
  1502. def is_running(self):
  1503. """Check whether this domain is running.
  1504. :returns: :py:obj:`True` if this domain is started, \
  1505. :py:obj:`False` otherwise.
  1506. :rtype: bool
  1507. """
  1508. if self.app.vmm.offline_mode:
  1509. return False
  1510. # don't try to define libvirt domain, if it isn't there, VM surely
  1511. # isn't running
  1512. # reason for this "if": allow vm.is_running() in PCI (or other
  1513. # device) extension while constructing libvirt XML
  1514. if self._libvirt_domain is None:
  1515. try:
  1516. self._libvirt_domain = self.app.vmm.libvirt_conn.lookupByUUID(
  1517. self.uuid.bytes)
  1518. except libvirt.libvirtError as e:
  1519. if e.get_error_code() == libvirt.VIR_ERR_NO_DOMAIN:
  1520. return False
  1521. raise
  1522. return bool(self.libvirt_domain.isActive())
  1523. def is_paused(self):
  1524. """Check whether this domain is paused.
  1525. :returns: :py:obj:`True` if this domain is paused, \
  1526. :py:obj:`False` otherwise.
  1527. :rtype: bool
  1528. """
  1529. return self.libvirt_domain \
  1530. and self.libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_PAUSED
  1531. def is_qrexec_running(self):
  1532. """Check whether qrexec for this domain is available.
  1533. :returns: :py:obj:`True` if qrexec is running, \
  1534. :py:obj:`False` otherwise.
  1535. :rtype: bool
  1536. """
  1537. if self.xid < 0: # pylint: disable=comparison-with-callable
  1538. return False
  1539. return os.path.exists('/var/run/qubes/qrexec.%s' % self.name)
  1540. def is_fully_usable(self):
  1541. return all(self.fire_event('domain-is-fully-usable'))
  1542. @qubes.events.handler('domain-is-fully-usable')
  1543. def on_domain_is_fully_usable(self, event):
  1544. """Check whether domain is running and sane.
  1545. Currently this checks for running qrexec.
  1546. """ # pylint: disable=unused-argument
  1547. # Running gui-daemon implies also VM running
  1548. if not self.is_qrexec_running():
  1549. yield False
  1550. # memory and disk
  1551. def get_mem(self):
  1552. """Get current memory usage from VM.
  1553. :returns: Memory usage [FIXME unit].
  1554. :rtype: FIXME
  1555. """
  1556. if self.libvirt_domain is None:
  1557. return 0
  1558. try:
  1559. if not self.libvirt_domain.isActive():
  1560. return 0
  1561. return self.libvirt_domain.info()[1]
  1562. except libvirt.libvirtError as e:
  1563. if e.get_error_code() in (
  1564. # qube no longer exists
  1565. libvirt.VIR_ERR_NO_DOMAIN,
  1566. # libxl_domain_info failed (race condition from isActive)
  1567. libvirt.VIR_ERR_INTERNAL_ERROR):
  1568. return 0
  1569. self.log.exception(
  1570. 'libvirt error code: {!r}'.format(e.get_error_code()))
  1571. raise
  1572. def get_mem_static_max(self):
  1573. """Get maximum memory available to VM.
  1574. :returns: Memory limit [FIXME unit].
  1575. :rtype: FIXME
  1576. """
  1577. if self.libvirt_domain is None:
  1578. return 0
  1579. try:
  1580. return self.libvirt_domain.maxMemory()
  1581. except libvirt.libvirtError as e:
  1582. if e.get_error_code() in (
  1583. # qube no longer exists
  1584. libvirt.VIR_ERR_NO_DOMAIN,
  1585. # libxl_domain_info failed (race condition from isActive)
  1586. libvirt.VIR_ERR_INTERNAL_ERROR):
  1587. return 0
  1588. self.log.exception(
  1589. 'libvirt error code: {!r}'.format(e.get_error_code()))
  1590. raise
  1591. def get_cputime(self):
  1592. """Get total CPU time burned by this domain since start.
  1593. :returns: CPU time usage [FIXME unit].
  1594. :rtype: FIXME
  1595. """
  1596. if self.libvirt_domain is None:
  1597. return 0
  1598. if self.libvirt_domain is None:
  1599. return 0
  1600. if not self.libvirt_domain.isActive():
  1601. return 0
  1602. try:
  1603. if not self.libvirt_domain.isActive():
  1604. return 0
  1605. # this does not work, because libvirt
  1606. # return self.libvirt_domain.getCPUStats(
  1607. # libvirt.VIR_NODE_CPU_STATS_ALL_CPUS, 0)[0]['cpu_time']/10**9
  1608. return self.libvirt_domain.info()[4]
  1609. except libvirt.libvirtError as e:
  1610. if e.get_error_code() in (
  1611. # qube no longer exists
  1612. libvirt.VIR_ERR_NO_DOMAIN,
  1613. # libxl_domain_info failed (race condition from isActive)
  1614. libvirt.VIR_ERR_INTERNAL_ERROR):
  1615. return 0
  1616. self.log.exception(
  1617. 'libvirt error code: {!r}'.format(e.get_error_code()))
  1618. raise
  1619. # miscellanous
  1620. @qubes.stateless_property
  1621. def start_time(self):
  1622. """Tell when machine was started.
  1623. :rtype: float or None
  1624. """
  1625. if not self.is_running():
  1626. return None
  1627. # TODO shouldn't this be qubesdb?
  1628. start_time = self.app.vmm.xs.read('',
  1629. '/vm/{}/start_time'.format(self.uuid))
  1630. if start_time != '':
  1631. return float(start_time)
  1632. return None
  1633. @property
  1634. def kernelopts_common(self):
  1635. """Kernel options which should be used in addition to *kernelopts*
  1636. property.
  1637. This is specific to kernel (and initrd if any)
  1638. """
  1639. if not self.kernel:
  1640. return ''
  1641. kernels_dir = self.storage.kernels_dir
  1642. kernelopts_path = os.path.join(kernels_dir,
  1643. 'default-kernelopts-common.txt')
  1644. if os.path.exists(kernelopts_path):
  1645. with open(kernelopts_path) as f_kernelopts:
  1646. return f_kernelopts.read().rstrip('\n\r')
  1647. else:
  1648. return qubes.config.defaults['kernelopts_common']
  1649. #
  1650. # helper methods
  1651. #
  1652. def relative_path(self, path):
  1653. """Return path relative to py:attr:`dir_path`.
  1654. :param str path: Path in question.
  1655. :returns: Relative path.
  1656. """
  1657. return os.path.relpath(path, self.dir_path)
  1658. def create_qdb_entries(self):
  1659. """Create entries in Qubes DB.
  1660. """
  1661. # pylint: disable=no-member
  1662. self.untrusted_qdb.write('/name', self.name)
  1663. self.untrusted_qdb.write('/type', self.__class__.__name__)
  1664. self.untrusted_qdb.write('/default-user', self.default_user)
  1665. self.untrusted_qdb.write('/qubes-vm-updateable', str(self.updateable))
  1666. self.untrusted_qdb.write('/qubes-vm-persistence',
  1667. 'full' if self.updateable else 'rw-only')
  1668. self.untrusted_qdb.write('/qubes-debug-mode', str(int(self.debug)))
  1669. try:
  1670. self.untrusted_qdb.write('/qubes-base-template', self.template.name)
  1671. except AttributeError:
  1672. self.untrusted_qdb.write('/qubes-base-template', '')
  1673. self.untrusted_qdb.write('/qubes-random-seed',
  1674. base64.b64encode(qubes.utils.urandom(64)))
  1675. if self.provides_network:
  1676. # '/qubes-netvm-network' value is only checked for being non empty
  1677. self.untrusted_qdb.write('/qubes-netvm-network', str(self.gateway))
  1678. self.untrusted_qdb.write('/qubes-netvm-gateway', str(self.gateway))
  1679. if self.gateway6: # pylint: disable=using-constant-test
  1680. self.untrusted_qdb.write('/qubes-netvm-gateway6',
  1681. str(self.gateway6))
  1682. self.untrusted_qdb.write('/qubes-netvm-netmask', str(self.netmask))
  1683. for i, addr in zip(('primary', 'secondary'), self.dns):
  1684. self.untrusted_qdb.write('/qubes-netvm-{}-dns'.format(i), addr)
  1685. if self.netvm is not None:
  1686. self.untrusted_qdb.write('/qubes-mac', str(self.mac))
  1687. self.untrusted_qdb.write('/qubes-ip', str(self.visible_ip))
  1688. self.untrusted_qdb.write('/qubes-netmask',
  1689. str(self.visible_netmask))
  1690. self.untrusted_qdb.write('/qubes-gateway',
  1691. str(self.visible_gateway))
  1692. for i, addr in zip(('primary', 'secondary'), self.dns):
  1693. self.untrusted_qdb.write('/qubes-{}-dns'.format(i), str(addr))
  1694. if self.visible_ip6: # pylint: disable=using-constant-test
  1695. self.untrusted_qdb.write('/qubes-ip6', str(self.visible_ip6))
  1696. if self.visible_gateway6: # pylint: disable=using-constant-test
  1697. self.untrusted_qdb.write('/qubes-gateway6',
  1698. str(self.visible_gateway6))
  1699. tzname = qubes.utils.get_timezone()
  1700. if tzname:
  1701. self.untrusted_qdb.write('/qubes-timezone', tzname)
  1702. self.untrusted_qdb.write('/qubes-block-devices', '')
  1703. self.untrusted_qdb.write('/qubes-usb-devices', '')
  1704. # TODO: Currently the whole qmemman is quite Xen-specific, so stay with
  1705. # xenstore for it until decided otherwise
  1706. if qmemman_present:
  1707. self.app.vmm.xs.set_permissions('',
  1708. '/local/domain/{}/memory'.format(
  1709. self.xid),
  1710. [{'dom': self.xid}])
  1711. self.fire_event('domain-qdb-create')
  1712. # TODO async; update this in constructor
  1713. def _update_libvirt_domain(self):
  1714. """Re-initialise :py:attr:`libvirt_domain`."""
  1715. domain_config = self.create_config_file()
  1716. try:
  1717. self._libvirt_domain = self.app.vmm.libvirt_conn.defineXML(
  1718. domain_config)
  1719. except libvirt.libvirtError as e:
  1720. if e.get_error_code() == libvirt.VIR_ERR_OS_TYPE \
  1721. and e.get_str2() == 'hvm':
  1722. raise qubes.exc.QubesVMError(
  1723. self,
  1724. 'HVM qubes are not supported on this machine. '
  1725. 'Check BIOS settings for VT-x/AMD-V extensions.')
  1726. raise
  1727. #
  1728. # workshop -- those are to be reworked later
  1729. #
  1730. def get_prefmem(self):
  1731. # TODO: qmemman is still xen specific
  1732. untrusted_meminfo_key = self.app.vmm.xs.read(
  1733. '', '/local/domain/{}/memory/meminfo'.format(self.xid))
  1734. if untrusted_meminfo_key is None or untrusted_meminfo_key == '':
  1735. return 0
  1736. domain = qubes.qmemman.DomainState(self.xid)
  1737. qubes.qmemman.algo.refresh_meminfo_for_domain(
  1738. domain, untrusted_meminfo_key)
  1739. if domain.mem_used is None:
  1740. # apparently invalid xenstore content
  1741. return 0
  1742. domain.memory_maximum = self.get_mem_static_max() * 1024
  1743. return qubes.qmemman.algo.prefmem(domain) / 1024
  1744. def _clean_volume_config(config):
  1745. common_attributes = ['name', 'pool', 'size',
  1746. 'revisions_to_keep', 'rw', 'snap_on_start',
  1747. 'save_on_stop', 'source']
  1748. return {k: v for k, v in config.items() if k in common_attributes}
  1749. def _patch_pool_config(config, pool=None, pools=None):
  1750. assert pool is not None or pools is not None
  1751. is_snapshot = config['snap_on_start']
  1752. is_rw = config['rw']
  1753. name = config['name']
  1754. if pool and not is_snapshot and is_rw:
  1755. config['pool'] = str(pool)
  1756. elif pool:
  1757. pass
  1758. elif pools and name in pools.keys():
  1759. if not is_snapshot:
  1760. config['pool'] = str(pools[name])
  1761. else:
  1762. msg = "Snapshot volume {0!s} must be in the same pool as its " \
  1763. "origin ({0!s} volume of template)," \
  1764. "cannot move to pool {1!s} " \
  1765. .format(name, pools[name])
  1766. raise qubes.exc.QubesException(msg)
  1767. return config
  1768. def _patch_volume_config(volume_config, pool=None, pools=None):
  1769. assert not (pool and pools), \
  1770. 'You can not pass pool & pools parameter at same time'
  1771. assert pool or pools
  1772. result = {}
  1773. for name, config in volume_config.items():
  1774. # copy only the subset of volume_config key/values
  1775. dst_config = _clean_volume_config(config)
  1776. if pool is not None or pools is not None:
  1777. dst_config = _patch_pool_config(dst_config, pool, pools)
  1778. result[name] = dst_config
  1779. return result