qube_manager.py 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307
  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. # apply DSA-4371
  237. with open('/usr/libexec/qubes-manager/dsa-4371-update', 'rb') \
  238. as dsa4371update:
  239. stdout, stderr = self.vm.run_service_for_stdio(
  240. "qubes.VMShell",
  241. user="root",
  242. input=dsa4371update.read())
  243. if stdout == b'changed=yes\n':
  244. subprocess.call(['notify-send', '-i', 'dialog-information',
  245. 'Debian DSA-4371 fix installed in {}'.format(
  246. self.vm.name)])
  247. elif stdout == b'changed=no\n':
  248. pass
  249. else:
  250. raise exc.QubesException(
  251. "Failed to apply DSA-4371 fix: {}".format(
  252. stderr.decode('ascii')))
  253. self.vm.run_service("qubes.InstallUpdatesGUI",\
  254. user="root", wait=False)
  255. except (ChildProcessError, exc.QubesException) as ex:
  256. self.msg = ("Error on qube update!", str(ex))
  257. # pylint: disable=too-few-public-methods
  258. class RunCommandThread(QtCore.QThread):
  259. def __init__(self, vm, command_to_run):
  260. QtCore.QThread.__init__(self)
  261. self.vm = vm
  262. self.command_to_run = command_to_run
  263. self.msg = None
  264. def run(self):
  265. try:
  266. self.vm.run(self.command_to_run)
  267. except (ChildProcessError, exc.QubesException) as ex:
  268. self.msg = ("Error while running command!", str(ex))
  269. class VmManagerWindow(ui_qubemanager.Ui_VmManagerWindow, QtGui.QMainWindow):
  270. # pylint: disable=too-many-instance-attributes
  271. row_height = 30
  272. column_width = 200
  273. search = ""
  274. # suppress saving settings while initializing widgets
  275. settings_loaded = False
  276. columns_indices = {"Type": 0,
  277. "Label": 1,
  278. "Name": 2,
  279. "State": 3,
  280. "Template": 4,
  281. "NetVM": 5,
  282. "Size": 6,
  283. "Internal": 7,
  284. "IP": 8,
  285. "Backups": 9,
  286. "Last backup": 10,
  287. }
  288. def __init__(self, qt_app, qubes_app, dispatcher, parent=None):
  289. # pylint: disable=unused-argument
  290. super(VmManagerWindow, self).__init__()
  291. self.setupUi(self)
  292. self.manager_settings = QtCore.QSettings(self)
  293. self.qubes_app = qubes_app
  294. self.qt_app = qt_app
  295. self.searchbox = SearchBox()
  296. self.searchbox.setValidator(QtGui.QRegExpValidator(
  297. QtCore.QRegExp("[a-zA-Z0-9_-]*", QtCore.Qt.CaseInsensitive), None))
  298. self.searchContainer.addWidget(self.searchbox)
  299. self.connect(self.table, QtCore.SIGNAL("itemSelectionChanged()"),
  300. self.table_selection_changed)
  301. self.table.setColumnWidth(0, self.column_width)
  302. self.sort_by_column = "Type"
  303. self.sort_order = QtCore.Qt.AscendingOrder
  304. self.vms_list = []
  305. self.vms_in_table = {}
  306. self.frame_width = 0
  307. self.frame_height = 0
  308. self.columns_actions = {
  309. self.columns_indices["Type"]: self.action_vm_type,
  310. self.columns_indices["Label"]: self.action_label,
  311. self.columns_indices["Name"]: self.action_name,
  312. self.columns_indices["State"]: self.action_state,
  313. self.columns_indices["Template"]: self.action_template,
  314. self.columns_indices["NetVM"]: self.action_netvm,
  315. self.columns_indices["Size"]: self.action_size_on_disk,
  316. self.columns_indices["Internal"]: self.action_internal,
  317. self.columns_indices["IP"]: self
  318. .action_ip, self.columns_indices["Backups"]: self
  319. .action_backups, self.columns_indices["Last backup"]: self
  320. .action_last_backup
  321. }
  322. self.visible_columns_count = len(self.columns_indices)
  323. # Other columns get sensible default sizes, but those have only
  324. # icon content, and thus PyQt makes them too wide
  325. self.table.setColumnWidth(self.columns_indices["State"], 80)
  326. self.table.setColumnWidth(self.columns_indices["Label"], 40)
  327. self.table.setColumnWidth(self.columns_indices["Type"], 40)
  328. self.table.horizontalHeader().setResizeMode(
  329. QtGui.QHeaderView.Interactive)
  330. self.table.horizontalHeader().setStretchLastSection(True)
  331. self.table.horizontalHeader().setMinimumSectionSize(40)
  332. self.context_menu = QtGui.QMenu(self)
  333. self.context_menu.addAction(self.action_settings)
  334. self.context_menu.addAction(self.action_editfwrules)
  335. self.context_menu.addAction(self.action_appmenus)
  336. self.context_menu.addAction(self.action_set_keyboard_layout)
  337. self.context_menu.addSeparator()
  338. self.context_menu.addAction(self.action_updatevm)
  339. self.context_menu.addAction(self.action_run_command_in_vm)
  340. self.context_menu.addAction(self.action_resumevm)
  341. self.context_menu.addAction(self.action_startvm_tools_install)
  342. self.context_menu.addAction(self.action_pausevm)
  343. self.context_menu.addAction(self.action_shutdownvm)
  344. self.context_menu.addAction(self.action_restartvm)
  345. self.context_menu.addAction(self.action_killvm)
  346. self.context_menu.addSeparator()
  347. self.context_menu.addAction(self.action_clonevm)
  348. self.context_menu.addAction(self.action_removevm)
  349. self.context_menu.addSeparator()
  350. self.context_menu.addMenu(self.logs_menu)
  351. self.context_menu.addSeparator()
  352. self.tools_context_menu = QtGui.QMenu(self)
  353. self.tools_context_menu.addAction(self.action_toolbar)
  354. self.tools_context_menu.addAction(self.action_menubar)
  355. self.dom0_context_menu = QtGui.QMenu(self)
  356. self.dom0_context_menu.addAction(self.action_global_settings)
  357. self.dom0_context_menu.addAction(self.action_updatevm)
  358. self.dom0_context_menu.addSeparator()
  359. self.dom0_context_menu.addMenu(self.logs_menu)
  360. self.dom0_context_menu.addSeparator()
  361. self.connect(
  362. self.table.horizontalHeader(),
  363. QtCore.SIGNAL("sortIndicatorChanged(int, Qt::SortOrder)"),
  364. self.sort_indicator_changed)
  365. self.connect(self.table,
  366. QtCore.SIGNAL("customContextMenuRequested(const QPoint&)"),
  367. self.open_context_menu)
  368. self.connect(self.menubar,
  369. QtCore.SIGNAL("customContextMenuRequested(const QPoint&)"),
  370. lambda pos: self.open_tools_context_menu(self.menubar,
  371. pos))
  372. self.connect(self.toolbar,
  373. QtCore.SIGNAL("customContextMenuRequested(const QPoint&)"),
  374. lambda pos: self.open_tools_context_menu(self.toolbar,
  375. pos))
  376. self.connect(self.logs_menu, QtCore.SIGNAL("triggered(QAction *)"),
  377. self.show_log)
  378. self.connect(self.searchbox,
  379. QtCore.SIGNAL("textChanged(const QString&)"),
  380. self.do_search)
  381. self.table.setContentsMargins(0, 0, 0, 0)
  382. self.centralwidget.layout().setContentsMargins(0, 0, 0, 0)
  383. self.layout().setContentsMargins(0, 0, 0, 0)
  384. self.connect(self.action_menubar, QtCore.SIGNAL("toggled(bool)"),
  385. self.showhide_menubar)
  386. self.connect(self.action_toolbar, QtCore.SIGNAL("toggled(bool)"),
  387. self.showhide_toolbar)
  388. self.load_manager_settings()
  389. self.fill_table()
  390. self.update_size_on_disk = False
  391. self.shutdown_monitor = {}
  392. # Connect events
  393. self.dispatcher = dispatcher
  394. dispatcher.add_handler('domain-pre-start',
  395. self.on_domain_status_changed)
  396. dispatcher.add_handler('domain-start', self.on_domain_status_changed)
  397. dispatcher.add_handler('domain-start-failed',
  398. self.on_domain_status_changed)
  399. dispatcher.add_handler('domain-stopped', self.on_domain_status_changed)
  400. dispatcher.add_handler('domain-pre-shutdown',
  401. self.on_domain_status_changed)
  402. dispatcher.add_handler('domain-shutdown', self.on_domain_status_changed)
  403. dispatcher.add_handler('domain-paused', self.on_domain_status_changed)
  404. dispatcher.add_handler('domain-unpaused', self.on_domain_status_changed)
  405. dispatcher.add_handler('domain-add', self.on_domain_added)
  406. dispatcher.add_handler('domain-delete', self.on_domain_removed)
  407. dispatcher.add_handler('property-set:*',
  408. self.on_domain_changed)
  409. dispatcher.add_handler('property-del:*',
  410. self.on_domain_changed)
  411. dispatcher.add_handler('property-load',
  412. self.on_domain_changed)
  413. # It needs to store threads until they finish
  414. self.threads_list = []
  415. self.progress = None
  416. # Check Updates Timer
  417. timer = QtCore.QTimer(self)
  418. timer.timeout.connect(self.check_updates)
  419. timer.start(1000 * 30) # 30s
  420. self.check_updates()
  421. def keyPressEvent(self, event): # pylint: disable=invalid-name
  422. if event.key() == QtCore.Qt.Key_Escape:
  423. self.searchbox.clear()
  424. super(VmManagerWindow, self).keyPressEvent(event)
  425. def clear_threads(self):
  426. for thread in self.threads_list:
  427. if thread.isFinished():
  428. if self.progress:
  429. self.progress.hide()
  430. self.progress = None
  431. if thread.msg:
  432. (title, msg) = thread.msg
  433. QtGui.QMessageBox.warning(
  434. None,
  435. self.tr(title),
  436. self.tr(msg))
  437. self.threads_list.remove(thread)
  438. return
  439. raise RuntimeError('No finished thread found')
  440. def closeEvent(self, event):
  441. # pylint: disable=invalid-name
  442. # save window size at close
  443. self.manager_settings.setValue("window_size", self.size())
  444. event.accept()
  445. def check_updates(self):
  446. for vm in self.qubes_app.domains:
  447. if vm.klass in {'TemplateVM', 'StandaloneVM'}:
  448. try:
  449. self.vms_in_table[vm.qid].info_widget.update_vm_state()
  450. except (exc.QubesException, KeyError):
  451. # the VM might have vanished in the meantime or
  452. # the signal might have been handled in the wrong order
  453. pass
  454. def on_domain_added(self, _submitter, _event, vm, **_kwargs):
  455. row_no = 0
  456. self.table.setSortingEnabled(False)
  457. try:
  458. domain = self.qubes_app.domains[vm]
  459. row_no = self.table.rowCount()
  460. self.table.setRowCount(row_no + 1)
  461. vm_row = VmRowInTable(domain, row_no, self.table)
  462. self.vms_in_table[domain.qid] = vm_row
  463. except (exc.QubesException, KeyError):
  464. if row_no != 0:
  465. self.table.removeRow(row_no)
  466. self.table.setSortingEnabled(True)
  467. self.showhide_vms()
  468. def on_domain_removed(self, _submitter, _event, **kwargs):
  469. row_to_delete = None
  470. qid_to_delete = None
  471. for qid, row in self.vms_in_table.items():
  472. if row.vm.name == kwargs['vm']:
  473. row_to_delete = row
  474. qid_to_delete = qid
  475. if not row_to_delete:
  476. return # for some reason, the VM was removed in some other way
  477. del self.vms_in_table[qid_to_delete]
  478. self.table.removeRow(row_to_delete.name_widget.row())
  479. def on_domain_status_changed(self, vm, _event, **_kwargs):
  480. try:
  481. self.vms_in_table[vm.qid].info_widget.update_vm_state()
  482. except exc.QubesPropertyAccessError:
  483. return # the VM was deleted before its status could be updated
  484. if vm == self.get_selected_vm():
  485. self.table_selection_changed()
  486. if vm.klass == 'TemplateVM':
  487. for row in self.vms_in_table.values():
  488. if getattr(row.vm, 'template', None) == vm:
  489. row.info_widget.update_vm_state()
  490. def on_domain_changed(self, vm, event, **_kwargs):
  491. if not vm: # change of global properties occured
  492. return
  493. try:
  494. self.vms_in_table[vm.qid].update(event=event)
  495. except exc.QubesPropertyAccessError:
  496. return # the VM was deleted before its status could be updated
  497. def load_manager_settings(self):
  498. # visible columns
  499. self.visible_columns_count = 0
  500. for col in self.columns_indices:
  501. col_no = self.columns_indices[col]
  502. visible = self.manager_settings.value(
  503. 'columns/%s' % col,
  504. defaultValue="true")
  505. self.columns_actions[col_no].setChecked(visible == "true")
  506. self.visible_columns_count += 1
  507. self.sort_by_column = str(
  508. self.manager_settings.value("view/sort_column",
  509. defaultValue=self.sort_by_column))
  510. self.sort_order = QtCore.Qt.SortOrder(
  511. self.manager_settings.value("view/sort_order",
  512. defaultValue=self.sort_order))
  513. self.table.sortItems(self.columns_indices[self.sort_by_column],
  514. self.sort_order)
  515. if not self.manager_settings.value("view/menubar_visible",
  516. defaultValue=True):
  517. self.action_menubar.setChecked(False)
  518. if not self.manager_settings.value("view/toolbar_visible",
  519. defaultValue=True):
  520. self.action_toolbar.setChecked(False)
  521. # load last window size
  522. self.resize(self.manager_settings.value("window_size",
  523. QtCore.QSize(1100, 600)))
  524. self.settings_loaded = True
  525. def get_vms_list(self):
  526. return [vm for vm in self.qubes_app.domains]
  527. def fill_table(self):
  528. self.table.setSortingEnabled(False)
  529. vms_list = self.get_vms_list()
  530. vms_in_table = {}
  531. self.table.setRowCount(len(vms_list))
  532. progress = QtGui.QProgressDialog(
  533. self.tr(
  534. "Loading Qube Manager..."), "", 0, len(vms_list))
  535. progress.setWindowTitle(self.tr("Qube Manager"))
  536. progress.setMinimumDuration(1000)
  537. progress.setCancelButton(None)
  538. row_no = 0
  539. for vm in vms_list:
  540. progress.setValue(row_no)
  541. vm_row = VmRowInTable(vm, row_no, self.table)
  542. vms_in_table[vm.qid] = vm_row
  543. row_no += 1
  544. progress.setValue(row_no)
  545. self.vms_list = vms_list
  546. self.vms_in_table = vms_in_table
  547. self.table.setSortingEnabled(True)
  548. def showhide_vms(self):
  549. if not self.search:
  550. for row_no in range(self.table.rowCount()):
  551. self.table.setRowHidden(row_no, False)
  552. else:
  553. for row_no in range(self.table.rowCount()):
  554. widget = self.table.cellWidget(row_no,
  555. self.columns_indices["State"])
  556. show = (self.search in widget.vm.name)
  557. self.table.setRowHidden(row_no, not show)
  558. @QtCore.pyqtSlot(str)
  559. def do_search(self, search):
  560. self.search = str(search)
  561. self.showhide_vms()
  562. # noinspection PyArgumentList
  563. @QtCore.pyqtSlot(name='on_action_search_triggered')
  564. def action_search_triggered(self):
  565. self.searchbox.setFocus()
  566. # noinspection PyPep8Naming
  567. def sort_indicator_changed(self, column, order):
  568. self.sort_by_column = [name for name in self.columns_indices if
  569. self.columns_indices[name] == column][0]
  570. self.sort_order = order
  571. if self.settings_loaded:
  572. self.manager_settings.setValue('view/sort_column',
  573. self.sort_by_column)
  574. self.manager_settings.setValue('view/sort_order', self.sort_order)
  575. self.manager_settings.sync()
  576. def table_selection_changed(self):
  577. vm = self.get_selected_vm()
  578. if vm is not None and vm in self.qubes_app.domains:
  579. # TODO: add boot from device to menu and add windows tools there
  580. # Update available actions:
  581. self.action_settings.setEnabled(vm.klass != 'AdminVM')
  582. self.action_removevm.setEnabled(
  583. vm.klass != 'AdminVM' and not vm.is_running())
  584. self.action_clonevm.setEnabled(vm.klass != 'AdminVM')
  585. self.action_resumevm.setEnabled(
  586. not vm.is_running() or vm.get_power_state() == "Paused")
  587. self.action_pausevm.setEnabled(
  588. vm.is_running() and vm.get_power_state() != "Paused"
  589. and vm.klass != 'AdminVM')
  590. self.action_shutdownvm.setEnabled(
  591. vm.is_running() and vm.get_power_state() != "Paused"
  592. and vm.klass != 'AdminVM')
  593. self.action_restartvm.setEnabled(
  594. vm.is_running() and vm.get_power_state() != "Paused"
  595. and vm.klass != 'AdminVM'
  596. and (vm.klass != 'DispVM' or not vm.auto_cleanup))
  597. self.action_killvm.setEnabled(
  598. (vm.get_power_state() == "Paused" or vm.is_running())
  599. and vm.klass != 'AdminVM')
  600. self.action_appmenus.setEnabled(
  601. vm.klass != 'AdminVM' and vm.klass != 'DispVM'
  602. and not vm.features.get('internal', False))
  603. self.action_editfwrules.setEnabled(vm.klass != 'AdminVM')
  604. self.action_updatevm.setEnabled(getattr(vm, 'updateable', False)
  605. or vm.qid == 0)
  606. self.action_run_command_in_vm.setEnabled(
  607. not vm.get_power_state() == "Paused" and vm.qid != 0)
  608. self.action_set_keyboard_layout.setEnabled(
  609. vm.qid != 0 and
  610. vm.get_power_state() != "Paused" and vm.is_running())
  611. else:
  612. self.action_settings.setEnabled(False)
  613. self.action_removevm.setEnabled(False)
  614. self.action_clonevm.setEnabled(False)
  615. self.action_resumevm.setEnabled(False)
  616. self.action_pausevm.setEnabled(False)
  617. self.action_shutdownvm.setEnabled(False)
  618. self.action_restartvm.setEnabled(False)
  619. self.action_killvm.setEnabled(False)
  620. self.action_appmenus.setEnabled(False)
  621. self.action_editfwrules.setEnabled(False)
  622. self.action_updatevm.setEnabled(False)
  623. self.action_run_command_in_vm.setEnabled(False)
  624. self.action_set_keyboard_layout.setEnabled(False)
  625. # noinspection PyArgumentList
  626. @QtCore.pyqtSlot(name='on_action_createvm_triggered')
  627. def action_createvm_triggered(self): # pylint: disable=no-self-use
  628. create_window = create_new_vm.NewVmDlg(self.qt_app, self.qubes_app)
  629. create_window.exec_()
  630. def get_selected_vm(self):
  631. # vm selection relies on the VmInfo widget's value used
  632. # for sorting by VM name
  633. row_index = self.table.currentRow()
  634. if row_index != -1:
  635. vm_item = self.table.item(row_index, self.columns_indices["Name"])
  636. # here is possible race with update_table timer so check
  637. # if really got the item
  638. if vm_item is None:
  639. return None
  640. qid = vm_item.qid
  641. assert self.vms_in_table[qid] is not None
  642. vm = self.vms_in_table[qid].vm
  643. return vm
  644. return None
  645. # noinspection PyArgumentList
  646. @QtCore.pyqtSlot(name='on_action_removevm_triggered')
  647. def action_removevm_triggered(self):
  648. # pylint: disable=no-else-return
  649. vm = self.get_selected_vm()
  650. dependencies = utils.vm_dependencies(self.qubes_app, vm)
  651. if dependencies:
  652. list_text = "<br>" + \
  653. manager_utils.format_dependencies_list(dependencies) + \
  654. "<br>"
  655. info_dialog = QtGui.QMessageBox(self)
  656. info_dialog.setWindowTitle(self.tr("Warning!"))
  657. info_dialog.setText(
  658. self.tr("This qube cannot be removed. It is used as:"
  659. " <br> {} <small>If you want to remove this qube, "
  660. "you should remove or change settings of each qube "
  661. "or setting that uses it.</small>").format(list_text))
  662. info_dialog.setModal(False)
  663. info_dialog.show()
  664. return
  665. (requested_name, ok) = QtGui.QInputDialog.getText(
  666. None, self.tr("Qube Removal Confirmation"),
  667. self.tr("Are you sure you want to remove the Qube <b>'{0}'</b>"
  668. "?<br> All data on this Qube's private storage will be "
  669. "lost!<br><br>Type the name of the Qube (<b>{1}</b>) below "
  670. "to confirm:").format(vm.name, vm.name))
  671. if not ok:
  672. # user clicked cancel
  673. return
  674. if requested_name != vm.name:
  675. # name did not match
  676. QtGui.QMessageBox.warning(
  677. None,
  678. self.tr("Qube removal confirmation failed"),
  679. self.tr(
  680. "Entered name did not match! Not removing "
  681. "{0}.").format(vm.name))
  682. return
  683. else:
  684. # remove the VM
  685. thread = common_threads.RemoveVMThread(vm)
  686. self.threads_list.append(thread)
  687. thread.finished.connect(self.clear_threads)
  688. thread.start()
  689. # noinspection PyArgumentList
  690. @QtCore.pyqtSlot(name='on_action_clonevm_triggered')
  691. def action_clonevm_triggered(self):
  692. vm = self.get_selected_vm()
  693. name_number = 1
  694. name_format = vm.name + '-clone-%d'
  695. while name_format % name_number in self.qubes_app.domains.keys():
  696. name_number += 1
  697. (clone_name, ok) = QtGui.QInputDialog.getText(
  698. self, self.tr('Qubes clone Qube'),
  699. self.tr('Enter name for Qube <b>{}</b> clone:').format(vm.name),
  700. text=(name_format % name_number))
  701. if not ok or clone_name == "":
  702. return
  703. self.progress = QtGui.QProgressDialog(
  704. self.tr(
  705. "Cloning Qube..."), "", 0, 0)
  706. self.progress.setCancelButton(None)
  707. self.progress.setModal(True)
  708. self.progress.show()
  709. thread = common_threads.CloneVMThread(vm, clone_name)
  710. thread.finished.connect(self.clear_threads)
  711. self.threads_list.append(thread)
  712. thread.start()
  713. # noinspection PyArgumentList
  714. @QtCore.pyqtSlot(name='on_action_resumevm_triggered')
  715. def action_resumevm_triggered(self):
  716. vm = self.get_selected_vm()
  717. if vm.get_power_state() in ["Paused", "Suspended"]:
  718. try:
  719. vm.unpause()
  720. except exc.QubesException as ex:
  721. QtGui.QMessageBox.warning(
  722. None, self.tr("Error unpausing Qube!"),
  723. self.tr("ERROR: {0}").format(ex))
  724. return
  725. self.start_vm(vm)
  726. def start_vm(self, vm):
  727. if vm.is_running():
  728. return
  729. thread = StartVMThread(vm)
  730. self.threads_list.append(thread)
  731. thread.finished.connect(self.clear_threads)
  732. thread.start()
  733. # noinspection PyArgumentList
  734. @QtCore.pyqtSlot(name='on_action_startvm_tools_install_triggered')
  735. # TODO: replace with boot from device
  736. def action_startvm_tools_install_triggered(self):
  737. # pylint: disable=invalid-name
  738. pass
  739. @QtCore.pyqtSlot(name='on_action_pausevm_triggered')
  740. def action_pausevm_triggered(self):
  741. vm = self.get_selected_vm()
  742. try:
  743. vm.pause()
  744. except exc.QubesException as ex:
  745. QtGui.QMessageBox.warning(
  746. None,
  747. self.tr("Error pausing Qube!"),
  748. self.tr("ERROR: {0}").format(ex))
  749. return
  750. # noinspection PyArgumentList
  751. @QtCore.pyqtSlot(name='on_action_shutdownvm_triggered')
  752. def action_shutdownvm_triggered(self):
  753. vm = self.get_selected_vm()
  754. reply = QtGui.QMessageBox.question(
  755. None, self.tr("Qube Shutdown Confirmation"),
  756. self.tr("Are you sure you want to power down the Qube"
  757. " <b>'{0}'</b>?<br><small>This will shutdown all the "
  758. "running applications within this Qube.</small>").format(
  759. vm.name), QtGui.QMessageBox.Yes | QtGui.QMessageBox.Cancel)
  760. if reply == QtGui.QMessageBox.Yes:
  761. self.shutdown_vm(vm)
  762. def shutdown_vm(self, vm, shutdown_time=vm_shutdown_timeout,
  763. check_time=vm_restart_check_timeout, and_restart=False):
  764. try:
  765. vm.shutdown()
  766. except exc.QubesException as ex:
  767. QtGui.QMessageBox.warning(
  768. None,
  769. self.tr("Error shutting down Qube!"),
  770. self.tr("ERROR: {0}").format(ex))
  771. return
  772. self.shutdown_monitor[vm.qid] = VmShutdownMonitor(vm, shutdown_time,
  773. check_time,
  774. and_restart, self)
  775. # noinspection PyCallByClass,PyTypeChecker
  776. QtCore.QTimer.singleShot(check_time, self.shutdown_monitor[
  777. vm.qid].check_if_vm_has_shutdown)
  778. # noinspection PyArgumentList
  779. @QtCore.pyqtSlot(name='on_action_restartvm_triggered')
  780. def action_restartvm_triggered(self):
  781. vm = self.get_selected_vm()
  782. reply = QtGui.QMessageBox.question(
  783. None, self.tr("Qube Restart Confirmation"),
  784. self.tr("Are you sure you want to restart the Qube <b>'{0}'</b>?"
  785. "<br><small>This will shutdown all the running "
  786. "applications within this Qube.</small>").format(vm.name),
  787. QtGui.QMessageBox.Yes | QtGui.QMessageBox.Cancel)
  788. if reply == QtGui.QMessageBox.Yes:
  789. # in case the user shut down the VM in the meantime
  790. if vm.is_running():
  791. self.shutdown_vm(vm, and_restart=True)
  792. else:
  793. self.start_vm(vm)
  794. # noinspection PyArgumentList
  795. @QtCore.pyqtSlot(name='on_action_killvm_triggered')
  796. def action_killvm_triggered(self):
  797. vm = self.get_selected_vm()
  798. if not (vm.is_running() or vm.is_paused()):
  799. info = self.tr("Qube <b>'{0}'</b> is not running. Are you "
  800. "absolutely sure you want to try to kill it?<br>"
  801. "<small>This will end <b>(not shutdown!)</b> all "
  802. "the running applications within this "
  803. "Qube.</small>").format(vm.name)
  804. else:
  805. info = self.tr("Are you sure you want to kill the Qube "
  806. "<b>'{0}'</b>?<br><small>This will end <b>(not "
  807. "shutdown!)</b> all the running applications within "
  808. "this Qube.</small>").format(vm.name)
  809. reply = QtGui.QMessageBox.question(
  810. None, self.tr("Qube Kill Confirmation"), info,
  811. QtGui.QMessageBox.Yes | QtGui.QMessageBox.Cancel,
  812. QtGui.QMessageBox.Cancel)
  813. if reply == QtGui.QMessageBox.Yes:
  814. try:
  815. vm.kill()
  816. except exc.QubesException as ex:
  817. QtGui.QMessageBox.critical(
  818. None, self.tr("Error while killing Qube!"),
  819. self.tr(
  820. "<b>An exception ocurred while killing {0}.</b><br>"
  821. "ERROR: {1}").format(vm.name, ex))
  822. return
  823. # noinspection PyArgumentList
  824. @QtCore.pyqtSlot(name='on_action_settings_triggered')
  825. def action_settings_triggered(self):
  826. vm = self.get_selected_vm()
  827. if vm:
  828. settings_window = settings.VMSettingsWindow(
  829. vm, self.qt_app, "basic")
  830. settings_window.exec_()
  831. vm_deleted = False
  832. try:
  833. # the VM might not exist after running Settings - it might
  834. # have been cloned or removed
  835. self.vms_in_table[vm.qid].update()
  836. except exc.QubesException:
  837. # TODO: this will be replaced by proper signal handling once
  838. # settings are migrated to AdminAPI
  839. vm_deleted = True
  840. if vm_deleted:
  841. for row in self.vms_in_table:
  842. try:
  843. self.vms_in_table[row].update()
  844. except exc.QubesException:
  845. pass
  846. # noinspection PyArgumentList
  847. @QtCore.pyqtSlot(name='on_action_appmenus_triggered')
  848. def action_appmenus_triggered(self):
  849. vm = self.get_selected_vm()
  850. if vm:
  851. settings_window = settings.VMSettingsWindow(
  852. vm, self.qt_app, "applications")
  853. settings_window.exec_()
  854. # noinspection PyArgumentList
  855. @QtCore.pyqtSlot(name='on_action_updatevm_triggered')
  856. def action_updatevm_triggered(self):
  857. vm = self.get_selected_vm()
  858. if not vm.is_running():
  859. reply = QtGui.QMessageBox.question(
  860. None, self.tr("Qube Update Confirmation"),
  861. self.tr(
  862. "<b>{0}</b><br>The Qube has to be running to be updated."
  863. "<br>Do you want to start it?<br>").format(vm.name),
  864. QtGui.QMessageBox.Yes | QtGui.QMessageBox.Cancel)
  865. if reply != QtGui.QMessageBox.Yes:
  866. return
  867. thread = UpdateVMThread(vm)
  868. self.threads_list.append(thread)
  869. thread.finished.connect(self.clear_threads)
  870. thread.start()
  871. # noinspection PyArgumentList
  872. @QtCore.pyqtSlot(name='on_action_run_command_in_vm_triggered')
  873. def action_run_command_in_vm_triggered(self):
  874. # pylint: disable=invalid-name
  875. vm = self.get_selected_vm()
  876. (command_to_run, ok) = QtGui.QInputDialog.getText(
  877. self, self.tr('Qubes command entry'),
  878. self.tr('Run command in <b>{}</b>:').format(vm.name))
  879. if not ok or command_to_run == "":
  880. return
  881. thread = RunCommandThread(vm, command_to_run)
  882. self.threads_list.append(thread)
  883. thread.finished.connect(self.clear_threads)
  884. thread.start()
  885. # noinspection PyArgumentList
  886. @QtCore.pyqtSlot(name='on_action_set_keyboard_layout_triggered')
  887. def action_set_keyboard_layout_triggered(self):
  888. # pylint: disable=invalid-name
  889. vm = self.get_selected_vm()
  890. vm.run('qubes-change-keyboard-layout')
  891. # noinspection PyArgumentList
  892. @QtCore.pyqtSlot(name='on_action_editfwrules_triggered')
  893. def action_editfwrules_triggered(self):
  894. vm = self.get_selected_vm()
  895. settings_window = settings.VMSettingsWindow(vm, self.qt_app, "firewall")
  896. settings_window.exec_()
  897. # noinspection PyArgumentList
  898. @QtCore.pyqtSlot(name='on_action_global_settings_triggered')
  899. def action_global_settings_triggered(self): # pylint: disable=invalid-name
  900. global_settings_window = global_settings.GlobalSettingsWindow(
  901. self.qt_app,
  902. self.qubes_app)
  903. global_settings_window.exec_()
  904. # noinspection PyArgumentList
  905. @QtCore.pyqtSlot(name='on_action_manage_templates_triggered')
  906. def action_manage_templates_triggered(self):
  907. # pylint: disable=invalid-name, no-self-use
  908. subprocess.check_call('qubes-template-manager')
  909. # noinspection PyArgumentList
  910. @QtCore.pyqtSlot(name='on_action_show_network_triggered')
  911. def action_show_network_triggered(self):
  912. pass
  913. # TODO: revive for 4.1
  914. # network_notes_dialog = NetworkNotesDialog()
  915. # network_notes_dialog.exec_()
  916. # noinspection PyArgumentList
  917. @QtCore.pyqtSlot(name='on_action_restore_triggered')
  918. def action_restore_triggered(self):
  919. restore_window = restore.RestoreVMsWindow(self.qt_app, self.qubes_app)
  920. restore_window.exec_()
  921. # noinspection PyArgumentList
  922. @QtCore.pyqtSlot(name='on_action_backup_triggered')
  923. def action_backup_triggered(self):
  924. backup_window = backup.BackupVMsWindow(self.qt_app, self.qubes_app,
  925. self.dispatcher, self)
  926. backup_window.show()
  927. # noinspection PyArgumentList
  928. @QtCore.pyqtSlot(name='on_action_exit_triggered')
  929. def action_exit_triggered(self):
  930. self.close()
  931. def showhide_menubar(self, checked):
  932. self.menubar.setVisible(checked)
  933. if not checked:
  934. self.context_menu.addAction(self.action_menubar)
  935. else:
  936. self.context_menu.removeAction(self.action_menubar)
  937. if self.settings_loaded:
  938. self.manager_settings.setValue('view/menubar_visible', checked)
  939. self.manager_settings.sync()
  940. def showhide_toolbar(self, checked):
  941. self.toolbar.setVisible(checked)
  942. if not checked:
  943. self.context_menu.addAction(self.action_toolbar)
  944. else:
  945. self.context_menu.removeAction(self.action_toolbar)
  946. if self.settings_loaded:
  947. self.manager_settings.setValue('view/toolbar_visible', checked)
  948. self.manager_settings.sync()
  949. def showhide_column(self, col_num, show):
  950. self.table.setColumnHidden(col_num, not show)
  951. val = 1 if show else -1
  952. self.visible_columns_count += val
  953. if self.visible_columns_count == 1:
  954. # disable hiding the last one
  955. for col in self.columns_actions:
  956. if self.columns_actions[col].isChecked():
  957. self.columns_actions[col].setEnabled(False)
  958. break
  959. elif self.visible_columns_count == 2 and val == 1:
  960. # enable hiding previously disabled column
  961. for col in self.columns_actions:
  962. if not self.columns_actions[col].isEnabled():
  963. self.columns_actions[col].setEnabled(True)
  964. break
  965. if self.settings_loaded:
  966. col_name = [name for name in self.columns_indices if
  967. self.columns_indices[name] == col_num][0]
  968. self.manager_settings.setValue('columns/%s' % col_name, show)
  969. self.manager_settings.sync()
  970. def on_action_vm_type_toggled(self, checked):
  971. self.showhide_column(self.columns_indices['Type'], checked)
  972. def on_action_label_toggled(self, checked):
  973. self.showhide_column(self.columns_indices['Label'], checked)
  974. def on_action_name_toggled(self, checked):
  975. self.showhide_column(self.columns_indices['Name'], checked)
  976. def on_action_state_toggled(self, checked):
  977. self.showhide_column(self.columns_indices['State'], checked)
  978. def on_action_internal_toggled(self, checked):
  979. self.showhide_column(self.columns_indices['Internal'], checked)
  980. def on_action_ip_toggled(self, checked):
  981. self.showhide_column(self.columns_indices['IP'], checked)
  982. def on_action_backups_toggled(self, checked):
  983. self.showhide_column(self.columns_indices['Backups'], checked)
  984. def on_action_last_backup_toggled(self, checked):
  985. self.showhide_column(self.columns_indices['Last backup'], checked)
  986. def on_action_template_toggled(self, checked):
  987. self.showhide_column(self.columns_indices['Template'], checked)
  988. def on_action_netvm_toggled(self, checked):
  989. self.showhide_column(self.columns_indices['NetVM'], checked)
  990. def on_action_size_on_disk_toggled(self, checked):
  991. self.showhide_column(self.columns_indices['Size'], checked)
  992. # noinspection PyArgumentList
  993. @QtCore.pyqtSlot(name='on_action_about_qubes_triggered')
  994. def action_about_qubes_triggered(self): # pylint: disable=no-self-use
  995. about = AboutDialog()
  996. about.exec_()
  997. def createPopupMenu(self): # pylint: disable=invalid-name
  998. menu = QtGui.QMenu()
  999. menu.addAction(self.action_toolbar)
  1000. menu.addAction(self.action_menubar)
  1001. return menu
  1002. def open_tools_context_menu(self, widget, point):
  1003. self.tools_context_menu.exec_(widget.mapToGlobal(point))
  1004. @QtCore.pyqtSlot('const QPoint&')
  1005. def open_context_menu(self, point):
  1006. try:
  1007. vm = self.get_selected_vm()
  1008. # logs menu
  1009. self.logs_menu.clear()
  1010. if vm.qid == 0:
  1011. logfiles = ["/var/log/xen/console/hypervisor.log"]
  1012. else:
  1013. logfiles = [
  1014. "/var/log/xen/console/guest-" + vm.name + ".log",
  1015. "/var/log/xen/console/guest-" + vm.name + "-dm.log",
  1016. "/var/log/qubes/guid." + vm.name + ".log",
  1017. "/var/log/qubes/qrexec." + vm.name + ".log",
  1018. ]
  1019. menu_empty = True
  1020. for logfile in logfiles:
  1021. if os.path.exists(logfile):
  1022. action = self.logs_menu.addAction(QtGui.QIcon(":/log.png"),
  1023. logfile)
  1024. action.setData(logfile)
  1025. menu_empty = False
  1026. self.logs_menu.setEnabled(not menu_empty)
  1027. if vm.qid == 0:
  1028. self.dom0_context_menu.exec_(self.table.mapToGlobal(
  1029. point + QtCore.QPoint(10, 0)))
  1030. else:
  1031. self.context_menu.exec_(self.table.mapToGlobal(
  1032. point + QtCore.QPoint(10, 0)))
  1033. except exc.QubesPropertyAccessError:
  1034. pass
  1035. @QtCore.pyqtSlot('QAction *')
  1036. def show_log(self, action):
  1037. log = str(action.data())
  1038. log_dlg = log_dialog.LogDialog(self.qt_app, log)
  1039. log_dlg.exec_()
  1040. # Bases on the original code by:
  1041. # Copyright (c) 2002-2007 Pascal Varet <p.varet@gmail.com>
  1042. def handle_exception(exc_type, exc_value, exc_traceback):
  1043. filename, line, dummy, dummy = traceback.extract_tb(exc_traceback).pop()
  1044. filename = os.path.basename(filename)
  1045. error = "%s: %s" % (exc_type.__name__, exc_value)
  1046. strace = ""
  1047. stacktrace = traceback.extract_tb(exc_traceback)
  1048. while stacktrace:
  1049. (filename, line, func, txt) = stacktrace.pop()
  1050. strace += "----\n"
  1051. strace += "line: %s\n" % txt
  1052. strace += "func: %s\n" % func
  1053. strace += "line no.: %d\n" % line
  1054. strace += "file: %s\n" % filename
  1055. msg_box = QtGui.QMessageBox()
  1056. msg_box.setDetailedText(strace)
  1057. msg_box.setIcon(QtGui.QMessageBox.Critical)
  1058. msg_box.setWindowTitle("Houston, we have a problem...")
  1059. msg_box.setText("Whoops. A critical error has occured. "
  1060. "This is most likely a bug in Qubes Manager.<br><br>"
  1061. "<b><i>%s</i></b>" % error +
  1062. "<br/>at line <b>%d</b><br/>of file %s.<br/><br/>"
  1063. % (line, filename))
  1064. msg_box.exec_()
  1065. def loop_shutdown():
  1066. pending = asyncio.Task.all_tasks()
  1067. for task in pending:
  1068. with suppress(asyncio.CancelledError):
  1069. task.cancel()
  1070. def main():
  1071. qt_app = QtGui.QApplication(sys.argv)
  1072. qt_app.setOrganizationName("The Qubes Project")
  1073. qt_app.setOrganizationDomain("http://qubes-os.org")
  1074. qt_app.setApplicationName("Qube Manager")
  1075. qt_app.setWindowIcon(QtGui.QIcon.fromTheme("qubes-manager"))
  1076. qt_app.lastWindowClosed.connect(loop_shutdown)
  1077. qubes_app = Qubes()
  1078. loop = quamash.QEventLoop(qt_app)
  1079. asyncio.set_event_loop(loop)
  1080. dispatcher = events.EventsDispatcher(qubes_app)
  1081. manager_window = VmManagerWindow(qt_app, qubes_app, dispatcher)
  1082. manager_window.show()
  1083. try:
  1084. loop.run_until_complete(
  1085. asyncio.ensure_future(dispatcher.listen_for_events()))
  1086. except asyncio.CancelledError:
  1087. pass
  1088. except Exception: # pylint: disable=broad-except
  1089. loop_shutdown()
  1090. exc_type, exc_value, exc_traceback = sys.exc_info()[:3]
  1091. handle_exception(exc_type, exc_value, exc_traceback)
  1092. if __name__ == "__main__":
  1093. main()