restore.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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. import shutil
  24. from PyQt4 import QtCore # pylint: disable=import-error
  25. from PyQt4 import QtGui # pylint: disable=import-error
  26. import threading
  27. import time
  28. import os
  29. import os.path
  30. import traceback
  31. import signal
  32. from qubes import backup
  33. from . import ui_restoredlg # pylint: disable=no-name-in-module
  34. from . import multiselectwidget
  35. from . import backup_utils
  36. from . import thread_monitor
  37. from multiprocessing import Queue, Event
  38. from multiprocessing.queues import Empty
  39. from qubesadmin import Qubes, exc
  40. from qubesadmin.backup import restore
  41. class RestoreVMsWindow(ui_restoredlg.Ui_Restore, QtGui.QWizard):
  42. __pyqtSignals__ = ("restore_progress(int)", "backup_progress(int)")
  43. def __init__(self, app, qvm_collection, parent=None):
  44. super(RestoreVMsWindow, self).__init__(parent)
  45. self.app = app
  46. self.qvm_collection = qvm_collection
  47. self.vms_to_restore = None
  48. self.func_output = []
  49. self.feedback_queue = Queue()
  50. self.canceled = False
  51. self.tmpdir_to_remove = None
  52. self.error_detected = Event()
  53. self.thread_monitor = None
  54. self.backup_restore = None
  55. self.target_appvm = None
  56. self.setupUi(self)
  57. self.select_vms_widget = multiselectwidget.MultiSelectWidget(self)
  58. self.select_vms_layout.insertWidget(1, self.select_vms_widget)
  59. self.connect(self,
  60. QtCore.SIGNAL("currentIdChanged(int)"),
  61. self.current_page_changed)
  62. self.connect(self,
  63. QtCore.SIGNAL("restore_progress(QString)"),
  64. self.commit_text_edit.append)
  65. self.connect(self,
  66. QtCore.SIGNAL("backup_progress(int)"),
  67. self.progress_bar.setValue)
  68. self.dir_line_edit.connect(self.dir_line_edit,
  69. QtCore.SIGNAL("textChanged(QString)"),
  70. self.backup_location_changed)
  71. self.connect(self.verify_only, QtCore.SIGNAL("stateChanged(int)"),
  72. self.on_verify_only_toogled)
  73. self.select_dir_page.isComplete = self.has_selected_dir
  74. self.select_vms_page.isComplete = self.has_selected_vms
  75. self.confirm_page.isComplete = self.all_vms_good
  76. # FIXME
  77. # this causes to run isComplete() twice, I don't know why
  78. self.select_vms_page.connect(
  79. self.select_vms_widget,
  80. QtCore.SIGNAL("selected_changed()"),
  81. QtCore.SIGNAL("completeChanged()"))
  82. backup_utils.fill_appvms_list(self)
  83. @QtCore.pyqtSlot(name='on_select_path_button_clicked')
  84. def select_path_button_clicked(self):
  85. backup_utils.select_path_button_clicked(self, True)
  86. def cleanupPage(self, p_int): # pylint: disable=invalid-name
  87. if self.page(p_int) is self.select_vms_page:
  88. self.vms_to_restore = None
  89. else:
  90. super(RestoreVMsWindow, self).cleanupPage(p_int)
  91. def __fill_vms_list__(self):
  92. if self.vms_to_restore is not None:
  93. return
  94. self.select_vms_widget.selected_list.clear()
  95. self.select_vms_widget.available_list.clear()
  96. self.target_appvm = None
  97. if self.appvm_combobox.currentIndex() != 0: # An existing appvm chosen
  98. self.target_appvm = self.qvm_collection.domains[
  99. str(self.appvm_combobox.currentText())]
  100. try:
  101. self.backup_restore = restore.BackupRestore(
  102. self.qvm_collection,
  103. self.dir_line_edit.text(),
  104. self.target_appvm,
  105. self.passphrase_line_edit.text()
  106. )
  107. if self.ignore_missing.isChecked():
  108. self.backup_restore.options.use_default_template = True
  109. self.backup_restore.options.use_default_netvm = True
  110. if self.ignore_uname_mismatch.isChecked():
  111. self.backup_restore.options.ignore_username_mismatch = True
  112. if self.verify_only.isChecked():
  113. self.backup_restore.options.verify_only = True
  114. self.vms_to_restore = self.backup_restore.get_restore_info()
  115. for vmname in self.vms_to_restore:
  116. if vmname.startswith('$'):
  117. # Internal info
  118. continue
  119. self.select_vms_widget.available_list.addItem(vmname)
  120. except exc.QubesException as ex:
  121. QtGui.QMessageBox.warning(None, self.tr("Restore error!"), str(ex))
  122. def restore_error_output(self, text):
  123. self.error_detected.set()
  124. self.feedback_queue.put((QtCore.SIGNAL("restore_progress(QString)"),
  125. u'<font color="red">{0}</font>'.format(text)))
  126. def restore_output(self, text):
  127. self.feedback_queue.put((
  128. QtCore.SIGNAL("restore_progress(QString)"),
  129. u'<font color="black">{0}</font>'.format(text)))
  130. def update_progress_bar(self, value):
  131. self.feedback_queue.put((QtCore.SIGNAL("backup_progress(int)"), value))
  132. def __do_restore__(self, t_monitor):
  133. err_msg = []
  134. try:
  135. self.backup_restore.progress_callback = self.update_progress_bar
  136. self.backup_restore.restore_do(self.vms_to_restore)
  137. except backup.BackupCanceledError as ex:
  138. self.canceled = True
  139. self.tmpdir_to_remove = ex.tmpdir
  140. err_msg.append(str(ex))
  141. except Exception as ex: # pylint: disable=broad-except
  142. err_msg.append(str(ex))
  143. err_msg.append(
  144. self.tr("Partially restored files left in /var/tmp/restore_*, "
  145. "investigate them and/or clean them up"))
  146. if self.canceled:
  147. self.emit(QtCore.SIGNAL("restore_progress(QString)"),
  148. '<b><font color="red">{0}</font></b>'
  149. .format(self.tr("Restore aborted!")))
  150. elif err_msg or self.error_detected.is_set():
  151. if err_msg:
  152. t_monitor.set_error_msg('\n'.join(err_msg))
  153. self.emit(QtCore.SIGNAL("restore_progress(QString)"),
  154. '<b><font color="red">{0}</font></b>'
  155. .format(self.tr("Finished with errors!")))
  156. else:
  157. self.emit(QtCore.SIGNAL("restore_progress(QString)"),
  158. '<font color="green">{0}</font>'
  159. .format(self.tr("Finished successfully!")))
  160. t_monitor.set_finished()
  161. def current_page_changed(self, page_id): # pylint: disable=unused-argument
  162. old_sigchld_handler = signal.signal(signal.SIGCHLD, signal.SIG_DFL)
  163. if self.currentPage() is self.select_vms_page:
  164. self.__fill_vms_list__()
  165. elif self.currentPage() is self.confirm_page:
  166. self.vms_to_restore = self.backup_restore.get_restore_info()
  167. for i in range(self.select_vms_widget.available_list.count()):
  168. vmname = self.select_vms_widget.available_list.item(i).text()
  169. del self.vms_to_restore[str(vmname)]
  170. self.vms_to_restore = self.backup_restore.restore_info_verify(
  171. self.vms_to_restore)
  172. self.func_output = self.backup_restore.get_restore_summary(
  173. self.vms_to_restore
  174. )
  175. self.confirm_text_edit.setReadOnly(True)
  176. self.confirm_text_edit.setFontFamily("Monospace")
  177. self.confirm_text_edit.setText(self.func_output)
  178. self.confirm_page.emit(QtCore.SIGNAL("completeChanged()"))
  179. elif self.currentPage() is self.commit_page:
  180. self.button(self.FinishButton).setDisabled(True)
  181. self.showFileDialog.setEnabled(True)
  182. self.showFileDialog.setChecked(self.showFileDialog.isEnabled()
  183. and str(self.dir_line_edit.text())
  184. .count("media/") > 0)
  185. self.thread_monitor = thread_monitor.ThreadMonitor()
  186. thread = threading.Thread(target=self.__do_restore__,
  187. args=(self.thread_monitor,))
  188. thread.daemon = True
  189. thread.start()
  190. while not self.thread_monitor.is_finished():
  191. self.app.processEvents()
  192. time.sleep(0.1)
  193. try:
  194. for (signal_to_emit, data) in iter(
  195. self.feedback_queue.get_nowait, None):
  196. self.emit(signal_to_emit, data)
  197. except Empty:
  198. pass
  199. if not self.thread_monitor.success:
  200. if self.canceled:
  201. if self.tmpdir_to_remove and \
  202. QtGui.QMessageBox.warning(
  203. None,
  204. self.tr("Restore aborted"),
  205. self.tr("Do you want to remove temporary files "
  206. "from %s?") % self.tmpdir_to_remove,
  207. QtGui.QMessageBox.Yes,
  208. QtGui.QMessageBox.No) == QtGui.QMessageBox.Yes:
  209. shutil.rmtree(self.tmpdir_to_remove)
  210. else:
  211. QtGui.QMessageBox.warning(
  212. None,
  213. self.tr("Backup error!"),
  214. self.tr("ERROR: {0}").format(
  215. self.thread_monitor.error_msg))
  216. if self.showFileDialog.isChecked(): # TODO: this is not working
  217. self.emit(QtCore.SIGNAL("restore_progress(QString)"),
  218. '<b><font color="black">{0}</font></b>'.format(
  219. self.tr(
  220. "Please unmount your backup volume and cancel"
  221. " the file selection dialog.")))
  222. if self.target_appvm: # TODO does this work at all?
  223. self.target_appvm.run("QUBESRPC %s dom0" %
  224. "qubes.SelectDirectory")
  225. else:
  226. file_dialog = QtGui.QFileDialog()
  227. file_dialog.setReadOnly(True)
  228. file_dialog.getExistingDirectory(
  229. self, self.tr("Detach backup device"),
  230. os.path.dirname(self.dir_line_edit.text()))
  231. self.progress_bar.setValue(100)
  232. self.button(self.FinishButton).setEnabled(True)
  233. self.button(self.CancelButton).setEnabled(False)
  234. self.showFileDialog.setEnabled(False)
  235. signal.signal(signal.SIGCHLD, old_sigchld_handler)
  236. def all_vms_good(self):
  237. for vm_info in self.vms_to_restore.values():
  238. if not vm_info.vm:
  239. continue
  240. if not vm_info.good_to_go:
  241. return False
  242. return True
  243. def reject(self): # TODO: probably not working too
  244. if self.currentPage() is self.commit_page:
  245. if self.backup_restore.canceled:
  246. self.emit(QtCore.SIGNAL("restore_progress(QString)"),
  247. '<font color="red">{0}</font>'
  248. .format(self.tr("Aborting the operation...")))
  249. self.button(self.CancelButton).setDisabled(True)
  250. else:
  251. self.done(0)
  252. def has_selected_dir(self):
  253. backup_location = self.dir_line_edit.text()
  254. if not backup_location:
  255. return False
  256. if self.appvm_combobox.currentIndex() == 0:
  257. if os.path.isfile(backup_location) or \
  258. os.path.isfile(os.path.join(backup_location, 'qubes.xml')):
  259. return True
  260. else:
  261. return True
  262. return False
  263. def has_selected_vms(self):
  264. return self.select_vms_widget.selected_list.count() > 0
  265. def backup_location_changed(self, new_dir=None):
  266. # pylint: disable=unused-argument
  267. self.select_dir_page.emit(QtCore.SIGNAL("completeChanged()"))
  268. # Bases on the original code by:
  269. # Copyright (c) 2002-2007 Pascal Varet <p.varet@gmail.com>
  270. def handle_exception(exc_type, exc_value, exc_traceback):
  271. filename, line, dummy, dummy = traceback.extract_tb(exc_traceback).pop()
  272. filename = os.path.basename(filename)
  273. error = "%s: %s" % (exc_type.__name__, exc_value)
  274. QtGui.QMessageBox.critical(None, "Houston, we have a problem...",
  275. "Whoops. A critical error has occured. "
  276. "This is most likely a bug "
  277. "in Qubes Restore VMs application.<br><br>"
  278. "<b><i>%s</i></b>" % error +
  279. "at <b>line %d</b> of file <b>%s</b>.<br/><br/>"
  280. % (line, filename))
  281. def main():
  282. qtapp = QtGui.QApplication(sys.argv)
  283. qtapp.setOrganizationName("The Qubes Project")
  284. qtapp.setOrganizationDomain("http://qubes-os.org")
  285. qtapp.setApplicationName("Qubes Restore VMs")
  286. sys.excepthook = handle_exception
  287. app = Qubes()
  288. restore_window = RestoreVMsWindow(qtapp, app)
  289. restore_window.show()
  290. qtapp.exec_()
  291. qtapp.exit()
  292. if __name__ == "__main__":
  293. main()