app.py 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552
  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.abc
  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.abc.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.abc.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_audiovm = qubes.VMProperty(
  591. 'default_audiovm',
  592. load_stage=3,
  593. default=lambda app: app.domains['dom0'], allow_none=True,
  594. doc='Default AudioVM for VMs.')
  595. default_netvm = qubes.VMProperty(
  596. 'default_netvm',
  597. load_stage=3,
  598. default=None, allow_none=True,
  599. setter=_setter_default_netvm,
  600. doc="""Default NetVM for AppVMs. Initial state is `None`, which means
  601. that AppVMs are not connected to the Internet.""")
  602. default_template = qubes.VMProperty(
  603. 'default_template', load_stage=3,
  604. vmclass=qubes.vm.templatevm.TemplateVM,
  605. doc='Default template for new AppVMs',
  606. allow_none=True)
  607. updatevm = qubes.VMProperty(
  608. 'updatevm', load_stage=3,
  609. default=None, allow_none=True,
  610. doc="""Which VM to use as `yum` proxy for updating AdminVM and
  611. TemplateVMs""")
  612. clockvm = qubes.VMProperty(
  613. 'clockvm', load_stage=3,
  614. default=None, allow_none=True,
  615. doc='Which VM to use as NTP proxy for updating '
  616. 'AdminVM')
  617. default_kernel = qubes.property(
  618. 'default_kernel', load_stage=3,
  619. doc='Which kernel to use when not overriden in VM')
  620. default_dispvm = qubes.VMProperty(
  621. 'default_dispvm',
  622. load_stage=3,
  623. default=None,
  624. doc='Default DispVM base for service calls',
  625. allow_none=True)
  626. management_dispvm = qubes.VMProperty(
  627. 'management_dispvm',
  628. load_stage=3,
  629. default=None,
  630. doc='Default DispVM base for managing VMs',
  631. allow_none=True)
  632. default_pool = qubes.property(
  633. 'default_pool',
  634. load_stage=3,
  635. default=_default_pool,
  636. setter=_setter_pool,
  637. doc='Default storage pool')
  638. default_pool_private = qubes.property(
  639. 'default_pool_private',
  640. load_stage=3,
  641. default=lambda app: app.default_pool,
  642. setter=_setter_pool,
  643. doc='Default storage pool for private volumes')
  644. default_pool_root = qubes.property(
  645. 'default_pool_root',
  646. load_stage=3,
  647. default=lambda app: app.default_pool,
  648. setter=_setter_pool,
  649. doc='Default storage pool for root volumes')
  650. default_pool_volatile = qubes.property(
  651. 'default_pool_volatile',
  652. load_stage=3,
  653. default=lambda app: app.default_pool,
  654. setter=_setter_pool,
  655. doc='Default storage pool for volatile volumes')
  656. default_pool_kernel = qubes.property(
  657. 'default_pool_kernel',
  658. load_stage=3,
  659. default=lambda app: app.default_pool,
  660. setter=_setter_pool,
  661. doc='Default storage pool for kernel volumes')
  662. default_qrexec_timeout = qubes.property(
  663. 'default_qrexec_timeout',
  664. load_stage=3,
  665. default=60,
  666. type=int,
  667. doc="""Default time in seconds after which qrexec connection attempt
  668. is deemed failed""")
  669. default_shutdown_timeout = qubes.property(
  670. 'default_shutdown_timeout',
  671. load_stage=3,
  672. default=60,
  673. type=int,
  674. doc="""Default time in seconds for VM shutdown to complete""")
  675. stats_interval = qubes.property(
  676. 'stats_interval',
  677. load_stage=3,
  678. default=3,
  679. type=int,
  680. doc='Interval in seconds for VM stats reporting (memory, CPU usage)')
  681. # TODO #1637 #892
  682. check_updates_vm = qubes.property(
  683. 'check_updates_vm',
  684. type=bool,
  685. setter=qubes.property.bool,
  686. load_stage=3,
  687. default=True,
  688. doc='Check for updates inside qubes')
  689. def __init__(self, store=None, load=True, offline_mode=None, lock=False,
  690. **kwargs):
  691. #: logger instance for logging global messages
  692. self.log = logging.getLogger('app')
  693. self.log.debug('init() -> %#x', id(self))
  694. self.log.debug('stack:')
  695. for frame in traceback.extract_stack():
  696. self.log.debug('%s', frame)
  697. self._extensions = qubes.ext.get_extensions()
  698. #: collection of all VMs managed by this Qubes instance
  699. self.domains = VMCollection(self)
  700. #: collection of all available labels for VMs
  701. self.labels = {}
  702. #: collection of all pools
  703. self.pools = {}
  704. #: Connection to VMM
  705. self.vmm = VMMConnection(
  706. offline_mode=offline_mode,
  707. libvirt_reconnect_cb=self.register_event_handlers)
  708. #: Information about host system
  709. self.host = QubesHost(self)
  710. if store is not None:
  711. self._store = store
  712. else:
  713. self._store = os.environ.get('QUBES_XML_PATH',
  714. os.path.join(
  715. qubes.config.qubes_base_dir,
  716. qubes.config.system_path[
  717. 'qubes_store_filename']))
  718. super(Qubes, self).__init__(xml=None, **kwargs)
  719. self.__load_timestamp = None
  720. self.__locked_fh = None
  721. self._domain_event_callback_id = None
  722. #: jinja2 environment for libvirt XML templates
  723. self.env = jinja2.Environment(
  724. loader=jinja2.FileSystemLoader([
  725. '/etc/qubes/templates',
  726. '/usr/share/qubes/templates',
  727. ]),
  728. undefined=jinja2.StrictUndefined)
  729. if load:
  730. self.load(lock=lock)
  731. self.events_enabled = True
  732. @property
  733. def store(self):
  734. return self._store
  735. def _migrate_global_properties(self):
  736. """Migrate renamed/dropped properties"""
  737. if self.xml is None:
  738. return
  739. # drop default_fw_netvm
  740. node_default_fw_netvm = self.xml.find(
  741. './properties/property[@name=\'default_fw_netvm\']')
  742. if node_default_fw_netvm is not None:
  743. node_default_netvm = self.xml.find(
  744. './properties/property[@name=\'default_netvm\']')
  745. try:
  746. default_fw_netvm = self.domains[node_default_fw_netvm.text]
  747. if node_default_netvm is None:
  748. default_netvm = None
  749. else:
  750. default_netvm = self.domains[node_default_netvm.text]
  751. if default_netvm != default_fw_netvm:
  752. for vm in self.domains:
  753. if not hasattr(vm, 'netvm'):
  754. continue
  755. if not getattr(vm, 'provides_network', False):
  756. continue
  757. node_netvm = vm.xml.find(
  758. './properties/property[@name=\'netvm\']')
  759. if node_netvm is not None:
  760. # non-default netvm
  761. continue
  762. # this will unfortunately break "being default"
  763. # property state, but the alternative (changing
  764. # value behind user's back) is worse
  765. properties = vm.xml.find('./properties')
  766. element = lxml.etree.Element('property',
  767. name='netvm')
  768. element.text = default_fw_netvm.name
  769. # manipulate xml directly, before loading netvm
  770. # property, to avoid hitting netvm loop detection
  771. properties.append(element)
  772. except KeyError:
  773. # if default_fw_netvm was set to invalid value, simply
  774. # drop it
  775. pass
  776. node_default_fw_netvm.getparent().remove(node_default_fw_netvm)
  777. def load(self, lock=False):
  778. """Open qubes.xml
  779. :throws EnvironmentError: failure on parsing store
  780. :throws xml.parsers.expat.ExpatError: failure on parsing store
  781. :raises lxml.etree.XMLSyntaxError: on syntax error in qubes.xml
  782. """
  783. fh = self._acquire_lock()
  784. self.xml = lxml.etree.parse(fh)
  785. # stage 1: load labels and pools
  786. for node in self.xml.xpath('./labels/label'):
  787. label = qubes.Label.fromxml(node)
  788. self.labels[label.index] = label
  789. for node in self.xml.xpath('./pools/pool'):
  790. name = node.get('name')
  791. assert name, "Pool name '%s' is invalid " % name
  792. try:
  793. self.pools[name] = self._get_pool(**node.attrib)
  794. except qubes.exc.QubesException as e:
  795. self.log.error(str(e))
  796. # stage 2: load VMs
  797. for node in self.xml.xpath('./domains/domain'):
  798. # pylint: disable=no-member
  799. cls = self.get_vm_class(node.get('class'))
  800. vm = cls(self, node)
  801. vm.load_properties(load_stage=2)
  802. vm.init_log()
  803. self.domains.add(vm, _enable_events=False)
  804. if 0 not in self.domains:
  805. self.domains.add(
  806. qubes.vm.adminvm.AdminVM(self, None),
  807. _enable_events=False)
  808. self._migrate_global_properties()
  809. # stage 3: load global properties
  810. self.load_properties(load_stage=3)
  811. # stage 4: fill all remaining VM properties
  812. for vm in self.domains:
  813. vm.load_properties(load_stage=4)
  814. vm.load_extras()
  815. # stage 5: misc fixups
  816. self.property_require('default_guivm', allow_none=True)
  817. self.property_require('default_netvm', allow_none=True)
  818. self.property_require('default_template', allow_none=True)
  819. self.property_require('clockvm', allow_none=True)
  820. self.property_require('updatevm', allow_none=True)
  821. for vm in self.domains:
  822. vm.events_enabled = True
  823. vm.fire_event('domain-load')
  824. # get a file timestamp (before closing it - still holding the lock!),
  825. # to detect whether anyone else have modified it in the meantime
  826. self.__load_timestamp = os.path.getmtime(self._store)
  827. if not lock:
  828. self._release_lock()
  829. def __xml__(self):
  830. element = lxml.etree.Element('qubes')
  831. element.append(self.xml_labels())
  832. pools_xml = lxml.etree.Element('pools')
  833. for pool in self.pools.values():
  834. xml = pool.__xml__()
  835. if xml is not None:
  836. pools_xml.append(xml)
  837. element.append(pools_xml)
  838. element.append(self.xml_properties())
  839. domains = lxml.etree.Element('domains')
  840. for vm in self.domains:
  841. domains.append(vm.__xml__())
  842. element.append(domains)
  843. return element
  844. def __str__(self):
  845. return type(self).__name__
  846. def save(self, lock=True):
  847. """Save all data to qubes.xml
  848. There are several problems with saving :file:`qubes.xml` which must be
  849. mitigated:
  850. - Running out of disk space. No space left should not result in empty
  851. file. This is done by writing to temporary file and then renaming.
  852. - Attempts to write two or more files concurrently. This is done by
  853. sophisticated locking.
  854. :param bool lock: keep file locked after saving
  855. :throws EnvironmentError: failure on saving
  856. """
  857. if not self.__locked_fh:
  858. self._acquire_lock(for_save=True)
  859. fh_new = tempfile.NamedTemporaryFile(
  860. prefix=self._store, delete=False)
  861. lxml.etree.ElementTree(self.__xml__()).write(
  862. fh_new, encoding='utf-8', pretty_print=True)
  863. fh_new.flush()
  864. try:
  865. os.chown(fh_new.name, -1, grp.getgrnam('qubes').gr_gid)
  866. os.chmod(fh_new.name, 0o660)
  867. except KeyError: # group 'qubes' not found
  868. # don't change mode if no 'qubes' group in the system
  869. pass
  870. os.rename(fh_new.name, self._store)
  871. # update stored mtime, in case of multiple save() calls without
  872. # loading qubes.xml again
  873. self.__load_timestamp = os.path.getmtime(self._store)
  874. # this releases lock for all other processes,
  875. # but they should instantly block on the new descriptor
  876. self.__locked_fh.close()
  877. self.__locked_fh = fh_new
  878. if not lock:
  879. self._release_lock()
  880. def close(self):
  881. """Deconstruct the object and break circular references
  882. After calling this the object is unusable, not even for saving."""
  883. self.log.debug('close() <- %#x', id(self))
  884. for frame in traceback.extract_stack():
  885. self.log.debug('%s', frame)
  886. # let all the extension cleanup things
  887. self.fire_event('qubes-close')
  888. super().close()
  889. if self._domain_event_callback_id is not None:
  890. self.vmm.libvirt_conn.domainEventDeregisterAny(
  891. self._domain_event_callback_id)
  892. self._domain_event_callback_id = None
  893. # Only our Lord, The God Almighty, knows what references
  894. # are kept in extensions.
  895. # NOTE: this doesn't really delete extension objects - Extension class
  896. # saves reference to instance, and also various registered (class level)
  897. # event handlers do that too
  898. del self._extensions
  899. for vm in self.domains:
  900. vm.close()
  901. self.domains.close()
  902. del self.domains
  903. self.vmm.close()
  904. del self.vmm
  905. del self.host
  906. if self.__locked_fh:
  907. self._release_lock()
  908. def _acquire_lock(self, for_save=False):
  909. assert self.__locked_fh is None, 'double lock'
  910. while True:
  911. try:
  912. fd = os.open(self._store,
  913. os.O_RDWR | (os.O_CREAT * int(for_save)))
  914. except FileNotFoundError:
  915. if not for_save:
  916. raise qubes.exc.QubesException(
  917. 'Qubes XML store {!r} is missing; '
  918. 'use qubes-create tool'.format(self._store))
  919. raise
  920. # While we were waiting for lock, someone could have unlink()ed
  921. # (or rename()d) our file out of the filesystem. We have to
  922. # ensure we got lock on something linked to filesystem.
  923. # If not, try again.
  924. if os.fstat(fd) != os.stat(self._store):
  925. os.close(fd)
  926. continue
  927. if self.__load_timestamp and \
  928. os.path.getmtime(self._store) != self.__load_timestamp:
  929. os.close(fd)
  930. raise qubes.exc.QubesException(
  931. 'Someone else modified qubes.xml in the meantime')
  932. break
  933. if os.name == 'posix':
  934. fcntl.lockf(fd, fcntl.LOCK_EX)
  935. elif os.name == 'nt':
  936. # pylint: disable=protected-access
  937. overlapped = pywintypes.OVERLAPPED()
  938. win32file.LockFileEx(
  939. win32file._get_osfhandle(fd),
  940. win32con.LOCKFILE_EXCLUSIVE_LOCK, 0, -0x10000, overlapped)
  941. self.__locked_fh = os.fdopen(fd, 'r+b')
  942. return self.__locked_fh
  943. def _release_lock(self):
  944. assert self.__locked_fh is not None, 'double release'
  945. # intentionally do not call explicit unlock to not unlock the file
  946. # before all buffers are flushed
  947. self.__locked_fh.close()
  948. self.__locked_fh = None
  949. def load_initial_values(self):
  950. self.labels = {
  951. 1: qubes.Label(1, '0xcc0000', 'red'),
  952. 2: qubes.Label(2, '0xf57900', 'orange'),
  953. 3: qubes.Label(3, '0xedd400', 'yellow'),
  954. 4: qubes.Label(4, '0x73d216', 'green'),
  955. 5: qubes.Label(5, '0x555753', 'gray'),
  956. 6: qubes.Label(6, '0x3465a4', 'blue'),
  957. 7: qubes.Label(7, '0x75507b', 'purple'),
  958. 8: qubes.Label(8, '0x000000', 'black'),
  959. }
  960. assert max(self.labels.keys()) == qubes.config.max_default_label
  961. pool_configs = copy.deepcopy(qubes.config.defaults['pool_configs'])
  962. root_volume_group, root_thin_pool = \
  963. qubes.storage.DirectoryThinPool.thin_pool('/')
  964. if root_thin_pool:
  965. lvm_config = {
  966. 'name': 'lvm',
  967. 'driver': 'lvm_thin',
  968. 'volume_group': root_volume_group,
  969. 'thin_pool': root_thin_pool
  970. }
  971. pool_configs[lvm_config['name']] = lvm_config
  972. for name, config in pool_configs.items():
  973. if 'driver' not in config and 'dir_path' in config:
  974. config['driver'] = 'file'
  975. try:
  976. os.makedirs(config['dir_path'], exist_ok=True)
  977. if qubes.storage.reflink.is_supported(config['dir_path']):
  978. config['driver'] = 'file-reflink'
  979. config['setup_check'] = 'no' # don't check twice
  980. except PermissionError: # looks like a testing environment
  981. pass # stay with 'file'
  982. self.pools[name] = self._get_pool(**config)
  983. self.default_pool_kernel = 'linux-kernel'
  984. self.domains.add(
  985. qubes.vm.adminvm.AdminVM(self, None, label='black'))
  986. @classmethod
  987. def create_empty_store(cls, *args, **kwargs):
  988. self = cls(*args, load=False, **kwargs)
  989. if os.path.exists(self.store):
  990. raise qubes.exc.QubesException(
  991. '{} already exists, aborting'.format(self.store))
  992. self.load_initial_values()
  993. # TODO py3 get lock= as keyword-only arg
  994. self.save(kwargs.get('lock'))
  995. return self
  996. def xml_labels(self):
  997. """Serialise labels
  998. :rtype: lxml.etree._Element
  999. """
  1000. labels = lxml.etree.Element('labels')
  1001. for label in sorted(self.labels.values(), key=lambda labl: labl.index):
  1002. labels.append(label.__xml__())
  1003. return labels
  1004. @staticmethod
  1005. def get_vm_class(clsname):
  1006. """Find the class for a domain.
  1007. Classes are registered as setuptools' entry points in ``qubes.vm``
  1008. group. Any package may supply their own classes.
  1009. :param str clsname: name of the class
  1010. :return type: class
  1011. """
  1012. try:
  1013. return qubes.utils.get_entry_point_one(
  1014. qubes.vm.VM_ENTRY_POINT, clsname)
  1015. except KeyError:
  1016. raise qubes.exc.QubesException(
  1017. 'no such VM class: {!r}'.format(clsname))
  1018. # don't catch TypeError
  1019. def add_new_vm(self, cls, qid=None, **kwargs):
  1020. """Add new Virtual Machine to collection
  1021. """
  1022. if qid is None:
  1023. qid = self.domains.get_new_unused_qid()
  1024. if isinstance(cls, str):
  1025. cls = self.get_vm_class(cls)
  1026. # handle default template; specifically allow template=None (do not
  1027. # override it with default template)
  1028. if 'template' not in kwargs and hasattr(cls, 'template'):
  1029. if cls == self.get_vm_class('DispVM'):
  1030. kwargs['template'] = self.default_dispvm
  1031. else:
  1032. kwargs['template'] = self.default_template
  1033. if kwargs['template'] is None:
  1034. raise qubes.exc.QubesValueError(
  1035. 'Template for the qube not specified, nor default '
  1036. 'template set.')
  1037. elif 'template' in kwargs and isinstance(kwargs['template'], str):
  1038. kwargs['template'] = self.domains[kwargs['template']]
  1039. return self.domains.add(cls(self, None, qid=qid, **kwargs))
  1040. def get_label(self, label):
  1041. """Get label as identified by index or name
  1042. :throws KeyError: when label is not found
  1043. """
  1044. # first search for index, verbatim
  1045. try:
  1046. return self.labels[label]
  1047. except KeyError:
  1048. pass
  1049. # then search for name
  1050. for i in self.labels.values():
  1051. if i.name == label:
  1052. return i
  1053. # last call, if label is a number represented as str, search in indices
  1054. try:
  1055. return self.labels[int(label)]
  1056. except (KeyError, ValueError):
  1057. pass
  1058. raise KeyError(label)
  1059. @asyncio.coroutine
  1060. def setup_pools(self):
  1061. """ Run implementation specific setup for each storage pool. """
  1062. yield from qubes.utils.void_coros_maybe(
  1063. pool.setup() for pool in self.pools.values())
  1064. @asyncio.coroutine
  1065. def add_pool(self, name, **kwargs):
  1066. """ Add a storage pool to config."""
  1067. if name in self.pools.keys():
  1068. raise qubes.exc.QubesException('pool named %s already exists \n' %
  1069. name)
  1070. kwargs['name'] = name
  1071. pool = self._get_pool(**kwargs)
  1072. yield from qubes.utils.coro_maybe(pool.setup())
  1073. self.pools[name] = pool
  1074. yield from self.fire_event_async('pool-add', pool=pool)
  1075. return pool
  1076. @asyncio.coroutine
  1077. def remove_pool(self, name):
  1078. """ Remove a storage pool from config file. """
  1079. try:
  1080. pool = self.pools[name]
  1081. volumes = [(vm, volume) for vm in self.domains
  1082. for volume in vm.volumes.values()
  1083. if volume.pool is pool]
  1084. if volumes:
  1085. raise qubes.exc.QubesPoolInUseError(pool)
  1086. prop_suffixes = ['', '_kernel', '_private', '_root', '_volatile']
  1087. for suffix in prop_suffixes:
  1088. if getattr(self, 'default_pool' + suffix, None) is pool:
  1089. raise qubes.exc.QubesPoolInUseError(
  1090. pool,
  1091. 'Storage pool is in use: '
  1092. 'set as {}'.format('default_pool' + suffix))
  1093. yield from self.fire_event_async('pool-pre-delete',
  1094. pre_event=True, pool=pool)
  1095. del self.pools[name]
  1096. yield from qubes.utils.coro_maybe(pool.destroy())
  1097. yield from self.fire_event_async('pool-delete', pool=pool)
  1098. except KeyError:
  1099. return
  1100. def get_pool(self, pool):
  1101. """ Returns a :py:class:`qubes.storage.Pool` instance """
  1102. if isinstance(pool, qubes.storage.Pool):
  1103. return pool
  1104. try:
  1105. return self.pools[pool]
  1106. except KeyError:
  1107. raise qubes.exc.QubesException('Unknown storage pool ' + pool)
  1108. @staticmethod
  1109. def _get_pool(**kwargs):
  1110. try:
  1111. name = kwargs['name']
  1112. assert name, 'Name needs to be an non empty string'
  1113. except KeyError:
  1114. raise qubes.exc.QubesException('No pool name for pool')
  1115. try:
  1116. driver = kwargs['driver']
  1117. except KeyError:
  1118. raise qubes.exc.QubesException('No driver specified for pool ' +
  1119. name)
  1120. try:
  1121. klass = qubes.utils.get_entry_point_one(
  1122. qubes.storage.STORAGE_ENTRY_POINT, driver)
  1123. del kwargs['driver']
  1124. return klass(**kwargs)
  1125. except KeyError:
  1126. raise qubes.exc.QubesException('No driver %s for pool %s' %
  1127. (driver, name))
  1128. def register_event_handlers(self, old_connection=None):
  1129. """Register libvirt event handlers, which will translate libvirt
  1130. events into qubes.events. This function should be called only in
  1131. 'qubesd' process and only when mainloop has been already set.
  1132. """
  1133. if old_connection:
  1134. try:
  1135. old_connection.domainEventDeregisterAny(
  1136. self._domain_event_callback_id)
  1137. except libvirt.libvirtError:
  1138. # the connection is probably in a bad state; but call the above
  1139. # anyway to cleanup the client structures
  1140. pass
  1141. self._domain_event_callback_id = (
  1142. self.vmm.libvirt_conn.domainEventRegisterAny(
  1143. None, # any domain
  1144. libvirt.VIR_DOMAIN_EVENT_ID_LIFECYCLE,
  1145. self._domain_event_callback,
  1146. None))
  1147. def _domain_event_callback(self, _conn, domain, event, _detail, _opaque):
  1148. """Generic libvirt event handler (virConnectDomainEventCallback),
  1149. translate libvirt event into qubes.events.
  1150. """
  1151. if not self.events_enabled:
  1152. return
  1153. try:
  1154. vm = self.domains[domain.name()]
  1155. except KeyError:
  1156. # ignore events for unknown domains
  1157. return
  1158. if event == libvirt.VIR_DOMAIN_EVENT_STOPPED:
  1159. vm.on_libvirt_domain_stopped()
  1160. elif event == libvirt.VIR_DOMAIN_EVENT_SUSPENDED:
  1161. try:
  1162. vm.fire_event('domain-paused')
  1163. except Exception: # pylint: disable=broad-except
  1164. self.log.exception(
  1165. 'Uncaught exception from domain-paused handler '
  1166. 'for domain %s', vm.name)
  1167. elif event == libvirt.VIR_DOMAIN_EVENT_RESUMED:
  1168. try:
  1169. vm.fire_event('domain-unpaused')
  1170. except Exception: # pylint: disable=broad-except
  1171. self.log.exception(
  1172. 'Uncaught exception from domain-unpaused handler '
  1173. 'for domain %s', vm.name)
  1174. @qubes.events.handler('domain-pre-delete')
  1175. def on_domain_pre_deleted(self, event, vm):
  1176. # pylint: disable=unused-argument
  1177. for obj in itertools.chain(self.domains, (self,)):
  1178. if obj is vm:
  1179. # allow removed VM to reference itself
  1180. continue
  1181. for prop in obj.property_list():
  1182. try:
  1183. if isinstance(prop, qubes.vm.VMProperty) and \
  1184. getattr(obj, prop.__name__) == vm:
  1185. self.log.error(
  1186. 'Cannot remove %s, used by %s.%s',
  1187. vm, obj, prop.__name__)
  1188. raise qubes.exc.QubesVMInUseError(
  1189. vm,
  1190. 'Domain is in use: {!r};'
  1191. 'see /var/log/qubes/qubes.log in dom0 for '
  1192. 'details'.format(
  1193. vm.name))
  1194. except AttributeError:
  1195. pass
  1196. assignments = vm.get_provided_assignments()
  1197. if assignments:
  1198. desc = ', '.join(
  1199. assignment.ident for assignment in assignments)
  1200. raise qubes.exc.QubesVMInUseError(
  1201. vm,
  1202. 'VM has devices attached persistently to other VMs: ' +
  1203. desc)
  1204. @qubes.events.handler('domain-delete')
  1205. def on_domain_deleted(self, event, vm):
  1206. # pylint: disable=unused-argument
  1207. for propname in (
  1208. 'default_guivm'
  1209. 'default_netvm',
  1210. 'default_fw_netvm',
  1211. 'clockvm',
  1212. 'updatevm',
  1213. 'default_template',
  1214. ):
  1215. try:
  1216. if getattr(self, propname) == vm:
  1217. delattr(self, propname)
  1218. except AttributeError:
  1219. pass
  1220. @qubes.events.handler('property-pre-set:clockvm')
  1221. def on_property_pre_set_clockvm(self, event, name, newvalue, oldvalue=None):
  1222. # pylint: disable=unused-argument,no-self-use
  1223. if newvalue is None:
  1224. return
  1225. if 'service.clocksync' not in newvalue.features:
  1226. newvalue.features['service.clocksync'] = True
  1227. @qubes.events.handler('property-set:clockvm')
  1228. def on_property_set_clockvm(self, event, name, newvalue, oldvalue=None):
  1229. # pylint: disable=unused-argument,no-self-use
  1230. if oldvalue == newvalue:
  1231. return
  1232. if oldvalue and oldvalue.features.get('service.clocksync', False):
  1233. del oldvalue.features['service.clocksync']
  1234. @qubes.events.handler('property-pre-set:default_netvm')
  1235. def on_property_pre_set_default_netvm(self, event, name, newvalue,
  1236. oldvalue=None):
  1237. # pylint: disable=unused-argument,invalid-name
  1238. if newvalue is not None and oldvalue is not None \
  1239. and oldvalue.is_running() and not newvalue.is_running() \
  1240. and self.domains.get_vms_connected_to(oldvalue):
  1241. raise qubes.exc.QubesVMNotRunningError(
  1242. newvalue,
  1243. 'Cannot change {!r} to domain that '
  1244. 'is not running ({!r}).'.format(
  1245. name, newvalue.name))
  1246. @qubes.events.handler('property-set:default_fw_netvm')
  1247. def on_property_set_default_fw_netvm(self, event, name, newvalue,
  1248. oldvalue=None):
  1249. # pylint: disable=unused-argument,invalid-name
  1250. for vm in self.domains:
  1251. if hasattr(vm, 'provides_network') and vm.provides_network and \
  1252. hasattr(vm, 'netvm') and vm.property_is_default('netvm'):
  1253. # fire property-del:netvm as it is responsible for resetting
  1254. # netvm to it's default value
  1255. vm.fire_event('property-pre-del:netvm', pre_event=True,
  1256. name='netvm', oldvalue=oldvalue)
  1257. vm.fire_event('property-del:netvm',
  1258. name='netvm', oldvalue=oldvalue)
  1259. @qubes.events.handler('property-set:default_netvm')
  1260. def on_property_set_default_netvm(self, event, name, newvalue,
  1261. oldvalue=None):
  1262. # pylint: disable=unused-argument
  1263. for vm in self.domains:
  1264. if hasattr(vm, 'provides_network') and not vm.provides_network and \
  1265. hasattr(vm, 'netvm') and vm.property_is_default('netvm'):
  1266. # fire property-del:netvm as it is responsible for resetting
  1267. # netvm to it's default value
  1268. vm.fire_event('property-pre-del:netvm', pre_event=True,
  1269. name='netvm', oldvalue=oldvalue)
  1270. vm.fire_event('property-del:netvm',
  1271. name='netvm', oldvalue=oldvalue)