qvm_ls.py 18 KB

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