utils.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. # encoding=utf-8
  2. #
  3. # The Qubes OS Project, https://www.qubes-os.org/
  4. #
  5. # Copyright (C) 2010-2015 Joanna Rutkowska <joanna@invisiblethingslab.com>
  6. # Copyright (C) 2013-2015 Marek Marczykowski-Górecki
  7. # <marmarek@invisiblethingslab.com>
  8. # Copyright (C) 2014-2015 Wojtek Porczyk <woju@invisiblethingslab.com>
  9. #
  10. # This program is free software; you can redistribute it and/or modify
  11. # it under the terms of the GNU Lesser General Public License as published by
  12. # the Free Software Foundation; either version 2.1 of the License, or
  13. # (at your option) any later version.
  14. #
  15. # This program is distributed in the hope that it will be useful,
  16. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. # GNU Lesser General Public License for more details.
  19. #
  20. # You should have received a copy of the GNU Lesser General Public License along
  21. # with this program; if not, write to the Free Software Foundation, Inc.,
  22. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  23. #
  24. '''Various utility functions.'''
  25. import os
  26. import pkg_resources
  27. import docutils
  28. import docutils.core
  29. import docutils.io
  30. import qubesadmin.exc
  31. def format_doc(docstring):
  32. '''Return parsed documentation string, stripping RST markup.
  33. '''
  34. if not docstring:
  35. return ''
  36. # pylint: disable=unused-variable
  37. output, pub = docutils.core.publish_programmatically(
  38. source_class=docutils.io.StringInput,
  39. source=' '.join(docstring.strip().split()),
  40. source_path=None,
  41. destination_class=docutils.io.NullOutput, destination=None,
  42. destination_path=None,
  43. reader=None, reader_name='standalone',
  44. parser=None, parser_name='restructuredtext',
  45. writer=None, writer_name='null',
  46. settings=None, settings_spec=None, settings_overrides=None,
  47. config_section=None, enable_exit_status=None)
  48. return pub.writer.document.astext()
  49. def parse_size(size):
  50. '''Parse human readable size into bytes.'''
  51. units = [
  52. ('K', 1000), ('KB', 1000),
  53. ('M', 1000 * 1000), ('MB', 1000 * 1000),
  54. ('G', 1000 * 1000 * 1000), ('GB', 1000 * 1000 * 1000),
  55. ('Ki', 1024), ('KiB', 1024),
  56. ('Mi', 1024 * 1024), ('MiB', 1024 * 1024),
  57. ('Gi', 1024 * 1024 * 1024), ('GiB', 1024 * 1024 * 1024),
  58. ]
  59. size = size.strip().upper()
  60. if size.isdigit():
  61. return int(size)
  62. for unit, multiplier in units:
  63. if size.endswith(unit.upper()):
  64. size = size[:-len(unit)].strip()
  65. return int(size) * multiplier
  66. raise qubesadmin.exc.QubesException("Invalid size: {0}.".format(size))
  67. def mbytes_to_kmg(size):
  68. '''Convert mbytes to human readable format.'''
  69. if size > 1024:
  70. return "%d GiB" % (size / 1024)
  71. return "%d MiB" % size
  72. def kbytes_to_kmg(size):
  73. '''Convert kbytes to human readable format.'''
  74. if size > 1024:
  75. return mbytes_to_kmg(size / 1024)
  76. return "%d KiB" % size
  77. def bytes_to_kmg(size):
  78. '''Convert bytes to human readable format.'''
  79. if size > 1024:
  80. return kbytes_to_kmg(size / 1024)
  81. return "%d B" % size
  82. def size_to_human(size):
  83. """Humane readable size, with 1/10 precision"""
  84. if size < 1024:
  85. return str(size)
  86. elif size < 1024 * 1024:
  87. return str(round(size / 1024.0, 1)) + ' KiB'
  88. elif size < 1024 * 1024 * 1024:
  89. return str(round(size / (1024.0 * 1024), 1)) + ' MiB'
  90. return str(round(size / (1024.0 * 1024 * 1024), 1)) + ' GiB'
  91. def get_entry_point_one(group, name):
  92. '''Get a single entry point of given type,
  93. raise TypeError when there are multiple.
  94. '''
  95. epoints = tuple(pkg_resources.iter_entry_points(group, name))
  96. if not epoints:
  97. raise KeyError(name)
  98. elif len(epoints) > 1:
  99. raise TypeError(
  100. 'more than 1 implementation of {!r} found: {}'.format(name,
  101. ', '.join('{}.{}'.format(ep.module_name, '.'.join(ep.attrs))
  102. for ep in epoints)))
  103. return epoints[0].load()
  104. UPDATES_DEFAULT_VM_DISABLE_FLAG = \
  105. '/var/lib/qubes/updates/vm-default-disable-updates'
  106. def updates_vms_status(qvm_collection):
  107. '''Check whether all VMs have the same check-updates value;
  108. if yes, return it; otherwise, return None
  109. '''
  110. # default value:
  111. status = not os.path.exists(UPDATES_DEFAULT_VM_DISABLE_FLAG)
  112. # check if all the VMs uses the default value
  113. for vm in qvm_collection.domains:
  114. if vm.qid == 0:
  115. continue
  116. if vm.features.get('check-updates', True) != status:
  117. # "mixed"
  118. return None
  119. return status