qube_manager.py 62 KB

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