qubesvm.py 66 KB

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