qubesvm.py 62 KB

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