qubesvm.py 78 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196
  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}, beacuse 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. # TODO: make it async?
  1274. shutil.rmtree(self.dir_path)
  1275. except FileNotFoundError:
  1276. pass
  1277. yield from self.storage.remove()
  1278. @asyncio.coroutine
  1279. def clone_disk_files(self, src, pool=None, pools=None, ):
  1280. '''Clone files from other vm.
  1281. :param qubes.vm.qubesvm.QubesVM src: source VM
  1282. '''
  1283. # If the current vm name is not a part of `self.app.domains.keys()`,
  1284. # then the current vm is in creation process. Calling
  1285. # `self.is_halted()` at this point, would instantiate libvirt, we want
  1286. # avoid that.
  1287. if self.name in self.app.domains.keys() and not self.is_halted():
  1288. raise qubes.exc.QubesVMNotHaltedError(
  1289. self, 'Cannot clone a running domain {!r}'.format(self.name))
  1290. msg = "Destination {!s} already exists".format(self.dir_path)
  1291. assert not os.path.exists(self.dir_path), msg
  1292. self.log.info('Creating directory: {0}'.format(self.dir_path))
  1293. os.makedirs(self.dir_path, mode=0o775, exist_ok=True)
  1294. if pool or pools:
  1295. # pylint: disable=attribute-defined-outside-init
  1296. self.volume_config = _patch_volume_config(self.volume_config, pool,
  1297. pools)
  1298. self.storage = qubes.storage.Storage(self)
  1299. yield from self.storage.clone(src)
  1300. self.storage.verify()
  1301. assert self.volumes != {}
  1302. if src.icon_path is not None \
  1303. and os.path.exists(src.icon_path) \
  1304. and self.icon_path is not None:
  1305. if os.path.islink(src.icon_path):
  1306. icon_path = os.readlink(src.icon_path)
  1307. self.log.info(
  1308. 'Creating icon symlink {} -> {}'.format(
  1309. self.icon_path, icon_path))
  1310. os.symlink(icon_path, self.icon_path)
  1311. else:
  1312. self.log.info(
  1313. 'Copying icon {} -> {}'.format(
  1314. src.icon_path, self.icon_path))
  1315. shutil.copy(src.icon_path, self.icon_path)
  1316. # fire hooks
  1317. yield from self.fire_event_async('domain-clone-files', src=src)
  1318. #
  1319. # methods for querying domain state
  1320. #
  1321. # state of the machine
  1322. def get_power_state(self):
  1323. '''Return power state description string.
  1324. Return value may be one of those:
  1325. =============== ========================================================
  1326. return value meaning
  1327. =============== ========================================================
  1328. ``'Halted'`` Machine is not active.
  1329. ``'Transient'`` Machine is running, but does not have :program:`guid`
  1330. or :program:`qrexec` available.
  1331. ``'Running'`` Machine is ready and running.
  1332. ``'Paused'`` Machine is paused.
  1333. ``'Suspended'`` Machine is S3-suspended.
  1334. ``'Halting'`` Machine is in process of shutting down.
  1335. ``'Dying'`` Machine is still in process of shutting down.
  1336. ``'Crashed'`` Machine crashed and is unusable, probably because of
  1337. bug in dom0.
  1338. ``'NA'`` Machine is in unknown state (most likely libvirt domain
  1339. is undefined).
  1340. =============== ========================================================
  1341. FIXME: graph below may be incomplete and wrong. Click on method name to
  1342. see its documentation.
  1343. .. graphviz::
  1344. digraph {
  1345. node [fontname="sans-serif"];
  1346. edge [fontname="mono"];
  1347. Halted;
  1348. NA;
  1349. Dying;
  1350. Crashed;
  1351. Transient;
  1352. Halting;
  1353. Running;
  1354. Paused [color=gray75 fontcolor=gray75];
  1355. Suspended;
  1356. NA -> Halted;
  1357. Halted -> NA [constraint=false];
  1358. Halted -> Transient
  1359. [xlabel="start()" URL="#qubes.vm.qubesvm.QubesVM.start"];
  1360. Transient -> Running;
  1361. Running -> Halting
  1362. [xlabel="shutdown()"
  1363. URL="#qubes.vm.qubesvm.QubesVM.shutdown"
  1364. constraint=false];
  1365. Halting -> Dying -> Halted [constraint=false];
  1366. /* cosmetic, invisible edges to put rank constraint */
  1367. Dying -> Halting [style="invis"];
  1368. Halting -> Transient [style="invis"];
  1369. Running -> Halted
  1370. [label="force_shutdown()"
  1371. URL="#qubes.vm.qubesvm.QubesVM.force_shutdown"
  1372. constraint=false];
  1373. Running -> Crashed [constraint=false];
  1374. Crashed -> Halted [constraint=false];
  1375. Running -> Paused
  1376. [label="pause()" URL="#qubes.vm.qubesvm.QubesVM.pause"
  1377. color=gray75 fontcolor=gray75];
  1378. Running -> Suspended
  1379. [label="suspend()" URL="#qubes.vm.qubesvm.QubesVM.suspend"
  1380. color=gray50 fontcolor=gray50];
  1381. Paused -> Running
  1382. [label="unpause()" URL="#qubes.vm.qubesvm.QubesVM.unpause"
  1383. color=gray75 fontcolor=gray75];
  1384. Suspended -> Running
  1385. [label="resume()" URL="#qubes.vm.qubesvm.QubesVM.resume"
  1386. color=gray50 fontcolor=gray50];
  1387. Running -> Suspended
  1388. [label="suspend()" URL="#qubes.vm.qubesvm.QubesVM.suspend"];
  1389. Suspended -> Running
  1390. [label="resume()" URL="#qubes.vm.qubesvm.QubesVM.resume"];
  1391. { rank=source; Halted NA };
  1392. { rank=same; Transient Halting };
  1393. { rank=same; Crashed Dying };
  1394. { rank=sink; Paused Suspended };
  1395. }
  1396. .. seealso::
  1397. http://wiki.libvirt.org/page/VM_lifecycle
  1398. Description of VM life cycle from the point of view of libvirt.
  1399. https://libvirt.org/html/libvirt-libvirt-domain.html#virDomainState
  1400. Libvirt's enum describing precise state of a domain.
  1401. ''' # pylint: disable=too-many-return-statements
  1402. # don't try to define libvirt domain, if it isn't there, VM surely
  1403. # isn't running
  1404. # reason for this "if": allow vm.is_running() in PCI (or other
  1405. # device) extension while constructing libvirt XML
  1406. if self.app.vmm.offline_mode:
  1407. return 'Halted'
  1408. if self._libvirt_domain is None:
  1409. try:
  1410. self._libvirt_domain = self.app.vmm.libvirt_conn.lookupByUUID(
  1411. self.uuid.bytes)
  1412. except libvirt.libvirtError as e:
  1413. if e.get_error_code() == libvirt.VIR_ERR_NO_DOMAIN:
  1414. return 'Halted'
  1415. raise
  1416. libvirt_domain = self.libvirt_domain
  1417. if libvirt_domain is None:
  1418. return 'Halted'
  1419. try:
  1420. if libvirt_domain.isActive():
  1421. # pylint: disable=line-too-long
  1422. if libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_PAUSED:
  1423. return "Paused"
  1424. if libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_CRASHED:
  1425. return "Crashed"
  1426. if libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_SHUTDOWN:
  1427. return "Halting"
  1428. if libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_SHUTOFF:
  1429. return "Dying"
  1430. if libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_PMSUSPENDED: # nopep8
  1431. return "Suspended"
  1432. if not self.is_fully_usable():
  1433. return "Transient"
  1434. return "Running"
  1435. return 'Halted'
  1436. except libvirt.libvirtError as e:
  1437. if e.get_error_code() == libvirt.VIR_ERR_NO_DOMAIN:
  1438. return 'Halted'
  1439. raise
  1440. assert False
  1441. def is_halted(self):
  1442. ''' Check whether this domain's state is 'Halted'
  1443. :returns: :py:obj:`True` if this domain is halted, \
  1444. :py:obj:`False` otherwise.
  1445. :rtype: bool
  1446. '''
  1447. return self.get_power_state() == 'Halted'
  1448. def is_running(self):
  1449. '''Check whether this domain is running.
  1450. :returns: :py:obj:`True` if this domain is started, \
  1451. :py:obj:`False` otherwise.
  1452. :rtype: bool
  1453. '''
  1454. if self.app.vmm.offline_mode:
  1455. return False
  1456. # don't try to define libvirt domain, if it isn't there, VM surely
  1457. # isn't running
  1458. # reason for this "if": allow vm.is_running() in PCI (or other
  1459. # device) extension while constructing libvirt XML
  1460. if self._libvirt_domain is None:
  1461. try:
  1462. self._libvirt_domain = self.app.vmm.libvirt_conn.lookupByUUID(
  1463. self.uuid.bytes)
  1464. except libvirt.libvirtError as e:
  1465. if e.get_error_code() == libvirt.VIR_ERR_NO_DOMAIN:
  1466. return False
  1467. raise
  1468. return bool(self.libvirt_domain.isActive())
  1469. def is_paused(self):
  1470. '''Check whether this domain is paused.
  1471. :returns: :py:obj:`True` if this domain is paused, \
  1472. :py:obj:`False` otherwise.
  1473. :rtype: bool
  1474. '''
  1475. return self.libvirt_domain \
  1476. and self.libvirt_domain.state()[0] == libvirt.VIR_DOMAIN_PAUSED
  1477. def is_qrexec_running(self):
  1478. '''Check whether qrexec for this domain is available.
  1479. :returns: :py:obj:`True` if qrexec is running, \
  1480. :py:obj:`False` otherwise.
  1481. :rtype: bool
  1482. '''
  1483. if self.xid < 0: # pylint: disable=comparison-with-callable
  1484. return False
  1485. return os.path.exists('/var/run/qubes/qrexec.%s' % self.name)
  1486. def is_fully_usable(self):
  1487. return all(self.fire_event('domain-is-fully-usable'))
  1488. @qubes.events.handler('domain-is-fully-usable')
  1489. def on_domain_is_fully_usable(self, event):
  1490. '''Check whether domain is running and sane.
  1491. Currently this checks for running qrexec.
  1492. ''' # pylint: disable=unused-argument
  1493. # Running gui-daemon implies also VM running
  1494. if not self.is_qrexec_running():
  1495. yield False
  1496. # memory and disk
  1497. def get_mem(self):
  1498. '''Get current memory usage from VM.
  1499. :returns: Memory usage [FIXME unit].
  1500. :rtype: FIXME
  1501. '''
  1502. if self.libvirt_domain is None:
  1503. return 0
  1504. try:
  1505. if not self.libvirt_domain.isActive():
  1506. return 0
  1507. return self.libvirt_domain.info()[1]
  1508. except libvirt.libvirtError as e:
  1509. if e.get_error_code() in (
  1510. # qube no longer exists
  1511. libvirt.VIR_ERR_NO_DOMAIN,
  1512. # libxl_domain_info failed (race condition from isActive)
  1513. libvirt.VIR_ERR_INTERNAL_ERROR):
  1514. return 0
  1515. self.log.exception(
  1516. 'libvirt error code: {!r}'.format(e.get_error_code()))
  1517. raise
  1518. def get_mem_static_max(self):
  1519. '''Get maximum memory available to VM.
  1520. :returns: Memory limit [FIXME unit].
  1521. :rtype: FIXME
  1522. '''
  1523. if self.libvirt_domain is None:
  1524. return 0
  1525. try:
  1526. return self.libvirt_domain.maxMemory()
  1527. except libvirt.libvirtError as e:
  1528. if e.get_error_code() in (
  1529. # qube no longer exists
  1530. libvirt.VIR_ERR_NO_DOMAIN,
  1531. # libxl_domain_info failed (race condition from isActive)
  1532. libvirt.VIR_ERR_INTERNAL_ERROR):
  1533. return 0
  1534. self.log.exception(
  1535. 'libvirt error code: {!r}'.format(e.get_error_code()))
  1536. raise
  1537. def get_cputime(self):
  1538. '''Get total CPU time burned by this domain since start.
  1539. :returns: CPU time usage [FIXME unit].
  1540. :rtype: FIXME
  1541. '''
  1542. if self.libvirt_domain is None:
  1543. return 0
  1544. if self.libvirt_domain is None:
  1545. return 0
  1546. if not self.libvirt_domain.isActive():
  1547. return 0
  1548. try:
  1549. if not self.libvirt_domain.isActive():
  1550. return 0
  1551. # this does not work, because libvirt
  1552. # return self.libvirt_domain.getCPUStats(
  1553. # libvirt.VIR_NODE_CPU_STATS_ALL_CPUS, 0)[0]['cpu_time']/10**9
  1554. return self.libvirt_domain.info()[4]
  1555. except libvirt.libvirtError as e:
  1556. if e.get_error_code() in (
  1557. # qube no longer exists
  1558. libvirt.VIR_ERR_NO_DOMAIN,
  1559. # libxl_domain_info failed (race condition from isActive)
  1560. libvirt.VIR_ERR_INTERNAL_ERROR):
  1561. return 0
  1562. self.log.exception(
  1563. 'libvirt error code: {!r}'.format(e.get_error_code()))
  1564. raise
  1565. # miscellanous
  1566. @qubes.stateless_property
  1567. def start_time(self):
  1568. '''Tell when machine was started.
  1569. :rtype: float or None
  1570. '''
  1571. if not self.is_running():
  1572. return None
  1573. # TODO shouldn't this be qubesdb?
  1574. start_time = self.app.vmm.xs.read('',
  1575. '/vm/{}/start_time'.format(self.uuid))
  1576. if start_time != '':
  1577. return float(start_time)
  1578. return None
  1579. @property
  1580. def kernelopts_common(self):
  1581. '''Kernel options which should be used in addition to *kernelopts*
  1582. property.
  1583. This is specific to kernel (and initrd if any)
  1584. '''
  1585. if not self.kernel:
  1586. return ''
  1587. kernels_dir = self.storage.kernels_dir
  1588. kernelopts_path = os.path.join(kernels_dir,
  1589. 'default-kernelopts-common.txt')
  1590. if os.path.exists(kernelopts_path):
  1591. with open(kernelopts_path) as f_kernelopts:
  1592. return f_kernelopts.read().rstrip('\n\r')
  1593. else:
  1594. return qubes.config.defaults['kernelopts_common']
  1595. #
  1596. # helper methods
  1597. #
  1598. def relative_path(self, path):
  1599. '''Return path relative to py:attr:`dir_path`.
  1600. :param str path: Path in question.
  1601. :returns: Relative path.
  1602. '''
  1603. return os.path.relpath(path, self.dir_path)
  1604. def create_qdb_entries(self):
  1605. '''Create entries in Qubes DB.
  1606. '''
  1607. # pylint: disable=no-member
  1608. self.untrusted_qdb.write('/name', self.name)
  1609. self.untrusted_qdb.write('/type', self.__class__.__name__)
  1610. self.untrusted_qdb.write('/default-user', self.default_user)
  1611. self.untrusted_qdb.write('/qubes-vm-updateable', str(self.updateable))
  1612. self.untrusted_qdb.write('/qubes-vm-persistence',
  1613. 'full' if self.updateable else 'rw-only')
  1614. self.untrusted_qdb.write('/qubes-debug-mode', str(int(self.debug)))
  1615. try:
  1616. self.untrusted_qdb.write('/qubes-base-template', self.template.name)
  1617. except AttributeError:
  1618. self.untrusted_qdb.write('/qubes-base-template', '')
  1619. self.untrusted_qdb.write('/qubes-random-seed',
  1620. base64.b64encode(qubes.utils.urandom(64)))
  1621. if self.provides_network:
  1622. # '/qubes-netvm-network' value is only checked for being non empty
  1623. self.untrusted_qdb.write('/qubes-netvm-network', str(self.gateway))
  1624. self.untrusted_qdb.write('/qubes-netvm-gateway', str(self.gateway))
  1625. if self.gateway6:
  1626. self.untrusted_qdb.write('/qubes-netvm-gateway6',
  1627. str(self.gateway6))
  1628. self.untrusted_qdb.write('/qubes-netvm-netmask', str(self.netmask))
  1629. for i, addr in zip(('primary', 'secondary'), self.dns):
  1630. self.untrusted_qdb.write('/qubes-netvm-{}-dns'.format(i), addr)
  1631. if self.netvm is not None:
  1632. self.untrusted_qdb.write('/qubes-ip', str(self.visible_ip))
  1633. self.untrusted_qdb.write('/qubes-netmask',
  1634. str(self.visible_netmask))
  1635. self.untrusted_qdb.write('/qubes-gateway',
  1636. str(self.visible_gateway))
  1637. for i, addr in zip(('primary', 'secondary'), self.dns):
  1638. self.untrusted_qdb.write('/qubes-{}-dns'.format(i), str(addr))
  1639. if self.visible_ip6:
  1640. self.untrusted_qdb.write('/qubes-ip6', str(self.visible_ip6))
  1641. if self.visible_gateway6:
  1642. self.untrusted_qdb.write('/qubes-gateway6',
  1643. str(self.visible_gateway6))
  1644. tzname = qubes.utils.get_timezone()
  1645. if tzname:
  1646. self.untrusted_qdb.write('/qubes-timezone', tzname)
  1647. self.untrusted_qdb.write('/qubes-block-devices', '')
  1648. self.untrusted_qdb.write('/qubes-usb-devices', '')
  1649. # TODO: Currently the whole qmemman is quite Xen-specific, so stay with
  1650. # xenstore for it until decided otherwise
  1651. if qmemman_present:
  1652. self.app.vmm.xs.set_permissions('',
  1653. '/local/domain/{}/memory'.format(self.xid),
  1654. [{'dom': self.xid}])
  1655. self.fire_event('domain-qdb-create')
  1656. # TODO async; update this in constructor
  1657. def _update_libvirt_domain(self):
  1658. '''Re-initialise :py:attr:`libvirt_domain`.'''
  1659. domain_config = self.create_config_file()
  1660. try:
  1661. self._libvirt_domain = self.app.vmm.libvirt_conn.defineXML(
  1662. domain_config)
  1663. except libvirt.libvirtError as e:
  1664. if e.get_error_code() == libvirt.VIR_ERR_OS_TYPE \
  1665. and e.get_str2() == 'hvm':
  1666. raise qubes.exc.QubesVMError(self,
  1667. 'HVM qubes are not supported on this machine. '
  1668. 'Check BIOS settings for VT-x/AMD-V extensions.')
  1669. raise
  1670. #
  1671. # workshop -- those are to be reworked later
  1672. #
  1673. def get_prefmem(self):
  1674. # TODO: qmemman is still xen specific
  1675. untrusted_meminfo_key = self.app.vmm.xs.read('',
  1676. '/local/domain/{}/memory/meminfo'.format(self.xid))
  1677. if untrusted_meminfo_key is None or untrusted_meminfo_key == '':
  1678. return 0
  1679. domain = qubes.qmemman.DomainState(self.xid)
  1680. qubes.qmemman.algo.refresh_meminfo_for_domain(
  1681. domain, untrusted_meminfo_key)
  1682. if domain.mem_used is None:
  1683. # apparently invalid xenstore content
  1684. return 0
  1685. domain.memory_maximum = self.get_mem_static_max() * 1024
  1686. return qubes.qmemman.algo.prefmem(domain) / 1024
  1687. def _clean_volume_config(config):
  1688. common_attributes = ['name', 'pool', 'size',
  1689. 'revisions_to_keep', 'rw', 'snap_on_start',
  1690. 'save_on_stop', 'source']
  1691. return {k: v for k, v in config.items() if k in common_attributes}
  1692. def _patch_pool_config(config, pool=None, pools=None):
  1693. assert pool is not None or pools is not None
  1694. is_snapshot = config['snap_on_start']
  1695. is_rw = config['rw']
  1696. name = config['name']
  1697. if pool and not is_snapshot and is_rw:
  1698. config['pool'] = str(pool)
  1699. elif pool:
  1700. pass
  1701. elif pools and name in pools.keys():
  1702. if not is_snapshot:
  1703. config['pool'] = str(pools[name])
  1704. else:
  1705. msg = "Snapshot volume {0!s} must be in the same pool as its " \
  1706. "origin ({0!s} volume of template)," \
  1707. "cannot move to pool {1!s} " \
  1708. .format(name, pools[name])
  1709. raise qubes.exc.QubesException(msg)
  1710. return config
  1711. def _patch_volume_config(volume_config, pool=None, pools=None):
  1712. assert not (pool and pools), \
  1713. 'You can not pass pool & pools parameter at same time'
  1714. assert pool or pools
  1715. result = {}
  1716. for name, config in volume_config.items():
  1717. # copy only the subset of volume_config key/values
  1718. dst_config = _clean_volume_config(config)
  1719. if pool is not None or pools is not None:
  1720. dst_config = _patch_pool_config(dst_config, pool, pools)
  1721. result[name] = dst_config
  1722. return result