app.py 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548
  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(Qubes, self).__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 load(self, lock=False):
  800. """Open qubes.xml
  801. :throws EnvironmentError: failure on parsing store
  802. :throws xml.parsers.expat.ExpatError: failure on parsing store
  803. :raises lxml.etree.XMLSyntaxError: on syntax error in qubes.xml
  804. """
  805. fh = self._acquire_lock()
  806. self.xml = lxml.etree.parse(fh)
  807. # stage 1: load labels and pools
  808. for node in self.xml.xpath('./labels/label'):
  809. label = qubes.Label.fromxml(node)
  810. self.labels[label.index] = label
  811. for node in self.xml.xpath('./pools/pool'):
  812. name = node.get('name')
  813. assert name, "Pool name '%s' is invalid " % name
  814. try:
  815. self.pools[name] = self._get_pool(**node.attrib)
  816. except qubes.exc.QubesException as e:
  817. self.log.error(str(e))
  818. # stage 2: load VMs
  819. for node in self.xml.xpath('./domains/domain'):
  820. # pylint: disable=no-member
  821. cls = self.get_vm_class(node.get('class'))
  822. vm = cls(self, node)
  823. vm.load_properties(load_stage=2)
  824. vm.init_log()
  825. self.domains.add(vm, _enable_events=False)
  826. if 0 not in self.domains:
  827. self.domains.add(
  828. qubes.vm.adminvm.AdminVM(self, None),
  829. _enable_events=False)
  830. self._migrate_global_properties()
  831. # stage 3: load global properties
  832. self.load_properties(load_stage=3)
  833. # stage 4: fill all remaining VM properties
  834. for vm in self.domains:
  835. vm.load_properties(load_stage=4)
  836. vm.load_extras()
  837. # stage 5: misc fixups
  838. self.property_require('default_guivm', allow_none=True)
  839. self.property_require('default_netvm', allow_none=True)
  840. self.property_require('default_template', allow_none=True)
  841. self.property_require('clockvm', allow_none=True)
  842. self.property_require('updatevm', allow_none=True)
  843. for vm in self.domains:
  844. vm.events_enabled = True
  845. vm.fire_event('domain-load')
  846. # get a file timestamp (before closing it - still holding the lock!),
  847. # to detect whether anyone else have modified it in the meantime
  848. self.__load_timestamp = os.path.getmtime(self._store)
  849. if not lock:
  850. self._release_lock()
  851. def __xml__(self):
  852. element = lxml.etree.Element('qubes')
  853. element.append(self.xml_labels())
  854. pools_xml = lxml.etree.Element('pools')
  855. for pool in self.pools.values():
  856. xml = pool.__xml__()
  857. if xml is not None:
  858. pools_xml.append(xml)
  859. element.append(pools_xml)
  860. element.append(self.xml_properties())
  861. domains = lxml.etree.Element('domains')
  862. for vm in self.domains:
  863. domains.append(vm.__xml__())
  864. element.append(domains)
  865. return element
  866. def __str__(self):
  867. return type(self).__name__
  868. def save(self, lock=True):
  869. """Save all data to qubes.xml
  870. There are several problems with saving :file:`qubes.xml` which must be
  871. mitigated:
  872. - Running out of disk space. No space left should not result in empty
  873. file. This is done by writing to temporary file and then renaming.
  874. - Attempts to write two or more files concurrently. This is done by
  875. sophisticated locking.
  876. :param bool lock: keep file locked after saving
  877. :throws EnvironmentError: failure on saving
  878. """
  879. if not self.__locked_fh:
  880. self._acquire_lock(for_save=True)
  881. fh_new = tempfile.NamedTemporaryFile(
  882. prefix=self._store, delete=False)
  883. lxml.etree.ElementTree(self.__xml__()).write(
  884. fh_new, encoding='utf-8', pretty_print=True)
  885. fh_new.flush()
  886. try:
  887. os.chown(fh_new.name, -1, grp.getgrnam('qubes').gr_gid)
  888. os.chmod(fh_new.name, 0o660)
  889. except KeyError: # group 'qubes' not found
  890. # don't change mode if no 'qubes' group in the system
  891. pass
  892. os.rename(fh_new.name, self._store)
  893. # update stored mtime, in case of multiple save() calls without
  894. # loading qubes.xml again
  895. self.__load_timestamp = os.path.getmtime(self._store)
  896. # this releases lock for all other processes,
  897. # but they should instantly block on the new descriptor
  898. self.__locked_fh.close()
  899. self.__locked_fh = fh_new
  900. if not lock:
  901. self._release_lock()
  902. def close(self):
  903. """Deconstruct the object and break circular references
  904. After calling this the object is unusable, not even for saving."""
  905. self.log.debug('close() <- %#x', id(self))
  906. for frame in traceback.extract_stack():
  907. self.log.debug('%s', frame)
  908. # let all the extension cleanup things
  909. self.fire_event('qubes-close')
  910. super().close()
  911. if self._domain_event_callback_id is not None:
  912. self.vmm.libvirt_conn.domainEventDeregisterAny(
  913. self._domain_event_callback_id)
  914. self._domain_event_callback_id = None
  915. # Only our Lord, The God Almighty, knows what references
  916. # are kept in extensions.
  917. # NOTE: this doesn't really delete extension objects - Extension class
  918. # saves reference to instance, and also various registered (class level)
  919. # event handlers do that too
  920. del self._extensions
  921. for vm in self.domains:
  922. vm.close()
  923. self.domains.close()
  924. del self.domains
  925. self.vmm.close()
  926. del self.vmm
  927. del self.host
  928. if self.__locked_fh:
  929. self._release_lock()
  930. def _acquire_lock(self, for_save=False):
  931. assert self.__locked_fh is None, 'double lock'
  932. while True:
  933. try:
  934. fd = os.open(self._store,
  935. os.O_RDWR | (os.O_CREAT * int(for_save)))
  936. except FileNotFoundError:
  937. if not for_save:
  938. raise qubes.exc.QubesException(
  939. 'Qubes XML store {!r} is missing; '
  940. 'use qubes-create tool'.format(self._store))
  941. raise
  942. # While we were waiting for lock, someone could have unlink()ed
  943. # (or rename()d) our file out of the filesystem. We have to
  944. # ensure we got lock on something linked to filesystem.
  945. # If not, try again.
  946. if os.fstat(fd) != os.stat(self._store):
  947. os.close(fd)
  948. continue
  949. if self.__load_timestamp and \
  950. os.path.getmtime(self._store) != self.__load_timestamp:
  951. os.close(fd)
  952. raise qubes.exc.QubesException(
  953. 'Someone else modified qubes.xml in the meantime')
  954. break
  955. if os.name == 'posix':
  956. fcntl.lockf(fd, fcntl.LOCK_EX)
  957. elif os.name == 'nt':
  958. # pylint: disable=protected-access
  959. overlapped = pywintypes.OVERLAPPED()
  960. win32file.LockFileEx(
  961. win32file._get_osfhandle(fd),
  962. win32con.LOCKFILE_EXCLUSIVE_LOCK, 0, -0x10000, overlapped)
  963. self.__locked_fh = os.fdopen(fd, 'r+b')
  964. return self.__locked_fh
  965. def _release_lock(self):
  966. assert self.__locked_fh is not None, 'double release'
  967. # intentionally do not call explicit unlock to not unlock the file
  968. # before all buffers are flushed
  969. self.__locked_fh.close()
  970. self.__locked_fh = None
  971. def load_initial_values(self):
  972. self.labels = {
  973. 1: qubes.Label(1, '0xcc0000', 'red'),
  974. 2: qubes.Label(2, '0xf57900', 'orange'),
  975. 3: qubes.Label(3, '0xedd400', 'yellow'),
  976. 4: qubes.Label(4, '0x73d216', 'green'),
  977. 5: qubes.Label(5, '0x555753', 'gray'),
  978. 6: qubes.Label(6, '0x3465a4', 'blue'),
  979. 7: qubes.Label(7, '0x75507b', 'purple'),
  980. 8: qubes.Label(8, '0x000000', 'black'),
  981. }
  982. assert max(self.labels.keys()) == qubes.config.max_default_label
  983. pool_configs = copy.deepcopy(qubes.config.defaults['pool_configs'])
  984. for name, config in pool_configs.items():
  985. if 'driver' not in config and 'dir_path' in config:
  986. config['driver'] = 'file'
  987. try:
  988. os.makedirs(config['dir_path'], exist_ok=True)
  989. if qubes.storage.reflink.is_supported(config['dir_path']):
  990. config['driver'] = 'file-reflink'
  991. config['setup_check'] = False # don't check twice
  992. except PermissionError: # looks like a testing environment
  993. pass # stay with 'file'
  994. self.pools[name] = self._get_pool(**config)
  995. self.default_pool_kernel = 'linux-kernel'
  996. self.domains.add(
  997. qubes.vm.adminvm.AdminVM(self, None, label='black'))
  998. @classmethod
  999. def create_empty_store(cls, *args, **kwargs):
  1000. self = cls(*args, load=False, **kwargs)
  1001. if os.path.exists(self.store):
  1002. raise qubes.exc.QubesException(
  1003. '{} already exists, aborting'.format(self.store))
  1004. self.load_initial_values()
  1005. # TODO py3 get lock= as keyword-only arg
  1006. self.save(kwargs.get('lock'))
  1007. return self
  1008. def xml_labels(self):
  1009. """Serialise labels
  1010. :rtype: lxml.etree._Element
  1011. """
  1012. labels = lxml.etree.Element('labels')
  1013. for label in sorted(self.labels.values(), key=lambda labl: labl.index):
  1014. labels.append(label.__xml__())
  1015. return labels
  1016. @staticmethod
  1017. def get_vm_class(clsname):
  1018. """Find the class for a domain.
  1019. Classes are registered as setuptools' entry points in ``qubes.vm``
  1020. group. Any package may supply their own classes.
  1021. :param str clsname: name of the class
  1022. :return type: class
  1023. """
  1024. try:
  1025. return qubes.utils.get_entry_point_one(
  1026. qubes.vm.VM_ENTRY_POINT, clsname)
  1027. except KeyError:
  1028. raise qubes.exc.QubesException(
  1029. 'no such VM class: {!r}'.format(clsname))
  1030. # don't catch TypeError
  1031. def add_new_vm(self, cls, qid=None, **kwargs):
  1032. """Add new Virtual Machine to collection
  1033. """
  1034. if qid is None:
  1035. qid = self.domains.get_new_unused_qid()
  1036. if isinstance(cls, str):
  1037. cls = self.get_vm_class(cls)
  1038. # handle default template; specifically allow template=None (do not
  1039. # override it with default template)
  1040. if 'template' not in kwargs and hasattr(cls, 'template'):
  1041. if cls == self.get_vm_class('DispVM'):
  1042. kwargs['template'] = self.default_dispvm
  1043. else:
  1044. kwargs['template'] = self.default_template
  1045. if kwargs['template'] is None:
  1046. raise qubes.exc.QubesValueError(
  1047. 'Template for the qube not specified, nor default '
  1048. 'template set.')
  1049. elif 'template' in kwargs and isinstance(kwargs['template'], str):
  1050. kwargs['template'] = self.domains[kwargs['template']]
  1051. return self.domains.add(cls(self, None, qid=qid, **kwargs))
  1052. def get_label(self, label):
  1053. """Get label as identified by index or name
  1054. :throws KeyError: when label is not found
  1055. """
  1056. # first search for index, verbatim
  1057. try:
  1058. return self.labels[label]
  1059. except KeyError:
  1060. pass
  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. try:
  1067. return self.labels[int(label)]
  1068. except (KeyError, ValueError):
  1069. pass
  1070. raise KeyError(label)
  1071. @asyncio.coroutine
  1072. def setup_pools(self):
  1073. """ Run implementation specific setup for each storage pool. """
  1074. yield from qubes.utils.void_coros_maybe(
  1075. pool.setup() for pool in self.pools.values())
  1076. @asyncio.coroutine
  1077. def add_pool(self, name, **kwargs):
  1078. """ Add a storage pool to config."""
  1079. if name in self.pools.keys():
  1080. raise qubes.exc.QubesException('pool named %s already exists \n' %
  1081. name)
  1082. kwargs['name'] = name
  1083. pool = self._get_pool(**kwargs)
  1084. yield from qubes.utils.coro_maybe(pool.setup())
  1085. self.pools[name] = pool
  1086. yield from self.fire_event_async('pool-add', pool=pool)
  1087. return pool
  1088. @asyncio.coroutine
  1089. def remove_pool(self, name):
  1090. """ Remove a storage pool from config file. """
  1091. try:
  1092. pool = self.pools[name]
  1093. volumes = [(vm, volume) for vm in self.domains
  1094. for volume in vm.volumes.values()
  1095. if volume.pool is pool]
  1096. if volumes:
  1097. raise qubes.exc.QubesPoolInUseError(pool)
  1098. prop_suffixes = ['', '_kernel', '_private', '_root', '_volatile']
  1099. for suffix in prop_suffixes:
  1100. if getattr(self, 'default_pool' + suffix, None) is pool:
  1101. raise qubes.exc.QubesPoolInUseError(
  1102. pool,
  1103. 'Storage pool is in use: '
  1104. 'set as {}'.format('default_pool' + suffix))
  1105. yield from self.fire_event_async('pool-pre-delete',
  1106. pre_event=True, pool=pool)
  1107. del self.pools[name]
  1108. yield from qubes.utils.coro_maybe(pool.destroy())
  1109. yield from self.fire_event_async('pool-delete', pool=pool)
  1110. except KeyError:
  1111. return
  1112. def get_pool(self, pool):
  1113. """ Returns a :py:class:`qubes.storage.Pool` instance """
  1114. if isinstance(pool, qubes.storage.Pool):
  1115. return pool
  1116. try:
  1117. return self.pools[pool]
  1118. except KeyError:
  1119. raise qubes.exc.QubesException('Unknown storage pool ' + pool)
  1120. @staticmethod
  1121. def _get_pool(**kwargs):
  1122. try:
  1123. name = kwargs['name']
  1124. assert name, 'Name needs to be an non empty string'
  1125. except KeyError:
  1126. raise qubes.exc.QubesException('No pool name for pool')
  1127. try:
  1128. driver = kwargs['driver']
  1129. except KeyError:
  1130. raise qubes.exc.QubesException('No driver specified for pool ' +
  1131. name)
  1132. try:
  1133. klass = qubes.utils.get_entry_point_one(
  1134. qubes.storage.STORAGE_ENTRY_POINT, driver)
  1135. del kwargs['driver']
  1136. return klass(**kwargs)
  1137. except KeyError:
  1138. raise qubes.exc.QubesException('No driver %s for pool %s' %
  1139. (driver, name))
  1140. def register_event_handlers(self, old_connection=None):
  1141. """Register libvirt event handlers, which will translate libvirt
  1142. events into qubes.events. This function should be called only in
  1143. 'qubesd' process and only when mainloop has been already set.
  1144. """
  1145. if old_connection:
  1146. try:
  1147. old_connection.domainEventDeregisterAny(
  1148. self._domain_event_callback_id)
  1149. except libvirt.libvirtError:
  1150. # the connection is probably in a bad state; but call the above
  1151. # anyway to cleanup the client structures
  1152. pass
  1153. self._domain_event_callback_id = (
  1154. self.vmm.libvirt_conn.domainEventRegisterAny(
  1155. None, # any domain
  1156. libvirt.VIR_DOMAIN_EVENT_ID_LIFECYCLE,
  1157. self._domain_event_callback,
  1158. None))
  1159. def _domain_event_callback(self, _conn, domain, event, _detail, _opaque):
  1160. """Generic libvirt event handler (virConnectDomainEventCallback),
  1161. translate libvirt event into qubes.events.
  1162. """
  1163. if not self.events_enabled:
  1164. return
  1165. try:
  1166. vm = self.domains[domain.name()]
  1167. except KeyError:
  1168. # ignore events for unknown domains
  1169. return
  1170. if event == libvirt.VIR_DOMAIN_EVENT_STOPPED:
  1171. vm.on_libvirt_domain_stopped()
  1172. elif event == libvirt.VIR_DOMAIN_EVENT_SUSPENDED:
  1173. try:
  1174. vm.fire_event('domain-paused')
  1175. except Exception: # pylint: disable=broad-except
  1176. self.log.exception(
  1177. 'Uncaught exception from domain-paused handler '
  1178. 'for domain %s', vm.name)
  1179. elif event == libvirt.VIR_DOMAIN_EVENT_RESUMED:
  1180. try:
  1181. vm.fire_event('domain-unpaused')
  1182. except Exception: # pylint: disable=broad-except
  1183. self.log.exception(
  1184. 'Uncaught exception from domain-unpaused handler '
  1185. 'for domain %s', vm.name)
  1186. @qubes.events.handler('domain-pre-delete')
  1187. def on_domain_pre_deleted(self, event, vm):
  1188. # pylint: disable=unused-argument
  1189. for obj in itertools.chain(self.domains, (self,)):
  1190. if obj is vm:
  1191. # allow removed VM to reference itself
  1192. continue
  1193. for prop in obj.property_list():
  1194. try:
  1195. if isinstance(prop, qubes.vm.VMProperty) and \
  1196. getattr(obj, prop.__name__) == vm:
  1197. self.log.error(
  1198. 'Cannot remove %s, used by %s.%s',
  1199. vm, obj, prop.__name__)
  1200. raise qubes.exc.QubesVMInUseError(
  1201. vm,
  1202. 'Domain is in use: {!r};'
  1203. 'see /var/log/qubes/qubes.log in dom0 for '
  1204. 'details'.format(
  1205. vm.name))
  1206. except AttributeError:
  1207. pass
  1208. assignments = vm.get_provided_assignments()
  1209. if assignments:
  1210. desc = ', '.join(
  1211. assignment.ident for assignment in assignments)
  1212. raise qubes.exc.QubesVMInUseError(
  1213. vm,
  1214. 'VM has devices attached persistently to other VMs: ' +
  1215. desc)
  1216. @qubes.events.handler('domain-delete')
  1217. def on_domain_deleted(self, event, vm):
  1218. # pylint: disable=unused-argument
  1219. for propname in (
  1220. 'default_guivm'
  1221. 'default_netvm',
  1222. 'default_fw_netvm',
  1223. 'clockvm',
  1224. 'updatevm',
  1225. 'default_template',
  1226. ):
  1227. try:
  1228. if getattr(self, propname) == vm:
  1229. delattr(self, propname)
  1230. except AttributeError:
  1231. pass
  1232. @qubes.events.handler('property-pre-set:clockvm')
  1233. def on_property_pre_set_clockvm(self, event, name, newvalue, oldvalue=None):
  1234. # pylint: disable=unused-argument,no-self-use
  1235. if newvalue is None:
  1236. return
  1237. if 'service.clocksync' not in newvalue.features:
  1238. newvalue.features['service.clocksync'] = True
  1239. @qubes.events.handler('property-set:clockvm')
  1240. def on_property_set_clockvm(self, event, name, newvalue, oldvalue=None):
  1241. # pylint: disable=unused-argument,no-self-use
  1242. if oldvalue == newvalue:
  1243. return
  1244. if oldvalue and oldvalue.features.get('service.clocksync', False):
  1245. del oldvalue.features['service.clocksync']
  1246. @qubes.events.handler('property-pre-set:default_netvm')
  1247. def on_property_pre_set_default_netvm(self, event, name, newvalue,
  1248. oldvalue=None):
  1249. # pylint: disable=unused-argument,invalid-name
  1250. if newvalue is not None and oldvalue is not None \
  1251. and oldvalue.is_running() and not newvalue.is_running() \
  1252. and self.domains.get_vms_connected_to(oldvalue):
  1253. raise qubes.exc.QubesVMNotRunningError(
  1254. newvalue,
  1255. 'Cannot change {!r} to domain that '
  1256. 'is not running ({!r}).'.format(
  1257. name, newvalue.name))
  1258. @qubes.events.handler('property-set:default_netvm')
  1259. def on_property_set_default_netvm(self, event, name, newvalue,
  1260. oldvalue=None):
  1261. # pylint: disable=unused-argument
  1262. for vm in self.domains:
  1263. if hasattr(vm, 'provides_network') and not vm.provides_network and \
  1264. hasattr(vm, 'netvm') and vm.property_is_default('netvm'):
  1265. # fire property-reset:netvm as it is responsible for resetting
  1266. # netvm to it's default value
  1267. vm.fire_event('property-reset:netvm',
  1268. name='netvm', oldvalue=oldvalue)