qube_manager.py 56 KB

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