__init__.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  1. #
  2. # The Qubes OS Project, https://www.qubes-os.org/
  3. #
  4. # Copyright (C) 2010-2015 Joanna Rutkowska <joanna@invisiblethingslab.com>
  5. # Copyright (C) 2011-2015 Marek Marczykowski-Górecki
  6. # <marmarek@invisiblethingslab.com>
  7. # Copyright (C) 2014-2015 Wojtek Porczyk <woju@invisiblethingslab.com>
  8. #
  9. # This program is free software; you can redistribute it and/or modify
  10. # it under the terms of the GNU General Public License as published by
  11. # the Free Software Foundation; either version 2 of the License, or
  12. # (at your option) any later version.
  13. #
  14. # This program is distributed in the hope that it will be useful,
  15. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. # GNU General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU General Public License along
  20. # with this program; if not, write to the Free Software Foundation, Inc.,
  21. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  22. #
  23. '''
  24. Qubes OS
  25. :copyright: © 2010-2015 Invisible Things Lab
  26. '''
  27. import builtins
  28. import collections
  29. import os
  30. import os.path
  31. import lxml.etree
  32. import qubes.config
  33. import qubes.events
  34. import qubes.exc
  35. __author__ = 'Invisible Things Lab'
  36. __license__ = 'GPLv2 or later'
  37. __version__ = 'R3'
  38. class Label(object):
  39. '''Label definition for virtual machines
  40. Label specifies colour of the padlock displayed next to VM's name.
  41. When this is a :py:class:`qubes.vm.dispvm.DispVM`, padlock is overlayed
  42. with recycling pictogram.
  43. :param int index: numeric identificator of label
  44. :param str color: colour specification as in HTML (``#abcdef``)
  45. :param str name: label's name like "red" or "green"
  46. '''
  47. def __init__(self, index, color, name):
  48. #: numeric identificator of label
  49. self.index = index
  50. #: colour specification as in HTML (``#abcdef``)
  51. self.color = color
  52. #: label's name like "red" or "green"
  53. self.name = name
  54. #: freedesktop icon name, suitable for use in
  55. #: :py:meth:`PyQt4.QtGui.QIcon.fromTheme`
  56. self.icon = 'appvm-' + name
  57. #: freedesktop icon name, suitable for use in
  58. #: :py:meth:`PyQt4.QtGui.QIcon.fromTheme` on DispVMs
  59. self.icon_dispvm = 'dispvm-' + name
  60. @classmethod
  61. def fromxml(cls, xml):
  62. '''Create label definition from XML node
  63. :param lxml.etree._Element xml: XML node reference
  64. :rtype: :py:class:`qubes.Label`
  65. '''
  66. index = int(xml.get('id').split('-', 1)[1])
  67. color = xml.get('color')
  68. name = xml.text
  69. return cls(index, color, name)
  70. def __xml__(self):
  71. element = lxml.etree.Element(
  72. 'label', id='label-{}'.format(self.index), color=self.color)
  73. element.text = self.name
  74. return element
  75. def __str__(self):
  76. return self.name
  77. def __repr__(self):
  78. return '{}({!r}, {!r}, {!r})'.format(
  79. self.__class__.__name__,
  80. self.index,
  81. self.color,
  82. self.name)
  83. @builtins.property
  84. def icon_path(self):
  85. '''Icon path
  86. .. deprecated:: 2.0
  87. use :py:meth:`PyQt4.QtGui.QIcon.fromTheme` and :py:attr:`icon`
  88. '''
  89. return os.path.join(qubes.config.system_path['qubes_icon_dir'],
  90. self.icon) + ".png"
  91. @builtins.property
  92. def icon_path_dispvm(self):
  93. '''Icon path
  94. .. deprecated:: 2.0
  95. use :py:meth:`PyQt4.QtGui.QIcon.fromTheme` and :py:attr:`icon_dispvm`
  96. '''
  97. return os.path.join(qubes.config.system_path['qubes_icon_dir'],
  98. self.icon_dispvm) + ".png"
  99. class property(object): # pylint: disable=redefined-builtin,invalid-name
  100. '''Qubes property.
  101. This class holds one property that can be saved to and loaded from
  102. :file:`qubes.xml`. It is used for both global and per-VM properties.
  103. Property can be unset by ordinary ``del`` statement or assigning
  104. :py:attr:`DEFAULT` special value to it. After deletion (or before first
  105. assignment/load) attempting to read a property will get its default value
  106. or, when no default, py:class:`exceptions.AttributeError`.
  107. :param str name: name of the property
  108. :param collections.Callable setter: if not :py:obj:`None`, this is used to \
  109. initialise value; first parameter to the function is holder instance \
  110. and the second is value; this is called before ``type``
  111. :param collections.Callable saver: function to coerce value to something \
  112. readable by setter
  113. :param type type: if not :py:obj:`None`, value is coerced to this type
  114. :param object default: default value; if callable, will be called with \
  115. holder as first argument
  116. :param int load_stage: stage when property should be loaded (see \
  117. :py:class:`Qubes` for description of stages)
  118. :param int order: order of evaluation (bigger order values are later)
  119. :param bool clone: :py:meth:`PropertyHolder.clone_properties` will not \
  120. include this property by default if :py:obj:`False`
  121. :param str ls_head: column head for :program:`qvm-ls`
  122. :param int ls_width: column width in :program:`qvm-ls`
  123. :param str doc: docstring; this should be one paragraph of plain RST, no \
  124. sphinx-specific features
  125. Setters and savers have following signatures:
  126. .. :py:function:: setter(self, prop, value)
  127. :noindex:
  128. :param self: instance of object that is holding property
  129. :param prop: property object
  130. :param value: value being assigned
  131. .. :py:function:: saver(self, prop, value)
  132. :noindex:
  133. :param self: instance of object that is holding property
  134. :param prop: property object
  135. :param value: value being saved
  136. :rtype: str
  137. :raises property.DontSave: when property should not be saved at all
  138. '''
  139. #: Assigning this value to property means setting it to its default value.
  140. #: If property has no default value, this will unset it.
  141. DEFAULT = object()
  142. # internal use only
  143. _NO_DEFAULT = object()
  144. def __init__(self, name, setter=None, saver=None, type=None,
  145. default=_NO_DEFAULT, write_once=False, load_stage=2, order=0,
  146. save_via_ref=False, clone=True,
  147. ls_head=None, ls_width=None, doc=None):
  148. # pylint: disable=redefined-builtin
  149. self.__name__ = name
  150. self._setter = setter
  151. self._saver = saver if saver is not None else (
  152. lambda self, prop, value: str(value))
  153. self._type = type
  154. self._default = default
  155. self._write_once = write_once
  156. self.order = order
  157. self.load_stage = load_stage
  158. self.save_via_ref = save_via_ref
  159. self.clone = clone
  160. self.__doc__ = doc
  161. self._attr_name = '_qubesprop_' + name
  162. if ls_head is not None or ls_width is not None:
  163. self.ls_head = ls_head or self.__name__.replace('_', '-').upper()
  164. self.ls_width = max(ls_width or 0, len(self.ls_head) + 1)
  165. def __get__(self, instance, owner):
  166. if instance is None:
  167. return self
  168. # XXX this violates duck typing, shall we keep it?
  169. if not isinstance(instance, PropertyHolder):
  170. raise AttributeError('qubes.property should be used on '
  171. 'qubes.PropertyHolder instances only')
  172. try:
  173. return getattr(instance, self._attr_name)
  174. except AttributeError:
  175. if self._default is self._NO_DEFAULT:
  176. raise AttributeError(
  177. 'property {!r} not set'.format(self.__name__))
  178. elif isinstance(self._default, collections.Callable):
  179. return self._default(instance)
  180. else:
  181. return self._default
  182. def __set__(self, instance, value):
  183. self._enforce_write_once(instance)
  184. if value is self.__class__.DEFAULT:
  185. self.__delete__(instance)
  186. return
  187. try:
  188. oldvalue = getattr(instance, self.__name__)
  189. has_oldvalue = True
  190. except AttributeError:
  191. has_oldvalue = False
  192. if self._setter is not None:
  193. value = self._setter(instance, self, value)
  194. if self._type not in (None, type(value)):
  195. value = self._type(value)
  196. if has_oldvalue:
  197. instance.fire_event_pre('property-pre-set:' + self.__name__,
  198. self.__name__, value, oldvalue)
  199. else:
  200. instance.fire_event_pre('property-pre-set:' + self.__name__,
  201. self.__name__, value)
  202. instance._property_init(self, value) # pylint: disable=protected-access
  203. if has_oldvalue:
  204. instance.fire_event('property-set:' + self.__name__, self.__name__,
  205. value, oldvalue)
  206. else:
  207. instance.fire_event('property-set:' + self.__name__, self.__name__,
  208. value)
  209. def __delete__(self, instance):
  210. self._enforce_write_once(instance)
  211. try:
  212. oldvalue = getattr(instance, self._attr_name)
  213. has_oldvalue = True
  214. except AttributeError:
  215. has_oldvalue = False
  216. if has_oldvalue:
  217. instance.fire_event_pre('property-pre-del:' + self.__name__,
  218. self.__name__, oldvalue)
  219. delattr(instance, self._attr_name)
  220. instance.fire_event('property-del:' + self.__name__,
  221. self.__name__, oldvalue)
  222. else:
  223. instance.fire_event_pre('property-pre-del:' + self.__name__,
  224. self.__name__)
  225. instance.fire_event('property-del:' + self.__name__,
  226. self.__name__)
  227. def __repr__(self):
  228. default = ' default={!r}'.format(self._default) \
  229. if self._default is not self._NO_DEFAULT \
  230. else ''
  231. return '<{} object at {:#x} name={!r}{}>'.format(
  232. self.__class__.__name__, id(self), self.__name__, default) \
  233. def __hash__(self):
  234. return hash(self.__name__)
  235. def __eq__(self, other):
  236. return isinstance(other, property) and self.__name__ == other.__name__
  237. def _enforce_write_once(self, instance):
  238. if self._write_once and not instance.property_is_default(self):
  239. raise AttributeError(
  240. 'property {!r} is write-once and already set'.format(
  241. self.__name__))
  242. #
  243. # exceptions
  244. #
  245. class DontSave(Exception):
  246. '''This exception may be raised from saver to sign that property should
  247. not be saved.
  248. '''
  249. pass
  250. @staticmethod
  251. def dontsave(self, prop, value):
  252. '''Dummy saver that never saves anything.'''
  253. # pylint: disable=bad-staticmethod-argument,unused-argument
  254. raise property.DontSave()
  255. #
  256. # some setters provided
  257. #
  258. @staticmethod
  259. def forbidden(self, prop, value):
  260. '''Property setter that forbids loading a property.
  261. This is used to effectively disable property in classes which inherit
  262. unwanted property. When someone attempts to load such a property, it
  263. :throws AttributeError: always
  264. ''' # pylint: disable=bad-staticmethod-argument,unused-argument
  265. raise AttributeError(
  266. 'setting {} property on {} instance is forbidden'.format(
  267. prop.__name__, self.__class__.__name__))
  268. @staticmethod
  269. def bool(self, prop, value):
  270. '''Property setter for boolean properties.
  271. It accepts (case-insensitive) ``'0'``, ``'no'`` and ``false`` as
  272. :py:obj:`False` and ``'1'``, ``'yes'`` and ``'true'`` as
  273. :py:obj:`True`.
  274. ''' # pylint: disable=bad-staticmethod-argument,unused-argument
  275. if isinstance(value, str):
  276. lcvalue = value.lower()
  277. if lcvalue in ('0', 'no', 'false', 'off'):
  278. return False
  279. if lcvalue in ('1', 'yes', 'true', 'on'):
  280. return True
  281. raise ValueError(
  282. 'Invalid literal for boolean property: {!r}'.format(value))
  283. return bool(value)
  284. class PropertyHolder(qubes.events.Emitter):
  285. '''Abstract class for holding :py:class:`qubes.property`
  286. Events fired by instances of this class:
  287. .. event:: property-load (subject, event)
  288. Fired once after all properties are loaded from XML. Individual
  289. ``property-set`` events are not fired.
  290. .. event:: property-set:<propname> \
  291. (subject, event, name, newvalue[, oldvalue])
  292. Fired when property changes state. Signature is variable,
  293. *oldvalue* is present only if there was an old value.
  294. :param name: Property name
  295. :param newvalue: New value of the property
  296. :param oldvalue: Old value of the property
  297. .. event:: property-pre-set:<propname> \
  298. (subject, event, name, newvalue[, oldvalue])
  299. Fired before property changes state. Signature is variable,
  300. *oldvalue* is present only if there was an old value.
  301. :param name: Property name
  302. :param newvalue: New value of the property
  303. :param oldvalue: Old value of the property
  304. .. event:: property-del:<propname> \
  305. (subject, event, name[, oldvalue])
  306. Fired when property gets deleted (is set to default). Signature is
  307. variable, *oldvalue* is present only if there was an old value.
  308. :param name: Property name
  309. :param oldvalue: Old value of the property
  310. .. event:: property-pre-del:<propname> \
  311. (subject, event, name[, oldvalue])
  312. Fired before property gets deleted (is set to default). Signature
  313. is variable, *oldvalue* is present only if there was an old value.
  314. :param name: Property name
  315. :param oldvalue: Old value of the property
  316. .. event:: clone-properties (subject, event, src, proplist)
  317. :param src: object, from which we are cloning
  318. :param proplist: list of properties
  319. Members:
  320. '''
  321. def __init__(self, xml, **kwargs):
  322. self.xml = xml
  323. propvalues = {}
  324. all_names = set(prop.__name__ for prop in self.property_list())
  325. for key in list(kwargs):
  326. if not key in all_names:
  327. continue
  328. propvalues[key] = kwargs.pop(key)
  329. super(PropertyHolder, self).__init__(**kwargs)
  330. for key, value in propvalues.items():
  331. setattr(self, key, value)
  332. if self.xml is not None:
  333. # check if properties are appropriate
  334. all_names = set(prop.__name__ for prop in self.property_list())
  335. for node in self.xml.xpath('./properties/property'):
  336. name = node.get('name')
  337. if name not in all_names:
  338. raise TypeError(
  339. 'property {!r} not applicable to {!r}'.format(
  340. name, self.__class__.__name__))
  341. @classmethod
  342. def property_list(cls, load_stage=None):
  343. '''List all properties attached to this VM's class
  344. :param load_stage: Filter by load stage
  345. :type load_stage: :py:func:`int` or :py:obj:`None`
  346. '''
  347. props = set()
  348. for class_ in cls.__mro__:
  349. props.update(prop for prop in class_.__dict__.values()
  350. if isinstance(prop, property))
  351. if load_stage is not None:
  352. props = set(prop for prop in props
  353. if prop.load_stage == load_stage)
  354. return sorted(props,
  355. key=lambda prop: (prop.load_stage, prop.order, prop.__name__))
  356. def _property_init(self, prop, value):
  357. '''Initialise property to a given value, without side effects.
  358. :param qubes.property prop: property object of particular interest
  359. :param value: value
  360. '''
  361. # pylint: disable=protected-access
  362. setattr(self, self.property_get_def(prop)._attr_name, value)
  363. def property_is_default(self, prop):
  364. '''Check whether property is in it's default value.
  365. Properties when unset may return some default value, so
  366. ``hasattr(vm, prop.__name__)`` is wrong in some circumstances. This
  367. method allows for checking if the value returned is in fact it's
  368. default value.
  369. :param qubes.property prop: property object of particular interest
  370. :rtype: bool
  371. ''' # pylint: disable=protected-access
  372. # both property_get_def() and ._attr_name may throw AttributeError,
  373. # which we don't want to catch
  374. attrname = self.property_get_def(prop)._attr_name
  375. return not hasattr(self, attrname)
  376. @classmethod
  377. def property_get_def(cls, prop):
  378. '''Return property definition object.
  379. If prop is already :py:class:`qubes.property` instance, return the same
  380. object.
  381. :param prop: property object or name
  382. :type prop: qubes.property or str
  383. :rtype: qubes.property
  384. '''
  385. if isinstance(prop, qubes.property):
  386. return prop
  387. for p in cls.property_list():
  388. if p.__name__ == prop:
  389. return p
  390. raise AttributeError('No property {!r} found in {!r}'.format(
  391. prop, cls))
  392. def load_properties(self, load_stage=None):
  393. '''Load properties from immediate children of XML node.
  394. ``property-set`` events are not fired for each individual property.
  395. :param int load_stage: Stage of loading.
  396. '''
  397. if self.xml is None:
  398. return
  399. all_names = set(
  400. prop.__name__ for prop in self.property_list(load_stage))
  401. for node in self.xml.xpath('./properties/property'):
  402. name = node.get('name')
  403. value = node.get('ref') or node.text
  404. if not name in all_names:
  405. continue
  406. setattr(self, name, value)
  407. def xml_properties(self, with_defaults=False):
  408. '''Iterator that yields XML nodes representing set properties.
  409. :param bool with_defaults: If :py:obj:`True`, then it also includes \
  410. properties which were not set explicite, but have default values \
  411. filled.
  412. '''
  413. properties = lxml.etree.Element('properties')
  414. for prop in self.property_list():
  415. # pylint: disable=protected-access
  416. try:
  417. value = getattr(
  418. self, (prop.__name__ if with_defaults else prop._attr_name))
  419. except AttributeError:
  420. continue
  421. try:
  422. value = prop._saver(self, prop, value)
  423. except property.DontSave:
  424. continue
  425. element = lxml.etree.Element('property', name=prop.__name__)
  426. if prop.save_via_ref:
  427. element.set('ref', value)
  428. else:
  429. element.text = value
  430. properties.append(element)
  431. return properties
  432. # this was clone_attrs
  433. def clone_properties(self, src, proplist=None):
  434. '''Clone properties from other object.
  435. :param PropertyHolder src: source object
  436. :param list proplist: list of properties \
  437. (:py:obj:`None` or omit for all properties except those with \
  438. :py:attr:`property.clone` set to :py:obj:`False`)
  439. '''
  440. if proplist is None:
  441. proplist = [prop for prop in self.property_list()
  442. if prop.clone]
  443. else:
  444. proplist = [prop for prop in self.property_list()
  445. if prop.__name__ in proplist or prop in proplist]
  446. for prop in proplist:
  447. try:
  448. # pylint: disable=protected-access
  449. self._property_init(prop, getattr(src, prop._attr_name))
  450. except AttributeError:
  451. continue
  452. self.fire_event('clone-properties', src, proplist)
  453. def property_require(self, prop, allow_none=False, hard=False):
  454. '''Complain badly when property is not set.
  455. :param prop: property name or object
  456. :type prop: qubes.property or str
  457. :param bool allow_none: if :py:obj:`True`, don't complain if \
  458. :py:obj:`None` is found
  459. :param bool hard: if :py:obj:`True`, raise :py:class:`AssertionError`; \
  460. if :py:obj:`False`, log warning instead
  461. '''
  462. if isinstance(prop, qubes.property):
  463. prop = prop.__name__
  464. try:
  465. value = getattr(self, prop)
  466. if value is None and not allow_none:
  467. raise AttributeError()
  468. except AttributeError:
  469. # pylint: disable=no-member
  470. msg = 'Required property {!r} not set on {!r}'.format(prop, self)
  471. if hard:
  472. raise AssertionError(msg)
  473. else:
  474. # pylint: disable=no-member
  475. self.log.fatal(msg)
  476. # pylint: disable=wrong-import-position
  477. from qubes.vm import VMProperty
  478. from qubes.app import Qubes
  479. __all__ = [
  480. 'Label',
  481. 'PropertyHolder',
  482. 'Qubes',
  483. 'VMProperty',
  484. 'property',
  485. ]