qubesvm.py 61 KB

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