qvm_volume.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  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. old_size = volume.size
  120. input_path = args.input_path
  121. if input_path == '-':
  122. input_file = sys.stdin.buffer
  123. else:
  124. input_file = open(input_path, 'rb')
  125. try:
  126. if args.no_resize:
  127. volume.import_data(stream=input_file)
  128. else:
  129. if args.size:
  130. size = args.size
  131. else:
  132. try:
  133. size = os.stat(input_file.fileno()).st_size
  134. except OSError as e:
  135. raise qubesadmin.exc.QubesException(
  136. 'Failed to get %s file size, '
  137. 'specify it explicitly with --size, '
  138. 'or use --no-resize option', str(e))
  139. volume.import_data_with_size(stream=input_file, size=size)
  140. finally:
  141. if input_path != '-':
  142. input_file.close()
  143. def list_volumes(args):
  144. ''' Called by the parser to execute the qvm-volume list subcommand. '''
  145. app = args.app
  146. if hasattr(args, 'domains') and args.domains:
  147. domains = args.domains
  148. else:
  149. domains = app.domains
  150. volumes = [v for vm in domains for v in vm.volumes.values()]
  151. if getattr(args, 'pools', None):
  152. # only specified pools
  153. volumes = [v for v in volumes if v.pool in args.pools]
  154. vd_dict = {}
  155. for volume in volumes:
  156. volume_data = VolumeData(volume)
  157. try:
  158. vd_dict[volume.pool][volume.vid] = volume_data
  159. except KeyError:
  160. vd_dict[volume.pool] = {volume.vid: volume_data}
  161. for domain in domains: # gather the domain names
  162. try:
  163. for name, volume in domain.volumes.items():
  164. try:
  165. volume_data = vd_dict[volume.pool][volume.vid]
  166. volume_data.domains += [(domain.name, name)]
  167. except KeyError:
  168. # Skipping volume
  169. continue
  170. except AttributeError:
  171. # Skipping domain without volumes
  172. continue
  173. if hasattr(args, 'domains') and args.domains:
  174. result = [x # reduce to only VolumeData with assigned domains
  175. for p in vd_dict.values() for x in p.values()
  176. if x.domains]
  177. else:
  178. result = [x for p in vd_dict.values() for x in p.values()]
  179. qubesadmin.tools.print_table(
  180. prepare_table(result, full=getattr(args, 'full', False)))
  181. def revert_volume(args):
  182. ''' Revert volume to previous state '''
  183. volume = args.volume
  184. if args.revision:
  185. revision = args.revision
  186. else:
  187. revisions = volume.revisions
  188. if not revisions:
  189. raise qubesadmin.exc.StoragePoolException(
  190. 'No snapshots available')
  191. revision = volume.revisions[-1]
  192. volume.revert(revision)
  193. def extend_volumes(args):
  194. ''' Called by the parser to execute the :program:`qvm-block extend`
  195. subcommand
  196. '''
  197. volume = args.volume
  198. size = qubesadmin.utils.parse_size(args.size)
  199. if not args.force and size < volume.size:
  200. raise qubesadmin.exc.StoragePoolException(
  201. 'For your own safety, shrinking of %s is'
  202. ' disabled (%d < %d). If you really know what you'
  203. ' are doing, resize filesystem manually first, then use `-f` '
  204. 'option.' %
  205. (volume.name, size, volume.size))
  206. volume.resize(size)
  207. def init_list_parser(sub_parsers):
  208. ''' Configures the parser for the :program:`qvm-block list` subcommand '''
  209. # pylint: disable=protected-access
  210. list_parser = sub_parsers.add_parser('list', aliases=('ls', 'l'),
  211. help='list storage volumes')
  212. list_parser.add_argument('-p', '--pool', dest='pools',
  213. action=qubesadmin.tools.PoolsAction)
  214. list_parser.add_argument(
  215. '--full', action='store_true',
  216. help='print full line for each POOL_NAME:VOLUME_ID & vm combination')
  217. vm_name_group = qubesadmin.tools.VmNameGroup(
  218. list_parser, required=False, vm_action=qubesadmin.tools.VmNameAction,
  219. help='list volumes from specified domain(s)')
  220. list_parser._mutually_exclusive_groups.append(vm_name_group)
  221. list_parser.set_defaults(func=list_volumes)
  222. def init_revert_parser(sub_parsers):
  223. ''' Add 'revert' action related options '''
  224. revert_parser = sub_parsers.add_parser(
  225. 'revert', aliases=('rv', 'r'),
  226. help='revert volume to previous revision')
  227. revert_parser.add_argument(metavar='VM:VOLUME', dest='volume',
  228. action=qubesadmin.tools.VMVolumeAction)
  229. revert_parser.add_argument(metavar='REVISION', dest='revision',
  230. help='Optional revision to revert to; '
  231. 'if not specified, latest one is assumed',
  232. action='store', nargs='?')
  233. revert_parser.set_defaults(func=revert_volume)
  234. def init_extend_parser(sub_parsers):
  235. ''' Add 'extend' action related options '''
  236. extend_parser = sub_parsers.add_parser(
  237. "resize", aliases=('extend', ), help="resize volume for domain")
  238. extend_parser.add_argument(metavar='VM:VOLUME', dest='volume',
  239. action=qubesadmin.tools.VMVolumeAction)
  240. extend_parser.add_argument('size', help='New size in bytes')
  241. extend_parser.add_argument('--force', '-f', action='store_true',
  242. help='Force operation, even if new size is smaller than the current '
  243. 'one')
  244. extend_parser.set_defaults(func=extend_volumes)
  245. def init_info_parser(sub_parsers):
  246. ''' Add 'info' action related options '''
  247. info_parser = sub_parsers.add_parser(
  248. 'info', aliases=('i',), help='info about volume')
  249. info_parser.add_argument(metavar='VM:VOLUME', dest='volume',
  250. action=qubesadmin.tools.VMVolumeAction)
  251. info_parser.add_argument(dest='property', action='store',
  252. nargs=argparse.OPTIONAL,
  253. help='Show only this property instead of all of them; use '
  254. '\'revisions\' to list available revisions')
  255. info_parser.set_defaults(func=info_volume)
  256. def init_config_parser(sub_parsers):
  257. ''' Add 'info' action related options '''
  258. info_parser = sub_parsers.add_parser(
  259. 'config', aliases=('c', 'set', 's'),
  260. help='set config option for a volume')
  261. info_parser.add_argument(metavar='VM:VOLUME', dest='volume',
  262. action=qubesadmin.tools.VMVolumeAction)
  263. info_parser.add_argument(dest='property', action='store')
  264. info_parser.add_argument(dest='value', action='store')
  265. info_parser.set_defaults(func=config_volume)
  266. def init_import_parser(sub_parsers):
  267. ''' Add 'import' action related options '''
  268. import_parser = sub_parsers.add_parser(
  269. 'import', help='import volume data')
  270. import_parser.add_argument(metavar='VM:VOLUME', dest='volume',
  271. action=qubesadmin.tools.VMVolumeAction)
  272. import_parser.add_argument('input_path', metavar='PATH',
  273. help='File path to import, use \'-\' for standard input')
  274. import_parser.add_argument('--size', action='store', type=int,
  275. help='Set volume size to this value in bytes')
  276. import_parser.add_argument('--no-resize', action='store_true',
  277. help='Do not resize volume before importing data')
  278. import_parser.set_defaults(func=import_volume)
  279. def get_parser():
  280. '''Create :py:class:`argparse.ArgumentParser` suitable for
  281. :program:`qvm-volume`.
  282. '''
  283. parser = qubesadmin.tools.QubesArgumentParser(description=__doc__,
  284. want_app=True)
  285. parser.register('action', 'parsers',
  286. qubesadmin.tools.AliasedSubParsersAction)
  287. sub_parsers = parser.add_subparsers(
  288. title='commands',
  289. description="For more information see qvm-volume command -h",
  290. dest='command')
  291. init_info_parser(sub_parsers)
  292. init_config_parser(sub_parsers)
  293. init_extend_parser(sub_parsers)
  294. init_list_parser(sub_parsers)
  295. init_revert_parser(sub_parsers)
  296. init_import_parser(sub_parsers)
  297. # default action
  298. parser.set_defaults(func=list_volumes)
  299. return parser
  300. def main(args=None, app=None):
  301. '''Main routine of :program:`qvm-volume`.'''
  302. parser = get_parser()
  303. try:
  304. args = parser.parse_args(args, app=app)
  305. args.func(args)
  306. except qubesadmin.exc.QubesException as e:
  307. parser.print_error(str(e))
  308. return 1
  309. return 0
  310. if __name__ == '__main__':
  311. sys.exit(main())