restore.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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 General Public License
  19. # along with this program; if not, write to the Free Software
  20. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  21. #
  22. #
  23. import sys
  24. import os
  25. from PyQt4.QtCore import *
  26. from PyQt4.QtGui import *
  27. from qubes.qubes import QubesVmCollection
  28. from qubes.qubes import QubesException
  29. from qubes.qubes import QubesDaemonPidfile
  30. from qubes.qubes import QubesHost
  31. from qubes.qubes import qubes_base_dir
  32. import qubesmanager.resources_rc
  33. from pyinotify import WatchManager, Notifier, ThreadedNotifier, EventsCodes, ProcessEvent
  34. import subprocess
  35. import time
  36. from operator import itemgetter
  37. from thread_monitor import *
  38. from qubes import qubesutils
  39. from ui_restoredlg import *
  40. from multiselectwidget import *
  41. from backup_utils import *
  42. class RestoreVMsWindow(Ui_Restore, QWizard):
  43. __pyqtSignals__ = ("restore_progress(int)",)
  44. def __init__(self, app, qvm_collection, blk_manager, parent=None):
  45. super(RestoreVMsWindow, self).__init__(parent)
  46. self.app = app
  47. self.qvm_collection = qvm_collection
  48. self.blk_manager = blk_manager
  49. self.dev_mount_path = None
  50. self.backup_dir = None
  51. self.restore_options = None
  52. self.backup_vms_list = None
  53. self.func_output = []
  54. self.excluded = {}
  55. for vm in self.qvm_collection.values():
  56. if vm.qid == 0:
  57. self.vm = vm
  58. break;
  59. assert self.vm != None
  60. self.setupUi(self)
  61. self.select_vms_widget = MultiSelectWidget(self)
  62. self.select_vms_layout.insertWidget(1, self.select_vms_widget)
  63. self.connect(self, SIGNAL("currentIdChanged(int)"), self.current_page_changed)
  64. self.connect(self.dev_combobox, SIGNAL("activated(int)"), self.dev_combobox_activated)
  65. self.connect(self, SIGNAL("restore_progress(QString)"), self.commit_text_edit.append)
  66. self.select_dir_page.isComplete = self.has_selected_dir
  67. self.select_vms_page.isComplete = self.has_selected_vms
  68. #FIXME
  69. #this causes to run isComplete() twice, I don't know why
  70. self.select_vms_page.connect(self.select_vms_widget, SIGNAL("selected_changed()"), SIGNAL("completeChanged()"))
  71. fill_devs_list(self)
  72. self.__init_restore_options__()
  73. def dev_combobox_activated(self, idx):
  74. dev_combobox_activated(self, idx)
  75. @pyqtSlot(name='on_select_path_button_clicked')
  76. def select_path_button_clicked(self):
  77. select_path_button_clicked(self)
  78. def on_ignore_missing_toggled(self, checked):
  79. self.restore_options['use-default-template'] = checked
  80. self.restore_options['use-default-netvm'] = checked
  81. def on_ignore_uname_mismatch_toggled(self, checked):
  82. self.restore_options['ignore-username-mismatch'] = checked
  83. def on_skip_dom0_toggled(self, checked):
  84. self.restore_options['dom0-home'] = checked
  85. def __fill_vms_list__(self):
  86. if self.backup_vms_list != None:
  87. return
  88. self.select_vms_widget.selected_list.clear()
  89. self.select_vms_widget.available_list.clear()
  90. self.vms_to_restore = qubesutils.backup_restore_prepare(str(self.backup_dir), self.restore_options, self.qvm_collection)
  91. for vmname in self.vms_to_restore:
  92. self.select_vms_widget.available_list.addItem(vmname)
  93. def __init_restore_options__(self):
  94. if not self.restore_options:
  95. self.restore_options = {}
  96. qubesutils.backup_restore_set_defaults(self.restore_options)
  97. if 'use-default-template' in self.restore_options and 'use-default-netvm' in self.restore_options:
  98. val = self.restore_options['use-default-template'] and self.restore_options['use-default-netvm']
  99. self.ignore_missing.setChecked(val)
  100. else:
  101. self.ignore_missing.setChecked(False)
  102. if 'ignore-username-mismatch' in self.restore_options:
  103. self.ignore_uname_mismatch.setChecked(self.restore_options['ignore-username-mismatch'])
  104. if 'dom0-home' in self.restore_options:
  105. self.skip_dom0.setChecked(self.restore_options['dom0-home'])
  106. def gather_output(self, s):
  107. self.func_output.append(s)
  108. def restore_error_output(self, s):
  109. self.emit(SIGNAL("restore_progress(QString)"), '<font color="red">{0}</font>'.format(s))
  110. def restore_output(self, s):
  111. self.emit(SIGNAL("restore_progress(QString)"),'<font color="black">{0}</font>'.format(s))
  112. def __do_restore__(self, thread_monitor):
  113. err_msg = []
  114. self.qvm_collection.lock_db_for_writing()
  115. try:
  116. qubesutils.backup_restore_do(str(self.backup_dir), self.vms_to_restore, self.qvm_collection, self.restore_output, self.restore_error_output)
  117. except Exception as ex:
  118. err_msg.append(str(ex))
  119. self.qvm_collection.unlock_db()
  120. if len(err_msg) > 0 :
  121. thread_monitor.set_error_msg('\n'.join(err_msg))
  122. self.emit(SIGNAL("restore_progress(QString)"),'<b><font color="red">{0}</font></b>'.format("Finished with errors!"))
  123. else:
  124. self.emit(SIGNAL("restore_progress(QString)"),'<font color="green">{0}</font>'.format("Finished successfully!"))
  125. thread_monitor.set_finished()
  126. def current_page_changed(self, id):
  127. if self.currentPage() is self.select_vms_page:
  128. self.__fill_vms_list__()
  129. elif self.currentPage() is self.confirm_page:
  130. for v in self.excluded:
  131. self.vms_to_restore[v] = self.excluded[v]
  132. self.excluded = {}
  133. for i in range(self.select_vms_widget.available_list.count()):
  134. vmname = self.select_vms_widget.available_list.item(i).text()
  135. self.excluded[str(vmname)] = self.vms_to_restore[str(vmname)]
  136. del self.vms_to_restore[str(vmname)]
  137. del self.func_output[:]
  138. qubesutils.backup_restore_print_summary(self.vms_to_restore, print_callback = self.gather_output)
  139. self.confirm_text_edit.setReadOnly(True)
  140. self.confirm_text_edit.setFontFamily("Monospace")
  141. self.confirm_text_edit.setText("\n".join(self.func_output))
  142. elif self.currentPage() is self.commit_page:
  143. self.button(self.CancelButton).setDisabled(True)
  144. self.button(self.FinishButton).setDisabled(True)
  145. self.thread_monitor = ThreadMonitor()
  146. thread = threading.Thread (target= self.__do_restore__ , args=(self.thread_monitor,))
  147. thread.daemon = True
  148. thread.start()
  149. while not self.thread_monitor.is_finished():
  150. self.app.processEvents()
  151. time.sleep (0.1)
  152. #if not self.thread_monitor.success:
  153. #QMessageBox.warning (None, "Backup error!", "ERROR: {1}".format(self.vm.name, self.thread_monitor.error_msg))
  154. if self.dev_mount_path != None:
  155. umount_device(self.dev_mount_path)
  156. self.button(self.FinishButton).setEnabled(True)
  157. def reject(self):
  158. if self.dev_mount_path != None:
  159. umount_device(self.dev_mount_path)
  160. self.done(0)
  161. def has_selected_dir(self):
  162. return self.backup_dir != None
  163. def has_selected_vms(self):
  164. return self.select_vms_widget.selected_list.count() > 0
  165. # Bases on the original code by:
  166. # Copyright (c) 2002-2007 Pascal Varet <p.varet@gmail.com>
  167. def handle_exception( exc_type, exc_value, exc_traceback ):
  168. import sys
  169. import os.path
  170. import traceback
  171. filename, line, dummy, dummy = traceback.extract_tb( exc_traceback ).pop()
  172. filename = os.path.basename( filename )
  173. error = "%s: %s" % ( exc_type.__name__, exc_value )
  174. QMessageBox.critical(None, "Houston, we have a problem...",
  175. "Whoops. A critical error has occured. This is most likely a bug "
  176. "in Qubes Restore VMs application.<br><br>"
  177. "<b><i>%s</i></b>" % error +
  178. "at <b>line %d</b> of file <b>%s</b>.<br/><br/>"
  179. % ( line, filename ))
  180. def main():
  181. global qubes_host
  182. qubes_host = QubesHost()
  183. global app
  184. app = QApplication(sys.argv)
  185. app.setOrganizationName("The Qubes Project")
  186. app.setOrganizationDomain("http://qubes-os.org")
  187. app.setApplicationName("Qubes Restore VMs")
  188. sys.excepthook = handle_exception
  189. qvm_collection = QubesVmCollection()
  190. qvm_collection.lock_db_for_reading()
  191. qvm_collection.load()
  192. qvm_collection.unlock_db()
  193. global restore_window
  194. restore_window = RestoreVMsWindow()
  195. restore_window.show()
  196. app.exec_()
  197. app.exit()
  198. if __name__ == "__main__":
  199. main()