restore.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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 = '<br />'.join(err_msg)
  57. self.msg = '<b><font color="red">{0}</font></b><br />'.format(
  58. self.tr("Finished with errors!")) + self.msg
  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().__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. self.passwd_show_button.pressed.connect(self.show_password)
  93. self.passwd_show_button.released.connect(self.hide_password)
  94. def show_password(self):
  95. self.passphrase_line_edit.setEchoMode(QtWidgets.QLineEdit.Normal)
  96. self.passwd_show_button.setIcon(QtGui.QIcon(':/eye.svg'))
  97. def hide_password(self):
  98. self.passphrase_line_edit.setEchoMode(QtWidgets.QLineEdit.Password)
  99. self.passwd_show_button.setIcon(QtGui.QIcon(':/eye-off.svg'))
  100. def setup_application(self):
  101. self.qt_app.setApplicationName(self.tr("Qubes Restore VMs"))
  102. self.qt_app.setWindowIcon(QtGui.QIcon.fromTheme("qubes-manager"))
  103. @QtCore.pyqtSlot(name='on_select_path_button_clicked')
  104. def select_path_button_clicked(self):
  105. backup_utils.select_path_button_clicked(self, True)
  106. def cleanupPage(self, p_int): # pylint: disable=invalid-name
  107. if self.page(p_int) is self.select_vms_page:
  108. self.vms_to_restore = None
  109. else:
  110. super().cleanupPage(p_int)
  111. def __fill_vms_list__(self):
  112. if self.vms_to_restore is not None:
  113. return
  114. self.select_vms_widget.selected_list.clear()
  115. self.select_vms_widget.available_list.clear()
  116. self.target_appvm = None
  117. if self.appvm_combobox.currentIndex() != 0: # An existing appvm chosen
  118. self.target_appvm = self.qubes_app.domains[
  119. str(self.appvm_combobox.currentText())]
  120. try:
  121. self.backup_restore = restore.BackupRestore(
  122. self.qubes_app,
  123. self.dir_line_edit.text(),
  124. self.target_appvm,
  125. self.passphrase_line_edit.text()
  126. )
  127. if self.ignore_missing.isChecked():
  128. self.backup_restore.options.use_default_template = True
  129. self.backup_restore.options.use_default_netvm = True
  130. if self.ignore_uname_mismatch.isChecked():
  131. self.backup_restore.options.ignore_username_mismatch = True
  132. if self.verify_only.isChecked():
  133. self.backup_restore.options.verify_only = True
  134. # pylint: disable=assignment-from-no-return
  135. self.vms_to_restore = self.backup_restore.get_restore_info()
  136. for vmname in self.vms_to_restore:
  137. if vmname.startswith('$'):
  138. # Internal info
  139. continue
  140. self.select_vms_widget.available_list.addItem(vmname)
  141. except exc.QubesException as ex:
  142. QtWidgets.QMessageBox.warning(
  143. self, self.tr("Restore error!"), str(ex))
  144. self.restart()
  145. def append_output(self, text):
  146. self.commit_text_edit.append(text)
  147. def current_page_changed(self, page_id): # pylint: disable=unused-argument
  148. if self.currentPage() is self.select_vms_page:
  149. self.__fill_vms_list__()
  150. elif self.currentPage() is self.confirm_page:
  151. # pylint: disable=assignment-from-no-return
  152. self.vms_to_restore = self.backup_restore.get_restore_info()
  153. for i in range(self.select_vms_widget.available_list.count()):
  154. vmname = self.select_vms_widget.available_list.item(i).text()
  155. del self.vms_to_restore[str(vmname)]
  156. if 'dom0' in self.vms_to_restore.keys():
  157. self.dom0_restored_label.setVisible(True)
  158. self.vms_to_restore = self.backup_restore.restore_info_verify(
  159. self.vms_to_restore)
  160. self.func_output = self.backup_restore.get_restore_summary(
  161. self.vms_to_restore
  162. )
  163. self.confirm_text_edit.setReadOnly(True)
  164. self.confirm_text_edit.setFontFamily("Monospace")
  165. self.confirm_text_edit.setText(self.func_output)
  166. self.confirm_page.completeChanged.emit()
  167. elif self.currentPage() is self.commit_page:
  168. self.button(self.FinishButton).setDisabled(True)
  169. self.showFileDialog.setEnabled(True)
  170. self.showFileDialog.setChecked(self.showFileDialog.isEnabled()
  171. and str(self.dir_line_edit.text())
  172. .count("media/") > 0)
  173. self.thread = RestoreThread(self.backup_restore,
  174. self.vms_to_restore)
  175. self.thread.finished.connect(self.thread_finished)
  176. # Start log timer
  177. timer = QtCore.QTimer(self)
  178. timer.timeout.connect(self.update_log)
  179. timer.start(1000)
  180. self.thread.start()
  181. def thread_finished(self):
  182. self.progress_bar.setMaximum(100)
  183. self.progress_bar.setValue(100)
  184. if self.thread.msg:
  185. QtWidgets.QMessageBox.warning(
  186. self,
  187. self.tr("Restore qubes"),
  188. self.tr(self.thread.msg))
  189. if self.thread.msg:
  190. self.append_output(self.thread.msg)
  191. if self.showFileDialog.isChecked():
  192. self.append_output(
  193. '<b><font color="black">{0}</font></b>'.format(
  194. self.tr("Please unmount your backup volume and cancel "
  195. "the file selection dialog.")))
  196. backup_utils.select_path_button_clicked(self, False, True)
  197. self.button(self.FinishButton).setEnabled(True)
  198. self.button(self.CancelButton).setEnabled(False)
  199. self.showFileDialog.setEnabled(False)
  200. def update_log(self):
  201. try:
  202. log_record = self.feedback_queue.get_nowait()
  203. while log_record:
  204. if log_record.levelno == logging.ERROR or\
  205. log_record.levelno == logging.CRITICAL:
  206. output = '<font color="red">{0}</font>'.format(
  207. log_record.getMessage())
  208. else:
  209. output = log_record.getMessage()
  210. self.append_output(output)
  211. log_record = self.feedback_queue.get_nowait()
  212. except Empty:
  213. pass
  214. def all_vms_good(self):
  215. for vm_info in self.vms_to_restore.values():
  216. if not vm_info.vm:
  217. continue
  218. if not vm_info.good_to_go:
  219. return False
  220. return True
  221. def reject(self):
  222. if self.currentPage() is self.commit_page and self.thread.isRunning():
  223. self.backup_restore.canceled = True
  224. self.append_output('<font color="red">{0}</font>'.format(
  225. self.tr("Aborting the operation...")))
  226. self.button(self.CancelButton).setDisabled(True)
  227. else:
  228. self.done(0)
  229. def has_selected_dir(self):
  230. backup_location = self.dir_line_edit.text()
  231. if not backup_location:
  232. return False
  233. if self.appvm_combobox.currentIndex() == 0:
  234. if os.path.isfile(backup_location) or \
  235. os.path.isfile(os.path.join(backup_location, 'qubes.xml')):
  236. return True
  237. else:
  238. return True
  239. return False
  240. def has_selected_vms(self):
  241. return self.select_vms_widget.selected_list.count() > 0
  242. def backup_location_changed(self, new_dir=None):
  243. # pylint: disable=unused-argument
  244. self.select_dir_page.completeChanged.emit()
  245. def main():
  246. utils.run_synchronous(RestoreVMsWindow)
  247. if __name__ == "__main__":
  248. main()