qvm_block.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. #!/usr/bin/python2
  2. # pylint: disable=C,R
  3. # -*- encoding: utf8 -*-
  4. #
  5. # The Qubes OS Project, http://www.qubes-os.org
  6. #
  7. # Copyright (C) 2016 Bahtiar `kalkin-` Gadimov <bahtiar@gadimov.de>
  8. #
  9. # This program is free software; you can redistribute it and/or modify
  10. # it under the terms of the GNU General Public License as published by
  11. # the Free Software Foundation; either version 2 of the License, or
  12. # (at your option) any later version.
  13. #
  14. # This program 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
  17. # GNU General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU General Public License along
  20. # with this program; if not, write to the Free Software Foundation, Inc.,
  21. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  22. '''Qubes volume and block device managment'''
  23. from __future__ import print_function
  24. import sys
  25. import qubes
  26. import qubes.exc
  27. import qubes.tools
  28. def prepare_table(vd_list, full=False):
  29. ''' Converts a list of :py:class:`VolumeData` objects to a list of tupples
  30. for the :py:func:`qubes.tools.print_table`.
  31. If :program:`qvm-block` is running in a TTY, it will ommit duplicate
  32. data.
  33. :param list vd_list: List of :py:class:`VolumeData` objects.
  34. :param bool full: If set to true duplicate data is printed even when
  35. running from TTY.
  36. :returns: list of tupples
  37. '''
  38. output = []
  39. if sys.stdout.isatty():
  40. output += [('POOL_NAME:VOLUME_ID', 'VOLUME_TYPE', 'VMNAME')]
  41. for volume in vd_list:
  42. if volume.domains:
  43. vmname = volume.domains.pop()
  44. output += [(str(volume), volume.volume_type, vmname)]
  45. for vmname in volume.domains:
  46. if full or not sys.stdout.isatty():
  47. output += [(str(volume), volume.volume_type, vmname)]
  48. else:
  49. output += [('', '', vmname)]
  50. else:
  51. output += [(str(volume), volume.volume_type)]
  52. return output
  53. class VolumeData(object):
  54. ''' Wrapper object around :py:class:`qubes.storage.Volume`, mainly to track
  55. the domains a volume is attached to.
  56. '''
  57. # pylint: disable=too-few-public-methods
  58. def __init__(self, volume):
  59. self.name = volume.name
  60. self.pool = volume.pool
  61. self.volume_type = volume.volume_type
  62. self.vid = volume.vid
  63. self.domains = []
  64. def __str__(self):
  65. return "{!s}:{!s}".format(self.pool, self.vid)
  66. def list_volumes(args):
  67. ''' Called by the parser to execute the qubes-block list subcommand. '''
  68. app = args.app
  69. if args.pools:
  70. pools = args.pools # only specified pools
  71. else:
  72. pools = app.pools.values() # all pools
  73. volumes = [v for p in pools for v in p.volumes]
  74. if not args.internal: # hide internal volumes
  75. volumes = [v for v in volumes if not v.internal]
  76. vd_dict = {}
  77. for volume in volumes:
  78. volume_data = VolumeData(volume)
  79. try:
  80. vd_dict[volume.pool][volume.vid] = volume_data
  81. except KeyError:
  82. vd_dict[volume.pool] = {volume.vid: volume_data}
  83. if hasattr(args, 'domains') and args.domains:
  84. domains = args.domains
  85. else:
  86. domains = args.app.domains
  87. for domain in domains: # gather the domain names
  88. try:
  89. for volume in domain.attached_volumes:
  90. try:
  91. volume_data = vd_dict[volume.pool][volume.vid]
  92. volume_data.domains += [domain.name]
  93. except KeyError:
  94. # Skipping volume
  95. continue
  96. except AttributeError:
  97. # Skipping domain without volumes
  98. continue
  99. if hasattr(args, 'domains') and args.domains:
  100. result = [x # reduce to only VolumeData with assigned domains
  101. for p in vd_dict.itervalues() for x in p.itervalues()
  102. if x.domains]
  103. else:
  104. result = [x for p in vd_dict.itervalues() for x in p.itervalues()]
  105. qubes.tools.print_table(prepare_table(result, full=args.full))
  106. def attach_volumes(args):
  107. ''' Called by the parser to execute the :program:`qvm-block attach`
  108. subcommand.
  109. '''
  110. volume = args.volume
  111. vm = args.domains[0]
  112. try:
  113. rw = not args.ro
  114. vm.storage.attach(volume, rw=rw)
  115. except qubes.storage.StoragePoolException as e:
  116. print(e.message, file=sys.stderr)
  117. sys.exit(1)
  118. def detach_volumes(args):
  119. ''' Called by the parser to execute the :program:`qvm-block detach`
  120. subcommand.
  121. '''
  122. volume = args.volume
  123. vm = args.domains[0]
  124. try:
  125. vm.storage.detach(volume)
  126. except qubes.storage.StoragePoolException as e:
  127. print(e.message, file=sys.stderr)
  128. sys.exit(1)
  129. def init_list_parser(sub_parsers):
  130. ''' Configures the parser for the :program:`qvm-block list` subcommand '''
  131. # pylint: disable=protected-access
  132. list_parser = sub_parsers.add_parser('list', aliases=('ls', 'l'),
  133. help='list block devices')
  134. list_parser.add_argument('-p', '--pool', dest='pools',
  135. action=qubes.tools.PoolsAction)
  136. list_parser.add_argument('-i', '--internal', action='store_true',
  137. help='Show internal volumes')
  138. list_parser.add_argument(
  139. '--full', action='store_true',
  140. help='print full line for each POOL_NAME:VOLUME_ID & vm combination')
  141. vm_name_group = qubes.tools.VmNameGroup(
  142. list_parser, required=False, vm_action=qubes.tools.VmNameAction,
  143. help='list volumes from specified domain(s)')
  144. list_parser._mutually_exclusive_groups.append(vm_name_group)
  145. list_parser.set_defaults(func=list_volumes)
  146. def get_parser():
  147. '''Create :py:class:`argparse.ArgumentParser` suitable for
  148. :program:`qvm-block`.
  149. '''
  150. parser = qubes.tools.QubesArgumentParser(description=__doc__, want_app=True)
  151. parser.register('action', 'parsers', qubes.tools.AliasedSubParsersAction)
  152. sub_parsers = parser.add_subparsers(
  153. title='commands',
  154. description="For more information see qvm-block command -h",
  155. dest='command')
  156. init_list_parser(sub_parsers)
  157. attach_parser = sub_parsers.add_parser(
  158. 'attach', help="Attach volume to domain", aliases=('at', 'a'))
  159. attach_parser.add_argument('--ro', help='attach device read-only',
  160. action='store_true')
  161. attach_parser.add_argument('VMNAME', action=qubes.tools.RunningVmNameAction)
  162. attach_parser.add_argument(metavar='POOL_NAME:VOLUME_ID', dest='volume',
  163. action=qubes.tools.VolumeAction)
  164. attach_parser.set_defaults(func=attach_volumes)
  165. detach_parser = sub_parsers.add_parser(
  166. "detach", help="Detach volume from domain", aliases=('d', 'dt'))
  167. detach_parser.add_argument('VMNAME', action=qubes.tools.RunningVmNameAction)
  168. detach_parser.add_argument(metavar='POOL_NAME:VOLUME_ID', dest='volume',
  169. action=qubes.tools.VolumeAction)
  170. detach_parser.set_defaults(func=detach_volumes)
  171. return parser
  172. def main(args=None):
  173. '''Main routine of :program:`qvm-block`.'''
  174. args = get_parser().parse_args(args)
  175. args.func(args)
  176. if __name__ == '__main__':
  177. sys.exit(main())