qube_manager.py 60 KB

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