qube_manager.py 50 KB

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