utils.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. #!/usr/bin/python2 -O
  2. # vim: fileencoding=utf-8
  3. #
  4. # The Qubes OS Project, https://www.qubes-os.org/
  5. #
  6. # Copyright (C) 2010-2015 Joanna Rutkowska <joanna@invisiblethingslab.com>
  7. # Copyright (C) 2013-2015 Marek Marczykowski-Górecki
  8. # <marmarek@invisiblethingslab.com>
  9. # Copyright (C) 2014-2015 Wojtek Porczyk <woju@invisiblethingslab.com>
  10. #
  11. # This program is free software; you can redistribute it and/or modify
  12. # it under the terms of the GNU General Public License as published by
  13. # the Free Software Foundation; either version 2 of the License, or
  14. # (at your option) any later version.
  15. #
  16. # This program is distributed in the hope that it will be useful,
  17. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. # GNU General Public License for more details.
  20. #
  21. # You should have received a copy of the GNU General Public License along
  22. # with this program; if not, write to the Free Software Foundation, Inc.,
  23. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  24. #
  25. import hashlib
  26. import random
  27. import string
  28. import os
  29. import re
  30. import subprocess
  31. import pkg_resources
  32. import docutils
  33. import docutils.core
  34. import docutils.io
  35. import qubes.exc
  36. def get_timezone():
  37. # fc18
  38. if os.path.islink('/etc/localtime'):
  39. return '/'.join(os.readlink('/etc/localtime').split('/')[-2:])
  40. # <=fc17
  41. elif os.path.exists('/etc/sysconfig/clock'):
  42. clock_config = open('/etc/sysconfig/clock', "r")
  43. clock_config_lines = clock_config.readlines()
  44. clock_config.close()
  45. zone_re = re.compile(r'^ZONE="(.*)"')
  46. for line in clock_config_lines:
  47. line_match = zone_re.match(line)
  48. if line_match:
  49. return line_match.group(1)
  50. else:
  51. # last resort way, some applications makes /etc/localtime
  52. # hardlink instead of symlink...
  53. tz_info = os.stat('/etc/localtime')
  54. if not tz_info:
  55. return None
  56. if tz_info.st_nlink > 1:
  57. p = subprocess.Popen(['find', '/usr/share/zoneinfo',
  58. '-inum', str(tz_info.st_ino), '-print', '-quit'],
  59. stdout=subprocess.PIPE)
  60. tz_path = p.communicate()[0].strip()
  61. return tz_path.replace('/usr/share/zoneinfo/', '')
  62. return None
  63. def format_doc(docstring):
  64. '''Return parsed documentation string, stripping RST markup.
  65. '''
  66. if not docstring:
  67. return ''
  68. # pylint: disable=unused-variable
  69. output, pub = docutils.core.publish_programmatically(
  70. source_class=docutils.io.StringInput,
  71. source=' '.join(docstring.strip().split()),
  72. source_path=None,
  73. destination_class=docutils.io.NullOutput, destination=None,
  74. destination_path=None,
  75. reader=None, reader_name='standalone',
  76. parser=None, parser_name='restructuredtext',
  77. writer=None, writer_name='null',
  78. settings=None, settings_spec=None, settings_overrides=None,
  79. config_section=None, enable_exit_status=None)
  80. return pub.writer.document.astext()
  81. def parse_size(size):
  82. units = [
  83. ('K', 1000), ('KB', 1000),
  84. ('M', 1000 * 1000), ('MB', 1000 * 1000),
  85. ('G', 1000 * 1000 * 1000), ('GB', 1000 * 1000 * 1000),
  86. ('Ki', 1024), ('KiB', 1024),
  87. ('Mi', 1024 * 1024), ('MiB', 1024 * 1024),
  88. ('Gi', 1024 * 1024 * 1024), ('GiB', 1024 * 1024 * 1024),
  89. ]
  90. size = size.strip().upper()
  91. if size.isdigit():
  92. return int(size)
  93. for unit, multiplier in units:
  94. if size.endswith(unit):
  95. size = size[:-len(unit)].strip()
  96. return int(size) * multiplier
  97. raise qubes.exc.QubesException("Invalid size: {0}.".format(size))
  98. def mbytes_to_kmg(size):
  99. if size > 1024:
  100. return "%d GiB" % (size / 1024)
  101. else:
  102. return "%d MiB" % size
  103. def kbytes_to_kmg(size):
  104. if size > 1024:
  105. return mbytes_to_kmg(size / 1024)
  106. else:
  107. return "%d KiB" % size
  108. def bytes_to_kmg(size):
  109. if size > 1024:
  110. return kbytes_to_kmg(size / 1024)
  111. else:
  112. return "%d B" % size
  113. def size_to_human(size):
  114. """Humane readable size, with 1/10 precision"""
  115. if size < 1024:
  116. return str(size)
  117. elif size < 1024 * 1024:
  118. return str(round(size / 1024.0, 1)) + ' KiB'
  119. elif size < 1024 * 1024 * 1024:
  120. return str(round(size / (1024.0 * 1024), 1)) + ' MiB'
  121. else:
  122. return str(round(size / (1024.0 * 1024 * 1024), 1)) + ' GiB'
  123. def urandom(size):
  124. rand = os.urandom(size)
  125. if rand is None:
  126. raise IOError('failed to read urandom')
  127. return hashlib.sha512(rand).digest()
  128. def get_entry_point_one(group, name):
  129. epoints = tuple(pkg_resources.iter_entry_points(group, name))
  130. if not epoints:
  131. raise KeyError(name)
  132. elif len(epoints) > 1:
  133. raise TypeError(
  134. 'more than 1 implementation of {!r} found: {}'.format(name,
  135. ', '.join('{}.{}'.format(ep.module_name, '.'.join(ep.attrs))
  136. for ep in epoints)))
  137. return epoints[0].load()
  138. def random_string(length=5):
  139. ''' Return random string consisting of ascii_leters and digits '''
  140. return ''.join(random.choice(string.ascii_letters + string.digits)
  141. for _ in range(length))