backup.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  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. import quamash
  25. from qubesadmin import Qubes, exc
  26. from qubesadmin import utils as admin_utils
  27. from qubesadmin import events
  28. from qubes.storage.file import get_disk_usage
  29. from PyQt4 import QtCore # pylint: disable=import-error
  30. from PyQt4 import QtGui # pylint: disable=import-error
  31. from . import ui_backupdlg # pylint: disable=no-name-in-module
  32. from . import multiselectwidget
  33. from . import backup_utils
  34. from . import utils
  35. import grp
  36. import pwd
  37. import sys
  38. import os
  39. import asyncio
  40. from contextlib import suppress
  41. # pylint: disable=too-few-public-methods
  42. class BackupThread(QtCore.QThread):
  43. def __init__(self, vm):
  44. QtCore.QThread.__init__(self)
  45. self.vm = vm
  46. self.msg = None
  47. def run(self):
  48. msg = []
  49. try:
  50. if not self.vm.is_running():
  51. self.vm.start()
  52. self.vm.app.qubesd_call(
  53. 'dom0', 'admin.backup.Execute',
  54. backup_utils.get_profile_name(True))
  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, multiselectwidget.QtGui.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.backup_settings = QtCore.QSettings()
  65. self.selected_vms = []
  66. self.thread = None
  67. self.setupUi(self)
  68. self.progress_status.text = self.tr("Backup in progress...")
  69. self.dir_line_edit.setReadOnly(False)
  70. self.select_vms_widget = multiselectwidget.MultiSelectWidget(self)
  71. self.verticalLayout.insertWidget(1, self.select_vms_widget)
  72. self.connect(self, QtCore.SIGNAL("currentIdChanged(int)"),
  73. self.current_page_changed)
  74. self.connect(self.select_vms_widget,
  75. QtCore.SIGNAL("items_removed(PyQt_PyObject)"),
  76. self.vms_removed)
  77. self.connect(self.select_vms_widget,
  78. QtCore.SIGNAL("items_added(PyQt_PyObject)"),
  79. self.vms_added)
  80. self.dir_line_edit.connect(self.dir_line_edit,
  81. QtCore.SIGNAL("textChanged(QString)"),
  82. self.backup_location_changed)
  83. self.select_vms_page.isComplete = self.has_selected_vms
  84. self.select_dir_page.isComplete = self.has_selected_dir_and_pass
  85. # FIXME
  86. # this causes to run isComplete() twice, I don't know why
  87. self.select_vms_page.connect(
  88. self.select_vms_widget,
  89. QtCore.SIGNAL("selected_changed()"),
  90. QtCore.SIGNAL("completeChanged()"))
  91. self.passphrase_line_edit.connect(
  92. self.passphrase_line_edit,
  93. QtCore.SIGNAL("textChanged(QString)"),
  94. self.backup_location_changed)
  95. self.passphrase_line_edit_verify.connect(
  96. self.passphrase_line_edit_verify,
  97. QtCore.SIGNAL("textChanged(QString)"),
  98. self.backup_location_changed)
  99. self.total_size = 0
  100. self.target_vm_list, self.target_vm_idx = utils.prepare_vm_choice(
  101. self.appvm_combobox,
  102. self.qubes_app,
  103. None,
  104. self.qubes_app.domains['dom0'],
  105. filter_function=(lambda vm:
  106. vm.klass != 'TemplateVM'
  107. and vm.is_running()
  108. and not vm.features.get('internal', False)),
  109. allow_default=False,
  110. allow_none=False
  111. )
  112. self.unrecognized_config_label.setVisible(False)
  113. self.load_settings()
  114. selected = self.vms_to_include()
  115. self.__fill_vms_list__(selected)
  116. # Connect backup events for progress_bar
  117. self.progress_bar.setMinimum(0)
  118. self.progress_bar.setMaximum(100)
  119. self.dispatcher = dispatcher
  120. dispatcher.add_handler('backup-progress', self.on_backup_progress)
  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', None):
  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. QtGui.QMessageBox.information(
  148. None, 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.unrecognized_config_label.setVisible(True)
  160. if 'destination_path' in profile_data:
  161. dest_path = profile_data['destination_path']
  162. self.dir_line_edit.setText(dest_path)
  163. if 'passphrase_text' in profile_data:
  164. self.passphrase_line_edit.setText(profile_data['passphrase_text'])
  165. self.passphrase_line_edit_verify.setText(
  166. profile_data['passphrase_text'])
  167. if 'compression' in profile_data:
  168. self.compress_checkbox.setChecked(profile_data['compression'])
  169. def save_settings(self, use_temp):
  170. """
  171. Helper function that saves backup profile to either
  172. /etc/qubes/backup/qubes-manager-backup.conf or
  173. /etc/qubes/backup/qubes-manager-backup-tmp.conf
  174. :param use_temp: whether to use temporary profile (True) or the default
  175. backup profile (False)
  176. """
  177. settings = {'destination_vm': self.appvm_combobox.currentText(),
  178. 'destination_path': self.dir_line_edit.text(),
  179. 'include': [vm.name for vm in self.selected_vms],
  180. 'passphrase_text': self.passphrase_line_edit.text(),
  181. 'compression': self.compress_checkbox.isChecked()}
  182. backup_utils.write_backup_profile(settings, use_temp)
  183. class VmListItem(QtGui.QListWidgetItem):
  184. # pylint: disable=too-few-public-methods
  185. def __init__(self, vm):
  186. self.vm = vm
  187. if vm.qid == 0:
  188. local_user = grp.getgrnam('qubes').gr_mem[0]
  189. home_dir = pwd.getpwnam(local_user).pw_dir
  190. self.size = get_disk_usage(home_dir)
  191. else:
  192. self.size = vm.get_disk_utilization()
  193. super(BackupVMsWindow.VmListItem, self).__init__(
  194. vm.name + " (" + admin_utils.size_to_human(self.size) + ")")
  195. def __fill_vms_list__(self, selected=None):
  196. for vm in self.qubes_app.domains:
  197. if vm.features.get('internal', False):
  198. continue
  199. item = BackupVMsWindow.VmListItem(vm)
  200. if (selected is None and
  201. getattr(vm, 'include_in_backups', True)) \
  202. or (selected and vm.name in selected):
  203. self.select_vms_widget.selected_list.addItem(item)
  204. self.total_size += item.size
  205. else:
  206. self.select_vms_widget.available_list.addItem(item)
  207. self.select_vms_widget.available_list.sortItems()
  208. self.select_vms_widget.selected_list.sortItems()
  209. self.total_size_label.setText(
  210. admin_utils.size_to_human(self.total_size))
  211. def vms_added(self, items):
  212. for i in items:
  213. self.total_size += i.size
  214. self.total_size_label.setText(
  215. admin_utils.size_to_human(self.total_size))
  216. def vms_removed(self, items):
  217. for i in items:
  218. self.total_size -= i.size
  219. self.total_size_label.setText(
  220. admin_utils.size_to_human(self.total_size))
  221. @QtCore.pyqtSlot(name='on_select_path_button_clicked')
  222. def select_path_button_clicked(self):
  223. backup_utils.select_path_button_clicked(self)
  224. def validateCurrentPage(self):
  225. # pylint: disable=invalid-name
  226. if self.currentPage() is self.select_vms_page:
  227. self.selected_vms = []
  228. for i in range(self.select_vms_widget.selected_list.count()):
  229. self.selected_vms.append(
  230. self.select_vms_widget.selected_list.item(i).vm)
  231. elif self.currentPage() is self.select_dir_page:
  232. backup_location = str(self.dir_line_edit.text())
  233. if not backup_location:
  234. QtGui.QMessageBox.information(
  235. None, self.tr("Wait!"),
  236. self.tr("Enter backup target location first."))
  237. return False
  238. if self.appvm_combobox.currentText() == "dom0" \
  239. and not os.path.isdir(backup_location):
  240. QtGui.QMessageBox.information(
  241. None, self.tr("Wait!"),
  242. self.tr("Selected directory do not exists or "
  243. "not a directory (%s).") % backup_location)
  244. return False
  245. if not self.passphrase_line_edit.text():
  246. QtGui.QMessageBox.information(
  247. None, self.tr("Wait!"),
  248. self.tr("Enter passphrase for backup "
  249. "encryption/verification first."))
  250. return False
  251. if self.passphrase_line_edit.text() !=\
  252. self.passphrase_line_edit_verify.text():
  253. QtGui.QMessageBox.information(
  254. None, self.tr("Wait!"),
  255. self.tr("Enter the same passphrase in both fields."))
  256. return False
  257. return True
  258. @staticmethod
  259. def cleanup_temporary_files():
  260. try:
  261. os.remove(backup_utils.get_profile_path(use_temp=True))
  262. except FileNotFoundError:
  263. pass
  264. def current_page_changed(self, page_id): # pylint: disable=unused-argument
  265. old_sigchld_handler = signal.signal(signal.SIGCHLD, signal.SIG_DFL)
  266. if self.currentPage() is self.confirm_page:
  267. self.save_settings(use_temp=True)
  268. backup_summary = self.qubes_app.qubesd_call(
  269. 'dom0', 'admin.backup.Info',
  270. backup_utils.get_profile_name(True))
  271. self.textEdit.setReadOnly(True)
  272. self.textEdit.setFontFamily("Monospace")
  273. self.textEdit.setText(backup_summary.decode())
  274. elif self.currentPage() is self.commit_page:
  275. if self.save_profile_checkbox.isChecked():
  276. self.save_settings(use_temp=False)
  277. self.button(self.FinishButton).setDisabled(True)
  278. self.showFileDialog.setEnabled(
  279. self.appvm_combobox.currentIndex() != 0)
  280. self.showFileDialog.setChecked(self.showFileDialog.isEnabled()
  281. and str(self.dir_line_edit.text())
  282. .count("media/") > 0)
  283. vm = self.qubes_app.domains[
  284. self.appvm_combobox.currentText()]
  285. self.thread = BackupThread(vm)
  286. self.thread.finished.connect(self.backup_finished)
  287. self.thread.start()
  288. signal.signal(signal.SIGCHLD, old_sigchld_handler)
  289. def backup_finished(self):
  290. if self.thread.msg:
  291. self.progress_status.setText(self.tr("Backup error."))
  292. QtGui.QMessageBox.warning(
  293. self, self.tr("Backup error!"),
  294. self.tr("ERROR: {}").format(
  295. self.thread.msg))
  296. else:
  297. self.progress_bar.setValue(100)
  298. self.progress_status.setText(self.tr("Backup finished."))
  299. if self.showFileDialog.isChecked():
  300. orig_text = self.progress_status.text
  301. self.progress_status.setText(
  302. orig_text + self.tr(
  303. " Please unmount your backup volume and cancel "
  304. "the file selection dialog."))
  305. backup_utils.select_path_button_clicked(self, False, True)
  306. self.button(self.CancelButton).setEnabled(False)
  307. self.button(self.FinishButton).setEnabled(True)
  308. self.showFileDialog.setEnabled(False)
  309. self.cleanup_temporary_files()
  310. # turn off only when backup was successful
  311. if self.turn_off_checkbox.isChecked():
  312. os.system('systemctl poweroff')
  313. def reject(self):
  314. if self.currentPage() is self.commit_page:
  315. self.qubes_app.qubesd_call(
  316. 'dom0', 'admin.backup.Cancel',
  317. backup_utils.get_profile_name(True))
  318. self.thread.wait()
  319. QtGui.QMessageBox.warning(
  320. self, self.tr("Backup aborted!"),
  321. self.tr("ERROR: {}").format("Aborted!"))
  322. self.cleanup_temporary_files()
  323. self.done(0)
  324. def has_selected_vms(self):
  325. return self.select_vms_widget.selected_list.count() > 0
  326. def has_selected_dir_and_pass(self):
  327. if not self.passphrase_line_edit.text():
  328. return False
  329. if self.passphrase_line_edit.text() != \
  330. self.passphrase_line_edit_verify.text():
  331. return False
  332. return len(self.dir_line_edit.text()) > 0
  333. def backup_location_changed(self, new_dir=None):
  334. # pylint: disable=unused-argument
  335. self.select_dir_page.emit(QtCore.SIGNAL("completeChanged()"))
  336. # Bases on the original code by:
  337. # Copyright (c) 2002-2007 Pascal Varet <p.varet@gmail.com>
  338. def handle_exception(exc_type, exc_value, exc_traceback):
  339. filename, line, dummy, dummy = traceback.extract_tb(exc_traceback).pop()
  340. filename = os.path.basename(filename)
  341. error = "%s: %s" % (exc_type.__name__, exc_value)
  342. QtGui.QMessageBox.critical(
  343. None,
  344. "Houston, we have a problem...",
  345. "Whoops. A critical error has occured. This is most likely a bug "
  346. "in Qubes Global Settings application.<br><br><b><i>%s</i></b>" %
  347. error + "at <b>line %d</b> of file <b>%s</b>.<br/><br/>"
  348. % (line, filename))
  349. def loop_shutdown():
  350. pending = asyncio.Task.all_tasks()
  351. for task in pending:
  352. with suppress(asyncio.CancelledError):
  353. task.cancel()
  354. def main():
  355. qt_app = QtGui.QApplication(sys.argv)
  356. qt_app.setOrganizationName("The Qubes Project")
  357. qt_app.setOrganizationDomain("http://qubes-os.org")
  358. qt_app.setApplicationName("Qubes Backup VMs")
  359. qt_app.lastWindowClosed.connect(loop_shutdown)
  360. sys.excepthook = handle_exception
  361. qubes_app = Qubes()
  362. loop = quamash.QEventLoop(qt_app)
  363. asyncio.set_event_loop(loop)
  364. dispatcher = events.EventsDispatcher(qubes_app)
  365. backup_window = BackupVMsWindow(qt_app, qubes_app, dispatcher)
  366. backup_window.show()
  367. try:
  368. loop.run_until_complete(
  369. asyncio.ensure_future(dispatcher.listen_for_events()))
  370. except asyncio.CancelledError:
  371. pass
  372. except Exception: # pylint: disable=broad-except
  373. loop_shutdown()
  374. exc_type, exc_value, exc_traceback = sys.exc_info()[:3]
  375. handle_exception(exc_type, exc_value, exc_traceback)
  376. if __name__ == "__main__":
  377. main()