qubesvm.py 66 KB

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