qvm_volume.py 13 KB

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