app.py 53 KB

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