backup.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. #!/usr/bin/python3
  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 Lesser General Public License along
  19. # with this program; if not, see <http://www.gnu.org/licenses/>.
  20. #
  21. #
  22. import traceback
  23. import signal
  24. from qubesadmin import Qubes, exc
  25. from qubesadmin import utils as admin_utils
  26. from qubes.storage.file import get_disk_usage
  27. from PyQt4 import QtCore # pylint: disable=import-error
  28. from PyQt4 import QtGui # pylint: disable=import-error
  29. from . import ui_backupdlg # pylint: disable=no-name-in-module
  30. from . import multiselectwidget
  31. from . import backup_utils
  32. from . import utils
  33. import grp
  34. import pwd
  35. import sys
  36. import os
  37. from . import thread_monitor
  38. import threading
  39. import time
  40. class BackupVMsWindow(ui_backupdlg.Ui_Backup, multiselectwidget.QtGui.QWizard):
  41. def __init__(self, qt_app, qubes_app, parent=None):
  42. super(BackupVMsWindow, self).__init__(parent)
  43. self.qt_app = qt_app
  44. self.qubes_app = qubes_app
  45. self.backup_settings = QtCore.QSettings()
  46. self.selected_vms = []
  47. self.canceled = False
  48. self.thread_monitor = None
  49. self.setupUi(self)
  50. self.progress_status.text = self.tr("Backup in progress...")
  51. self.dir_line_edit.setReadOnly(False)
  52. self.select_vms_widget = multiselectwidget.MultiSelectWidget(self)
  53. self.verticalLayout.insertWidget(1, self.select_vms_widget)
  54. self.connect(self, QtCore.SIGNAL("currentIdChanged(int)"),
  55. self.current_page_changed)
  56. self.connect(self.select_vms_widget,
  57. QtCore.SIGNAL("items_removed(PyQt_PyObject)"),
  58. self.vms_removed)
  59. self.connect(self.select_vms_widget,
  60. QtCore.SIGNAL("items_added(PyQt_PyObject)"),
  61. self.vms_added)
  62. self.dir_line_edit.connect(self.dir_line_edit,
  63. QtCore.SIGNAL("textChanged(QString)"),
  64. self.backup_location_changed)
  65. self.select_vms_page.isComplete = self.has_selected_vms
  66. self.select_dir_page.isComplete = self.has_selected_dir_and_pass
  67. # FIXME
  68. # this causes to run isComplete() twice, I don't know why
  69. self.select_vms_page.connect(
  70. self.select_vms_widget,
  71. QtCore.SIGNAL("selected_changed()"),
  72. QtCore.SIGNAL("completeChanged()"))
  73. self.passphrase_line_edit.connect(
  74. self.passphrase_line_edit,
  75. QtCore.SIGNAL("textChanged(QString)"),
  76. self.backup_location_changed)
  77. self.passphrase_line_edit_verify.connect(
  78. self.passphrase_line_edit_verify,
  79. QtCore.SIGNAL("textChanged(QString)"),
  80. self.backup_location_changed)
  81. self.total_size = 0
  82. self.target_vm_list, self.target_vm_idx = utils.prepare_vm_choice(
  83. self.appvm_combobox,
  84. self.qubes_app,
  85. None,
  86. self.qubes_app.domains['dom0'],
  87. (lambda vm: vm.klass != 'TemplateVM' and vm.is_running()),
  88. allow_internal=False,
  89. allow_default=False,
  90. allow_none=False
  91. )
  92. selected = self.load_settings()
  93. self.__fill_vms_list__(selected)
  94. def load_settings(self):
  95. """
  96. Helper function that tries to load existing backup profile
  97. (default path: /etc/qubes/backup/qubes-manager-backup.conf )
  98. and then apply its contents to the Backup window.
  99. :return: list of vms to include in backup, if it exists in the profile,
  100. or None if it does not
  101. """
  102. try:
  103. profile_data = backup_utils.load_backup_profile()
  104. except FileNotFoundError:
  105. return
  106. except exc.QubesException:
  107. QtGui.QMessageBox.information(
  108. None, self.tr("Error loading backup profile"),
  109. self.tr("Unable to load saved backup profile."))
  110. return
  111. if not profile_data:
  112. return
  113. if 'destination_vm' in profile_data:
  114. dest_vm_name = profile_data['destination_vm']
  115. dest_vm_idx = self.appvm_combobox.findText(dest_vm_name)
  116. if dest_vm_idx > -1:
  117. self.appvm_combobox.setCurrentIndex(dest_vm_idx)
  118. if 'destination_path' in profile_data:
  119. dest_path = profile_data['destination_path']
  120. self.dir_line_edit.setText(dest_path)
  121. if 'passphrase_text' in profile_data:
  122. self.passphrase_line_edit.setText(profile_data['passphrase_text'])
  123. self.passphrase_line_edit_verify.setText(
  124. profile_data['passphrase_text'])
  125. if 'compression' in profile_data:
  126. self.compress_checkbox.setChecked(profile_data['compression'])
  127. if 'include' in profile_data:
  128. return profile_data['include']
  129. return None
  130. def save_settings(self, use_temp):
  131. """
  132. Helper function that saves backup profile to either
  133. /etc/qubes/backup/qubes-manager-backup.conf or
  134. /etc/qubes/backup/qubes-manager-backup-tmp.conf
  135. :param use_temp: whether to use temporary profile (True) or the default
  136. backup profile (False)
  137. """
  138. settings = {'destination_vm': self.appvm_combobox.currentText(),
  139. 'destination_path': self.dir_line_edit.text(),
  140. 'include': [vm.name for vm in self.selected_vms],
  141. 'passphrase_text': self.passphrase_line_edit.text(),
  142. 'compression': self.compress_checkbox.isChecked()}
  143. backup_utils.write_backup_profile(settings, use_temp)
  144. class VmListItem(QtGui.QListWidgetItem):
  145. # pylint: disable=too-few-public-methods
  146. def __init__(self, vm):
  147. self.vm = vm
  148. if vm.qid == 0:
  149. local_user = grp.getgrnam('qubes').gr_mem[0]
  150. home_dir = pwd.getpwnam(local_user).pw_dir
  151. self.size = get_disk_usage(home_dir)
  152. else:
  153. self.size = vm.get_disk_utilization()
  154. super(BackupVMsWindow.VmListItem, self).__init__(
  155. vm.name + " (" + admin_utils.size_to_human(self.size) + ")")
  156. def __fill_vms_list__(self, selected=None):
  157. for vm in self.qubes_app.domains:
  158. if vm.features.get('internal', False):
  159. continue
  160. item = BackupVMsWindow.VmListItem(vm)
  161. if (selected is None and
  162. getattr(vm, 'include_in_backups', True)) \
  163. or (selected and vm.name in selected):
  164. self.select_vms_widget.selected_list.addItem(item)
  165. self.total_size += item.size
  166. else:
  167. self.select_vms_widget.available_list.addItem(item)
  168. self.select_vms_widget.available_list.sortItems()
  169. self.select_vms_widget.selected_list.sortItems()
  170. self.unrecognized_config_label.setVisible(
  171. selected is not None and
  172. len(selected) != len(self.select_vms_widget.selected_list))
  173. self.total_size_label.setText(
  174. admin_utils.size_to_human(self.total_size))
  175. def vms_added(self, items):
  176. for i in items:
  177. self.total_size += i.size
  178. self.total_size_label.setText(
  179. admin_utils.size_to_human(self.total_size))
  180. def vms_removed(self, items):
  181. for i in items:
  182. self.total_size -= i.size
  183. self.total_size_label.setText(
  184. admin_utils.size_to_human(self.total_size))
  185. @QtCore.pyqtSlot(name='on_select_path_button_clicked')
  186. def select_path_button_clicked(self):
  187. backup_utils.select_path_button_clicked(self)
  188. def validateCurrentPage(self):
  189. # pylint: disable=invalid-name
  190. if self.currentPage() is self.select_vms_page:
  191. self.selected_vms = []
  192. for i in range(self.select_vms_widget.selected_list.count()):
  193. self.selected_vms.append(
  194. self.select_vms_widget.selected_list.item(i).vm)
  195. elif self.currentPage() is self.select_dir_page:
  196. backup_location = str(self.dir_line_edit.text())
  197. if not backup_location:
  198. QtGui.QMessageBox.information(
  199. None, self.tr("Wait!"),
  200. self.tr("Enter backup target location first."))
  201. return False
  202. if self.appvm_combobox.currentIndex() == 0 \
  203. and not os.path.isdir(backup_location):
  204. QtGui.QMessageBox.information(
  205. None, self.tr("Wait!"),
  206. self.tr("Selected directory do not exists or "
  207. "not a directory (%s).") % backup_location)
  208. return False
  209. if not self.passphrase_line_edit.text():
  210. QtGui.QMessageBox.information(
  211. None, self.tr("Wait!"),
  212. self.tr("Enter passphrase for backup "
  213. "encryption/verification first."))
  214. return False
  215. if self.passphrase_line_edit.text() !=\
  216. self.passphrase_line_edit_verify.text():
  217. QtGui.QMessageBox.information(
  218. None, self.tr("Wait!"),
  219. self.tr("Enter the same passphrase in both fields."))
  220. return False
  221. return True
  222. def __do_backup__(self, t_monitor):
  223. msg = []
  224. try:
  225. vm = self.qubes_app.domains[
  226. self.appvm_combobox.currentText()]
  227. if not vm.is_running():
  228. vm.start()
  229. self.qubes_app.qubesd_call(
  230. 'dom0', 'admin.backup.Execute',
  231. backup_utils.get_profile_name(True))
  232. except Exception as ex: # pylint: disable=broad-except
  233. msg.append(str(ex))
  234. if msg:
  235. t_monitor.set_error_msg('\n'.join(msg))
  236. t_monitor.set_finished()
  237. @staticmethod
  238. def cleanup_temporary_files():
  239. try:
  240. os.remove(backup_utils.get_profile_path(use_temp=True))
  241. except FileNotFoundError:
  242. pass
  243. def current_page_changed(self, page_id): # pylint: disable=unused-argument
  244. old_sigchld_handler = signal.signal(signal.SIGCHLD, signal.SIG_DFL)
  245. if self.currentPage() is self.confirm_page:
  246. self.save_settings(use_temp=True)
  247. backup_summary = self.qubes_app.qubesd_call(
  248. 'dom0', 'admin.backup.Info',
  249. backup_utils.get_profile_name(True))
  250. self.textEdit.setReadOnly(True)
  251. self.textEdit.setFontFamily("Monospace")
  252. self.textEdit.setText(backup_summary.decode())
  253. elif self.currentPage() is self.commit_page:
  254. if self.save_profile_checkbox.isChecked():
  255. self.save_settings(use_temp=False)
  256. self.button(self.FinishButton).setDisabled(True)
  257. self.showFileDialog.setEnabled(
  258. self.appvm_combobox.currentIndex() != 0)
  259. self.showFileDialog.setChecked(self.showFileDialog.isEnabled()
  260. and str(self.dir_line_edit.text())
  261. .count("media/") > 0)
  262. self.thread_monitor = thread_monitor.ThreadMonitor()
  263. thread = threading.Thread(
  264. target=self.__do_backup__,
  265. args=(self.thread_monitor,))
  266. thread.daemon = True
  267. thread.start()
  268. while not self.thread_monitor.is_finished():
  269. self.qt_app.processEvents()
  270. time.sleep(0.1)
  271. if not self.thread_monitor.success:
  272. if self.canceled:
  273. self.progress_status.setText(
  274. self.tr(
  275. "Backup aborted. "
  276. "Temporary file may be left at backup location."))
  277. else:
  278. self.progress_status.setText(self.tr("Backup error."))
  279. QtGui.QMessageBox.warning(
  280. self, self.tr("Backup error!"),
  281. self.tr("ERROR: {}").format(
  282. self.thread_monitor.error_msg))
  283. else:
  284. self.progress_bar.setMaximum(100)
  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. backup_utils.select_path_button_clicked(self, False, True)
  294. self.button(self.CancelButton).setEnabled(False)
  295. self.button(self.FinishButton).setEnabled(True)
  296. self.showFileDialog.setEnabled(False)
  297. self.cleanup_temporary_files()
  298. signal.signal(signal.SIGCHLD, old_sigchld_handler)
  299. def reject(self):
  300. if self.currentPage() is self.commit_page:
  301. self.canceled = True
  302. self.qubes_app.qubesd_call(
  303. 'dom0', 'admin.backup.Cancel',
  304. backup_utils.get_profile_name(True))
  305. self.progress_bar.setMaximum(100)
  306. self.progress_bar.setValue(0)
  307. self.button(self.CancelButton).setDisabled(True)
  308. self.cleanup_temporary_files()
  309. else:
  310. self.cleanup_temporary_files()
  311. self.done(0)
  312. def has_selected_vms(self):
  313. return self.select_vms_widget.selected_list.count() > 0
  314. def has_selected_dir_and_pass(self):
  315. if not self.passphrase_line_edit.text():
  316. return False
  317. if self.passphrase_line_edit.text() != \
  318. self.passphrase_line_edit_verify.text():
  319. return False
  320. return len(self.dir_line_edit.text()) > 0
  321. def backup_location_changed(self, new_dir=None):
  322. # pylint: disable=unused-argument
  323. self.select_dir_page.emit(QtCore.SIGNAL("completeChanged()"))
  324. # Bases on the original code by:
  325. # Copyright (c) 2002-2007 Pascal Varet <p.varet@gmail.com>
  326. def handle_exception(exc_type, exc_value, exc_traceback):
  327. filename, line, dummy, dummy = traceback.extract_tb(exc_traceback).pop()
  328. filename = os.path.basename(filename)
  329. error = "%s: %s" % (exc_type.__name__, exc_value)
  330. QtGui.QMessageBox.critical(
  331. None,
  332. "Houston, we have a problem...",
  333. "Whoops. A critical error has occured. This is most likely a bug "
  334. "in Qubes Global Settings application.<br><br><b><i>%s</i></b>" %
  335. error + "at <b>line %d</b> of file <b>%s</b>.<br/><br/>"
  336. % (line, filename))
  337. def main():
  338. qt_app = QtGui.QApplication(sys.argv)
  339. qt_app.setOrganizationName("The Qubes Project")
  340. qt_app.setOrganizationDomain("http://qubes-os.org")
  341. qt_app.setApplicationName("Qubes Backup VMs")
  342. sys.excepthook = handle_exception
  343. app = Qubes()
  344. backup_window = BackupVMsWindow(qt_app, app)
  345. backup_window.show()
  346. qt_app.exec_()
  347. qt_app.exit()
  348. if __name__ == "__main__":
  349. main()