qubesvm.py 74 KB

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