app.py 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493
  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('default_guivm', load_stage=3,
  570. default=None, allow_none=True,
  571. doc='Default GuiVM for VMs.')
  572. default_netvm = qubes.VMProperty('default_netvm', load_stage=3,
  573. default=None, allow_none=True,
  574. setter=_setter_default_netvm,
  575. doc="""Default NetVM for AppVMs. Initial
  576. state is `None`, which means that AppVMs
  577. are not connected to the Internet.""")
  578. default_template = qubes.VMProperty('default_template', load_stage=3,
  579. vmclass=qubes.vm.templatevm.TemplateVM,
  580. doc='Default template for new AppVMs',
  581. allow_none=True)
  582. updatevm = qubes.VMProperty('updatevm', load_stage=3,
  583. default=None, allow_none=True,
  584. doc="""Which VM to use as `yum` proxy for
  585. updating AdminVM and TemplateVMs""")
  586. clockvm = qubes.VMProperty('clockvm', load_stage=3,
  587. default=None, allow_none=True,
  588. doc='Which VM to use as NTP proxy for updating '
  589. 'AdminVM')
  590. default_kernel = qubes.property('default_kernel', load_stage=3,
  591. doc='Which kernel to use when not '
  592. 'overriden in VM')
  593. default_dispvm = qubes.VMProperty('default_dispvm', load_stage=3,
  594. default=None,
  595. doc='Default DispVM base for service '
  596. 'calls',
  597. allow_none=True)
  598. management_dispvm = qubes.VMProperty('management_dispvm', load_stage=3,
  599. default=None,
  600. doc='Default DispVM base for '
  601. 'managing VMs',
  602. allow_none=True)
  603. default_pool = qubes.property('default_pool', load_stage=3,
  604. default=_default_pool,
  605. setter=_setter_pool,
  606. doc='Default storage pool')
  607. default_pool_private = qubes.property('default_pool_private', load_stage=3,
  608. default=lambda app: app.default_pool,
  609. setter=_setter_pool,
  610. doc='Default storage pool for '
  611. 'private volumes')
  612. default_pool_root = qubes.property('default_pool_root', load_stage=3,
  613. default=lambda app: app.default_pool,
  614. setter=_setter_pool,
  615. doc='Default storage pool for root '
  616. 'volumes')
  617. default_pool_volatile = qubes.property('default_pool_volatile',
  618. load_stage=3,
  619. default=lambda app: app.default_pool,
  620. setter=_setter_pool,
  621. doc='Default storage pool for '
  622. 'volatile volumes')
  623. default_pool_kernel = qubes.property('default_pool_kernel', load_stage=3,
  624. default=lambda app: app.default_pool,
  625. setter=_setter_pool,
  626. doc='Default storage pool for kernel '
  627. 'volumes')
  628. default_qrexec_timeout = qubes.property('default_qrexec_timeout',
  629. load_stage=3,
  630. default=60,
  631. type=int,
  632. doc="""Default time in seconds
  633. after which qrexec connection
  634. attempt is deemed failed""")
  635. default_shutdown_timeout = qubes.property('default_shutdown_timeout',
  636. load_stage=3,
  637. default=60,
  638. type=int,
  639. doc="""Default time in seconds
  640. for VM shutdown to complete""")
  641. stats_interval = qubes.property('stats_interval',
  642. load_stage=3,
  643. default=3,
  644. type=int,
  645. doc='Interval in seconds for VM stats '
  646. 'reporting (memory, CPU usage)')
  647. # TODO #1637 #892
  648. check_updates_vm = qubes.property('check_updates_vm',
  649. type=bool, setter=qubes.property.bool,
  650. load_stage=3,
  651. default=True,
  652. doc='check for updates inside qubes')
  653. def __init__(self, store=None, load=True, offline_mode=None, lock=False,
  654. **kwargs):
  655. #: logger instance for logging global messages
  656. self.log = logging.getLogger('app')
  657. self.log.debug('init() -> %#x', id(self))
  658. self.log.debug('stack:')
  659. for frame in traceback.extract_stack():
  660. self.log.debug('%s', frame)
  661. self._extensions = qubes.ext.get_extensions()
  662. #: collection of all VMs managed by this Qubes instance
  663. self.domains = VMCollection(self)
  664. #: collection of all available labels for VMs
  665. self.labels = {}
  666. #: collection of all pools
  667. self.pools = {}
  668. #: Connection to VMM
  669. self.vmm = VMMConnection(
  670. offline_mode=offline_mode,
  671. libvirt_reconnect_cb=self.register_event_handlers)
  672. #: Information about host system
  673. self.host = QubesHost(self)
  674. if store is not None:
  675. self._store = store
  676. else:
  677. self._store = os.environ.get('QUBES_XML_PATH',
  678. os.path.join(
  679. qubes.config.qubes_base_dir,
  680. qubes.config.system_path[
  681. 'qubes_store_filename']))
  682. super(Qubes, self).__init__(xml=None, **kwargs)
  683. self.__load_timestamp = None
  684. self.__locked_fh = None
  685. self._domain_event_callback_id = None
  686. #: jinja2 environment for libvirt XML templates
  687. self.env = jinja2.Environment(
  688. loader=jinja2.FileSystemLoader([
  689. '/etc/qubes/templates',
  690. '/usr/share/qubes/templates',
  691. ]),
  692. undefined=jinja2.StrictUndefined)
  693. if load:
  694. self.load(lock=lock)
  695. self.events_enabled = True
  696. @property
  697. def store(self):
  698. return self._store
  699. def _migrate_global_properties(self):
  700. """Migrate renamed/dropped properties"""
  701. if self.xml is None:
  702. return
  703. # drop default_fw_netvm
  704. node_default_fw_netvm = self.xml.find(
  705. './properties/property[@name=\'default_fw_netvm\']')
  706. if node_default_fw_netvm is not None:
  707. node_default_netvm = self.xml.find(
  708. './properties/property[@name=\'default_netvm\']')
  709. try:
  710. default_fw_netvm = self.domains[node_default_fw_netvm.text]
  711. if node_default_netvm is None:
  712. default_netvm = None
  713. else:
  714. default_netvm = self.domains[node_default_netvm.text]
  715. if default_netvm != default_fw_netvm:
  716. for vm in self.domains:
  717. if not hasattr(vm, 'netvm'):
  718. continue
  719. if not getattr(vm, 'provides_network', False):
  720. continue
  721. node_netvm = vm.xml.find(
  722. './properties/property[@name=\'netvm\']')
  723. if node_netvm is not None:
  724. # non-default netvm
  725. continue
  726. # this will unfortunately break "being default"
  727. # property state, but the alternative (changing
  728. # value behind user's back) is worse
  729. properties = vm.xml.find('./properties')
  730. element = lxml.etree.Element('property',
  731. name='netvm')
  732. element.text = default_fw_netvm.name
  733. # manipulate xml directly, before loading netvm
  734. # property, to avoid hitting netvm loop detection
  735. properties.append(element)
  736. except KeyError:
  737. # if default_fw_netvm was set to invalid value, simply
  738. # drop it
  739. pass
  740. node_default_fw_netvm.getparent().remove(node_default_fw_netvm)
  741. def load(self, lock=False):
  742. """Open qubes.xml
  743. :throws EnvironmentError: failure on parsing store
  744. :throws xml.parsers.expat.ExpatError: failure on parsing store
  745. :raises lxml.etree.XMLSyntaxError: on syntax error in qubes.xml
  746. """
  747. fh = self._acquire_lock()
  748. self.xml = lxml.etree.parse(fh)
  749. # stage 1: load labels and pools
  750. for node in self.xml.xpath('./labels/label'):
  751. label = qubes.Label.fromxml(node)
  752. self.labels[label.index] = label
  753. for node in self.xml.xpath('./pools/pool'):
  754. name = node.get('name')
  755. assert name, "Pool name '%s' is invalid " % name
  756. try:
  757. self.pools[name] = self._get_pool(**node.attrib)
  758. except qubes.exc.QubesException as e:
  759. self.log.error(str(e))
  760. # stage 2: load VMs
  761. for node in self.xml.xpath('./domains/domain'):
  762. # pylint: disable=no-member
  763. cls = self.get_vm_class(node.get('class'))
  764. vm = cls(self, node)
  765. vm.load_properties(load_stage=2)
  766. vm.init_log()
  767. self.domains.add(vm, _enable_events=False)
  768. if 0 not in self.domains:
  769. self.domains.add(
  770. qubes.vm.adminvm.AdminVM(self, None),
  771. _enable_events=False)
  772. self._migrate_global_properties()
  773. # stage 3: load global properties
  774. self.load_properties(load_stage=3)
  775. # stage 4: fill all remaining VM properties
  776. for vm in self.domains:
  777. vm.load_properties(load_stage=4)
  778. vm.load_extras()
  779. # stage 5: misc fixups
  780. self.property_require('default_guivm', allow_none=True)
  781. self.property_require('default_netvm', allow_none=True)
  782. self.property_require('default_template', allow_none=True)
  783. self.property_require('clockvm', allow_none=True)
  784. self.property_require('updatevm', allow_none=True)
  785. for vm in self.domains:
  786. vm.events_enabled = True
  787. vm.fire_event('domain-load')
  788. # get a file timestamp (before closing it - still holding the lock!),
  789. # to detect whether anyone else have modified it in the meantime
  790. self.__load_timestamp = os.path.getmtime(self._store)
  791. if not lock:
  792. self._release_lock()
  793. def __xml__(self):
  794. element = lxml.etree.Element('qubes')
  795. element.append(self.xml_labels())
  796. pools_xml = lxml.etree.Element('pools')
  797. for pool in self.pools.values():
  798. xml = pool.__xml__()
  799. if xml is not None:
  800. pools_xml.append(xml)
  801. element.append(pools_xml)
  802. element.append(self.xml_properties())
  803. domains = lxml.etree.Element('domains')
  804. for vm in self.domains:
  805. domains.append(vm.__xml__())
  806. element.append(domains)
  807. return element
  808. def __str__(self):
  809. return type(self).__name__
  810. def save(self, lock=True):
  811. """Save all data to qubes.xml
  812. There are several problems with saving :file:`qubes.xml` which must be
  813. mitigated:
  814. - Running out of disk space. No space left should not result in empty
  815. file. This is done by writing to temporary file and then renaming.
  816. - Attempts to write two or more files concurrently. This is done by
  817. sophisticated locking.
  818. :param bool lock: keep file locked after saving
  819. :throws EnvironmentError: failure on saving
  820. """
  821. if not self.__locked_fh:
  822. self._acquire_lock(for_save=True)
  823. fh_new = tempfile.NamedTemporaryFile(
  824. prefix=self._store, delete=False)
  825. lxml.etree.ElementTree(self.__xml__()).write(
  826. fh_new, encoding='utf-8', pretty_print=True)
  827. fh_new.flush()
  828. try:
  829. os.chown(fh_new.name, -1, grp.getgrnam('qubes').gr_gid)
  830. os.chmod(fh_new.name, 0o660)
  831. except KeyError: # group 'qubes' not found
  832. # don't change mode if no 'qubes' group in the system
  833. pass
  834. os.rename(fh_new.name, self._store)
  835. # update stored mtime, in case of multiple save() calls without
  836. # loading qubes.xml again
  837. self.__load_timestamp = os.path.getmtime(self._store)
  838. # this releases lock for all other processes,
  839. # but they should instantly block on the new descriptor
  840. self.__locked_fh.close()
  841. self.__locked_fh = fh_new
  842. if not lock:
  843. self._release_lock()
  844. def close(self):
  845. """Deconstruct the object and break circular references
  846. After calling this the object is unusable, not even for saving."""
  847. self.log.debug('close() <- %#x', id(self))
  848. for frame in traceback.extract_stack():
  849. self.log.debug('%s', frame)
  850. super().close()
  851. if self._domain_event_callback_id is not None:
  852. self.vmm.libvirt_conn.domainEventDeregisterAny(
  853. self._domain_event_callback_id)
  854. self._domain_event_callback_id = None
  855. # Only our Lord, The God Almighty, knows what references
  856. # are kept in extensions.
  857. del self._extensions
  858. for vm in self.domains:
  859. vm.close()
  860. self.domains.close()
  861. del self.domains
  862. self.vmm.close()
  863. del self.vmm
  864. del self.host
  865. if self.__locked_fh:
  866. self._release_lock()
  867. def _acquire_lock(self, for_save=False):
  868. assert self.__locked_fh is None, 'double lock'
  869. while True:
  870. try:
  871. fd = os.open(self._store,
  872. os.O_RDWR | (os.O_CREAT * int(for_save)))
  873. except FileNotFoundError:
  874. if not for_save:
  875. raise qubes.exc.QubesException(
  876. 'Qubes XML store {!r} is missing; '
  877. 'use qubes-create tool'.format(self._store))
  878. raise
  879. # While we were waiting for lock, someone could have unlink()ed
  880. # (or rename()d) our file out of the filesystem. We have to
  881. # ensure we got lock on something linked to filesystem.
  882. # If not, try again.
  883. if os.fstat(fd) != os.stat(self._store):
  884. os.close(fd)
  885. continue
  886. if self.__load_timestamp and \
  887. os.path.getmtime(self._store) != self.__load_timestamp:
  888. os.close(fd)
  889. raise qubes.exc.QubesException(
  890. 'Someone else modified qubes.xml in the meantime')
  891. break
  892. if os.name == 'posix':
  893. fcntl.lockf(fd, fcntl.LOCK_EX)
  894. elif os.name == 'nt':
  895. # pylint: disable=protected-access
  896. overlapped = pywintypes.OVERLAPPED()
  897. win32file.LockFileEx(
  898. win32file._get_osfhandle(fd),
  899. win32con.LOCKFILE_EXCLUSIVE_LOCK, 0, -0x10000, overlapped)
  900. self.__locked_fh = os.fdopen(fd, 'r+b')
  901. return self.__locked_fh
  902. def _release_lock(self):
  903. assert self.__locked_fh is not None, 'double release'
  904. # intentionally do not call explicit unlock to not unlock the file
  905. # before all buffers are flushed
  906. self.__locked_fh.close()
  907. self.__locked_fh = None
  908. def load_initial_values(self):
  909. self.labels = {
  910. 1: qubes.Label(1, '0xcc0000', 'red'),
  911. 2: qubes.Label(2, '0xf57900', 'orange'),
  912. 3: qubes.Label(3, '0xedd400', 'yellow'),
  913. 4: qubes.Label(4, '0x73d216', 'green'),
  914. 5: qubes.Label(5, '0x555753', 'gray'),
  915. 6: qubes.Label(6, '0x3465a4', 'blue'),
  916. 7: qubes.Label(7, '0x75507b', 'purple'),
  917. 8: qubes.Label(8, '0x000000', 'black'),
  918. }
  919. assert max(self.labels.keys()) == qubes.config.max_default_label
  920. pool_configs = copy.deepcopy(qubes.config.defaults['pool_configs'])
  921. root_volume_group, root_thin_pool = \
  922. qubes.storage.DirectoryThinPool.thin_pool('/')
  923. if root_thin_pool:
  924. lvm_config = {
  925. 'name': 'lvm',
  926. 'driver': 'lvm_thin',
  927. 'volume_group': root_volume_group,
  928. 'thin_pool': root_thin_pool
  929. }
  930. pool_configs[lvm_config['name']] = lvm_config
  931. for name, config in pool_configs.items():
  932. if 'driver' not in config and 'dir_path' in config:
  933. config['driver'] = 'file'
  934. try:
  935. os.makedirs(config['dir_path'], exist_ok=True)
  936. if qubes.storage.reflink.is_supported(config['dir_path']):
  937. config['driver'] = 'file-reflink'
  938. config['setup_check'] = 'no' # don't check twice
  939. except PermissionError: # looks like a testing environment
  940. pass # stay with 'file'
  941. self.pools[name] = self._get_pool(**config)
  942. self.default_pool_kernel = 'linux-kernel'
  943. self.domains.add(
  944. qubes.vm.adminvm.AdminVM(self, None, label='black'))
  945. @classmethod
  946. def create_empty_store(cls, *args, **kwargs):
  947. self = cls(*args, load=False, **kwargs)
  948. if os.path.exists(self.store):
  949. raise qubes.exc.QubesException(
  950. '{} already exists, aborting'.format(self.store))
  951. self.load_initial_values()
  952. # TODO py3 get lock= as keyword-only arg
  953. self.save(kwargs.get('lock'))
  954. return self
  955. def xml_labels(self):
  956. """Serialise labels
  957. :rtype: lxml.etree._Element
  958. """
  959. labels = lxml.etree.Element('labels')
  960. for label in sorted(self.labels.values(), key=lambda labl: labl.index):
  961. labels.append(label.__xml__())
  962. return labels
  963. @staticmethod
  964. def get_vm_class(clsname):
  965. """Find the class for a domain.
  966. Classes are registered as setuptools' entry points in ``qubes.vm``
  967. group. Any package may supply their own classes.
  968. :param str clsname: name of the class
  969. :return type: class
  970. """
  971. try:
  972. return qubes.utils.get_entry_point_one(
  973. qubes.vm.VM_ENTRY_POINT, clsname)
  974. except KeyError:
  975. raise qubes.exc.QubesException(
  976. 'no such VM class: {!r}'.format(clsname))
  977. # don't catch TypeError
  978. def add_new_vm(self, cls, qid=None, **kwargs):
  979. """Add new Virtual Machine to collection
  980. """
  981. if qid is None:
  982. qid = self.domains.get_new_unused_qid()
  983. if isinstance(cls, str):
  984. cls = self.get_vm_class(cls)
  985. # handle default template; specifically allow template=None (do not
  986. # override it with default template)
  987. if 'template' not in kwargs and hasattr(cls, 'template'):
  988. if cls == self.get_vm_class('DispVM'):
  989. kwargs['template'] = self.default_dispvm
  990. else:
  991. kwargs['template'] = self.default_template
  992. if kwargs['template'] is None:
  993. raise qubes.exc.QubesValueError(
  994. 'Template for the qube not specified, nor default '
  995. 'template set.')
  996. elif 'template' in kwargs and isinstance(kwargs['template'], str):
  997. kwargs['template'] = self.domains[kwargs['template']]
  998. return self.domains.add(cls(self, None, qid=qid, **kwargs))
  999. def get_label(self, label):
  1000. """Get label as identified by index or name
  1001. :throws KeyError: when label is not found
  1002. """
  1003. # first search for index, verbatim
  1004. try:
  1005. return self.labels[label]
  1006. except KeyError:
  1007. pass
  1008. # then search for name
  1009. for i in self.labels.values():
  1010. if i.name == label:
  1011. return i
  1012. # last call, if label is a number represented as str, search in indices
  1013. try:
  1014. return self.labels[int(label)]
  1015. except (KeyError, ValueError):
  1016. pass
  1017. raise KeyError(label)
  1018. @asyncio.coroutine
  1019. def setup_pools(self):
  1020. """ Run implementation specific setup for each storage pool. """
  1021. yield from qubes.utils.void_coros_maybe(
  1022. pool.setup() for pool in self.pools.values())
  1023. @asyncio.coroutine
  1024. def add_pool(self, name, **kwargs):
  1025. """ Add a storage pool to config."""
  1026. if name in self.pools.keys():
  1027. raise qubes.exc.QubesException('pool named %s already exists \n' %
  1028. name)
  1029. kwargs['name'] = name
  1030. pool = self._get_pool(**kwargs)
  1031. yield from qubes.utils.coro_maybe(pool.setup())
  1032. self.pools[name] = pool
  1033. yield from self.fire_event_async('pool-add', pool=pool)
  1034. return pool
  1035. @asyncio.coroutine
  1036. def remove_pool(self, name):
  1037. """ Remove a storage pool from config file. """
  1038. try:
  1039. pool = self.pools[name]
  1040. volumes = [(vm, volume) for vm in self.domains
  1041. for volume in vm.volumes.values()
  1042. if volume.pool is pool]
  1043. if volumes:
  1044. raise qubes.exc.QubesPoolInUseError(pool)
  1045. prop_suffixes = ['', '_kernel', '_private', '_root', '_volatile']
  1046. for suffix in prop_suffixes:
  1047. if getattr(self, 'default_pool' + suffix, None) is pool:
  1048. raise qubes.exc.QubesPoolInUseError(
  1049. pool,
  1050. 'Storage pool is in use: '
  1051. 'set as {}'.format('default_pool' + suffix))
  1052. yield from self.fire_event_async('pool-pre-delete',
  1053. pre_event=True, pool=pool)
  1054. del self.pools[name]
  1055. yield from qubes.utils.coro_maybe(pool.destroy())
  1056. yield from self.fire_event_async('pool-delete', pool=pool)
  1057. except KeyError:
  1058. return
  1059. def get_pool(self, pool):
  1060. """ Returns a :py:class:`qubes.storage.Pool` instance """
  1061. if isinstance(pool, qubes.storage.Pool):
  1062. return pool
  1063. try:
  1064. return self.pools[pool]
  1065. except KeyError:
  1066. raise qubes.exc.QubesException('Unknown storage pool ' + pool)
  1067. @staticmethod
  1068. def _get_pool(**kwargs):
  1069. try:
  1070. name = kwargs['name']
  1071. assert name, 'Name needs to be an non empty string'
  1072. except KeyError:
  1073. raise qubes.exc.QubesException('No pool name for pool')
  1074. try:
  1075. driver = kwargs['driver']
  1076. except KeyError:
  1077. raise qubes.exc.QubesException('No driver specified for pool ' +
  1078. name)
  1079. try:
  1080. klass = qubes.utils.get_entry_point_one(
  1081. qubes.storage.STORAGE_ENTRY_POINT, driver)
  1082. del kwargs['driver']
  1083. return klass(**kwargs)
  1084. except KeyError:
  1085. raise qubes.exc.QubesException('No driver %s for pool %s' %
  1086. (driver, name))
  1087. def register_event_handlers(self, old_connection=None):
  1088. """Register libvirt event handlers, which will translate libvirt
  1089. events into qubes.events. This function should be called only in
  1090. 'qubesd' process and only when mainloop has been already set.
  1091. """
  1092. if old_connection:
  1093. try:
  1094. old_connection.domainEventDeregisterAny(
  1095. self._domain_event_callback_id)
  1096. except libvirt.libvirtError:
  1097. # the connection is probably in a bad state; but call the above
  1098. # anyway to cleanup the client structures
  1099. pass
  1100. self._domain_event_callback_id = (
  1101. self.vmm.libvirt_conn.domainEventRegisterAny(
  1102. None, # any domain
  1103. libvirt.VIR_DOMAIN_EVENT_ID_LIFECYCLE,
  1104. self._domain_event_callback,
  1105. None))
  1106. def _domain_event_callback(self, _conn, domain, event, _detail, _opaque):
  1107. """Generic libvirt event handler (virConnectDomainEventCallback),
  1108. translate libvirt event into qubes.events.
  1109. """
  1110. if not self.events_enabled:
  1111. return
  1112. try:
  1113. vm = self.domains[domain.name()]
  1114. except KeyError:
  1115. # ignore events for unknown domains
  1116. return
  1117. if event == libvirt.VIR_DOMAIN_EVENT_STOPPED:
  1118. vm.on_libvirt_domain_stopped()
  1119. elif event == libvirt.VIR_DOMAIN_EVENT_SUSPENDED:
  1120. try:
  1121. vm.fire_event('domain-paused')
  1122. except Exception: # pylint: disable=broad-except
  1123. self.log.exception(
  1124. 'Uncaught exception from domain-paused handler '
  1125. 'for domain %s', vm.name)
  1126. elif event == libvirt.VIR_DOMAIN_EVENT_RESUMED:
  1127. try:
  1128. vm.fire_event('domain-unpaused')
  1129. except Exception: # pylint: disable=broad-except
  1130. self.log.exception(
  1131. 'Uncaught exception from domain-unpaused handler '
  1132. 'for domain %s', vm.name)
  1133. @qubes.events.handler('domain-pre-delete')
  1134. def on_domain_pre_deleted(self, event, vm):
  1135. # pylint: disable=unused-argument
  1136. for obj in itertools.chain(self.domains, (self,)):
  1137. if obj is vm:
  1138. # allow removed VM to reference itself
  1139. continue
  1140. for prop in obj.property_list():
  1141. try:
  1142. if isinstance(prop, qubes.vm.VMProperty) and \
  1143. getattr(obj, prop.__name__) == vm:
  1144. self.log.error(
  1145. 'Cannot remove %s, used by %s.%s',
  1146. vm, obj, prop.__name__)
  1147. raise qubes.exc.QubesVMInUseError(
  1148. vm,
  1149. 'Domain is in use: {!r};'
  1150. 'see /var/log/qubes/qubes.log in dom0 for '
  1151. 'details'.format(
  1152. vm.name))
  1153. except AttributeError:
  1154. pass
  1155. @qubes.events.handler('domain-delete')
  1156. def on_domain_deleted(self, event, vm):
  1157. # pylint: disable=unused-argument
  1158. for propname in (
  1159. 'default_guivm'
  1160. 'default_netvm',
  1161. 'default_fw_netvm',
  1162. 'clockvm',
  1163. 'updatevm',
  1164. 'default_template',
  1165. ):
  1166. try:
  1167. if getattr(self, propname) == vm:
  1168. delattr(self, propname)
  1169. except AttributeError:
  1170. pass
  1171. @qubes.events.handler('property-pre-set:clockvm')
  1172. def on_property_pre_set_clockvm(self, event, name, newvalue, oldvalue=None):
  1173. # pylint: disable=unused-argument,no-self-use
  1174. if newvalue is None:
  1175. return
  1176. if 'service.clocksync' not in newvalue.features:
  1177. newvalue.features['service.clocksync'] = True
  1178. @qubes.events.handler('property-set:clockvm')
  1179. def on_property_set_clockvm(self, event, name, newvalue, oldvalue=None):
  1180. # pylint: disable=unused-argument,no-self-use
  1181. if oldvalue and oldvalue.features.get('service.clocksync', False):
  1182. del oldvalue.features['service.clocksync']
  1183. @qubes.events.handler('property-pre-set:default_netvm')
  1184. def on_property_pre_set_default_netvm(self, event, name, newvalue,
  1185. oldvalue=None):
  1186. # pylint: disable=unused-argument,invalid-name
  1187. if newvalue is not None and oldvalue is not None \
  1188. and oldvalue.is_running() and not newvalue.is_running() \
  1189. and self.domains.get_vms_connected_to(oldvalue):
  1190. raise qubes.exc.QubesVMNotRunningError(
  1191. newvalue,
  1192. 'Cannot change {!r} to domain that '
  1193. 'is not running ({!r}).'.format(
  1194. name, newvalue.name))
  1195. @qubes.events.handler('property-set:default_fw_netvm')
  1196. def on_property_set_default_fw_netvm(self, event, name, newvalue,
  1197. oldvalue=None):
  1198. # pylint: disable=unused-argument,invalid-name
  1199. for vm in self.domains:
  1200. if hasattr(vm, 'provides_network') and vm.provides_network and \
  1201. hasattr(vm, 'netvm') and vm.property_is_default('netvm'):
  1202. # fire property-del:netvm as it is responsible for resetting
  1203. # netvm to it's default value
  1204. vm.fire_event('property-pre-del:netvm', pre_event=True,
  1205. name='netvm', oldvalue=oldvalue)
  1206. vm.fire_event('property-del:netvm',
  1207. name='netvm', oldvalue=oldvalue)
  1208. @qubes.events.handler('property-set:default_netvm')
  1209. def on_property_set_default_netvm(self, event, name, newvalue,
  1210. oldvalue=None):
  1211. # pylint: disable=unused-argument
  1212. for vm in self.domains:
  1213. if hasattr(vm, 'provides_network') and not vm.provides_network and \
  1214. hasattr(vm, 'netvm') and vm.property_is_default('netvm'):
  1215. # fire property-del:netvm as it is responsible for resetting
  1216. # netvm to it's default value
  1217. vm.fire_event('property-pre-del:netvm', pre_event=True,
  1218. name='netvm', oldvalue=oldvalue)
  1219. vm.fire_event('property-del:netvm',
  1220. name='netvm', oldvalue=oldvalue)