qubesvm.py 64 KB

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