qube_manager.py 56 KB

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