utils.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  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 fcntl
  26. import os
  27. import re
  28. import qubesadmin.exc
  29. def parse_size(size):
  30. """Parse human readable size into bytes."""
  31. units = [
  32. ('K', 1000), ('KB', 1000),
  33. ('M', 1000 * 1000), ('MB', 1000 * 1000),
  34. ('G', 1000 * 1000 * 1000), ('GB', 1000 * 1000 * 1000),
  35. ('Ki', 1024), ('KiB', 1024),
  36. ('Mi', 1024 * 1024), ('MiB', 1024 * 1024),
  37. ('Gi', 1024 * 1024 * 1024), ('GiB', 1024 * 1024 * 1024),
  38. ]
  39. size = size.strip().upper()
  40. if size.isdigit():
  41. return int(size)
  42. for unit, multiplier in units:
  43. if size.endswith(unit.upper()):
  44. size = size[:-len(unit)].strip()
  45. return int(size) * multiplier
  46. raise qubesadmin.exc.QubesException("Invalid size: {0}.".format(size))
  47. def mbytes_to_kmg(size):
  48. """Convert mbytes to human readable format."""
  49. if size > 1024:
  50. return "%d GiB" % (size / 1024)
  51. return "%d MiB" % size
  52. def kbytes_to_kmg(size):
  53. """Convert kbytes to human readable format."""
  54. if size > 1024:
  55. return mbytes_to_kmg(size / 1024)
  56. return "%d KiB" % size
  57. def bytes_to_kmg(size):
  58. """Convert bytes to human readable format."""
  59. if size > 1024:
  60. return kbytes_to_kmg(size / 1024)
  61. return "%d B" % size
  62. def size_to_human(size):
  63. """Humane readable size, with 1/10 precision"""
  64. if size < 1024:
  65. return str(size)
  66. if size < 1024 * 1024:
  67. return str(round(size / 1024.0, 1)) + ' KiB'
  68. if size < 1024 * 1024 * 1024:
  69. return str(round(size / (1024.0 * 1024), 1)) + ' MiB'
  70. return str(round(size / (1024.0 * 1024 * 1024), 1)) + ' GiB'
  71. def get_entry_point_one(group, name):
  72. """Get a single entry point of given type,
  73. raise TypeError when there are multiple.
  74. """
  75. import pkg_resources
  76. epoints = tuple(pkg_resources.iter_entry_points(group, name))
  77. if not epoints:
  78. raise KeyError(name)
  79. if len(epoints) > 1:
  80. raise TypeError('more than 1 implementation of {!r} found: {}'.format(
  81. name, ', '.join('{}.{}'.format(ep.module_name, '.'.join(ep.attrs))
  82. for ep in epoints)))
  83. return epoints[0].load()
  84. UPDATES_DEFAULT_VM_DISABLE_FLAG = \
  85. '/var/lib/qubes/updates/vm-default-disable-updates'
  86. def updates_vms_status(qvm_collection):
  87. """Check whether all VMs have the same check-updates value;
  88. if yes, return it; otherwise, return None
  89. """
  90. # default value:
  91. status = not os.path.exists(UPDATES_DEFAULT_VM_DISABLE_FLAG)
  92. # check if all the VMs uses the default value
  93. for vm in qvm_collection.domains:
  94. if vm.qid == 0:
  95. continue
  96. if vm.features.get('check-updates', True) != status:
  97. # "mixed"
  98. return None
  99. return status
  100. def vm_dependencies(app, reference_vm):
  101. """Helper function that returns a list of all the places a given VM is used
  102. in. Output is a list of tuples (property_holder, property_name), with None
  103. as property_holder for global properties
  104. """
  105. result = []
  106. global_properties = ['default_dispvm', 'default_netvm', 'default_guivm',
  107. 'default_audiovm', 'default_template', 'clockvm',
  108. 'updatevm', 'management_dispvm']
  109. for prop in global_properties:
  110. if reference_vm == getattr(app, prop, None):
  111. result.append((None, prop))
  112. vm_properties = ['template', 'netvm', 'guivm', 'audiovm',
  113. 'default_dispvm', 'management_dispvm']
  114. for vm in app.domains:
  115. if vm == reference_vm:
  116. continue
  117. for prop in vm_properties:
  118. if not hasattr(vm, prop):
  119. continue
  120. try:
  121. is_prop_default = vm.property_is_default(prop)
  122. except qubesadmin.exc.QubesPropertyAccessError:
  123. is_prop_default = False
  124. if reference_vm == getattr(vm, prop, None) and not is_prop_default:
  125. result.append((vm, prop))
  126. return result
  127. def encode_for_vmexec(args):
  128. """
  129. Encode an argument list for qubes.VMExec call.
  130. """
  131. def encode(part):
  132. if part.group(0) == b'-':
  133. return b'--'
  134. return '-{:02X}'.format(ord(part.group(0))).encode('ascii')
  135. parts = []
  136. for arg in args:
  137. part = re.sub(br'[^a-zA-Z0-9_.]', encode, arg.encode('utf-8'))
  138. parts.append(part)
  139. return b'+'.join(parts).decode('ascii')
  140. class LockFile(object):
  141. """Simple locking context manager. It opens a file with an advisory lock
  142. taken (fcntl.lockf)"""
  143. def __init__(self, path, nonblock=False):
  144. """Open the file. Call *acquire* or enter the context to lock
  145. the file"""
  146. self.file = open(path, "w")
  147. self.nonblock = nonblock
  148. def __enter__(self, *args, **kwargs):
  149. self.acquire()
  150. return self
  151. def acquire(self):
  152. """Lock the opened file"""
  153. fcntl.lockf(self.file,
  154. fcntl.LOCK_EX | (fcntl.LOCK_NB if self.nonblock else 0))
  155. def __exit__(self, exc_type=None, exc_value=None, traceback=None):
  156. self.release()
  157. def release(self):
  158. """Unlock the file and close the file object"""
  159. fcntl.lockf(self.file, fcntl.LOCK_UN)
  160. self.file.close()