qube_manager.py 45 KB

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