qube_manager.py 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753
  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_template_menu()
  611. self.init_network_menu()
  612. self.__init_context_menu()
  613. self.tools_context_menu = QMenu(self)
  614. self.tools_context_menu.addAction(self.action_toolbar)
  615. self.tools_context_menu.addAction(self.action_menubar)
  616. self.menubar.customContextMenuRequested.connect(
  617. lambda pos: self.open_tools_context_menu(self.menubar, pos))
  618. self.toolbar.customContextMenuRequested.connect(
  619. lambda pos: self.open_tools_context_menu(self.toolbar, pos))
  620. self.action_menubar.toggled.connect(self.showhide_menubar)
  621. self.action_toolbar.toggled.connect(self.showhide_toolbar)
  622. self.action_show_logs.triggered.connect(self.show_log)
  623. self.action_compact_view.toggled.connect(self.set_compactview)
  624. self.table.resizeColumnsToContents()
  625. self.update_size_on_disk = False
  626. self.shutdown_monitor = {}
  627. self.qubes_cache = QubesCache(qubes_app)
  628. self.fill_cache()
  629. self.qubes_model = QubesTableModel(self.qubes_cache)
  630. self.proxy = QubesProxyModel(self)
  631. self.proxy.setSourceModel(self.qubes_model)
  632. self.proxy.setSortRole(Qt.UserRole + 1)
  633. self.proxy.setSortCaseSensitivity(Qt.CaseInsensitive)
  634. self.proxy.setFilterKeyColumn(2)
  635. self.proxy.setFilterCaseSensitivity(Qt.CaseInsensitive)
  636. self.proxy.layoutChanged.connect(self.save_sorting)
  637. self.proxy.layoutChanged.connect(self.update_template_menu)
  638. self.proxy.layoutChanged.connect(self.update_network_menu)
  639. self.show_running.stateChanged.connect(self.invalidate)
  640. self.show_halted.stateChanged.connect(self.invalidate)
  641. self.show_network.stateChanged.connect(self.invalidate)
  642. self.show_templates.stateChanged.connect(self.invalidate)
  643. self.show_standalone.stateChanged.connect(self.invalidate)
  644. self.show_all.stateChanged.connect(self.invalidate)
  645. self.table.setModel(self.proxy)
  646. self.table.setItemDelegateForColumn(3, StateIconDelegate())
  647. self.table.resizeColumnsToContents()
  648. selection_model = self.table.selectionModel()
  649. selection_model.selectionChanged.connect(self.table_selection_changed)
  650. self.table.setContextMenuPolicy(Qt.CustomContextMenu)
  651. self.table.customContextMenuRequested.connect(self.open_context_menu)
  652. # Create view menu
  653. for col_no in range(len(self.qubes_model.columns_indices)):
  654. column = self.qubes_model.columns_indices[col_no]
  655. action = self.menu_view.addAction(column)
  656. action.setData(column)
  657. action.setCheckable(True)
  658. action.toggled.connect(partial(self.showhide_column, col_no))
  659. self.menu_view.addSeparator()
  660. self.menu_view.addAction(self.action_toolbar)
  661. self.menu_view.addAction(self.action_menubar)
  662. self.menu_view.addSeparator()
  663. self.menu_view.addAction(self.action_compact_view)
  664. try:
  665. self.load_manager_settings()
  666. except Exception as ex: # pylint: disable=broad-except
  667. QMessageBox.warning(
  668. self,
  669. self.tr("Manager settings unreadable"),
  670. self.tr("Qube Manager settings cannot be parsed. Previously "
  671. "saved display settings may not be restored "
  672. "correctly.\nError: {}".format(str(ex))))
  673. self.settings_loaded = True
  674. # Connect events
  675. self.dispatcher = dispatcher
  676. dispatcher.add_handler('domain-pre-start',
  677. self.on_domain_status_changed)
  678. dispatcher.add_handler('domain-start', self.on_domain_status_changed)
  679. dispatcher.add_handler('domain-start-failed',
  680. self.on_domain_status_changed)
  681. dispatcher.add_handler('domain-stopped', self.on_domain_status_changed)
  682. dispatcher.add_handler('domain-pre-shutdown',
  683. self.on_domain_status_changed)
  684. dispatcher.add_handler('domain-shutdown', self.on_domain_status_changed)
  685. dispatcher.add_handler('domain-paused', self.on_domain_status_changed)
  686. dispatcher.add_handler('domain-unpaused', self.on_domain_status_changed)
  687. dispatcher.add_handler('domain-add', self.on_domain_added)
  688. dispatcher.add_handler('domain-delete', self.on_domain_removed)
  689. dispatcher.add_handler('property-set:*',
  690. self.on_domain_changed)
  691. dispatcher.add_handler('property-del:*',
  692. self.on_domain_changed)
  693. dispatcher.add_handler('property-load',
  694. self.on_domain_changed)
  695. dispatcher.add_handler('domain-feature-set:internal',
  696. self.on_domain_changed)
  697. dispatcher.add_handler('domain-feature-delete:internal',
  698. self.on_domain_changed)
  699. dispatcher.add_handler('domain-feature-set:updates-available',
  700. self.on_domain_updates_available)
  701. dispatcher.add_handler('domain-feature-delete:updates-available',
  702. self.on_domain_updates_available)
  703. # It needs to store threads until they finish
  704. self.threads_list = []
  705. self.progress = None
  706. self.check_updates()
  707. def change_template(self, template):
  708. selected_vms = self.get_selected_vms()
  709. reply = QMessageBox.question(
  710. self, self.tr("Template Change Confirmation"),
  711. self.tr("Do you want to change '{0}'<br>"
  712. "to Template <b>'{1}'</b>?").format(
  713. ', '.join(vm.name for vm in selected_vms), template),
  714. QMessageBox.Yes | QMessageBox.Cancel)
  715. if reply == QMessageBox.Yes:
  716. errors = []
  717. for info in selected_vms:
  718. try:
  719. info.vm.template = template
  720. except exc.QubesValueError as ex:
  721. errors.append((info.name, str(ex)))
  722. for error in errors:
  723. QMessageBox.warning(self, self.tr("{0} template change failed!")
  724. .format(error[0]), error[1])
  725. def change_network(self, netvm_name):
  726. selected_vms = self.get_selected_vms()
  727. reply = QMessageBox.question(
  728. self, self.tr("Network Change Confirmation"),
  729. self.tr("Do you want to change '{0}'<br>"
  730. "to Network <b>'{1}'</b>?").format(
  731. ', '.join(vm.name for vm in selected_vms), netvm_name),
  732. QMessageBox.Yes | QMessageBox.Cancel)
  733. if reply != QMessageBox.Yes:
  734. return
  735. if netvm_name not in [None, 'default']:
  736. check_power = any(info.state['power'] == 'Running' for info
  737. in self.get_selected_vms())
  738. netvm = self.qubes_cache.get_vm(name=netvm_name)
  739. if check_power and netvm.state['power'] != 'Running':
  740. reply = QMessageBox.question(
  741. self, self.tr("Qube Start Confirmation"),
  742. self.tr("<br>Can not change netvm to a halted Qube.<br>"
  743. "Do you want to start the Qube <b>'{0}'</b>?").format(
  744. netvm_name),
  745. QMessageBox.Yes | QMessageBox.Cancel)
  746. if reply == QMessageBox.Yes:
  747. self.start_vm(netvm.vm, True)
  748. else:
  749. return
  750. errors = []
  751. for info in self.get_selected_vms():
  752. try:
  753. if netvm_name == 'default':
  754. delattr(info.vm, 'netvm')
  755. else:
  756. info.vm.netvm = netvm_name
  757. except exc.QubesValueError as ex:
  758. errors.append((info.name, str(ex)))
  759. for error in errors:
  760. QMessageBox.warning(self, self.tr("{0} network change failed!")
  761. .format(error[0]), error[1])
  762. def __init_context_menu(self):
  763. self.context_menu = QMenu(self)
  764. self.context_menu.addAction(self.action_settings)
  765. self.context_menu.addAction(self.template_menu.menuAction())
  766. self.context_menu.addAction(self.network_menu.menuAction())
  767. self.context_menu.addAction(self.action_editfwrules)
  768. self.context_menu.addAction(self.action_appmenus)
  769. self.context_menu.addAction(self.action_set_keyboard_layout)
  770. self.context_menu.addSeparator()
  771. self.context_menu.addAction(self.action_updatevm)
  772. self.context_menu.addAction(self.action_run_command_in_vm)
  773. self.context_menu.addAction(self.action_open_console)
  774. self.context_menu.addAction(self.action_resumevm)
  775. self.context_menu.addAction(self.action_startvm_tools_install)
  776. self.context_menu.addAction(self.action_pausevm)
  777. self.context_menu.addAction(self.action_shutdownvm)
  778. self.context_menu.addAction(self.action_restartvm)
  779. self.context_menu.addAction(self.action_killvm)
  780. self.context_menu.addSeparator()
  781. self.context_menu.addAction(self.action_clonevm)
  782. self.context_menu.addAction(self.action_removevm)
  783. self.context_menu.addSeparator()
  784. self.context_menu.addAction(self.action_show_logs)
  785. def save_showing(self):
  786. self.manager_settings.setValue('show/running',
  787. self.show_running.isChecked())
  788. self.manager_settings.setValue('show/halted',
  789. self.show_halted.isChecked())
  790. self.manager_settings.setValue('show/network',
  791. self.show_network.isChecked())
  792. self.manager_settings.setValue('show/templates',
  793. self.show_templates.isChecked())
  794. self.manager_settings.setValue('show/standalone',
  795. self.show_standalone.isChecked())
  796. self.manager_settings.setValue('show/all', self.show_all.isChecked())
  797. def save_sorting(self):
  798. self.manager_settings.setValue('view/sort_column',
  799. self.proxy.sortColumn())
  800. self.manager_settings.setValue('view/sort_order',
  801. self.proxy.sortOrder())
  802. def invalidate(self):
  803. self.proxy.invalidate()
  804. self.table.resizeColumnsToContents()
  805. def fill_cache(self):
  806. progress = QProgressDialog(
  807. self.tr(
  808. "Loading Qube Manager..."), "", 0,
  809. len(self.qubes_app.domains.keys()))
  810. progress.setWindowTitle(self.tr("Qube Manager"))
  811. progress.setMinimumDuration(1000)
  812. progress.setWindowModality(Qt.WindowModal)
  813. progress.setCancelButton(None)
  814. row_no = 0
  815. for vm in self.qubes_app.domains:
  816. progress.setValue(row_no)
  817. self.qubes_cache.add_vm(vm)
  818. row_no += 1
  819. progress.setValue(row_no)
  820. def init_template_menu(self):
  821. self.template_menu.clear()
  822. for vm in self.qubes_app.domains:
  823. if vm.klass == 'TemplateVM':
  824. action = self.template_menu.addAction(vm.name)
  825. action.setData(vm.name)
  826. action.triggered.connect(partial(self.change_template, vm.name))
  827. def _get_default_netvm(self):
  828. for vm in self.qubes_app.domains:
  829. if vm.klass == 'AppVM':
  830. return vm.property_get_default('netvm')
  831. def init_network_menu(self):
  832. default = self._get_default_netvm()
  833. self.network_menu.clear()
  834. action = self.network_menu.addAction("None")
  835. action.triggered.connect(partial(self.change_network, None))
  836. action = self.network_menu.addAction("default ({0})".format(default))
  837. action.triggered.connect(partial(self.change_network, 'default'))
  838. for vm in self.qubes_app.domains:
  839. if vm.qid != 0 and vm.provides_network:
  840. action = self.network_menu.addAction(vm.name)
  841. action.setData(vm.name)
  842. action.triggered.connect(partial(self.change_network, vm.name))
  843. def setup_application(self):
  844. self.qt_app.setApplicationName(self.tr("Qube Manager"))
  845. self.qt_app.setWindowIcon(QIcon.fromTheme("qubes-manager"))
  846. def keyPressEvent(self, event): # pylint: disable=invalid-name
  847. if event.key() == Qt.Key_Escape:
  848. self.searchbox.clear()
  849. super().keyPressEvent(event)
  850. def clear_threads(self):
  851. for thread in self.threads_list:
  852. if thread.isFinished():
  853. if self.progress:
  854. self.progress.hide()
  855. self.progress = None
  856. if thread.msg:
  857. (title, msg) = thread.msg
  858. if thread.msg_is_success:
  859. QMessageBox.information(
  860. self,
  861. title,
  862. msg)
  863. else:
  864. QMessageBox.warning(
  865. self,
  866. title,
  867. msg)
  868. self.threads_list.remove(thread)
  869. return
  870. raise RuntimeError(self.tr('No finished thread found'))
  871. # pylint: disable=invalid-name
  872. def resizeEvent(self, event):
  873. self.manager_settings.setValue("window_size", event.size())
  874. def check_updates(self, info=None):
  875. if info is None:
  876. for info_iter in self.qubes_cache:
  877. self.check_updates(info_iter)
  878. return
  879. try:
  880. if info.vm.klass in {'TemplateVM', 'StandaloneVM'} and \
  881. manager_utils.get_feature(
  882. info.vm, 'updates-available', False):
  883. info.state['outdated'] = 'update'
  884. except exc.QubesDaemonAccessError:
  885. return
  886. def on_domain_added(self, _submitter, _event, vm, **_kwargs):
  887. try:
  888. domain = self.qubes_app.domains[vm]
  889. self.qubes_cache.add_vm(domain)
  890. self.proxy.invalidate()
  891. if domain.klass == 'TemplateVM':
  892. self.init_template_menu()
  893. except (exc.QubesException, KeyError):
  894. pass
  895. def on_domain_removed(self, _submitter, _event, **kwargs):
  896. self.qubes_cache.remove_vm(name=kwargs['vm'])
  897. self.proxy.invalidate()
  898. self.init_template_menu()
  899. self.init_network_menu()
  900. def on_domain_status_changed(self, vm, event, **_kwargs):
  901. try:
  902. self.qubes_cache.get_vm(qid=vm.qid).update(event=event)
  903. if vm.klass in {'TemplateVM'}:
  904. for appvm in vm.appvms:
  905. self.qubes_cache.get_vm(qid=appvm.qid).\
  906. update(event="outdated")
  907. self.proxy.invalidate()
  908. self.table_selection_changed()
  909. except exc.QubesDaemonAccessError:
  910. return # the VM was deleted before its status could be updated
  911. except KeyError: # adding the VM failed for some reason
  912. self.on_domain_added(None, None, vm)
  913. def on_domain_updates_available(self, vm, _event, **_kwargs):
  914. self.check_updates(self.qubes_cache.get_vm(qid=vm.qid))
  915. def on_domain_changed(self, vm, event, **_kwargs):
  916. if not vm: # change of global properties occured
  917. if event.endswith(':default_netvm'):
  918. for vm_info in self.qubes_cache:
  919. vm_info.update(event='property-set:netvm')
  920. if event.endswith(':default_dispvm'):
  921. for vm_info in self.qubes_cache:
  922. vm_info.update(event='property-set:default_dispvm')
  923. return
  924. try:
  925. if event.endswith(':provides_network'):
  926. self.init_network_menu()
  927. self.qubes_cache.get_vm(qid=vm.qid).update(event=event)
  928. self.proxy.invalidate()
  929. except exc.QubesDaemonAccessError:
  930. return # the VM was deleted before its status could be updated
  931. def load_manager_settings(self):
  932. # Load view menu settings
  933. for action in self.menu_view.actions():
  934. column = action.data()
  935. if column is not None:
  936. col_no = self.qubes_model.columns_indices.index(column)
  937. if column == 'Name':
  938. # 'Name' column should be always visible
  939. action.setChecked(True)
  940. else:
  941. visible = self.manager_settings.value('columns/%s' % column,
  942. defaultValue="true")
  943. action.setChecked(visible == "true")
  944. self.showhide_column(col_no, visible == "true")
  945. # Restore sorting
  946. sort_column = int(self.manager_settings.value("view/sort_column",
  947. defaultValue=2))
  948. order = Qt.SortOrder(self.manager_settings.value("view/sort_order",
  949. defaultValue=Qt.AscendingOrder))
  950. if not sort_column: # Default sort by name
  951. self.table.sortByColumn(2, Qt.AscendingOrder)
  952. else:
  953. self.table.sortByColumn(sort_column, order)
  954. if not self.manager_settings.value("view/menubar_visible",
  955. defaultValue=True):
  956. self.action_menubar.setChecked(False)
  957. if not self.manager_settings.value("view/toolbar_visible",
  958. defaultValue=True):
  959. self.action_toolbar.setChecked(False)
  960. if self.manager_settings.value("view/compactview",
  961. defaultValue="false") != "false":
  962. self.action_compact_view.setChecked(True)
  963. # Restore show checkboxes
  964. self.show_running.setChecked(self.manager_settings.value(
  965. 'show/running', "true") == "true")
  966. self.show_halted.setChecked(self.manager_settings.value(
  967. 'show/halted', "true") == "true")
  968. self.show_network.setChecked(self.manager_settings.value(
  969. 'show/network', "true") == "true")
  970. self.show_templates.setChecked(self.manager_settings.value(
  971. 'show/templates', "true") == "true")
  972. self.show_standalone.setChecked(self.manager_settings.value(
  973. 'show/standalone', "true") == "true")
  974. self.show_all.setChecked(self.manager_settings.value(
  975. 'show/all', "true") == "true")
  976. # load last window size
  977. self.resize(self.manager_settings.value("window_size",
  978. QSize(1100, 600)))
  979. @pyqtSlot(str)
  980. def do_search(self, search):
  981. self.proxy.setFilterFixedString(search)
  982. # noinspection PyArgumentList
  983. @pyqtSlot(name='on_action_search_triggered')
  984. def action_search_triggered(self):
  985. self.searchbox.setFocus()
  986. def get_selected_vms(self):
  987. vms = []
  988. selection = self.table.selectionModel().selection()
  989. indexes = self.proxy.mapSelectionToSource(selection).indexes()
  990. for index in indexes:
  991. if index.column() != 0:
  992. continue
  993. vms.append(index.data(Qt.UserRole))
  994. return vms
  995. def table_selection_changed(self):
  996. # Since selection could have multiple domains
  997. # enable all first and then filter them
  998. self.template_menu.setEnabled(True)
  999. self.network_menu.setEnabled(True)
  1000. for action in self.toolbar.actions() + self.context_menu.actions():
  1001. action.setEnabled(True)
  1002. for vm in self.get_selected_vms():
  1003. # TODO: add boot from device to menu and add windows tools there
  1004. # Update available actions:
  1005. if vm.state['power'] in \
  1006. ['Running', 'Transient', 'Halting', 'Dying']:
  1007. self.action_resumevm.setEnabled(False)
  1008. self.action_removevm.setEnabled(False)
  1009. self.template_menu.setEnabled(False)
  1010. elif vm.state['power'] == 'Paused':
  1011. self.action_removevm.setEnabled(False)
  1012. self.action_pausevm.setEnabled(False)
  1013. self.action_set_keyboard_layout.setEnabled(False)
  1014. self.action_restartvm.setEnabled(False)
  1015. self.action_open_console.setEnabled(False)
  1016. self.template_menu.setEnabled(False)
  1017. elif vm.state['power'] == 'Suspend':
  1018. self.action_set_keyboard_layout.setEnabled(False)
  1019. self.action_removevm.setEnabled(False)
  1020. self.action_pausevm.setEnabled(False)
  1021. self.action_open_console.setEnabled(False)
  1022. self.template_menu.setEnabled(False)
  1023. elif vm.state['power'] == 'Halted':
  1024. self.action_set_keyboard_layout.setEnabled(False)
  1025. self.action_pausevm.setEnabled(False)
  1026. self.action_shutdownvm.setEnabled(False)
  1027. self.action_restartvm.setEnabled(False)
  1028. self.action_killvm.setEnabled(False)
  1029. self.action_open_console.setEnabled(False)
  1030. if vm.klass == 'AdminVM':
  1031. self.action_open_console.setEnabled(False)
  1032. self.action_settings.setEnabled(False)
  1033. self.action_resumevm.setEnabled(False)
  1034. self.action_removevm.setEnabled(False)
  1035. self.action_clonevm.setEnabled(False)
  1036. self.action_pausevm.setEnabled(False)
  1037. self.action_restartvm.setEnabled(False)
  1038. self.action_killvm.setEnabled(False)
  1039. self.action_shutdownvm.setEnabled(False)
  1040. self.action_appmenus.setEnabled(False)
  1041. self.action_editfwrules.setEnabled(False)
  1042. self.action_set_keyboard_layout.setEnabled(False)
  1043. self.action_run_command_in_vm.setEnabled(False)
  1044. self.template_menu.setEnabled(False)
  1045. self.network_menu.setEnabled(False)
  1046. elif vm.klass == 'DispVM':
  1047. self.action_appmenus.setEnabled(False)
  1048. self.action_restartvm.setEnabled(False)
  1049. self.template_menu.setEnabled(False)
  1050. elif vm.klass == 'TemplateVM':
  1051. self.template_menu.setEnabled(False)
  1052. self.network_menu.setEnabled(False)
  1053. if vm.vm.features.get('internal', False):
  1054. self.action_appmenus.setEnabled(False)
  1055. if not vm.updateable and vm.klass != 'AdminVM':
  1056. self.action_updatevm.setEnabled(False)
  1057. self.update_template_menu()
  1058. self.update_network_menu()
  1059. def update_template_menu(self):
  1060. if not self.template_menu.isEnabled():
  1061. return
  1062. for entry in self.template_menu.actions():
  1063. entry.setIcon(QIcon())
  1064. vms = self.get_selected_vms()
  1065. for vm in vms:
  1066. for entry in self.template_menu.actions():
  1067. if entry.data() == vm.template:
  1068. if len(vms) == 1:
  1069. entry.setIcon(QIcon(":/on.png"))
  1070. else:
  1071. entry.setIcon(QIcon(":/transient.png"))
  1072. def update_network_menu(self):
  1073. if not self.network_menu.isEnabled():
  1074. return
  1075. for entry in self.network_menu.actions():
  1076. entry.setIcon(QIcon())
  1077. if len(self.get_selected_vms()) == 1:
  1078. icon = QIcon(":/on.png")
  1079. else:
  1080. icon = QIcon(":/transient.png")
  1081. for vm in self.get_selected_vms():
  1082. if vm.netvm == "n/a":
  1083. self.network_menu.actions()[0].setIcon(QIcon(icon))
  1084. elif vm.vm.property_is_default("netvm"):
  1085. self.network_menu.actions()[1].setIcon(QIcon(icon))
  1086. else:
  1087. for entry in self.network_menu.actions():
  1088. if entry.data() == vm.netvm:
  1089. entry.setIcon(icon)
  1090. # noinspection PyArgumentList
  1091. @pyqtSlot(name='on_action_createvm_triggered')
  1092. def action_createvm_triggered(self):
  1093. with common_threads.busy_cursor():
  1094. create_window = create_new_vm.NewVmDlg(self.qt_app, self.qubes_app)
  1095. create_window.exec_()
  1096. # noinspection PyArgumentList
  1097. @pyqtSlot(name='on_action_removevm_triggered')
  1098. def action_removevm_triggered(self):
  1099. remove_vms = []
  1100. for vm_info in self.get_selected_vms():
  1101. vm = vm_info.vm
  1102. dependencies = utils.vm_dependencies(self.qubes_app, vm)
  1103. if dependencies:
  1104. list_deps = manager_utils.format_dependencies_list(dependencies)
  1105. list_text = "<br>" + list_deps + "<br>"
  1106. info_dialog = QMessageBox(self)
  1107. info_dialog.setWindowTitle(self.tr("Warning!"))
  1108. info_dialog.setText(
  1109. self.tr("This qube cannot be removed. It is used as: <br> "
  1110. "{} <small>If you want to remove this qube, you "
  1111. "should remove or change settings of each qube or "
  1112. "setting that uses it.</small>").format(list_text))
  1113. info_dialog.setModal(False)
  1114. info_dialog.show()
  1115. return
  1116. (requested_name, ok) = QInputDialog.getText(
  1117. self, self.tr("Qube Removal Confirmation"),
  1118. self.tr("Are you sure you want to remove the Qube <b>'{0}'</b>"
  1119. "?<br> All data on this Qube's private storage will be "
  1120. "lost!<br><br>Type the name of the Qube (<b>{1}</b>) be"
  1121. "low to confirm:").format(vm.name, vm.name))
  1122. if not ok:
  1123. # user clicked cancel
  1124. continue
  1125. if requested_name == vm.name:
  1126. remove_vms.append(vm)
  1127. else:
  1128. # name did not match
  1129. QMessageBox.warning(
  1130. self,
  1131. self.tr("Qube removal confirmation failed"),
  1132. self.tr(
  1133. "Entered name did not match! Not removing "
  1134. "{0}.").format(vm.name))
  1135. # remove the VMs
  1136. for vm in remove_vms:
  1137. thread = common_threads.RemoveVMThread(vm)
  1138. self.threads_list.append(thread)
  1139. thread.finished.connect(self.clear_threads)
  1140. thread.start()
  1141. # noinspection PyArgumentList
  1142. @pyqtSlot(name='on_action_clonevm_triggered')
  1143. def action_clonevm_triggered(self):
  1144. for vm_info in self.get_selected_vms():
  1145. vm = vm_info.vm
  1146. with common_threads.busy_cursor():
  1147. clone_window = clone_vm.CloneVMDlg(
  1148. self.qt_app, self.qubes_app, src_vm=vm)
  1149. clone_window.exec_()
  1150. # noinspection PyArgumentList
  1151. @pyqtSlot(name='on_action_resumevm_triggered')
  1152. def action_resumevm_triggered(self):
  1153. for vm_info in self.get_selected_vms():
  1154. vm = vm_info.vm
  1155. try:
  1156. if vm.get_power_state() in ["Paused", "Suspended"]:
  1157. vm.unpause()
  1158. except exc.QubesException as ex:
  1159. QMessageBox.warning(
  1160. self, self.tr("Error unpausing Qube!"),
  1161. self.tr("ERROR: {0}").format(ex))
  1162. return
  1163. self.start_vm(vm)
  1164. def start_vm(self, vm, wait=False):
  1165. if manager_utils.is_running(vm, False):
  1166. return
  1167. thread = StartVMThread(vm)
  1168. self.threads_list.append(thread)
  1169. thread.finished.connect(self.clear_threads)
  1170. thread.start()
  1171. if wait:
  1172. with common_threads.busy_cursor():
  1173. thread.wait()
  1174. # noinspection PyArgumentList
  1175. @pyqtSlot(name='on_action_startvm_tools_install_triggered')
  1176. # TODO: replace with boot from device
  1177. def action_startvm_tools_install_triggered(self):
  1178. # pylint: disable=invalid-name
  1179. pass
  1180. @pyqtSlot(name='on_action_pausevm_triggered')
  1181. def action_pausevm_triggered(self):
  1182. for vm_info in self.get_selected_vms():
  1183. try:
  1184. vm_info.vm.pause()
  1185. except exc.QubesException as ex:
  1186. QMessageBox.warning(
  1187. self,
  1188. self.tr("Error pausing Qube!"),
  1189. self.tr("ERROR: {0}").format(ex))
  1190. return
  1191. # noinspection PyArgumentList
  1192. @pyqtSlot(name='on_action_shutdownvm_triggered')
  1193. def action_shutdownvm_triggered(self):
  1194. for vm_info in self.get_selected_vms():
  1195. vm = vm_info.vm
  1196. reply = QMessageBox.question(
  1197. self, self.tr("Qube Shutdown Confirmation"),
  1198. self.tr("Are you sure you want to power down the Qube <b>'{0}'"
  1199. "</b>?<br><small>This will shutdown all the running"
  1200. " applications within this Qube.</small>").format(
  1201. vm.name),
  1202. QMessageBox.Yes | QMessageBox.Cancel)
  1203. if reply == QMessageBox.Yes:
  1204. self.shutdown_vm(vm)
  1205. def get_connected_vms(self, vm, connected_vms):
  1206. for connected_vm in vm.connected_vms:
  1207. if connected_vm.is_running():
  1208. connected_vms.append(connected_vm)
  1209. self.get_connected_vms(connected_vm, connected_vms)
  1210. def shutdown_vm(self, vm, force=False, check_time=vm_restart_check_timeout,
  1211. and_restart=False):
  1212. try:
  1213. connected_vms = []
  1214. if not and_restart:
  1215. self.get_connected_vms(vm, connected_vms)
  1216. if len(connected_vms) > 0:
  1217. reply = QMessageBox.question(
  1218. self, self.tr("Qube Shutdown Confirmation"),
  1219. self.tr("There are some qubes connected to <b>'{0}'</b>!"
  1220. "<br><small>Do you want to shutdown: </small>"
  1221. "<b>'{1}'</b>?").format(vm.name,
  1222. ", ".join([x.name for x in connected_vms])),
  1223. QMessageBox.Yes | QMessageBox.Cancel)
  1224. if reply != QMessageBox.Yes:
  1225. return False
  1226. force = True
  1227. for connected_vm in connected_vms:
  1228. connected_vm.shutdown(force=force)
  1229. vm.shutdown(force=force)
  1230. except exc.QubesException as ex:
  1231. QMessageBox.warning(
  1232. self,
  1233. self.tr("Error shutting down Qube!"),
  1234. self.tr("ERROR: {0}").format(ex))
  1235. return False
  1236. self.shutdown_monitor[vm.qid] = VmShutdownMonitor(vm, check_time,
  1237. and_restart, self)
  1238. # noinspection PyCallByClass,PyTypeChecker
  1239. QTimer.singleShot(check_time, self.shutdown_monitor[
  1240. vm.qid].check_if_vm_has_shutdown)
  1241. return True
  1242. # noinspection PyArgumentList
  1243. @pyqtSlot(name='on_action_restartvm_triggered')
  1244. def action_restartvm_triggered(self):
  1245. for vm_info in self.get_selected_vms():
  1246. vm = vm_info.vm
  1247. reply = QMessageBox.question(
  1248. self, self.tr("Qube Restart Confirmation"),
  1249. self.tr("Are you sure you want to restart the Qube <b>'{0}'</b>"
  1250. "?<br><small>This will shutdown all the running applica"
  1251. "tions within this Qube.</small>").format(vm.name),
  1252. QMessageBox.Yes | QMessageBox.Cancel)
  1253. if reply == QMessageBox.Yes:
  1254. # in case the user shut down the VM in the meantime
  1255. try:
  1256. if manager_utils.is_running(vm, False):
  1257. self.shutdown_vm(vm, force=True, and_restart=True)
  1258. else:
  1259. self.start_vm(vm)
  1260. except exc.QubesException as ex:
  1261. QMessageBox.warning(
  1262. self,
  1263. self.tr("Error restarting Qube!"),
  1264. self.tr("ERROR: {0}").format(ex))
  1265. # noinspection PyArgumentList
  1266. @pyqtSlot(name='on_action_killvm_triggered')
  1267. def action_killvm_triggered(self):
  1268. for vm_info in self.get_selected_vms():
  1269. vm = vm_info.vm
  1270. try:
  1271. vm_not_running = not (vm.is_running() or vm.is_paused())
  1272. except exc.QubesDaemonAccessError:
  1273. vm_not_running = False
  1274. if vm_not_running:
  1275. info = self.tr("Qube <b>'{0}'</b> is not running. Are you "
  1276. "absolutely sure you want to try to kill it?<br>"
  1277. "<small>This will end <b>(not shutdown!)</b> "
  1278. "all the running applications within this "
  1279. "Qube.</small>").format(vm.name)
  1280. else:
  1281. info = self.tr("Are you sure you want to kill the Qube "
  1282. "<b>'{0}'</b>?<br><small>This will end <b>(not "
  1283. "shutdown!)</b> all the running applications "
  1284. "within this Qube.</small>").format(vm.name)
  1285. reply = QMessageBox.question(
  1286. self, self.tr("Qube Kill Confirmation"), info,
  1287. QMessageBox.Yes | QMessageBox.Cancel,
  1288. QMessageBox.Cancel)
  1289. if reply == QMessageBox.Yes:
  1290. try:
  1291. vm.kill()
  1292. except exc.QubesException as ex:
  1293. QMessageBox.critical(
  1294. self, self.tr("Error while killing Qube!"),
  1295. self.tr(
  1296. "<b>An exception occurred while killing {0}.</b>"
  1297. "<br>ERROR: {1}").format(vm.name, ex))
  1298. return
  1299. def open_settings(self, vm, tab='basic'):
  1300. try:
  1301. with common_threads.busy_cursor():
  1302. settings_window = settings.VMSettingsWindow(
  1303. vm, init_page=tab, qapp=self.qt_app,
  1304. qubesapp=self.qubes_app)
  1305. settings_window.show()
  1306. self.settings_windows[vm.name] = settings_window
  1307. except exc.QubesException as ex:
  1308. QMessageBox.warning(
  1309. self,
  1310. self.tr("Qube settings unavailable"),
  1311. self.tr(
  1312. "Qube settings cannot be opened. The qube might have "
  1313. "been removed or unavailable due to policy settings."
  1314. "\nError: {}".format(str(ex))))
  1315. return
  1316. def closeEvent(self, _):
  1317. self.save_showing()
  1318. # noinspection PyArgumentList
  1319. @pyqtSlot(name='on_action_settings_triggered')
  1320. def action_settings_triggered(self):
  1321. for vm_info in self.get_selected_vms():
  1322. self.open_settings(vm_info.vm, "basic")
  1323. # noinspection PyArgumentList
  1324. @pyqtSlot(name='on_action_appmenus_triggered')
  1325. def action_appmenus_triggered(self):
  1326. for vm_info in self.get_selected_vms():
  1327. self.open_settings(vm_info.vm, "applications")
  1328. # noinspection PyArgumentList
  1329. @pyqtSlot(name='on_action_updatevm_triggered')
  1330. def action_updatevm_triggered(self):
  1331. for vm_info in self.get_selected_vms():
  1332. vm = vm_info.vm
  1333. if not manager_utils.is_running(vm, True):
  1334. reply = QMessageBox.question(
  1335. self, self.tr("Qube Update Confirmation"),
  1336. self.tr(
  1337. "<b>{0}</b>"
  1338. "<br>The Qube has to be running to be updated."
  1339. "<br>Do you want to start it?<br>").format(vm.name),
  1340. QMessageBox.Yes | QMessageBox.Cancel)
  1341. if reply != QMessageBox.Yes:
  1342. return
  1343. thread = UpdateVMThread(vm)
  1344. self.threads_list.append(thread)
  1345. thread.finished.connect(self.clear_threads)
  1346. thread.start()
  1347. # noinspection PyArgumentList
  1348. @pyqtSlot(name='on_action_run_command_in_vm_triggered')
  1349. def action_run_command_in_vm_triggered(self):
  1350. # pylint: disable=invalid-name
  1351. for vm_info in self.get_selected_vms():
  1352. (command_to_run, ok) = QInputDialog.getText(
  1353. self, self.tr('Qubes command entry'),
  1354. self.tr('Run command in <b>{}</b>:').format(vm_info.name))
  1355. if not ok or command_to_run == "":
  1356. return
  1357. thread = RunCommandThread(vm_info.vm, command_to_run)
  1358. self.threads_list.append(thread)
  1359. thread.finished.connect(self.clear_threads)
  1360. thread.start()
  1361. # noinspection PyArgumentList
  1362. @pyqtSlot(name='on_action_open_console_triggered')
  1363. def action_open_console_triggered(self):
  1364. # pylint: disable=invalid-name
  1365. for vm in self.get_selected_vms():
  1366. subprocess.Popen(['qvm-console-dispvm', vm.name],
  1367. stdout=subprocess.DEVNULL,
  1368. stderr=subprocess.DEVNULL)
  1369. # noinspection PyArgumentList
  1370. @pyqtSlot(name='on_action_set_keyboard_layout_triggered')
  1371. def action_set_keyboard_layout_triggered(self):
  1372. # pylint: disable=invalid-name
  1373. for vm_info in self.get_selected_vms():
  1374. if vm_info.vm.features.check_with_template(
  1375. "supported-feature.keyboard-layout", False):
  1376. vm_info.vm.run('qubes-change-keyboard-layout')
  1377. else:
  1378. QMessageBox.warning(
  1379. self,
  1380. self.tr("Keyboard layout change unsupported"),
  1381. self.tr(
  1382. "Please update the qube {} or its template to the "
  1383. "newest version of Qubes tools.").format(
  1384. str(vm_info.vm)))
  1385. # noinspection PyArgumentList
  1386. @pyqtSlot(name='on_action_editfwrules_triggered')
  1387. def action_editfwrules_triggered(self):
  1388. for vm_info in self.get_selected_vms():
  1389. self.open_settings(vm_info.vm, "firewall")
  1390. # noinspection PyArgumentList
  1391. @pyqtSlot(name='on_action_global_settings_triggered')
  1392. def action_global_settings_triggered(self): # pylint: disable=invalid-name
  1393. with common_threads.busy_cursor():
  1394. global_settings_window = global_settings.GlobalSettingsWindow(
  1395. self.qt_app,
  1396. self.qubes_app)
  1397. global_settings_window.show()
  1398. self.settings_windows['global_settings_window'] = global_settings_window
  1399. # noinspection PyArgumentList
  1400. @pyqtSlot(name='on_action_manage_templates_triggered')
  1401. def action_manage_templates_triggered(self):
  1402. # pylint: disable=no-self-use
  1403. subprocess.check_call('qubes-template-manager')
  1404. # noinspection PyArgumentList
  1405. @pyqtSlot(name='on_action_show_network_triggered')
  1406. def action_show_network_triggered(self):
  1407. pass
  1408. # TODO: revive for 4.1
  1409. # network_notes_dialog = NetworkNotesDialog()
  1410. # network_notes_dialog.exec_()
  1411. # noinspection PyArgumentList
  1412. @pyqtSlot(name='on_action_restore_triggered')
  1413. def action_restore_triggered(self):
  1414. with common_threads.busy_cursor():
  1415. restore_window = restore.RestoreVMsWindow(self.qt_app,
  1416. self.qubes_app)
  1417. restore_window.exec_()
  1418. # noinspection PyArgumentList
  1419. @pyqtSlot(name='on_action_backup_triggered')
  1420. def action_backup_triggered(self):
  1421. with common_threads.busy_cursor():
  1422. backup_window = backup.BackupVMsWindow(
  1423. self.qt_app, self.qubes_app, self.dispatcher, self)
  1424. backup_window.show()
  1425. # noinspection PyArgumentList
  1426. @pyqtSlot(name='on_action_exit_triggered')
  1427. def action_exit_triggered(self):
  1428. self.close()
  1429. def set_compactview(self, checked):
  1430. if checked:
  1431. self.toolbar.setToolButtonStyle(Qt.ToolButtonIconOnly)
  1432. else:
  1433. self.toolbar.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
  1434. if self.settings_loaded:
  1435. self.manager_settings.setValue('view/compactview', checked)
  1436. def showhide_menubar(self, checked):
  1437. self.menubar.setVisible(checked)
  1438. if not checked:
  1439. self.context_menu.addAction(self.action_menubar)
  1440. else:
  1441. self.context_menu.removeAction(self.action_menubar)
  1442. if self.settings_loaded:
  1443. self.manager_settings.setValue('view/menubar_visible', checked)
  1444. def showhide_toolbar(self, checked):
  1445. self.toolbar.setVisible(checked)
  1446. if not checked:
  1447. self.context_menu.addAction(self.action_toolbar)
  1448. else:
  1449. self.context_menu.removeAction(self.action_toolbar)
  1450. if self.settings_loaded:
  1451. self.manager_settings.setValue('view/toolbar_visible', checked)
  1452. def showhide_column(self, col_num, show):
  1453. self.table.setColumnHidden(col_num, not show)
  1454. col_name = self.qubes_model.columns_indices[col_num]
  1455. self.manager_settings.setValue('columns/%s' % col_name, show)
  1456. # noinspection PyArgumentList
  1457. @pyqtSlot(name='on_action_about_qubes_triggered')
  1458. def action_about_qubes_triggered(self): # pylint: disable=no-self-use
  1459. about = AboutDialog()
  1460. about.exec_()
  1461. def createPopupMenu(self): # pylint: disable=invalid-name
  1462. menu = QMenu()
  1463. menu.addAction(self.action_toolbar)
  1464. menu.addAction(self.action_menubar)
  1465. return menu
  1466. def open_tools_context_menu(self, widget, point):
  1467. self.tools_context_menu.exec_(widget.mapToGlobal(point))
  1468. @pyqtSlot('const QPoint&')
  1469. def open_context_menu(self, point):
  1470. self.context_menu.exec_(self.table.mapToGlobal(
  1471. point + QPoint(10, 0)))
  1472. def show_log(self):
  1473. logfiles = []
  1474. try:
  1475. for vm_info in self.get_selected_vms():
  1476. vm = vm_info.vm
  1477. if vm.klass == 'AdminVM':
  1478. logfiles.append("/var/log/xen/console/hypervisor.log")
  1479. else:
  1480. logfiles.extend([
  1481. "/var/log/xen/console/guest-" + vm.name + ".log",
  1482. "/var/log/xen/console/guest-" + vm.name + "-dm.log",
  1483. "/var/log/qubes/guid." + vm.name + ".log",
  1484. "/var/log/qubes/qrexec." + vm.name + ".log",
  1485. ])
  1486. logfiles = [x for x in logfiles if path.exists(x)]
  1487. if len(logfiles) > 0:
  1488. log_dlg = log_dialog.LogDialog(self.qt_app, logfiles)
  1489. log_dlg.exec_()
  1490. else:
  1491. QMessageBox.warning(
  1492. self,
  1493. self.tr("Error"),
  1494. self.tr(
  1495. "No log files were found for the selected qubes."))
  1496. except exc.QubesDaemonAccessError:
  1497. pass
  1498. def main():
  1499. manager_utils.run_asynchronous(VmManagerWindow)
  1500. if __name__ == "__main__":
  1501. main()