qubesvm.py 63 KB

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