qubesvm.py 78 KB

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