backup.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  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 signal
  23. from qubesadmin import exc
  24. from qubesadmin import utils as admin_utils
  25. from PyQt5 import QtCore, QtWidgets, QtGui # pylint: disable=import-error
  26. from . import ui_backupdlg # pylint: disable=no-name-in-module
  27. from . import multiselectwidget
  28. from . import backup_utils
  29. from . import utils
  30. import grp
  31. import pwd
  32. import os
  33. import shutil
  34. # pylint: disable=too-few-public-methods
  35. class BackupThread(QtCore.QThread):
  36. def __init__(self, vm):
  37. QtCore.QThread.__init__(self)
  38. self.vm = vm
  39. self.msg = None
  40. def run(self):
  41. msg = []
  42. try:
  43. if not self.vm.is_running():
  44. self.vm.start()
  45. except exc.QubesException:
  46. # we may have insufficient exceptions to ensure the qube is running
  47. pass
  48. try:
  49. self.vm.app.qubesd_call(
  50. 'dom0', 'admin.backup.Execute',
  51. backup_utils.get_profile_name(True))
  52. except exc.BackupAlreadyRunningError:
  53. msg.append("This backup is already in progress! Cancel it "
  54. "or wait until it finishes.")
  55. except Exception as ex: # pylint: disable=broad-except
  56. msg.append(str(ex))
  57. if msg:
  58. self.msg = '\n'.join(msg)
  59. class BackupVMsWindow(ui_backupdlg.Ui_Backup, QtWidgets.QWizard):
  60. def __init__(self, qt_app, qubes_app, dispatcher, parent=None):
  61. super(BackupVMsWindow, self).__init__(parent)
  62. self.qt_app = qt_app
  63. self.qubes_app = qubes_app
  64. self.selected_vms = []
  65. self.thread = None
  66. self.setupUi(self)
  67. self.progress_status.text = self.tr("Backup in progress...")
  68. self.dir_line_edit.setReadOnly(False)
  69. self.select_vms_widget = multiselectwidget.MultiSelectWidget(self)
  70. self.verticalLayout.insertWidget(1, self.select_vms_widget)
  71. self.currentIdChanged.connect(self.current_page_changed)
  72. self.select_vms_widget.itemsRemoved.connect(self.vms_removed)
  73. self.select_vms_widget.itemsAdded.connect(self.vms_added)
  74. self.dir_line_edit.textChanged.connect(self.backup_location_changed)
  75. self.select_vms_page.isComplete = self.has_selected_vms
  76. self.select_dir_page.isComplete = self.has_selected_dir_and_pass
  77. # FIXME
  78. # this causes to run isComplete() twice, I don't know why
  79. self.select_vms_widget.selectedChanged.connect(
  80. self.select_vms_page.completeChanged.emit)
  81. self.passphrase_line_edit.textChanged.connect(
  82. self.backup_location_changed)
  83. self.passphrase_line_edit_verify.textChanged.connect(
  84. self.backup_location_changed)
  85. self.total_size = 0
  86. utils.initialize_widget_with_vms(
  87. widget=self.appvm_combobox,
  88. qubes_app=self.qubes_app,
  89. filter_function=(lambda vm:
  90. vm.klass != 'TemplateVM'
  91. and utils.is_running(vm, False)
  92. and not utils.get_feature(vm, 'internal', False)),
  93. allow_internal=True,
  94. )
  95. self.appvm_combobox.setCurrentIndex(
  96. self.appvm_combobox.findText("dom0"))
  97. self.unrecognized_config_label.setVisible(False)
  98. self.load_settings()
  99. selected = self.vms_to_include()
  100. self.__fill_vms_list__(selected)
  101. # Connect backup events for progress_bar
  102. self.progress_bar.setMinimum(0)
  103. self.progress_bar.setMaximum(100)
  104. self.dispatcher = dispatcher
  105. dispatcher.add_handler('backup-progress', self.on_backup_progress)
  106. def setup_application(self):
  107. self.qt_app.setApplicationName(self.tr("Qubes Backup VMs"))
  108. self.qt_app.setWindowIcon(QtGui.QIcon.fromTheme("qubes-manager"))
  109. def on_backup_progress(self, __submitter, _event, **kwargs):
  110. self.progress_bar.setValue(int(float(kwargs['progress'])))
  111. def vms_to_include(self):
  112. """
  113. Helper function that returns list of VMs with 'include_in_backups'
  114. attribute set to True.
  115. :return: list of VM names
  116. """
  117. result = []
  118. for domain in self.qubes_app.domains:
  119. if getattr(domain, 'include_in_backups', None):
  120. result.append(domain.name)
  121. return result
  122. def load_settings(self):
  123. """
  124. Helper function that tries to load existing backup profile
  125. (default path: /etc/qubes/backup/qubes-manager-backup.conf )
  126. and then apply its contents to the Backup window.
  127. Ignores listed VMs, to prioritize include_in_backups feature.
  128. :return: None
  129. """
  130. try:
  131. profile_data = backup_utils.load_backup_profile()
  132. except FileNotFoundError:
  133. return
  134. except exc.QubesException:
  135. QtWidgets.QMessageBox.information(
  136. self, self.tr("Error loading backup profile"),
  137. self.tr("Unable to load saved backup profile."))
  138. return
  139. if not profile_data:
  140. return
  141. if 'destination_vm' in profile_data:
  142. dest_vm_name = profile_data['destination_vm']
  143. dest_vm_idx = self.appvm_combobox.findText(dest_vm_name)
  144. if dest_vm_idx > -1:
  145. self.appvm_combobox.setCurrentIndex(dest_vm_idx)
  146. else:
  147. self.unrecognized_config_label.setVisible(True)
  148. if 'destination_path' in profile_data:
  149. dest_path = profile_data['destination_path']
  150. self.dir_line_edit.setText(dest_path)
  151. if 'passphrase_text' in profile_data:
  152. self.passphrase_line_edit.setText(profile_data['passphrase_text'])
  153. self.passphrase_line_edit_verify.setText(
  154. profile_data['passphrase_text'])
  155. if 'compression' in profile_data:
  156. self.compress_checkbox.setChecked(profile_data['compression'])
  157. def save_settings(self, use_temp):
  158. """
  159. Helper function that saves backup profile to either
  160. /etc/qubes/backup/qubes-manager-backup.conf or
  161. /etc/qubes/backup/qubes-manager-backup-tmp.conf
  162. :param use_temp: whether to use temporary profile (True) or the default
  163. backup profile (False)
  164. """
  165. settings = {'destination_vm': self.appvm_combobox.currentText(),
  166. 'destination_path': self.dir_line_edit.text(),
  167. 'include': [vm.name for vm in self.selected_vms],
  168. 'passphrase_text': self.passphrase_line_edit.text(),
  169. 'compression': self.compress_checkbox.isChecked()}
  170. backup_utils.write_backup_profile(settings, use_temp)
  171. class VmListItem(QtWidgets.QListWidgetItem):
  172. # pylint: disable=too-few-public-methods
  173. def __init__(self, vm):
  174. self.vm = vm
  175. if vm.qid == 0:
  176. local_user = grp.getgrnam('qubes').gr_mem[0]
  177. home_dir = pwd.getpwnam(local_user).pw_dir
  178. self.size = shutil.disk_usage(home_dir)[1]
  179. else:
  180. self.size = vm.get_disk_utilization()
  181. super(BackupVMsWindow.VmListItem, self).__init__(
  182. vm.name + " (" + admin_utils.size_to_human(self.size) + ")")
  183. def __fill_vms_list__(self, selected=None):
  184. for vm in self.qubes_app.domains:
  185. if utils.get_feature(vm, 'internal', False):
  186. continue
  187. item = BackupVMsWindow.VmListItem(vm)
  188. if (selected is None and
  189. getattr(vm, 'include_in_backups', True)) \
  190. or (selected and vm.name in selected):
  191. self.select_vms_widget.selected_list.addItem(item)
  192. self.total_size += item.size
  193. else:
  194. self.select_vms_widget.available_list.addItem(item)
  195. self.select_vms_widget.available_list.sortItems()
  196. self.select_vms_widget.selected_list.sortItems()
  197. self.total_size_label.setText(
  198. admin_utils.size_to_human(self.total_size))
  199. def vms_added(self, items):
  200. for i in items:
  201. self.total_size += i.size
  202. self.total_size_label.setText(
  203. admin_utils.size_to_human(self.total_size))
  204. def vms_removed(self, items):
  205. for i in items:
  206. self.total_size -= i.size
  207. self.total_size_label.setText(
  208. admin_utils.size_to_human(self.total_size))
  209. @QtCore.pyqtSlot(name='on_select_path_button_clicked')
  210. def select_path_button_clicked(self):
  211. backup_utils.select_path_button_clicked(self)
  212. def validateCurrentPage(self):
  213. # pylint: disable=invalid-name
  214. if self.currentPage() is self.select_vms_page:
  215. self.selected_vms = []
  216. for i in range(self.select_vms_widget.selected_list.count()):
  217. self.selected_vms.append(
  218. self.select_vms_widget.selected_list.item(i).vm)
  219. elif self.currentPage() is self.select_dir_page:
  220. backup_location = str(self.dir_line_edit.text())
  221. if not backup_location:
  222. QtWidgets.QMessageBox.information(
  223. self, self.tr("Wait!"),
  224. self.tr("Enter backup target location first."))
  225. return False
  226. if self.appvm_combobox.currentText() == "dom0" \
  227. and not os.path.isdir(backup_location):
  228. QtWidgets.QMessageBox.information(
  229. self, self.tr("Wait!"),
  230. self.tr("Selected directory do not exists or "
  231. "not a directory (%s).") % backup_location)
  232. return False
  233. if not self.passphrase_line_edit.text():
  234. QtWidgets.QMessageBox.information(
  235. self, self.tr("Wait!"),
  236. self.tr("Enter passphrase for backup "
  237. "encryption/verification first."))
  238. return False
  239. if self.passphrase_line_edit.text() !=\
  240. self.passphrase_line_edit_verify.text():
  241. QtWidgets.QMessageBox.information(
  242. self, self.tr("Wait!"),
  243. self.tr("Enter the same passphrase in both fields."))
  244. return False
  245. return True
  246. @staticmethod
  247. def cleanup_temporary_files():
  248. try:
  249. os.remove(backup_utils.get_profile_path(use_temp=True))
  250. except FileNotFoundError:
  251. pass
  252. def current_page_changed(self, page_id): # pylint: disable=unused-argument
  253. old_sigchld_handler = signal.signal(signal.SIGCHLD, signal.SIG_DFL)
  254. if self.currentPage() is self.confirm_page:
  255. self.save_settings(use_temp=True)
  256. try:
  257. backup_summary = self.qubes_app.qubesd_call(
  258. 'dom0', 'admin.backup.Info',
  259. backup_utils.get_profile_name(True)).decode()
  260. except exc.QubesDaemonCommunicationError:
  261. backup_summary = "Failed to get backup summary: " \
  262. "insufficient permissions"
  263. self.textEdit.setReadOnly(True)
  264. self.textEdit.setFontFamily("Monospace")
  265. self.textEdit.setText(backup_summary)
  266. elif self.currentPage() is self.commit_page:
  267. if self.save_profile_checkbox.isChecked():
  268. self.save_settings(use_temp=False)
  269. self.button(self.FinishButton).setDisabled(True)
  270. self.showFileDialog.setEnabled(
  271. self.appvm_combobox.currentIndex() != 0)
  272. self.showFileDialog.setChecked(self.showFileDialog.isEnabled()
  273. and str(self.dir_line_edit.text())
  274. .count("media/") > 0)
  275. vm = self.qubes_app.domains[
  276. self.appvm_combobox.currentText()]
  277. self.thread = BackupThread(vm)
  278. self.thread.finished.connect(self.backup_finished)
  279. self.thread.start()
  280. signal.signal(signal.SIGCHLD, old_sigchld_handler)
  281. def backup_finished(self):
  282. if self.thread.msg:
  283. self.progress_status.setText(self.tr("Backup error"))
  284. QtWidgets.QMessageBox.warning(
  285. self, self.tr("Backup error"),
  286. self.tr("ERROR: {}").format(
  287. self.thread.msg))
  288. self.button(self.CancelButton).setEnabled(False)
  289. self.button(self.FinishButton).setEnabled(True)
  290. self.cleanup_temporary_files()
  291. else:
  292. self.progress_bar.setValue(100)
  293. self.progress_status.setText(self.tr("Backup finished."))
  294. if self.showFileDialog.isChecked():
  295. orig_text = self.progress_status.text
  296. self.progress_status.setText(
  297. orig_text + self.tr(
  298. " Please unmount your backup volume and cancel "
  299. "the file selection dialog."))
  300. backup_utils.select_path_button_clicked(self, False, True)
  301. self.button(self.CancelButton).setEnabled(False)
  302. self.button(self.FinishButton).setEnabled(True)
  303. self.showFileDialog.setEnabled(False)
  304. self.cleanup_temporary_files()
  305. # turn off only when backup was successful
  306. if self.turn_off_checkbox.isChecked():
  307. os.system('systemctl poweroff')
  308. def reject(self):
  309. if (self.currentPage() is self.commit_page) and \
  310. self.button(self.CancelButton).isEnabled():
  311. try:
  312. self.qubes_app.qubesd_call(
  313. 'dom0', 'admin.backup.Cancel',
  314. backup_utils.get_profile_name(True))
  315. except exc.QubesException as ex:
  316. QtWidgets.QMessageBox.warning(
  317. self, self.tr("Error cancelling backup!"),
  318. self.tr("ERROR: {}").format(str(ex)))
  319. self.thread.wait()
  320. QtWidgets.QMessageBox.warning(
  321. self, self.tr("Backup aborted!"),
  322. self.tr("ERROR: Aborted"))
  323. self.cleanup_temporary_files()
  324. self.done(0)
  325. def has_selected_vms(self):
  326. return self.select_vms_widget.selected_list.count() > 0
  327. def has_selected_dir_and_pass(self):
  328. if not self.passphrase_line_edit.text():
  329. return False
  330. if self.passphrase_line_edit.text() != \
  331. self.passphrase_line_edit_verify.text():
  332. return False
  333. return len(self.dir_line_edit.text()) > 0
  334. def backup_location_changed(self, new_dir=None):
  335. # pylint: disable=unused-argument
  336. self.select_dir_page.completeChanged.emit()
  337. def main():
  338. utils.run_asynchronous(BackupVMsWindow)
  339. if __name__ == "__main__":
  340. main()