app.py 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546
  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) 2011-2015 Marek Marczykowski-Górecki
  6. # <marmarek@invisiblethingslab.com>
  7. # Copyright (C) 2014-2015 Wojtek Porczyk <woju@invisiblethingslab.com>
  8. #
  9. # This library is free software; you can redistribute it and/or
  10. # modify it under the terms of the GNU Lesser General Public
  11. # License as published by the Free Software Foundation; either
  12. # version 2.1 of the License, or (at your option) any later version.
  13. #
  14. # This library 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 GNU
  17. # Lesser General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU Lesser General Public
  20. # License along with this library; if not, see <https://www.gnu.org/licenses/>.
  21. #
  22. import collections
  23. import copy
  24. import functools
  25. import grp
  26. import itertools
  27. import logging
  28. import os
  29. import random
  30. import sys
  31. import tempfile
  32. import time
  33. import traceback
  34. import uuid
  35. import asyncio
  36. import jinja2
  37. import libvirt
  38. import lxml.etree
  39. try:
  40. import xen.lowlevel.xs # pylint: disable=wrong-import-order
  41. import xen.lowlevel.xc # pylint: disable=wrong-import-order
  42. except ImportError:
  43. pass
  44. if os.name == 'posix':
  45. # pylint: disable=wrong-import-order
  46. import fcntl
  47. elif os.name == 'nt':
  48. # pylint: disable=import-error
  49. import win32con
  50. import win32file
  51. import pywintypes
  52. else:
  53. raise RuntimeError("Qubes works only on POSIX or WinNT systems")
  54. # pylint: disable=wrong-import-position
  55. import qubes
  56. import qubes.ext
  57. import qubes.utils
  58. import qubes.storage
  59. import qubes.storage.reflink
  60. import qubes.vm
  61. import qubes.vm.adminvm
  62. import qubes.vm.qubesvm
  63. import qubes.vm.templatevm
  64. # pylint: enable=wrong-import-position
  65. class VirDomainWrapper:
  66. # pylint: disable=too-few-public-methods
  67. def __init__(self, connection, vm):
  68. self._connection = connection
  69. self._vm = vm
  70. def _reconnect_if_dead(self):
  71. try:
  72. is_dead = not self._vm.connect().isAlive()
  73. except libvirt.libvirtError as ex:
  74. if ex.get_error_code() == libvirt.VIR_ERR_INVALID_CONN:
  75. # connection to libvirt was re-established in the meantime
  76. is_dead = True
  77. else:
  78. raise
  79. if is_dead:
  80. # pylint: disable=protected-access
  81. self._connection._reconnect_if_dead()
  82. self._vm = self._connection._conn.lookupByUUID(self._vm.UUID())
  83. return is_dead
  84. def __getattr__(self, attrname):
  85. attr = getattr(self._vm, attrname)
  86. if not isinstance(attr, collections.Callable):
  87. return attr
  88. @functools.wraps(attr)
  89. def wrapper(*args, **kwargs):
  90. try:
  91. return attr(*args, **kwargs)
  92. except libvirt.libvirtError:
  93. if self._reconnect_if_dead():
  94. return getattr(self._vm, attrname)(*args, **kwargs)
  95. raise
  96. return wrapper
  97. class VirConnectWrapper:
  98. # pylint: disable=too-few-public-methods
  99. def __init__(self, uri, reconnect_cb=None):
  100. self._conn = libvirt.open(uri)
  101. self._reconnect_cb = reconnect_cb
  102. def _reconnect_if_dead(self):
  103. is_dead = not self._conn.isAlive()
  104. if is_dead:
  105. uri = self._conn.getURI()
  106. old_conn = self._conn
  107. self._conn = libvirt.open(uri)
  108. if callable(self._reconnect_cb):
  109. self._reconnect_cb(old_conn)
  110. old_conn.close()
  111. return is_dead
  112. def _wrap_domain(self, ret):
  113. if isinstance(ret, libvirt.virDomain):
  114. ret = VirDomainWrapper(self, ret)
  115. return ret
  116. def __getattr__(self, attrname):
  117. attr = getattr(self._conn, attrname)
  118. if not isinstance(attr, collections.Callable):
  119. return attr
  120. if attrname == 'close':
  121. return attr
  122. @functools.wraps(attr)
  123. def wrapper(*args, **kwargs):
  124. try:
  125. return self._wrap_domain(attr(*args, **kwargs))
  126. except libvirt.libvirtError:
  127. if self._reconnect_if_dead():
  128. return self._wrap_domain(
  129. getattr(self._conn, attrname)(*args, **kwargs))
  130. raise
  131. return wrapper
  132. class VMMConnection:
  133. """Connection to Virtual Machine Manager (libvirt)"""
  134. def __init__(self, offline_mode=None, libvirt_reconnect_cb=None):
  135. """
  136. :param offline_mode: enable/disable offline mode; default is to
  137. enable when running in chroot as root, otherwise disable
  138. :param libvirt_reconnect_cb: callable to be called when connection to
  139. libvirt is re-established; the callback is called with old connection
  140. as argument
  141. """
  142. if offline_mode is None:
  143. offline_mode = bool(os.getuid() == 0 and
  144. os.stat('/') != os.stat('/proc/1/root/.'))
  145. self._offline_mode = offline_mode
  146. self._libvirt_reconnect_cb = libvirt_reconnect_cb
  147. self._libvirt_conn = None
  148. self._xs = None
  149. self._xc = None
  150. @property
  151. def offline_mode(self):
  152. """Check or enable offline mode (do not actually connect to vmm)"""
  153. return self._offline_mode
  154. def _libvirt_error_handler(self, ctx, error):
  155. pass
  156. def init_vmm_connection(self):
  157. """Initialise connection
  158. This method is automatically called when getting"""
  159. if self._libvirt_conn is not None:
  160. # Already initialized
  161. return
  162. if self._offline_mode:
  163. # Do not initialize in offline mode
  164. raise qubes.exc.QubesException(
  165. 'VMM operations disabled in offline mode')
  166. if 'xen.lowlevel.xs' in sys.modules:
  167. self._xs = xen.lowlevel.xs.xs()
  168. if 'xen.lowlevel.xc' in sys.modules:
  169. self._xc = xen.lowlevel.xc.xc()
  170. self._libvirt_conn = VirConnectWrapper(
  171. qubes.config.defaults['libvirt_uri'],
  172. reconnect_cb=self._libvirt_reconnect_cb)
  173. libvirt.registerErrorHandler(self._libvirt_error_handler, None)
  174. @property
  175. def libvirt_conn(self):
  176. """Connection to libvirt"""
  177. self.init_vmm_connection()
  178. return self._libvirt_conn
  179. @property
  180. def xs(self):
  181. """Connection to Xen Store
  182. This property in available only when running on Xen.
  183. """
  184. # XXX what about the case when we run under KVM,
  185. # but xen modules are importable?
  186. if 'xen.lowlevel.xs' not in sys.modules:
  187. raise AttributeError(
  188. 'xs object is available under Xen hypervisor only')
  189. self.init_vmm_connection()
  190. return self._xs
  191. @property
  192. def xc(self):
  193. """Connection to Xen
  194. This property in available only when running on Xen.
  195. """
  196. # XXX what about the case when we run under KVM,
  197. # but xen modules are importable?
  198. if 'xen.lowlevel.xc' not in sys.modules:
  199. raise AttributeError(
  200. 'xc object is available under Xen hypervisor only')
  201. self.init_vmm_connection()
  202. return self._xc
  203. def close(self):
  204. libvirt.registerErrorHandler(None, None)
  205. if self._xs:
  206. self._xs.close()
  207. self._xs = None
  208. if self._libvirt_conn:
  209. self._libvirt_conn.close()
  210. self._libvirt_conn = None
  211. self._xc = None # and pray it will get garbage-collected
  212. class QubesHost:
  213. """Basic information about host machine
  214. :param qubes.Qubes app: Qubes application context (must have \
  215. :py:attr:`Qubes.vmm` attribute defined)
  216. """
  217. def __init__(self, app):
  218. self.app = app
  219. self._no_cpus = None
  220. self._total_mem = None
  221. self._physinfo = None
  222. def _fetch(self):
  223. if self._no_cpus is not None:
  224. return
  225. # pylint: disable=unused-variable
  226. (model, memory, cpus, mhz, nodes, socket, cores, threads) = \
  227. self.app.vmm.libvirt_conn.getInfo()
  228. self._total_mem = int(memory) * 1024
  229. self._no_cpus = cpus
  230. self.app.log.debug('QubesHost: no_cpus={} memory_total={}'.format(
  231. self.no_cpus, self.memory_total))
  232. try:
  233. self.app.log.debug('QubesHost: xen_free_memory={}'.format(
  234. self.get_free_xen_memory()))
  235. except NotImplementedError:
  236. pass
  237. @property
  238. def memory_total(self):
  239. """Total memory, in kbytes"""
  240. if self.app.vmm.offline_mode:
  241. return 2 ** 64 - 1
  242. self._fetch()
  243. return self._total_mem
  244. @property
  245. def no_cpus(self):
  246. """Number of CPUs"""
  247. if self.app.vmm.offline_mode:
  248. return 42
  249. self._fetch()
  250. return self._no_cpus
  251. def get_free_xen_memory(self):
  252. """Get free memory from Xen's physinfo.
  253. :raises NotImplementedError: when not under Xen
  254. """
  255. try:
  256. self._physinfo = self.app.vmm.xc.physinfo()
  257. except AttributeError:
  258. raise NotImplementedError('This function requires Xen hypervisor')
  259. return int(self._physinfo['free_memory'])
  260. def is_iommu_supported(self):
  261. """Check if IOMMU is supported on this platform"""
  262. if self._physinfo is None:
  263. try:
  264. self._physinfo = self.app.vmm.xc.physinfo()
  265. except AttributeError:
  266. raise NotImplementedError(
  267. 'This function requires Xen hypervisor')
  268. return 'hvm_directio' in self._physinfo['virt_caps']
  269. def get_vm_stats(self, previous_time=None, previous=None, only_vm=None):
  270. """Measure cpu usage for all domains at once.
  271. If previous measurements are given, CPU usage will be given in
  272. percents of time. Otherwise only absolute value (seconds).
  273. Return a tuple of (measurements_time, measurements),
  274. where measurements is a dictionary with key: domid, value: dict:
  275. - cpu_time - absolute CPU usage (seconds since its startup)
  276. - cpu_usage_raw - CPU usage in %
  277. - cpu_usage - CPU usage in % (normalized to number of vcpus)
  278. - memory_kb - current memory assigned, in kb
  279. This function requires Xen hypervisor.
  280. ..warning:
  281. This function may return info about implementation-specific VMs,
  282. like stubdomains for HVM
  283. :param previous: previous measurement
  284. :param previous_time: time of previous measurement
  285. :param only_vm: get measurements only for this VM
  286. :raises NotImplementedError: when not under Xen
  287. """
  288. if (previous_time is None) != (previous is None):
  289. raise ValueError(
  290. 'previous and previous_time must be given together (or none)')
  291. if previous is None:
  292. previous = {}
  293. current_time = time.time()
  294. current = {}
  295. try:
  296. if only_vm:
  297. xid = only_vm.xid
  298. if xid < 0:
  299. raise qubes.exc.QubesVMNotRunningError(only_vm)
  300. info = self.app.vmm.xc.domain_getinfo(xid, 1)
  301. if info[0]['domid'] != xid:
  302. raise qubes.exc.QubesVMNotRunningError(only_vm)
  303. else:
  304. info = self.app.vmm.xc.domain_getinfo(0, 1024)
  305. except AttributeError:
  306. raise NotImplementedError(
  307. 'This function requires Xen hypervisor')
  308. # TODO: add stubdomain stats to actual VMs
  309. for vm in info:
  310. domid = vm['domid']
  311. current[domid] = {}
  312. current[domid]['memory_kb'] = vm['mem_kb']
  313. current[domid]['cpu_time'] = int(vm['cpu_time'])
  314. vcpus = max(vm['online_vcpus'], 1)
  315. if domid in previous:
  316. current[domid]['cpu_usage_raw'] = int(
  317. (current[domid]['cpu_time'] - previous[domid]['cpu_time'])
  318. / 1000 ** 3 * 100 / (current_time - previous_time))
  319. if current[domid]['cpu_usage_raw'] < 0:
  320. # VM has been rebooted
  321. current[domid]['cpu_usage_raw'] = 0
  322. else:
  323. current[domid]['cpu_usage_raw'] = 0
  324. current[domid]['cpu_usage'] = \
  325. int(current[domid]['cpu_usage_raw'] / vcpus)
  326. return current_time, current
  327. class VMCollection:
  328. """A collection of Qubes VMs
  329. VMCollection supports ``in`` operator. You may test for ``qid``, ``name``
  330. and whole VM object's presence.
  331. Iterating over VMCollection will yield machine objects.
  332. """
  333. def __init__(self, app):
  334. self.app = app
  335. self._dict = dict()
  336. def close(self):
  337. del self.app
  338. self._dict.clear()
  339. del self._dict
  340. def __repr__(self):
  341. return '<{} {!r}>'.format(
  342. self.__class__.__name__, list(sorted(self.keys())))
  343. def items(self):
  344. """Iterate over ``(qid, vm)`` pairs"""
  345. for qid in self.qids():
  346. yield (qid, self[qid])
  347. def qids(self):
  348. """Iterate over all qids
  349. qids are sorted by numerical order.
  350. """
  351. return iter(sorted(self._dict.keys()))
  352. keys = qids
  353. def names(self):
  354. """Iterate over all names
  355. names are sorted by lexical order.
  356. """
  357. return iter(sorted(vm.name for vm in self._dict.values()))
  358. def vms(self):
  359. """Iterate over all machines
  360. vms are sorted by qid.
  361. """
  362. return iter(sorted(self._dict.values()))
  363. __iter__ = vms
  364. values = vms
  365. def add(self, value, _enable_events=True):
  366. """Add VM to collection
  367. :param qubes.vm.BaseVM value: VM to add
  368. :param _enable_events:
  369. :raises TypeError: when value is of wrong type
  370. :raises ValueError: when there is already VM which has equal ``qid``
  371. """
  372. # this violates duck typing, but is needed
  373. # for VMProperty to function correctly
  374. if not isinstance(value, qubes.vm.BaseVM):
  375. raise TypeError('{} holds only BaseVM instances'.format(
  376. self.__class__.__name__))
  377. if value.qid in self:
  378. raise ValueError('This collection already holds VM that has '
  379. 'qid={!r} ({!r})'.format(value.qid,
  380. self[value.qid]))
  381. if value.name in self:
  382. raise ValueError('A VM named {!s} already exists'
  383. .format(value.name))
  384. self._dict[value.qid] = value
  385. if _enable_events:
  386. value.events_enabled = True
  387. self.app.fire_event('domain-add', vm=value)
  388. return value
  389. def __getitem__(self, key):
  390. if isinstance(key, int):
  391. return self._dict[key]
  392. if isinstance(key, str):
  393. for vm in self:
  394. if vm.name == key:
  395. return vm
  396. raise KeyError(key)
  397. if isinstance(key, qubes.vm.BaseVM):
  398. key = key.uuid
  399. if isinstance(key, uuid.UUID):
  400. for vm in self:
  401. if vm.uuid == key:
  402. return vm
  403. raise KeyError(key)
  404. raise KeyError(key)
  405. def __delitem__(self, key):
  406. vm = self[key]
  407. if not vm.is_halted():
  408. raise qubes.exc.QubesVMNotHaltedError(vm)
  409. self.app.fire_event('domain-pre-delete', pre_event=True, vm=vm)
  410. try:
  411. if vm.libvirt_domain:
  412. vm.libvirt_domain.undefine()
  413. # pylint: disable=protected-access
  414. vm._libvirt_domain = None
  415. except libvirt.libvirtError as e:
  416. if e.get_error_code() == libvirt.VIR_ERR_NO_DOMAIN:
  417. # already undefined
  418. pass
  419. del self._dict[vm.qid]
  420. self.app.fire_event('domain-delete', vm=vm)
  421. def __contains__(self, key):
  422. return any((key in (vm, vm.qid, vm.name))
  423. for vm in self)
  424. def __len__(self):
  425. return len(self._dict)
  426. def get_vms_based_on(self, template):
  427. template = self[template]
  428. return set(vm for vm in self
  429. if hasattr(vm, 'template') and vm.template == template)
  430. def get_vms_connected_to(self, netvm):
  431. new_vms = {self[netvm]}
  432. dependent_vms = set()
  433. # Dependency resolving only makes sense on NetVM (or derivative)
  434. # if not self[netvm_qid].is_netvm():
  435. # return set([])
  436. while new_vms:
  437. cur_vm = new_vms.pop()
  438. for vm in cur_vm.connected_vms:
  439. if vm in dependent_vms:
  440. continue
  441. dependent_vms.add(vm)
  442. # if vm.is_netvm():
  443. new_vms.add(vm)
  444. return dependent_vms
  445. # XXX with Qubes Admin Api this will probably lead to race condition
  446. # whole process of creating and adding should be synchronised
  447. def get_new_unused_qid(self):
  448. used_ids = set(self.qids())
  449. for i in range(1, qubes.config.max_qid):
  450. if i not in used_ids:
  451. return i
  452. raise LookupError("Cannot find unused qid!")
  453. def get_new_unused_dispid(self):
  454. for _ in range(int(qubes.config.max_dispid ** 0.5)):
  455. dispid = random.SystemRandom().randrange(qubes.config.max_dispid)
  456. if not any(getattr(vm, 'dispid', None) == dispid for vm in self):
  457. return dispid
  458. raise LookupError((
  459. 'https://xkcd.com/221/',
  460. 'http://dilbert.com/strip/2001-10-25')[
  461. random.randint(0, 1)])
  462. def _default_pool(app):
  463. """ Default storage pool.
  464. 1. If there is one named 'default', use it.
  465. 2. Check if root fs is on LVM thin - use that
  466. 3. Look for file(-reflink)-based pool pointing to /var/lib/qubes
  467. 4. Fail
  468. """
  469. if 'default' in app.pools:
  470. return app.pools['default']
  471. if 'DEFAULT_LVM_POOL' in os.environ:
  472. thin_pool = os.environ['DEFAULT_LVM_POOL']
  473. for pool in app.pools.values():
  474. if pool.config.get('driver', None) != 'lvm_thin':
  475. continue
  476. if pool.config['thin_pool'] == thin_pool:
  477. return pool
  478. # no DEFAULT_LVM_POOL, or pool not defined
  479. root_volume_group, root_thin_pool = \
  480. qubes.storage.DirectoryThinPool.thin_pool('/')
  481. if root_thin_pool:
  482. for pool in app.pools.values():
  483. if pool.config.get('driver', None) != 'lvm_thin':
  484. continue
  485. if (pool.config['volume_group'] == root_volume_group and
  486. pool.config['thin_pool'] == root_thin_pool):
  487. return pool
  488. # not a thin volume? look for file pools
  489. for pool in app.pools.values():
  490. if pool.config.get('driver', None) not in ('file', 'file-reflink'):
  491. continue
  492. if pool.config['dir_path'] == qubes.config.qubes_base_dir:
  493. return pool
  494. raise AttributeError('Cannot determine default storage pool')
  495. def _setter_pool(app, prop, value):
  496. if isinstance(value, qubes.storage.Pool):
  497. return value
  498. try:
  499. return app.pools[value]
  500. except KeyError:
  501. raise qubes.exc.QubesPropertyValueError(app, prop, value,
  502. 'No such storage pool')
  503. def _setter_default_netvm(app, prop, value):
  504. # skip netvm loop check while loading qubes.xml, to avoid tricky loading
  505. # order
  506. if not app.events_enabled:
  507. return value
  508. if value is None:
  509. return value
  510. # forbid setting to a value that would result in netvm loop
  511. for vm in app.domains:
  512. if not hasattr(vm, 'netvm'):
  513. continue
  514. if not vm.property_is_default('netvm'):
  515. continue
  516. if value == vm \
  517. or value in app.domains.get_vms_connected_to(vm):
  518. raise qubes.exc.QubesPropertyValueError(
  519. app, prop, value, 'Network loop on \'{!s}\''.format(vm))
  520. return value
  521. class Qubes(qubes.PropertyHolder):
  522. """Main Qubes application
  523. :param str store: path to ``qubes.xml``
  524. The store is loaded in stages:
  525. 1. In the first stage there are loaded some basic features from store
  526. (currently labels).
  527. 2. In the second stage stubs for all VMs are loaded. They are filled
  528. with their basic properties, like ``qid`` and ``name``.
  529. 3. In the third stage all global properties are loaded. They often
  530. reference VMs, like default netvm, so they should be filled after
  531. loading VMs.
  532. 4. In the fourth stage all remaining VM properties are loaded. They
  533. also need all VMs loaded, because they represent dependencies
  534. between VMs like aforementioned netvm.
  535. 5. In the fifth stage there are some fixups to ensure sane system
  536. operation.
  537. This class emits following events:
  538. .. event:: domain-add (subject, event, vm)
  539. When domain is added.
  540. :param subject: Event emitter
  541. :param event: Event name (``'domain-add'``)
  542. :param vm: Domain object
  543. .. event:: domain-pre-delete (subject, event, vm)
  544. When domain is deleted. VM still has reference to ``app`` object,
  545. and is contained within VMCollection. You may prevent removal by
  546. raising an exception.
  547. :param subject: Event emitter
  548. :param event: Event name (``'domain-pre-delete'``)
  549. :param vm: Domain object
  550. .. event:: domain-delete (subject, event, vm)
  551. When domain is deleted. VM still has reference to ``app`` object,
  552. but is not contained within VMCollection.
  553. :param subject: Event emitter
  554. :param event: Event name (``'domain-delete'``)
  555. :param vm: Domain object
  556. .. event:: pool-add (subject, event, pool)
  557. When storage pool is added.
  558. Handler for this event can be asynchronous (a coroutine).
  559. :param subject: Event emitter
  560. :param event: Event name (``'pool-add'``)
  561. :param pool: Pool object
  562. .. event:: pool-pre-delete (subject, event, pool)
  563. When pool is deleted. Pool is still contained within app.pools
  564. dictionary. You may prevent removal by raising an exception.
  565. Handler for this event can be asynchronous (a coroutine).
  566. :param subject: Event emitter
  567. :param event: Event name (``'pool-pre-delete'``)
  568. :param pool: Pool object
  569. .. event:: pool-delete (subject, event, pool)
  570. When storage pool is deleted. The pool is already removed at this
  571. point.
  572. Handler for this event can be asynchronous (a coroutine).
  573. :param subject: Event emitter
  574. :param event: Event name (``'pool-delete'``)
  575. :param pool: Pool object
  576. .. event:: qubes-close (subject, event)
  577. Fired when this Qubes() object instance is going to be closed
  578. and destroyed. In practice it is called only during tests, to
  579. cleanup objects from one test, before another.
  580. It is _not_ called when qubesd daemon is stopped.
  581. :param subject: Event emitter
  582. :param event: Event name (``'qubes-close'``)
  583. Methods and attributes:
  584. """
  585. default_guivm = qubes.VMProperty(
  586. 'default_guivm',
  587. load_stage=3,
  588. default=lambda app: app.domains['dom0'], allow_none=True,
  589. doc='Default GuiVM for VMs.')
  590. default_netvm = qubes.VMProperty(
  591. 'default_netvm',
  592. load_stage=3,
  593. default=None, allow_none=True,
  594. setter=_setter_default_netvm,
  595. doc="""Default NetVM for AppVMs. Initial state is `None`, which means
  596. that AppVMs are not connected to the Internet.""")
  597. default_template = qubes.VMProperty(
  598. 'default_template', load_stage=3,
  599. vmclass=qubes.vm.templatevm.TemplateVM,
  600. doc='Default template for new AppVMs',
  601. allow_none=True)
  602. updatevm = qubes.VMProperty(
  603. 'updatevm', load_stage=3,
  604. default=None, allow_none=True,
  605. doc="""Which VM to use as `yum` proxy for updating AdminVM and
  606. TemplateVMs""")
  607. clockvm = qubes.VMProperty(
  608. 'clockvm', load_stage=3,
  609. default=None, allow_none=True,
  610. doc='Which VM to use as NTP proxy for updating '
  611. 'AdminVM')
  612. default_kernel = qubes.property(
  613. 'default_kernel', load_stage=3,
  614. doc='Which kernel to use when not overriden in VM')
  615. default_dispvm = qubes.VMProperty(
  616. 'default_dispvm',
  617. load_stage=3,
  618. default=None,
  619. doc='Default DispVM base for service calls',
  620. allow_none=True)
  621. management_dispvm = qubes.VMProperty(
  622. 'management_dispvm',
  623. load_stage=3,
  624. default=None,
  625. doc='Default DispVM base for managing VMs',
  626. allow_none=True)
  627. default_pool = qubes.property(
  628. 'default_pool',
  629. load_stage=3,
  630. default=_default_pool,
  631. setter=_setter_pool,
  632. doc='Default storage pool')
  633. default_pool_private = qubes.property(
  634. 'default_pool_private',
  635. load_stage=3,
  636. default=lambda app: app.default_pool,
  637. setter=_setter_pool,
  638. doc='Default storage pool for private volumes')
  639. default_pool_root = qubes.property(
  640. 'default_pool_root',
  641. load_stage=3,
  642. default=lambda app: app.default_pool,
  643. setter=_setter_pool,
  644. doc='Default storage pool for root volumes')
  645. default_pool_volatile = qubes.property(
  646. 'default_pool_volatile',
  647. load_stage=3,
  648. default=lambda app: app.default_pool,
  649. setter=_setter_pool,
  650. doc='Default storage pool for volatile volumes')
  651. default_pool_kernel = qubes.property(
  652. 'default_pool_kernel',
  653. load_stage=3,
  654. default=lambda app: app.default_pool,
  655. setter=_setter_pool,
  656. doc='Default storage pool for kernel volumes')
  657. default_qrexec_timeout = qubes.property(
  658. 'default_qrexec_timeout',
  659. load_stage=3,
  660. default=60,
  661. type=int,
  662. doc="""Default time in seconds after which qrexec connection attempt
  663. is deemed failed""")
  664. default_shutdown_timeout = qubes.property(
  665. 'default_shutdown_timeout',
  666. load_stage=3,
  667. default=60,
  668. type=int,
  669. doc="""Default time in seconds for VM shutdown to complete""")
  670. stats_interval = qubes.property(
  671. 'stats_interval',
  672. load_stage=3,
  673. default=3,
  674. type=int,
  675. doc='Interval in seconds for VM stats reporting (memory, CPU usage)')
  676. # TODO #1637 #892
  677. check_updates_vm = qubes.property(
  678. 'check_updates_vm',
  679. type=bool,
  680. setter=qubes.property.bool,
  681. load_stage=3,
  682. default=True,
  683. doc='Check for updates inside qubes')
  684. def __init__(self, store=None, load=True, offline_mode=None, lock=False,
  685. **kwargs):
  686. #: logger instance for logging global messages
  687. self.log = logging.getLogger('app')
  688. self.log.debug('init() -> %#x', id(self))
  689. self.log.debug('stack:')
  690. for frame in traceback.extract_stack():
  691. self.log.debug('%s', frame)
  692. self._extensions = qubes.ext.get_extensions()
  693. #: collection of all VMs managed by this Qubes instance
  694. self.domains = VMCollection(self)
  695. #: collection of all available labels for VMs
  696. self.labels = {}
  697. #: collection of all pools
  698. self.pools = {}
  699. #: Connection to VMM
  700. self.vmm = VMMConnection(
  701. offline_mode=offline_mode,
  702. libvirt_reconnect_cb=self.register_event_handlers)
  703. #: Information about host system
  704. self.host = QubesHost(self)
  705. if store is not None:
  706. self._store = store
  707. else:
  708. self._store = os.environ.get('QUBES_XML_PATH',
  709. os.path.join(
  710. qubes.config.qubes_base_dir,
  711. qubes.config.system_path[
  712. 'qubes_store_filename']))
  713. super(Qubes, self).__init__(xml=None, **kwargs)
  714. self.__load_timestamp = None
  715. self.__locked_fh = None
  716. self._domain_event_callback_id = None
  717. #: jinja2 environment for libvirt XML templates
  718. self.env = jinja2.Environment(
  719. loader=jinja2.FileSystemLoader([
  720. '/etc/qubes/templates',
  721. '/usr/share/qubes/templates',
  722. ]),
  723. undefined=jinja2.StrictUndefined)
  724. if load:
  725. self.load(lock=lock)
  726. self.events_enabled = True
  727. @property
  728. def store(self):
  729. return self._store
  730. def _migrate_global_properties(self):
  731. """Migrate renamed/dropped properties"""
  732. if self.xml is None:
  733. return
  734. # drop default_fw_netvm
  735. node_default_fw_netvm = self.xml.find(
  736. './properties/property[@name=\'default_fw_netvm\']')
  737. if node_default_fw_netvm is not None:
  738. node_default_netvm = self.xml.find(
  739. './properties/property[@name=\'default_netvm\']')
  740. try:
  741. default_fw_netvm = self.domains[node_default_fw_netvm.text]
  742. if node_default_netvm is None:
  743. default_netvm = None
  744. else:
  745. default_netvm = self.domains[node_default_netvm.text]
  746. if default_netvm != default_fw_netvm:
  747. for vm in self.domains:
  748. if not hasattr(vm, 'netvm'):
  749. continue
  750. if not getattr(vm, 'provides_network', False):
  751. continue
  752. node_netvm = vm.xml.find(
  753. './properties/property[@name=\'netvm\']')
  754. if node_netvm is not None:
  755. # non-default netvm
  756. continue
  757. # this will unfortunately break "being default"
  758. # property state, but the alternative (changing
  759. # value behind user's back) is worse
  760. properties = vm.xml.find('./properties')
  761. element = lxml.etree.Element('property',
  762. name='netvm')
  763. element.text = default_fw_netvm.name
  764. # manipulate xml directly, before loading netvm
  765. # property, to avoid hitting netvm loop detection
  766. properties.append(element)
  767. except KeyError:
  768. # if default_fw_netvm was set to invalid value, simply
  769. # drop it
  770. pass
  771. node_default_fw_netvm.getparent().remove(node_default_fw_netvm)
  772. def load(self, lock=False):
  773. """Open qubes.xml
  774. :throws EnvironmentError: failure on parsing store
  775. :throws xml.parsers.expat.ExpatError: failure on parsing store
  776. :raises lxml.etree.XMLSyntaxError: on syntax error in qubes.xml
  777. """
  778. fh = self._acquire_lock()
  779. self.xml = lxml.etree.parse(fh)
  780. # stage 1: load labels and pools
  781. for node in self.xml.xpath('./labels/label'):
  782. label = qubes.Label.fromxml(node)
  783. self.labels[label.index] = label
  784. for node in self.xml.xpath('./pools/pool'):
  785. name = node.get('name')
  786. assert name, "Pool name '%s' is invalid " % name
  787. try:
  788. self.pools[name] = self._get_pool(**node.attrib)
  789. except qubes.exc.QubesException as e:
  790. self.log.error(str(e))
  791. # stage 2: load VMs
  792. for node in self.xml.xpath('./domains/domain'):
  793. # pylint: disable=no-member
  794. cls = self.get_vm_class(node.get('class'))
  795. vm = cls(self, node)
  796. vm.load_properties(load_stage=2)
  797. vm.init_log()
  798. self.domains.add(vm, _enable_events=False)
  799. if 0 not in self.domains:
  800. self.domains.add(
  801. qubes.vm.adminvm.AdminVM(self, None),
  802. _enable_events=False)
  803. self._migrate_global_properties()
  804. # stage 3: load global properties
  805. self.load_properties(load_stage=3)
  806. # stage 4: fill all remaining VM properties
  807. for vm in self.domains:
  808. vm.load_properties(load_stage=4)
  809. vm.load_extras()
  810. # stage 5: misc fixups
  811. self.property_require('default_guivm', allow_none=True)
  812. self.property_require('default_netvm', allow_none=True)
  813. self.property_require('default_template', allow_none=True)
  814. self.property_require('clockvm', allow_none=True)
  815. self.property_require('updatevm', allow_none=True)
  816. for vm in self.domains:
  817. vm.events_enabled = True
  818. vm.fire_event('domain-load')
  819. # get a file timestamp (before closing it - still holding the lock!),
  820. # to detect whether anyone else have modified it in the meantime
  821. self.__load_timestamp = os.path.getmtime(self._store)
  822. if not lock:
  823. self._release_lock()
  824. def __xml__(self):
  825. element = lxml.etree.Element('qubes')
  826. element.append(self.xml_labels())
  827. pools_xml = lxml.etree.Element('pools')
  828. for pool in self.pools.values():
  829. xml = pool.__xml__()
  830. if xml is not None:
  831. pools_xml.append(xml)
  832. element.append(pools_xml)
  833. element.append(self.xml_properties())
  834. domains = lxml.etree.Element('domains')
  835. for vm in self.domains:
  836. domains.append(vm.__xml__())
  837. element.append(domains)
  838. return element
  839. def __str__(self):
  840. return type(self).__name__
  841. def save(self, lock=True):
  842. """Save all data to qubes.xml
  843. There are several problems with saving :file:`qubes.xml` which must be
  844. mitigated:
  845. - Running out of disk space. No space left should not result in empty
  846. file. This is done by writing to temporary file and then renaming.
  847. - Attempts to write two or more files concurrently. This is done by
  848. sophisticated locking.
  849. :param bool lock: keep file locked after saving
  850. :throws EnvironmentError: failure on saving
  851. """
  852. if not self.__locked_fh:
  853. self._acquire_lock(for_save=True)
  854. fh_new = tempfile.NamedTemporaryFile(
  855. prefix=self._store, delete=False)
  856. lxml.etree.ElementTree(self.__xml__()).write(
  857. fh_new, encoding='utf-8', pretty_print=True)
  858. fh_new.flush()
  859. try:
  860. os.chown(fh_new.name, -1, grp.getgrnam('qubes').gr_gid)
  861. os.chmod(fh_new.name, 0o660)
  862. except KeyError: # group 'qubes' not found
  863. # don't change mode if no 'qubes' group in the system
  864. pass
  865. os.rename(fh_new.name, self._store)
  866. # update stored mtime, in case of multiple save() calls without
  867. # loading qubes.xml again
  868. self.__load_timestamp = os.path.getmtime(self._store)
  869. # this releases lock for all other processes,
  870. # but they should instantly block on the new descriptor
  871. self.__locked_fh.close()
  872. self.__locked_fh = fh_new
  873. if not lock:
  874. self._release_lock()
  875. def close(self):
  876. """Deconstruct the object and break circular references
  877. After calling this the object is unusable, not even for saving."""
  878. self.log.debug('close() <- %#x', id(self))
  879. for frame in traceback.extract_stack():
  880. self.log.debug('%s', frame)
  881. # let all the extension cleanup things
  882. self.fire_event('qubes-close')
  883. super().close()
  884. if self._domain_event_callback_id is not None:
  885. self.vmm.libvirt_conn.domainEventDeregisterAny(
  886. self._domain_event_callback_id)
  887. self._domain_event_callback_id = None
  888. # Only our Lord, The God Almighty, knows what references
  889. # are kept in extensions.
  890. # NOTE: this doesn't really delete extension objects - Extension class
  891. # saves reference to instance, and also various registered (class level)
  892. # event handlers do that too
  893. del self._extensions
  894. for vm in self.domains:
  895. vm.close()
  896. self.domains.close()
  897. del self.domains
  898. self.vmm.close()
  899. del self.vmm
  900. del self.host
  901. if self.__locked_fh:
  902. self._release_lock()
  903. def _acquire_lock(self, for_save=False):
  904. assert self.__locked_fh is None, 'double lock'
  905. while True:
  906. try:
  907. fd = os.open(self._store,
  908. os.O_RDWR | (os.O_CREAT * int(for_save)))
  909. except FileNotFoundError:
  910. if not for_save:
  911. raise qubes.exc.QubesException(
  912. 'Qubes XML store {!r} is missing; '
  913. 'use qubes-create tool'.format(self._store))
  914. raise
  915. # While we were waiting for lock, someone could have unlink()ed
  916. # (or rename()d) our file out of the filesystem. We have to
  917. # ensure we got lock on something linked to filesystem.
  918. # If not, try again.
  919. if os.fstat(fd) != os.stat(self._store):
  920. os.close(fd)
  921. continue
  922. if self.__load_timestamp and \
  923. os.path.getmtime(self._store) != self.__load_timestamp:
  924. os.close(fd)
  925. raise qubes.exc.QubesException(
  926. 'Someone else modified qubes.xml in the meantime')
  927. break
  928. if os.name == 'posix':
  929. fcntl.lockf(fd, fcntl.LOCK_EX)
  930. elif os.name == 'nt':
  931. # pylint: disable=protected-access
  932. overlapped = pywintypes.OVERLAPPED()
  933. win32file.LockFileEx(
  934. win32file._get_osfhandle(fd),
  935. win32con.LOCKFILE_EXCLUSIVE_LOCK, 0, -0x10000, overlapped)
  936. self.__locked_fh = os.fdopen(fd, 'r+b')
  937. return self.__locked_fh
  938. def _release_lock(self):
  939. assert self.__locked_fh is not None, 'double release'
  940. # intentionally do not call explicit unlock to not unlock the file
  941. # before all buffers are flushed
  942. self.__locked_fh.close()
  943. self.__locked_fh = None
  944. def load_initial_values(self):
  945. self.labels = {
  946. 1: qubes.Label(1, '0xcc0000', 'red'),
  947. 2: qubes.Label(2, '0xf57900', 'orange'),
  948. 3: qubes.Label(3, '0xedd400', 'yellow'),
  949. 4: qubes.Label(4, '0x73d216', 'green'),
  950. 5: qubes.Label(5, '0x555753', 'gray'),
  951. 6: qubes.Label(6, '0x3465a4', 'blue'),
  952. 7: qubes.Label(7, '0x75507b', 'purple'),
  953. 8: qubes.Label(8, '0x000000', 'black'),
  954. }
  955. assert max(self.labels.keys()) == qubes.config.max_default_label
  956. pool_configs = copy.deepcopy(qubes.config.defaults['pool_configs'])
  957. root_volume_group, root_thin_pool = \
  958. qubes.storage.DirectoryThinPool.thin_pool('/')
  959. if root_thin_pool:
  960. lvm_config = {
  961. 'name': 'lvm',
  962. 'driver': 'lvm_thin',
  963. 'volume_group': root_volume_group,
  964. 'thin_pool': root_thin_pool
  965. }
  966. pool_configs[lvm_config['name']] = lvm_config
  967. for name, config in pool_configs.items():
  968. if 'driver' not in config and 'dir_path' in config:
  969. config['driver'] = 'file'
  970. try:
  971. os.makedirs(config['dir_path'], exist_ok=True)
  972. if qubes.storage.reflink.is_supported(config['dir_path']):
  973. config['driver'] = 'file-reflink'
  974. config['setup_check'] = 'no' # don't check twice
  975. except PermissionError: # looks like a testing environment
  976. pass # stay with 'file'
  977. self.pools[name] = self._get_pool(**config)
  978. self.default_pool_kernel = 'linux-kernel'
  979. self.domains.add(
  980. qubes.vm.adminvm.AdminVM(self, None, label='black'))
  981. @classmethod
  982. def create_empty_store(cls, *args, **kwargs):
  983. self = cls(*args, load=False, **kwargs)
  984. if os.path.exists(self.store):
  985. raise qubes.exc.QubesException(
  986. '{} already exists, aborting'.format(self.store))
  987. self.load_initial_values()
  988. # TODO py3 get lock= as keyword-only arg
  989. self.save(kwargs.get('lock'))
  990. return self
  991. def xml_labels(self):
  992. """Serialise labels
  993. :rtype: lxml.etree._Element
  994. """
  995. labels = lxml.etree.Element('labels')
  996. for label in sorted(self.labels.values(), key=lambda labl: labl.index):
  997. labels.append(label.__xml__())
  998. return labels
  999. @staticmethod
  1000. def get_vm_class(clsname):
  1001. """Find the class for a domain.
  1002. Classes are registered as setuptools' entry points in ``qubes.vm``
  1003. group. Any package may supply their own classes.
  1004. :param str clsname: name of the class
  1005. :return type: class
  1006. """
  1007. try:
  1008. return qubes.utils.get_entry_point_one(
  1009. qubes.vm.VM_ENTRY_POINT, clsname)
  1010. except KeyError:
  1011. raise qubes.exc.QubesException(
  1012. 'no such VM class: {!r}'.format(clsname))
  1013. # don't catch TypeError
  1014. def add_new_vm(self, cls, qid=None, **kwargs):
  1015. """Add new Virtual Machine to collection
  1016. """
  1017. if qid is None:
  1018. qid = self.domains.get_new_unused_qid()
  1019. if isinstance(cls, str):
  1020. cls = self.get_vm_class(cls)
  1021. # handle default template; specifically allow template=None (do not
  1022. # override it with default template)
  1023. if 'template' not in kwargs and hasattr(cls, 'template'):
  1024. if cls == self.get_vm_class('DispVM'):
  1025. kwargs['template'] = self.default_dispvm
  1026. else:
  1027. kwargs['template'] = self.default_template
  1028. if kwargs['template'] is None:
  1029. raise qubes.exc.QubesValueError(
  1030. 'Template for the qube not specified, nor default '
  1031. 'template set.')
  1032. elif 'template' in kwargs and isinstance(kwargs['template'], str):
  1033. kwargs['template'] = self.domains[kwargs['template']]
  1034. return self.domains.add(cls(self, None, qid=qid, **kwargs))
  1035. def get_label(self, label):
  1036. """Get label as identified by index or name
  1037. :throws KeyError: when label is not found
  1038. """
  1039. # first search for index, verbatim
  1040. try:
  1041. return self.labels[label]
  1042. except KeyError:
  1043. pass
  1044. # then search for name
  1045. for i in self.labels.values():
  1046. if i.name == label:
  1047. return i
  1048. # last call, if label is a number represented as str, search in indices
  1049. try:
  1050. return self.labels[int(label)]
  1051. except (KeyError, ValueError):
  1052. pass
  1053. raise KeyError(label)
  1054. @asyncio.coroutine
  1055. def setup_pools(self):
  1056. """ Run implementation specific setup for each storage pool. """
  1057. yield from qubes.utils.void_coros_maybe(
  1058. pool.setup() for pool in self.pools.values())
  1059. @asyncio.coroutine
  1060. def add_pool(self, name, **kwargs):
  1061. """ Add a storage pool to config."""
  1062. if name in self.pools.keys():
  1063. raise qubes.exc.QubesException('pool named %s already exists \n' %
  1064. name)
  1065. kwargs['name'] = name
  1066. pool = self._get_pool(**kwargs)
  1067. yield from qubes.utils.coro_maybe(pool.setup())
  1068. self.pools[name] = pool
  1069. yield from self.fire_event_async('pool-add', pool=pool)
  1070. return pool
  1071. @asyncio.coroutine
  1072. def remove_pool(self, name):
  1073. """ Remove a storage pool from config file. """
  1074. try:
  1075. pool = self.pools[name]
  1076. volumes = [(vm, volume) for vm in self.domains
  1077. for volume in vm.volumes.values()
  1078. if volume.pool is pool]
  1079. if volumes:
  1080. raise qubes.exc.QubesPoolInUseError(pool)
  1081. prop_suffixes = ['', '_kernel', '_private', '_root', '_volatile']
  1082. for suffix in prop_suffixes:
  1083. if getattr(self, 'default_pool' + suffix, None) is pool:
  1084. raise qubes.exc.QubesPoolInUseError(
  1085. pool,
  1086. 'Storage pool is in use: '
  1087. 'set as {}'.format('default_pool' + suffix))
  1088. yield from self.fire_event_async('pool-pre-delete',
  1089. pre_event=True, pool=pool)
  1090. del self.pools[name]
  1091. yield from qubes.utils.coro_maybe(pool.destroy())
  1092. yield from self.fire_event_async('pool-delete', pool=pool)
  1093. except KeyError:
  1094. return
  1095. def get_pool(self, pool):
  1096. """ Returns a :py:class:`qubes.storage.Pool` instance """
  1097. if isinstance(pool, qubes.storage.Pool):
  1098. return pool
  1099. try:
  1100. return self.pools[pool]
  1101. except KeyError:
  1102. raise qubes.exc.QubesException('Unknown storage pool ' + pool)
  1103. @staticmethod
  1104. def _get_pool(**kwargs):
  1105. try:
  1106. name = kwargs['name']
  1107. assert name, 'Name needs to be an non empty string'
  1108. except KeyError:
  1109. raise qubes.exc.QubesException('No pool name for pool')
  1110. try:
  1111. driver = kwargs['driver']
  1112. except KeyError:
  1113. raise qubes.exc.QubesException('No driver specified for pool ' +
  1114. name)
  1115. try:
  1116. klass = qubes.utils.get_entry_point_one(
  1117. qubes.storage.STORAGE_ENTRY_POINT, driver)
  1118. del kwargs['driver']
  1119. return klass(**kwargs)
  1120. except KeyError:
  1121. raise qubes.exc.QubesException('No driver %s for pool %s' %
  1122. (driver, name))
  1123. def register_event_handlers(self, old_connection=None):
  1124. """Register libvirt event handlers, which will translate libvirt
  1125. events into qubes.events. This function should be called only in
  1126. 'qubesd' process and only when mainloop has been already set.
  1127. """
  1128. if old_connection:
  1129. try:
  1130. old_connection.domainEventDeregisterAny(
  1131. self._domain_event_callback_id)
  1132. except libvirt.libvirtError:
  1133. # the connection is probably in a bad state; but call the above
  1134. # anyway to cleanup the client structures
  1135. pass
  1136. self._domain_event_callback_id = (
  1137. self.vmm.libvirt_conn.domainEventRegisterAny(
  1138. None, # any domain
  1139. libvirt.VIR_DOMAIN_EVENT_ID_LIFECYCLE,
  1140. self._domain_event_callback,
  1141. None))
  1142. def _domain_event_callback(self, _conn, domain, event, _detail, _opaque):
  1143. """Generic libvirt event handler (virConnectDomainEventCallback),
  1144. translate libvirt event into qubes.events.
  1145. """
  1146. if not self.events_enabled:
  1147. return
  1148. try:
  1149. vm = self.domains[domain.name()]
  1150. except KeyError:
  1151. # ignore events for unknown domains
  1152. return
  1153. if event == libvirt.VIR_DOMAIN_EVENT_STOPPED:
  1154. vm.on_libvirt_domain_stopped()
  1155. elif event == libvirt.VIR_DOMAIN_EVENT_SUSPENDED:
  1156. try:
  1157. vm.fire_event('domain-paused')
  1158. except Exception: # pylint: disable=broad-except
  1159. self.log.exception(
  1160. 'Uncaught exception from domain-paused handler '
  1161. 'for domain %s', vm.name)
  1162. elif event == libvirt.VIR_DOMAIN_EVENT_RESUMED:
  1163. try:
  1164. vm.fire_event('domain-unpaused')
  1165. except Exception: # pylint: disable=broad-except
  1166. self.log.exception(
  1167. 'Uncaught exception from domain-unpaused handler '
  1168. 'for domain %s', vm.name)
  1169. @qubes.events.handler('domain-pre-delete')
  1170. def on_domain_pre_deleted(self, event, vm):
  1171. # pylint: disable=unused-argument
  1172. for obj in itertools.chain(self.domains, (self,)):
  1173. if obj is vm:
  1174. # allow removed VM to reference itself
  1175. continue
  1176. for prop in obj.property_list():
  1177. try:
  1178. if isinstance(prop, qubes.vm.VMProperty) and \
  1179. getattr(obj, prop.__name__) == vm:
  1180. self.log.error(
  1181. 'Cannot remove %s, used by %s.%s',
  1182. vm, obj, prop.__name__)
  1183. raise qubes.exc.QubesVMInUseError(
  1184. vm,
  1185. 'Domain is in use: {!r};'
  1186. 'see /var/log/qubes/qubes.log in dom0 for '
  1187. 'details'.format(
  1188. vm.name))
  1189. except AttributeError:
  1190. pass
  1191. assignments = vm.get_provided_assignments()
  1192. if assignments:
  1193. desc = ', '.join(
  1194. assignment.ident for assignment in assignments)
  1195. raise qubes.exc.QubesVMInUseError(
  1196. vm,
  1197. 'VM has devices attached persistently to other VMs: ' +
  1198. desc)
  1199. @qubes.events.handler('domain-delete')
  1200. def on_domain_deleted(self, event, vm):
  1201. # pylint: disable=unused-argument
  1202. for propname in (
  1203. 'default_guivm'
  1204. 'default_netvm',
  1205. 'default_fw_netvm',
  1206. 'clockvm',
  1207. 'updatevm',
  1208. 'default_template',
  1209. ):
  1210. try:
  1211. if getattr(self, propname) == vm:
  1212. delattr(self, propname)
  1213. except AttributeError:
  1214. pass
  1215. @qubes.events.handler('property-pre-set:clockvm')
  1216. def on_property_pre_set_clockvm(self, event, name, newvalue, oldvalue=None):
  1217. # pylint: disable=unused-argument,no-self-use
  1218. if newvalue is None:
  1219. return
  1220. if 'service.clocksync' not in newvalue.features:
  1221. newvalue.features['service.clocksync'] = True
  1222. @qubes.events.handler('property-set:clockvm')
  1223. def on_property_set_clockvm(self, event, name, newvalue, oldvalue=None):
  1224. # pylint: disable=unused-argument,no-self-use
  1225. if oldvalue == newvalue:
  1226. return
  1227. if oldvalue and oldvalue.features.get('service.clocksync', False):
  1228. del oldvalue.features['service.clocksync']
  1229. @qubes.events.handler('property-pre-set:default_netvm')
  1230. def on_property_pre_set_default_netvm(self, event, name, newvalue,
  1231. oldvalue=None):
  1232. # pylint: disable=unused-argument,invalid-name
  1233. if newvalue is not None and oldvalue is not None \
  1234. and oldvalue.is_running() and not newvalue.is_running() \
  1235. and self.domains.get_vms_connected_to(oldvalue):
  1236. raise qubes.exc.QubesVMNotRunningError(
  1237. newvalue,
  1238. 'Cannot change {!r} to domain that '
  1239. 'is not running ({!r}).'.format(
  1240. name, newvalue.name))
  1241. @qubes.events.handler('property-set:default_fw_netvm')
  1242. def on_property_set_default_fw_netvm(self, event, name, newvalue,
  1243. oldvalue=None):
  1244. # pylint: disable=unused-argument,invalid-name
  1245. for vm in self.domains:
  1246. if hasattr(vm, 'provides_network') and vm.provides_network and \
  1247. hasattr(vm, 'netvm') and vm.property_is_default('netvm'):
  1248. # fire property-del:netvm as it is responsible for resetting
  1249. # netvm to it's default value
  1250. vm.fire_event('property-pre-del:netvm', pre_event=True,
  1251. name='netvm', oldvalue=oldvalue)
  1252. vm.fire_event('property-del:netvm',
  1253. name='netvm', oldvalue=oldvalue)
  1254. @qubes.events.handler('property-set:default_netvm')
  1255. def on_property_set_default_netvm(self, event, name, newvalue,
  1256. oldvalue=None):
  1257. # pylint: disable=unused-argument
  1258. for vm in self.domains:
  1259. if hasattr(vm, 'provides_network') and not vm.provides_network and \
  1260. hasattr(vm, 'netvm') and vm.property_is_default('netvm'):
  1261. # fire property-del:netvm as it is responsible for resetting
  1262. # netvm to it's default value
  1263. vm.fire_event('property-pre-del:netvm', pre_event=True,
  1264. name='netvm', oldvalue=oldvalue)
  1265. vm.fire_event('property-del:netvm',
  1266. name='netvm', oldvalue=oldvalue)