qvm_ls.py 18 KB

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