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. return ret
  232. @flag(2)
  233. def power(self, vm):
  234. '''Current power state.
  235. r running
  236. t transient
  237. p paused
  238. s suspended
  239. h halting
  240. d dying
  241. c crashed
  242. ? unknown
  243. '''
  244. state = vm.get_power_state().lower()
  245. if state == 'unknown':
  246. return '?'
  247. elif state in ('running', 'transient', 'paused', 'suspended',
  248. 'halting', 'dying', 'crashed'):
  249. return state[0]
  250. updateable = simple_flag(3, 'U', 'updateable',
  251. doc='If the domain is updateable.')
  252. provides_network = simple_flag(4, 'N', 'provides_network',
  253. doc='If the domain provides network.')
  254. installed_by_rpm = simple_flag(5, 'R', 'installed_by_rpm',
  255. doc='If the domain is installed by RPM.')
  256. internal = simple_flag(6, 'i', 'internal',
  257. doc='If the domain is internal (not normally shown, no appmenus).')
  258. debug = simple_flag(7, 'D', 'debug',
  259. doc='If the domain is being debugged.')
  260. autostart = simple_flag(8, 'A', 'autostart',
  261. doc='If the domain is marked for autostart.')
  262. # TODO (not sure if really):
  263. # include in backups
  264. # uses_custom_config
  265. def _no_flag(self, vm):
  266. '''Reserved for future use.'''
  267. @classmethod
  268. def get_flags(cls):
  269. '''Get all flags as list.
  270. Holes between flags are filled with :py:meth:`_no_flag`.
  271. :rtype: list
  272. '''
  273. flags = {}
  274. for mycls in cls.__mro__:
  275. for attr in mycls.__dict__.values():
  276. if not hasattr(attr, 'field'):
  277. continue
  278. if attr.field in flags:
  279. continue
  280. flags[attr.field] = attr
  281. return [(flags[i] if i in flags else cls._no_flag)
  282. for i in range(1, max(flags) + 1)]
  283. def format(self, vm):
  284. return ''.join((flag(self, vm) or '-') for flag in self.get_flags())
  285. def calc_size(vm, volume_name):
  286. ''' Calculates the volume size in MB '''
  287. try:
  288. return vm.volumes[volume_name].size // 1024 // 1024
  289. except KeyError:
  290. return 0
  291. def calc_usage(vm, volume_name):
  292. ''' Calculates the volume usage in MB '''
  293. try:
  294. return vm.volumes[volume_name].usage // 1024 // 1024
  295. except KeyError:
  296. return 0
  297. def calc_used(vm, volume_name):
  298. ''' Calculates the volume usage in percent '''
  299. size = calc_size(vm, volume_name)
  300. if size == 0:
  301. return 0
  302. usage = calc_usage(vm, volume_name)
  303. return usage * 100 // size
  304. # todo maxmem
  305. Column('GATEWAY', width=15,
  306. attr='netvm.gateway',
  307. doc='Network gateway.')
  308. Column('MEMORY', width=5,
  309. attr=(lambda vm: vm.get_mem() / 1024 if vm.is_running() else None),
  310. doc='Memory currently used by VM')
  311. Column('DISK', width=5,
  312. attr=(lambda vm: vm.storage.get_disk_utilization() / 1024 / 1024),
  313. doc='Total disk utilisation.')
  314. Column('PRIV-CURR', width=5,
  315. attr=(lambda vm: calc_usage(vm, 'private')),
  316. doc='Disk utilisation by private image (/home, /usr/local).')
  317. Column('PRIV-MAX', width=5,
  318. attr=(lambda vm: calc_size(vm, 'private')),
  319. doc='Maximum available space for private image.')
  320. Column('PRIV-USED', width=5,
  321. attr=(lambda vm: calc_used(vm, 'private')),
  322. doc='Disk utilisation by private image as a percentage of available space.')
  323. Column('ROOT-CURR', width=5,
  324. attr=(lambda vm: calc_usage(vm, 'root')),
  325. doc='Disk utilisation by root image (/usr, /lib, /etc, ...).')
  326. Column('ROOT-MAX', width=5,
  327. attr=(lambda vm: calc_size(vm, 'root')),
  328. doc='Maximum available space for root image.')
  329. Column('ROOT-USED', width=5,
  330. attr=(lambda vm: calc_used(vm, 'root')),
  331. doc='Disk utilisation by root image as a percentage of available space.')
  332. StatusColumn()
  333. class Table(object):
  334. '''Table that is displayed to the user.
  335. :param qubes.Qubes app: Qubes application object.
  336. :param list colnames: Names of the columns (need not to be uppercase).
  337. '''
  338. def __init__(self, app, colnames, raw_data=False):
  339. self.app = app
  340. self.columns = tuple(Column.columns[col.upper()] for col in colnames)
  341. self.raw_data = raw_data
  342. def format_head(self):
  343. '''Format table head (all column heads).'''
  344. return ''.join('{head:{width}s}'.format(
  345. head=col.ls_head, width=col.ls_width)
  346. for col in self.columns[:-1]) + \
  347. self.columns[-1].ls_head
  348. def format_row(self, vm):
  349. '''Format single table row (all columns for one domain).'''
  350. if self.raw_data:
  351. return '|'.join(col.format(vm) for col in self.columns)
  352. return ''.join(col.cell(vm) for col in self.columns)
  353. def write_table(self, stream=sys.stdout):
  354. '''Write whole table to file-like object.
  355. :param file stream: Stream to write the table to.
  356. '''
  357. if not self.raw_data:
  358. stream.write(self.format_head() + '\n')
  359. for vm in self.app.domains:
  360. stream.write(self.format_row(vm) + '\n')
  361. #: Available formats. Feel free to plug your own one.
  362. formats = {
  363. 'simple': ('name', 'status', 'label', 'template', 'netvm'),
  364. 'network': ('name', 'status', 'netvm', 'ip', 'ipback', 'gateway'),
  365. 'full': ('name', 'status', 'label', 'qid', 'xid', 'uuid'),
  366. # 'perf': ('name', 'status', 'cpu', 'memory'),
  367. 'disk': ('name', 'status', 'disk',
  368. 'priv-curr', 'priv-max', 'priv-used',
  369. 'root-curr', 'root-max', 'root-used'),
  370. }
  371. class _HelpColumnsAction(argparse.Action):
  372. '''Action for argument parser that displays all columns and exits.'''
  373. # pylint: disable=redefined-builtin
  374. def __init__(self,
  375. option_strings,
  376. dest=argparse.SUPPRESS,
  377. default=argparse.SUPPRESS,
  378. help='list all available columns with short descriptions and exit'):
  379. super(_HelpColumnsAction, self).__init__(
  380. option_strings=option_strings,
  381. dest=dest,
  382. default=default,
  383. nargs=0,
  384. help=help)
  385. def __call__(self, parser, namespace, values, option_string=None):
  386. width = max(len(column.ls_head) for column in Column.columns.values())
  387. wrapper = textwrap.TextWrapper(width=80,
  388. initial_indent=' ', subsequent_indent=' ' * (width + 6))
  389. text = 'Available columns:\n' + '\n'.join(
  390. wrapper.fill('{head:{width}s} {doc}'.format(
  391. head=column.ls_head,
  392. doc=column.__doc__ or '',
  393. width=width))
  394. for column in sorted(Column.columns.values()))
  395. parser.exit(message=text + '\n')
  396. class _HelpFormatsAction(argparse.Action):
  397. '''Action for argument parser that displays all formats and exits.'''
  398. # pylint: disable=redefined-builtin
  399. def __init__(self,
  400. option_strings,
  401. dest=argparse.SUPPRESS,
  402. default=argparse.SUPPRESS,
  403. help='list all available formats with their definitions and exit'):
  404. super(_HelpFormatsAction, self).__init__(
  405. option_strings=option_strings,
  406. dest=dest,
  407. default=default,
  408. nargs=0,
  409. help=help)
  410. def __call__(self, parser, namespace, values, option_string=None):
  411. width = max(len(fmt) for fmt in formats)
  412. text = 'Available formats:\n' + ''.join(
  413. ' {fmt:{width}s} {columns}\n'.format(
  414. fmt=fmt, columns=','.join(formats[fmt]).upper(), width=width)
  415. for fmt in sorted(formats))
  416. parser.exit(message=text)
  417. def get_parser():
  418. '''Create :py:class:`argparse.ArgumentParser` suitable for
  419. :program:`qvm-ls`.
  420. '''
  421. # parser creation is delayed to get all the columns that are scattered
  422. # thorough the modules
  423. wrapper = textwrap.TextWrapper(width=80, break_on_hyphens=False,
  424. initial_indent=' ', subsequent_indent=' ')
  425. parser = qubes.tools.QubesArgumentParser(
  426. formatter_class=argparse.RawTextHelpFormatter,
  427. description='List Qubes domains and their parametres.',
  428. epilog='available formats (see --help-formats):\n{}\n\n'
  429. 'available columns (see --help-columns):\n{}'.format(
  430. wrapper.fill(', '.join(sorted(formats.keys()))),
  431. wrapper.fill(', '.join(sorted(sorted(Column.columns.keys()))))))
  432. parser.add_argument('--help-columns', action=_HelpColumnsAction)
  433. parser.add_argument('--help-formats', action=_HelpFormatsAction)
  434. parser_formats = parser.add_mutually_exclusive_group()
  435. parser_formats.add_argument('--format', '-o', metavar='FORMAT',
  436. action='store', choices=formats.keys(), default='simple',
  437. help='preset format')
  438. parser_formats.add_argument('--fields', '-O', metavar='FIELD,...',
  439. action='store',
  440. help='user specified format (see available columns below)')
  441. parser.add_argument('--raw-data', action='store_true',
  442. help='Display specify data of specified VMs. Intended for '
  443. 'bash-parsing.')
  444. # parser.add_argument('--conf', '-c',
  445. # action='store', metavar='CFGFILE',
  446. # help='Qubes config file')
  447. return parser
  448. def main(args=None):
  449. '''Main routine of :program:`qvm-ls`.
  450. :param list args: Optional arguments to override those delivered from \
  451. command line.
  452. '''
  453. parser = get_parser()
  454. try:
  455. args = parser.parse_args(args)
  456. except qubes.exc.QubesException as e:
  457. parser.print_error(str(e))
  458. return 1
  459. if args.fields:
  460. columns = [col.strip() for col in args.fields.split(',')]
  461. for col in columns:
  462. if col.upper() not in Column.columns:
  463. parser.error('no such column: {!r}'.format(col))
  464. else:
  465. columns = formats[args.format]
  466. table = Table(args.app, columns)
  467. table.write_table(sys.stdout)
  468. return 0
  469. if __name__ == '__main__':
  470. sys.exit(main())