app.py 46 KB

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