qvm_ls.py 18 KB

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