restore.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. #!/usr/bin/python2
  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 <marmarek@mimuw.edu.pl>
  7. #
  8. # This program is free software; you can redistribute it and/or
  9. # modify it under the terms of the GNU General Public License
  10. # as published by the Free Software Foundation; either version 2
  11. # of the License, or (at your option) any later version.
  12. #
  13. # This program is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU Lesser General Public License along
  19. # with this program; if not, see <http://www.gnu.org/licenses/>.
  20. #
  21. #
  22. import sys
  23. from PyQt4 import QtCore # pylint: disable=import-error
  24. from PyQt4 import QtGui # pylint: disable=import-error
  25. import os
  26. import os.path
  27. import traceback
  28. import logging
  29. import logging.handlers
  30. from qubes import backup
  31. from . import ui_restoredlg # pylint: disable=no-name-in-module
  32. from . import multiselectwidget
  33. from . import backup_utils
  34. from multiprocessing import Queue
  35. from multiprocessing.queues import Empty
  36. from qubesadmin import Qubes, exc
  37. from qubesadmin.backup import restore
  38. # pylint: disable=too-few-public-methods
  39. class RestoreThread(QtCore.QThread):
  40. def __init__(self, backup_restore, vms_to_restore):
  41. QtCore.QThread.__init__(self)
  42. self.backup_restore = backup_restore
  43. self.vms_to_restore = vms_to_restore
  44. self.msg = None
  45. self.canceled = None
  46. def run(self):
  47. err_msg = []
  48. try:
  49. self.backup_restore.restore_do(self.vms_to_restore)
  50. except backup.BackupCanceledError as ex:
  51. self.canceled = True
  52. err_msg.append(str(ex))
  53. except Exception as ex: # pylint: disable=broad-except
  54. err_msg.append(str(ex))
  55. err_msg.append(
  56. self.tr("Partially restored files left in /var/tmp/restore_*, "
  57. "investigate them and/or clean them up"))
  58. if err_msg:
  59. self.msg = '\n'.join(err_msg)
  60. self.msg = '<b><font color="red">{0}</font></b>'.format(
  61. self.tr("Finished with errors!"))
  62. else:
  63. self.msg = '<font color="green">{0}</font>'.format(
  64. self.tr("Finished successfully!"))
  65. class RestoreVMsWindow(ui_restoredlg.Ui_Restore, QtGui.QWizard):
  66. def __init__(self, qt_app, qubes_app, parent=None):
  67. super(RestoreVMsWindow, self).__init__(parent)
  68. self.qt_app = qt_app
  69. self.qubes_app = qubes_app
  70. self.vms_to_restore = None
  71. self.func_output = []
  72. self.thread = None
  73. # Set up logging
  74. self.feedback_queue = Queue()
  75. handler = logging.handlers.QueueHandler(self.feedback_queue)
  76. logger = logging.getLogger('qubesadmin.backup')
  77. logger.addHandler(handler)
  78. logger.setLevel(logging.INFO)
  79. self.backup_restore = None
  80. self.target_appvm = None
  81. self.setupUi(self)
  82. self.select_vms_widget = multiselectwidget.MultiSelectWidget(self)
  83. self.select_vms_layout.insertWidget(1, self.select_vms_widget)
  84. self.connect(self,
  85. QtCore.SIGNAL("currentIdChanged(int)"),
  86. self.current_page_changed)
  87. self.dir_line_edit.connect(self.dir_line_edit,
  88. QtCore.SIGNAL("textChanged(QString)"),
  89. self.backup_location_changed)
  90. self.select_dir_page.isComplete = self.has_selected_dir
  91. self.select_vms_page.isComplete = self.has_selected_vms
  92. self.confirm_page.isComplete = self.all_vms_good
  93. # FIXME
  94. # this causes to run isComplete() twice, I don't know why
  95. self.select_vms_page.connect(
  96. self.select_vms_widget,
  97. QtCore.SIGNAL("selected_changed()"),
  98. QtCore.SIGNAL("completeChanged()"))
  99. backup_utils.fill_appvms_list(self)
  100. @QtCore.pyqtSlot(name='on_select_path_button_clicked')
  101. def select_path_button_clicked(self):
  102. backup_utils.select_path_button_clicked(self, True)
  103. def cleanupPage(self, p_int): # pylint: disable=invalid-name
  104. if self.page(p_int) is self.select_vms_page:
  105. self.vms_to_restore = None
  106. else:
  107. super(RestoreVMsWindow, self).cleanupPage(p_int)
  108. def __fill_vms_list__(self):
  109. if self.vms_to_restore is not None:
  110. return
  111. self.select_vms_widget.selected_list.clear()
  112. self.select_vms_widget.available_list.clear()
  113. self.target_appvm = None
  114. if self.appvm_combobox.currentIndex() != 0: # An existing appvm chosen
  115. self.target_appvm = self.qubes_app.domains[
  116. str(self.appvm_combobox.currentText())]
  117. try:
  118. self.backup_restore = restore.BackupRestore(
  119. self.qubes_app,
  120. self.dir_line_edit.text(),
  121. self.target_appvm,
  122. self.passphrase_line_edit.text()
  123. )
  124. if self.ignore_missing.isChecked():
  125. self.backup_restore.options.use_default_template = True
  126. self.backup_restore.options.use_default_netvm = True
  127. if self.ignore_uname_mismatch.isChecked():
  128. self.backup_restore.options.ignore_username_mismatch = True
  129. if self.verify_only.isChecked():
  130. self.backup_restore.options.verify_only = True
  131. # pylint: disable=assignment-from-no-return
  132. self.vms_to_restore = self.backup_restore.get_restore_info()
  133. for vmname in self.vms_to_restore:
  134. if vmname.startswith('$'):
  135. # Internal info
  136. continue
  137. self.select_vms_widget.available_list.addItem(vmname)
  138. except exc.QubesException as ex:
  139. QtGui.QMessageBox.warning(None, self.tr("Restore error!"), str(ex))
  140. self.restart()
  141. def append_output(self, text):
  142. self.commit_text_edit.append(text)
  143. def current_page_changed(self, page_id): # pylint: disable=unused-argument
  144. if self.currentPage() is self.select_vms_page:
  145. self.__fill_vms_list__()
  146. elif self.currentPage() is self.confirm_page:
  147. # pylint: disable=assignment-from-no-return
  148. self.vms_to_restore = self.backup_restore.get_restore_info()
  149. for i in range(self.select_vms_widget.available_list.count()):
  150. vmname = self.select_vms_widget.available_list.item(i).text()
  151. del self.vms_to_restore[str(vmname)]
  152. self.vms_to_restore = self.backup_restore.restore_info_verify(
  153. self.vms_to_restore)
  154. self.func_output = self.backup_restore.get_restore_summary(
  155. self.vms_to_restore
  156. )
  157. self.confirm_text_edit.setReadOnly(True)
  158. self.confirm_text_edit.setFontFamily("Monospace")
  159. self.confirm_text_edit.setText(self.func_output)
  160. self.confirm_page.emit(QtCore.SIGNAL("completeChanged()"))
  161. elif self.currentPage() is self.commit_page:
  162. self.button(self.FinishButton).setDisabled(True)
  163. self.showFileDialog.setEnabled(True)
  164. self.showFileDialog.setChecked(self.showFileDialog.isEnabled()
  165. and str(self.dir_line_edit.text())
  166. .count("media/") > 0)
  167. self.thread = RestoreThread(self.backup_restore,
  168. self.vms_to_restore)
  169. self.thread.finished.connect(self.thread_finished)
  170. # Start log timer
  171. timer = QtCore.QTimer(self)
  172. timer.timeout.connect(self.update_log)
  173. timer.start(1000)
  174. self.thread.start()
  175. def thread_finished(self):
  176. self.progress_bar.setMaximum(100)
  177. self.progress_bar.setValue(100)
  178. if self.thread.msg:
  179. QtGui.QMessageBox.warning(
  180. None,
  181. self.tr("Restore qubes"),
  182. self.tr(self.thread.msg))
  183. if self.thread.msg:
  184. self.append_output(self.thread.msg)
  185. if self.showFileDialog.isChecked():
  186. self.append_output(
  187. '<b><font color="black">{0}</font></b>'.format(
  188. self.tr("Please unmount your backup volume and cancel "
  189. "the file selection dialog.")))
  190. backup_utils.select_path_button_clicked(self, False, True)
  191. self.button(self.FinishButton).setEnabled(True)
  192. self.button(self.CancelButton).setEnabled(False)
  193. self.showFileDialog.setEnabled(False)
  194. def update_log(self):
  195. try:
  196. log_record = self.feedback_queue.get_nowait()
  197. while log_record:
  198. if log_record.levelno == logging.ERROR or\
  199. log_record.levelno == logging.CRITICAL:
  200. output = '<font color="red">{0}</font>'.format(
  201. log_record.getMessage())
  202. else:
  203. output = log_record.getMessage()
  204. self.append_output(output)
  205. log_record = self.feedback_queue.get_nowait()
  206. except Empty:
  207. pass
  208. def all_vms_good(self):
  209. for vm_info in self.vms_to_restore.values():
  210. if not vm_info.vm:
  211. continue
  212. if not vm_info.good_to_go:
  213. return False
  214. return True
  215. def reject(self):
  216. if self.currentPage() is self.commit_page and self.thread.isRunning():
  217. self.backup_restore.canceled = True
  218. self.append_output('<font color="red">{0}</font>'.format(
  219. self.tr("Aborting the operation...")))
  220. self.button(self.CancelButton).setDisabled(True)
  221. else:
  222. self.done(0)
  223. def has_selected_dir(self):
  224. backup_location = self.dir_line_edit.text()
  225. if not backup_location:
  226. return False
  227. if self.appvm_combobox.currentIndex() == 0:
  228. if os.path.isfile(backup_location) or \
  229. os.path.isfile(os.path.join(backup_location, 'qubes.xml')):
  230. return True
  231. else:
  232. return True
  233. return False
  234. def has_selected_vms(self):
  235. return self.select_vms_widget.selected_list.count() > 0
  236. def backup_location_changed(self, new_dir=None):
  237. # pylint: disable=unused-argument
  238. self.select_dir_page.emit(QtCore.SIGNAL("completeChanged()"))
  239. # Bases on the original code by:
  240. # Copyright (c) 2002-2007 Pascal Varet <p.varet@gmail.com>
  241. def handle_exception(exc_type, exc_value, exc_traceback):
  242. filename, line, dummy, dummy = traceback.extract_tb(exc_traceback).pop()
  243. filename = os.path.basename(filename)
  244. error = "%s: %s" % (exc_type.__name__, exc_value)
  245. QtGui.QMessageBox.critical(None, "Houston, we have a problem...",
  246. "Whoops. A critical error has occured. "
  247. "This is most likely a bug "
  248. "in Qubes Restore VMs application.<br><br>"
  249. "<b><i>%s</i></b>" % error +
  250. "at <b>line %d</b> of file <b>%s</b>.<br/><br/>"
  251. % (line, filename))
  252. def main():
  253. qt_app = QtGui.QApplication(sys.argv)
  254. qt_app.setOrganizationName("The Qubes Project")
  255. qt_app.setOrganizationDomain("http://qubes-os.org")
  256. qt_app.setApplicationName("Qubes Restore VMs")
  257. sys.excepthook = handle_exception
  258. qubes_app = Qubes()
  259. restore_window = RestoreVMsWindow(qt_app, qubes_app)
  260. restore_window.show()
  261. qt_app.exec_()
  262. qt_app.exit()
  263. if __name__ == "__main__":
  264. main()