qube_manager.py 56 KB

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