backup.py 16 KB

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