utils.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  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) 2013-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. import hashlib
  23. import random
  24. import string
  25. import os
  26. import re
  27. import socket
  28. import subprocess
  29. import pkg_resources
  30. import docutils
  31. import docutils.core
  32. import docutils.io
  33. import qubes.exc
  34. def get_timezone():
  35. # fc18
  36. if os.path.islink('/etc/localtime'):
  37. return '/'.join(os.readlink('/etc/localtime').split('/')[-2:])
  38. # <=fc17
  39. if os.path.exists('/etc/sysconfig/clock'):
  40. clock_config = open('/etc/sysconfig/clock', "r")
  41. clock_config_lines = clock_config.readlines()
  42. clock_config.close()
  43. zone_re = re.compile(r'^ZONE="(.*)"')
  44. for line in clock_config_lines:
  45. line_match = zone_re.match(line)
  46. if line_match:
  47. return line_match.group(1)
  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(b'/usr/share/zoneinfo/', b'')
  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. def parse_size(size):
  79. units = [
  80. ('K', 1000), ('KB', 1000),
  81. ('M', 1000 * 1000), ('MB', 1000 * 1000),
  82. ('G', 1000 * 1000 * 1000), ('GB', 1000 * 1000 * 1000),
  83. ('Ki', 1024), ('KiB', 1024),
  84. ('Mi', 1024 * 1024), ('MiB', 1024 * 1024),
  85. ('Gi', 1024 * 1024 * 1024), ('GiB', 1024 * 1024 * 1024),
  86. ]
  87. size = size.strip().upper()
  88. if size.isdigit():
  89. return int(size)
  90. for unit, multiplier in units:
  91. if size.endswith(unit.upper()):
  92. size = size[:-len(unit)].strip()
  93. return int(size) * multiplier
  94. raise qubes.exc.QubesException("Invalid size: {0}.".format(size))
  95. def mbytes_to_kmg(size):
  96. if size > 1024:
  97. return "%d GiB" % (size / 1024)
  98. return "%d MiB" % size
  99. def kbytes_to_kmg(size):
  100. if size > 1024:
  101. return mbytes_to_kmg(size / 1024)
  102. return "%d KiB" % size
  103. def bytes_to_kmg(size):
  104. if size > 1024:
  105. return kbytes_to_kmg(size / 1024)
  106. return "%d B" % size
  107. def size_to_human(size):
  108. """Humane readable size, with 1/10 precision"""
  109. if size < 1024:
  110. return str(size)
  111. if size < 1024 * 1024:
  112. return str(round(size / 1024.0, 1)) + ' KiB'
  113. if size < 1024 * 1024 * 1024:
  114. return str(round(size / (1024.0 * 1024), 1)) + ' MiB'
  115. return str(round(size / (1024.0 * 1024 * 1024), 1)) + ' GiB'
  116. def urandom(size):
  117. rand = os.urandom(size)
  118. if rand is None:
  119. raise IOError('failed to read urandom')
  120. return hashlib.sha512(rand).digest()
  121. def get_entry_point_one(group, name):
  122. epoints = tuple(pkg_resources.iter_entry_points(group, name))
  123. if not epoints:
  124. raise KeyError(name)
  125. if len(epoints) > 1:
  126. raise TypeError(
  127. 'more than 1 implementation of {!r} found: {}'.format(name,
  128. ', '.join('{}.{}'.format(ep.module_name, '.'.join(ep.attrs))
  129. for ep in epoints)))
  130. return epoints[0].load()
  131. def random_string(length=5):
  132. ''' Return random string consisting of ascii_leters and digits '''
  133. return ''.join(random.choice(string.ascii_letters + string.digits)
  134. for _ in range(length))
  135. def systemd_notify():
  136. '''Notify systemd'''
  137. nofity_socket = os.getenv('NOTIFY_SOCKET')
  138. if not nofity_socket:
  139. return
  140. if nofity_socket.startswith('@'):
  141. nofity_socket = '\0' + nofity_socket[1:]
  142. sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
  143. sock.connect(nofity_socket)
  144. sock.sendall(b'READY=1')
  145. sock.close()
  146. def match_vm_name_with_special(vm, name):
  147. '''Check if *vm* matches given name, which may be specified as @tag:...
  148. or @type:...'''
  149. if name.startswith('@tag:'):
  150. return name[len('@tag:'):] in vm.tags
  151. if name.startswith('@type:'):
  152. return name[len('@type:'):] == vm.__class__.__name__
  153. return name == vm.name