qvm_block.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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. import qubes.utils
  29. def prepare_table(vd_list, full=False):
  30. ''' Converts a list of :py:class:`VolumeData` objects to a list of tupples
  31. for the :py:func:`qubes.tools.print_table`.
  32. If :program:`qvm-block` is running in a TTY, it will ommit duplicate
  33. data.
  34. :param list vd_list: List of :py:class:`VolumeData` objects.
  35. :param bool full: If set to true duplicate data is printed even when
  36. running from TTY.
  37. :returns: list of tupples
  38. '''
  39. output = []
  40. if sys.stdout.isatty():
  41. # NOQA
  42. output += [('POOL:VOLUME', 'VMNAME', 'VOLUME_NAME', 'REVERT_POSSIBLE')]
  43. for volume in vd_list:
  44. if volume.domains:
  45. vmname, volume_name = volume.domains.pop()
  46. output += [(str(volume), vmname, volume_name, volume.revisions)]
  47. for tupple in volume.domains:
  48. vmname, volume_name = tupple
  49. if full or not sys.stdout.isatty():
  50. output += [(str(volume), vmname, volume_name,
  51. volume.revisions)]
  52. else:
  53. output += [('', vmname, volume_name, '', volume.revisions)]
  54. else:
  55. output += [(str(volume), "")]
  56. return output
  57. class VolumeData(object):
  58. ''' Wrapper object around :py:class:`qubes.storage.Volume`, mainly to track
  59. the domains a volume is attached to.
  60. '''
  61. # pylint: disable=too-few-public-methods
  62. def __init__(self, volume):
  63. self.name = volume.name
  64. self.pool = volume.pool
  65. self.vid = volume.vid
  66. if volume.revisions != {}:
  67. self.revisions = 'Yes'
  68. else:
  69. self.revisions = 'No'
  70. self.domains = []
  71. def __str__(self):
  72. return "{!s}:{!s}".format(self.pool, self.vid)
  73. def list_volumes(args):
  74. ''' Called by the parser to execute the qubes-block list subcommand. '''
  75. app = args.app
  76. if args.pools:
  77. pools = args.pools # only specified pools
  78. else:
  79. pools = app.pools.values() # all pools
  80. volumes = [v for p in pools for v in p.volumes]
  81. if not args.internal: # hide internal volumes
  82. volumes = [v for v in volumes if not v.internal]
  83. vd_dict = {}
  84. for volume in volumes:
  85. volume_data = VolumeData(volume)
  86. try:
  87. vd_dict[volume.pool][volume.vid] = volume_data
  88. except KeyError:
  89. vd_dict[volume.pool] = {volume.vid: volume_data}
  90. if hasattr(args, 'domains') and args.domains:
  91. domains = args.domains
  92. else:
  93. domains = args.app.domains
  94. for domain in domains: # gather the domain names
  95. try:
  96. for volume in domain.attached_volumes:
  97. if not args.internal and volume.internal:
  98. continue
  99. try:
  100. volume_data = vd_dict[volume.pool][volume.vid]
  101. volume_data.domains += [(domain.name, volume.name)]
  102. except KeyError:
  103. # Skipping volume
  104. continue
  105. except AttributeError:
  106. # Skipping domain without volumes
  107. continue
  108. if hasattr(args, 'domains') and args.domains:
  109. result = [x # reduce to only VolumeData with assigned domains
  110. for p in vd_dict.itervalues() for x in p.itervalues()
  111. if x.domains]
  112. else:
  113. result = [x for p in vd_dict.itervalues() for x in p.itervalues()]
  114. qubes.tools.print_table(prepare_table(result, full=args.full))
  115. def revert_volume(args):
  116. volume = args.volume
  117. app = args.app
  118. try:
  119. pool = app.pools[volume.pool]
  120. pool.revert(volume)
  121. except qubes.storage.StoragePoolException as e:
  122. print(e.message, file=sys.stderr)
  123. sys.exit(1)
  124. def attach_volumes(args):
  125. ''' Called by the parser to execute the :program:`qvm-block attach`
  126. subcommand.
  127. '''
  128. volume = args.volume
  129. vm = args.domains[0]
  130. try:
  131. rw = not args.ro
  132. vm.storage.attach(volume, rw=rw)
  133. except qubes.storage.StoragePoolException as e:
  134. print(e.message, file=sys.stderr)
  135. sys.exit(1)
  136. def detach_volumes(args):
  137. ''' Called by the parser to execute the :program:`qvm-block detach`
  138. subcommand.
  139. '''
  140. volume = args.volume
  141. vm = args.domains[0]
  142. try:
  143. vm.storage.detach(volume)
  144. except qubes.storage.StoragePoolException as e:
  145. print(e.message, file=sys.stderr)
  146. sys.exit(1)
  147. def extend_volumes(args):
  148. ''' Called by the parser to execute the :program:`qvm-block extend`
  149. subcommand
  150. '''
  151. volume = args.volume
  152. app = args.app
  153. size = qubes.utils.parse_size(args.size)
  154. pool = app.get_pool(volume.pool)
  155. pool.resize(volume, volume.size+size)
  156. app.save()
  157. def init_list_parser(sub_parsers):
  158. ''' Configures the parser for the :program:`qvm-block list` subcommand '''
  159. # pylint: disable=protected-access
  160. list_parser = sub_parsers.add_parser('list', aliases=('ls', 'l'),
  161. help='list block devices')
  162. list_parser.add_argument('-p', '--pool', dest='pools',
  163. action=qubes.tools.PoolsAction)
  164. list_parser.add_argument('-i', '--internal', action='store_true',
  165. help='Show internal volumes')
  166. list_parser.add_argument(
  167. '--full', action='store_true',
  168. help='print full line for each POOL_NAME:VOLUME_ID & vm combination')
  169. vm_name_group = qubes.tools.VmNameGroup(
  170. list_parser, required=False, vm_action=qubes.tools.VmNameAction,
  171. help='list volumes from specified domain(s)')
  172. list_parser._mutually_exclusive_groups.append(vm_name_group)
  173. list_parser.set_defaults(func=list_volumes)
  174. def init_revert_parser(sub_parsers):
  175. revert_parser = sub_parsers.add_parser(
  176. 'revert', aliases=('rv', 'r'),
  177. help='revert volume to previous revision')
  178. revert_parser.add_argument(metavar='POOL_NAME:VOLUME_ID', dest='volume',
  179. action=qubes.tools.VolumeAction)
  180. revert_parser.set_defaults(func=revert_volume)
  181. def init_attach_parser(sub_parsers):
  182. attach_parser = sub_parsers.add_parser(
  183. 'attach', help="Attach volume to domain", aliases=('at', 'a'))
  184. attach_parser.add_argument('--ro', help='attach device read-only',
  185. action='store_true')
  186. attach_parser.add_argument('VMNAME', action=qubes.tools.RunningVmNameAction)
  187. attach_parser.add_argument(metavar='POOL_NAME:VOLUME_ID', dest='volume',
  188. action=qubes.tools.VolumeAction)
  189. attach_parser.set_defaults(func=attach_volumes)
  190. def init_dettach_parser(sub_parsers):
  191. detach_parser = sub_parsers.add_parser(
  192. "detach", help="Detach volume from domain", aliases=('d', 'dt'))
  193. detach_parser.add_argument('VMNAME', action=qubes.tools.RunningVmNameAction)
  194. detach_parser.add_argument(metavar='POOL_NAME:VOLUME_ID', dest='volume',
  195. action=qubes.tools.VolumeAction)
  196. detach_parser.set_defaults(func=detach_volumes)
  197. def init_extend_parser(sub_parsers):
  198. extend_parser = sub_parsers.add_parser(
  199. "extend", help="extend volume from domain", aliases=('d', 'dt'))
  200. extend_parser.add_argument(metavar='POOL_NAME:VOLUME_ID', dest='volume',
  201. action=qubes.tools.VolumeAction)
  202. extend_parser.add_argument('size', help='New size in bytes')
  203. extend_parser.set_defaults(func=extend_volumes)
  204. def get_parser():
  205. '''Create :py:class:`argparse.ArgumentParser` suitable for
  206. :program:`qvm-block`.
  207. '''
  208. parser = qubes.tools.QubesArgumentParser(description=__doc__, want_app=True)
  209. parser.register('action', 'parsers', qubes.tools.AliasedSubParsersAction)
  210. sub_parsers = parser.add_subparsers(
  211. title='commands',
  212. description="For more information see qvm-block command -h",
  213. dest='command')
  214. init_attach_parser(sub_parsers)
  215. init_dettach_parser(sub_parsers)
  216. init_extend_parser(sub_parsers)
  217. init_list_parser(sub_parsers)
  218. init_revert_parser(sub_parsers)
  219. return parser
  220. def main(args=None):
  221. '''Main routine of :program:`qvm-block`.'''
  222. parser = get_parser()
  223. try:
  224. args = parser.parse_args(args)
  225. args.func(args)
  226. except qubes.exc.QubesException as e:
  227. parser.print_error(e.message)
  228. return 1
  229. if __name__ == '__main__':
  230. sys.exit(main())