qube_manager.py 57 KB

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