qvm_ls.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  1. # pylint: disable=too-few-public-methods
  2. #
  3. # The Qubes OS Project, https://www.qubes-os.org/
  4. #
  5. # Copyright (C) 2015 Joanna Rutkowska <joanna@invisiblethingslab.com>
  6. # Copyright (C) 2015 Wojtek Porczyk <woju@invisiblethingslab.com>
  7. #
  8. # This program is free software; you can redistribute it and/or modify
  9. # it under the terms of the GNU General Public License as published by
  10. # the Free Software Foundation; either version 2 of the License, or
  11. # (at your option) any later version.
  12. #
  13. # This program is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU General Public License along
  19. # with this program; if not, write to the Free Software Foundation, Inc.,
  20. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  21. #
  22. '''qvm-ls - List available domains'''
  23. from __future__ import print_function
  24. import argparse
  25. import collections
  26. import sys
  27. import textwrap
  28. import qubes
  29. import qubes.config
  30. import qubes.tools
  31. import qubes.utils
  32. #
  33. # columns
  34. #
  35. class Column(object):
  36. '''A column in qvm-ls output characterised by its head, a width and a way
  37. to fetch a parameter describing the domain.
  38. :param str head: Column head (usually uppercase).
  39. :param int width: Column width.
  40. :param str attr: Attribute, possibly complex (containing ``.``). This may \
  41. also be a callable that gets as its only argument the domain.
  42. :param str doc: Description of column (will be visible in --help-columns).
  43. '''
  44. #: collection of all columns
  45. columns = {}
  46. def __init__(self, head, width=0, attr=None, doc=None):
  47. self.ls_head = head
  48. self.ls_width = max(width, len(self.ls_head) + 1)
  49. self.__doc__ = doc if doc is None else qubes.utils.format_doc(doc)
  50. # intentionally not always do set self._attr,
  51. # to cause AttributeError in self.format()
  52. if attr is not None:
  53. self._attr = attr
  54. self.__class__.columns[self.ls_head] = self
  55. def cell(self, vm):
  56. '''Format one cell.
  57. .. note::
  58. This is only for technical formatting (filling with space). If you
  59. want to subclass the :py:class:`Column` class, you should override
  60. :py:meth:`Column.format` method instead.
  61. :param qubes.vm.qubesvm.QubesVM: Domain to get a value from.
  62. :returns: string that is at least as wide as needed to fill table row.
  63. :rtype: str
  64. '''
  65. value = self.format(vm) or '-'
  66. return value.ljust(self.ls_width)
  67. def format(self, vm):
  68. '''Format one cell value.
  69. Return value to put in a table cell.
  70. :param qubes.vm.qubesvm.QubesVM: Domain to get a value from.
  71. :returns: Value to put, or :py:obj:`None` if no value.
  72. :rtype: str or None
  73. '''
  74. ret = None
  75. try:
  76. if isinstance(self._attr, str):
  77. ret = vm
  78. for attrseg in self._attr.split('.'):
  79. ret = getattr(ret, attrseg)
  80. elif isinstance(self._attr, collections.Callable):
  81. ret = self._attr(vm)
  82. except (AttributeError, ZeroDivisionError):
  83. # division by 0 may be caused by arithmetic in callable attr
  84. return None
  85. if ret is None:
  86. return None
  87. # late import to avoid circular import
  88. # pylint: disable=redefined-outer-name
  89. import qubes.vm
  90. if isinstance(ret, (qubes.vm.BaseVM, qubes.Label)):
  91. return ret.name
  92. if isinstance(ret, int):
  93. return str(ret)
  94. return ret
  95. def __repr__(self):
  96. return '{}(head={!r}, width={!r})'.format(self.__class__.__name__,
  97. self.ls_head, self.ls_width)
  98. def __eq__(self, other):
  99. return self.ls_head == other.ls_head
  100. def __lt__(self, other):
  101. return self.ls_head < other.ls_head
  102. def column(width=0, head=None):
  103. '''Mark function or plain property as valid column in :program:`qvm-ls`.
  104. By default all instances of :py:class:`qubes.property` are valid.
  105. :param int width: Column width
  106. :param str head: Column head (default: take property's name)
  107. '''
  108. def decorator(obj):
  109. # pylint: disable=missing-docstring
  110. # we keep hints on fget, so the order of decorators does not matter
  111. holder = obj.fget if isinstance(obj, property) else obj
  112. try:
  113. holder.ls_head = head or holder.__name__.replace('_', '-').upper()
  114. except AttributeError:
  115. raise TypeError('Cannot find default column name '
  116. 'for a strange object {!r}'.format(obj))
  117. holder.ls_width = max(width, len(holder.ls_head) + 1)
  118. return obj
  119. return decorator
  120. class PropertyColumn(Column):
  121. '''Column that displays value from property (:py:class:`property` or
  122. :py:class:`qubes.property`) of domain.
  123. You shouldn't use this class directly, see :py:func:`column` decorator.
  124. :param holder: Holder of magic attributes.
  125. '''
  126. def __init__(self, holder):
  127. super(PropertyColumn, self).__init__(
  128. head=holder.ls_head,
  129. width=holder.ls_width,
  130. attr=holder.__name__,
  131. doc=holder.__doc__)
  132. self.holder = holder
  133. def __repr__(self):
  134. return '{}(head={!r}, width={!r} holder={!r})'.format(
  135. self.__class__.__name__,
  136. self.ls_head,
  137. self.ls_width,
  138. self.holder)
  139. def process_class(cls):
  140. '''Process class after definition to find all listable properties.
  141. It is used in metaclass of the domain.
  142. :param qubes.vm.BaseVMMeta cls: Class to round up.
  143. '''
  144. for klass in cls.__mro__:
  145. for prop in klass.__dict__.values():
  146. holder = prop.fget \
  147. if isinstance(prop, property) \
  148. else prop
  149. if not hasattr(holder, 'ls_head') or holder.ls_head is None:
  150. continue
  151. for col in Column.columns.values():
  152. if not isinstance(col, PropertyColumn):
  153. continue
  154. if col.holder.__name__ != holder.__name__:
  155. continue
  156. if col.ls_head != holder.ls_head:
  157. raise TypeError('Found column head mismatch in class {!r} '
  158. '({!r} != {!r})'.format(cls.__name__,
  159. holder.ls_head, col.ls_head))
  160. if col.ls_width != holder.ls_width:
  161. raise TypeError('Found column width mismatch in class {!r} '
  162. '({!r} != {!r})'.format(cls.__name__,
  163. holder.ls_width, col.ls_width))
  164. PropertyColumn(holder)
  165. def flag(field):
  166. '''Mark method as flag field.
  167. :param int field: Which field to fill (counted from 1)
  168. '''
  169. def decorator(obj):
  170. # pylint: disable=missing-docstring
  171. obj.field = field
  172. return obj
  173. return decorator
  174. def simple_flag(field, letter, attr, doc=None):
  175. '''Create simple, binary flag.
  176. :param str attr: Attribute name to check. If result is true, flag is fired.
  177. :param str letter: The letter to show.
  178. '''
  179. def helper(self, vm):
  180. # pylint: disable=missing-docstring,unused-argument
  181. try:
  182. value = getattr(vm, attr)
  183. except AttributeError:
  184. value = False
  185. if value:
  186. return letter[0]
  187. helper.__doc__ = doc
  188. helper.field = field
  189. return helper
  190. class StatusColumn(Column):
  191. '''Some fancy flags that describe general status of the domain.'''
  192. # pylint: disable=no-self-use
  193. def __init__(self):
  194. super(StatusColumn, self).__init__(
  195. head='STATUS',
  196. width=len(self.get_flags()) + 1,
  197. doc=self.__class__.__doc__)
  198. @flag(1)
  199. def type(self, vm):
  200. '''Type of domain.
  201. 0 AdminVM (AKA Dom0)
  202. aA AppVM
  203. dD DisposableVM
  204. sS StandaloneVM
  205. tT TemplateVM
  206. When it is HVM (optimised VM), the letter is capital.
  207. '''
  208. # late import because of circular dependency
  209. # pylint: disable=redefined-outer-name
  210. import qubes.vm
  211. import qubes.vm.adminvm
  212. import qubes.vm.appvm
  213. import qubes.vm.dispvm
  214. import qubes.vm.qubesvm
  215. import qubes.vm.templatevm
  216. if isinstance(vm, qubes.vm.adminvm.AdminVM):
  217. return '0'
  218. ret = None
  219. # TODO right order, depending on inheritance
  220. if isinstance(vm, qubes.vm.templatevm.TemplateVM):
  221. ret = 't'
  222. if isinstance(vm, qubes.vm.appvm.AppVM):
  223. ret = 'a'
  224. # if isinstance(vm, qubes.vm.standalonevm.StandaloneVM):
  225. # ret = 's'
  226. if isinstance(vm, qubes.vm.dispvm.DispVM):
  227. ret = 'd'
  228. if ret is not None:
  229. if getattr(vm, 'hvm', False):
  230. return ret.upper()
  231. else:
  232. return ret
  233. @flag(2)
  234. def power(self, vm):
  235. '''Current power state.
  236. r running
  237. t transient
  238. p paused
  239. s suspended
  240. h halting
  241. d dying
  242. c crashed
  243. ? unknown
  244. '''
  245. state = vm.get_power_state().lower()
  246. if state == 'unknown':
  247. return '?'
  248. elif state in ('running', 'transient', 'paused', 'suspended',
  249. 'halting', 'dying', 'crashed'):
  250. return state[0]
  251. updateable = simple_flag(3, 'U', 'updateable',
  252. doc='If the domain is updateable.')
  253. provides_network = simple_flag(4, 'N', 'provides_network',
  254. doc='If the domain provides network.')
  255. installed_by_rpm = simple_flag(5, 'R', 'installed_by_rpm',
  256. doc='If the domain is installed by RPM.')
  257. internal = simple_flag(6, 'i', 'internal',
  258. doc='If the domain is internal (not normally shown, no appmenus).')
  259. debug = simple_flag(7, 'D', 'debug',
  260. doc='If the domain is being debugged.')
  261. autostart = simple_flag(8, 'A', 'autostart',
  262. doc='If the domain is marked for autostart.')
  263. # TODO (not sure if really):
  264. # include in backups
  265. # uses_custom_config
  266. def _no_flag(self, vm):
  267. '''Reserved for future use.'''
  268. @classmethod
  269. def get_flags(cls):
  270. '''Get all flags as list.
  271. Holes between flags are filled with :py:meth:`_no_flag`.
  272. :rtype: list
  273. '''
  274. flags = {}
  275. for mycls in cls.__mro__:
  276. for attr in mycls.__dict__.values():
  277. if not hasattr(attr, 'field'):
  278. continue
  279. if attr.field in flags:
  280. continue
  281. flags[attr.field] = attr
  282. return [(flags[i] if i in flags else cls._no_flag)
  283. for i in range(1, max(flags) + 1)]
  284. def format(self, vm):
  285. return ''.join((flag(self, vm) or '-') for flag in self.get_flags())
  286. def calc_size(vm, volume_name):
  287. ''' Calculates the volume size in MB '''
  288. try:
  289. return vm.volumes[volume_name].size // 1024 // 1024
  290. except KeyError:
  291. return 0
  292. def calc_usage(vm, volume_name):
  293. ''' Calculates the volume usage in MB '''
  294. try:
  295. return vm.volumes[volume_name].usage // 1024 // 1024
  296. except KeyError:
  297. return 0
  298. def calc_used(vm, volume_name):
  299. ''' Calculates the volume usage in percent '''
  300. size = calc_size(vm, volume_name)
  301. if size == 0:
  302. return 0
  303. usage = calc_usage(vm, volume_name)
  304. return usage * 100 // size
  305. # todo maxmem
  306. Column('GATEWAY', width=15,
  307. attr='netvm.gateway',
  308. doc='Network gateway.')
  309. Column('MEMORY', width=5,
  310. attr=(lambda vm: vm.get_mem() / 1024 if vm.is_running() else None),
  311. doc='Memory currently used by VM')
  312. Column('DISK', width=5,
  313. attr=(lambda vm: vm.storage.get_disk_utilization() / 1024 / 1024),
  314. doc='Total disk utilisation.')
  315. Column('PRIV-CURR', width=5,
  316. attr=(lambda vm: calc_usage(vm, 'private')),
  317. doc='Disk utilisation by private image (/home, /usr/local).')
  318. Column('PRIV-MAX', width=5,
  319. attr=(lambda vm: calc_size(vm, 'private')),
  320. doc='Maximum available space for private image.')
  321. Column('PRIV-USED', width=5,
  322. attr=(lambda vm: calc_used(vm, 'private')),
  323. doc='Disk utilisation by private image as a percentage of available space.')
  324. Column('ROOT-CURR', width=5,
  325. attr=(lambda vm: calc_usage(vm, 'root')),
  326. doc='Disk utilisation by root image (/usr, /lib, /etc, ...).')
  327. Column('ROOT-MAX', width=5,
  328. attr=(lambda vm: calc_size(vm, 'root')),
  329. doc='Maximum available space for root image.')
  330. Column('ROOT-USED', width=5,
  331. attr=(lambda vm: calc_used(vm, 'root')),
  332. doc='Disk utilisation by root image as a percentage of available space.')
  333. StatusColumn()
  334. class Table(object):
  335. '''Table that is displayed to the user.
  336. :param qubes.Qubes app: Qubes application object.
  337. :param list colnames: Names of the columns (need not to be uppercase).
  338. '''
  339. def __init__(self, app, colnames, raw_data=False):
  340. self.app = app
  341. self.columns = tuple(Column.columns[col.upper()] for col in colnames)
  342. self.raw_data = raw_data
  343. def format_head(self):
  344. '''Format table head (all column heads).'''
  345. return ''.join('{head:{width}s}'.format(
  346. head=col.ls_head, width=col.ls_width)
  347. for col in self.columns[:-1]) + \
  348. self.columns[-1].ls_head
  349. def format_row(self, vm):
  350. '''Format single table row (all columns for one domain).'''
  351. if self.raw_data:
  352. return '|'.join(col.format(vm) for col in self.columns)
  353. else:
  354. return ''.join(col.cell(vm) for col in self.columns)
  355. def write_table(self, stream=sys.stdout):
  356. '''Write whole table to file-like object.
  357. :param file stream: Stream to write the table to.
  358. '''
  359. if not self.raw_data:
  360. stream.write(self.format_head() + '\n')
  361. for vm in self.app.domains:
  362. stream.write(self.format_row(vm) + '\n')
  363. #: Available formats. Feel free to plug your own one.
  364. formats = {
  365. 'simple': ('name', 'status', 'label', 'template', 'netvm'),
  366. 'network': ('name', 'status', 'netvm', 'ip', 'ipback', 'gateway'),
  367. 'full': ('name', 'status', 'label', 'qid', 'xid', 'uuid'),
  368. # 'perf': ('name', 'status', 'cpu', 'memory'),
  369. 'disk': ('name', 'status', 'disk',
  370. 'priv-curr', 'priv-max', 'priv-used',
  371. 'root-curr', 'root-max', 'root-used'),
  372. }
  373. class _HelpColumnsAction(argparse.Action):
  374. '''Action for argument parser that displays all columns and exits.'''
  375. # pylint: disable=redefined-builtin
  376. def __init__(self,
  377. option_strings,
  378. dest=argparse.SUPPRESS,
  379. default=argparse.SUPPRESS,
  380. help='list all available columns with short descriptions and exit'):
  381. super(_HelpColumnsAction, self).__init__(
  382. option_strings=option_strings,
  383. dest=dest,
  384. default=default,
  385. nargs=0,
  386. help=help)
  387. def __call__(self, parser, namespace, values, option_string=None):
  388. width = max(len(column.ls_head) for column in Column.columns.values())
  389. wrapper = textwrap.TextWrapper(width=80,
  390. initial_indent=' ', subsequent_indent=' ' * (width + 6))
  391. text = 'Available columns:\n' + '\n'.join(
  392. wrapper.fill('{head:{width}s} {doc}'.format(
  393. head=column.ls_head,
  394. doc=column.__doc__ or '',
  395. width=width))
  396. for column in sorted(Column.columns.values()))
  397. parser.exit(message=text + '\n')
  398. class _HelpFormatsAction(argparse.Action):
  399. '''Action for argument parser that displays all formats and exits.'''
  400. # pylint: disable=redefined-builtin
  401. def __init__(self,
  402. option_strings,
  403. dest=argparse.SUPPRESS,
  404. default=argparse.SUPPRESS,
  405. help='list all available formats with their definitions and exit'):
  406. super(_HelpFormatsAction, self).__init__(
  407. option_strings=option_strings,
  408. dest=dest,
  409. default=default,
  410. nargs=0,
  411. help=help)
  412. def __call__(self, parser, namespace, values, option_string=None):
  413. width = max(len(fmt) for fmt in formats)
  414. text = 'Available formats:\n' + ''.join(
  415. ' {fmt:{width}s} {columns}\n'.format(
  416. fmt=fmt, columns=','.join(formats[fmt]).upper(), width=width)
  417. for fmt in sorted(formats))
  418. parser.exit(message=text)
  419. def get_parser():
  420. '''Create :py:class:`argparse.ArgumentParser` suitable for
  421. :program:`qvm-ls`.
  422. '''
  423. # parser creation is delayed to get all the columns that are scattered
  424. # thorough the modules
  425. wrapper = textwrap.TextWrapper(width=80, break_on_hyphens=False,
  426. initial_indent=' ', subsequent_indent=' ')
  427. parser = qubes.tools.QubesArgumentParser(
  428. formatter_class=argparse.RawTextHelpFormatter,
  429. description='List Qubes domains and their parametres.',
  430. epilog='available formats (see --help-formats):\n{}\n\n'
  431. 'available columns (see --help-columns):\n{}'.format(
  432. wrapper.fill(', '.join(sorted(formats.keys()))),
  433. wrapper.fill(', '.join(sorted(sorted(Column.columns.keys()))))))
  434. parser.add_argument('--help-columns', action=_HelpColumnsAction)
  435. parser.add_argument('--help-formats', action=_HelpFormatsAction)
  436. parser_formats = parser.add_mutually_exclusive_group()
  437. parser_formats.add_argument('--format', '-o', metavar='FORMAT',
  438. action='store', choices=formats.keys(), default='simple',
  439. help='preset format')
  440. parser_formats.add_argument('--fields', '-O', metavar='FIELD,...',
  441. action='store',
  442. help='user specified format (see available columns below)')
  443. parser.add_argument('--raw-data', action='store_true',
  444. help='Display specify data of specified VMs. Intended for '
  445. 'bash-parsing.')
  446. # parser.add_argument('--conf', '-c',
  447. # action='store', metavar='CFGFILE',
  448. # help='Qubes config file')
  449. return parser
  450. def main(args=None):
  451. '''Main routine of :program:`qvm-ls`.
  452. :param list args: Optional arguments to override those delivered from \
  453. command line.
  454. '''
  455. parser = get_parser()
  456. try:
  457. args = parser.parse_args(args)
  458. except qubes.exc.QubesException as e:
  459. parser.print_error(str(e))
  460. return 1
  461. if args.fields:
  462. columns = [col.strip() for col in args.fields.split(',')]
  463. for col in columns:
  464. if col.upper() not in Column.columns:
  465. parser.error('no such column: {!r}'.format(col))
  466. else:
  467. columns = formats[args.format]
  468. table = Table(args.app, columns)
  469. table.write_table(sys.stdout)
  470. return 0
  471. if __name__ == '__main__':
  472. sys.exit(main())