app.py 51 KB

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