features.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. # -*- encoding: utf8 -*-
  2. #
  3. # The Qubes OS Project, http://www.qubes-os.org
  4. #
  5. # Copyright (C) 2017 Marek Marczykowski-Górecki
  6. # <marmarek@invisiblethingslab.com>
  7. #
  8. # This program is free software; you can redistribute it and/or modify
  9. # it under the terms of the GNU Lesser General Public License as published by
  10. # the Free Software Foundation; either version 2.1 of the License, or
  11. # (at your option) any later version.
  12. #
  13. # This program is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU Lesser General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU Lesser General Public License along
  19. # with this program; if not, see <http://www.gnu.org/licenses/>.
  20. '''VM features interface'''
  21. class Features(object):
  22. '''Manager of the features.
  23. Features can have three distinct values: no value (not present in mapping,
  24. which is closest thing to :py:obj:`None`), empty string (which is
  25. interpreted as :py:obj:`False`) and non-empty string, which is
  26. :py:obj:`True`. Anything assigned to the mapping is coerced to strings,
  27. however if you assign instances of :py:class:`bool`, they are converted as
  28. described above. Be aware that assigning the number `0` (which is considered
  29. false in Python) will result in string `'0'`, which is considered true.
  30. '''
  31. # pylint: disable=too-few-public-methods
  32. def __init__(self, vm):
  33. super(Features, self).__init__()
  34. self.vm = vm
  35. def __delitem__(self, key):
  36. self.vm.qubesd_call(self.vm.name, 'mgmt.vm.feature.Remove', key)
  37. def __setitem__(self, key, value):
  38. self.vm.qubesd_call(self.vm.name, 'mgmt.vm.feature.Set', key, value)
  39. def __getitem__(self, item):
  40. return self.vm.qubesd_call(
  41. self.vm.name, 'mgmt.vm.feature.Get', item).decode('utf-8')
  42. def __iter__(self):
  43. qubesd_response = self.vm.qubesd_call(self.vm.name,
  44. 'mgmt.vm.feature.List')
  45. return iter(qubesd_response.decode('utf-8').splitlines())
  46. keys = __iter__
  47. _NO_DEFAULT = object()
  48. def check_with_template(self, feature, default=_NO_DEFAULT):
  49. ''' Check if the vm's template has the specified feature. '''
  50. try:
  51. qubesd_response = self.vm.qubesd_call(
  52. self.vm.name, 'mgmt.vm.feature.CheckWithTemplate', feature)
  53. return qubesd_response.decode('utf-8')
  54. except KeyError:
  55. if default is self._NO_DEFAULT:
  56. raise
  57. return default