app.py 48 KB

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