qube_manager.py 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432
  1. #!/usr/bin/python3
  2. #
  3. # The Qubes OS Project, http://www.qubes-os.org
  4. #
  5. # Copyright (C) 2012 Agnieszka Kostrzewa <agnieszka.kostrzewa@gmail.com>
  6. # Copyright (C) 2012 Marek Marczykowski-Górecki
  7. # <marmarek@invisiblethingslab.com>
  8. # Copyright (C) 2017 Wojtek Porczyk <woju@invisiblethingslab.com>
  9. #
  10. # This program is free software; you can redistribute it and/or
  11. # modify it under the terms of the GNU General Public License
  12. # as published by the Free Software Foundation; either version 2
  13. # of the License, or (at your option) any later version.
  14. #
  15. # This program is distributed in the hope that it will be useful,
  16. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. # GNU General Public License for more details.
  19. #
  20. # You should have received a copy of the GNU Lesser General Public License along
  21. # with this program; if not, see <http://www.gnu.org/licenses/>.
  22. #
  23. #
  24. import os
  25. import os.path
  26. import subprocess
  27. from datetime import datetime, timedelta
  28. from functools import partial
  29. from qubesadmin import exc
  30. from qubesadmin import utils
  31. # pylint: disable=import-error
  32. from PyQt5.QtCore import (Qt, QAbstractTableModel, QObject, pyqtSlot, QEvent,
  33. QSettings, QRegExp, QSortFilterProxyModel, QSize, QPoint, QTimer)
  34. # pylint: disable=import-error
  35. from PyQt5.QtWidgets import (QLineEdit, QStyledItemDelegate, QToolTip,
  36. QMenu, QInputDialog, QMainWindow, QProgressDialog, QStyleOptionViewItem,
  37. QAbstractItemView, QMessageBox)
  38. # pylint: disable=import-error
  39. from PyQt5.QtGui import (QIcon, QPixmap, QRegExpValidator, QFont, QColor)
  40. from qubesmanager.about import AboutDialog
  41. from . import ui_qubemanager # pylint: disable=no-name-in-module
  42. from . import settings
  43. from . import global_settings
  44. from . import restore
  45. from . import backup
  46. from . import create_new_vm
  47. from . import log_dialog
  48. from . import utils as manager_utils
  49. from . import common_threads
  50. class SearchBox(QLineEdit):
  51. def __init__(self, parent=None):
  52. super(SearchBox, self).__init__(parent)
  53. self.focusing = False
  54. def focusInEvent(self, e): # pylint: disable=invalid-name
  55. super(SearchBox, self).focusInEvent(e)
  56. self.selectAll()
  57. self.focusing = True
  58. def mousePressEvent(self, e): # pylint: disable=invalid-name
  59. super(SearchBox, self).mousePressEvent(e)
  60. if self.focusing:
  61. self.selectAll()
  62. self.focusing = False
  63. icon_size = QSize(24, 24)
  64. # pylint: disable=invalid-name
  65. class StateIconDelegate(QStyledItemDelegate):
  66. lastIndex = None
  67. def __init__(self):
  68. super(StateIconDelegate, self).__init__()
  69. self.stateIcons = {
  70. "Running" : QIcon(":/on.png"),
  71. "Paused" : QIcon(":/paused.png"),
  72. "Suspended" : QIcon(":/paused.png"),
  73. "Transient" : QIcon(":/transient.png"),
  74. "Halting" : QIcon(":/transient.png"),
  75. "Dying" : QIcon(":/transient.png"),
  76. "Halted" : QIcon(":/off.png")
  77. }
  78. self.outdatedIcons = {
  79. "update" : QIcon(":/update-recommended.png"),
  80. "outdated" : QIcon(":/outdated.png"),
  81. "to-be-outdated" : QIcon(":/to-be-outdated.png"),
  82. }
  83. self.outdatedTooltips = {
  84. "update" : self.tr("Updates pending!"),
  85. "outdated" : self.tr(
  86. "The qube must be restarted for its filesystem to reflect"
  87. " the template's recent committed changes."),
  88. "to-be-outdated" : self.tr(
  89. "The Template must be stopped before changes from its "
  90. "current session can be picked up by this qube."),
  91. }
  92. def sizeHint(self, option, index):
  93. hint = super(StateIconDelegate, self).sizeHint(option, index)
  94. option = QStyleOptionViewItem(option)
  95. option.features |= option.HasDecoration
  96. widget = option.widget
  97. style = widget.style()
  98. iconRect = style.subElementRect(style.SE_ItemViewItemDecoration,
  99. option, widget)
  100. width = iconRect.width() * 3 # Nº of possible icons
  101. hint.setWidth(width)
  102. return hint
  103. def paint(self, qp, option, index):
  104. # create a new QStyleOption (*never* use the one given in arguments)
  105. option = QStyleOptionViewItem(option)
  106. widget = option.widget
  107. style = widget.style()
  108. # paint the base item (borders, gradients, selection colors, etc)
  109. style.drawControl(style.CE_ItemViewItem, option, qp, widget)
  110. # "lie" about the decoration, to get a valid icon rectangle (even if we
  111. # don't have any "real" icon set for the item)
  112. option.features |= option.HasDecoration
  113. iconRect = style.subElementRect(style.SE_ItemViewItemDecoration,
  114. option, widget)
  115. iconSize = iconRect.size()
  116. margin = iconRect.left() - option.rect.left()
  117. qp.save()
  118. # ensure that we do not draw outside the item rectangle (and add some
  119. # fancy margin on the right
  120. qp.setClipRect(option.rect.adjusted(0, 0, -margin, 0))
  121. # draw the main state icon, assuming all items have one
  122. qp.drawPixmap(iconRect,
  123. self.stateIcons[index.data()['power']].pixmap(iconSize))
  124. left = delta = margin + iconRect.width()
  125. if index.data()['outdated']:
  126. qp.drawPixmap(iconRect.translated(left, 0),
  127. self.outdatedIcons[index.data()['outdated']]\
  128. .pixmap(iconSize))
  129. left += delta
  130. qp.restore()
  131. def helpEvent(self, event, view, option, index):
  132. if event.type() != QEvent.ToolTip:
  133. return super(StateIconDelegate, self).helpEvent(event, view,
  134. option, index)
  135. option = QStyleOptionViewItem(option)
  136. widget = option.widget
  137. style = widget.style()
  138. option.features |= option.HasDecoration
  139. iconRect = style.subElementRect(style.SE_ItemViewItemDecoration,
  140. option, widget)
  141. iconRect.setTop(option.rect.y())
  142. iconRect.setHeight(option.rect.height())
  143. # similar to what we do in the paint() method
  144. if event.pos() in iconRect:
  145. # (*) clear any existing tooltip; a single space is better , as
  146. # sometimes it's not enough to use an empty string
  147. if index != self.lastIndex:
  148. QToolTip.showText(QPoint(), ' ')
  149. QToolTip.showText(event.globalPos(),
  150. index.data()['power'], view)
  151. else:
  152. margin = iconRect.left() - option.rect.left()
  153. left = delta = margin + iconRect.width()
  154. if index.data()['outdated']:
  155. if event.pos() in iconRect.translated(left, 0):
  156. # see above (*)
  157. if index != self.lastIndex:
  158. QToolTip.showText(QPoint(), ' ')
  159. QToolTip.showText(event.globalPos(),
  160. self.outdatedTooltips[index.data()['outdated']],
  161. view)
  162. # shift the left *only* if the role is True, otherwise we
  163. # can assume that that icon doesn't exist at all
  164. left += delta
  165. self.lastIndex = index
  166. return True
  167. # pylint: disable=too-many-instance-attributes
  168. # pylint: disable=too-few-public-methods
  169. class VmInfo():
  170. def __init__(self, vm):
  171. self.vm = vm
  172. self.qid = vm.qid
  173. self.name = self.vm.name
  174. self.label = self.vm.label
  175. self.klass = self.vm.klass
  176. self.state = {'power': "", 'outdated': ""}
  177. self.updateable = getattr(vm, 'updateable', False)
  178. self.update(True)
  179. def update(self, update_size_on_disk=False, event=None):
  180. """
  181. Update VmInfo
  182. :param update_size_on_disk: should disk utilization be updated?
  183. :param event: name of the event that caused the update, to avoid
  184. updating unnecessary properties; if event is none, update everything
  185. :return: None
  186. """
  187. try:
  188. self.state['power'] = self.vm.get_power_state()
  189. if self.vm.is_running():
  190. if hasattr(self.vm, 'template') and \
  191. self.vm.template.is_running():
  192. self.state['outdated'] = "to-be-outdated"
  193. else:
  194. for vol in self.vm.volumes.values():
  195. if vol.is_outdated():
  196. self.state['outdated'] = "outdated"
  197. break
  198. else:
  199. self.state['outdated'] = ""
  200. if self.vm.klass in {'TemplateVM', 'StandaloneVM'} and \
  201. self.vm.features.get('updates-available', False):
  202. self.state['outdated'] = 'update'
  203. if not event or event.endswith(':label'):
  204. self.label = self.vm.label
  205. if not event or event.endswith(':template'):
  206. try:
  207. self.template = self.vm.template.name
  208. except AttributeError:
  209. self.template = None
  210. if not event or event.endswith(':netvm'):
  211. self.netvm = getattr(self.vm, 'netvm', None)
  212. if self.netvm:
  213. self.netvm = self.netvm.name
  214. else:
  215. self.netvm = "n/a"
  216. if self.qid != 0 and self.vm.property_is_default("netvm"):
  217. self.netvm = "default (" + self.netvm + ")"
  218. if not event or event.endswith(':internal'):
  219. # this is a feature, not a property; TODO: fix event handling
  220. self.internal = self.vm.features.get('internal', False)
  221. if not event or event.endswith(':ip'):
  222. self.ip = getattr(self.vm, 'ip', "n/a")
  223. if not event or event.endswith(':include_in_backups'):
  224. self.inc_backup = getattr(self.vm, 'include_in_backups', None)
  225. if not event or event.endswith(':backup_timestamp'):
  226. self.last_backup = getattr(self.vm, 'backup_timestamp', None)
  227. if self.last_backup:
  228. self.last_backup = str(datetime.fromtimestamp(
  229. self.last_backup))
  230. if not event or event.endswith(':default_dispvm'):
  231. self.dvm = getattr(self.vm, 'default_dispvm', None)
  232. if self.vm.property_is_default("default_dispvm"):
  233. self.dvm = "default (" + str(self.dvm) + ")"
  234. elif self.dvm is not None:
  235. self.dvm = self.dvm.name
  236. if not event or event.endswith(':template_for_dispvms'):
  237. self.dvm_template = getattr(self.vm, 'template_for_dispvms',
  238. None)
  239. if self.qid != 0 and update_size_on_disk:
  240. self.disk_float = float(self.vm.get_disk_utilization())
  241. self.disk = str(round(self.disk_float/(1024*1024), 2)) + " MiB"
  242. if self.qid != 0:
  243. self.virt_mode = self.vm.virt_mode
  244. else:
  245. self.virt_mode = None
  246. self.disk = "n/a"
  247. except exc.QubesPropertyAccessError:
  248. pass
  249. except exc.QubesDaemonNoResponseError:
  250. # TODO: this will be fixed by a rewrite moving the event system to
  251. # AdminAPI
  252. pass
  253. class QubesCache(QAbstractTableModel):
  254. def __init__(self, qubes_app):
  255. QAbstractTableModel.__init__(self)
  256. self._qubes_app = qubes_app
  257. self._info_list = []
  258. self._info_by_id = {}
  259. def add_vm(self, vm):
  260. vm_info = VmInfo(vm)
  261. self._info_list.append(vm_info)
  262. self._info_by_id[vm.qid] = vm_info
  263. def remove_vm(self, name):
  264. vm_info = self.get_vm(name=name)
  265. self._info_list.remove(vm_info)
  266. del self._info_by_id[vm_info.qid]
  267. def get_vm(self, row=None, qid=None, name=None):
  268. if row is not None:
  269. return self._info_list[row]
  270. if qid is not None:
  271. return self._info_by_id[qid]
  272. return next(x for x in self._info_list if x.name == name)
  273. def __len__(self):
  274. return len(self._info_list)
  275. def __iter__(self):
  276. return iter(self._info_list)
  277. class QubesTableModel(QAbstractTableModel):
  278. def __init__(self, qubes_cache):
  279. QAbstractTableModel.__init__(self)
  280. self.qubes_cache = qubes_cache
  281. self.template = {}
  282. self.klass_pixmap = {}
  283. self.label_pixmap = {}
  284. self.columns_indices = [
  285. "Type",
  286. "Label",
  287. "Name",
  288. "State",
  289. "Template",
  290. "NetVM",
  291. "Disk Usage",
  292. "Internal",
  293. "IP",
  294. "Include in backups",
  295. "Last backup",
  296. "Default DispVM",
  297. "Is DVM Template",
  298. "Virt Mode"
  299. ]
  300. # pylint: disable=invalid-name
  301. def rowCount(self, _):
  302. return len(self.qubes_cache)
  303. # pylint: disable=invalid-name
  304. def columnCount(self, _):
  305. return len(self.columns_indices)
  306. # pylint: disable=too-many-return-statements
  307. def data(self, index, role):
  308. if not index.isValid():
  309. return None
  310. col = index.column()
  311. row = index.row()
  312. col_name = self.columns_indices[col]
  313. vm = self.qubes_cache.get_vm(row)
  314. if role == Qt.DisplayRole:
  315. if col in [0, 1]:
  316. return None
  317. if col_name == "Name":
  318. return vm.name
  319. if col_name == "State":
  320. return vm.state
  321. if col_name == "Template":
  322. if vm.template is None:
  323. return vm.klass
  324. return vm.template
  325. if col_name == "NetVM":
  326. return vm.netvm
  327. if col_name == "Disk Usage":
  328. return vm.disk
  329. if col_name == "Internal":
  330. return "Yes" if vm.internal else ""
  331. if col_name == "IP":
  332. return vm.ip
  333. if col_name == "Include in backups":
  334. return "Yes" if vm.inc_backup else ""
  335. if col_name == "Last backup":
  336. return vm.last_backup
  337. if col_name == "Default DispVM":
  338. return vm.dvm
  339. if col_name == "Is DVM Template":
  340. return "Yes" if vm.dvm_template else ""
  341. if col_name == "Virt Mode":
  342. return vm.virt_mode
  343. if role == Qt.DecorationRole:
  344. if col_name == "Type":
  345. try:
  346. return self.klass_pixmap[vm.klass]
  347. except KeyError:
  348. pixmap = QPixmap()
  349. icon_name = ":/"+vm.klass.lower()+".png"
  350. icon_name = icon_name.replace("adminvm", "dom0")
  351. icon_name = icon_name.replace("dispvm", "appvm")
  352. pixmap.load(icon_name)
  353. self.klass_pixmap[vm.klass] = pixmap.scaled(icon_size)
  354. return self.klass_pixmap[vm.klass]
  355. if col_name == "Label":
  356. try:
  357. return self.label_pixmap[vm.label]
  358. except KeyError:
  359. icon = QIcon.fromTheme(vm.label.icon)
  360. self.label_pixmap[vm.label] = icon.pixmap(icon_size)
  361. return self.label_pixmap[vm.label]
  362. if role == Qt.FontRole:
  363. if col_name == "Template":
  364. if vm.template is None:
  365. font = QFont()
  366. font.setItalic(True)
  367. return font
  368. if role == Qt.ForegroundRole:
  369. if col_name == "Template":
  370. if vm.template is None:
  371. return QColor("gray")
  372. # Used for get VM Object
  373. if role == Qt.UserRole:
  374. return vm
  375. # Used for sorting
  376. if role == Qt.UserRole + 1:
  377. if vm.qid == 0:
  378. return ""
  379. if col_name == "Type":
  380. return vm.klass
  381. if col_name == "Label":
  382. return vm.label.name
  383. if col_name == "State":
  384. return str(vm.state)
  385. if col_name == "Disk Usage":
  386. return vm.disk_float
  387. return self.data(index, Qt.DisplayRole)
  388. # pylint: disable=invalid-name
  389. def headerData(self, col, orientation, role):
  390. if col < 2:
  391. return None
  392. if orientation == Qt.Horizontal and role == Qt.DisplayRole:
  393. return self.columns_indices[col]
  394. return None
  395. vm_shutdown_timeout = 20000 # in msec
  396. vm_restart_check_timeout = 1000 # in msec
  397. class VmShutdownMonitor(QObject):
  398. def __init__(self, vm, shutdown_time=vm_shutdown_timeout,
  399. check_time=vm_restart_check_timeout,
  400. and_restart=False, caller=None):
  401. QObject.__init__(self)
  402. self.vm = vm
  403. self.shutdown_time = shutdown_time
  404. self.check_time = check_time
  405. self.and_restart = and_restart
  406. self.shutdown_started = datetime.now()
  407. self.caller = caller
  408. def restart_vm_if_needed(self):
  409. if self.and_restart and self.caller:
  410. self.caller.start_vm(self.vm)
  411. def check_again_later(self):
  412. # noinspection PyTypeChecker,PyCallByClass
  413. QTimer.singleShot(self.check_time, self.check_if_vm_has_shutdown)
  414. def timeout_reached(self):
  415. actual = datetime.now() - self.shutdown_started
  416. allowed = timedelta(milliseconds=self.shutdown_time)
  417. return actual > allowed
  418. def check_if_vm_has_shutdown(self):
  419. vm = self.vm
  420. vm_is_running = vm.is_running()
  421. try:
  422. vm_start_time = datetime.fromtimestamp(float(vm.start_time))
  423. except (AttributeError, TypeError, ValueError):
  424. vm_start_time = None
  425. if vm_is_running and vm_start_time \
  426. and vm_start_time < self.shutdown_started:
  427. if self.timeout_reached():
  428. msgbox = QMessageBox(self.caller)
  429. msgbox.setIcon(QMessageBox.Question)
  430. msgbox.setWindowTitle(self.tr("Qube Shutdown"))
  431. msgbox.setText(self.tr(
  432. "The Qube <b>'{0}'</b> hasn't shutdown within the last "
  433. "{1} seconds, do you want to kill it?<br>").format(
  434. vm.name, self.shutdown_time / 1000))
  435. kill_button = msgbox.addButton(
  436. self.tr("Kill it!"), QMessageBox.YesRole)
  437. wait_button = msgbox.addButton(
  438. self.tr("Wait another {0} seconds...").format(
  439. self.shutdown_time / 1000),
  440. QMessageBox.NoRole)
  441. msgbox.setDefaultButton(wait_button)
  442. msgbox.exec_()
  443. msgbox.deleteLater()
  444. if msgbox.clickedButton() is kill_button:
  445. try:
  446. vm.kill()
  447. except exc.QubesVMNotStartedError:
  448. # the VM shut down while the user was thinking about
  449. # shutting it down
  450. pass
  451. self.restart_vm_if_needed()
  452. else:
  453. self.shutdown_started = datetime.now()
  454. self.check_again_later()
  455. else:
  456. self.check_again_later()
  457. else:
  458. if vm_is_running:
  459. # Due to unknown reasons, Xen sometimes reports that a domain
  460. # is running even though its start-up timestamp is not valid.
  461. # Make sure that "restart_vm_if_needed" is not called until
  462. # the domain has been completely shut down according to Xen.
  463. self.check_again_later()
  464. return
  465. self.restart_vm_if_needed()
  466. # pylint: disable=too-few-public-methods
  467. class StartVMThread(common_threads.QubesThread):
  468. def run(self):
  469. try:
  470. self.vm.start()
  471. except exc.QubesException as ex:
  472. self.msg = ("Error starting Qube!", str(ex))
  473. # pylint: disable=too-few-public-methods
  474. class UpdateVMThread(common_threads.QubesThread):
  475. def run(self):
  476. try:
  477. if self.vm.qid == 0:
  478. subprocess.check_call(
  479. ["/usr/bin/qubes-dom0-update", "--clean", "--gui"])
  480. else:
  481. if not self.vm.is_running():
  482. self.vm.start()
  483. # apply DSA-4371
  484. with open('/usr/libexec/qubes-manager/dsa-4371-update', 'rb') \
  485. as dsa4371update:
  486. stdout, stderr = self.vm.run_service_for_stdio(
  487. "qubes.VMShell",
  488. user="root",
  489. input=dsa4371update.read())
  490. if stdout == b'changed=yes\n':
  491. subprocess.call(
  492. ['notify-send', '-i', 'dialog-information',
  493. self.tr('Debian DSA-4371 fix installed in {}').format(
  494. self.vm.name)])
  495. elif stdout == b'changed=no\n':
  496. pass
  497. else:
  498. raise exc.QubesException(
  499. self.tr("Failed to apply DSA-4371 fix: {}").format(
  500. stderr.decode('ascii')))
  501. self.vm.run_service("qubes.InstallUpdatesGUI",
  502. user="root", wait=False)
  503. except (ChildProcessError, exc.QubesException) as ex:
  504. self.msg = (self.tr("Error on qube update!"), str(ex))
  505. # pylint: disable=too-few-public-methods
  506. class RunCommandThread(common_threads.QubesThread):
  507. def __init__(self, vm, command_to_run):
  508. super(RunCommandThread, self).__init__(vm)
  509. self.command_to_run = command_to_run
  510. def run(self):
  511. try:
  512. self.vm.run(self.command_to_run)
  513. except (ChildProcessError, exc.QubesException) as ex:
  514. self.msg = (self.tr("Error while running command!"), str(ex))
  515. class QubesProxyModel(QSortFilterProxyModel):
  516. def lessThan(self, left, right):
  517. if left.data(self.sortRole()) != right.data(self.sortRole()):
  518. return super().lessThan(left, right)
  519. left_vm = left.data(Qt.UserRole)
  520. right_vm = right.data(Qt.UserRole)
  521. return left_vm.name.lower() < right_vm.name.lower()
  522. class VmManagerWindow(ui_qubemanager.Ui_VmManagerWindow, QMainWindow):
  523. # suppress saving settings while initializing widgets
  524. settings_loaded = False
  525. def __init__(self, qt_app, qubes_app, dispatcher, _parent=None):
  526. super(VmManagerWindow, self).__init__()
  527. self.setupUi(self)
  528. self.manager_settings = QSettings(self)
  529. self.qubes_app = qubes_app
  530. self.qt_app = qt_app
  531. self.searchbox = SearchBox()
  532. self.searchbox.setValidator(QRegExpValidator(
  533. QRegExp("[a-zA-Z0-9_-]*", Qt.CaseInsensitive), None))
  534. self.searchbox.textChanged.connect(self.do_search)
  535. self.searchContainer.addWidget(self.searchbox)
  536. self.settings_windows = {}
  537. self.frame_width = 0
  538. self.frame_height = 0
  539. self.context_menu = QMenu(self)
  540. self.context_menu.addAction(self.action_settings)
  541. self.context_menu.addAction(self.action_editfwrules)
  542. self.context_menu.addAction(self.action_appmenus)
  543. self.context_menu.addAction(self.action_set_keyboard_layout)
  544. self.context_menu.addSeparator()
  545. self.context_menu.addAction(self.action_updatevm)
  546. self.context_menu.addAction(self.action_run_command_in_vm)
  547. self.context_menu.addAction(self.action_open_console)
  548. self.context_menu.addAction(self.action_resumevm)
  549. self.context_menu.addAction(self.action_startvm_tools_install)
  550. self.context_menu.addAction(self.action_pausevm)
  551. self.context_menu.addAction(self.action_shutdownvm)
  552. self.context_menu.addAction(self.action_restartvm)
  553. self.context_menu.addAction(self.action_killvm)
  554. self.context_menu.addSeparator()
  555. self.context_menu.addAction(self.action_clonevm)
  556. self.context_menu.addAction(self.action_removevm)
  557. self.context_menu.addSeparator()
  558. self.context_menu.addMenu(self.logs_menu)
  559. self.context_menu.addSeparator()
  560. self.tools_context_menu = QMenu(self)
  561. self.tools_context_menu.addAction(self.action_toolbar)
  562. self.tools_context_menu.addAction(self.action_menubar)
  563. self.menubar.customContextMenuRequested.connect(
  564. lambda pos: self.open_tools_context_menu(self.menubar, pos))
  565. self.toolbar.customContextMenuRequested.connect(
  566. lambda pos: self.open_tools_context_menu(self.toolbar, pos))
  567. self.action_menubar.toggled.connect(self.showhide_menubar)
  568. self.action_toolbar.toggled.connect(self.showhide_toolbar)
  569. self.logs_menu.triggered.connect(self.show_log)
  570. self.table.resizeColumnsToContents()
  571. self.update_size_on_disk = False
  572. self.shutdown_monitor = {}
  573. self.qubes_cache = QubesCache(qubes_app)
  574. self.fill_cache()
  575. self.qubes_model = QubesTableModel(self.qubes_cache)
  576. self.proxy = QubesProxyModel()
  577. self.proxy.setSourceModel(self.qubes_model)
  578. self.proxy.setSortRole(Qt.UserRole + 1)
  579. self.proxy.setSortCaseSensitivity(Qt.CaseInsensitive)
  580. self.proxy.setFilterKeyColumn(2)
  581. self.proxy.setFilterCaseSensitivity(Qt.CaseInsensitive)
  582. self.proxy.layoutChanged.connect(self.save_sorting)
  583. self.table.setModel(self.proxy)
  584. self.table.setItemDelegateForColumn(3, StateIconDelegate())
  585. self.table.resizeColumnsToContents()
  586. self.table.setSelectionMode(QAbstractItemView.ExtendedSelection)
  587. selection_model = self.table.selectionModel()
  588. selection_model.selectionChanged.connect(self.table_selection_changed)
  589. self.table.setContextMenuPolicy(Qt.CustomContextMenu)
  590. self.table.customContextMenuRequested.connect(self.open_context_menu)
  591. # Create view menu
  592. for col_no in range(len(self.qubes_model.columns_indices)):
  593. column = self.qubes_model.columns_indices[col_no]
  594. action = self.menu_view.addAction(column)
  595. action.setData(column)
  596. action.setCheckable(True)
  597. action.toggled.connect(partial(self.showhide_column, col_no))
  598. self.menu_view.addSeparator()
  599. self.menu_view.addAction(self.action_toolbar)
  600. self.menu_view.addAction(self.action_menubar)
  601. try:
  602. self.load_manager_settings()
  603. except Exception as ex: # pylint: disable=broad-except
  604. QMessageBox.warning(
  605. self,
  606. self.tr("Manager settings unreadable"),
  607. self.tr("Qube Manager settings cannot be parsed. Previously "
  608. "saved display settings may not be restored "
  609. "correctly.\nError: {}".format(str(ex))))
  610. self.settings_loaded = True
  611. # Connect events
  612. self.dispatcher = dispatcher
  613. dispatcher.add_handler('domain-pre-start',
  614. self.on_domain_status_changed)
  615. dispatcher.add_handler('domain-start', self.on_domain_status_changed)
  616. dispatcher.add_handler('domain-start-failed',
  617. self.on_domain_status_changed)
  618. dispatcher.add_handler('domain-stopped', self.on_domain_status_changed)
  619. dispatcher.add_handler('domain-pre-shutdown',
  620. self.on_domain_status_changed)
  621. dispatcher.add_handler('domain-shutdown', self.on_domain_status_changed)
  622. dispatcher.add_handler('domain-paused', self.on_domain_status_changed)
  623. dispatcher.add_handler('domain-unpaused', self.on_domain_status_changed)
  624. dispatcher.add_handler('domain-add', self.on_domain_added)
  625. dispatcher.add_handler('domain-delete', self.on_domain_removed)
  626. dispatcher.add_handler('property-set:*',
  627. self.on_domain_changed)
  628. dispatcher.add_handler('property-del:*',
  629. self.on_domain_changed)
  630. dispatcher.add_handler('property-load',
  631. self.on_domain_changed)
  632. dispatcher.add_handler('domain-feature-set:updates-available',
  633. self.on_domain_updates_available)
  634. dispatcher.add_handler('domain-feature-delete:updates-available',
  635. self.on_domain_updates_available)
  636. # It needs to store threads until they finish
  637. self.threads_list = []
  638. self.progress = None
  639. self.check_updates()
  640. def save_sorting(self):
  641. self.manager_settings.setValue('view/sort_column',
  642. self.proxy.sortColumn())
  643. self.manager_settings.setValue('view/sort_order',
  644. self.proxy.sortOrder())
  645. def fill_cache(self):
  646. progress = QProgressDialog(
  647. self.tr(
  648. "Loading Qube Manager..."), "", 0,
  649. len(self.qubes_app.domains.keys()))
  650. progress.setWindowTitle(self.tr("Qube Manager"))
  651. progress.setMinimumDuration(1000)
  652. progress.setWindowModality(Qt.WindowModal)
  653. progress.setCancelButton(None)
  654. row_no = 0
  655. for vm in self.qubes_app.domains:
  656. progress.setValue(row_no)
  657. self.qubes_cache.add_vm(vm)
  658. row_no += 1
  659. progress.setValue(row_no)
  660. def setup_application(self):
  661. self.qt_app.setApplicationName(self.tr("Qube Manager"))
  662. self.qt_app.setWindowIcon(QIcon.fromTheme("qubes-manager"))
  663. def keyPressEvent(self, event): # pylint: disable=invalid-name
  664. if event.key() == Qt.Key_Escape:
  665. self.searchbox.clear()
  666. super(VmManagerWindow, self).keyPressEvent(event)
  667. def clear_threads(self):
  668. for thread in self.threads_list:
  669. if thread.isFinished():
  670. if self.progress:
  671. self.progress.hide()
  672. self.progress = None
  673. if thread.msg:
  674. (title, msg) = thread.msg
  675. if thread.msg_is_success:
  676. QMessageBox.information(
  677. self,
  678. title,
  679. msg)
  680. else:
  681. QMessageBox.warning(
  682. self,
  683. title,
  684. msg)
  685. self.threads_list.remove(thread)
  686. return
  687. raise RuntimeError(self.tr('No finished thread found'))
  688. # pylint: disable=invalid-name
  689. def resizeEvent(self, event):
  690. self.manager_settings.setValue("window_size", event.size())
  691. def check_updates(self, info=None):
  692. if info is None:
  693. for info_iter in self.qubes_cache:
  694. self.check_updates(info_iter)
  695. return
  696. if info.vm.klass in {'TemplateVM', 'StandaloneVM'} and \
  697. info.vm.features.get('updates-available', False):
  698. info.state['outdated'] = 'update'
  699. def on_domain_added(self, _submitter, _event, vm, **_kwargs):
  700. try:
  701. domain = self.qubes_app.domains[vm]
  702. self.qubes_cache.add_vm(domain)
  703. self.proxy.invalidate()
  704. except (exc.QubesException, KeyError):
  705. pass
  706. def on_domain_removed(self, _submitter, _event, **kwargs):
  707. self.qubes_cache.remove_vm(name=kwargs['vm'])
  708. self.proxy.invalidate()
  709. def on_domain_status_changed(self, vm, event, **_kwargs):
  710. try:
  711. self.qubes_cache.get_vm(qid=vm.qid).update(event=event)
  712. if vm.klass in {'TemplateVM'}:
  713. for appvm in vm.appvms:
  714. self.qubes_cache.get_vm(qid=appvm.qid).\
  715. update(event="outdated")
  716. self.proxy.invalidate()
  717. self.table_selection_changed()
  718. except exc.QubesPropertyAccessError:
  719. return # the VM was deleted before its status could be updated
  720. except KeyError: # adding the VM failed for some reason
  721. self.on_domain_added(None, None, vm)
  722. def on_domain_updates_available(self, vm, _event, **_kwargs):
  723. self.check_updates(self.qubes_cache.get_vm(qid=vm.qid))
  724. def on_domain_changed(self, vm, event, **_kwargs):
  725. if not vm: # change of global properties occured
  726. if event.endswith(':default_netvm'):
  727. for vm_info in self.qubes_cache:
  728. vm_info.update(event='property-set:netvm')
  729. if event.endswith(':default_dispvm'):
  730. for vm_info in self.qubes_cache:
  731. vm_info.update(event='property-set:default_dispvm')
  732. return
  733. try:
  734. self.qubes_cache.get_vm(qid=vm.qid).update(event=event)
  735. self.proxy.invalidate()
  736. except exc.QubesPropertyAccessError:
  737. return # the VM was deleted before its status could be updated
  738. def load_manager_settings(self):
  739. # Load view menu settings
  740. for action in self.menu_view.actions():
  741. column = action.data()
  742. if column is not None:
  743. col_no = self.qubes_model.columns_indices.index(column)
  744. if column == 'Name':
  745. # 'Name' column should be always visible
  746. action.setChecked(True)
  747. else:
  748. visible = self.manager_settings.value('columns/%s' % column,
  749. defaultValue="true")
  750. action.setChecked(visible == "true")
  751. self.showhide_column(col_no, visible == "true")
  752. # Restore sorting
  753. sort_column = int(self.manager_settings.value("view/sort_column",
  754. defaultValue=2))
  755. order = Qt.SortOrder(self.manager_settings.value("view/sort_order",
  756. defaultValue=Qt.AscendingOrder))
  757. if not sort_column: # Default sort by name
  758. self.table.sortByColumn(2, Qt.AscendingOrder)
  759. else:
  760. self.table.sortByColumn(sort_column, order)
  761. if not self.manager_settings.value("view/menubar_visible",
  762. defaultValue=True):
  763. self.action_menubar.setChecked(False)
  764. if not self.manager_settings.value("view/toolbar_visible",
  765. defaultValue=True):
  766. self.action_toolbar.setChecked(False)
  767. # load last window size
  768. self.resize(self.manager_settings.value("window_size",
  769. QSize(1100, 600)))
  770. @pyqtSlot(str)
  771. def do_search(self, search):
  772. self.proxy.setFilterFixedString(search)
  773. # noinspection PyArgumentList
  774. @pyqtSlot(name='on_action_search_triggered')
  775. def action_search_triggered(self):
  776. self.searchbox.setFocus()
  777. def get_selected_vms(self):
  778. vms = []
  779. selection = self.table.selectionModel().selection()
  780. indexes = self.proxy.mapSelectionToSource(selection).indexes()
  781. for index in indexes:
  782. if index.column() != 0:
  783. continue
  784. vms.append(index.data(Qt.UserRole))
  785. return vms
  786. def table_selection_changed(self):
  787. # Since selection could have multiple domains
  788. # enable all first and then filter them
  789. for action in self.toolbar.actions() + self.context_menu.actions():
  790. action.setEnabled(True)
  791. for vm in self.get_selected_vms():
  792. # TODO: add boot from device to menu and add windows tools there
  793. # Update available actions:
  794. if vm.state['power'] in \
  795. ['Running', 'Transient', 'Halting', 'Dying']:
  796. self.action_resumevm.setEnabled(False)
  797. self.action_removevm.setEnabled(False)
  798. elif vm.state['power'] == 'Paused':
  799. self.action_removevm.setEnabled(False)
  800. self.action_pausevm.setEnabled(False)
  801. self.action_set_keyboard_layout.setEnabled(False)
  802. self.action_restartvm.setEnabled(False)
  803. self.action_open_console.setEnabled(False)
  804. elif vm.state['power'] == 'Suspend':
  805. self.action_set_keyboard_layout.setEnabled(False)
  806. self.action_removevm.setEnabled(False)
  807. self.action_pausevm.setEnabled(False)
  808. self.action_open_console.setEnabled(False)
  809. elif vm.state['power'] == 'Halted':
  810. self.action_set_keyboard_layout.setEnabled(False)
  811. self.action_pausevm.setEnabled(False)
  812. self.action_shutdownvm.setEnabled(False)
  813. self.action_restartvm.setEnabled(False)
  814. self.action_killvm.setEnabled(False)
  815. self.action_open_console.setEnabled(False)
  816. if vm.klass == 'AdminVM':
  817. self.action_open_console.setEnabled(False)
  818. self.action_settings.setEnabled(False)
  819. self.action_resumevm.setEnabled(False)
  820. self.action_removevm.setEnabled(False)
  821. self.action_clonevm.setEnabled(False)
  822. self.action_pausevm.setEnabled(False)
  823. self.action_restartvm.setEnabled(False)
  824. self.action_killvm.setEnabled(False)
  825. self.action_shutdownvm.setEnabled(False)
  826. self.action_appmenus.setEnabled(False)
  827. self.action_editfwrules.setEnabled(False)
  828. self.action_set_keyboard_layout.setEnabled(False)
  829. self.action_run_command_in_vm.setEnabled(False)
  830. elif vm.klass == 'DispVM':
  831. self.action_appmenus.setEnabled(False)
  832. self.action_restartvm.setEnabled(False)
  833. if vm.vm.features.get('internal', False):
  834. self.action_appmenus.setEnabled(False)
  835. if not vm.updateable and vm.qid != 0:
  836. self.action_updatevm.setEnabled(False)
  837. self.update_logs_menu()
  838. # noinspection PyArgumentList
  839. @pyqtSlot(name='on_action_createvm_triggered')
  840. def action_createvm_triggered(self):
  841. with common_threads.busy_cursor():
  842. create_window = create_new_vm.NewVmDlg(self.qt_app, self.qubes_app)
  843. create_window.exec_()
  844. # noinspection PyArgumentList
  845. @pyqtSlot(name='on_action_removevm_triggered')
  846. def action_removevm_triggered(self):
  847. remove_vms = []
  848. for vm_info in self.get_selected_vms():
  849. vm = vm_info.vm
  850. dependencies = utils.vm_dependencies(self.qubes_app, vm)
  851. if dependencies:
  852. list_deps = manager_utils.format_dependencies_list(dependencies)
  853. list_text = "<br>" + list_deps + "<br>"
  854. info_dialog = QMessageBox(self)
  855. info_dialog.setWindowTitle(self.tr("Warning!"))
  856. info_dialog.setText(
  857. self.tr("This qube cannot be removed. It is used as: <br> "
  858. "{} <small>If you want to remove this qube, you "
  859. "should remove or change settings of each qube or "
  860. "setting that uses it.</small>").format(list_text))
  861. info_dialog.setModal(False)
  862. info_dialog.show()
  863. return
  864. (requested_name, ok) = QInputDialog.getText(
  865. self, self.tr("Qube Removal Confirmation"),
  866. self.tr("Are you sure you want to remove the Qube <b>'{0}'</b>"
  867. "?<br> All data on this Qube's private storage will be "
  868. "lost!<br><br>Type the name of the Qube (<b>{1}</b>) be"
  869. "low to confirm:").format(vm.name, vm.name))
  870. if not ok:
  871. # user clicked cancel
  872. continue
  873. if requested_name == vm.name:
  874. remove_vms.append(vm)
  875. else:
  876. # name did not match
  877. QMessageBox.warning(
  878. self,
  879. self.tr("Qube removal confirmation failed"),
  880. self.tr(
  881. "Entered name did not match! Not removing "
  882. "{0}.").format(vm.name))
  883. # remove the VMs
  884. for vm in remove_vms:
  885. thread = common_threads.RemoveVMThread(vm)
  886. self.threads_list.append(thread)
  887. thread.finished.connect(self.clear_threads)
  888. thread.start()
  889. # noinspection PyArgumentList
  890. @pyqtSlot(name='on_action_clonevm_triggered')
  891. def action_clonevm_triggered(self):
  892. for vm_info in self.get_selected_vms():
  893. vm = vm_info.vm
  894. name_number = 1
  895. name_format = vm.name + '-clone-%d'
  896. while name_format % name_number in self.qubes_app.domains.keys():
  897. name_number += 1
  898. (clone_name, ok) = QInputDialog.getText(
  899. self, self.tr('Qubes clone Qube'),
  900. self.tr('Enter name for Qube <b>{}</b> clone:').format(vm.name),
  901. text=(name_format % name_number))
  902. if not ok or clone_name == "":
  903. return
  904. name_in_use = clone_name in self.qubes_app.domains
  905. if name_in_use:
  906. QMessageBox.warning(
  907. self, self.tr("Name already in use!"),
  908. self.tr("There already exists a qube called '{}'. "
  909. "Cloning aborted.").format(clone_name))
  910. return
  911. self.progress = QProgressDialog(
  912. self.tr(
  913. "Cloning Qube..."), "", 0, 0)
  914. self.progress.setCancelButton(None)
  915. self.progress.setModal(True)
  916. self.progress.setWindowTitle(self.tr("Cloning qube..."))
  917. self.progress.show()
  918. thread = common_threads.CloneVMThread(vm, clone_name)
  919. thread.finished.connect(self.clear_threads)
  920. self.threads_list.append(thread)
  921. thread.start()
  922. # noinspection PyArgumentList
  923. @pyqtSlot(name='on_action_resumevm_triggered')
  924. def action_resumevm_triggered(self):
  925. for vm_info in self.get_selected_vms():
  926. vm = vm_info.vm
  927. if vm.get_power_state() in ["Paused", "Suspended"]:
  928. try:
  929. vm.unpause()
  930. except exc.QubesException as ex:
  931. QMessageBox.warning(
  932. self, self.tr("Error unpausing Qube!"),
  933. self.tr("ERROR: {0}").format(ex))
  934. return
  935. self.start_vm(vm)
  936. def start_vm(self, vm):
  937. if vm.is_running():
  938. return
  939. thread = StartVMThread(vm)
  940. self.threads_list.append(thread)
  941. thread.finished.connect(self.clear_threads)
  942. thread.start()
  943. # noinspection PyArgumentList
  944. @pyqtSlot(name='on_action_startvm_tools_install_triggered')
  945. # TODO: replace with boot from device
  946. def action_startvm_tools_install_triggered(self):
  947. # pylint: disable=invalid-name
  948. pass
  949. @pyqtSlot(name='on_action_pausevm_triggered')
  950. def action_pausevm_triggered(self):
  951. for vm_info in self.get_selected_vms():
  952. try:
  953. vm_info.vm.pause()
  954. except exc.QubesException as ex:
  955. QMessageBox.warning(
  956. self,
  957. self.tr("Error pausing Qube!"),
  958. self.tr("ERROR: {0}").format(ex))
  959. return
  960. # noinspection PyArgumentList
  961. @pyqtSlot(name='on_action_shutdownvm_triggered')
  962. def action_shutdownvm_triggered(self):
  963. for vm_info in self.get_selected_vms():
  964. vm = vm_info.vm
  965. reply = QMessageBox.question(
  966. self, self.tr("Qube Shutdown Confirmation"),
  967. self.tr("Are you sure you want to power down the Qube <b>'{0}'"
  968. "</b>?<br><small>This will shutdown all the running"
  969. " applications within this Qube.</small>").format(
  970. vm.name),
  971. QMessageBox.Yes | QMessageBox.Cancel)
  972. if reply == QMessageBox.Yes:
  973. self.shutdown_vm(vm)
  974. def shutdown_vm(self, vm, shutdown_time=vm_shutdown_timeout,
  975. check_time=vm_restart_check_timeout, and_restart=False):
  976. try:
  977. vm.shutdown()
  978. except exc.QubesException as ex:
  979. QMessageBox.warning(
  980. self,
  981. self.tr("Error shutting down Qube!"),
  982. self.tr("ERROR: {0}").format(ex))
  983. return
  984. self.shutdown_monitor[vm.qid] = VmShutdownMonitor(vm, shutdown_time,
  985. check_time,
  986. and_restart, self)
  987. # noinspection PyCallByClass,PyTypeChecker
  988. QTimer.singleShot(check_time, self.shutdown_monitor[
  989. vm.qid].check_if_vm_has_shutdown)
  990. # noinspection PyArgumentList
  991. @pyqtSlot(name='on_action_restartvm_triggered')
  992. def action_restartvm_triggered(self):
  993. for vm_info in self.get_selected_vms():
  994. vm = vm_info.vm
  995. reply = QMessageBox.question(
  996. self, self.tr("Qube Restart Confirmation"),
  997. self.tr("Are you sure you want to restart the Qube <b>'{0}'</b>"
  998. "?<br><small>This will shutdown all the running applica"
  999. "tions within this Qube.</small>").format(vm.name),
  1000. QMessageBox.Yes | QMessageBox.Cancel)
  1001. if reply == QMessageBox.Yes:
  1002. # in case the user shut down the VM in the meantime
  1003. if vm.is_running():
  1004. self.shutdown_vm(vm, and_restart=True)
  1005. else:
  1006. self.start_vm(vm)
  1007. # noinspection PyArgumentList
  1008. @pyqtSlot(name='on_action_killvm_triggered')
  1009. def action_killvm_triggered(self):
  1010. for vm_info in self.get_selected_vms():
  1011. vm = vm_info.vm
  1012. if not (vm.is_running() or vm.is_paused()):
  1013. info = self.tr("Qube <b>'{0}'</b> is not running. Are you "
  1014. "absolutely sure you want to try to kill it?<br>"
  1015. "<small>This will end <b>(not shutdown!)</b> "
  1016. "all the running applications within this "
  1017. "Qube.</small>").format(vm.name)
  1018. else:
  1019. info = self.tr("Are you sure you want to kill the Qube "
  1020. "<b>'{0}'</b>?<br><small>This will end <b>(not "
  1021. "shutdown!)</b> all the running applications "
  1022. "within this Qube.</small>").format(vm.name)
  1023. reply = QMessageBox.question(
  1024. self, self.tr("Qube Kill Confirmation"), info,
  1025. QMessageBox.Yes | QMessageBox.Cancel,
  1026. QMessageBox.Cancel)
  1027. if reply == QMessageBox.Yes:
  1028. try:
  1029. vm.kill()
  1030. except exc.QubesException as ex:
  1031. QMessageBox.critical(
  1032. self, self.tr("Error while killing Qube!"),
  1033. self.tr(
  1034. "<b>An exception ocurred while killing {0}.</b><br>"
  1035. "ERROR: {1}").format(vm.name, ex))
  1036. return
  1037. def open_settings(self, vm, tab='basic'):
  1038. try:
  1039. with common_threads.busy_cursor():
  1040. settings_window = settings.VMSettingsWindow(
  1041. vm, init_page=tab, qapp=self.qt_app,
  1042. qubesapp=self.qubes_app)
  1043. settings_window.show()
  1044. self.settings_windows[vm.name] = settings_window
  1045. except exc.QubesException as ex:
  1046. QMessageBox.warning(
  1047. self,
  1048. self.tr("Qube settings unavailable"),
  1049. self.tr(
  1050. "Qube settings cannot be opened. The qube might have "
  1051. "been removed or unavailable due to policy settings."
  1052. "\nError: {}".format(str(ex))))
  1053. return
  1054. # noinspection PyArgumentList
  1055. @pyqtSlot(name='on_action_settings_triggered')
  1056. def action_settings_triggered(self):
  1057. for vm_info in self.get_selected_vms():
  1058. self.open_settings(vm_info.vm, "basic")
  1059. # noinspection PyArgumentList
  1060. @pyqtSlot(name='on_action_appmenus_triggered')
  1061. def action_appmenus_triggered(self):
  1062. for vm_info in self.get_selected_vms():
  1063. self.open_settings(vm_info.vm, "applications")
  1064. # noinspection PyArgumentList
  1065. @pyqtSlot(name='on_action_updatevm_triggered')
  1066. def action_updatevm_triggered(self):
  1067. for vm_info in self.get_selected_vms():
  1068. vm = vm_info.vm
  1069. if not vm.is_running():
  1070. reply = QMessageBox.question(
  1071. self, self.tr("Qube Update Confirmation"),
  1072. self.tr(
  1073. "<b>{0}</b>"
  1074. "<br>The Qube has to be running to be updated."
  1075. "<br>Do you want to start it?<br>").format(vm.name),
  1076. QMessageBox.Yes | QMessageBox.Cancel)
  1077. if reply != QMessageBox.Yes:
  1078. return
  1079. thread = UpdateVMThread(vm)
  1080. self.threads_list.append(thread)
  1081. thread.finished.connect(self.clear_threads)
  1082. thread.start()
  1083. # noinspection PyArgumentList
  1084. @pyqtSlot(name='on_action_run_command_in_vm_triggered')
  1085. def action_run_command_in_vm_triggered(self):
  1086. # pylint: disable=invalid-name
  1087. for vm_info in self.get_selected_vms():
  1088. (command_to_run, ok) = QInputDialog.getText(
  1089. self, self.tr('Qubes command entry'),
  1090. self.tr('Run command in <b>{}</b>:').format(vm_info.name))
  1091. if not ok or command_to_run == "":
  1092. return
  1093. thread = RunCommandThread(vm_info.vm, command_to_run)
  1094. self.threads_list.append(thread)
  1095. thread.finished.connect(self.clear_threads)
  1096. thread.start()
  1097. # noinspection PyArgumentList
  1098. @pyqtSlot(name='on_action_open_console_triggered')
  1099. def action_open_console_triggered(self):
  1100. # pylint: disable=invalid-name
  1101. for vm in self.get_selected_vms():
  1102. subprocess.Popen(['qvm-console-dispvm', vm.name],
  1103. stdout=subprocess.DEVNULL,
  1104. stderr=subprocess.DEVNULL)
  1105. # noinspection PyArgumentList
  1106. @pyqtSlot(name='on_action_set_keyboard_layout_triggered')
  1107. def action_set_keyboard_layout_triggered(self):
  1108. # pylint: disable=invalid-name
  1109. for vm_info in self.get_selected_vms():
  1110. vm_info.vm.run('qubes-change-keyboard-layout')
  1111. # noinspection PyArgumentList
  1112. @pyqtSlot(name='on_action_editfwrules_triggered')
  1113. def action_editfwrules_triggered(self):
  1114. for vm_info in self.get_selected_vms():
  1115. self.open_settings(vm_info.vm, "firewall")
  1116. # noinspection PyArgumentList
  1117. @pyqtSlot(name='on_action_global_settings_triggered')
  1118. def action_global_settings_triggered(self): # pylint: disable=invalid-name
  1119. with common_threads.busy_cursor():
  1120. global_settings_window = global_settings.GlobalSettingsWindow(
  1121. self.qt_app,
  1122. self.qubes_app)
  1123. global_settings_window.show()
  1124. self.settings_windows['global_settings_window'] = global_settings_window
  1125. # noinspection PyArgumentList
  1126. @pyqtSlot(name='on_action_manage_templates_triggered')
  1127. def action_manage_templates_triggered(self):
  1128. # pylint: disable=no-self-use
  1129. subprocess.check_call('qubes-template-manager')
  1130. # noinspection PyArgumentList
  1131. @pyqtSlot(name='on_action_show_network_triggered')
  1132. def action_show_network_triggered(self):
  1133. pass
  1134. # TODO: revive for 4.1
  1135. # network_notes_dialog = NetworkNotesDialog()
  1136. # network_notes_dialog.exec_()
  1137. # noinspection PyArgumentList
  1138. @pyqtSlot(name='on_action_restore_triggered')
  1139. def action_restore_triggered(self):
  1140. with common_threads.busy_cursor():
  1141. restore_window = restore.RestoreVMsWindow(self.qt_app,
  1142. self.qubes_app)
  1143. restore_window.exec_()
  1144. # noinspection PyArgumentList
  1145. @pyqtSlot(name='on_action_backup_triggered')
  1146. def action_backup_triggered(self):
  1147. with common_threads.busy_cursor():
  1148. backup_window = backup.BackupVMsWindow(
  1149. self.qt_app, self.qubes_app, self.dispatcher, self)
  1150. backup_window.show()
  1151. # noinspection PyArgumentList
  1152. @pyqtSlot(name='on_action_exit_triggered')
  1153. def action_exit_triggered(self):
  1154. self.close()
  1155. def showhide_menubar(self, checked):
  1156. self.menubar.setVisible(checked)
  1157. if not checked:
  1158. self.context_menu.addAction(self.action_menubar)
  1159. else:
  1160. self.context_menu.removeAction(self.action_menubar)
  1161. if self.settings_loaded:
  1162. self.manager_settings.setValue('view/menubar_visible', checked)
  1163. def showhide_toolbar(self, checked):
  1164. self.toolbar.setVisible(checked)
  1165. if not checked:
  1166. self.context_menu.addAction(self.action_toolbar)
  1167. else:
  1168. self.context_menu.removeAction(self.action_toolbar)
  1169. if self.settings_loaded:
  1170. self.manager_settings.setValue('view/toolbar_visible', checked)
  1171. def showhide_column(self, col_num, show):
  1172. self.table.setColumnHidden(col_num, not show)
  1173. col_name = self.qubes_model.columns_indices[col_num]
  1174. self.manager_settings.setValue('columns/%s' % col_name, show)
  1175. # noinspection PyArgumentList
  1176. @pyqtSlot(name='on_action_about_qubes_triggered')
  1177. def action_about_qubes_triggered(self): # pylint: disable=no-self-use
  1178. about = AboutDialog()
  1179. about.exec_()
  1180. def createPopupMenu(self): # pylint: disable=invalid-name
  1181. menu = QMenu()
  1182. menu.addAction(self.action_toolbar)
  1183. menu.addAction(self.action_menubar)
  1184. return menu
  1185. def open_tools_context_menu(self, widget, point):
  1186. self.tools_context_menu.exec_(widget.mapToGlobal(point))
  1187. def update_logs_menu(self):
  1188. self.logs_menu.clear()
  1189. menu_empty = True
  1190. try:
  1191. vm_info = self.get_selected_vms()
  1192. if len(vm_info) == 1:
  1193. vm = vm_info[0].vm
  1194. if vm.qid == 0:
  1195. logfiles = ["/var/log/xen/console/hypervisor.log"]
  1196. else:
  1197. logfiles = [
  1198. "/var/log/xen/console/guest-" + vm.name + ".log",
  1199. "/var/log/xen/console/guest-" + vm.name + "-dm.log",
  1200. "/var/log/qubes/guid." + vm.name + ".log",
  1201. "/var/log/qubes/qrexec." + vm.name + ".log",
  1202. ]
  1203. for logfile in logfiles:
  1204. if os.path.exists(logfile):
  1205. action = self.logs_menu.addAction(QIcon(":/log.png"),
  1206. logfile)
  1207. action.setData(logfile)
  1208. menu_empty = False
  1209. self.logs_menu.setEnabled(not menu_empty)
  1210. except exc.QubesPropertyAccessError:
  1211. pass
  1212. @pyqtSlot('const QPoint&')
  1213. def open_context_menu(self, point):
  1214. self.context_menu.exec_(self.table.mapToGlobal(
  1215. point + QPoint(10, 0)))
  1216. @pyqtSlot('QAction *')
  1217. def show_log(self, action):
  1218. log = str(action.data())
  1219. log_dlg = log_dialog.LogDialog(self.qt_app, log)
  1220. log_dlg.exec_()
  1221. def main():
  1222. manager_utils.run_asynchronous(VmManagerWindow)
  1223. if __name__ == "__main__":
  1224. main()