qvm_ls.py 18 KB

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