__init__.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653
  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. def __eq__(self, other):
  84. if isinstance(other, Label):
  85. return self.name == other.name
  86. return NotImplemented
  87. @builtins.property
  88. def icon_path(self):
  89. '''Icon path
  90. .. deprecated:: 2.0
  91. use :py:meth:`PyQt4.QtGui.QIcon.fromTheme` and :py:attr:`icon`
  92. '''
  93. return os.path.join(qubes.config.system_path['qubes_icon_dir'],
  94. self.icon) + ".png"
  95. @builtins.property
  96. def icon_path_dispvm(self):
  97. '''Icon path
  98. .. deprecated:: 2.0
  99. use :py:meth:`PyQt4.QtGui.QIcon.fromTheme` and :py:attr:`icon_dispvm`
  100. '''
  101. return os.path.join(qubes.config.system_path['qubes_icon_dir'],
  102. self.icon_dispvm) + ".png"
  103. class property(object): # pylint: disable=redefined-builtin,invalid-name
  104. '''Qubes property.
  105. This class holds one property that can be saved to and loaded from
  106. :file:`qubes.xml`. It is used for both global and per-VM properties.
  107. Property can be unset by ordinary ``del`` statement or assigning
  108. :py:attr:`DEFAULT` special value to it. After deletion (or before first
  109. assignment/load) attempting to read a property will get its default value
  110. or, when no default, py:class:`exceptions.AttributeError`.
  111. :param str name: name of the property
  112. :param collections.Callable setter: if not :py:obj:`None`, this is used to \
  113. initialise value; first parameter to the function is holder instance \
  114. and the second is value; this is called before ``type``
  115. :param collections.Callable saver: function to coerce value to something \
  116. readable by setter
  117. :param type type: if not :py:obj:`None`, value is coerced to this type
  118. :param object default: default value; if callable, will be called with \
  119. holder as first argument
  120. :param int load_stage: stage when property should be loaded (see \
  121. :py:class:`Qubes` for description of stages)
  122. :param int order: order of evaluation (bigger order values are later)
  123. :param bool clone: :py:meth:`PropertyHolder.clone_properties` will not \
  124. include this property by default if :py:obj:`False`
  125. :param str ls_head: column head for :program:`qvm-ls`
  126. :param int ls_width: column width in :program:`qvm-ls`
  127. :param str doc: docstring; this should be one paragraph of plain RST, no \
  128. sphinx-specific features
  129. Setters and savers have following signatures:
  130. .. :py:function:: setter(self, prop, value)
  131. :noindex:
  132. :param self: instance of object that is holding property
  133. :param prop: property object
  134. :param value: value being assigned
  135. .. :py:function:: saver(self, prop, value)
  136. :noindex:
  137. :param self: instance of object that is holding property
  138. :param prop: property object
  139. :param value: value being saved
  140. :rtype: str
  141. :raises property.DontSave: when property should not be saved at all
  142. '''
  143. #: Assigning this value to property means setting it to its default value.
  144. #: If property has no default value, this will unset it.
  145. DEFAULT = object()
  146. # internal use only
  147. _NO_DEFAULT = object()
  148. def __init__(self, name, setter=None, saver=None, type=None,
  149. default=_NO_DEFAULT, write_once=False, load_stage=2, order=0,
  150. save_via_ref=False, clone=True,
  151. ls_head=None, ls_width=None, doc=None):
  152. # pylint: disable=redefined-builtin
  153. self.__name__ = name
  154. self._setter = setter
  155. self._saver = saver if saver is not None else (
  156. lambda self, prop, value: str(value))
  157. self.type = type
  158. self._default = default
  159. self._write_once = write_once
  160. self.order = order
  161. self.load_stage = load_stage
  162. self.save_via_ref = save_via_ref
  163. self.clone = clone
  164. self.__doc__ = doc
  165. self._attr_name = '_qubesprop_' + name
  166. if ls_head is not None or ls_width is not None:
  167. self.ls_head = ls_head or self.__name__.replace('_', '-').upper()
  168. self.ls_width = max(ls_width or 0, len(self.ls_head) + 1)
  169. def __get__(self, instance, owner):
  170. if instance is None:
  171. return self
  172. # XXX this violates duck typing, shall we keep it?
  173. if not isinstance(instance, PropertyHolder):
  174. raise AttributeError('qubes.property should be used on '
  175. 'qubes.PropertyHolder instances only')
  176. try:
  177. return getattr(instance, self._attr_name)
  178. except AttributeError:
  179. if self._default is self._NO_DEFAULT:
  180. raise AttributeError(
  181. 'property {!r} not set'.format(self.__name__))
  182. elif isinstance(self._default, collections.Callable):
  183. return self._default(instance)
  184. else:
  185. return self._default
  186. def __set__(self, instance, value):
  187. self._enforce_write_once(instance)
  188. if value is self.__class__.DEFAULT:
  189. self.__delete__(instance)
  190. return
  191. try:
  192. oldvalue = getattr(instance, self.__name__)
  193. has_oldvalue = True
  194. except AttributeError:
  195. has_oldvalue = False
  196. if self._setter is not None:
  197. value = self._setter(instance, self, value)
  198. if self.type not in (None, type(value)):
  199. value = self.type(value)
  200. if has_oldvalue:
  201. instance.fire_event_pre('property-pre-set:' + self.__name__,
  202. name=self.__name__, newvalue=value, oldvalue=oldvalue)
  203. else:
  204. instance.fire_event_pre('property-pre-set:' + self.__name__,
  205. name=self.__name__, newvalue=value)
  206. instance._property_init(self, value) # pylint: disable=protected-access
  207. if has_oldvalue:
  208. instance.fire_event('property-set:' + self.__name__,
  209. name=self.__name__, newvalue=value, oldvalue=oldvalue)
  210. else:
  211. instance.fire_event('property-set:' + self.__name__,
  212. name=self.__name__, newvalue=value)
  213. def __delete__(self, instance):
  214. self._enforce_write_once(instance)
  215. try:
  216. oldvalue = getattr(instance, self._attr_name)
  217. has_oldvalue = True
  218. except AttributeError:
  219. has_oldvalue = False
  220. if has_oldvalue:
  221. instance.fire_event_pre('property-pre-del:' + self.__name__,
  222. name=self.__name__, oldvalue=oldvalue)
  223. delattr(instance, self._attr_name)
  224. instance.fire_event('property-del:' + self.__name__,
  225. name=self.__name__, oldvalue=oldvalue)
  226. else:
  227. instance.fire_event_pre('property-pre-del:' + self.__name__,
  228. name=self.__name__)
  229. instance.fire_event('property-del:' + self.__name__,
  230. name=self.__name__)
  231. def __repr__(self):
  232. default = ' default={!r}'.format(self._default) \
  233. if self._default is not self._NO_DEFAULT \
  234. else ''
  235. return '<{} object at {:#x} name={!r}{}>'.format(
  236. self.__class__.__name__, id(self), self.__name__, default) \
  237. def __hash__(self):
  238. return hash(self.__name__)
  239. def __lt__(self, other):
  240. if isinstance(other, property):
  241. return (self.load_stage, self.order, self.__name__) <\
  242. (other.load_stage, other.order, other.__name__)
  243. return NotImplemented
  244. def __eq__(self, other):
  245. if isinstance(other, str):
  246. return self.__name__ == other
  247. return isinstance(other, property) and self.__name__ == other.__name__
  248. def _enforce_write_once(self, instance):
  249. if self._write_once and not instance.property_is_default(self):
  250. raise AttributeError(
  251. 'property {!r} is write-once and already set'.format(
  252. self.__name__))
  253. #
  254. # exceptions
  255. #
  256. class DontSave(Exception):
  257. '''This exception may be raised from saver to sign that property should
  258. not be saved.
  259. '''
  260. pass
  261. @staticmethod
  262. def dontsave(self, prop, value):
  263. '''Dummy saver that never saves anything.'''
  264. # pylint: disable=bad-staticmethod-argument,unused-argument
  265. raise property.DontSave()
  266. #
  267. # some setters provided
  268. #
  269. @staticmethod
  270. def forbidden(self, prop, value):
  271. '''Property setter that forbids loading a property.
  272. This is used to effectively disable property in classes which inherit
  273. unwanted property. When someone attempts to load such a property, it
  274. :throws AttributeError: always
  275. ''' # pylint: disable=bad-staticmethod-argument,unused-argument
  276. raise AttributeError(
  277. 'setting {} property on {} instance is forbidden'.format(
  278. prop.__name__, self.__class__.__name__))
  279. @staticmethod
  280. def bool(self, prop, value):
  281. '''Property setter for boolean properties.
  282. It accepts (case-insensitive) ``'0'``, ``'no'`` and ``false`` as
  283. :py:obj:`False` and ``'1'``, ``'yes'`` and ``'true'`` as
  284. :py:obj:`True`.
  285. ''' # pylint: disable=bad-staticmethod-argument,unused-argument
  286. if isinstance(value, str):
  287. lcvalue = value.lower()
  288. if lcvalue in ('0', 'no', 'false', 'off'):
  289. return False
  290. if lcvalue in ('1', 'yes', 'true', 'on'):
  291. return True
  292. raise qubes.exc.QubesValueError(
  293. 'Invalid literal for boolean property: {!r}'.format(value))
  294. return bool(value)
  295. class PropertyHolder(qubes.events.Emitter):
  296. '''Abstract class for holding :py:class:`qubes.property`
  297. Events fired by instances of this class:
  298. .. event:: property-load (subject, event)
  299. Fired once after all properties are loaded from XML. Individual
  300. ``property-set`` events are not fired.
  301. .. event:: property-set:<propname> \
  302. (subject, event, name, newvalue[, oldvalue])
  303. Fired when property changes state. Signature is variable,
  304. *oldvalue* is present only if there was an old value.
  305. :param name: Property name
  306. :param newvalue: New value of the property
  307. :param oldvalue: Old value of the property
  308. .. event:: property-pre-set:<propname> \
  309. (subject, event, name, newvalue[, oldvalue])
  310. Fired before property changes state. Signature is variable,
  311. *oldvalue* is present only if there was an old value.
  312. :param name: Property name
  313. :param newvalue: New value of the property
  314. :param oldvalue: Old value of the property
  315. .. event:: property-del:<propname> \
  316. (subject, event, name[, oldvalue])
  317. Fired when property gets deleted (is set to default). Signature is
  318. variable, *oldvalue* is present only if there was an old value.
  319. :param name: Property name
  320. :param oldvalue: Old value of the property
  321. .. event:: property-pre-del:<propname> \
  322. (subject, event, name[, oldvalue])
  323. Fired before property gets deleted (is set to default). Signature
  324. is variable, *oldvalue* is present only if there was an old value.
  325. :param name: Property name
  326. :param oldvalue: Old value of the property
  327. .. event:: clone-properties (subject, event, src, proplist)
  328. :param src: object, from which we are cloning
  329. :param proplist: list of properties
  330. Members:
  331. '''
  332. def __init__(self, xml, **kwargs):
  333. self.xml = xml
  334. propvalues = {}
  335. all_names = set(prop.__name__ for prop in self.property_list())
  336. for key in list(kwargs):
  337. if not key in all_names:
  338. continue
  339. propvalues[key] = kwargs.pop(key)
  340. super(PropertyHolder, self).__init__(**kwargs)
  341. for key, value in propvalues.items():
  342. setattr(self, key, value)
  343. if self.xml is not None:
  344. # check if properties are appropriate
  345. all_names = set(prop.__name__ for prop in self.property_list())
  346. for node in self.xml.xpath('./properties/property'):
  347. name = node.get('name')
  348. if name not in all_names:
  349. raise TypeError(
  350. 'property {!r} not applicable to {!r}'.format(
  351. name, self.__class__.__name__))
  352. @classmethod
  353. def property_list(cls, load_stage=None):
  354. '''List all properties attached to this VM's class
  355. :param load_stage: Filter by load stage
  356. :type load_stage: :py:func:`int` or :py:obj:`None`
  357. '''
  358. props = set()
  359. for class_ in cls.__mro__:
  360. props.update(prop for prop in class_.__dict__.values()
  361. if isinstance(prop, property))
  362. if load_stage is not None:
  363. props = set(prop for prop in props
  364. if prop.load_stage == load_stage)
  365. return sorted(props)
  366. def _property_init(self, prop, value):
  367. '''Initialise property to a given value, without side effects.
  368. :param qubes.property prop: property object of particular interest
  369. :param value: value
  370. '''
  371. # pylint: disable=protected-access
  372. setattr(self, self.property_get_def(prop)._attr_name, value)
  373. def property_is_default(self, prop):
  374. '''Check whether property is in it's default value.
  375. Properties when unset may return some default value, so
  376. ``hasattr(vm, prop.__name__)`` is wrong in some circumstances. This
  377. method allows for checking if the value returned is in fact it's
  378. default value.
  379. :param qubes.property prop: property object of particular interest
  380. :rtype: bool
  381. ''' # pylint: disable=protected-access
  382. # both property_get_def() and ._attr_name may throw AttributeError,
  383. # which we don't want to catch
  384. attrname = self.property_get_def(prop)._attr_name
  385. return not hasattr(self, attrname)
  386. @classmethod
  387. def property_get_def(cls, prop):
  388. '''Return property definition object.
  389. If prop is already :py:class:`qubes.property` instance, return the same
  390. object.
  391. :param prop: property object or name
  392. :type prop: qubes.property or str
  393. :rtype: qubes.property
  394. '''
  395. if isinstance(prop, qubes.property):
  396. return prop
  397. for p in cls.property_list():
  398. if p.__name__ == prop:
  399. return p
  400. raise AttributeError('No property {!r} found in {!r}'.format(
  401. prop, cls))
  402. def load_properties(self, load_stage=None):
  403. '''Load properties from immediate children of XML node.
  404. ``property-set`` events are not fired for each individual property.
  405. :param int load_stage: Stage of loading.
  406. '''
  407. if self.xml is None:
  408. return
  409. all_names = set(
  410. prop.__name__ for prop in self.property_list(load_stage))
  411. for node in self.xml.xpath('./properties/property'):
  412. name = node.get('name')
  413. value = node.get('ref') or node.text
  414. if not name in all_names:
  415. continue
  416. setattr(self, name, value)
  417. def xml_properties(self, with_defaults=False):
  418. '''Iterator that yields XML nodes representing set properties.
  419. :param bool with_defaults: If :py:obj:`True`, then it also includes \
  420. properties which were not set explicite, but have default values \
  421. filled.
  422. '''
  423. properties = lxml.etree.Element('properties')
  424. for prop in self.property_list():
  425. # pylint: disable=protected-access
  426. try:
  427. value = getattr(
  428. self, (prop.__name__ if with_defaults else prop._attr_name))
  429. except AttributeError:
  430. continue
  431. try:
  432. value = prop._saver(self, prop, value)
  433. except property.DontSave:
  434. continue
  435. element = lxml.etree.Element('property', name=prop.__name__)
  436. if prop.save_via_ref:
  437. element.set('ref', value)
  438. else:
  439. element.text = value
  440. properties.append(element)
  441. return properties
  442. # this was clone_attrs
  443. def clone_properties(self, src, proplist=None):
  444. '''Clone properties from other object.
  445. :param PropertyHolder src: source object
  446. :param list proplist: list of properties \
  447. (:py:obj:`None` or omit for all properties except those with \
  448. :py:attr:`property.clone` set to :py:obj:`False`)
  449. '''
  450. if proplist is None:
  451. proplist = [prop for prop in self.property_list()
  452. if prop.clone]
  453. else:
  454. proplist = [prop for prop in self.property_list()
  455. if prop.__name__ in proplist or prop in proplist]
  456. for prop in proplist:
  457. try:
  458. # pylint: disable=protected-access
  459. self._property_init(prop, getattr(src, prop._attr_name))
  460. except AttributeError:
  461. continue
  462. self.fire_event('clone-properties', src=src, proplist=proplist)
  463. def property_require(self, prop, allow_none=False, hard=False):
  464. '''Complain badly when property is not set.
  465. :param prop: property name or object
  466. :type prop: qubes.property or str
  467. :param bool allow_none: if :py:obj:`True`, don't complain if \
  468. :py:obj:`None` is found
  469. :param bool hard: if :py:obj:`True`, raise :py:class:`AssertionError`; \
  470. if :py:obj:`False`, log warning instead
  471. '''
  472. if isinstance(prop, qubes.property):
  473. prop = prop.__name__
  474. try:
  475. value = getattr(self, prop)
  476. if value is None and not allow_none:
  477. raise AttributeError()
  478. except AttributeError:
  479. # pylint: disable=no-member
  480. msg = 'Required property {!r} not set on {!r}'.format(prop, self)
  481. if hard:
  482. raise AssertionError(msg)
  483. else:
  484. # pylint: disable=no-member
  485. self.log.fatal(msg)
  486. # pylint: disable=wrong-import-position
  487. from qubes.vm import VMProperty
  488. from qubes.app import Qubes
  489. __all__ = [
  490. 'Label',
  491. 'PropertyHolder',
  492. 'Qubes',
  493. 'VMProperty',
  494. 'property',
  495. ]