__init__.py 49 KB

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