qvm_ls.py 16 KB

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