restore.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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 <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. from PyQt5 import QtCore, QtWidgets, QtGui # pylint: disable=import-error
  23. import os
  24. import os.path
  25. import logging
  26. import logging.handlers
  27. from . import ui_restoredlg # pylint: disable=no-name-in-module
  28. from . import multiselectwidget
  29. from . import backup_utils
  30. from . import utils
  31. from multiprocessing import Queue
  32. from queue import Empty
  33. from qubesadmin import exc
  34. from qubesadmin.backup import restore
  35. # pylint: disable=too-few-public-methods
  36. class RestoreThread(QtCore.QThread):
  37. def __init__(self, backup_restore, vms_to_restore):
  38. QtCore.QThread.__init__(self)
  39. self.backup_restore = backup_restore
  40. self.vms_to_restore = vms_to_restore
  41. self.msg = None
  42. self.canceled = None
  43. def run(self):
  44. err_msg = []
  45. try:
  46. self.backup_restore.restore_do(self.vms_to_restore)
  47. except exc.BackupCancelledError as ex:
  48. self.canceled = True
  49. err_msg.append(str(ex))
  50. except Exception as ex: # pylint: disable=broad-except
  51. err_msg.append(str(ex))
  52. err_msg.append(
  53. self.tr("Partially restored files left in /var/tmp/restore_*, "
  54. "investigate them and/or clean them up"))
  55. if err_msg:
  56. self.msg = '\n'.join(err_msg)
  57. self.msg = '<b><font color="red">{0}</font></b>'.format(
  58. self.tr("Finished with errors!"))
  59. else:
  60. self.msg = '<font color="green">{0}</font>'.format(
  61. self.tr("Finished successfully!"))
  62. class RestoreVMsWindow(ui_restoredlg.Ui_Restore, QtWidgets.QWizard):
  63. def __init__(self, qt_app, qubes_app, parent=None):
  64. super(RestoreVMsWindow, self).__init__(parent)
  65. self.qt_app = qt_app
  66. self.qubes_app = qubes_app
  67. self.vms_to_restore = None
  68. self.func_output = []
  69. self.thread = None
  70. # Set up logging
  71. self.feedback_queue = Queue()
  72. handler = logging.handlers.QueueHandler(self.feedback_queue)
  73. logger = logging.getLogger('qubesadmin.backup')
  74. logger.addHandler(handler)
  75. logger.setLevel(logging.INFO)
  76. self.backup_restore = None
  77. self.target_appvm = None
  78. self.setupUi(self)
  79. self.dom0_restored_label.setVisible(False)
  80. self.select_vms_widget = multiselectwidget.MultiSelectWidget(self)
  81. self.select_vms_layout.insertWidget(1, self.select_vms_widget)
  82. self.currentIdChanged.connect(self.current_page_changed)
  83. self.dir_line_edit.textChanged.connect(self.backup_location_changed)
  84. self.select_dir_page.isComplete = self.has_selected_dir
  85. self.select_vms_page.isComplete = self.has_selected_vms
  86. self.confirm_page.isComplete = self.all_vms_good
  87. # FIXME
  88. # this causes to run isComplete() twice, I don't know why
  89. self.select_vms_widget.selectedChanged.connect(
  90. self.select_vms_page.completeChanged.emit)
  91. backup_utils.fill_appvms_list(self)
  92. def setup_application(self):
  93. self.qt_app.setApplicationName(self.tr("Qubes Restore VMs"))
  94. self.qt_app.setWindowIcon(QtGui.QIcon.fromTheme("qubes-manager"))
  95. @QtCore.pyqtSlot(name='on_select_path_button_clicked')
  96. def select_path_button_clicked(self):
  97. backup_utils.select_path_button_clicked(self, True)
  98. def cleanupPage(self, p_int): # pylint: disable=invalid-name
  99. if self.page(p_int) is self.select_vms_page:
  100. self.vms_to_restore = None
  101. else:
  102. super(RestoreVMsWindow, self).cleanupPage(p_int)
  103. def __fill_vms_list__(self):
  104. if self.vms_to_restore is not None:
  105. return
  106. self.select_vms_widget.selected_list.clear()
  107. self.select_vms_widget.available_list.clear()
  108. self.target_appvm = None
  109. if self.appvm_combobox.currentIndex() != 0: # An existing appvm chosen
  110. self.target_appvm = self.qubes_app.domains[
  111. str(self.appvm_combobox.currentText())]
  112. try:
  113. self.backup_restore = restore.BackupRestore(
  114. self.qubes_app,
  115. self.dir_line_edit.text(),
  116. self.target_appvm,
  117. self.passphrase_line_edit.text()
  118. )
  119. if self.ignore_missing.isChecked():
  120. self.backup_restore.options.use_default_template = True
  121. self.backup_restore.options.use_default_netvm = True
  122. if self.ignore_uname_mismatch.isChecked():
  123. self.backup_restore.options.ignore_username_mismatch = True
  124. if self.verify_only.isChecked():
  125. self.backup_restore.options.verify_only = True
  126. # pylint: disable=assignment-from-no-return
  127. self.vms_to_restore = self.backup_restore.get_restore_info()
  128. for vmname in self.vms_to_restore:
  129. if vmname.startswith('$'):
  130. # Internal info
  131. continue
  132. self.select_vms_widget.available_list.addItem(vmname)
  133. except exc.QubesException as ex:
  134. QtWidgets.QMessageBox.warning(
  135. self, self.tr("Restore error!"), str(ex))
  136. self.restart()
  137. def append_output(self, text):
  138. self.commit_text_edit.append(text)
  139. def current_page_changed(self, page_id): # pylint: disable=unused-argument
  140. if self.currentPage() is self.select_vms_page:
  141. self.__fill_vms_list__()
  142. elif self.currentPage() is self.confirm_page:
  143. # pylint: disable=assignment-from-no-return
  144. self.vms_to_restore = self.backup_restore.get_restore_info()
  145. for i in range(self.select_vms_widget.available_list.count()):
  146. vmname = self.select_vms_widget.available_list.item(i).text()
  147. del self.vms_to_restore[str(vmname)]
  148. if 'dom0' in self.vms_to_restore.keys():
  149. self.dom0_restored_label.setVisible(True)
  150. self.vms_to_restore = self.backup_restore.restore_info_verify(
  151. self.vms_to_restore)
  152. self.func_output = self.backup_restore.get_restore_summary(
  153. self.vms_to_restore
  154. )
  155. self.confirm_text_edit.setReadOnly(True)
  156. self.confirm_text_edit.setFontFamily("Monospace")
  157. self.confirm_text_edit.setText(self.func_output)
  158. self.confirm_page.completeChanged.emit()
  159. elif self.currentPage() is self.commit_page:
  160. self.button(self.FinishButton).setDisabled(True)
  161. self.showFileDialog.setEnabled(True)
  162. self.showFileDialog.setChecked(self.showFileDialog.isEnabled()
  163. and str(self.dir_line_edit.text())
  164. .count("media/") > 0)
  165. self.thread = RestoreThread(self.backup_restore,
  166. self.vms_to_restore)
  167. self.thread.finished.connect(self.thread_finished)
  168. # Start log timer
  169. timer = QtCore.QTimer(self)
  170. timer.timeout.connect(self.update_log)
  171. timer.start(1000)
  172. self.thread.start()
  173. def thread_finished(self):
  174. self.progress_bar.setMaximum(100)
  175. self.progress_bar.setValue(100)
  176. if self.thread.msg:
  177. QtWidgets.QMessageBox.warning(
  178. self,
  179. self.tr("Restore qubes"),
  180. self.tr(self.thread.msg))
  181. if self.thread.msg:
  182. self.append_output(self.thread.msg)
  183. if self.showFileDialog.isChecked():
  184. self.append_output(
  185. '<b><font color="black">{0}</font></b>'.format(
  186. self.tr("Please unmount your backup volume and cancel "
  187. "the file selection dialog.")))
  188. backup_utils.select_path_button_clicked(self, False, True)
  189. self.button(self.FinishButton).setEnabled(True)
  190. self.button(self.CancelButton).setEnabled(False)
  191. self.showFileDialog.setEnabled(False)
  192. def update_log(self):
  193. try:
  194. log_record = self.feedback_queue.get_nowait()
  195. while log_record:
  196. if log_record.levelno == logging.ERROR or\
  197. log_record.levelno == logging.CRITICAL:
  198. output = '<font color="red">{0}</font>'.format(
  199. log_record.getMessage())
  200. else:
  201. output = log_record.getMessage()
  202. self.append_output(output)
  203. log_record = self.feedback_queue.get_nowait()
  204. except Empty:
  205. pass
  206. def all_vms_good(self):
  207. for vm_info in self.vms_to_restore.values():
  208. if not vm_info.vm:
  209. continue
  210. if not vm_info.good_to_go:
  211. return False
  212. return True
  213. def reject(self):
  214. if self.currentPage() is self.commit_page and self.thread.isRunning():
  215. self.backup_restore.canceled = True
  216. self.append_output('<font color="red">{0}</font>'.format(
  217. self.tr("Aborting the operation...")))
  218. self.button(self.CancelButton).setDisabled(True)
  219. else:
  220. self.done(0)
  221. def has_selected_dir(self):
  222. backup_location = self.dir_line_edit.text()
  223. if not backup_location:
  224. return False
  225. if self.appvm_combobox.currentIndex() == 0:
  226. if os.path.isfile(backup_location) or \
  227. os.path.isfile(os.path.join(backup_location, 'qubes.xml')):
  228. return True
  229. else:
  230. return True
  231. return False
  232. def has_selected_vms(self):
  233. return self.select_vms_widget.selected_list.count() > 0
  234. def backup_location_changed(self, new_dir=None):
  235. # pylint: disable=unused-argument
  236. self.select_dir_page.completeChanged.emit()
  237. def main():
  238. utils.run_synchronous(RestoreVMsWindow)
  239. if __name__ == "__main__":
  240. main()