restore.py 15 KB

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