qvm_block.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. # pylint: disable=C,R
  2. #
  3. # The Qubes OS Project, http://www.qubes-os.org
  4. #
  5. # Copyright (C) 2016 Bahtiar `kalkin-` Gadimov <bahtiar@gadimov.de>
  6. #
  7. # This program is free software; you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation; either version 2 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # This program is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License along
  18. # with this program; if not, write to the Free Software Foundation, Inc.,
  19. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  20. '''Qubes volume and block device managment'''
  21. from __future__ import print_function
  22. import sys
  23. import qubes
  24. import qubes.exc
  25. import qubes.tools
  26. import qubes.utils
  27. def prepare_table(vd_list, full=False):
  28. ''' Converts a list of :py:class:`VolumeData` objects to a list of tupples
  29. for the :py:func:`qubes.tools.print_table`.
  30. If :program:`qvm-block` is running in a TTY, it will ommit duplicate
  31. data.
  32. :param list vd_list: List of :py:class:`VolumeData` objects.
  33. :param bool full: If set to true duplicate data is printed even when
  34. running from TTY.
  35. :returns: list of tupples
  36. '''
  37. output = []
  38. if sys.stdout.isatty():
  39. # NOQA
  40. output += [('POOL:VOLUME', 'VMNAME', 'VOLUME_NAME', 'REVERT_POSSIBLE')]
  41. for volume in vd_list:
  42. if volume.domains:
  43. vmname, volume_name = volume.domains.pop()
  44. output += [(str(volume), vmname, volume_name, volume.revisions)]
  45. for tupple in volume.domains:
  46. vmname, volume_name = tupple
  47. if full or not sys.stdout.isatty():
  48. output += [(str(volume), vmname, volume_name,
  49. volume.revisions)]
  50. else:
  51. output += [('', vmname, volume_name, '', volume.revisions)]
  52. else:
  53. output += [(str(volume), "")]
  54. return output
  55. class VolumeData(object):
  56. ''' Wrapper object around :py:class:`qubes.storage.Volume`, mainly to track
  57. the domains a volume is attached to.
  58. '''
  59. # pylint: disable=too-few-public-methods
  60. def __init__(self, volume):
  61. self.name = volume.name
  62. self.pool = volume.pool
  63. self.vid = volume.vid
  64. if volume.revisions != {}:
  65. self.revisions = 'Yes'
  66. else:
  67. self.revisions = 'No'
  68. self.domains = []
  69. def __str__(self):
  70. return "{!s}:{!s}".format(self.pool, self.vid)
  71. def list_volumes(args):
  72. ''' Called by the parser to execute the qubes-block list subcommand. '''
  73. app = args.app
  74. if args.pools:
  75. pools = args.pools # only specified pools
  76. else:
  77. pools = app.pools.values() # all pools
  78. volumes = [v for p in pools for v in p.volumes]
  79. if not args.internal: # hide internal volumes
  80. volumes = [v for v in volumes if not v.internal]
  81. vd_dict = {}
  82. for volume in volumes:
  83. volume_data = VolumeData(volume)
  84. try:
  85. vd_dict[volume.pool][volume.vid] = volume_data
  86. except KeyError:
  87. vd_dict[volume.pool] = {volume.vid: volume_data}
  88. if hasattr(args, 'domains') and args.domains:
  89. domains = args.domains
  90. else:
  91. domains = args.app.domains
  92. for domain in domains: # gather the domain names
  93. try:
  94. for volume in domain.attached_volumes:
  95. try:
  96. if not args.internal and volume.internal:
  97. # some pools (LVM) may set 'internal' flag only when
  98. # listing volumes of specific domain
  99. del vd_dict[volume.pool][volume.vid]
  100. else:
  101. volume_data = vd_dict[volume.pool][volume.vid]
  102. volume_data.domains += [(domain.name, volume.name)]
  103. except KeyError:
  104. # Skipping volume
  105. continue
  106. except AttributeError:
  107. # Skipping domain without volumes
  108. continue
  109. if hasattr(args, 'domains') and args.domains:
  110. result = [x # reduce to only VolumeData with assigned domains
  111. for p in vd_dict.values() for x in p.values()
  112. if x.domains]
  113. else:
  114. result = [x for p in vd_dict.values() for x in p.values()]
  115. qubes.tools.print_table(prepare_table(result, full=args.full))
  116. def revert_volume(args):
  117. volume = args.volume
  118. app = args.app
  119. try:
  120. pool = app.pools[volume.pool]
  121. pool.revert(volume)
  122. except qubes.storage.StoragePoolException as e:
  123. print(str(e), file=sys.stderr)
  124. sys.exit(1)
  125. def attach_volumes(args):
  126. ''' Called by the parser to execute the :program:`qvm-block attach`
  127. subcommand.
  128. '''
  129. volume = args.volume
  130. vm = args.domains[0]
  131. try:
  132. rw = not args.ro
  133. vm.storage.attach(volume, rw=rw)
  134. except qubes.storage.StoragePoolException as e:
  135. print(str(e), file=sys.stderr)
  136. sys.exit(1)
  137. def detach_volumes(args):
  138. ''' Called by the parser to execute the :program:`qvm-block detach`
  139. subcommand.
  140. '''
  141. volume = args.volume
  142. vm = args.domains[0]
  143. try:
  144. vm.storage.detach(volume)
  145. except qubes.storage.StoragePoolException as e:
  146. print(str(e), file=sys.stderr)
  147. sys.exit(1)
  148. def extend_volumes(args):
  149. ''' Called by the parser to execute the :program:`qvm-block extend`
  150. subcommand
  151. '''
  152. volume = args.volume
  153. app = args.app
  154. size = qubes.utils.parse_size(args.size)
  155. pool = app.get_pool(volume.pool)
  156. pool.resize(volume, volume.size+size)
  157. app.save()
  158. def init_list_parser(sub_parsers):
  159. ''' Configures the parser for the :program:`qvm-block list` subcommand '''
  160. # pylint: disable=protected-access
  161. list_parser = sub_parsers.add_parser('list', aliases=('ls', 'l'),
  162. help='list block devices')
  163. list_parser.add_argument('-p', '--pool', dest='pools',
  164. action=qubes.tools.PoolsAction)
  165. list_parser.add_argument('-i', '--internal', action='store_true',
  166. help='Show internal volumes')
  167. list_parser.add_argument(
  168. '--full', action='store_true',
  169. help='print full line for each POOL_NAME:VOLUME_ID & vm combination')
  170. vm_name_group = qubes.tools.VmNameGroup(
  171. list_parser, required=False, vm_action=qubes.tools.VmNameAction,
  172. help='list volumes from specified domain(s)')
  173. list_parser._mutually_exclusive_groups.append(vm_name_group)
  174. list_parser.set_defaults(func=list_volumes)
  175. def init_revert_parser(sub_parsers):
  176. revert_parser = sub_parsers.add_parser(
  177. 'revert', aliases=('rv', 'r'),
  178. help='revert volume to previous revision')
  179. revert_parser.add_argument(metavar='POOL_NAME:VOLUME_ID', dest='volume',
  180. action=qubes.tools.VolumeAction)
  181. revert_parser.set_defaults(func=revert_volume)
  182. def init_attach_parser(sub_parsers):
  183. attach_parser = sub_parsers.add_parser(
  184. 'attach', help="Attach volume to domain", aliases=('at', 'a'))
  185. attach_parser.add_argument('--ro', help='attach device read-only',
  186. action='store_true')
  187. attach_parser.add_argument('VMNAME', action=qubes.tools.RunningVmNameAction)
  188. attach_parser.add_argument(metavar='POOL_NAME:VOLUME_ID', dest='volume',
  189. action=qubes.tools.VolumeAction)
  190. attach_parser.set_defaults(func=attach_volumes)
  191. def init_dettach_parser(sub_parsers):
  192. detach_parser = sub_parsers.add_parser(
  193. "detach", help="Detach volume from domain", aliases=('d', 'dt'))
  194. detach_parser.add_argument('VMNAME', action=qubes.tools.RunningVmNameAction)
  195. detach_parser.add_argument(metavar='POOL_NAME:VOLUME_ID', dest='volume',
  196. action=qubes.tools.VolumeAction)
  197. detach_parser.set_defaults(func=detach_volumes)
  198. def init_extend_parser(sub_parsers):
  199. extend_parser = sub_parsers.add_parser(
  200. "extend", help="extend volume from domain", aliases=('d', 'dt'))
  201. extend_parser.add_argument(metavar='POOL_NAME:VOLUME_ID', dest='volume',
  202. action=qubes.tools.VolumeAction)
  203. extend_parser.add_argument('size', help='New size in bytes')
  204. extend_parser.set_defaults(func=extend_volumes)
  205. def get_parser():
  206. '''Create :py:class:`argparse.ArgumentParser` suitable for
  207. :program:`qvm-block`.
  208. '''
  209. parser = qubes.tools.QubesArgumentParser(description=__doc__, want_app=True)
  210. parser.register('action', 'parsers', qubes.tools.AliasedSubParsersAction)
  211. sub_parsers = parser.add_subparsers(
  212. title='commands',
  213. description="For more information see qvm-block command -h",
  214. dest='command')
  215. init_attach_parser(sub_parsers)
  216. init_dettach_parser(sub_parsers)
  217. init_extend_parser(sub_parsers)
  218. init_list_parser(sub_parsers)
  219. init_revert_parser(sub_parsers)
  220. return parser
  221. def main(args=None):
  222. '''Main routine of :program:`qvm-block`.'''
  223. parser = get_parser()
  224. try:
  225. args = parser.parse_args(args)
  226. args.func(args)
  227. except qubes.exc.QubesException as e:
  228. parser.print_error(str(e))
  229. return 1
  230. if __name__ == '__main__':
  231. sys.exit(main())