__init__.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810
  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 library is free software; you can redistribute it and/or
  10. # modify it under the terms of the GNU Lesser General Public
  11. # License as published by the Free Software Foundation; either
  12. # version 2.1 of the License, or (at your option) any later version.
  13. #
  14. # This library 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 GNU
  17. # Lesser General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU Lesser General Public
  20. # License along with this library; if not, see <https://www.gnu.org/licenses/>.
  21. #
  22. '''
  23. Qubes OS
  24. :copyright: © 2010-2015 Invisible Things Lab
  25. '''
  26. import builtins
  27. import collections.abc
  28. import os
  29. import os.path
  30. import string
  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:
  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. def __hash__(self):
  88. return hash(self.name)
  89. @builtins.property
  90. def icon_path(self):
  91. '''Icon path
  92. .. deprecated:: 2.0
  93. use :py:meth:`PyQt4.QtGui.QIcon.fromTheme` and :py:attr:`icon`
  94. '''
  95. return os.path.join(qubes.config.system_path['qubes_icon_dir'],
  96. self.icon) + ".png"
  97. @builtins.property
  98. def icon_path_dispvm(self):
  99. '''Icon path
  100. .. deprecated:: 2.0
  101. use :py:meth:`PyQt4.QtGui.QIcon.fromTheme` and :py:attr:`icon_dispvm`
  102. '''
  103. return os.path.join(qubes.config.system_path['qubes_icon_dir'],
  104. self.icon_dispvm) + ".png"
  105. class property: # pylint: disable=redefined-builtin,invalid-name
  106. '''Qubes property.
  107. This class holds one property that can be saved to and loaded from
  108. :file:`qubes.xml`. It is used for both global and per-VM properties.
  109. Property can be unset by ordinary ``del`` statement or assigning
  110. :py:attr:`DEFAULT` special value to it. After deletion (or before first
  111. assignment/load) attempting to read a property will get its default value
  112. or, when no default, py:class:`exceptions.AttributeError`.
  113. :param str name: name of the property
  114. :param collections.abc.Callable setter: if not :py:obj:`None`, this is \
  115. used to initialise value; first parameter to the function is holder \
  116. instance and the second is value; this is called before ``type``
  117. :param collections.abc.Callable saver: function to coerce value to \
  118. something readable by setter
  119. :param type type: if not :py:obj:`None`, value is coerced to this type
  120. :param object default: default value; if callable, will be called with \
  121. holder as first argument
  122. :param int load_stage: stage when property should be loaded (see \
  123. :py:class:`Qubes` for description of stages)
  124. :param int order: order of evaluation (bigger order values are later)
  125. :param bool clone: :py:meth:`PropertyHolder.clone_properties` will not \
  126. include this property by default if :py:obj:`False`
  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. doc=None):
  152. # pylint: disable=redefined-builtin
  153. self.__name__ = name
  154. if setter is None and type is bool:
  155. setter = qubes.property.bool
  156. self._setter = setter
  157. self._saver = saver if saver is not None else (
  158. lambda self, prop, value: str(value))
  159. self.type = type
  160. self._default = default
  161. self._default_function = None
  162. if isinstance(default, collections.abc.Callable):
  163. self._default_function = default
  164. self._write_once = write_once
  165. self.order = order
  166. self.load_stage = load_stage
  167. self.save_via_ref = save_via_ref
  168. self.clone = clone
  169. self.__doc__ = doc
  170. self._attr_name = '_qubesprop_' + name
  171. def __get__(self, instance, owner):
  172. if instance is None:
  173. return self
  174. # XXX this violates duck typing, shall we keep it?
  175. if not isinstance(instance, PropertyHolder):
  176. raise AttributeError('qubes.property should be used on '
  177. 'qubes.PropertyHolder instances only')
  178. try:
  179. return getattr(instance, self._attr_name)
  180. except AttributeError:
  181. return self.get_default(instance)
  182. def get_default(self, instance):
  183. if self._default is self._NO_DEFAULT:
  184. raise AttributeError(
  185. 'property {!r} have no default'.format(self.__name__))
  186. if self._default_function:
  187. return self._default_function(instance)
  188. return self._default
  189. def __set__(self, instance, value):
  190. self._enforce_write_once(instance)
  191. if value is self.__class__.DEFAULT:
  192. self.__delete__(instance)
  193. return
  194. try:
  195. oldvalue = getattr(instance, self.__name__)
  196. has_oldvalue = True
  197. except AttributeError:
  198. has_oldvalue = False
  199. if self._setter is not None:
  200. value = self._setter(instance, self, value)
  201. if self.type not in (None, type(value)):
  202. value = self.type(value)
  203. if has_oldvalue:
  204. instance.fire_event('property-pre-set:' + self.__name__,
  205. pre_event=True,
  206. name=self.__name__, newvalue=value, oldvalue=oldvalue)
  207. else:
  208. instance.fire_event('property-pre-set:' + self.__name__,
  209. pre_event=True,
  210. name=self.__name__, newvalue=value)
  211. instance._property_init(self, value) # pylint: disable=protected-access
  212. if has_oldvalue:
  213. instance.fire_event('property-set:' + self.__name__,
  214. name=self.__name__, newvalue=value, oldvalue=oldvalue)
  215. else:
  216. instance.fire_event('property-set:' + self.__name__,
  217. name=self.__name__, newvalue=value)
  218. def __delete__(self, instance):
  219. self._enforce_write_once(instance)
  220. try:
  221. oldvalue = getattr(instance, self.__name__)
  222. has_oldvalue = True
  223. except AttributeError:
  224. has_oldvalue = False
  225. if has_oldvalue:
  226. instance.fire_event('property-pre-reset:' + self.__name__,
  227. pre_event=True,
  228. name=self.__name__, oldvalue=oldvalue)
  229. # deprecated, to be removed in Qubes 5.0
  230. instance.fire_event('property-pre-del:' + self.__name__,
  231. pre_event=True,
  232. name=self.__name__, oldvalue=oldvalue)
  233. try:
  234. delattr(instance, self._attr_name)
  235. except AttributeError:
  236. pass
  237. instance.fire_event('property-reset:' + self.__name__,
  238. name=self.__name__, oldvalue=oldvalue)
  239. # deprecated, to be removed in Qubes 5.0
  240. instance.fire_event('property-del:' + self.__name__,
  241. name=self.__name__, oldvalue=oldvalue)
  242. else:
  243. instance.fire_event('property-pre-reset:' + self.__name__,
  244. pre_event=True,
  245. name=self.__name__)
  246. # deprecated, to be removed in Qubes 5.0
  247. instance.fire_event('property-pre-del:' + self.__name__,
  248. pre_event=True,
  249. name=self.__name__)
  250. instance.fire_event('property-reset:' + self.__name__,
  251. name=self.__name__)
  252. # deprecated, to be removed in Qubes 5.0
  253. instance.fire_event('property-del:' + self.__name__,
  254. name=self.__name__)
  255. def __repr__(self):
  256. default = ' default={!r}'.format(self._default) \
  257. if self._default is not self._NO_DEFAULT \
  258. else ''
  259. return '<{} object at {:#x} name={!r}{}>'.format(
  260. self.__class__.__name__, id(self), self.__name__, default)
  261. def __str__(self):
  262. return self.__name__
  263. def __hash__(self):
  264. return hash(self.__name__)
  265. def __lt__(self, other):
  266. if isinstance(other, property):
  267. return (self.load_stage, self.order, self.__name__) <\
  268. (other.load_stage, other.order, other.__name__)
  269. return NotImplemented
  270. def __eq__(self, other):
  271. if isinstance(other, str):
  272. return self.__name__ == other
  273. return isinstance(other, property) and self.__name__ == other.__name__
  274. def _enforce_write_once(self, instance):
  275. if self._write_once and not instance.property_is_default(self):
  276. raise AttributeError(
  277. 'property {!r} is write-once and already set'.format(
  278. self.__name__))
  279. def sanitize(self, *, untrusted_newvalue):
  280. '''Coarse sanitization of value to be set, before sending it to a
  281. setter. Can raise QubesValueError if the value is invalid.
  282. :param untrusted_newvalue: value to be validated
  283. :return: sanitized value
  284. :raises: qubes.exc.QubesValueError
  285. '''
  286. # do not treat type='str' as sufficient validation
  287. if self.type is not None and self.type is not str:
  288. # assume specific type will preform enough validation
  289. try:
  290. untrusted_newvalue = untrusted_newvalue.decode('ascii',
  291. errors='strict')
  292. except UnicodeDecodeError:
  293. raise qubes.exc.QubesValueError
  294. if self.type is bool:
  295. return self.bool(None, None, untrusted_newvalue)
  296. try:
  297. return self.type(untrusted_newvalue)
  298. except ValueError:
  299. raise qubes.exc.QubesValueError
  300. else:
  301. # 'str' or not specified type
  302. try:
  303. untrusted_newvalue = untrusted_newvalue.decode('ascii',
  304. errors='strict')
  305. except UnicodeDecodeError:
  306. raise qubes.exc.QubesValueError
  307. allowed_set = string.printable
  308. if not all(x in allowed_set for x in untrusted_newvalue):
  309. raise qubes.exc.QubesValueError(
  310. 'Invalid characters in property value')
  311. return untrusted_newvalue
  312. #
  313. # exceptions
  314. #
  315. class DontSave(Exception):
  316. '''This exception may be raised from saver to sign that property should
  317. not be saved.
  318. '''
  319. @staticmethod
  320. def dontsave(self, prop, value):
  321. '''Dummy saver that never saves anything.'''
  322. # pylint: disable=bad-staticmethod-argument,unused-argument
  323. raise property.DontSave()
  324. #
  325. # some setters provided
  326. #
  327. @staticmethod
  328. def forbidden(self, prop, value):
  329. '''Property setter that forbids loading a property.
  330. This is used to effectively disable property in classes which inherit
  331. unwanted property. When someone attempts to load such a property, it
  332. :throws qubes.exc.QubesPropertyValueError: always
  333. ''' # pylint: disable=bad-staticmethod-argument,unused-argument
  334. raise qubes.exc.QubesPropertyValueError(
  335. self, self.property_get_def(prop), value,
  336. 'property {!r} on {} instance cannot be set'.format(
  337. prop.__name__, self.__class__.__name__))
  338. @staticmethod
  339. def bool(self, prop, value):
  340. '''Property setter for boolean properties.
  341. It accepts (case-insensitive) ``'0'``, ``'no'`` and ``false`` as
  342. :py:obj:`False` and ``'1'``, ``'yes'`` and ``'true'`` as
  343. :py:obj:`True`.
  344. ''' # pylint: disable=bad-staticmethod-argument,unused-argument
  345. if isinstance(value, str):
  346. lcvalue = value.lower()
  347. if lcvalue in ('0', 'no', 'false', 'off'):
  348. return False
  349. if lcvalue in ('1', 'yes', 'true', 'on'):
  350. return True
  351. raise qubes.exc.QubesValueError(
  352. 'Invalid literal for boolean property: {!r}'.format(value))
  353. return bool(value)
  354. def stateless_property(func):
  355. '''Decorator similar to :py:class:`builtins.property`, but for properties
  356. exposed through management API (including qvm-prefs etc)'''
  357. return property(func.__name__,
  358. setter=property.forbidden,
  359. saver=property.dontsave,
  360. default=func,
  361. doc=func.__doc__)
  362. class PropertyHolder(qubes.events.Emitter):
  363. '''Abstract class for holding :py:class:`qubes.property`
  364. Events fired by instances of this class:
  365. .. event:: property-load (subject, event)
  366. Fired once after all properties are loaded from XML. Individual
  367. ``property-set`` events are not fired.
  368. .. event:: property-set:<propname> \
  369. (subject, event, name, newvalue[, oldvalue])
  370. Fired when property changes state. Signature is variable,
  371. *oldvalue* is present only if there was an old value.
  372. :param name: Property name
  373. :param newvalue: New value of the property
  374. :param oldvalue: Old value of the property
  375. .. event:: property-pre-set:<propname> \
  376. (subject, event, name, newvalue[, oldvalue])
  377. Fired before property changes state. Signature is variable,
  378. *oldvalue* is present only if there was an old value.
  379. :param name: Property name
  380. :param newvalue: New value of the property
  381. :param oldvalue: Old value of the property
  382. .. event:: property-del:<propname> \
  383. (subject, event, name[, oldvalue])
  384. Fired when property gets deleted (is set to default). Signature is
  385. variable, *oldvalue* is present only if there was an old value.
  386. This event is deprecated and will be removed in Qubes 5.0.
  387. Use property-reset instead.
  388. :param name: Property name
  389. :param oldvalue: Old value of the property
  390. .. event:: property-pre-del:<propname> \
  391. (subject, event, name[, oldvalue])
  392. Fired before property gets deleted (is set to default). Signature
  393. is variable, *oldvalue* is present only if there was an old value.
  394. This event is deprecated and will be removed in Qubes 5.0.
  395. Use property-pre-reset instead.
  396. :param name: Property name
  397. :param oldvalue: Old value of the property
  398. .. event:: property-reset:<propname> \
  399. (subject, event, name[, oldvalue])
  400. Fired when property gets reset to the (possibly dynamic) default.
  401. This even may be also fired when the property is already in
  402. "default" state, but the calculated default value changes.
  403. Signature is variable, *oldvalue* is present only if there was an
  404. old value.
  405. :param name: Property name
  406. :param oldvalue: Old value of the property
  407. .. event:: property-pre-reset:<propname> \
  408. (subject, event, name[, oldvalue])
  409. Fired before property gets reset to the (possibly dynamic) default.
  410. Signature is variable, *oldvalue* is present only if there was an
  411. old value.
  412. :param name: Property name
  413. :param oldvalue: Old value of the property
  414. .. event:: clone-properties (subject, event, src, proplist)
  415. :param src: object, from which we are cloning
  416. :param proplist: list of properties
  417. Members:
  418. '''
  419. def __init__(self, xml, **kwargs):
  420. self.xml = xml
  421. propvalues = {}
  422. all_names = self.property_dict()
  423. for key in list(kwargs):
  424. if not key in all_names:
  425. continue
  426. propvalues[key] = kwargs.pop(key)
  427. super().__init__(**kwargs)
  428. for key, value in propvalues.items():
  429. setattr(self, key, value)
  430. if self.xml is not None:
  431. # check if properties are appropriate
  432. for node in self.xml.xpath('./properties/property'):
  433. name = node.get('name')
  434. if name not in all_names:
  435. raise TypeError(
  436. 'property {!r} not applicable to {!r}'.format(
  437. name, self.__class__.__name__))
  438. # pylint: disable=too-many-nested-blocks
  439. @classmethod
  440. def property_dict(cls, load_stage=None):
  441. '''List all properties attached to this VM's class
  442. :param load_stage: Filter by load stage
  443. :type load_stage: :py:func:`int` or :py:obj:`None`
  444. '''
  445. # use cls.__dict__ since we must not look at parent classes
  446. if "_property_dict" not in cls.__dict__:
  447. cls._property_dict = {}
  448. memo = cls._property_dict
  449. if load_stage not in memo:
  450. props = dict()
  451. if load_stage is None:
  452. for class_ in cls.__mro__:
  453. for name in class_.__dict__:
  454. # don't overwrite props with those from base classes
  455. if name not in props:
  456. prop = class_.__dict__[name]
  457. if isinstance(prop, property):
  458. assert name == prop.__name__
  459. props[name] = prop
  460. else:
  461. for prop in cls.property_dict().values():
  462. if prop.load_stage == load_stage:
  463. props[prop.__name__] = prop
  464. memo[load_stage] = props
  465. return memo[load_stage]
  466. @classmethod
  467. def property_list(cls, load_stage=None):
  468. '''List all properties attached to this VM's class
  469. :param load_stage: Filter by load stage
  470. :type load_stage: :py:func:`int` or :py:obj:`None`
  471. '''
  472. # use cls.__dict__ since we must not look at parent classes
  473. if "_property_list" not in cls.__dict__:
  474. cls._property_list = {}
  475. memo = cls._property_list
  476. if load_stage not in memo:
  477. memo[load_stage] = sorted(cls.property_dict(load_stage).values())
  478. return memo[load_stage]
  479. def _property_init(self, prop, value):
  480. '''Initialise property to a given value, without side effects.
  481. :param qubes.property prop: property object of particular interest
  482. :param value: value
  483. '''
  484. # pylint: disable=protected-access
  485. setattr(self, self.property_get_def(prop)._attr_name, value)
  486. def property_is_default(self, prop):
  487. '''Check whether property is in it's default value.
  488. Properties when unset may return some default value, so
  489. ``hasattr(vm, prop.__name__)`` is wrong in some circumstances. This
  490. method allows for checking if the value returned is in fact it's
  491. default value.
  492. :param qubes.property prop: property object of particular interest
  493. :rtype: bool
  494. ''' # pylint: disable=protected-access
  495. # both property_get_def() and ._attr_name may throw AttributeError,
  496. # which we don't want to catch
  497. attrname = self.property_get_def(prop)._attr_name
  498. return not hasattr(self, attrname)
  499. def property_get_default(self, prop):
  500. '''Get property default value.
  501. :param qubes.property or str prop: property object of particular
  502. interest
  503. '''
  504. return self.property_get_def(prop).get_default(self)
  505. @classmethod
  506. def property_get_def(cls, prop):
  507. '''Return property definition object.
  508. If prop is already :py:class:`qubes.property` instance, return the same
  509. object.
  510. :param prop: property object or name
  511. :type prop: qubes.property or str
  512. :rtype: qubes.property
  513. '''
  514. if isinstance(prop, qubes.property):
  515. return prop
  516. props = cls.property_dict()
  517. if prop in props:
  518. return props[prop]
  519. raise AttributeError('No property {!r} found in {!r}'.format(
  520. prop, cls))
  521. def load_properties(self, load_stage=None):
  522. '''Load properties from immediate children of XML node.
  523. ``property-set`` events are not fired for each individual property.
  524. :param int load_stage: Stage of loading.
  525. '''
  526. if self.xml is None:
  527. return
  528. all_names = set(
  529. prop.__name__ for prop in self.property_list(load_stage))
  530. for node in self.xml.xpath('./properties/property'):
  531. name = node.get('name')
  532. value = node.get('ref') or node.text
  533. if not name in all_names:
  534. continue
  535. setattr(self, name, value)
  536. def xml_properties(self, with_defaults=False):
  537. '''Iterator that yields XML nodes representing set properties.
  538. :param bool with_defaults: If :py:obj:`True`, then it also includes \
  539. properties which were not set explicite, but have default values \
  540. filled.
  541. '''
  542. properties = lxml.etree.Element('properties')
  543. for prop in self.property_list():
  544. # pylint: disable=protected-access
  545. try:
  546. value = getattr(
  547. self, (prop.__name__ if with_defaults else prop._attr_name))
  548. except AttributeError:
  549. continue
  550. try:
  551. value = prop._saver(self, prop, value)
  552. except property.DontSave:
  553. continue
  554. element = lxml.etree.Element('property', name=prop.__name__)
  555. if prop.save_via_ref:
  556. element.set('ref', value)
  557. else:
  558. element.text = value
  559. properties.append(element)
  560. return properties
  561. # this was clone_attrs
  562. def clone_properties(self, src, proplist=None):
  563. '''Clone properties from other object.
  564. :param PropertyHolder src: source object
  565. :param iterable proplist: list of properties \
  566. (:py:obj:`None` or omit for all properties except those with \
  567. :py:attr:`property.clone` set to :py:obj:`False`)
  568. '''
  569. if proplist is None:
  570. proplist = [prop for prop in self.property_list()
  571. if prop.clone]
  572. else:
  573. proplist = [prop for prop in self.property_list()
  574. if prop.__name__ in proplist or prop in proplist]
  575. for prop in proplist:
  576. try:
  577. # pylint: disable=protected-access
  578. self._property_init(prop, getattr(src, prop._attr_name))
  579. except AttributeError:
  580. continue
  581. self.fire_event('clone-properties', src=src, proplist=proplist)
  582. def property_require(self, prop, allow_none=False, hard=False):
  583. '''Complain badly when property is not set.
  584. :param prop: property name or object
  585. :type prop: qubes.property or str
  586. :param bool allow_none: if :py:obj:`True`, don't complain if \
  587. :py:obj:`None` is found
  588. :param bool hard: if :py:obj:`True`, raise :py:class:`AssertionError`; \
  589. if :py:obj:`False`, log warning instead
  590. '''
  591. if isinstance(prop, qubes.property):
  592. prop = prop.__name__
  593. try:
  594. value = getattr(self, prop)
  595. if value is None and not allow_none:
  596. msg = 'Property {!r} cannot be None'.format(prop)
  597. if hard:
  598. raise ValueError(msg)
  599. self.log.fatal(msg)
  600. except AttributeError:
  601. # pylint: disable=no-member
  602. msg = 'Required property {!r} not set on {!r}'.format(prop, self)
  603. if hard:
  604. raise ValueError(msg)
  605. # pylint: disable=no-member
  606. self.log.fatal(msg)
  607. def close(self):
  608. super().close()
  609. # Remove all properties -- somewhere in them there are cyclic
  610. # references. This just removes all the properties, just in case.
  611. # They are removed directly, bypassing write_once.
  612. for prop in self.property_list():
  613. # pylint: disable=protected-access
  614. try:
  615. delattr(self, prop._attr_name)
  616. except AttributeError:
  617. pass
  618. # pylint: disable=wrong-import-position
  619. from qubes.vm import VMProperty
  620. from qubes.app import Qubes
  621. __all__ = [
  622. 'Label',
  623. 'PropertyHolder',
  624. 'Qubes',
  625. 'VMProperty',
  626. 'property',
  627. ]