backup.py 16 KB

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