app.py 53 KB

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