restore.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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.dom0_restored_label.setVisible(False)
  83. self.select_vms_widget = multiselectwidget.MultiSelectWidget(self)
  84. self.select_vms_layout.insertWidget(1, self.select_vms_widget)
  85. self.connect(self,
  86. QtCore.SIGNAL("currentIdChanged(int)"),
  87. self.current_page_changed)
  88. self.dir_line_edit.connect(self.dir_line_edit,
  89. QtCore.SIGNAL("textChanged(QString)"),
  90. self.backup_location_changed)
  91. self.select_dir_page.isComplete = self.has_selected_dir
  92. self.select_vms_page.isComplete = self.has_selected_vms
  93. self.confirm_page.isComplete = self.all_vms_good
  94. # FIXME
  95. # this causes to run isComplete() twice, I don't know why
  96. self.select_vms_page.connect(
  97. self.select_vms_widget,
  98. QtCore.SIGNAL("selected_changed()"),
  99. QtCore.SIGNAL("completeChanged()"))
  100. backup_utils.fill_appvms_list(self)
  101. @QtCore.pyqtSlot(name='on_select_path_button_clicked')
  102. def select_path_button_clicked(self):
  103. backup_utils.select_path_button_clicked(self, True)
  104. def cleanupPage(self, p_int): # pylint: disable=invalid-name
  105. if self.page(p_int) is self.select_vms_page:
  106. self.vms_to_restore = None
  107. else:
  108. super(RestoreVMsWindow, self).cleanupPage(p_int)
  109. def __fill_vms_list__(self):
  110. if self.vms_to_restore is not None:
  111. return
  112. self.select_vms_widget.selected_list.clear()
  113. self.select_vms_widget.available_list.clear()
  114. self.target_appvm = None
  115. if self.appvm_combobox.currentIndex() != 0: # An existing appvm chosen
  116. self.target_appvm = self.qubes_app.domains[
  117. str(self.appvm_combobox.currentText())]
  118. try:
  119. self.backup_restore = restore.BackupRestore(
  120. self.qubes_app,
  121. self.dir_line_edit.text(),
  122. self.target_appvm,
  123. self.passphrase_line_edit.text()
  124. )
  125. if self.ignore_missing.isChecked():
  126. self.backup_restore.options.use_default_template = True
  127. self.backup_restore.options.use_default_netvm = True
  128. if self.ignore_uname_mismatch.isChecked():
  129. self.backup_restore.options.ignore_username_mismatch = True
  130. if self.verify_only.isChecked():
  131. self.backup_restore.options.verify_only = True
  132. # pylint: disable=assignment-from-no-return
  133. self.vms_to_restore = self.backup_restore.get_restore_info()
  134. for vmname in self.vms_to_restore:
  135. if vmname.startswith('$'):
  136. # Internal info
  137. continue
  138. self.select_vms_widget.available_list.addItem(vmname)
  139. except exc.QubesException as ex:
  140. QtGui.QMessageBox.warning(None, self.tr("Restore error!"), str(ex))
  141. self.restart()
  142. def append_output(self, text):
  143. self.commit_text_edit.append(text)
  144. def current_page_changed(self, page_id): # pylint: disable=unused-argument
  145. if self.currentPage() is self.select_vms_page:
  146. self.__fill_vms_list__()
  147. elif self.currentPage() is self.confirm_page:
  148. # pylint: disable=assignment-from-no-return
  149. self.vms_to_restore = self.backup_restore.get_restore_info()
  150. for i in range(self.select_vms_widget.available_list.count()):
  151. vmname = self.select_vms_widget.available_list.item(i).text()
  152. del self.vms_to_restore[str(vmname)]
  153. if 'dom0' in self.vms_to_restore.keys():
  154. self.dom0_restored_label.setVisible(True)
  155. self.vms_to_restore = self.backup_restore.restore_info_verify(
  156. self.vms_to_restore)
  157. self.func_output = self.backup_restore.get_restore_summary(
  158. self.vms_to_restore
  159. )
  160. self.confirm_text_edit.setReadOnly(True)
  161. self.confirm_text_edit.setFontFamily("Monospace")
  162. self.confirm_text_edit.setText(self.func_output)
  163. self.confirm_page.emit(QtCore.SIGNAL("completeChanged()"))
  164. elif self.currentPage() is self.commit_page:
  165. self.button(self.FinishButton).setDisabled(True)
  166. self.showFileDialog.setEnabled(True)
  167. self.showFileDialog.setChecked(self.showFileDialog.isEnabled()
  168. and str(self.dir_line_edit.text())
  169. .count("media/") > 0)
  170. self.thread = RestoreThread(self.backup_restore,
  171. self.vms_to_restore)
  172. self.thread.finished.connect(self.thread_finished)
  173. # Start log timer
  174. timer = QtCore.QTimer(self)
  175. timer.timeout.connect(self.update_log)
  176. timer.start(1000)
  177. self.thread.start()
  178. def thread_finished(self):
  179. self.progress_bar.setMaximum(100)
  180. self.progress_bar.setValue(100)
  181. if self.thread.msg:
  182. QtGui.QMessageBox.warning(
  183. None,
  184. self.tr("Restore qubes"),
  185. self.tr(self.thread.msg))
  186. if self.thread.msg:
  187. self.append_output(self.thread.msg)
  188. if self.showFileDialog.isChecked():
  189. self.append_output(
  190. '<b><font color="black">{0}</font></b>'.format(
  191. self.tr("Please unmount your backup volume and cancel "
  192. "the file selection dialog.")))
  193. backup_utils.select_path_button_clicked(self, False, True)
  194. self.button(self.FinishButton).setEnabled(True)
  195. self.button(self.CancelButton).setEnabled(False)
  196. self.showFileDialog.setEnabled(False)
  197. def update_log(self):
  198. try:
  199. log_record = self.feedback_queue.get_nowait()
  200. while log_record:
  201. if log_record.levelno == logging.ERROR or\
  202. log_record.levelno == logging.CRITICAL:
  203. output = '<font color="red">{0}</font>'.format(
  204. log_record.getMessage())
  205. else:
  206. output = log_record.getMessage()
  207. self.append_output(output)
  208. log_record = self.feedback_queue.get_nowait()
  209. except Empty:
  210. pass
  211. def all_vms_good(self):
  212. for vm_info in self.vms_to_restore.values():
  213. if not vm_info.vm:
  214. continue
  215. if not vm_info.good_to_go:
  216. return False
  217. return True
  218. def reject(self):
  219. if self.currentPage() is self.commit_page and self.thread.isRunning():
  220. self.backup_restore.canceled = True
  221. self.append_output('<font color="red">{0}</font>'.format(
  222. self.tr("Aborting the operation...")))
  223. self.button(self.CancelButton).setDisabled(True)
  224. else:
  225. self.done(0)
  226. def has_selected_dir(self):
  227. backup_location = self.dir_line_edit.text()
  228. if not backup_location:
  229. return False
  230. if self.appvm_combobox.currentIndex() == 0:
  231. if os.path.isfile(backup_location) or \
  232. os.path.isfile(os.path.join(backup_location, 'qubes.xml')):
  233. return True
  234. else:
  235. return True
  236. return False
  237. def has_selected_vms(self):
  238. return self.select_vms_widget.selected_list.count() > 0
  239. def backup_location_changed(self, new_dir=None):
  240. # pylint: disable=unused-argument
  241. self.select_dir_page.emit(QtCore.SIGNAL("completeChanged()"))
  242. # Bases on the original code by:
  243. # Copyright (c) 2002-2007 Pascal Varet <p.varet@gmail.com>
  244. def handle_exception(exc_type, exc_value, exc_traceback):
  245. filename, line, dummy, dummy = traceback.extract_tb(exc_traceback).pop()
  246. filename = os.path.basename(filename)
  247. error = "%s: %s" % (exc_type.__name__, exc_value)
  248. QtGui.QMessageBox.critical(None, "Houston, we have a problem...",
  249. "Whoops. A critical error has occured. "
  250. "This is most likely a bug "
  251. "in Qubes Restore VMs application.<br><br>"
  252. "<b><i>%s</i></b>" % error +
  253. "at <b>line %d</b> of file <b>%s</b>.<br/><br/>"
  254. % (line, filename))
  255. def main():
  256. qt_app = QtGui.QApplication(sys.argv)
  257. qt_app.setOrganizationName("The Qubes Project")
  258. qt_app.setOrganizationDomain("http://qubes-os.org")
  259. qt_app.setApplicationName("Qubes Restore VMs")
  260. sys.excepthook = handle_exception
  261. qubes_app = Qubes()
  262. restore_window = RestoreVMsWindow(qt_app, qubes_app)
  263. restore_window.show()
  264. qt_app.exec_()
  265. qt_app.exit()
  266. if __name__ == "__main__":
  267. main()