__init__.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. #!/usr/bin/python2 -O
  2. # vim: fileencoding=utf-8
  3. #
  4. # The Qubes OS Project, https://www.qubes-os.org/
  5. #
  6. # Copyright (C) 2015 Joanna Rutkowska <joanna@invisiblethingslab.com>
  7. # Copyright (C) 2015 Wojtek Porczyk <woju@invisiblethingslab.com>
  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. #
  23. '''Qubes' command line tools
  24. '''
  25. from __future__ import print_function
  26. import argparse
  27. import importlib
  28. import logging
  29. import os
  30. import subprocess
  31. import sys
  32. import textwrap
  33. import qubes.log
  34. #: constant returned when some action should be performed on all qubes
  35. VM_ALL = object()
  36. class QubesAction(argparse.Action):
  37. ''' Interface providing a convinience method to be called, after
  38. `namespace.app` is instantiated.
  39. '''
  40. # pylint: disable=too-few-public-methods
  41. def parse_qubes_app(self, parser, namespace):
  42. ''' This method is called by :py:class:`qubes.tools.QubesArgumentParser`
  43. after the `namespace.app` is instantiated. Oerwrite this method when
  44. extending :py:class:`qubes.tools.QubesAction` to initialized values
  45. based on the `namespace.app`
  46. '''
  47. raise NotImplementedError
  48. class PropertyAction(argparse.Action):
  49. '''Action for argument parser that stores a property.'''
  50. # pylint: disable=redefined-builtin,too-few-public-methods
  51. def __init__(self,
  52. option_strings,
  53. dest,
  54. metavar='NAME=VALUE',
  55. required=False,
  56. help='set property to a value'):
  57. super(PropertyAction, self).__init__(option_strings, 'properties',
  58. metavar=metavar, default={}, help=help)
  59. def __call__(self, parser, namespace, values, option_string=None):
  60. try:
  61. prop, value = values.split('=', 1)
  62. except ValueError:
  63. parser.error('invalid property token: {!r}'.format(values))
  64. getattr(namespace, self.dest)[prop] = value
  65. class SinglePropertyAction(argparse.Action):
  66. '''Action for argument parser that stores a property.'''
  67. # pylint: disable=redefined-builtin,too-few-public-methods
  68. def __init__(self,
  69. option_strings,
  70. dest,
  71. metavar='VALUE',
  72. const=None,
  73. nargs=None,
  74. required=False,
  75. help=None):
  76. if help is None:
  77. help = 'set {!r} property to a value'.format(dest)
  78. if const is not None:
  79. help += ' {!r}'.format(const)
  80. if const is not None:
  81. nargs = 0
  82. super(SinglePropertyAction, self).__init__(option_strings, 'properties',
  83. metavar=metavar, help=help, default={}, const=const,
  84. nargs=nargs)
  85. self.name = dest
  86. def __call__(self, parser, namespace, values, option_string=None):
  87. getattr(namespace, self.dest)[self.name] = values \
  88. if self.const is None else self.const
  89. class HelpPropertiesAction(argparse.Action):
  90. '''Action for argument parser that displays all properties and exits.'''
  91. # pylint: disable=redefined-builtin,too-few-public-methods
  92. def __init__(self,
  93. option_strings,
  94. klass=None,
  95. dest=argparse.SUPPRESS,
  96. default=argparse.SUPPRESS,
  97. help='list all available properties with short descriptions'
  98. ' and exit'):
  99. super(HelpPropertiesAction, self).__init__(
  100. option_strings=option_strings,
  101. dest=dest,
  102. default=default,
  103. nargs=0,
  104. help=help)
  105. # late import because of circular dependency
  106. import qubes # pylint: disable=redefined-outer-name
  107. self._klass = klass if klass is not None else qubes.Qubes
  108. def __call__(self, parser, namespace, values, option_string=None):
  109. # pylint: disable=redefined-outer-name
  110. properties = self._klass.property_list()
  111. width = max(len(prop.__name__) for prop in properties)
  112. wrapper = textwrap.TextWrapper(width=80,
  113. initial_indent=' ', subsequent_indent=' ' * (width + 6))
  114. text = 'Common properties:\n' + '\n'.join(
  115. wrapper.fill('{name:{width}s} {doc}'.format(
  116. name=prop.__name__,
  117. doc=qubes.utils.format_doc(prop.__doc__) if prop.__doc__ else'',
  118. width=width))
  119. for prop in sorted(properties))
  120. if self._klass is not qubes.Qubes:
  121. text += '\n\n' \
  122. 'There may be more properties in specific domain classes.\n'
  123. parser.exit(message=text)
  124. class VmNameAction(QubesAction):
  125. ''' Action for parsing one ore multiple domains from provided VMNAMEs '''
  126. # pylint: disable=too-few-public-methods,redefined-builtin
  127. def __init__(self, option_strings, nargs=1, dest='vmnames', help=None,
  128. **kwargs):
  129. if help is None:
  130. if nargs == argparse.OPTIONAL:
  131. help = 'at most one domain name'
  132. elif nargs == 1:
  133. help = 'a domain name'
  134. elif nargs == argparse.ZERO_OR_MORE:
  135. help = 'zero or more domain names'
  136. elif nargs == argparse.ONE_OR_MORE:
  137. help = 'one or more domain names'
  138. elif nargs > 1:
  139. help = '%s domain names' % nargs
  140. else:
  141. raise argparse.ArgumentError(
  142. nargs, "Passed unexpected value {!s} as {!s} nargs ".format(
  143. nargs, dest))
  144. super(VmNameAction, self).__init__(option_strings, dest=dest, help=help,
  145. nargs=nargs, **kwargs)
  146. def __call__(self, parser, namespace, values, option_string=None):
  147. ''' Set ``namespace.vmname`` to ``values`` '''
  148. setattr(namespace, self.dest, values)
  149. def parse_qubes_app(self, parser, namespace):
  150. assert hasattr(namespace, 'app')
  151. setattr(namespace, 'domains', [])
  152. app = namespace.app
  153. if hasattr(namespace, 'all_domains') and namespace.all_domains:
  154. namespace.domains = [
  155. vm
  156. for vm in app.domains
  157. if vm.qid != 0 and vm.name not in namespace.exclude
  158. ]
  159. else:
  160. if hasattr(namespace, 'exclude') and namespace.exclude:
  161. parser.error('--exclude can only be used with --all')
  162. for vm_name in getattr(namespace, self.dest):
  163. try:
  164. namespace.domains += [app.domains[vm_name]]
  165. except KeyError:
  166. parser.error('no such domain: {!r}'.format(vm_name))
  167. class RunningVmNameAction(VmNameAction):
  168. ''' Action for argument parser that gets a running domain from VMNAME '''
  169. # pylint: disable=too-few-public-methods
  170. def __init__(self, option_strings, nargs=1, dest='vmnames', help=None,
  171. **kwargs):
  172. # pylint: disable=redefined-builtin
  173. if help is None:
  174. if nargs == argparse.OPTIONAL:
  175. help = 'at most one running domain'
  176. elif nargs == 1:
  177. help = 'running domain name'
  178. elif nargs == argparse.ZERO_OR_MORE:
  179. help = 'zero or more running domains'
  180. elif nargs == argparse.ONE_OR_MORE:
  181. help = 'one or more running domains'
  182. elif nargs > 1:
  183. help = '%s running domains' % nargs
  184. else:
  185. raise argparse.ArgumentError(
  186. nargs, "Passed unexpected value {!s} as {!s} nargs ".format(
  187. nargs, dest))
  188. super(RunningVmNameAction, self).__init__(
  189. option_strings, dest=dest, help=help, nargs=nargs, **kwargs)
  190. def parse_qubes_app(self, parser, namespace):
  191. super(RunningVmNameAction, self).parse_qubes_app(parser, namespace)
  192. for vm in namespace.domains:
  193. if not vm.is_running():
  194. parser.error_runtime("domain {!r} is not running".format(
  195. vm.name))
  196. class VolumeAction(QubesAction):
  197. ''' Action for argument parser that gets the
  198. :py:class:``qubes.storage.Volume`` from a POOL_NAME:VOLUME_ID string.
  199. '''
  200. # pylint: disable=too-few-public-methods
  201. def __init__(self, help='A pool & volume id combination',
  202. required=True, **kwargs):
  203. # pylint: disable=redefined-builtin
  204. super(VolumeAction, self).__init__(help=help, required=required,
  205. **kwargs)
  206. def __call__(self, parser, namespace, values, option_string=None):
  207. ''' Set ``namespace.vmname`` to ``values`` '''
  208. setattr(namespace, self.dest, values)
  209. def parse_qubes_app(self, parser, namespace):
  210. ''' Acquire the :py:class:``qubes.storage.Volume`` object from
  211. ``namespace.app``.
  212. '''
  213. assert hasattr(namespace, 'app')
  214. app = namespace.app
  215. try:
  216. pool_name, vid = getattr(namespace, self.dest).split(':')
  217. try:
  218. pool = app.pools[pool_name]
  219. volume = [v for v in pool.volumes if v.vid == vid]
  220. assert volume > 1, 'Duplicate vids in pool %s' % pool_name
  221. if len(volume) == 0:
  222. parser.error_runtime(
  223. 'no volume with id {!r} pool: {!r}'.format(vid,
  224. pool_name))
  225. else:
  226. setattr(namespace, self.dest, volume[0])
  227. except KeyError:
  228. parser.error_runtime('no pool {!r}'.format(pool_name))
  229. except ValueError:
  230. parser.error('expected a pool & volume id combination like foo:bar')
  231. class PoolsAction(QubesAction):
  232. ''' Action for argument parser to gather multiple pools '''
  233. # pylint: disable=too-few-public-methods
  234. def __call__(self, parser, namespace, values, option_string=None):
  235. ''' Set ``namespace.vmname`` to ``values`` '''
  236. if hasattr(namespace, self.dest) and getattr(namespace, self.dest):
  237. names = getattr(namespace, self.dest)
  238. else:
  239. names = []
  240. names += [values]
  241. setattr(namespace, self.dest, names)
  242. def parse_qubes_app(self, parser, namespace):
  243. app = namespace.app
  244. pool_names = getattr(namespace, self.dest)
  245. if pool_names:
  246. try:
  247. pools = [app.get_pool(name) for name in pool_names]
  248. setattr(namespace, self.dest, pools)
  249. except qubes.exc.QubesException as e:
  250. parser.error(e.message)
  251. sys.exit(2)
  252. class QubesArgumentParser(argparse.ArgumentParser):
  253. '''Parser preconfigured for use in most of the Qubes command-line tools.
  254. :param bool want_app: instantiate :py:class:`qubes.Qubes` object
  255. :param bool want_app_no_instance: don't actually instantiate \
  256. :py:class:`qubes.Qubes` object, just add argument for custom xml file
  257. :param bool want_force_root: add ``--force-root`` option
  258. :param mixed vmname_nargs: The number of ``VMNAME`` arguments that should be
  259. consumed. Values include:
  260. - N (an integer) consumes N arguments (and produces a list)
  261. - '?' consumes zero or one arguments
  262. - '*' consumes zero or more arguments (and produces a list)
  263. - '+' consumes one or more arguments (and produces a list)
  264. *kwargs* are passed to :py:class:`argparser.ArgumentParser`.
  265. Currenty supported options:
  266. ``--force-root`` (optional)
  267. ``--qubesxml`` location of :file:`qubes.xml` (help is suppressed)
  268. ``--offline-mode`` do not talk to hypervisor (help is suppressed)
  269. ``--verbose`` and ``--quiet``
  270. '''
  271. def __init__(self, want_app=True, want_app_no_instance=False,
  272. want_force_root=False, vmname_nargs=None, **kwargs):
  273. super(QubesArgumentParser, self).__init__(**kwargs)
  274. self._want_app = want_app
  275. self._want_app_no_instance = want_app_no_instance
  276. self._want_force_root = want_force_root
  277. self._vmname_nargs = vmname_nargs
  278. if self._want_app:
  279. self.add_argument('--qubesxml', metavar='FILE', action='store',
  280. dest='app', help=argparse.SUPPRESS)
  281. self.add_argument('--offline-mode', action='store_true',
  282. default=False, dest='offline_mode', help=argparse.SUPPRESS)
  283. self.add_argument('--verbose', '-v', action='count',
  284. help='increase verbosity')
  285. self.add_argument('--quiet', '-q', action='count',
  286. help='decrease verbosity')
  287. if self._want_force_root:
  288. self.add_argument('--force-root', action='store_true',
  289. default=False, help='force to run as root')
  290. if self._vmname_nargs in [argparse.ZERO_OR_MORE, argparse.ONE_OR_MORE]:
  291. vm_name_group = VmNameGroup(self, self._vmname_nargs)
  292. self._mutually_exclusive_groups.append(vm_name_group)
  293. elif self._vmname_nargs is not None:
  294. self.add_argument('VMNAME', nargs=self._vmname_nargs,
  295. action=VmNameAction)
  296. self.set_defaults(verbose=1, quiet=0)
  297. def parse_args(self, *args, **kwargs):
  298. namespace = super(QubesArgumentParser, self).parse_args(*args, **kwargs)
  299. if self._want_app and not self._want_app_no_instance:
  300. self.set_qubes_verbosity(namespace)
  301. namespace.app = qubes.Qubes(namespace.app,
  302. offline_mode=namespace.offline_mode)
  303. if self._want_force_root:
  304. self.dont_run_as_root(namespace)
  305. for action in self._actions:
  306. # pylint: disable=protected-access
  307. if issubclass(action.__class__, QubesAction):
  308. action.parse_qubes_app(self, namespace)
  309. elif issubclass(action.__class__,
  310. argparse._SubParsersAction): # pylint: disable=no-member
  311. assert hasattr(namespace, 'command')
  312. command = namespace.command
  313. subparser = action._name_parser_map[command]
  314. for subaction in subparser._actions:
  315. if issubclass(subaction.__class__, QubesAction):
  316. subaction.parse_qubes_app(self, namespace)
  317. return namespace
  318. def error_runtime(self, message):
  319. '''Runtime error, without showing usage.
  320. :param str message: message to show
  321. '''
  322. self.exit(1, '{}: error: {}\n'.format(self.prog, message))
  323. def dont_run_as_root(self, namespace):
  324. '''Prevent running as root.
  325. :param argparse.Namespace args: if there is ``.force_root`` attribute \
  326. set to true, run anyway
  327. '''
  328. try:
  329. euid = os.geteuid()
  330. except AttributeError: # no geteuid(), probably NT
  331. return
  332. if euid == 0 and not namespace.force_root:
  333. self.error_runtime(
  334. 'refusing to run as root; add --force-root to override')
  335. @staticmethod
  336. def get_loglevel_from_verbosity(namespace):
  337. ''' Return loglevel calculated from quiet and verbose arguments '''
  338. return (namespace.quiet - namespace.verbose) * 10 + logging.WARNING
  339. @staticmethod
  340. def set_qubes_verbosity(namespace):
  341. '''Apply a verbosity setting.
  342. This is done by configuring global logging.
  343. :param argparse.Namespace args: args as parsed by parser
  344. '''
  345. verbose = namespace.verbose - namespace.quiet
  346. if verbose >= 2:
  347. qubes.log.enable_debug()
  348. elif verbose >= 1:
  349. qubes.log.enable()
  350. # pylint: disable=no-self-use
  351. def print_error(self, *args, **kwargs):
  352. ''' Print to ``sys.stderr``'''
  353. print(*args, file=sys.stderr, **kwargs)
  354. class AliasedSubParsersAction(argparse._SubParsersAction):
  355. # source https://gist.github.com/sampsyo/471779
  356. # pylint: disable=protected-access,too-few-public-methods
  357. class _AliasedPseudoAction(argparse.Action):
  358. # pylint: disable=redefined-builtin
  359. def __init__(self, name, aliases, help):
  360. dest = name
  361. if aliases:
  362. dest += ' (%s)' % ','.join(aliases)
  363. sup = super(AliasedSubParsersAction._AliasedPseudoAction, self)
  364. sup.__init__(option_strings=[], dest=dest, help=help)
  365. def __call__(self, **kwargs):
  366. super(AliasedSubParsersAction._AliasedPseudoAction, self).__call__(
  367. **kwargs)
  368. def add_parser(self, name, **kwargs):
  369. if 'aliases' in kwargs:
  370. aliases = kwargs['aliases']
  371. del kwargs['aliases']
  372. else:
  373. aliases = []
  374. local_parser = super(AliasedSubParsersAction, self).add_parser(
  375. name, **kwargs)
  376. # Make the aliases work.
  377. for alias in aliases:
  378. self._name_parser_map[alias] = local_parser
  379. # Make the help text reflect them, first removing old help entry.
  380. if 'help' in kwargs:
  381. self._choices_actions.pop()
  382. pseudo_action = self._AliasedPseudoAction(name, aliases,
  383. kwargs.pop('help'))
  384. self._choices_actions.append(pseudo_action)
  385. return local_parser
  386. def get_parser_for_command(command):
  387. '''Get parser for given qvm-tool.
  388. :param str command: command name
  389. :rtype: argparse.ArgumentParser
  390. :raises ImportError: when command's module is not found
  391. :raises AttributeError: when parser was not found
  392. '''
  393. module = importlib.import_module(
  394. '.' + command.replace('-', '_'), 'qubes.tools')
  395. try:
  396. parser = module.parser
  397. except AttributeError:
  398. try:
  399. parser = module.get_parser()
  400. except AttributeError:
  401. raise AttributeError('cannot find parser in module')
  402. return parser
  403. # pylint: disable=protected-access
  404. class VmNameGroup(argparse._MutuallyExclusiveGroup):
  405. ''' Adds an a VMNAME, --all & --exclude parameters to a
  406. :py:class:``argparse.ArgumentParser```.
  407. '''
  408. def __init__(self, container, required, vm_action=VmNameAction, help=None):
  409. # pylint: disable=redefined-builtin
  410. super(VmNameGroup, self).__init__(container, required=required)
  411. if not help:
  412. help = 'perform the action on all qubes'
  413. self.add_argument('--all', action='store_true', dest='all_domains',
  414. help=help)
  415. container.add_argument('--exclude', action='append', default=[],
  416. help='exclude the qube from --all')
  417. # ⚠ the default parameter below is important! ⚠
  418. # See https://stackoverflow.com/questions/35044288 and
  419. # `argparse.ArgumentParser.parse_args()` implementation
  420. self.add_argument('VMNAME', action=vm_action, nargs='*', default=[])
  421. def print_table(table):
  422. ''' Uses the unix column command to print pretty table.
  423. :param str text: list of lists/sets
  424. '''
  425. unit_separator = chr(31)
  426. cmd = ['column', '-t', '-s', unit_separator]
  427. text_table = '\n'.join([unit_separator.join(row) for row in table])
  428. text_table += '\n'
  429. # for tests...
  430. if sys.stdout != sys.__stdout__:
  431. p = subprocess.Popen(cmd + ['-c', '80'], stdin=subprocess.PIPE,
  432. stdout=subprocess.PIPE)
  433. p.stdin.write(text_table)
  434. (out, _) = p.communicate()
  435. sys.stdout.write(out)
  436. else:
  437. p = subprocess.Popen(cmd, stdin=subprocess.PIPE)
  438. p.communicate(text_table)