backup.py 15 KB

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