backup.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. #!/usr/bin/python3
  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 traceback
  24. import signal
  25. import shutil
  26. from qubesadmin import Qubes, events, exc
  27. from qubesadmin import utils as admin_utils
  28. from qubes.storage.file import get_disk_usage
  29. from PyQt4 import QtCore # pylint: disable=import-error
  30. from PyQt4 import QtGui # pylint: disable=import-error
  31. from . import ui_backupdlg
  32. from . import multiselectwidget
  33. from . import backup_utils
  34. from . import utils
  35. import grp
  36. import pwd
  37. import sys
  38. import os
  39. from . import thread_monitor
  40. import threading
  41. import time
  42. class BackupVMsWindow(ui_backupdlg.Ui_Backup, multiselectwidget.QtGui.QWizard):
  43. __pyqtSignals__ = ("backup_progress(int)",)
  44. def __init__(self, app, qvm_collection, parent=None):
  45. super(BackupVMsWindow, self).__init__(parent)
  46. self.app = app
  47. self.qvm_collection = qvm_collection
  48. self.backup_settings = QtCore.QSettings()
  49. self.func_output = []
  50. self.selected_vms = []
  51. self.tmpdir_to_remove = None
  52. self.canceled = False
  53. self.files_to_backup = None
  54. self.setupUi(self)
  55. self.progress_status.text = self.tr("Backup in progress...")
  56. self.dir_line_edit.setReadOnly(False)
  57. self.select_vms_widget = multiselectwidget.MultiSelectWidget(self)
  58. self.verticalLayout.insertWidget(1, self.select_vms_widget)
  59. self.connect(self, QtCore.SIGNAL("currentIdChanged(int)"),
  60. self.current_page_changed)
  61. self.connect(self.select_vms_widget,
  62. QtCore.SIGNAL("items_removed(PyQt_PyObject)"),
  63. self.vms_removed)
  64. self.connect(self.select_vms_widget,
  65. QtCore.SIGNAL("items_added(PyQt_PyObject)"),
  66. self.vms_added)
  67. self.connect(self, QtCore.SIGNAL("backup_progress(int)"),
  68. self.progress_bar.setValue)
  69. self.dir_line_edit.connect(self.dir_line_edit,
  70. QtCore.SIGNAL("textChanged(QString)"),
  71. self.backup_location_changed)
  72. self.select_vms_page.isComplete = self.has_selected_vms
  73. self.select_dir_page.isComplete = self.has_selected_dir_and_pass
  74. # FIXME
  75. # this causes to run isComplete() twice, I don't know why
  76. self.select_vms_page.connect(
  77. self.select_vms_widget,
  78. QtCore.SIGNAL("selected_changed()"),
  79. QtCore.SIGNAL("completeChanged()"))
  80. self.passphrase_line_edit.connect(
  81. self.passphrase_line_edit,
  82. QtCore.SIGNAL("textChanged(QString)"),
  83. self.backup_location_changed)
  84. self.passphrase_line_edit_verify.connect(
  85. self.passphrase_line_edit_verify,
  86. QtCore.SIGNAL("textChanged(QString)"),
  87. self.backup_location_changed)
  88. self.total_size = 0
  89. # TODO: is the is_running criterion really necessary? It's designed to
  90. # avoid backuping a VM into itself or surprising the user with starting
  91. # a VM when they didn't plan to.
  92. # TODO: inform the user only running VMs are listed?
  93. self.target_vm_list, self.target_vm_idx = utils.prepare_vm_choice(
  94. self.appvm_combobox,
  95. self.qvm_collection,
  96. None,
  97. self.qvm_collection.domains['dom0'],
  98. (lambda vm: vm.klass != 'TemplateVM' and vm.is_running()),
  99. allow_internal=False,
  100. allow_default=False,
  101. allow_none=False
  102. )
  103. selected = self.load_settings()
  104. self.__fill_vms_list__(selected)
  105. def load_settings(self):
  106. try:
  107. profile_data = backup_utils.load_backup_profile()
  108. except Exception as ex: # TODO: fix just for file not found
  109. return
  110. if not profile_data:
  111. return
  112. if 'destination_vm' in profile_data:
  113. dest_vm_name = profile_data['destination_vm']
  114. dest_vm_idx = self.appvm_combobox.findText(dest_vm_name)
  115. if dest_vm_idx > -1:
  116. self.appvm_combobox.setCurrentIndex(dest_vm_idx)
  117. if 'destination_path' in profile_data:
  118. dest_path = profile_data['destination_path']
  119. self.dir_line_edit.setText(dest_path)
  120. if 'passphrase_text' in profile_data:
  121. self.passphrase_line_edit.setText(profile_data['passphrase_text'])
  122. self.passphrase_line_edit_verify.setText(
  123. profile_data['passphrase_text'])
  124. # TODO: make a checkbox for saving the profile
  125. # TODO: warn that unknown data will be overwritten
  126. if 'include' in profile_data:
  127. return profile_data['include']
  128. return None
  129. def save_settings(self):
  130. settings = {'destination_vm': self.appvm_combobox.currentText(),
  131. 'destination_path': self.dir_line_edit.text(),
  132. 'include': [vm.name for vm in self.selected_vms],
  133. 'passphrase_text': self.passphrase_line_edit.text()}
  134. # TODO: add compression when it is added
  135. backup_utils.write_backup_profile(settings)
  136. class VmListItem(QtGui.QListWidgetItem):
  137. def __init__(self, vm):
  138. self.vm = vm
  139. if vm.qid == 0:
  140. local_user = grp.getgrnam('qubes').gr_mem[0]
  141. home_dir = pwd.getpwnam(local_user).pw_dir
  142. self.size = get_disk_usage(home_dir)
  143. else:
  144. self.size = vm.get_disk_utilization()
  145. super(BackupVMsWindow.VmListItem, self).__init__(
  146. vm.name + " (" + admin_utils.size_to_human(self.size) + ")")
  147. def __fill_vms_list__(self, selected=None):
  148. for vm in self.qvm_collection.domains:
  149. if vm.features.get('internal', False):
  150. continue
  151. item = BackupVMsWindow.VmListItem(vm)
  152. if (selected is None and
  153. getattr(vm, 'include_in_backups', True)) \
  154. or (selected and vm.name in selected):
  155. self.select_vms_widget.selected_list.addItem(item)
  156. self.total_size += item.size
  157. else:
  158. self.select_vms_widget.available_list.addItem(item)
  159. self.select_vms_widget.available_list.sortItems()
  160. self.select_vms_widget.selected_list.sortItems()
  161. self.unrecognized_config_label.setVisible(
  162. selected is not None and
  163. len(selected) != len(self.select_vms_widget.selected_list))
  164. self.total_size_label.setText(
  165. admin_utils.size_to_human(self.total_size))
  166. def vms_added(self, items):
  167. for i in items:
  168. self.total_size += i.size
  169. self.total_size_label.setText(
  170. admin_utils.size_to_human(self.total_size))
  171. def vms_removed(self, items):
  172. for i in items:
  173. self.total_size -= i.size
  174. self.total_size_label.setText(
  175. admin_utils.size_to_human(self.total_size))
  176. @QtCore.pyqtSlot(name='on_select_path_button_clicked')
  177. def select_path_button_clicked(self):
  178. backup_utils.select_path_button_clicked(self)
  179. def validateCurrentPage(self):
  180. if self.currentPage() is self.select_vms_page:
  181. self.selected_vms = []
  182. for i in range(self.select_vms_widget.selected_list.count()):
  183. self.selected_vms.append(
  184. self.select_vms_widget.selected_list.item(i).vm)
  185. elif self.currentPage() is self.select_dir_page:
  186. backup_location = str(self.dir_line_edit.text())
  187. if not backup_location:
  188. QtGui.QMessageBox.information(
  189. None, self.tr("Wait!"),
  190. self.tr("Enter backup target location first."))
  191. return False
  192. if self.appvm_combobox.currentIndex() == 0 \
  193. and not os.path.isdir(backup_location):
  194. QtGui.QMessageBox.information(
  195. None, self.tr("Wait!"),
  196. self.tr("Selected directory do not exists or "
  197. "not a directory (%s).") % backup_location)
  198. return False
  199. if not len(self.passphrase_line_edit.text()):
  200. QtGui.QMessageBox.information(
  201. None, self.tr("Wait!"),
  202. self.tr("Enter passphrase for backup "
  203. "encryption/verification first."))
  204. return False
  205. if self.passphrase_line_edit.text() !=\
  206. self.passphrase_line_edit_verify.text():
  207. QtGui.QMessageBox.information(
  208. None, self.tr("Wait!"),
  209. self.tr("Enter the same passphrase in both fields."))
  210. return False
  211. return True
  212. # def gather_output(self, s):
  213. # self.func_output.append(s)
  214. def update_progress_bar(self, value):
  215. self.emit(QtCore.SIGNAL("backup_progress(int)"), value)
  216. def __do_backup__(self, thread_monitor):
  217. msg = []
  218. try:
  219. # TODO: this does nothing, events are not handled
  220. events_dispatcher = events.EventsDispatcher(self.app)
  221. events_dispatcher.add_handler('backup-progress',
  222. self.update_progress_bar)
  223. try:
  224. vm = self.qvm_collection.domains[
  225. self.appvm_combobox.currentText()]
  226. if not vm.is_running():
  227. vm.start()
  228. self.qvm_collection.qubesd_call('dom0',
  229. 'admin.backup.Execute',
  230. 'qubes-manager-backup')
  231. except exc.QubesException as err:
  232. # TODO fixme
  233. print('\nBackup error: {}'.format(err), file=sys.stderr)
  234. return 1
  235. except Exception as ex: # TODO: fixme
  236. print("Exception:", ex)
  237. msg.append(str(ex))
  238. if len(msg) > 0:
  239. thread_monitor.set_error_msg('\n'.join(msg))
  240. thread_monitor.set_finished()
  241. def current_page_changed(self, id):
  242. old_sigchld_handler = signal.signal(signal.SIGCHLD, signal.SIG_DFL)
  243. if self.currentPage() is self.confirm_page:
  244. self.save_settings()
  245. backup_summary = self.qvm_collection.qubesd_call(
  246. 'dom0', 'admin.backup.Info', 'qubes-manager-backup')
  247. self.textEdit.setReadOnly(True)
  248. self.textEdit.setFontFamily("Monospace")
  249. self.textEdit.setText(backup_summary.decode())
  250. elif self.currentPage() is self.commit_page:
  251. self.button(self.FinishButton).setDisabled(True)
  252. self.showFileDialog.setEnabled(
  253. self.appvm_combobox.currentIndex() != 0)
  254. self.showFileDialog.setChecked(self.showFileDialog.isEnabled()
  255. and str(self.dir_line_edit.text())
  256. .count("media/") > 0)
  257. self.thread_monitor = thread_monitor.ThreadMonitor()
  258. thread = threading.Thread(
  259. target=self.__do_backup__,
  260. args=(self.thread_monitor,))
  261. thread.daemon = True
  262. thread.start()
  263. while not self.thread_monitor.is_finished():
  264. self.app.processEvents()
  265. time.sleep(0.1)
  266. if not self.thread_monitor.success:
  267. if self.canceled:
  268. self.progress_status.setText(self.tr("Backup aborted."))
  269. if self.tmpdir_to_remove:
  270. if QtGui.QMessageBox.warning(
  271. None, self.tr("Backup aborted"),
  272. self.tr(
  273. "Do you want to remove temporary files "
  274. "from %s?") % self.tmpdir_to_remove,
  275. QtGui.QMessageBox.Yes,
  276. QtGui.QMessageBox.No) == QtGui.QMessageBox.Yes:
  277. shutil.rmtree(self.tmpdir_to_remove)
  278. else:
  279. self.progress_status.setText(self.tr("Backup error."))
  280. QtGui.QMessageBox.warning(
  281. self, self.tr("Backup error!"),
  282. self.tr("ERROR: {}").format(
  283. self.thread_monitor.error_msg))
  284. else:
  285. self.progress_bar.setValue(100)
  286. self.progress_status.setText(self.tr("Backup finished."))
  287. if self.showFileDialog.isChecked():
  288. orig_text = self.progress_status.text
  289. self.progress_status.setText(
  290. orig_text + self.tr(
  291. " Please unmount your backup volume and cancel "
  292. "the file selection dialog."))
  293. if self.target_appvm: # FIXME I'm not sure if this works
  294. self.target_appvm.run(
  295. "QUBESRPC %s dom0" % "qubes.SelectDirectory")
  296. self.button(self.CancelButton).setEnabled(False)
  297. self.button(self.FinishButton).setEnabled(True)
  298. self.showFileDialog.setEnabled(False)
  299. signal.signal(signal.SIGCHLD, old_sigchld_handler)
  300. def reject(self):
  301. # cancell clicked while the backup is in progress.
  302. # calling kill on tar.
  303. if self.currentPage() is self.commit_page:
  304. pass # TODO: this does nothing
  305. # if backup.backup_cancel():
  306. # self.button(self.CancelButton).setDisabled(True)
  307. else:
  308. self.done(0)
  309. def has_selected_vms(self):
  310. return self.select_vms_widget.selected_list.count() > 0
  311. def has_selected_dir_and_pass(self):
  312. if not len(self.passphrase_line_edit.text()):
  313. return False
  314. if self.passphrase_line_edit.text() != \
  315. self.passphrase_line_edit_verify.text():
  316. return False
  317. return len(self.dir_line_edit.text()) > 0
  318. def backup_location_changed(self, new_dir=None):
  319. self.select_dir_page.emit(QtCore.SIGNAL("completeChanged()"))
  320. # Bases on the original code by:
  321. # Copyright (c) 2002-2007 Pascal Varet <p.varet@gmail.com>
  322. def handle_exception(exc_type, exc_value, exc_traceback):
  323. filename, line, dummy, dummy = traceback.extract_tb(exc_traceback).pop()
  324. filename = os.path.basename(filename)
  325. error = "%s: %s" % (exc_type.__name__, exc_value)
  326. QtGui.QMessageBox.critical(
  327. None,
  328. "Houston, we have a problem...",
  329. "Whoops. A critical error has occured. This is most likely a bug "
  330. "in Qubes Global Settings application.<br><br><b><i>%s</i></b>" %
  331. error + "at <b>line %d</b> of file <b>%s</b>.<br/><br/>"
  332. % (line, filename))
  333. def main():
  334. qtapp = QtGui.QApplication(sys.argv)
  335. qtapp.setOrganizationName("The Qubes Project")
  336. qtapp.setOrganizationDomain("http://qubes-os.org")
  337. qtapp.setApplicationName("Qubes Backup VMs")
  338. sys.excepthook = handle_exception
  339. app = Qubes()
  340. backup_window = BackupVMsWindow(qtapp, app)
  341. backup_window.show()
  342. qtapp.exec_()
  343. qtapp.exit()
  344. if __name__ == "__main__":
  345. main()