qvm_ls.py 18 KB

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