backup.py 15 KB

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