qube_manager.py 67 KB

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