utils.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  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 os
  27. import re
  28. import subprocess
  29. import docutils
  30. import docutils.core
  31. import docutils.io
  32. import qubes.exc
  33. def get_timezone():
  34. # fc18
  35. if os.path.islink('/etc/localtime'):
  36. return '/'.join(os.readlink('/etc/localtime').split('/')[-2:])
  37. # <=fc17
  38. elif os.path.exists('/etc/sysconfig/clock'):
  39. clock_config = open('/etc/sysconfig/clock', "r")
  40. clock_config_lines = clock_config.readlines()
  41. clock_config.close()
  42. zone_re = re.compile(r'^ZONE="(.*)"')
  43. for line in clock_config_lines:
  44. line_match = zone_re.match(line)
  45. if line_match:
  46. return line_match.group(1)
  47. else:
  48. # last resort way, some applications makes /etc/localtime
  49. # hardlink instead of symlink...
  50. tz_info = os.stat('/etc/localtime')
  51. if not tz_info:
  52. return None
  53. if tz_info.st_nlink > 1:
  54. p = subprocess.Popen(['find', '/usr/share/zoneinfo',
  55. '-inum', str(tz_info.st_ino), '-print', '-quit'],
  56. stdout=subprocess.PIPE)
  57. tz_path = p.communicate()[0].strip()
  58. return tz_path.replace('/usr/share/zoneinfo/', '')
  59. return None
  60. def format_doc(docstring):
  61. '''Return parsed documentation string, stripping RST markup.
  62. '''
  63. if not docstring:
  64. return ''
  65. # pylint: disable=unused-variable
  66. output, pub = docutils.core.publish_programmatically(
  67. source_class=docutils.io.StringInput,
  68. source=' '.join(docstring.strip().split()),
  69. source_path=None,
  70. destination_class=docutils.io.NullOutput, destination=None,
  71. destination_path=None,
  72. reader=None, reader_name='standalone',
  73. parser=None, parser_name='restructuredtext',
  74. writer=None, writer_name='null',
  75. settings=None, settings_spec=None, settings_overrides=None,
  76. config_section=None, enable_exit_status=None)
  77. return pub.writer.document.astext()
  78. # FIXME those are wrong, k/M/G are SI prefixes and means 10**3
  79. # maybe adapt https://code.activestate.com/recipes/578019
  80. def parse_size(size):
  81. units = [
  82. ('K', 1000), ('KB', 1000),
  83. ('M', 1000 * 1000), ('MB', 1000 * 1000),
  84. ('G', 1000 * 1000 * 1000), ('GB', 1000 * 1000 * 1000),
  85. ('Ki', 1024), ('KiB', 1024),
  86. ('Mi', 1024 * 1024), ('MiB', 1024 * 1024),
  87. ('Gi', 1024 * 1024 * 1024), ('GiB', 1024 * 1024 * 1024),
  88. ]
  89. size = size.strip().upper()
  90. if size.isdigit():
  91. return int(size)
  92. for unit, multiplier in units:
  93. if size.endswith(unit):
  94. size = size[:-len(unit)].strip()
  95. return int(size) * multiplier
  96. raise qubes.exc.QubesException("Invalid size: {0}.".format(size))
  97. def mbytes_to_kmg(size):
  98. if size > 1024:
  99. return "%d GiB" % (size / 1024)
  100. else:
  101. return "%d MiB" % size
  102. def kbytes_to_kmg(size):
  103. if size > 1024:
  104. return mbytes_to_kmg(size / 1024)
  105. else:
  106. return "%d KiB" % size
  107. def bytes_to_kmg(size):
  108. if size > 1024:
  109. return kbytes_to_kmg(size / 1024)
  110. else:
  111. return "%d B" % size
  112. def size_to_human(size):
  113. """Humane readable size, with 1/10 precision"""
  114. if size < 1024:
  115. return str(size)
  116. elif size < 1024 * 1024:
  117. return str(round(size / 1024.0, 1)) + ' KiB'
  118. elif size < 1024 * 1024 * 1024:
  119. return str(round(size / (1024.0 * 1024), 1)) + ' MiB'
  120. else:
  121. return str(round(size / (1024.0 * 1024 * 1024), 1)) + ' GiB'
  122. def urandom(size):
  123. rand = os.urandom(size)
  124. if rand is None:
  125. raise IOError('failed to read urandom')
  126. return hashlib.sha512(rand).digest()