app.py 51 KB

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