qube_manager.py 52 KB

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