backup.py 15 KB

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