__init__.py 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527
  1. #!/usr/bin/python2 -O
  2. # vim: fileencoding=utf-8
  3. #
  4. # The Qubes OS Project, https://www.qubes-os.org/
  5. #
  6. # Copyright (C) 2010-2015 Joanna Rutkowska <joanna@invisiblethingslab.com>
  7. # Copyright (C) 2011-2015 Marek Marczykowski-Górecki
  8. # <marmarek@invisiblethingslab.com>
  9. # Copyright (C) 2014-2015 Wojtek Porczyk <woju@invisiblethingslab.com>
  10. #
  11. # This program is free software; you can redistribute it and/or modify
  12. # it under the terms of the GNU General Public License as published by
  13. # the Free Software Foundation; either version 2 of the License, or
  14. # (at your option) any later version.
  15. #
  16. # This program is distributed in the hope that it will be useful,
  17. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. # GNU General Public License for more details.
  20. #
  21. # You should have received a copy of the GNU General Public License along
  22. # with this program; if not, write to the Free Software Foundation, Inc.,
  23. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  24. #
  25. '''
  26. Qubes OS
  27. :copyright: © 2010-2015 Invisible Things Lab
  28. '''
  29. from __future__ import absolute_import
  30. __author__ = 'Invisible Things Lab'
  31. __license__ = 'GPLv2 or later'
  32. __version__ = 'R3'
  33. import ast
  34. import atexit
  35. import collections
  36. import errno
  37. import grp
  38. import logging
  39. import os
  40. import os.path
  41. import sys
  42. import tempfile
  43. import time
  44. import warnings
  45. import __builtin__
  46. import docutils.core
  47. import docutils.io
  48. import lxml.etree
  49. import pkg_resources
  50. import qubes.config
  51. import qubes.events
  52. import qubes.exc
  53. import qubes.ext
  54. if os.name == 'posix':
  55. import fcntl
  56. elif os.name == 'nt':
  57. # pylint: disable=import-error
  58. import win32con
  59. import win32file
  60. import pywintypes
  61. else:
  62. raise RuntimeError("Qubes works only on POSIX or WinNT systems")
  63. import libvirt
  64. try:
  65. import xen.lowlevel.xs
  66. import xen.lowlevel.xc
  67. except ImportError:
  68. pass
  69. class VMMConnection(object):
  70. '''Connection to Virtual Machine Manager (libvirt)'''
  71. def __init__(self):
  72. self._libvirt_conn = None
  73. self._xs = None
  74. self._xc = None
  75. self._offline_mode = False
  76. @__builtin__.property
  77. def offline_mode(self):
  78. '''Check or enable offline mode (do not actually connect to vmm)'''
  79. return self._offline_mode
  80. @offline_mode.setter
  81. def offline_mode(self, value):
  82. if value and self._libvirt_conn is not None:
  83. raise qubes.exc.QubesException(
  84. 'Cannot change offline mode while already connected')
  85. self._offline_mode = value
  86. def _libvirt_error_handler(self, ctx, error):
  87. pass
  88. def init_vmm_connection(self):
  89. '''Initialise connection
  90. This method is automatically called when getting'''
  91. if self._libvirt_conn is not None:
  92. # Already initialized
  93. return
  94. if self._offline_mode:
  95. # Do not initialize in offline mode
  96. raise qubes.exc.QubesException(
  97. 'VMM operations disabled in offline mode')
  98. if 'xen.lowlevel.xs' in sys.modules:
  99. self._xs = xen.lowlevel.xs.xs()
  100. if 'xen.lowlevel.cs' in sys.modules:
  101. self._xc = xen.lowlevel.xc.xc()
  102. self._libvirt_conn = libvirt.open(qubes.config.defaults['libvirt_uri'])
  103. if self._libvirt_conn is None:
  104. raise qubes.exc.QubesException('Failed connect to libvirt driver')
  105. libvirt.registerErrorHandler(self._libvirt_error_handler, None)
  106. @__builtin__.property
  107. def libvirt_conn(self):
  108. '''Connection to libvirt'''
  109. self.init_vmm_connection()
  110. return self._libvirt_conn
  111. @__builtin__.property
  112. def xs(self):
  113. '''Connection to Xen Store
  114. This property in available only when running on Xen.
  115. '''
  116. # XXX what about the case when we run under KVM,
  117. # but xen modules are importable?
  118. if 'xen.lowlevel.xs' not in sys.modules:
  119. raise AttributeError(
  120. 'xs object is available under Xen hypervisor only')
  121. self.init_vmm_connection()
  122. return self._xs
  123. @__builtin__.property
  124. def xc(self):
  125. '''Connection to Xen
  126. This property in available only when running on Xen.
  127. '''
  128. # XXX what about the case when we run under KVM,
  129. # but xen modules are importable?
  130. if 'xen.lowlevel.xc' not in sys.modules:
  131. raise AttributeError(
  132. 'xc object is available under Xen hypervisor only')
  133. self.init_vmm_connection()
  134. return self._xs
  135. def __del__(self):
  136. if self._libvirt_conn:
  137. self._libvirt_conn.close()
  138. class QubesHost(object):
  139. '''Basic information about host machine
  140. :param qubes.Qubes app: Qubes application context (must have \
  141. :py:attr:`Qubes.vmm` attribute defined)
  142. '''
  143. def __init__(self, app):
  144. self.app = app
  145. self._no_cpus = None
  146. self._total_mem = None
  147. self._physinfo = None
  148. def _fetch(self):
  149. if self._no_cpus is not None:
  150. return
  151. # pylint: disable=unused-variable
  152. (model, memory, cpus, mhz, nodes, socket, cores, threads) = \
  153. self.app.vmm.libvirt_conn.getInfo()
  154. self._total_mem = long(memory) * 1024
  155. self._no_cpus = cpus
  156. self.app.log.debug('QubesHost: no_cpus={} memory_total={}'.format(
  157. self.no_cpus, self.memory_total))
  158. try:
  159. self.app.log.debug('QubesHost: xen_free_memory={}'.format(
  160. self.get_free_xen_memory()))
  161. except NotImplementedError:
  162. pass
  163. @__builtin__.property
  164. def memory_total(self):
  165. '''Total memory, in kbytes'''
  166. self._fetch()
  167. return self._total_mem
  168. @__builtin__.property
  169. def no_cpus(self):
  170. '''Number of CPUs'''
  171. self._fetch()
  172. return self._no_cpus
  173. def get_free_xen_memory(self):
  174. '''Get free memory from Xen's physinfo.
  175. :raises NotImplementedError: when not under Xen
  176. '''
  177. try:
  178. self._physinfo = self.app.xc.physinfo()
  179. except AttributeError:
  180. raise NotImplementedError('This function requires Xen hypervisor')
  181. return long(self._physinfo['free_memory'])
  182. def measure_cpu_usage(self, previous_time=None, previous=None,
  183. wait_time=1):
  184. '''Measure cpu usage for all domains at once.
  185. This function requires Xen hypervisor.
  186. .. versionchanged:: 3.0
  187. argument order to match return tuple
  188. :raises NotImplementedError: when not under Xen
  189. '''
  190. if previous is None:
  191. previous_time = time.time()
  192. previous = {}
  193. try:
  194. info = self.app.vmm.xc.domain_getinfo(0, qubes.config.max_qid)
  195. except AttributeError:
  196. raise NotImplementedError(
  197. 'This function requires Xen hypervisor')
  198. for vm in info:
  199. previous[vm['domid']] = {}
  200. previous[vm['domid']]['cpu_time'] = (
  201. vm['cpu_time'] / vm['online_vcpus'])
  202. previous[vm['domid']]['cpu_usage'] = 0
  203. time.sleep(wait_time)
  204. current_time = time.time()
  205. current = {}
  206. try:
  207. info = self.app.vmm.xc.domain_getinfo(0, qubes.config.max_qid)
  208. except AttributeError:
  209. raise NotImplementedError(
  210. 'This function requires Xen hypervisor')
  211. for vm in info:
  212. current[vm['domid']] = {}
  213. current[vm['domid']]['cpu_time'] = (
  214. vm['cpu_time'] / max(vm['online_vcpus'], 1))
  215. if vm['domid'] in previous.keys():
  216. current[vm['domid']]['cpu_usage'] = (
  217. float(current[vm['domid']]['cpu_time'] -
  218. previous[vm['domid']]['cpu_time']) /
  219. long(1000 ** 3) / (current_time - previous_time) * 100)
  220. if current[vm['domid']]['cpu_usage'] < 0:
  221. # VM has been rebooted
  222. current[vm['domid']]['cpu_usage'] = 0
  223. else:
  224. current[vm['domid']]['cpu_usage'] = 0
  225. return (current_time, current)
  226. class Label(object):
  227. '''Label definition for virtual machines
  228. Label specifies colour of the padlock displayed next to VM's name.
  229. When this is a :py:class:`qubes.vm.dispvm.DispVM`, padlock is overlayed
  230. with recycling pictogram.
  231. :param int index: numeric identificator of label
  232. :param str color: colour specification as in HTML (``#abcdef``)
  233. :param str name: label's name like "red" or "green"
  234. '''
  235. def __init__(self, index, color, name):
  236. #: numeric identificator of label
  237. self.index = index
  238. #: colour specification as in HTML (``#abcdef``)
  239. self.color = color
  240. #: label's name like "red" or "green"
  241. self.name = name
  242. #: freedesktop icon name, suitable for use in
  243. #: :py:meth:`PyQt4.QtGui.QIcon.fromTheme`
  244. self.icon = 'appvm-' + name
  245. #: freedesktop icon name, suitable for use in
  246. #: :py:meth:`PyQt4.QtGui.QIcon.fromTheme` on DispVMs
  247. self.icon_dispvm = 'dispvm-' + name
  248. @classmethod
  249. def fromxml(cls, xml):
  250. '''Create label definition from XML node
  251. :param lxml.etree._Element xml: XML node reference
  252. :rtype: :py:class:`qubes.Label`
  253. '''
  254. index = int(xml.get('id').split('-', 1)[1])
  255. color = xml.get('color')
  256. name = xml.text
  257. return cls(index, color, name)
  258. def __xml__(self):
  259. element = lxml.etree.Element(
  260. 'label', id='label-{}'.format(self.index), color=self.color)
  261. element.text = self.name
  262. return element
  263. def __str__(self):
  264. return self.name
  265. def __repr__(self):
  266. return '{}({!r}, {!r}, {!r})'.format(
  267. self.__class__.__name__,
  268. self.index,
  269. self.color,
  270. self.name)
  271. @__builtin__.property
  272. def icon_path(self):
  273. '''Icon path
  274. .. deprecated:: 2.0
  275. use :py:meth:`PyQt4.QtGui.QIcon.fromTheme` and :py:attr:`icon`
  276. '''
  277. return os.path.join(qubes.config.system_path['qubes_icon_dir'],
  278. self.icon) + ".png"
  279. @__builtin__.property
  280. def icon_path_dispvm(self):
  281. '''Icon path
  282. .. deprecated:: 2.0
  283. use :py:meth:`PyQt4.QtGui.QIcon.fromTheme` and :py:attr:`icon_dispvm`
  284. '''
  285. return os.path.join(qubes.config.system_path['qubes_icon_dir'],
  286. self.icon_dispvm) + ".png"
  287. class VMCollection(object):
  288. '''A collection of Qubes VMs
  289. VMCollection supports ``in`` operator. You may test for ``qid``, ``name``
  290. and whole VM object's presence.
  291. Iterating over VMCollection will yield machine objects.
  292. '''
  293. def __init__(self, app):
  294. self.app = app
  295. self._dict = dict()
  296. def __repr__(self):
  297. return '<{} {!r}>'.format(
  298. self.__class__.__name__, list(sorted(self.keys())))
  299. def items(self):
  300. '''Iterate over ``(qid, vm)`` pairs'''
  301. for qid in self.qids():
  302. yield (qid, self[qid])
  303. def qids(self):
  304. '''Iterate over all qids
  305. qids are sorted by numerical order.
  306. '''
  307. return iter(sorted(self._dict.keys()))
  308. keys = qids
  309. def names(self):
  310. '''Iterate over all names
  311. names are sorted by lexical order.
  312. '''
  313. return iter(sorted(vm.name for vm in self._dict.values()))
  314. def vms(self):
  315. '''Iterate over all machines
  316. vms are sorted by qid.
  317. '''
  318. return iter(sorted(self._dict.values()))
  319. __iter__ = vms
  320. values = vms
  321. def add(self, value):
  322. '''Add VM to collection
  323. :param qubes.vm.BaseVM value: VM to add
  324. :raises TypeError: when value is of wrong type
  325. :raises ValueError: when there is already VM which has equal ``qid``
  326. '''
  327. # this violates duck typing, but is needed
  328. # for VMProperty to function correctly
  329. if not isinstance(value, qubes.vm.BaseVM):
  330. raise TypeError('{} holds only BaseVM instances'.format(
  331. self.__class__.__name__))
  332. if value.qid in self:
  333. raise ValueError('This collection already holds VM that has '
  334. 'qid={!r} ({!r})'.format(value.qid, self[value.qid]))
  335. if value.name in self:
  336. raise ValueError('This collection already holds VM that has '
  337. 'name={!r} ({!r})'.format(value.name, self[value.name]))
  338. self._dict[value.qid] = value
  339. value.events_enabled = True
  340. self.app.fire_event('domain-added', value)
  341. return value
  342. def __getitem__(self, key):
  343. if isinstance(key, int):
  344. return self._dict[key]
  345. if isinstance(key, basestring):
  346. for vm in self:
  347. if vm.name == key:
  348. return vm
  349. raise KeyError(key)
  350. if isinstance(key, qubes.vm.BaseVM):
  351. if key in self:
  352. return key
  353. raise KeyError(key)
  354. raise KeyError(key)
  355. def __delitem__(self, key):
  356. vm = self[key]
  357. del self._dict[vm.qid]
  358. self.app.fire_event('domain-deleted', vm)
  359. def __contains__(self, key):
  360. return any((key == vm or key == vm.qid or key == vm.name)
  361. for vm in self)
  362. def __len__(self):
  363. return len(self._dict)
  364. def get_vms_based_on(self, template):
  365. template = self[template]
  366. return set(vm for vm in self if vm.template == template)
  367. def get_vms_connected_to(self, netvm):
  368. new_vms = set([self[netvm]])
  369. dependent_vms = set()
  370. # Dependency resolving only makes sense on NetVM (or derivative)
  371. # if not self[netvm_qid].is_netvm():
  372. # return set([])
  373. while len(new_vms) > 0:
  374. cur_vm = new_vms.pop()
  375. for vm in cur_vm.connected_vms.values():
  376. if vm in dependent_vms:
  377. continue
  378. dependent_vms.add(vm.qid)
  379. # if vm.is_netvm():
  380. new_vms.add(vm.qid)
  381. return dependent_vms
  382. # XXX with Qubes Admin Api this will probably lead to race condition
  383. # whole process of creating and adding should be synchronised
  384. def get_new_unused_qid(self):
  385. used_ids = set(self.qids())
  386. for i in range(1, qubes.config.max_qid):
  387. if i not in used_ids:
  388. return i
  389. raise LookupError("Cannot find unused qid!")
  390. def get_new_unused_netid(self):
  391. used_ids = set([vm.netid for vm in self]) # if vm.is_netvm()])
  392. for i in range(1, qubes.config.max_netid):
  393. if i not in used_ids:
  394. return i
  395. raise LookupError("Cannot find unused netid!")
  396. class property(object): # pylint: disable=redefined-builtin,invalid-name
  397. '''Qubes property.
  398. This class holds one property that can be saved to and loaded from
  399. :file:`qubes.xml`. It is used for both global and per-VM properties.
  400. Property can be unset by ordinary ``del`` statement or assigning
  401. :py:attr:`DEFAULT` special value to it. After deletion (or before first
  402. assignment/load) attempting to read a property will get its default value
  403. or, when no default, py:class:`exceptions.AttributeError`.
  404. :param str name: name of the property
  405. :param collections.Callable setter: if not :py:obj:`None`, this is used to \
  406. initialise value; first parameter to the function is holder instance \
  407. and the second is value; this is called before ``type``
  408. :param collections.Callable saver: function to coerce value to something \
  409. readable by setter
  410. :param type type: if not :py:obj:`None`, value is coerced to this type
  411. :param object default: default value; if callable, will be called with \
  412. holder as first argument
  413. :param int load_stage: stage when property should be loaded (see \
  414. :py:class:`Qubes` for description of stages)
  415. :param int order: order of evaluation (bigger order values are later)
  416. :param bool clone: :py:meth:`PropertyHolder.clone_properties` will not \
  417. include this property by default if :py:obj:`False`
  418. :param str ls_head: column head for :program:`qvm-ls`
  419. :param int ls_width: column width in :program:`qvm-ls`
  420. :param str doc: docstring; this should be one paragraph of plain RST, no \
  421. sphinx-specific features
  422. Setters and savers have following signatures:
  423. .. :py:function:: setter(self, prop, value)
  424. :noindex:
  425. :param self: instance of object that is holding property
  426. :param prop: property object
  427. :param value: value being assigned
  428. .. :py:function:: saver(self, prop, value)
  429. :noindex:
  430. :param self: instance of object that is holding property
  431. :param prop: property object
  432. :param value: value being saved
  433. :rtype: str
  434. :raises property.DontSave: when property should not be saved at all
  435. '''
  436. #: Assigning this value to property means setting it to its default value.
  437. #: If property has no default value, this will unset it.
  438. DEFAULT = object()
  439. # internal use only
  440. _NO_DEFAULT = object()
  441. def __init__(self, name, setter=None, saver=None, type=None,
  442. default=_NO_DEFAULT, write_once=False, load_stage=2, order=0,
  443. save_via_ref=False, clone=True,
  444. ls_head=None, ls_width=None, doc=None):
  445. # pylint: disable=redefined-builtin
  446. self.__name__ = name
  447. self._setter = setter
  448. self._saver = saver if saver is not None else (
  449. lambda self, prop, value: str(value))
  450. self._type = type
  451. self._default = default
  452. self._write_once = write_once
  453. self.order = order
  454. self.load_stage = load_stage
  455. self.save_via_ref = save_via_ref
  456. self.clone = clone
  457. self.__doc__ = doc
  458. self._attr_name = '_qubesprop_' + name
  459. if ls_head is not None or ls_width is not None:
  460. self.ls_head = ls_head or self.__name__.replace('_', '-').upper()
  461. self.ls_width = max(ls_width or 0, len(self.ls_head) + 1)
  462. def __get__(self, instance, owner):
  463. if instance is None:
  464. return self
  465. # XXX this violates duck typing, shall we keep it?
  466. if not isinstance(instance, PropertyHolder):
  467. raise AttributeError('qubes.property should be used on '
  468. 'qubes.PropertyHolder instances only')
  469. try:
  470. return getattr(instance, self._attr_name)
  471. except AttributeError:
  472. if self._default is self._NO_DEFAULT:
  473. raise AttributeError(
  474. 'property {!r} not set'.format(self.__name__))
  475. elif isinstance(self._default, collections.Callable):
  476. return self._default(instance)
  477. else:
  478. return self._default
  479. def __set__(self, instance, value):
  480. self._enforce_write_once(instance)
  481. if value is self.__class__.DEFAULT:
  482. self.__delete__(instance)
  483. return
  484. try:
  485. oldvalue = getattr(instance, self.__name__)
  486. has_oldvalue = True
  487. except AttributeError:
  488. has_oldvalue = False
  489. if self._setter is not None:
  490. value = self._setter(instance, self, value)
  491. if self._type not in (None, type(value)):
  492. value = self._type(value)
  493. if has_oldvalue:
  494. instance.fire_event_pre('property-pre-set:' + self.__name__,
  495. self.__name__, value, oldvalue)
  496. else:
  497. instance.fire_event_pre('property-pre-set:' + self.__name__,
  498. self.__name__, value)
  499. instance._property_init(self, value) # pylint: disable=protected-access
  500. if has_oldvalue:
  501. instance.fire_event('property-set:' + self.__name__, self.__name__,
  502. value, oldvalue)
  503. else:
  504. instance.fire_event('property-set:' + self.__name__, self.__name__,
  505. value)
  506. def __delete__(self, instance):
  507. self._enforce_write_once(instance)
  508. try:
  509. oldvalue = getattr(instance, self.__name__)
  510. has_oldvalue = True
  511. except AttributeError:
  512. has_oldvalue = False
  513. if has_oldvalue:
  514. instance.fire_event_pre('property-pre-deleted:' + self.__name__,
  515. self.__name__, oldvalue)
  516. else:
  517. instance.fire_event_pre('property-pre-deleted:' + self.__name__,
  518. self.__name__)
  519. delattr(instance, self._attr_name)
  520. if has_oldvalue:
  521. instance.fire_event('property-deleted:' + self.__name__,
  522. self.__name__, oldvalue)
  523. else:
  524. instance.fire_event('property-deleted:' + self.__name__,
  525. self.__name__)
  526. def __repr__(self):
  527. default = ' default={!r}'.format(self._default) \
  528. if self._default is not self._NO_DEFAULT \
  529. else ''
  530. return '<{} object at {:#x} name={!r}{}>'.format(
  531. self.__class__.__name__, id(self), self.__name__, default) \
  532. def __hash__(self):
  533. return hash(self.__name__)
  534. def __eq__(self, other):
  535. return isinstance(other, property) and self.__name__ == other.__name__
  536. def _enforce_write_once(self, instance):
  537. if self._write_once and not instance.property_is_default(self):
  538. raise AttributeError(
  539. 'property {!r} is write-once and already set'.format(
  540. self.__name__))
  541. #
  542. # exceptions
  543. #
  544. class DontSave(Exception):
  545. '''This exception may be raised from saver to sign that property should
  546. not be saved.
  547. '''
  548. pass
  549. @staticmethod
  550. def dontsave(self, prop, value):
  551. '''Dummy saver that never saves anything.'''
  552. # pylint: disable=bad-staticmethod-argument,unused-argument
  553. raise property.DontSave()
  554. #
  555. # some setters provided
  556. #
  557. @staticmethod
  558. def forbidden(self, prop, value):
  559. '''Property setter that forbids loading a property.
  560. This is used to effectively disable property in classes which inherit
  561. unwanted property. When someone attempts to load such a property, it
  562. :throws AttributeError: always
  563. ''' # pylint: disable=bad-staticmethod-argument,unused-argument
  564. raise AttributeError(
  565. 'setting {} property on {} instance is forbidden'.format(
  566. prop.__name__, self.__class__.__name__))
  567. @staticmethod
  568. def bool(self, prop, value):
  569. '''Property setter for boolean properties.
  570. It accepts (case-insensitive) ``'0'``, ``'no'`` and ``false`` as
  571. :py:obj:`False` and ``'1'``, ``'yes'`` and ``'true'`` as
  572. :py:obj:`True`.
  573. ''' # pylint: disable=bad-staticmethod-argument,unused-argument
  574. if isinstance(value, basestring):
  575. lcvalue = value.lower()
  576. if lcvalue in ('0', 'no', 'false', 'off'):
  577. return False
  578. if lcvalue in ('1', 'yes', 'true', 'on'):
  579. return True
  580. raise ValueError(
  581. 'Invalid literal for boolean property: {!r}'.format(value))
  582. return bool(value)
  583. class PropertyHolder(qubes.events.Emitter):
  584. '''Abstract class for holding :py:class:`qubes.property`
  585. Events fired by instances of this class:
  586. .. event:: property-load (subject, event)
  587. Fired once after all properties are loaded from XML. Individual
  588. ``property-set`` events are not fired.
  589. .. event:: property-set:<propname> \
  590. (subject, event, name, newvalue[, oldvalue])
  591. Fired when property changes state. Signature is variable,
  592. *oldvalue* is present only if there was an old value.
  593. :param name: Property name
  594. :param newvalue: New value of the property
  595. :param oldvalue: Old value of the property
  596. .. event:: property-pre-set:<propname> \
  597. (subject, event, name, newvalue[, oldvalue])
  598. Fired before property changes state. Signature is variable,
  599. *oldvalue* is present only if there was an old value.
  600. :param name: Property name
  601. :param newvalue: New value of the property
  602. :param oldvalue: Old value of the property
  603. .. event:: property-del:<propname> \
  604. (subject, event, name[, oldvalue])
  605. Fired when property gets deleted (is set to default). Signature is
  606. variable, *oldvalue* is present only if there was an old value.
  607. :param name: Property name
  608. :param oldvalue: Old value of the property
  609. .. event:: property-pre-del:<propname> \
  610. (subject, event, name[, oldvalue])
  611. Fired before property gets deleted (is set to default). Signature
  612. is variable, *oldvalue* is present only if there was an old value.
  613. :param name: Property name
  614. :param oldvalue: Old value of the property
  615. Members:
  616. '''
  617. def __init__(self, xml, **kwargs):
  618. self.xml = xml
  619. propvalues = {}
  620. all_names = set(prop.__name__ for prop in self.property_list())
  621. for key in list(kwargs.keys()):
  622. if not key in all_names:
  623. continue
  624. propvalues[key] = kwargs.pop(key)
  625. super(PropertyHolder, self).__init__(**kwargs)
  626. for key, value in propvalues.items():
  627. setattr(self, key, value)
  628. @classmethod
  629. def property_list(cls, load_stage=None):
  630. '''List all properties attached to this VM's class
  631. :param load_stage: Filter by load stage
  632. :type load_stage: :py:func:`int` or :py:obj:`None`
  633. '''
  634. props = set()
  635. for class_ in cls.__mro__:
  636. props.update(prop for prop in class_.__dict__.values()
  637. if isinstance(prop, property))
  638. if load_stage is not None:
  639. props = set(prop for prop in props
  640. if prop.load_stage == load_stage)
  641. return sorted(props,
  642. key=lambda prop: (prop.load_stage, prop.order, prop.__name__))
  643. def _property_init(self, prop, value):
  644. '''Initialise property to a given value, without side effects.
  645. :param qubes.property prop: property object of particular interest
  646. :param value: value
  647. '''
  648. # pylint: disable=protected-access
  649. setattr(self, self.property_get_def(prop)._attr_name, value)
  650. def property_is_default(self, prop):
  651. '''Check whether property is in it's default value.
  652. Properties when unset may return some default value, so
  653. ``hasattr(vm, prop.__name__)`` is wrong in some circumstances. This
  654. method allows for checking if the value returned is in fact it's
  655. default value.
  656. :param qubes.property prop: property object of particular interest
  657. :rtype: bool
  658. ''' # pylint: disable=protected-access
  659. # both property_get_def() and ._attr_name may throw AttributeError,
  660. # which we don't want to catch
  661. attrname = self.property_get_def(prop)._attr_name
  662. return not hasattr(self, attrname)
  663. @classmethod
  664. def property_get_def(cls, prop):
  665. '''Return property definition object.
  666. If prop is already :py:class:`qubes.property` instance, return the same
  667. object.
  668. :param prop: property object or name
  669. :type prop: qubes.property or str
  670. :rtype: qubes.property
  671. '''
  672. if isinstance(prop, qubes.property):
  673. return prop
  674. for p in cls.property_list():
  675. if p.__name__ == prop:
  676. return p
  677. raise AttributeError('No property {!r} found in {!r}'.format(
  678. prop, cls))
  679. def load_properties(self, load_stage=None):
  680. '''Load properties from immediate children of XML node.
  681. ``property-set`` events are not fired for each individual property.
  682. :param int load_stage: Stage of loading.
  683. '''
  684. if self.xml is None:
  685. return
  686. all_names = set(
  687. prop.__name__ for prop in self.property_list(load_stage))
  688. for node in self.xml.xpath('./properties/property'):
  689. name = node.get('name')
  690. value = node.get('ref') or node.text
  691. if not name in all_names:
  692. continue
  693. setattr(self, name, value)
  694. def xml_properties(self, with_defaults=False):
  695. '''Iterator that yields XML nodes representing set properties.
  696. :param bool with_defaults: If :py:obj:`True`, then it also includes \
  697. properties which were not set explicite, but have default values \
  698. filled.
  699. '''
  700. properties = lxml.etree.Element('properties')
  701. for prop in self.property_list():
  702. # pylint: disable=protected-access
  703. try:
  704. value = getattr(
  705. self, (prop.__name__ if with_defaults else prop._attr_name))
  706. except AttributeError:
  707. continue
  708. try:
  709. value = prop._saver(self, prop, value)
  710. except property.DontSave:
  711. continue
  712. element = lxml.etree.Element('property', name=prop.__name__)
  713. if prop.save_via_ref:
  714. element.set('ref', value)
  715. else:
  716. element.text = value
  717. properties.append(element)
  718. return properties
  719. # this was clone_attrs
  720. def clone_properties(self, src, proplist=None):
  721. '''Clone properties from other object.
  722. :param PropertyHolder src: source object
  723. :param list proplist: list of properties \
  724. (:py:obj:`None` or omit for all properties except those with \
  725. :py:attr:`property.clone` set to :py:obj:`False`)
  726. '''
  727. if proplist is None:
  728. proplist = [prop for prop in self.property_list()
  729. if prop.clone]
  730. else:
  731. proplist = [prop for prop in self.property_list()
  732. if prop.__name__ in proplist or prop in proplist]
  733. for prop in proplist:
  734. try:
  735. # pylint: disable=protected-access
  736. self._property_init(prop, getattr(src, prop._attr_name))
  737. except AttributeError:
  738. continue
  739. self.fire_event('cloned-properties', src, proplist)
  740. def property_require(self, prop, allow_none=False, hard=False):
  741. '''Complain badly when property is not set.
  742. :param prop: property name or object
  743. :type prop: qubes.property or str
  744. :param bool allow_none: if :py:obj:`True`, don't complain if \
  745. :py:obj:`None` is found
  746. :param bool hard: if :py:obj:`True`, raise :py:class:`AssertionError`; \
  747. if :py:obj:`False`, log warning instead
  748. '''
  749. if isinstance(prop, qubes.property):
  750. prop = prop.__name__
  751. try:
  752. value = getattr(self, prop)
  753. if value is None and not allow_none:
  754. raise AttributeError()
  755. except AttributeError:
  756. # pylint: disable=no-member
  757. msg = 'Required property {!r} not set on {!r}'.format(prop, self)
  758. if hard:
  759. raise AssertionError(msg)
  760. else:
  761. # pylint: disable=no-member
  762. self.log.fatal(msg)
  763. import qubes.vm
  764. class VMProperty(property):
  765. '''Property that is referring to a VM
  766. :param type vmclass: class that returned VM is supposed to be instance of
  767. and all supported by :py:class:`property` with the exception of ``type`` \
  768. and ``setter``
  769. '''
  770. _none_value = ''
  771. def __init__(self, name, vmclass=qubes.vm.BaseVM, allow_none=False,
  772. **kwargs):
  773. if 'type' in kwargs:
  774. raise TypeError(
  775. "'type' keyword parameter is unsupported in {}".format(
  776. self.__class__.__name__))
  777. if 'setter' in kwargs:
  778. raise TypeError(
  779. "'setter' keyword parameter is unsupported in {}".format(
  780. self.__class__.__name__))
  781. if not issubclass(vmclass, qubes.vm.BaseVM):
  782. raise TypeError(
  783. "'vmclass' should specify a subclass of qubes.vm.BaseVM")
  784. super(VMProperty, self).__init__(name,
  785. saver=(lambda self_, prop, value:
  786. self._none_value if value is None else value.name),
  787. **kwargs)
  788. self.vmclass = vmclass
  789. self.allow_none = allow_none
  790. def __set__(self, instance, value):
  791. if value == self._none_value:
  792. value = None
  793. if value is None:
  794. if self.allow_none:
  795. super(VMProperty, self).__set__(instance, value)
  796. return
  797. else:
  798. raise ValueError(
  799. 'Property {!r} does not allow setting to {!r}'.format(
  800. self.__name__, value))
  801. app = instance if isinstance(instance, Qubes) else instance.app
  802. try:
  803. vm = app.domains[value]
  804. except KeyError:
  805. raise qubes.exc.QubesVMNotFoundError(value)
  806. if not isinstance(vm, self.vmclass):
  807. raise TypeError('wrong VM class: domains[{!r}] if of type {!s} '
  808. 'and not {!s}'.format(value,
  809. vm.__class__.__name__,
  810. self.vmclass.__name__))
  811. super(VMProperty, self).__set__(instance, vm)
  812. import qubes.vm.qubesvm
  813. import qubes.vm.templatevm
  814. class Qubes(PropertyHolder):
  815. '''Main Qubes application
  816. :param str store: path to ``qubes.xml``
  817. The store is loaded in stages:
  818. 1. In the first stage there are loaded some basic features from store
  819. (currently labels).
  820. 2. In the second stage stubs for all VMs are loaded. They are filled
  821. with their basic properties, like ``qid`` and ``name``.
  822. 3. In the third stage all global properties are loaded. They often
  823. reference VMs, like default netvm, so they should be filled after
  824. loading VMs.
  825. 4. In the fourth stage all remaining VM properties are loaded. They
  826. also need all VMs loaded, because they represent dependencies
  827. between VMs like aforementioned netvm.
  828. 5. In the fifth stage there are some fixups to ensure sane system
  829. operation.
  830. This class emits following events:
  831. .. event:: domain-added (subject, event, vm)
  832. When domain is added.
  833. :param subject: Event emitter
  834. :param event: Event name (``'domain-added'``)
  835. :param vm: Domain object
  836. .. event:: domain-deleted (subject, event, vm)
  837. When domain is deleted. VM still has reference to ``app`` object,
  838. but is not contained within VMCollection.
  839. :param subject: Event emitter
  840. :param event: Event name (``'domain-deleted'``)
  841. :param vm: Domain object
  842. Methods and attributes:
  843. '''
  844. default_netvm = VMProperty('default_netvm', load_stage=3,
  845. default=None, allow_none=True,
  846. doc='''Default NetVM for AppVMs. Initial state is `None`, which means
  847. that AppVMs are not connected to the Internet.''')
  848. default_fw_netvm = VMProperty('default_fw_netvm', load_stage=3,
  849. default=None, allow_none=True,
  850. doc='''Default NetVM for ProxyVMs. Initial state is `None`, which means
  851. that ProxyVMs (including FirewallVM) are not connected to the
  852. Internet.''')
  853. default_template = VMProperty('default_template', load_stage=3,
  854. vmclass=qubes.vm.templatevm.TemplateVM,
  855. doc='Default template for new AppVMs')
  856. updatevm = VMProperty('updatevm', load_stage=3,
  857. allow_none=True,
  858. doc='''Which VM to use as `yum` proxy for updating AdminVM and
  859. TemplateVMs''')
  860. clockvm = VMProperty('clockvm', load_stage=3,
  861. allow_none=True,
  862. doc='Which VM to use as NTP proxy for updating AdminVM')
  863. default_kernel = property('default_kernel', load_stage=3,
  864. doc='Which kernel to use when not overriden in VM')
  865. # TODO #1637 #892
  866. check_updates_vm = property('check_updates_vm',
  867. type=bool, setter=property.bool,
  868. default=True,
  869. doc='check for updates inside qubes')
  870. def __init__(self, store=None, load=True, **kwargs):
  871. #: logger instance for logging global messages
  872. self.log = logging.getLogger('app')
  873. # pylint: disable=no-member
  874. self.extensions = set(ext.load()(self)
  875. for ext in pkg_resources.iter_entry_points('qubes.ext'))
  876. #: collection of all VMs managed by this Qubes instance
  877. self.domains = VMCollection(self)
  878. #: collection of all available labels for VMs
  879. self.labels = {}
  880. #: Connection to VMM
  881. self.vmm = VMMConnection()
  882. #: Information about host system
  883. self.host = QubesHost(self)
  884. if store is not None:
  885. self._store = store
  886. else:
  887. self._store = os.environ.get('QUBES_XML_PATH',
  888. os.path.join(
  889. qubes.config.system_path['qubes_base_dir'],
  890. qubes.config.system_path['qubes_store_filename']))
  891. super(Qubes, self).__init__(xml=None, **kwargs)
  892. self.__load_timestamp = None
  893. if load:
  894. self.load()
  895. self.events_enabled = True
  896. def load(self):
  897. '''Open qubes.xml
  898. :throws EnvironmentError: failure on parsing store
  899. :throws xml.parsers.expat.ExpatError: failure on parsing store
  900. :raises lxml.etree.XMLSyntaxError: on syntax error in qubes.xml
  901. '''
  902. fd = os.open(self._store, os.O_RDWR) # no O_CREAT
  903. fh = os.fdopen(fd, 'rb')
  904. if os.name == 'posix':
  905. fcntl.lockf(fh, fcntl.LOCK_EX)
  906. elif os.name == 'nt':
  907. # pylint: disable=protected-access
  908. win32file.LockFileEx(
  909. win32file._get_osfhandle(fh.fileno()),
  910. win32con.LOCKFILE_EXCLUSIVE_LOCK,
  911. 0, -0x10000,
  912. pywintypes.OVERLAPPED())
  913. self.xml = lxml.etree.parse(fh)
  914. # stage 1: load labels
  915. for node in self.xml.xpath('./labels/label'):
  916. label = Label.fromxml(node)
  917. self.labels[label.index] = label
  918. # stage 2: load VMs
  919. for node in self.xml.xpath('./domains/domain'):
  920. # pylint: disable=no-member
  921. cls = self.get_vm_class(node.get('class'))
  922. vm = cls(self, node)
  923. vm.load_properties(load_stage=2)
  924. vm.init_log()
  925. self.domains.add(vm)
  926. if not 0 in self.domains:
  927. self.domains.add(qubes.vm.adminvm.AdminVM(
  928. self, None, qid=0, name='dom0'))
  929. # stage 3: load global properties
  930. self.load_properties(load_stage=3)
  931. # stage 4: fill all remaining VM properties
  932. for vm in self.domains:
  933. vm.load_properties(load_stage=4)
  934. # stage 5: misc fixups
  935. self.property_require('default_fw_netvm', allow_none=True)
  936. self.property_require('default_netvm', allow_none=True)
  937. self.property_require('default_template')
  938. self.property_require('clockvm', allow_none=True)
  939. self.property_require('updatevm', allow_none=True)
  940. # Disable ntpd in ClockVM - to not conflict with ntpdate (both are
  941. # using 123/udp port)
  942. if hasattr(self, 'clockvm') and self.clockvm is not None:
  943. if self.clockvm.features.get('services/ntpd', False):
  944. self.log.warning("VM set as clockvm ({!r}) has enabled 'ntpd' "
  945. "service! Expect failure when syncing time in dom0.".format(
  946. self.clockvm))
  947. else:
  948. self.clockvm.features['services/ntpd'] = ''
  949. for vm in self.domains:
  950. vm.events_enabled = True
  951. vm.fire_event('domain-loaded')
  952. # get a file timestamp (before closing it - still holding the lock!),
  953. # to detect whether anyone else have modified it in the meantime
  954. self.__load_timestamp = os.path.getmtime(self._store)
  955. # intentionally do not call explicit unlock
  956. fh.close()
  957. del fh
  958. def __xml__(self):
  959. element = lxml.etree.Element('qubes')
  960. element.append(self.xml_labels())
  961. element.append(self.xml_properties())
  962. domains = lxml.etree.Element('domains')
  963. for vm in self.domains:
  964. domains.append(vm.__xml__())
  965. element.append(domains)
  966. return element
  967. def save(self):
  968. '''Save all data to qubes.xml
  969. There are several problems with saving :file:`qubes.xml` which must be
  970. mitigated:
  971. - Running out of disk space. No space left should not result in empty
  972. file. This is done by writing to temporary file and then renaming.
  973. - Attempts to write two or more files concurrently. This is done by
  974. sophisticated locking.
  975. :throws EnvironmentError: failure on saving
  976. '''
  977. while True:
  978. fd_old = os.open(self._store, os.O_RDWR | os.O_CREAT)
  979. if os.name == 'posix':
  980. fcntl.lockf(fd_old, fcntl.LOCK_EX)
  981. elif os.name == 'nt':
  982. # pylint: disable=protected-access
  983. overlapped = pywintypes.OVERLAPPED()
  984. win32file.LockFileEx(
  985. win32file._get_osfhandle(fd_old),
  986. win32con.LOCKFILE_EXCLUSIVE_LOCK, 0, -0x10000, overlapped)
  987. # While we were waiting for lock, someone could have unlink()ed (or
  988. # rename()d) our file out of the filesystem. We have to ensure we
  989. # got lock on something linked to filesystem. If not, try again.
  990. if os.fstat(fd_old) == os.stat(self._store):
  991. break
  992. else:
  993. os.close(fd_old)
  994. if self.__load_timestamp:
  995. current_file_timestamp = os.path.getmtime(self._store)
  996. if current_file_timestamp != self.__load_timestamp:
  997. os.close(fd_old)
  998. raise qubes.exc.QubesException(
  999. "Someone else modified qubes.xml in the meantime")
  1000. fh_new = tempfile.NamedTemporaryFile(prefix=self._store, delete=False)
  1001. lxml.etree.ElementTree(self.__xml__()).write(
  1002. fh_new, encoding='utf-8', pretty_print=True)
  1003. fh_new.flush()
  1004. os.chmod(fh_new.name, 0660)
  1005. os.chown(fh_new.name, -1, grp.getgrnam('qubes').gr_gid)
  1006. os.rename(fh_new.name, self._store)
  1007. # intentionally do not call explicit unlock to not unlock the file
  1008. # before all buffers are flushed
  1009. fh_new.close()
  1010. # update stored mtime, in case of multiple save() calls without
  1011. # loading qubes.xml again
  1012. self.__load_timestamp = os.path.getmtime(self._store)
  1013. os.close(fd_old)
  1014. @classmethod
  1015. def create_empty_store(cls, *args, **kwargs):
  1016. self = cls(*args, load=False, **kwargs)
  1017. self.labels = {
  1018. 1: Label(1, '0xcc0000', 'red'),
  1019. 2: Label(2, '0xf57900', 'orange'),
  1020. 3: Label(3, '0xedd400', 'yellow'),
  1021. 4: Label(4, '0x73d216', 'green'),
  1022. 5: Label(5, '0x555753', 'gray'),
  1023. 6: Label(6, '0x3465a4', 'blue'),
  1024. 7: Label(7, '0x75507b', 'purple'),
  1025. 8: Label(8, '0x000000', 'black'),
  1026. }
  1027. self.domains.add(
  1028. qubes.vm.adminvm.AdminVM(self, None, qid=0, name='dom0'))
  1029. self.save()
  1030. return self
  1031. def xml_labels(self):
  1032. '''Serialise labels
  1033. :rtype: lxml.etree._Element
  1034. '''
  1035. labels = lxml.etree.Element('labels')
  1036. for label in sorted(self.labels.values(), key=lambda labl: labl.index):
  1037. labels.append(label.__xml__())
  1038. return labels
  1039. def get_vm_class(self, clsname):
  1040. '''Find the class for a domain.
  1041. Classess are registered as setuptools' entry points in ``qubes.vm``
  1042. group. Any package may supply their own classess.
  1043. :param str clsname: name of the class
  1044. :return type: class
  1045. '''
  1046. epoints = tuple(pkg_resources.iter_entry_points('qubes.vm', clsname))
  1047. if not epoints:
  1048. raise qubes.exc.QubesException(
  1049. 'no such VM class: {!r}'.format(clsname))
  1050. elif len(epoints) > 1:
  1051. raise qubes.exc.QubesException(
  1052. 'more than 1 implementation of {!r} found: {}'.format(
  1053. clsname,
  1054. ', '.join(
  1055. '{}.{}'.format(ep.module_name, '.'.join(ep.attrs))
  1056. for ep in epoints)))
  1057. return epoints[0].load()
  1058. def add_new_vm(self, cls, qid=None, **kwargs):
  1059. '''Add new Virtual Machine to colletion
  1060. '''
  1061. if qid is None:
  1062. qid = self.domains.get_new_unused_qid()
  1063. # handle default template; specifically allow template=None (do not
  1064. # override it with default template)
  1065. if 'template' not in kwargs and hasattr(cls, 'template'):
  1066. kwargs['template'] = self.default_template
  1067. return self.domains.add(cls(self, None, qid=qid, **kwargs))
  1068. def get_label(self, label):
  1069. '''Get label as identified by index or name
  1070. :throws KeyError: when label is not found
  1071. '''
  1072. # first search for index, verbatim
  1073. try:
  1074. return self.labels[label]
  1075. except KeyError:
  1076. pass
  1077. # then search for name
  1078. for i in self.labels.values():
  1079. if i.name == label:
  1080. return i
  1081. # last call, if label is a number represented as str, search in indices
  1082. try:
  1083. return self.labels[int(label)]
  1084. except (KeyError, ValueError):
  1085. pass
  1086. raise KeyError(label)
  1087. @qubes.events.handler('domain-pre-deleted')
  1088. def on_domain_pre_deleted(self, event, vm):
  1089. # pylint: disable=unused-argument
  1090. if isinstance(vm, qubes.vm.templatevm.TemplateVM):
  1091. appvms = self.domains.get_vms_based_on(vm)
  1092. if appvms:
  1093. raise qubes.exc.QubesException(
  1094. 'Cannot remove template that has dependent AppVMs. '
  1095. 'Affected are: {}'.format(', '.join(
  1096. vm.name for name in sorted(appvms))))
  1097. @qubes.events.handler('domain-deleted')
  1098. def on_domain_deleted(self, event, vm):
  1099. # pylint: disable=unused-argument
  1100. for propname in (
  1101. 'default_netvm',
  1102. 'default_fw_netvm',
  1103. 'clockvm',
  1104. 'updatevm',
  1105. 'default_template',
  1106. ):
  1107. try:
  1108. if getattr(self, propname) == vm:
  1109. delattr(self, propname)
  1110. except AttributeError:
  1111. pass
  1112. @qubes.events.handler('property-pre-set:clockvm')
  1113. def on_property_pre_set_clockvm(self, event, name, newvalue, oldvalue=None):
  1114. # pylint: disable=unused-argument,no-self-use
  1115. if newvalue is None:
  1116. return
  1117. if newvalue.features.get('services/ntpd', False):
  1118. raise qubes.exc.QubesVMError(newvalue,
  1119. 'Cannot set {!r} as {!r} since it has ntpd enabled.'.format(
  1120. newvalue.name, name))
  1121. else:
  1122. newvalue.features['services/ntpd'] = ''
  1123. @qubes.events.handler(
  1124. 'property-pre-set:default_netvm',
  1125. 'property-pre-set:default_fw_netvm')
  1126. def on_property_pre_set_default_netvm(self, event, name, newvalue,
  1127. oldvalue=None):
  1128. # pylint: disable=unused-argument,invalid-name
  1129. if newvalue is not None and oldvalue is not None \
  1130. and oldvalue.is_running() and not newvalue.is_running() \
  1131. and self.domains.get_vms_connected_to(oldvalue):
  1132. raise qubes.exc.QubesVMNotRunningError(newvalue,
  1133. 'Cannot change {!r} to domain that '
  1134. 'is not running ({!r}).'.format(name, newvalue.name))
  1135. @qubes.events.handler('property-set:default_fw_netvm')
  1136. def on_property_set_default_fw_netvm(self, event, name, newvalue,
  1137. oldvalue=None):
  1138. # pylint: disable=unused-argument,invalid-name
  1139. for vm in self.domains:
  1140. if not vm.provides_network and vm.property_is_default('netvm'):
  1141. # fire property-del:netvm as it is responsible for resetting
  1142. # netvm to it's default value
  1143. vm.fire_event('property-del:netvm', 'netvm', newvalue, oldvalue)
  1144. @qubes.events.handler('property-set:default_netvm')
  1145. def on_property_set_default_netvm(self, event, name, newvalue,
  1146. oldvalue=None):
  1147. # pylint: disable=unused-argument
  1148. for vm in self.domains:
  1149. if vm.provides_network and vm.property_is_default('netvm'):
  1150. # fire property-del:netvm as it is responsible for resetting
  1151. # netvm to it's default value
  1152. vm.fire_event('property-del:netvm', 'netvm', newvalue, oldvalue)