restore.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. #!/usr/bin/python2
  2. # pylint: skip-file
  3. #
  4. # The Qubes OS Project, http://www.qubes-os.org
  5. #
  6. # Copyright (C) 2012 Agnieszka Kostrzewa <agnieszka.kostrzewa@gmail.com>
  7. # Copyright (C) 2012 Marek Marczykowski <marmarek@mimuw.edu.pl>
  8. #
  9. # This program is free software; you can redistribute it and/or
  10. # modify it under the terms of the GNU General Public License
  11. # as published by the Free Software Foundation; either version 2
  12. # of the License, or (at your option) any later version.
  13. #
  14. # This program is distributed in the hope that it will be useful,
  15. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. # GNU General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU Lesser General Public License along
  20. # with this program; if not, see <http://www.gnu.org/licenses/>.
  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. self.dir_line_edit.text(),
  107. 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, self.tr("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(str(ex))
  154. except Exception as ex:
  155. print ("Exception:", ex)
  156. err_msg.append(str(ex))
  157. err_msg.append(
  158. self.tr("Partially restored files left in "
  159. "/var/tmp/restore_*, investigate them and/or clean them up"))
  160. self.qvm_collection.unlock_db()
  161. if self.canceled:
  162. self.emit(SIGNAL("restore_progress(QString)"),
  163. '<b><font color="red">{0}</font></b>'
  164. .format(self.tr("Restore aborted!")))
  165. elif len(err_msg) > 0 or self.error_detected.is_set():
  166. if len(err_msg) > 0:
  167. thread_monitor.set_error_msg('\n'.join(err_msg))
  168. self.emit(SIGNAL("restore_progress(QString)"),
  169. '<b><font color="red">{0}</font></b>'
  170. .format(self.tr("Finished with errors!")))
  171. else:
  172. self.emit(SIGNAL("restore_progress(QString)"),
  173. '<font color="green">{0}</font>'
  174. .format(self.tr("Finished successfully!")))
  175. thread_monitor.set_finished()
  176. def current_page_changed(self, id):
  177. old_sigchld_handler = signal.signal(signal.SIGCHLD, signal.SIG_DFL)
  178. if self.currentPage() is self.select_vms_page:
  179. self.__fill_vms_list__()
  180. elif self.currentPage() is self.confirm_page:
  181. for v in self.excluded:
  182. self.vms_to_restore[v] = self.excluded[v]
  183. self.excluded = {}
  184. for i in range(self.select_vms_widget.available_list.count()):
  185. vmname = self.select_vms_widget.available_list.item(i).text()
  186. self.excluded[str(vmname)] = self.vms_to_restore[str(vmname)]
  187. del self.vms_to_restore[str(vmname)]
  188. del self.func_output[:]
  189. self.vms_to_restore = backup.restore_info_verify(self.vms_to_restore,
  190. self.qvm_collection)
  191. backup.backup_restore_print_summary(
  192. self.vms_to_restore, print_callback = self.gather_output)
  193. self.confirm_text_edit.setReadOnly(True)
  194. self.confirm_text_edit.setFontFamily("Monospace")
  195. self.confirm_text_edit.setText("\n".join(self.func_output))
  196. self.confirm_page.emit(SIGNAL("completeChanged()"))
  197. elif self.currentPage() is self.commit_page:
  198. self.button(self.FinishButton).setDisabled(True)
  199. self.showFileDialog.setEnabled(True)
  200. self.showFileDialog.setChecked(self.showFileDialog.isEnabled()
  201. and str(self.dir_line_edit.text())
  202. .count("media/") > 0)
  203. self.thread_monitor = ThreadMonitor()
  204. thread = threading.Thread (target= self.__do_restore__ , args=(self.thread_monitor,))
  205. thread.daemon = True
  206. thread.start()
  207. while not self.thread_monitor.is_finished():
  208. self.app.processEvents()
  209. time.sleep (0.1)
  210. try:
  211. for (signal_to_emit,data) in iter(self.feedback_queue.get_nowait,None):
  212. self.emit(signal_to_emit,data)
  213. except Empty:
  214. pass
  215. if not self.thread_monitor.success:
  216. if self.canceled:
  217. if self.tmpdir_to_remove and \
  218. QMessageBox.warning(None, self.tr("Restore aborted"),
  219. self.tr("Do you want to remove temporary files "
  220. "from %s?") % self.tmpdir_to_remove,
  221. QMessageBox.Yes, QMessageBox.No) == \
  222. QMessageBox.Yes:
  223. shutil.rmtree(self.tmpdir_to_remove)
  224. else:
  225. QMessageBox.warning(None,
  226. self.tr("Backup error!"), self.tr("ERROR: {0}")
  227. .format(self.thread_monitor.error_msg))
  228. if self.showFileDialog.isChecked():
  229. self.emit(SIGNAL("restore_progress(QString)"),
  230. '<b><font color="black">{0}</font></b>'.format(
  231. self.tr(
  232. "Please unmount your backup volume and cancel"
  233. " the file selection dialog.")))
  234. if self.target_appvm:
  235. self.target_appvm.run("QUBESRPC %s dom0" %
  236. "qubes.SelectDirectory")
  237. else:
  238. file_dialog = QFileDialog()
  239. file_dialog.setReadOnly(True)
  240. file_dialog.getExistingDirectory(
  241. self, self.tr("Detach backup device"),
  242. os.path.dirname(self.dir_line_edit.text()))
  243. self.progress_bar.setValue(100)
  244. self.button(self.FinishButton).setEnabled(True)
  245. self.button(self.CancelButton).setEnabled(False)
  246. self.showFileDialog.setEnabled(False)
  247. signal.signal(signal.SIGCHLD, old_sigchld_handler)
  248. def all_vms_good(self):
  249. for vminfo in self.vms_to_restore.values():
  250. if not vminfo.has_key('vm'):
  251. continue
  252. if not vminfo['good-to-go']:
  253. return False
  254. return True
  255. def reject(self):
  256. if self.currentPage() is self.commit_page:
  257. if backup.backup_cancel():
  258. self.emit(SIGNAL("restore_progress(QString)"),
  259. '<font color="red">{0}</font>'
  260. .format(self.tr("Aborting the operation...")))
  261. self.button(self.CancelButton).setDisabled(True)
  262. else:
  263. self.done(0)
  264. def has_selected_dir(self):
  265. backup_location = self.dir_line_edit.text()
  266. if not backup_location:
  267. return False
  268. if self.appvm_combobox.currentIndex() == 0:
  269. if os.path.isfile(backup_location) or \
  270. os.path.isfile(os.path.join(backup_location, 'qubes.xml')):
  271. return True
  272. else:
  273. return True
  274. return False
  275. def has_selected_vms(self):
  276. return self.select_vms_widget.selected_list.count() > 0
  277. def backup_location_changed(self, new_dir = None):
  278. self.select_dir_page.emit(SIGNAL("completeChanged()"))
  279. # Bases on the original code by:
  280. # Copyright (c) 2002-2007 Pascal Varet <p.varet@gmail.com>
  281. def handle_exception( exc_type, exc_value, exc_traceback ):
  282. import sys
  283. import os.path
  284. import traceback
  285. filename, line, dummy, dummy = traceback.extract_tb( exc_traceback ).pop()
  286. filename = os.path.basename( filename )
  287. error = "%s: %s" % ( exc_type.__name__, exc_value )
  288. QMessageBox.critical(None, "Houston, we have a problem...",
  289. "Whoops. A critical error has occured. This is most likely a bug "
  290. "in Qubes Restore VMs application.<br><br>"
  291. "<b><i>%s</i></b>" % error +
  292. "at <b>line %d</b> of file <b>%s</b>.<br/><br/>"
  293. % ( line, filename ))
  294. def main():
  295. global qubes_host
  296. qubes_host = QubesHost()
  297. global app
  298. app = QApplication(sys.argv)
  299. app.setOrganizationName("The Qubes Project")
  300. app.setOrganizationDomain("http://qubes-os.org")
  301. app.setApplicationName("Qubes Restore VMs")
  302. sys.excepthook = handle_exception
  303. qvm_collection = QubesVmCollection()
  304. qvm_collection.lock_db_for_reading()
  305. qvm_collection.load()
  306. qvm_collection.unlock_db()
  307. global restore_window
  308. restore_window = RestoreVMsWindow()
  309. restore_window.show()
  310. app.exec_()
  311. app.exit()
  312. if __name__ == "__main__":
  313. main()