qvm_volume.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. # encoding=utf-8
  2. #
  3. # The Qubes OS Project, http://www.qubes-os.org
  4. #
  5. # Copyright (C) 2016 Bahtiar `kalkin-` Gadimov <bahtiar@gadimov.de>
  6. # Copyright (C) 2017 Marek Marczykowski-Górecki
  7. # <marmarek@invisiblethingslab.com>
  8. #
  9. # This program is free software; you can redistribute it and/or modify
  10. # it under the terms of the GNU Lesser General Public License as published by
  11. # the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU Lesser General Public License along
  20. # with this program; if not, see <http://www.gnu.org/licenses/>.
  21. '''Qubes volume management'''
  22. from __future__ import print_function
  23. import argparse
  24. import os
  25. import sys
  26. import collections
  27. import qubesadmin
  28. import qubesadmin.exc
  29. import qubesadmin.tools
  30. import qubesadmin.utils
  31. def prepare_table(vd_list, full=False):
  32. ''' Converts a list of :py:class:`VolumeData` objects to a list of tupples
  33. for the :py:func:`qubes.tools.print_table`.
  34. If :program:`qvm-volume` is running in a TTY, it will ommit duplicate
  35. data.
  36. :param list vd_list: List of :py:class:`VolumeData` objects.
  37. :param bool full: If set to true duplicate data is printed even when
  38. running from TTY.
  39. :returns: list of tupples
  40. '''
  41. output = []
  42. output += [('POOL:VOLUME', 'VMNAME', 'VOLUME_NAME', 'REVERT_POSSIBLE')]
  43. for volume in sorted(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.pool = volume.pool
  64. self.vid = volume.vid
  65. if volume.revisions:
  66. self.revisions = 'Yes'
  67. else:
  68. self.revisions = 'No'
  69. self.domains = []
  70. def __lt__(self, other):
  71. return (self.pool, self.vid) < (other.pool, other.vid)
  72. def __str__(self):
  73. return "{!s}:{!s}".format(self.pool, self.vid)
  74. def info_volume(args):
  75. ''' Show info about selected volume '''
  76. volume = args.volume
  77. info_items = ('pool', 'vid', 'rw', 'source', 'save_on_stop',
  78. 'snap_on_start', 'size', 'usage', 'revisions_to_keep')
  79. if args.property:
  80. if args.property == 'revisions':
  81. for rev in volume.revisions:
  82. print(rev)
  83. elif args.property == 'is_outdated':
  84. print(volume.is_outdated())
  85. elif args.property in info_items:
  86. value = getattr(volume, args.property)
  87. if value is None:
  88. value = ''
  89. print(value)
  90. else:
  91. raise qubesadmin.exc.StoragePoolException(
  92. 'No such property: {}'.format(args.property))
  93. else:
  94. info = collections.OrderedDict()
  95. for item in info_items:
  96. value = getattr(volume, item)
  97. if value is None:
  98. value = ''
  99. info[item] = str(value)
  100. info['is_outdated'] = str(volume.is_outdated())
  101. qubesadmin.tools.print_table(info.items())
  102. revisions = volume.revisions
  103. if revisions:
  104. print('Available revisions (for revert):')
  105. for rev in revisions:
  106. print(' ' + rev)
  107. else:
  108. print('Available revisions (for revert): none')
  109. def config_volume(args):
  110. ''' Change property of selected volume '''
  111. volume = args.volume
  112. if not args.property in ('rw', 'revisions_to_keep'):
  113. raise qubesadmin.exc.QubesNoSuchPropertyError(
  114. 'Invalid property: {}'.format(args.property))
  115. setattr(volume, args.property, args.value)
  116. def import_volume(args):
  117. ''' Import a file into volume '''
  118. volume = args.volume
  119. input_path = args.input_path
  120. if input_path == '-':
  121. input_file = sys.stdin.buffer
  122. else:
  123. input_file = open(input_path, 'rb')
  124. try:
  125. if args.no_resize:
  126. volume.import_data(stream=input_file)
  127. else:
  128. if args.size:
  129. size = args.size
  130. else:
  131. try:
  132. size = os.stat(input_file.fileno()).st_size
  133. except OSError as e:
  134. raise qubesadmin.exc.QubesException(
  135. 'Failed to get %s file size, '
  136. 'specify it explicitly with --size, '
  137. 'or use --no-resize option', str(e))
  138. volume.import_data_with_size(stream=input_file, size=size)
  139. finally:
  140. if input_path != '-':
  141. input_file.close()
  142. def list_volumes(args):
  143. ''' Called by the parser to execute the qvm-volume list subcommand. '''
  144. app = args.app
  145. if hasattr(args, 'domains') and args.domains:
  146. domains = args.domains
  147. else:
  148. domains = app.domains
  149. volumes = [v for vm in domains for v in vm.volumes.values()]
  150. if getattr(args, 'pools', None):
  151. # only specified pools
  152. volumes = [v for v in volumes if v.pool in args.pools]
  153. vd_dict = {}
  154. for volume in volumes:
  155. volume_data = VolumeData(volume)
  156. try:
  157. vd_dict[volume.pool][volume.vid] = volume_data
  158. except KeyError:
  159. vd_dict[volume.pool] = {volume.vid: volume_data}
  160. for domain in domains: # gather the domain names
  161. try:
  162. for name, volume in domain.volumes.items():
  163. try:
  164. volume_data = vd_dict[volume.pool][volume.vid]
  165. volume_data.domains += [(domain.name, name)]
  166. except KeyError:
  167. # Skipping volume
  168. continue
  169. except AttributeError:
  170. # Skipping domain without volumes
  171. continue
  172. if hasattr(args, 'domains') and args.domains:
  173. result = [x # reduce to only VolumeData with assigned domains
  174. for p in vd_dict.values() for x in p.values()
  175. if x.domains]
  176. else:
  177. result = [x for p in vd_dict.values() for x in p.values()]
  178. qubesadmin.tools.print_table(
  179. prepare_table(result, full=getattr(args, 'full', False)))
  180. def revert_volume(args):
  181. ''' Revert volume to previous state '''
  182. volume = args.volume
  183. if args.revision:
  184. revision = args.revision
  185. else:
  186. revisions = volume.revisions
  187. if not revisions:
  188. raise qubesadmin.exc.StoragePoolException(
  189. 'No snapshots available')
  190. revision = volume.revisions[-1]
  191. volume.revert(revision)
  192. def extend_volumes(args):
  193. ''' Called by the parser to execute the :program:`qvm-block extend`
  194. subcommand
  195. '''
  196. volume = args.volume
  197. size = qubesadmin.utils.parse_size(args.size)
  198. if not args.force and size < volume.size:
  199. raise qubesadmin.exc.StoragePoolException(
  200. 'For your own safety, shrinking of %s is'
  201. ' disabled (%d < %d). If you really know what you'
  202. ' are doing, resize filesystem manually first, then use `-f` '
  203. 'option.' %
  204. (volume.name, size, volume.size))
  205. volume.resize(size)
  206. def init_list_parser(sub_parsers):
  207. ''' Configures the parser for the :program:`qvm-block list` subcommand '''
  208. # pylint: disable=protected-access
  209. list_parser = sub_parsers.add_parser('list', aliases=('ls', 'l'),
  210. help='list storage volumes')
  211. list_parser.add_argument('-p', '--pool', dest='pools',
  212. action=qubesadmin.tools.PoolsAction)
  213. list_parser.add_argument(
  214. '--full', action='store_true',
  215. help='print full line for each POOL_NAME:VOLUME_ID & vm combination')
  216. vm_name_group = qubesadmin.tools.VmNameGroup(
  217. list_parser, required=False, vm_action=qubesadmin.tools.VmNameAction,
  218. help='list volumes from specified domain(s)')
  219. list_parser._mutually_exclusive_groups.append(vm_name_group)
  220. list_parser.set_defaults(func=list_volumes)
  221. def init_revert_parser(sub_parsers):
  222. ''' Add 'revert' action related options '''
  223. revert_parser = sub_parsers.add_parser(
  224. 'revert', aliases=('rv', 'r'),
  225. help='revert volume to previous revision')
  226. revert_parser.add_argument(metavar='VM:VOLUME', dest='volume',
  227. action=qubesadmin.tools.VMVolumeAction)
  228. revert_parser.add_argument(metavar='REVISION', dest='revision',
  229. help='Optional revision to revert to; '
  230. 'if not specified, latest one is assumed',
  231. action='store', nargs='?')
  232. revert_parser.set_defaults(func=revert_volume)
  233. def init_extend_parser(sub_parsers):
  234. ''' Add 'extend' action related options '''
  235. extend_parser = sub_parsers.add_parser(
  236. "resize", aliases=('extend', ), help="resize volume for domain")
  237. extend_parser.add_argument(metavar='VM:VOLUME', dest='volume',
  238. action=qubesadmin.tools.VMVolumeAction)
  239. extend_parser.add_argument('size', help='New size in bytes')
  240. extend_parser.add_argument('--force', '-f', action='store_true',
  241. help='Force operation, even if new size is smaller than the current '
  242. 'one')
  243. extend_parser.set_defaults(func=extend_volumes)
  244. def init_info_parser(sub_parsers):
  245. ''' Add 'info' action related options '''
  246. info_parser = sub_parsers.add_parser(
  247. 'info', aliases=('i',), help='info about volume')
  248. info_parser.add_argument(metavar='VM:VOLUME', dest='volume',
  249. action=qubesadmin.tools.VMVolumeAction)
  250. info_parser.add_argument(dest='property', action='store',
  251. nargs=argparse.OPTIONAL,
  252. help='Show only this property instead of all of them; use '
  253. '\'revisions\' to list available revisions')
  254. info_parser.set_defaults(func=info_volume)
  255. def init_config_parser(sub_parsers):
  256. ''' Add 'info' action related options '''
  257. info_parser = sub_parsers.add_parser(
  258. 'config', aliases=('c', 'set', 's'),
  259. help='set config option for a volume')
  260. info_parser.add_argument(metavar='VM:VOLUME', dest='volume',
  261. action=qubesadmin.tools.VMVolumeAction)
  262. info_parser.add_argument(dest='property', action='store')
  263. info_parser.add_argument(dest='value', action='store')
  264. info_parser.set_defaults(func=config_volume)
  265. def init_import_parser(sub_parsers):
  266. ''' Add 'import' action related options '''
  267. import_parser = sub_parsers.add_parser(
  268. 'import', help='import volume data')
  269. import_parser.add_argument(metavar='VM:VOLUME', dest='volume',
  270. action=qubesadmin.tools.VMVolumeAction)
  271. import_parser.add_argument('input_path', metavar='PATH',
  272. help='File path to import, use \'-\' for standard input')
  273. import_parser.add_argument('--size', action='store', type=int,
  274. help='Set volume size to this value in bytes')
  275. import_parser.add_argument('--no-resize', action='store_true',
  276. help='Do not resize volume before importing data')
  277. import_parser.set_defaults(func=import_volume)
  278. def get_parser():
  279. '''Create :py:class:`argparse.ArgumentParser` suitable for
  280. :program:`qvm-volume`.
  281. '''
  282. parser = qubesadmin.tools.QubesArgumentParser(description=__doc__)
  283. parser.register('action', 'parsers',
  284. qubesadmin.tools.AliasedSubParsersAction)
  285. sub_parsers = parser.add_subparsers(
  286. title='commands',
  287. description="For more information see qvm-volume command -h",
  288. dest='command')
  289. init_info_parser(sub_parsers)
  290. init_config_parser(sub_parsers)
  291. init_extend_parser(sub_parsers)
  292. init_list_parser(sub_parsers)
  293. init_revert_parser(sub_parsers)
  294. init_import_parser(sub_parsers)
  295. # default action
  296. parser.set_defaults(func=list_volumes)
  297. return parser
  298. def main(args=None, app=None):
  299. '''Main routine of :program:`qvm-volume`.'''
  300. parser = get_parser()
  301. try:
  302. args = parser.parse_args(args, app=app)
  303. args.func(args)
  304. except qubesadmin.exc.QubesException as e:
  305. parser.print_error(str(e))
  306. return 1
  307. return 0
  308. if __name__ == '__main__':
  309. sys.exit(main())