app.py 46 KB

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