__init__.py 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552
  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. delattr(instance, self._attr_name)
  530. instance.fire_event('property-del:' + self.__name__,
  531. self.__name__, oldvalue)
  532. else:
  533. instance.fire_event_pre('property-pre-del:' + self.__name__,
  534. self.__name__)
  535. instance.fire_event('property-del:' + self.__name__,
  536. self.__name__)
  537. def __repr__(self):
  538. default = ' default={!r}'.format(self._default) \
  539. if self._default is not self._NO_DEFAULT \
  540. else ''
  541. return '<{} object at {:#x} name={!r}{}>'.format(
  542. self.__class__.__name__, id(self), self.__name__, default) \
  543. def __hash__(self):
  544. return hash(self.__name__)
  545. def __eq__(self, other):
  546. return isinstance(other, property) and self.__name__ == other.__name__
  547. def _enforce_write_once(self, instance):
  548. if self._write_once and not instance.property_is_default(self):
  549. raise AttributeError(
  550. 'property {!r} is write-once and already set'.format(
  551. self.__name__))
  552. #
  553. # exceptions
  554. #
  555. class DontSave(Exception):
  556. '''This exception may be raised from saver to sign that property should
  557. not be saved.
  558. '''
  559. pass
  560. @staticmethod
  561. def dontsave(self, prop, value):
  562. '''Dummy saver that never saves anything.'''
  563. # pylint: disable=bad-staticmethod-argument,unused-argument
  564. raise property.DontSave()
  565. #
  566. # some setters provided
  567. #
  568. @staticmethod
  569. def forbidden(self, prop, value):
  570. '''Property setter that forbids loading a property.
  571. This is used to effectively disable property in classes which inherit
  572. unwanted property. When someone attempts to load such a property, it
  573. :throws AttributeError: always
  574. ''' # pylint: disable=bad-staticmethod-argument,unused-argument
  575. raise AttributeError(
  576. 'setting {} property on {} instance is forbidden'.format(
  577. prop.__name__, self.__class__.__name__))
  578. @staticmethod
  579. def bool(self, prop, value):
  580. '''Property setter for boolean properties.
  581. It accepts (case-insensitive) ``'0'``, ``'no'`` and ``false`` as
  582. :py:obj:`False` and ``'1'``, ``'yes'`` and ``'true'`` as
  583. :py:obj:`True`.
  584. ''' # pylint: disable=bad-staticmethod-argument,unused-argument
  585. if isinstance(value, basestring):
  586. lcvalue = value.lower()
  587. if lcvalue in ('0', 'no', 'false', 'off'):
  588. return False
  589. if lcvalue in ('1', 'yes', 'true', 'on'):
  590. return True
  591. raise ValueError(
  592. 'Invalid literal for boolean property: {!r}'.format(value))
  593. return bool(value)
  594. class PropertyHolder(qubes.events.Emitter):
  595. '''Abstract class for holding :py:class:`qubes.property`
  596. Events fired by instances of this class:
  597. .. event:: property-load (subject, event)
  598. Fired once after all properties are loaded from XML. Individual
  599. ``property-set`` events are not fired.
  600. .. event:: property-set:<propname> \
  601. (subject, event, name, newvalue[, oldvalue])
  602. Fired when property changes state. Signature is variable,
  603. *oldvalue* is present only if there was an old value.
  604. :param name: Property name
  605. :param newvalue: New value of the property
  606. :param oldvalue: Old value of the property
  607. .. event:: property-pre-set:<propname> \
  608. (subject, event, name, newvalue[, oldvalue])
  609. Fired before property changes state. Signature is variable,
  610. *oldvalue* is present only if there was an old value.
  611. :param name: Property name
  612. :param newvalue: New value of the property
  613. :param oldvalue: Old value of the property
  614. .. event:: property-del:<propname> \
  615. (subject, event, name[, oldvalue])
  616. Fired when property gets deleted (is set to default). Signature is
  617. variable, *oldvalue* is present only if there was an old value.
  618. :param name: Property name
  619. :param oldvalue: Old value of the property
  620. .. event:: property-pre-del:<propname> \
  621. (subject, event, name[, oldvalue])
  622. Fired before property gets deleted (is set to default). Signature
  623. is variable, *oldvalue* is present only if there was an old value.
  624. :param name: Property name
  625. :param oldvalue: Old value of the property
  626. Members:
  627. '''
  628. def __init__(self, xml, **kwargs):
  629. self.xml = xml
  630. propvalues = {}
  631. all_names = set(prop.__name__ for prop in self.property_list())
  632. for key in list(kwargs.keys()):
  633. if not key in all_names:
  634. continue
  635. propvalues[key] = kwargs.pop(key)
  636. super(PropertyHolder, self).__init__(**kwargs)
  637. for key, value in propvalues.items():
  638. setattr(self, key, value)
  639. @classmethod
  640. def property_list(cls, load_stage=None):
  641. '''List all properties attached to this VM's class
  642. :param load_stage: Filter by load stage
  643. :type load_stage: :py:func:`int` or :py:obj:`None`
  644. '''
  645. props = set()
  646. for class_ in cls.__mro__:
  647. props.update(prop for prop in class_.__dict__.values()
  648. if isinstance(prop, property))
  649. if load_stage is not None:
  650. props = set(prop for prop in props
  651. if prop.load_stage == load_stage)
  652. return sorted(props,
  653. key=lambda prop: (prop.load_stage, prop.order, prop.__name__))
  654. def _property_init(self, prop, value):
  655. '''Initialise property to a given value, without side effects.
  656. :param qubes.property prop: property object of particular interest
  657. :param value: value
  658. '''
  659. # pylint: disable=protected-access
  660. setattr(self, self.property_get_def(prop)._attr_name, value)
  661. def property_is_default(self, prop):
  662. '''Check whether property is in it's default value.
  663. Properties when unset may return some default value, so
  664. ``hasattr(vm, prop.__name__)`` is wrong in some circumstances. This
  665. method allows for checking if the value returned is in fact it's
  666. default value.
  667. :param qubes.property prop: property object of particular interest
  668. :rtype: bool
  669. ''' # pylint: disable=protected-access
  670. # both property_get_def() and ._attr_name may throw AttributeError,
  671. # which we don't want to catch
  672. attrname = self.property_get_def(prop)._attr_name
  673. return not hasattr(self, attrname)
  674. @classmethod
  675. def property_get_def(cls, prop):
  676. '''Return property definition object.
  677. If prop is already :py:class:`qubes.property` instance, return the same
  678. object.
  679. :param prop: property object or name
  680. :type prop: qubes.property or str
  681. :rtype: qubes.property
  682. '''
  683. if isinstance(prop, qubes.property):
  684. return prop
  685. for p in cls.property_list():
  686. if p.__name__ == prop:
  687. return p
  688. raise AttributeError('No property {!r} found in {!r}'.format(
  689. prop, cls))
  690. def load_properties(self, load_stage=None):
  691. '''Load properties from immediate children of XML node.
  692. ``property-set`` events are not fired for each individual property.
  693. :param int load_stage: Stage of loading.
  694. '''
  695. if self.xml is None:
  696. return
  697. all_names = set(
  698. prop.__name__ for prop in self.property_list(load_stage))
  699. for node in self.xml.xpath('./properties/property'):
  700. name = node.get('name')
  701. value = node.get('ref') or node.text
  702. if not name in all_names:
  703. continue
  704. setattr(self, name, value)
  705. def xml_properties(self, with_defaults=False):
  706. '''Iterator that yields XML nodes representing set properties.
  707. :param bool with_defaults: If :py:obj:`True`, then it also includes \
  708. properties which were not set explicite, but have default values \
  709. filled.
  710. '''
  711. properties = lxml.etree.Element('properties')
  712. for prop in self.property_list():
  713. # pylint: disable=protected-access
  714. try:
  715. value = getattr(
  716. self, (prop.__name__ if with_defaults else prop._attr_name))
  717. except AttributeError:
  718. continue
  719. try:
  720. value = prop._saver(self, prop, value)
  721. except property.DontSave:
  722. continue
  723. element = lxml.etree.Element('property', name=prop.__name__)
  724. if prop.save_via_ref:
  725. element.set('ref', value)
  726. else:
  727. element.text = value
  728. properties.append(element)
  729. return properties
  730. # this was clone_attrs
  731. def clone_properties(self, src, proplist=None):
  732. '''Clone properties from other object.
  733. :param PropertyHolder src: source object
  734. :param list proplist: list of properties \
  735. (:py:obj:`None` or omit for all properties except those with \
  736. :py:attr:`property.clone` set to :py:obj:`False`)
  737. '''
  738. if proplist is None:
  739. proplist = [prop for prop in self.property_list()
  740. if prop.clone]
  741. else:
  742. proplist = [prop for prop in self.property_list()
  743. if prop.__name__ in proplist or prop in proplist]
  744. for prop in proplist:
  745. try:
  746. # pylint: disable=protected-access
  747. self._property_init(prop, getattr(src, prop._attr_name))
  748. except AttributeError:
  749. continue
  750. self.fire_event('clone-properties', src, proplist)
  751. def property_require(self, prop, allow_none=False, hard=False):
  752. '''Complain badly when property is not set.
  753. :param prop: property name or object
  754. :type prop: qubes.property or str
  755. :param bool allow_none: if :py:obj:`True`, don't complain if \
  756. :py:obj:`None` is found
  757. :param bool hard: if :py:obj:`True`, raise :py:class:`AssertionError`; \
  758. if :py:obj:`False`, log warning instead
  759. '''
  760. if isinstance(prop, qubes.property):
  761. prop = prop.__name__
  762. try:
  763. value = getattr(self, prop)
  764. if value is None and not allow_none:
  765. raise AttributeError()
  766. except AttributeError:
  767. # pylint: disable=no-member
  768. msg = 'Required property {!r} not set on {!r}'.format(prop, self)
  769. if hard:
  770. raise AssertionError(msg)
  771. else:
  772. # pylint: disable=no-member
  773. self.log.fatal(msg)
  774. import qubes.vm
  775. class VMProperty(property):
  776. '''Property that is referring to a VM
  777. :param type vmclass: class that returned VM is supposed to be instance of
  778. and all supported by :py:class:`property` with the exception of ``type`` \
  779. and ``setter``
  780. '''
  781. _none_value = ''
  782. def __init__(self, name, vmclass=qubes.vm.BaseVM, allow_none=False,
  783. **kwargs):
  784. if 'type' in kwargs:
  785. raise TypeError(
  786. "'type' keyword parameter is unsupported in {}".format(
  787. self.__class__.__name__))
  788. if 'setter' in kwargs:
  789. raise TypeError(
  790. "'setter' keyword parameter is unsupported in {}".format(
  791. self.__class__.__name__))
  792. if not issubclass(vmclass, qubes.vm.BaseVM):
  793. raise TypeError(
  794. "'vmclass' should specify a subclass of qubes.vm.BaseVM")
  795. super(VMProperty, self).__init__(name,
  796. saver=(lambda self_, prop, value:
  797. self._none_value if value is None else value.name),
  798. **kwargs)
  799. self.vmclass = vmclass
  800. self.allow_none = allow_none
  801. def __set__(self, instance, value):
  802. if value is self.__class__.DEFAULT:
  803. self.__delete__(instance)
  804. return
  805. if value == self._none_value:
  806. value = None
  807. if value is None:
  808. if self.allow_none:
  809. super(VMProperty, self).__set__(instance, value)
  810. return
  811. else:
  812. raise ValueError(
  813. 'Property {!r} does not allow setting to {!r}'.format(
  814. self.__name__, value))
  815. app = instance if isinstance(instance, Qubes) else instance.app
  816. try:
  817. vm = app.domains[value]
  818. except KeyError:
  819. raise qubes.exc.QubesVMNotFoundError(value)
  820. if not isinstance(vm, self.vmclass):
  821. raise TypeError('wrong VM class: domains[{!r}] if of type {!s} '
  822. 'and not {!s}'.format(value,
  823. vm.__class__.__name__,
  824. self.vmclass.__name__))
  825. super(VMProperty, self).__set__(instance, vm)
  826. import qubes.vm.qubesvm
  827. import qubes.vm.templatevm
  828. import qubes.vm.adminvm
  829. class Qubes(PropertyHolder):
  830. '''Main Qubes application
  831. :param str store: path to ``qubes.xml``
  832. The store is loaded in stages:
  833. 1. In the first stage there are loaded some basic features from store
  834. (currently labels).
  835. 2. In the second stage stubs for all VMs are loaded. They are filled
  836. with their basic properties, like ``qid`` and ``name``.
  837. 3. In the third stage all global properties are loaded. They often
  838. reference VMs, like default netvm, so they should be filled after
  839. loading VMs.
  840. 4. In the fourth stage all remaining VM properties are loaded. They
  841. also need all VMs loaded, because they represent dependencies
  842. between VMs like aforementioned netvm.
  843. 5. In the fifth stage there are some fixups to ensure sane system
  844. operation.
  845. This class emits following events:
  846. .. event:: domain-add (subject, event, vm)
  847. When domain is added.
  848. :param subject: Event emitter
  849. :param event: Event name (``'domain-add'``)
  850. :param vm: Domain object
  851. .. event:: domain-delete (subject, event, vm)
  852. When domain is deleted. VM still has reference to ``app`` object,
  853. but is not contained within VMCollection.
  854. :param subject: Event emitter
  855. :param event: Event name (``'domain-delete'``)
  856. :param vm: Domain object
  857. Methods and attributes:
  858. '''
  859. default_netvm = VMProperty('default_netvm', load_stage=3,
  860. default=None, allow_none=True,
  861. doc='''Default NetVM for AppVMs. Initial state is `None`, which means
  862. that AppVMs are not connected to the Internet.''')
  863. default_fw_netvm = VMProperty('default_fw_netvm', load_stage=3,
  864. default=None, allow_none=True,
  865. doc='''Default NetVM for ProxyVMs. Initial state is `None`, which means
  866. that ProxyVMs (including FirewallVM) are not connected to the
  867. Internet.''')
  868. default_template = VMProperty('default_template', load_stage=3,
  869. vmclass=qubes.vm.templatevm.TemplateVM,
  870. doc='Default template for new AppVMs')
  871. updatevm = VMProperty('updatevm', load_stage=3,
  872. allow_none=True,
  873. doc='''Which VM to use as `yum` proxy for updating AdminVM and
  874. TemplateVMs''')
  875. clockvm = VMProperty('clockvm', load_stage=3,
  876. allow_none=True,
  877. doc='Which VM to use as NTP proxy for updating AdminVM')
  878. default_kernel = property('default_kernel', load_stage=3,
  879. doc='Which kernel to use when not overriden in VM')
  880. # TODO #1637 #892
  881. check_updates_vm = property('check_updates_vm',
  882. type=bool, setter=property.bool,
  883. default=True,
  884. doc='check for updates inside qubes')
  885. def __init__(self, store=None, load=True, **kwargs):
  886. #: logger instance for logging global messages
  887. self.log = logging.getLogger('app')
  888. self._extensions = qubes.ext.get_extensions()
  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. @__builtin__.property
  914. def store(self):
  915. return self._store
  916. def load(self):
  917. '''Open qubes.xml
  918. :throws EnvironmentError: failure on parsing store
  919. :throws xml.parsers.expat.ExpatError: failure on parsing store
  920. :raises lxml.etree.XMLSyntaxError: on syntax error in qubes.xml
  921. '''
  922. try:
  923. fd = os.open(self._store, os.O_RDWR) # no O_CREAT
  924. except OSError as e:
  925. if e.errno != errno.ENOENT:
  926. raise
  927. raise qubes.exc.QubesException(
  928. 'Qubes XML store {!r} is missing; use qubes-create tool'.format(
  929. self._store))
  930. fh = os.fdopen(fd, 'rb')
  931. if os.name == 'posix':
  932. fcntl.lockf(fh, fcntl.LOCK_EX)
  933. elif os.name == 'nt':
  934. # pylint: disable=protected-access
  935. win32file.LockFileEx(
  936. win32file._get_osfhandle(fh.fileno()),
  937. win32con.LOCKFILE_EXCLUSIVE_LOCK,
  938. 0, -0x10000,
  939. pywintypes.OVERLAPPED())
  940. self.xml = lxml.etree.parse(fh)
  941. # stage 1: load labels
  942. for node in self.xml.xpath('./labels/label'):
  943. label = Label.fromxml(node)
  944. self.labels[label.index] = label
  945. # stage 2: load VMs
  946. for node in self.xml.xpath('./domains/domain'):
  947. # pylint: disable=no-member
  948. cls = self.get_vm_class(node.get('class'))
  949. vm = cls(self, node)
  950. vm.load_properties(load_stage=2)
  951. vm.init_log()
  952. self.domains.add(vm)
  953. if not 0 in self.domains:
  954. self.domains.add(qubes.vm.adminvm.AdminVM(
  955. self, None, qid=0, name='dom0'))
  956. # stage 3: load global properties
  957. self.load_properties(load_stage=3)
  958. # stage 4: fill all remaining VM properties
  959. for vm in self.domains:
  960. vm.load_properties(load_stage=4)
  961. # stage 5: misc fixups
  962. self.property_require('default_fw_netvm', allow_none=True)
  963. self.property_require('default_netvm', allow_none=True)
  964. self.property_require('default_template')
  965. self.property_require('clockvm', allow_none=True)
  966. self.property_require('updatevm', allow_none=True)
  967. # Disable ntpd in ClockVM - to not conflict with ntpdate (both are
  968. # using 123/udp port)
  969. if hasattr(self, 'clockvm') and self.clockvm is not None:
  970. if self.clockvm.features.get('services/ntpd', False):
  971. self.log.warning("VM set as clockvm ({!r}) has enabled 'ntpd' "
  972. "service! Expect failure when syncing time in dom0.".format(
  973. self.clockvm))
  974. else:
  975. self.clockvm.features['services/ntpd'] = ''
  976. for vm in self.domains:
  977. vm.events_enabled = True
  978. vm.fire_event('domain-load')
  979. # get a file timestamp (before closing it - still holding the lock!),
  980. # to detect whether anyone else have modified it in the meantime
  981. self.__load_timestamp = os.path.getmtime(self._store)
  982. # intentionally do not call explicit unlock
  983. fh.close()
  984. del fh
  985. def __xml__(self):
  986. element = lxml.etree.Element('qubes')
  987. element.append(self.xml_labels())
  988. element.append(self.xml_properties())
  989. domains = lxml.etree.Element('domains')
  990. for vm in self.domains:
  991. domains.append(vm.__xml__())
  992. element.append(domains)
  993. return element
  994. def save(self):
  995. '''Save all data to qubes.xml
  996. There are several problems with saving :file:`qubes.xml` which must be
  997. mitigated:
  998. - Running out of disk space. No space left should not result in empty
  999. file. This is done by writing to temporary file and then renaming.
  1000. - Attempts to write two or more files concurrently. This is done by
  1001. sophisticated locking.
  1002. :throws EnvironmentError: failure on saving
  1003. '''
  1004. while True:
  1005. fd_old = os.open(self._store, os.O_RDWR | os.O_CREAT)
  1006. if os.name == 'posix':
  1007. fcntl.lockf(fd_old, fcntl.LOCK_EX)
  1008. elif os.name == 'nt':
  1009. # pylint: disable=protected-access
  1010. overlapped = pywintypes.OVERLAPPED()
  1011. win32file.LockFileEx(
  1012. win32file._get_osfhandle(fd_old),
  1013. win32con.LOCKFILE_EXCLUSIVE_LOCK, 0, -0x10000, overlapped)
  1014. # While we were waiting for lock, someone could have unlink()ed (or
  1015. # rename()d) our file out of the filesystem. We have to ensure we
  1016. # got lock on something linked to filesystem. If not, try again.
  1017. if os.fstat(fd_old) == os.stat(self._store):
  1018. break
  1019. else:
  1020. os.close(fd_old)
  1021. if self.__load_timestamp:
  1022. current_file_timestamp = os.path.getmtime(self._store)
  1023. if current_file_timestamp != self.__load_timestamp:
  1024. os.close(fd_old)
  1025. raise qubes.exc.QubesException(
  1026. "Someone else modified qubes.xml in the meantime")
  1027. fh_new = tempfile.NamedTemporaryFile(prefix=self._store, delete=False)
  1028. lxml.etree.ElementTree(self.__xml__()).write(
  1029. fh_new, encoding='utf-8', pretty_print=True)
  1030. fh_new.flush()
  1031. os.chmod(fh_new.name, 0660)
  1032. os.chown(fh_new.name, -1, grp.getgrnam('qubes').gr_gid)
  1033. os.rename(fh_new.name, self._store)
  1034. # intentionally do not call explicit unlock to not unlock the file
  1035. # before all buffers are flushed
  1036. fh_new.close()
  1037. # update stored mtime, in case of multiple save() calls without
  1038. # loading qubes.xml again
  1039. self.__load_timestamp = os.path.getmtime(self._store)
  1040. os.close(fd_old)
  1041. @classmethod
  1042. def create_empty_store(cls, *args, **kwargs):
  1043. self = cls(*args, load=False, **kwargs)
  1044. self.labels = {
  1045. 1: Label(1, '0xcc0000', 'red'),
  1046. 2: Label(2, '0xf57900', 'orange'),
  1047. 3: Label(3, '0xedd400', 'yellow'),
  1048. 4: Label(4, '0x73d216', 'green'),
  1049. 5: Label(5, '0x555753', 'gray'),
  1050. 6: Label(6, '0x3465a4', 'blue'),
  1051. 7: Label(7, '0x75507b', 'purple'),
  1052. 8: Label(8, '0x000000', 'black'),
  1053. }
  1054. self.domains.add(
  1055. qubes.vm.adminvm.AdminVM(self, None, qid=0, name='dom0'))
  1056. self.save()
  1057. return self
  1058. def xml_labels(self):
  1059. '''Serialise labels
  1060. :rtype: lxml.etree._Element
  1061. '''
  1062. labels = lxml.etree.Element('labels')
  1063. for label in sorted(self.labels.values(), key=lambda labl: labl.index):
  1064. labels.append(label.__xml__())
  1065. return labels
  1066. def get_vm_class(self, clsname):
  1067. '''Find the class for a domain.
  1068. Classess are registered as setuptools' entry points in ``qubes.vm``
  1069. group. Any package may supply their own classess.
  1070. :param str clsname: name of the class
  1071. :return type: class
  1072. '''
  1073. try:
  1074. return get_entry_point_one('qubes.vm', clsname)
  1075. except KeyError:
  1076. raise qubes.exc.QubesException(
  1077. 'no such VM class: {!r}'.format(clsname))
  1078. # don't catch TypeError
  1079. def add_new_vm(self, cls, qid=None, **kwargs):
  1080. '''Add new Virtual Machine to colletion
  1081. '''
  1082. if qid is None:
  1083. qid = self.domains.get_new_unused_qid()
  1084. # handle default template; specifically allow template=None (do not
  1085. # override it with default template)
  1086. if 'template' not in kwargs and hasattr(cls, 'template'):
  1087. kwargs['template'] = self.default_template
  1088. return self.domains.add(cls(self, None, qid=qid, **kwargs))
  1089. def get_label(self, label):
  1090. '''Get label as identified by index or name
  1091. :throws KeyError: when label is not found
  1092. '''
  1093. # first search for index, verbatim
  1094. try:
  1095. return self.labels[label]
  1096. except KeyError:
  1097. pass
  1098. # then search for name
  1099. for i in self.labels.values():
  1100. if i.name == label:
  1101. return i
  1102. # last call, if label is a number represented as str, search in indices
  1103. try:
  1104. return self.labels[int(label)]
  1105. except (KeyError, ValueError):
  1106. pass
  1107. raise KeyError(label)
  1108. @qubes.events.handler('domain-pre-delete')
  1109. def on_domain_pre_deleted(self, event, vm):
  1110. # pylint: disable=unused-argument
  1111. if isinstance(vm, qubes.vm.templatevm.TemplateVM):
  1112. appvms = self.domains.get_vms_based_on(vm)
  1113. if appvms:
  1114. raise qubes.exc.QubesException(
  1115. 'Cannot remove template that has dependent AppVMs. '
  1116. 'Affected are: {}'.format(', '.join(
  1117. vm.name for name in sorted(appvms))))
  1118. @qubes.events.handler('domain-delete')
  1119. def on_domain_deleted(self, event, vm):
  1120. # pylint: disable=unused-argument
  1121. for propname in (
  1122. 'default_netvm',
  1123. 'default_fw_netvm',
  1124. 'clockvm',
  1125. 'updatevm',
  1126. 'default_template',
  1127. ):
  1128. try:
  1129. if getattr(self, propname) == vm:
  1130. delattr(self, propname)
  1131. except AttributeError:
  1132. pass
  1133. @qubes.events.handler('property-pre-set:clockvm')
  1134. def on_property_pre_set_clockvm(self, event, name, newvalue, oldvalue=None):
  1135. # pylint: disable=unused-argument,no-self-use
  1136. if newvalue is None:
  1137. return
  1138. if newvalue.features.get('services/ntpd', False):
  1139. raise qubes.exc.QubesVMError(newvalue,
  1140. 'Cannot set {!r} as {!r} since it has ntpd enabled.'.format(
  1141. newvalue.name, name))
  1142. else:
  1143. newvalue.features['services/ntpd'] = ''
  1144. @qubes.events.handler(
  1145. 'property-pre-set:default_netvm',
  1146. 'property-pre-set:default_fw_netvm')
  1147. def on_property_pre_set_default_netvm(self, event, name, newvalue,
  1148. oldvalue=None):
  1149. # pylint: disable=unused-argument,invalid-name
  1150. if newvalue is not None and oldvalue is not None \
  1151. and oldvalue.is_running() and not newvalue.is_running() \
  1152. and self.domains.get_vms_connected_to(oldvalue):
  1153. raise qubes.exc.QubesVMNotRunningError(newvalue,
  1154. 'Cannot change {!r} to domain that '
  1155. 'is not running ({!r}).'.format(name, newvalue.name))
  1156. @qubes.events.handler('property-set:default_fw_netvm')
  1157. def on_property_set_default_fw_netvm(self, event, name, newvalue,
  1158. oldvalue=None):
  1159. # pylint: disable=unused-argument,invalid-name
  1160. for vm in self.domains:
  1161. if not vm.provides_network and vm.property_is_default('netvm'):
  1162. # fire property-del:netvm as it is responsible for resetting
  1163. # netvm to it's default value
  1164. vm.fire_event('property-del:netvm', 'netvm', newvalue, oldvalue)
  1165. @qubes.events.handler('property-set:default_netvm')
  1166. def on_property_set_default_netvm(self, event, name, newvalue,
  1167. oldvalue=None):
  1168. # pylint: disable=unused-argument
  1169. for vm in self.domains:
  1170. if vm.provides_network and vm.property_is_default('netvm'):
  1171. # fire property-del:netvm as it is responsible for resetting
  1172. # netvm to it's default value
  1173. vm.fire_event('property-del:netvm', 'netvm', newvalue, oldvalue)