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