qube_manager.py 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290
  1. #!/usr/bin/python3
  2. #
  3. # The Qubes OS Project, http://www.qubes-os.org
  4. #
  5. # Copyright (C) 2012 Agnieszka Kostrzewa <agnieszka.kostrzewa@gmail.com>
  6. # Copyright (C) 2012 Marek Marczykowski-Górecki
  7. # <marmarek@invisiblethingslab.com>
  8. # Copyright (C) 2017 Wojtek Porczyk <woju@invisiblethingslab.com>
  9. #
  10. # This program is free software; you can redistribute it and/or
  11. # modify it under the terms of the GNU General Public License
  12. # as published by the Free Software Foundation; either version 2
  13. # of the License, or (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 Lesser General Public License along
  21. # with this program; if not, see <http://www.gnu.org/licenses/>.
  22. #
  23. #
  24. import sys
  25. import os
  26. import os.path
  27. import subprocess
  28. from datetime import datetime, timedelta
  29. import traceback
  30. from contextlib import suppress
  31. import quamash
  32. import asyncio
  33. from qubesadmin import Qubes
  34. from qubesadmin import exc
  35. from qubesadmin import utils
  36. from qubesadmin import events
  37. from PyQt4 import QtGui # pylint: disable=import-error
  38. from PyQt4 import QtCore # pylint: disable=import-error
  39. from qubesmanager.about import AboutDialog
  40. from . import ui_qubemanager # pylint: disable=no-name-in-module
  41. from . import table_widgets
  42. from . import settings
  43. from . import global_settings
  44. from . import restore
  45. from . import backup
  46. from . import create_new_vm
  47. from . import log_dialog
  48. from . import utils as manager_utils
  49. from . import common_threads
  50. class SearchBox(QtGui.QLineEdit):
  51. def __init__(self, parent=None):
  52. super(SearchBox, self).__init__(parent)
  53. self.focusing = False
  54. def focusInEvent(self, e): # pylint: disable=invalid-name
  55. super(SearchBox, self).focusInEvent(e)
  56. self.selectAll()
  57. self.focusing = True
  58. def mousePressEvent(self, e): # pylint: disable=invalid-name
  59. super(SearchBox, self).mousePressEvent(e)
  60. if self.focusing:
  61. self.selectAll()
  62. self.focusing = False
  63. class VmRowInTable:
  64. # pylint: disable=too-few-public-methods
  65. def __init__(self, vm, row_no, table):
  66. self.vm = vm
  67. # TODO: replace a various different widgets with a more generic
  68. # VmFeatureWidget or VMPropertyWidget
  69. table_widgets.row_height = VmManagerWindow.row_height
  70. table.setRowHeight(row_no, VmManagerWindow.row_height)
  71. self.type_widget = table_widgets.VmTypeWidget(vm)
  72. table.setCellWidget(row_no, VmManagerWindow.columns_indices['Type'],
  73. self.type_widget)
  74. table.setItem(row_no, VmManagerWindow.columns_indices['Type'],
  75. self.type_widget.table_item)
  76. self.label_widget = table_widgets.VmLabelWidget(vm)
  77. table.setCellWidget(row_no, VmManagerWindow.columns_indices['Label'],
  78. self.label_widget)
  79. table.setItem(row_no, VmManagerWindow.columns_indices['Label'],
  80. self.label_widget.table_item)
  81. self.name_widget = table_widgets.VmNameItem(vm)
  82. table.setItem(row_no, VmManagerWindow.columns_indices['Name'],
  83. self.name_widget)
  84. self.info_widget = table_widgets.VmInfoWidget(vm)
  85. table.setCellWidget(row_no, VmManagerWindow.columns_indices['State'],
  86. self.info_widget)
  87. table.setItem(row_no, VmManagerWindow.columns_indices['State'],
  88. self.info_widget.table_item)
  89. self.template_widget = table_widgets.VmTemplateItem(vm)
  90. table.setItem(row_no, VmManagerWindow.columns_indices['Template'],
  91. self.template_widget)
  92. self.netvm_widget = table_widgets.VmNetvmItem(vm)
  93. table.setItem(row_no, VmManagerWindow.columns_indices['NetVM'],
  94. self.netvm_widget)
  95. self.size_widget = table_widgets.VmSizeOnDiskItem(vm)
  96. table.setItem(row_no, VmManagerWindow.columns_indices['Size'],
  97. self.size_widget)
  98. self.internal_widget = table_widgets.VmInternalItem(vm)
  99. table.setItem(row_no, VmManagerWindow.columns_indices['Internal'],
  100. self.internal_widget)
  101. self.ip_widget = table_widgets.VmIPItem(vm)
  102. table.setItem(row_no, VmManagerWindow.columns_indices['IP'],
  103. self.ip_widget)
  104. self.include_in_backups_widget = \
  105. table_widgets.VmIncludeInBackupsItem(vm)
  106. table.setItem(row_no, VmManagerWindow.columns_indices[
  107. 'Backups'], self.include_in_backups_widget)
  108. self.last_backup_widget = table_widgets.VmLastBackupItem(vm)
  109. table.setItem(row_no, VmManagerWindow.columns_indices[
  110. 'Last backup'], self.last_backup_widget)
  111. self.table = table
  112. def update(self, update_size_on_disk=False, event=None):
  113. """
  114. Update info in a single VM row
  115. :param update_size_on_disk: should disk utilization be updated? the
  116. widget will extract the data from VM object
  117. :param event: name of the event that caused the update, to avoid
  118. updating unnecessary properties; if event is none, update everything
  119. :return: None
  120. """
  121. try:
  122. self.info_widget.update_vm_state()
  123. if not event or event.endswith(':label'):
  124. self.label_widget.update()
  125. if not event or event.endswith(':template'):
  126. self.template_widget.update()
  127. if not event or event.endswith(':netvm'):
  128. self.netvm_widget.update()
  129. if not event or event.endswith(':internal'):
  130. self.internal_widget.update()
  131. if not event or event.endswith(':ip'):
  132. self.ip_widget.update()
  133. if not event or event.endswith(':include_in_backups'):
  134. self.include_in_backups_widget.update()
  135. if not event or event.endswith(':backup_timestamp'):
  136. self.last_backup_widget.update()
  137. if update_size_on_disk:
  138. self.size_widget.update()
  139. except exc.QubesPropertyAccessError:
  140. pass
  141. except exc.QubesDaemonNoResponseError:
  142. # TODO: this will be fixed by a rewrite moving the event system to
  143. # AdminAPI
  144. pass
  145. #force re-sorting
  146. self.table.setSortingEnabled(True)
  147. vm_shutdown_timeout = 20000 # in msec
  148. vm_restart_check_timeout = 1000 # in msec
  149. class VmShutdownMonitor(QtCore.QObject):
  150. def __init__(self, vm, shutdown_time=vm_shutdown_timeout,
  151. check_time=vm_restart_check_timeout,
  152. and_restart=False, caller=None):
  153. QtCore.QObject.__init__(self)
  154. self.vm = vm
  155. self.shutdown_time = shutdown_time
  156. self.check_time = check_time
  157. self.and_restart = and_restart
  158. self.shutdown_started = datetime.now()
  159. self.caller = caller
  160. def restart_vm_if_needed(self):
  161. if self.and_restart and self.caller:
  162. self.caller.start_vm(self.vm)
  163. def check_again_later(self):
  164. # noinspection PyTypeChecker,PyCallByClass
  165. QtCore.QTimer.singleShot(self.check_time, self.check_if_vm_has_shutdown)
  166. def timeout_reached(self):
  167. actual = datetime.now() - self.shutdown_started
  168. allowed = timedelta(milliseconds=self.shutdown_time)
  169. return actual > allowed
  170. def check_if_vm_has_shutdown(self):
  171. vm = self.vm
  172. vm_is_running = vm.is_running()
  173. try:
  174. vm_start_time = datetime.fromtimestamp(float(vm.start_time))
  175. except (AttributeError, TypeError, ValueError):
  176. vm_start_time = None
  177. if vm_is_running and vm_start_time \
  178. and vm_start_time < self.shutdown_started:
  179. if self.timeout_reached():
  180. reply = QtGui.QMessageBox.question(
  181. None, self.tr("Qube Shutdown"),
  182. self.tr(
  183. "The Qube <b>'{0}'</b> hasn't shutdown within the last "
  184. "{1} seconds, do you want to kill it?<br>").format(
  185. vm.name, self.shutdown_time / 1000),
  186. self.tr("Kill it!"),
  187. self.tr("Wait another {0} seconds...").format(
  188. self.shutdown_time / 1000))
  189. if reply == 0:
  190. try:
  191. vm.kill()
  192. except exc.QubesVMNotStartedError:
  193. # the VM shut down while the user was thinking about
  194. # shutting it down
  195. pass
  196. self.restart_vm_if_needed()
  197. else:
  198. self.shutdown_started = datetime.now()
  199. self.check_again_later()
  200. else:
  201. self.check_again_later()
  202. else:
  203. if vm_is_running:
  204. # Due to unknown reasons, Xen sometimes reports that a domain
  205. # is running even though its start-up timestamp is not valid.
  206. # Make sure that "restart_vm_if_needed" is not called until
  207. # the domain has been completely shut down according to Xen.
  208. self.check_again_later()
  209. return
  210. self.restart_vm_if_needed()
  211. # pylint: disable=too-few-public-methods
  212. class StartVMThread(QtCore.QThread):
  213. def __init__(self, vm):
  214. QtCore.QThread.__init__(self)
  215. self.vm = vm
  216. self.msg = None
  217. def run(self):
  218. try:
  219. self.vm.start()
  220. except exc.QubesException as ex:
  221. self.msg = ("Error starting Qube!", str(ex))
  222. # pylint: disable=too-few-public-methods
  223. class UpdateVMThread(QtCore.QThread):
  224. def __init__(self, vm):
  225. QtCore.QThread.__init__(self)
  226. self.vm = vm
  227. self.msg = None
  228. def run(self):
  229. try:
  230. if self.vm.qid == 0:
  231. subprocess.check_call(
  232. ["/usr/bin/qubes-dom0-update", "--clean", "--gui"])
  233. else:
  234. if not self.vm.is_running():
  235. self.vm.start()
  236. self.vm.run_service("qubes.InstallUpdatesGUI",\
  237. user="root", wait=False)
  238. except (ChildProcessError, exc.QubesException) as ex:
  239. self.msg = ("Error on qube update!", str(ex))
  240. # pylint: disable=too-few-public-methods
  241. class RunCommandThread(QtCore.QThread):
  242. def __init__(self, vm, command_to_run):
  243. QtCore.QThread.__init__(self)
  244. self.vm = vm
  245. self.command_to_run = command_to_run
  246. self.msg = None
  247. def run(self):
  248. try:
  249. self.vm.run(self.command_to_run)
  250. except (ChildProcessError, exc.QubesException) as ex:
  251. self.msg = ("Error while running command!", str(ex))
  252. class VmManagerWindow(ui_qubemanager.Ui_VmManagerWindow, QtGui.QMainWindow):
  253. # pylint: disable=too-many-instance-attributes
  254. row_height = 30
  255. column_width = 200
  256. search = ""
  257. # suppress saving settings while initializing widgets
  258. settings_loaded = False
  259. columns_indices = {"Type": 0,
  260. "Label": 1,
  261. "Name": 2,
  262. "State": 3,
  263. "Template": 4,
  264. "NetVM": 5,
  265. "Size": 6,
  266. "Internal": 7,
  267. "IP": 8,
  268. "Backups": 9,
  269. "Last backup": 10,
  270. }
  271. def __init__(self, qt_app, qubes_app, dispatcher, parent=None):
  272. # pylint: disable=unused-argument
  273. super(VmManagerWindow, self).__init__()
  274. self.setupUi(self)
  275. self.manager_settings = QtCore.QSettings(self)
  276. self.qubes_app = qubes_app
  277. self.qt_app = qt_app
  278. self.searchbox = SearchBox()
  279. self.searchbox.setValidator(QtGui.QRegExpValidator(
  280. QtCore.QRegExp("[a-zA-Z0-9_-]*", QtCore.Qt.CaseInsensitive), None))
  281. self.searchContainer.addWidget(self.searchbox)
  282. self.connect(self.table, QtCore.SIGNAL("itemSelectionChanged()"),
  283. self.table_selection_changed)
  284. self.table.setColumnWidth(0, self.column_width)
  285. self.sort_by_column = "Type"
  286. self.sort_order = QtCore.Qt.AscendingOrder
  287. self.vms_list = []
  288. self.vms_in_table = {}
  289. self.frame_width = 0
  290. self.frame_height = 0
  291. self.columns_actions = {
  292. self.columns_indices["Type"]: self.action_vm_type,
  293. self.columns_indices["Label"]: self.action_label,
  294. self.columns_indices["Name"]: self.action_name,
  295. self.columns_indices["State"]: self.action_state,
  296. self.columns_indices["Template"]: self.action_template,
  297. self.columns_indices["NetVM"]: self.action_netvm,
  298. self.columns_indices["Size"]: self.action_size_on_disk,
  299. self.columns_indices["Internal"]: self.action_internal,
  300. self.columns_indices["IP"]: self
  301. .action_ip, self.columns_indices["Backups"]: self
  302. .action_backups, self.columns_indices["Last backup"]: self
  303. .action_last_backup
  304. }
  305. self.visible_columns_count = len(self.columns_indices)
  306. # Other columns get sensible default sizes, but those have only
  307. # icon content, and thus PyQt makes them too wide
  308. self.table.setColumnWidth(self.columns_indices["State"], 80)
  309. self.table.setColumnWidth(self.columns_indices["Label"], 40)
  310. self.table.setColumnWidth(self.columns_indices["Type"], 40)
  311. self.table.horizontalHeader().setResizeMode(
  312. QtGui.QHeaderView.Interactive)
  313. self.table.horizontalHeader().setStretchLastSection(True)
  314. self.table.horizontalHeader().setMinimumSectionSize(40)
  315. self.context_menu = QtGui.QMenu(self)
  316. self.context_menu.addAction(self.action_settings)
  317. self.context_menu.addAction(self.action_editfwrules)
  318. self.context_menu.addAction(self.action_appmenus)
  319. self.context_menu.addAction(self.action_set_keyboard_layout)
  320. self.context_menu.addSeparator()
  321. self.context_menu.addAction(self.action_updatevm)
  322. self.context_menu.addAction(self.action_run_command_in_vm)
  323. self.context_menu.addAction(self.action_resumevm)
  324. self.context_menu.addAction(self.action_startvm_tools_install)
  325. self.context_menu.addAction(self.action_pausevm)
  326. self.context_menu.addAction(self.action_shutdownvm)
  327. self.context_menu.addAction(self.action_restartvm)
  328. self.context_menu.addAction(self.action_killvm)
  329. self.context_menu.addSeparator()
  330. self.context_menu.addAction(self.action_clonevm)
  331. self.context_menu.addAction(self.action_removevm)
  332. self.context_menu.addSeparator()
  333. self.context_menu.addMenu(self.logs_menu)
  334. self.context_menu.addSeparator()
  335. self.tools_context_menu = QtGui.QMenu(self)
  336. self.tools_context_menu.addAction(self.action_toolbar)
  337. self.tools_context_menu.addAction(self.action_menubar)
  338. self.dom0_context_menu = QtGui.QMenu(self)
  339. self.dom0_context_menu.addAction(self.action_global_settings)
  340. self.dom0_context_menu.addAction(self.action_updatevm)
  341. self.dom0_context_menu.addSeparator()
  342. self.dom0_context_menu.addMenu(self.logs_menu)
  343. self.dom0_context_menu.addSeparator()
  344. self.connect(
  345. self.table.horizontalHeader(),
  346. QtCore.SIGNAL("sortIndicatorChanged(int, Qt::SortOrder)"),
  347. self.sort_indicator_changed)
  348. self.connect(self.table,
  349. QtCore.SIGNAL("customContextMenuRequested(const QPoint&)"),
  350. self.open_context_menu)
  351. self.connect(self.menubar,
  352. QtCore.SIGNAL("customContextMenuRequested(const QPoint&)"),
  353. lambda pos: self.open_tools_context_menu(self.menubar,
  354. pos))
  355. self.connect(self.toolbar,
  356. QtCore.SIGNAL("customContextMenuRequested(const QPoint&)"),
  357. lambda pos: self.open_tools_context_menu(self.toolbar,
  358. pos))
  359. self.connect(self.logs_menu, QtCore.SIGNAL("triggered(QAction *)"),
  360. self.show_log)
  361. self.connect(self.searchbox,
  362. QtCore.SIGNAL("textChanged(const QString&)"),
  363. self.do_search)
  364. self.table.setContentsMargins(0, 0, 0, 0)
  365. self.centralwidget.layout().setContentsMargins(0, 0, 0, 0)
  366. self.layout().setContentsMargins(0, 0, 0, 0)
  367. self.connect(self.action_menubar, QtCore.SIGNAL("toggled(bool)"),
  368. self.showhide_menubar)
  369. self.connect(self.action_toolbar, QtCore.SIGNAL("toggled(bool)"),
  370. self.showhide_toolbar)
  371. self.load_manager_settings()
  372. self.fill_table()
  373. self.update_size_on_disk = False
  374. self.shutdown_monitor = {}
  375. # Connect events
  376. self.dispatcher = dispatcher
  377. dispatcher.add_handler('domain-pre-start',
  378. self.on_domain_status_changed)
  379. dispatcher.add_handler('domain-start', self.on_domain_status_changed)
  380. dispatcher.add_handler('domain-start-failed',
  381. self.on_domain_status_changed)
  382. dispatcher.add_handler('domain-stopped', self.on_domain_status_changed)
  383. dispatcher.add_handler('domain-pre-shutdown',
  384. self.on_domain_status_changed)
  385. dispatcher.add_handler('domain-shutdown', self.on_domain_status_changed)
  386. dispatcher.add_handler('domain-paused', self.on_domain_status_changed)
  387. dispatcher.add_handler('domain-unpaused', self.on_domain_status_changed)
  388. dispatcher.add_handler('domain-add', self.on_domain_added)
  389. dispatcher.add_handler('domain-delete', self.on_domain_removed)
  390. dispatcher.add_handler('property-set:*',
  391. self.on_domain_changed)
  392. dispatcher.add_handler('property-del:*',
  393. self.on_domain_changed)
  394. dispatcher.add_handler('property-load',
  395. self.on_domain_changed)
  396. # It needs to store threads until they finish
  397. self.threads_list = []
  398. self.progress = None
  399. # Check Updates Timer
  400. timer = QtCore.QTimer(self)
  401. timer.timeout.connect(self.check_updates)
  402. timer.start(1000 * 30) # 30s
  403. self.check_updates()
  404. def keyPressEvent(self, event): # pylint: disable=invalid-name
  405. if event.key() == QtCore.Qt.Key_Escape:
  406. self.searchbox.clear()
  407. super(VmManagerWindow, self).keyPressEvent(event)
  408. def clear_threads(self):
  409. for thread in self.threads_list:
  410. if thread.isFinished():
  411. if self.progress:
  412. self.progress.hide()
  413. self.progress = None
  414. if thread.msg:
  415. (title, msg) = thread.msg
  416. QtGui.QMessageBox.warning(
  417. None,
  418. self.tr(title),
  419. self.tr(msg))
  420. self.threads_list.remove(thread)
  421. return
  422. raise RuntimeError('No finished thread found')
  423. def closeEvent(self, event):
  424. # pylint: disable=invalid-name
  425. # save window size at close
  426. self.manager_settings.setValue("window_size", self.size())
  427. event.accept()
  428. def check_updates(self):
  429. for vm in self.qubes_app.domains:
  430. if vm.klass in {'TemplateVM', 'StandaloneVM'}:
  431. try:
  432. self.vms_in_table[vm.qid].info_widget.update_vm_state()
  433. except (exc.QubesException, KeyError):
  434. # the VM might have vanished in the meantime or
  435. # the signal might have been handled in the wrong order
  436. pass
  437. def on_domain_added(self, _submitter, _event, vm, **_kwargs):
  438. row_no = 0
  439. self.table.setSortingEnabled(False)
  440. try:
  441. domain = self.qubes_app.domains[vm]
  442. row_no = self.table.rowCount()
  443. self.table.setRowCount(row_no + 1)
  444. vm_row = VmRowInTable(domain, row_no, self.table)
  445. self.vms_in_table[domain.qid] = vm_row
  446. except (exc.QubesException, KeyError):
  447. if row_no != 0:
  448. self.table.removeRow(row_no)
  449. self.table.setSortingEnabled(True)
  450. self.showhide_vms()
  451. def on_domain_removed(self, _submitter, _event, **kwargs):
  452. row_to_delete = None
  453. qid_to_delete = None
  454. for qid, row in self.vms_in_table.items():
  455. if row.vm.name == kwargs['vm']:
  456. row_to_delete = row
  457. qid_to_delete = qid
  458. if not row_to_delete:
  459. return # for some reason, the VM was removed in some other way
  460. del self.vms_in_table[qid_to_delete]
  461. self.table.removeRow(row_to_delete.name_widget.row())
  462. def on_domain_status_changed(self, vm, _event, **_kwargs):
  463. try:
  464. self.vms_in_table[vm.qid].info_widget.update_vm_state()
  465. except exc.QubesPropertyAccessError:
  466. return # the VM was deleted before its status could be updated
  467. if vm == self.get_selected_vm():
  468. self.table_selection_changed()
  469. if vm.klass == 'TemplateVM':
  470. for row in self.vms_in_table.values():
  471. if getattr(row.vm, 'template', None) == vm:
  472. row.info_widget.update_vm_state()
  473. def on_domain_changed(self, vm, event, **_kwargs):
  474. if not vm: # change of global properties occured
  475. return
  476. try:
  477. self.vms_in_table[vm.qid].update(event=event)
  478. except exc.QubesPropertyAccessError:
  479. return # the VM was deleted before its status could be updated
  480. def load_manager_settings(self):
  481. # visible columns
  482. self.visible_columns_count = 0
  483. for col in self.columns_indices:
  484. col_no = self.columns_indices[col]
  485. visible = self.manager_settings.value(
  486. 'columns/%s' % col,
  487. defaultValue="true")
  488. self.columns_actions[col_no].setChecked(visible == "true")
  489. self.visible_columns_count += 1
  490. self.sort_by_column = str(
  491. self.manager_settings.value("view/sort_column",
  492. defaultValue=self.sort_by_column))
  493. self.sort_order = QtCore.Qt.SortOrder(
  494. self.manager_settings.value("view/sort_order",
  495. defaultValue=self.sort_order))
  496. self.table.sortItems(self.columns_indices[self.sort_by_column],
  497. self.sort_order)
  498. if not self.manager_settings.value("view/menubar_visible",
  499. defaultValue=True):
  500. self.action_menubar.setChecked(False)
  501. if not self.manager_settings.value("view/toolbar_visible",
  502. defaultValue=True):
  503. self.action_toolbar.setChecked(False)
  504. # load last window size
  505. self.resize(self.manager_settings.value("window_size",
  506. QtCore.QSize(1100, 600)))
  507. self.settings_loaded = True
  508. def get_vms_list(self):
  509. return [vm for vm in self.qubes_app.domains]
  510. def fill_table(self):
  511. self.table.setSortingEnabled(False)
  512. vms_list = self.get_vms_list()
  513. vms_in_table = {}
  514. self.table.setRowCount(len(vms_list))
  515. progress = QtGui.QProgressDialog(
  516. self.tr(
  517. "Loading Qube Manager..."), "", 0, len(vms_list))
  518. progress.setWindowTitle(self.tr("Qube Manager"))
  519. progress.setMinimumDuration(1000)
  520. progress.setCancelButton(None)
  521. row_no = 0
  522. for vm in vms_list:
  523. progress.setValue(row_no)
  524. vm_row = VmRowInTable(vm, row_no, self.table)
  525. vms_in_table[vm.qid] = vm_row
  526. row_no += 1
  527. progress.setValue(row_no)
  528. self.vms_list = vms_list
  529. self.vms_in_table = vms_in_table
  530. self.table.setSortingEnabled(True)
  531. def showhide_vms(self):
  532. if not self.search:
  533. for row_no in range(self.table.rowCount()):
  534. self.table.setRowHidden(row_no, False)
  535. else:
  536. for row_no in range(self.table.rowCount()):
  537. widget = self.table.cellWidget(row_no,
  538. self.columns_indices["State"])
  539. show = (self.search in widget.vm.name)
  540. self.table.setRowHidden(row_no, not show)
  541. @QtCore.pyqtSlot(str)
  542. def do_search(self, search):
  543. self.search = str(search)
  544. self.showhide_vms()
  545. # noinspection PyArgumentList
  546. @QtCore.pyqtSlot(name='on_action_search_triggered')
  547. def action_search_triggered(self):
  548. self.searchbox.setFocus()
  549. # noinspection PyPep8Naming
  550. def sort_indicator_changed(self, column, order):
  551. self.sort_by_column = [name for name in self.columns_indices if
  552. self.columns_indices[name] == column][0]
  553. self.sort_order = order
  554. if self.settings_loaded:
  555. self.manager_settings.setValue('view/sort_column',
  556. self.sort_by_column)
  557. self.manager_settings.setValue('view/sort_order', self.sort_order)
  558. self.manager_settings.sync()
  559. def table_selection_changed(self):
  560. vm = self.get_selected_vm()
  561. if vm is not None and vm in self.qubes_app.domains:
  562. # TODO: add boot from device to menu and add windows tools there
  563. # Update available actions:
  564. self.action_settings.setEnabled(vm.klass != 'AdminVM')
  565. self.action_removevm.setEnabled(
  566. vm.klass != 'AdminVM' and not vm.is_running())
  567. self.action_clonevm.setEnabled(vm.klass != 'AdminVM')
  568. self.action_resumevm.setEnabled(
  569. not vm.is_running() or vm.get_power_state() == "Paused")
  570. self.action_pausevm.setEnabled(
  571. vm.is_running() and vm.get_power_state() != "Paused"
  572. and vm.klass != 'AdminVM')
  573. self.action_shutdownvm.setEnabled(
  574. vm.is_running() and vm.get_power_state() != "Paused"
  575. and vm.klass != 'AdminVM')
  576. self.action_restartvm.setEnabled(
  577. vm.is_running() and vm.get_power_state() != "Paused"
  578. and vm.klass != 'AdminVM'
  579. and (vm.klass != 'DispVM' or not vm.auto_cleanup))
  580. self.action_killvm.setEnabled(
  581. (vm.get_power_state() == "Paused" or vm.is_running())
  582. and vm.klass != 'AdminVM')
  583. self.action_appmenus.setEnabled(
  584. vm.klass != 'AdminVM' and vm.klass != 'DispVM'
  585. and not vm.features.get('internal', False))
  586. self.action_editfwrules.setEnabled(vm.klass != 'AdminVM')
  587. self.action_updatevm.setEnabled(getattr(vm, 'updateable', False)
  588. or vm.qid == 0)
  589. self.action_run_command_in_vm.setEnabled(
  590. not vm.get_power_state() == "Paused" and vm.qid != 0)
  591. self.action_set_keyboard_layout.setEnabled(
  592. vm.qid != 0 and
  593. vm.get_power_state() != "Paused" and vm.is_running())
  594. else:
  595. self.action_settings.setEnabled(False)
  596. self.action_removevm.setEnabled(False)
  597. self.action_clonevm.setEnabled(False)
  598. self.action_resumevm.setEnabled(False)
  599. self.action_pausevm.setEnabled(False)
  600. self.action_shutdownvm.setEnabled(False)
  601. self.action_restartvm.setEnabled(False)
  602. self.action_killvm.setEnabled(False)
  603. self.action_appmenus.setEnabled(False)
  604. self.action_editfwrules.setEnabled(False)
  605. self.action_updatevm.setEnabled(False)
  606. self.action_run_command_in_vm.setEnabled(False)
  607. self.action_set_keyboard_layout.setEnabled(False)
  608. # noinspection PyArgumentList
  609. @QtCore.pyqtSlot(name='on_action_createvm_triggered')
  610. def action_createvm_triggered(self): # pylint: disable=no-self-use
  611. create_window = create_new_vm.NewVmDlg(self.qt_app, self.qubes_app)
  612. create_window.exec_()
  613. def get_selected_vm(self):
  614. # vm selection relies on the VmInfo widget's value used
  615. # for sorting by VM name
  616. row_index = self.table.currentRow()
  617. if row_index != -1:
  618. vm_item = self.table.item(row_index, self.columns_indices["Name"])
  619. # here is possible race with update_table timer so check
  620. # if really got the item
  621. if vm_item is None:
  622. return None
  623. qid = vm_item.qid
  624. assert self.vms_in_table[qid] is not None
  625. vm = self.vms_in_table[qid].vm
  626. return vm
  627. return None
  628. # noinspection PyArgumentList
  629. @QtCore.pyqtSlot(name='on_action_removevm_triggered')
  630. def action_removevm_triggered(self):
  631. # pylint: disable=no-else-return
  632. vm = self.get_selected_vm()
  633. dependencies = utils.vm_dependencies(self.qubes_app, vm)
  634. if dependencies:
  635. list_text = "<br>" + \
  636. manager_utils.format_dependencies_list(dependencies) + \
  637. "<br>"
  638. info_dialog = QtGui.QMessageBox(self)
  639. info_dialog.setWindowTitle(self.tr("Warning!"))
  640. info_dialog.setText(
  641. self.tr("This qube cannot be removed. It is used as:"
  642. " <br> {} <small>If you want to remove this qube, "
  643. "you should remove or change settings of each qube "
  644. "or setting that uses it.</small>").format(list_text))
  645. info_dialog.setModal(False)
  646. info_dialog.show()
  647. return
  648. (requested_name, ok) = QtGui.QInputDialog.getText(
  649. None, self.tr("Qube Removal Confirmation"),
  650. self.tr("Are you sure you want to remove the Qube <b>'{0}'</b>"
  651. "?<br> All data on this Qube's private storage will be "
  652. "lost!<br><br>Type the name of the Qube (<b>{1}</b>) below "
  653. "to confirm:").format(vm.name, vm.name))
  654. if not ok:
  655. # user clicked cancel
  656. return
  657. if requested_name != vm.name:
  658. # name did not match
  659. QtGui.QMessageBox.warning(
  660. None,
  661. self.tr("Qube removal confirmation failed"),
  662. self.tr(
  663. "Entered name did not match! Not removing "
  664. "{0}.").format(vm.name))
  665. return
  666. else:
  667. # remove the VM
  668. thread = common_threads.RemoveVMThread(vm)
  669. self.threads_list.append(thread)
  670. thread.finished.connect(self.clear_threads)
  671. thread.start()
  672. # noinspection PyArgumentList
  673. @QtCore.pyqtSlot(name='on_action_clonevm_triggered')
  674. def action_clonevm_triggered(self):
  675. vm = self.get_selected_vm()
  676. name_number = 1
  677. name_format = vm.name + '-clone-%d'
  678. while name_format % name_number in self.qubes_app.domains.keys():
  679. name_number += 1
  680. (clone_name, ok) = QtGui.QInputDialog.getText(
  681. self, self.tr('Qubes clone Qube'),
  682. self.tr('Enter name for Qube <b>{}</b> clone:').format(vm.name),
  683. text=(name_format % name_number))
  684. if not ok or clone_name == "":
  685. return
  686. self.progress = QtGui.QProgressDialog(
  687. self.tr(
  688. "Cloning Qube..."), "", 0, 0)
  689. self.progress.setCancelButton(None)
  690. self.progress.setModal(True)
  691. self.progress.show()
  692. thread = common_threads.CloneVMThread(vm, clone_name)
  693. thread.finished.connect(self.clear_threads)
  694. self.threads_list.append(thread)
  695. thread.start()
  696. # noinspection PyArgumentList
  697. @QtCore.pyqtSlot(name='on_action_resumevm_triggered')
  698. def action_resumevm_triggered(self):
  699. vm = self.get_selected_vm()
  700. if vm.get_power_state() in ["Paused", "Suspended"]:
  701. try:
  702. vm.unpause()
  703. except exc.QubesException as ex:
  704. QtGui.QMessageBox.warning(
  705. None, self.tr("Error unpausing Qube!"),
  706. self.tr("ERROR: {0}").format(ex))
  707. return
  708. self.start_vm(vm)
  709. def start_vm(self, vm):
  710. if vm.is_running():
  711. return
  712. thread = StartVMThread(vm)
  713. self.threads_list.append(thread)
  714. thread.finished.connect(self.clear_threads)
  715. thread.start()
  716. # noinspection PyArgumentList
  717. @QtCore.pyqtSlot(name='on_action_startvm_tools_install_triggered')
  718. # TODO: replace with boot from device
  719. def action_startvm_tools_install_triggered(self):
  720. # pylint: disable=invalid-name
  721. pass
  722. @QtCore.pyqtSlot(name='on_action_pausevm_triggered')
  723. def action_pausevm_triggered(self):
  724. vm = self.get_selected_vm()
  725. try:
  726. vm.pause()
  727. except exc.QubesException as ex:
  728. QtGui.QMessageBox.warning(
  729. None,
  730. self.tr("Error pausing Qube!"),
  731. self.tr("ERROR: {0}").format(ex))
  732. return
  733. # noinspection PyArgumentList
  734. @QtCore.pyqtSlot(name='on_action_shutdownvm_triggered')
  735. def action_shutdownvm_triggered(self):
  736. vm = self.get_selected_vm()
  737. reply = QtGui.QMessageBox.question(
  738. None, self.tr("Qube Shutdown Confirmation"),
  739. self.tr("Are you sure you want to power down the Qube"
  740. " <b>'{0}'</b>?<br><small>This will shutdown all the "
  741. "running applications within this Qube.</small>").format(
  742. vm.name), QtGui.QMessageBox.Yes | QtGui.QMessageBox.Cancel)
  743. if reply == QtGui.QMessageBox.Yes:
  744. self.shutdown_vm(vm)
  745. def shutdown_vm(self, vm, shutdown_time=vm_shutdown_timeout,
  746. check_time=vm_restart_check_timeout, and_restart=False):
  747. try:
  748. vm.shutdown()
  749. except exc.QubesException as ex:
  750. QtGui.QMessageBox.warning(
  751. None,
  752. self.tr("Error shutting down Qube!"),
  753. self.tr("ERROR: {0}").format(ex))
  754. return
  755. self.shutdown_monitor[vm.qid] = VmShutdownMonitor(vm, shutdown_time,
  756. check_time,
  757. and_restart, self)
  758. # noinspection PyCallByClass,PyTypeChecker
  759. QtCore.QTimer.singleShot(check_time, self.shutdown_monitor[
  760. vm.qid].check_if_vm_has_shutdown)
  761. # noinspection PyArgumentList
  762. @QtCore.pyqtSlot(name='on_action_restartvm_triggered')
  763. def action_restartvm_triggered(self):
  764. vm = self.get_selected_vm()
  765. reply = QtGui.QMessageBox.question(
  766. None, self.tr("Qube Restart Confirmation"),
  767. self.tr("Are you sure you want to restart the Qube <b>'{0}'</b>?"
  768. "<br><small>This will shutdown all the running "
  769. "applications within this Qube.</small>").format(vm.name),
  770. QtGui.QMessageBox.Yes | QtGui.QMessageBox.Cancel)
  771. if reply == QtGui.QMessageBox.Yes:
  772. # in case the user shut down the VM in the meantime
  773. if vm.is_running():
  774. self.shutdown_vm(vm, and_restart=True)
  775. else:
  776. self.start_vm(vm)
  777. # noinspection PyArgumentList
  778. @QtCore.pyqtSlot(name='on_action_killvm_triggered')
  779. def action_killvm_triggered(self):
  780. vm = self.get_selected_vm()
  781. if not (vm.is_running() or vm.is_paused()):
  782. info = self.tr("Qube <b>'{0}'</b> is not running. Are you "
  783. "absolutely sure you want to try to kill it?<br>"
  784. "<small>This will end <b>(not shutdown!)</b> all "
  785. "the running applications within this "
  786. "Qube.</small>").format(vm.name)
  787. else:
  788. info = self.tr("Are you sure you want to kill the Qube "
  789. "<b>'{0}'</b>?<br><small>This will end <b>(not "
  790. "shutdown!)</b> all the running applications within "
  791. "this Qube.</small>").format(vm.name)
  792. reply = QtGui.QMessageBox.question(
  793. None, self.tr("Qube Kill Confirmation"), info,
  794. QtGui.QMessageBox.Yes | QtGui.QMessageBox.Cancel,
  795. QtGui.QMessageBox.Cancel)
  796. if reply == QtGui.QMessageBox.Yes:
  797. try:
  798. vm.kill()
  799. except exc.QubesException as ex:
  800. QtGui.QMessageBox.critical(
  801. None, self.tr("Error while killing Qube!"),
  802. self.tr(
  803. "<b>An exception ocurred while killing {0}.</b><br>"
  804. "ERROR: {1}").format(vm.name, ex))
  805. return
  806. # noinspection PyArgumentList
  807. @QtCore.pyqtSlot(name='on_action_settings_triggered')
  808. def action_settings_triggered(self):
  809. vm = self.get_selected_vm()
  810. if vm:
  811. settings_window = settings.VMSettingsWindow(
  812. vm, self.qt_app, "basic")
  813. settings_window.exec_()
  814. vm_deleted = False
  815. try:
  816. # the VM might not exist after running Settings - it might
  817. # have been cloned or removed
  818. self.vms_in_table[vm.qid].update()
  819. except exc.QubesException:
  820. # TODO: this will be replaced by proper signal handling once
  821. # settings are migrated to AdminAPI
  822. vm_deleted = True
  823. if vm_deleted:
  824. for row in self.vms_in_table:
  825. try:
  826. self.vms_in_table[row].update()
  827. except exc.QubesException:
  828. pass
  829. # noinspection PyArgumentList
  830. @QtCore.pyqtSlot(name='on_action_appmenus_triggered')
  831. def action_appmenus_triggered(self):
  832. vm = self.get_selected_vm()
  833. if vm:
  834. settings_window = settings.VMSettingsWindow(
  835. vm, self.qt_app, "applications")
  836. settings_window.exec_()
  837. # noinspection PyArgumentList
  838. @QtCore.pyqtSlot(name='on_action_updatevm_triggered')
  839. def action_updatevm_triggered(self):
  840. vm = self.get_selected_vm()
  841. if not vm.is_running():
  842. reply = QtGui.QMessageBox.question(
  843. None, self.tr("Qube Update Confirmation"),
  844. self.tr(
  845. "<b>{0}</b><br>The Qube has to be running to be updated."
  846. "<br>Do you want to start it?<br>").format(vm.name),
  847. QtGui.QMessageBox.Yes | QtGui.QMessageBox.Cancel)
  848. if reply != QtGui.QMessageBox.Yes:
  849. return
  850. thread = UpdateVMThread(vm)
  851. self.threads_list.append(thread)
  852. thread.finished.connect(self.clear_threads)
  853. thread.start()
  854. # noinspection PyArgumentList
  855. @QtCore.pyqtSlot(name='on_action_run_command_in_vm_triggered')
  856. def action_run_command_in_vm_triggered(self):
  857. # pylint: disable=invalid-name
  858. vm = self.get_selected_vm()
  859. (command_to_run, ok) = QtGui.QInputDialog.getText(
  860. self, self.tr('Qubes command entry'),
  861. self.tr('Run command in <b>{}</b>:').format(vm.name))
  862. if not ok or command_to_run == "":
  863. return
  864. thread = RunCommandThread(vm, command_to_run)
  865. self.threads_list.append(thread)
  866. thread.finished.connect(self.clear_threads)
  867. thread.start()
  868. # noinspection PyArgumentList
  869. @QtCore.pyqtSlot(name='on_action_set_keyboard_layout_triggered')
  870. def action_set_keyboard_layout_triggered(self):
  871. # pylint: disable=invalid-name
  872. vm = self.get_selected_vm()
  873. vm.run('qubes-change-keyboard-layout')
  874. # noinspection PyArgumentList
  875. @QtCore.pyqtSlot(name='on_action_editfwrules_triggered')
  876. def action_editfwrules_triggered(self):
  877. vm = self.get_selected_vm()
  878. settings_window = settings.VMSettingsWindow(vm, self.qt_app, "firewall")
  879. settings_window.exec_()
  880. # noinspection PyArgumentList
  881. @QtCore.pyqtSlot(name='on_action_global_settings_triggered')
  882. def action_global_settings_triggered(self): # pylint: disable=invalid-name
  883. global_settings_window = global_settings.GlobalSettingsWindow(
  884. self.qt_app,
  885. self.qubes_app)
  886. global_settings_window.exec_()
  887. # noinspection PyArgumentList
  888. @QtCore.pyqtSlot(name='on_action_manage_templates_triggered')
  889. def action_manage_templates_triggered(self):
  890. # pylint: disable=invalid-name, no-self-use
  891. subprocess.check_call('qubes-template-manager')
  892. # noinspection PyArgumentList
  893. @QtCore.pyqtSlot(name='on_action_show_network_triggered')
  894. def action_show_network_triggered(self):
  895. pass
  896. # TODO: revive for 4.1
  897. # network_notes_dialog = NetworkNotesDialog()
  898. # network_notes_dialog.exec_()
  899. # noinspection PyArgumentList
  900. @QtCore.pyqtSlot(name='on_action_restore_triggered')
  901. def action_restore_triggered(self):
  902. restore_window = restore.RestoreVMsWindow(self.qt_app, self.qubes_app)
  903. restore_window.exec_()
  904. # noinspection PyArgumentList
  905. @QtCore.pyqtSlot(name='on_action_backup_triggered')
  906. def action_backup_triggered(self):
  907. backup_window = backup.BackupVMsWindow(self.qt_app, self.qubes_app,
  908. self.dispatcher, self)
  909. backup_window.show()
  910. # noinspection PyArgumentList
  911. @QtCore.pyqtSlot(name='on_action_exit_triggered')
  912. def action_exit_triggered(self):
  913. self.close()
  914. def showhide_menubar(self, checked):
  915. self.menubar.setVisible(checked)
  916. if not checked:
  917. self.context_menu.addAction(self.action_menubar)
  918. else:
  919. self.context_menu.removeAction(self.action_menubar)
  920. if self.settings_loaded:
  921. self.manager_settings.setValue('view/menubar_visible', checked)
  922. self.manager_settings.sync()
  923. def showhide_toolbar(self, checked):
  924. self.toolbar.setVisible(checked)
  925. if not checked:
  926. self.context_menu.addAction(self.action_toolbar)
  927. else:
  928. self.context_menu.removeAction(self.action_toolbar)
  929. if self.settings_loaded:
  930. self.manager_settings.setValue('view/toolbar_visible', checked)
  931. self.manager_settings.sync()
  932. def showhide_column(self, col_num, show):
  933. self.table.setColumnHidden(col_num, not show)
  934. val = 1 if show else -1
  935. self.visible_columns_count += val
  936. if self.visible_columns_count == 1:
  937. # disable hiding the last one
  938. for col in self.columns_actions:
  939. if self.columns_actions[col].isChecked():
  940. self.columns_actions[col].setEnabled(False)
  941. break
  942. elif self.visible_columns_count == 2 and val == 1:
  943. # enable hiding previously disabled column
  944. for col in self.columns_actions:
  945. if not self.columns_actions[col].isEnabled():
  946. self.columns_actions[col].setEnabled(True)
  947. break
  948. if self.settings_loaded:
  949. col_name = [name for name in self.columns_indices if
  950. self.columns_indices[name] == col_num][0]
  951. self.manager_settings.setValue('columns/%s' % col_name, show)
  952. self.manager_settings.sync()
  953. def on_action_vm_type_toggled(self, checked):
  954. self.showhide_column(self.columns_indices['Type'], checked)
  955. def on_action_label_toggled(self, checked):
  956. self.showhide_column(self.columns_indices['Label'], checked)
  957. def on_action_name_toggled(self, checked):
  958. self.showhide_column(self.columns_indices['Name'], checked)
  959. def on_action_state_toggled(self, checked):
  960. self.showhide_column(self.columns_indices['State'], checked)
  961. def on_action_internal_toggled(self, checked):
  962. self.showhide_column(self.columns_indices['Internal'], checked)
  963. def on_action_ip_toggled(self, checked):
  964. self.showhide_column(self.columns_indices['IP'], checked)
  965. def on_action_backups_toggled(self, checked):
  966. self.showhide_column(self.columns_indices['Backups'], checked)
  967. def on_action_last_backup_toggled(self, checked):
  968. self.showhide_column(self.columns_indices['Last backup'], checked)
  969. def on_action_template_toggled(self, checked):
  970. self.showhide_column(self.columns_indices['Template'], checked)
  971. def on_action_netvm_toggled(self, checked):
  972. self.showhide_column(self.columns_indices['NetVM'], checked)
  973. def on_action_size_on_disk_toggled(self, checked):
  974. self.showhide_column(self.columns_indices['Size'], checked)
  975. # noinspection PyArgumentList
  976. @QtCore.pyqtSlot(name='on_action_about_qubes_triggered')
  977. def action_about_qubes_triggered(self): # pylint: disable=no-self-use
  978. about = AboutDialog()
  979. about.exec_()
  980. def createPopupMenu(self): # pylint: disable=invalid-name
  981. menu = QtGui.QMenu()
  982. menu.addAction(self.action_toolbar)
  983. menu.addAction(self.action_menubar)
  984. return menu
  985. def open_tools_context_menu(self, widget, point):
  986. self.tools_context_menu.exec_(widget.mapToGlobal(point))
  987. @QtCore.pyqtSlot('const QPoint&')
  988. def open_context_menu(self, point):
  989. try:
  990. vm = self.get_selected_vm()
  991. # logs menu
  992. self.logs_menu.clear()
  993. if vm.qid == 0:
  994. logfiles = ["/var/log/xen/console/hypervisor.log"]
  995. else:
  996. logfiles = [
  997. "/var/log/xen/console/guest-" + vm.name + ".log",
  998. "/var/log/xen/console/guest-" + vm.name + "-dm.log",
  999. "/var/log/qubes/guid." + vm.name + ".log",
  1000. "/var/log/qubes/qrexec." + vm.name + ".log",
  1001. ]
  1002. menu_empty = True
  1003. for logfile in logfiles:
  1004. if os.path.exists(logfile):
  1005. action = self.logs_menu.addAction(QtGui.QIcon(":/log.png"),
  1006. logfile)
  1007. action.setData(logfile)
  1008. menu_empty = False
  1009. self.logs_menu.setEnabled(not menu_empty)
  1010. if vm.qid == 0:
  1011. self.dom0_context_menu.exec_(self.table.mapToGlobal(
  1012. point + QtCore.QPoint(10, 0)))
  1013. else:
  1014. self.context_menu.exec_(self.table.mapToGlobal(
  1015. point + QtCore.QPoint(10, 0)))
  1016. except exc.QubesPropertyAccessError:
  1017. pass
  1018. @QtCore.pyqtSlot('QAction *')
  1019. def show_log(self, action):
  1020. log = str(action.data())
  1021. log_dlg = log_dialog.LogDialog(self.qt_app, log)
  1022. log_dlg.exec_()
  1023. # Bases on the original code by:
  1024. # Copyright (c) 2002-2007 Pascal Varet <p.varet@gmail.com>
  1025. def handle_exception(exc_type, exc_value, exc_traceback):
  1026. filename, line, dummy, dummy = traceback.extract_tb(exc_traceback).pop()
  1027. filename = os.path.basename(filename)
  1028. error = "%s: %s" % (exc_type.__name__, exc_value)
  1029. strace = ""
  1030. stacktrace = traceback.extract_tb(exc_traceback)
  1031. while stacktrace:
  1032. (filename, line, func, txt) = stacktrace.pop()
  1033. strace += "----\n"
  1034. strace += "line: %s\n" % txt
  1035. strace += "func: %s\n" % func
  1036. strace += "line no.: %d\n" % line
  1037. strace += "file: %s\n" % filename
  1038. msg_box = QtGui.QMessageBox()
  1039. msg_box.setDetailedText(strace)
  1040. msg_box.setIcon(QtGui.QMessageBox.Critical)
  1041. msg_box.setWindowTitle("Houston, we have a problem...")
  1042. msg_box.setText("Whoops. A critical error has occured. "
  1043. "This is most likely a bug in Qubes Manager.<br><br>"
  1044. "<b><i>%s</i></b>" % error +
  1045. "<br/>at line <b>%d</b><br/>of file %s.<br/><br/>"
  1046. % (line, filename))
  1047. msg_box.exec_()
  1048. def loop_shutdown():
  1049. pending = asyncio.Task.all_tasks()
  1050. for task in pending:
  1051. with suppress(asyncio.CancelledError):
  1052. task.cancel()
  1053. def main():
  1054. qt_app = QtGui.QApplication(sys.argv)
  1055. qt_app.setOrganizationName("The Qubes Project")
  1056. qt_app.setOrganizationDomain("http://qubes-os.org")
  1057. qt_app.setApplicationName("Qube Manager")
  1058. qt_app.setWindowIcon(QtGui.QIcon.fromTheme("qubes-manager"))
  1059. qt_app.lastWindowClosed.connect(loop_shutdown)
  1060. qubes_app = Qubes()
  1061. loop = quamash.QEventLoop(qt_app)
  1062. asyncio.set_event_loop(loop)
  1063. dispatcher = events.EventsDispatcher(qubes_app)
  1064. manager_window = VmManagerWindow(qt_app, qubes_app, dispatcher)
  1065. manager_window.show()
  1066. try:
  1067. loop.run_until_complete(
  1068. asyncio.ensure_future(dispatcher.listen_for_events()))
  1069. except asyncio.CancelledError:
  1070. pass
  1071. except Exception: # pylint: disable=broad-except
  1072. loop_shutdown()
  1073. exc_type, exc_value, exc_traceback = sys.exc_info()[:3]
  1074. handle_exception(exc_type, exc_value, exc_traceback)
  1075. if __name__ == "__main__":
  1076. main()