backup.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. #!/usr/bin/python2.6
  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 General Public License
  19. # along with this program; if not, write to the Free Software
  20. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  21. #
  22. #
  23. import sys
  24. import os
  25. from PyQt4.QtCore import *
  26. from PyQt4.QtGui import *
  27. from qubes.qubes import QubesVmCollection
  28. from qubes.qubes import QubesException
  29. from qubes.qubes import QubesDaemonPidfile
  30. from qubes.qubes import QubesHost
  31. from qubes import qubesutils
  32. import qubesmanager.resources_rc
  33. from pyinotify import WatchManager, Notifier, ThreadedNotifier, EventsCodes, ProcessEvent
  34. import subprocess
  35. import time
  36. from thread_monitor import *
  37. from operator import itemgetter
  38. from datetime import datetime
  39. from string import replace
  40. from ui_backupdlg import *
  41. from multiselectwidget import *
  42. from backup_utils import *
  43. import grp,pwd
  44. class BackupVMsWindow(Ui_Backup, QWizard):
  45. __pyqtSignals__ = ("backup_progress(int)",)
  46. def __init__(self, app, qvm_collection, blk_manager, shutdown_vm_func, parent=None):
  47. super(BackupVMsWindow, self).__init__(parent)
  48. self.app = app
  49. self.qvm_collection = qvm_collection
  50. self.blk_manager = blk_manager
  51. self.shutdown_vm_func = shutdown_vm_func
  52. self.dev_mount_path = None
  53. self.backup_dir = None
  54. self.func_output = []
  55. self.excluded = []
  56. for vm in self.qvm_collection.values():
  57. if vm.qid == 0:
  58. self.vm = vm
  59. break;
  60. assert self.vm != None
  61. self.setupUi(self)
  62. self.show_running_vms_warning(False)
  63. self.dir_line_edit.setReadOnly(True)
  64. self.select_vms_widget = MultiSelectWidget(self)
  65. self.verticalLayout.insertWidget(1, self.select_vms_widget)
  66. self.connect(self, SIGNAL("currentIdChanged(int)"), self.current_page_changed)
  67. self.connect(self.select_vms_widget, SIGNAL("selected_changed()"), self.check_running)
  68. self.connect(self.select_vms_widget, SIGNAL("items_removed(list)"), self.vms_removed)
  69. self.connect(self.select_vms_widget, SIGNAL("items_added(list)"), self.vms_added)
  70. self.refresh_button.clicked.connect(self.check_running)
  71. self.shutdown_running_vms_button.clicked.connect(self.shutdown_all_running_selected)
  72. self.connect(self.dev_combobox, SIGNAL("activated(int)"), self.dev_combobox_activated)
  73. self.connect(self, SIGNAL("backup_progress(int)"), self.progress_bar.setValue)
  74. self.select_vms_page.isComplete = self.has_selected_vms
  75. self.select_dir_page.isComplete = self.has_selected_dir
  76. #FIXME
  77. #this causes to run isComplete() twice, I don't know why
  78. self.select_vms_page.connect(self.select_vms_widget, SIGNAL("selected_changed()"), SIGNAL("completeChanged()"))
  79. self.total_size = 0
  80. self.__fill_vms_list__()
  81. fill_devs_list(self)
  82. def show_running_vms_warning(self, show):
  83. self.running_vms_warning.setVisible(show)
  84. self.shutdown_running_vms_button.setVisible(show)
  85. self.refresh_button.setVisible(show)
  86. class VmListItem(QListWidgetItem):
  87. def __init__(self, vm):
  88. self.vm = vm
  89. if vm.qid == 0:
  90. local_user = grp.getgrnam('qubes').gr_mem[0]
  91. home_dir = pwd.getpwnam(local_user).pw_dir
  92. self.size = qubesutils.get_disk_usage(home_dir)
  93. else:
  94. self.size = self.get_vm_size(vm)
  95. super(BackupVMsWindow.VmListItem, self).__init__(vm.name+ " (" + qubesutils.size_to_human(self.size) + ")")
  96. def get_vm_size(self, vm):
  97. size = 0
  98. if vm.private_img is not None:
  99. size += vm.get_disk_usage (vm.private_img)
  100. if vm.updateable:
  101. size += vm.get_disk_usage(vm.root_img)
  102. return size
  103. def __fill_vms_list__(self):
  104. for vm in self.qvm_collection.values():
  105. if vm.is_appvm() and vm.internal:
  106. continue
  107. if vm.is_template() and vm.installed_by_rpm:
  108. continue
  109. item = BackupVMsWindow.VmListItem(vm)
  110. if vm.include_in_backups == True:
  111. self.select_vms_widget.selected_list.addItem(item)
  112. self.total_size += item.size
  113. else:
  114. self.select_vms_widget.available_list.addItem(item)
  115. self.check_running()
  116. self.total_size_label.setText(qubesutils.size_to_human(self.total_size))
  117. def vms_added(self, items):
  118. for i in items:
  119. self.total_size += i.size
  120. self.total_size_label.setText(qubesutils.size_to_human(self.total_size))
  121. def vms_removed(self, items):
  122. for i in items:
  123. self.total_size -= i.size
  124. self.total_size_label.setText(qubesutils.size_to_human(self.total_size))
  125. def check_running(self):
  126. some_selected_vms_running = False
  127. for i in range(self.select_vms_widget.selected_list.count()):
  128. item = self.select_vms_widget.selected_list.item(i)
  129. if item.vm.is_running() and item.vm.qid != 0:
  130. item.setForeground(QBrush(QColor(255, 0, 0)))
  131. some_selected_vms_running = True
  132. else:
  133. item.setForeground(QBrush(QColor(0, 0, 0)))
  134. self.show_running_vms_warning(some_selected_vms_running)
  135. for i in range(self.select_vms_widget.available_list.count()):
  136. item = self.select_vms_widget.available_list.item(i)
  137. if item.vm.is_running() and item.vm.qid != 0:
  138. item.setForeground(QBrush(QColor(255, 0, 0)))
  139. else:
  140. item.setForeground(QBrush(QColor(0, 0, 0)))
  141. return some_selected_vms_running
  142. def shutdown_all_running_selected(self):
  143. names = []
  144. vms = []
  145. for i in range(self.select_vms_widget.selected_list.count()):
  146. item = self.select_vms_widget.selected_list.item(i)
  147. if item.vm.is_running() and item.vm.qid != 0:
  148. names.append(item.vm.name)
  149. vms.append(item.vm)
  150. if len(vms) == 0:
  151. return;
  152. reply = QMessageBox.question(None, "VM Shutdown Confirmation",
  153. "Are you sure you want to power down the following VMs: <b>{0}</b>?<br>"
  154. "<small>This will shutdown all the running applications within them.</small>".format(', '.join(names)),
  155. QMessageBox.Yes | QMessageBox.Cancel)
  156. self.app.processEvents()
  157. if reply == QMessageBox.Yes:
  158. for vm in vms:
  159. self.shutdown_vm_func(vm)
  160. progress = QProgressDialog ("Shutting down VMs <b>{0}</b>...".format(', '.join(names)), "", 0, 0)
  161. progress.setModal(True)
  162. progress.show()
  163. wait_time = 15.0
  164. wait_for = wait_time
  165. while self.check_running() and wait_for > 0:
  166. self.app.processEvents()
  167. time.sleep (0.1)
  168. wait_for -= 0.1
  169. progress.hide()
  170. if self.check_running():
  171. QMessageBox.information(None, "Strange", "Could not power down the VMs in {0} seconds...".format(wait_time))
  172. def dev_combobox_activated(self, idx):
  173. dev_combobox_activated(self, idx)
  174. @pyqtSlot(name='on_select_path_button_clicked')
  175. def select_path_button_clicked(self):
  176. select_path_button_clicked(self)
  177. def validateCurrentPage(self):
  178. if self.currentPage() is self.select_vms_page:
  179. for i in range(self.select_vms_widget.selected_list.count()):
  180. if self.check_running() == True:
  181. QMessageBox.information(None, "Wait!", "Some selected VMs are running. Running VMs can not be backuped. Please shut them down or remove them from the list.")
  182. return False
  183. del self.excluded[:]
  184. for i in range(self.select_vms_widget.available_list.count()):
  185. vmname = self.select_vms_widget.available_list.item(i).vm.name
  186. self.excluded.append(vmname)
  187. return True
  188. def gather_output(self, s):
  189. self.func_output.append(s)
  190. def update_progress_bar(self, value):
  191. self.emit(SIGNAL("backup_progress(int)"), value)
  192. def __do_backup__(self, thread_monitor):
  193. msg = []
  194. try:
  195. qubesutils.backup_do(str(self.backup_dir), self.files_to_backup, self.update_progress_bar)
  196. #simulate_long_lasting_proces(10, self.update_progress_bar)
  197. except Exception as ex:
  198. msg.append(str(ex))
  199. if len(msg) > 0 :
  200. thread_monitor.set_error_msg('\n'.join(msg))
  201. thread_monitor.set_finished()
  202. def current_page_changed(self, id):
  203. if self.currentPage() is self.confirm_page:
  204. del self.func_output[:]
  205. try:
  206. self.files_to_backup = qubesutils.backup_prepare(str(self.backup_dir), exclude_list = self.excluded, print_callback = self.gather_output)
  207. except Exception as ex:
  208. QMessageBox.critical(None, "Error while prepering backup.", "ERROR: {0}".format(ex))
  209. self.textEdit.setReadOnly(True)
  210. self.textEdit.setFontFamily("Monospace")
  211. self.textEdit.setText("\n".join(self.func_output))
  212. elif self.currentPage() is self.commit_page:
  213. self.button(self.CancelButton).setDisabled(True)
  214. self.button(self.FinishButton).setDisabled(True)
  215. self.thread_monitor = ThreadMonitor()
  216. thread = threading.Thread (target= self.__do_backup__ , args=(self.thread_monitor,))
  217. thread.daemon = True
  218. thread.start()
  219. while not self.thread_monitor.is_finished():
  220. self.app.processEvents()
  221. time.sleep (0.1)
  222. if not self.thread_monitor.success:
  223. QMessageBox.warning (None, "Backup error!", "ERROR: {1}".format(self.vm.name, self.thread_monitor.error_msg))
  224. if self.dev_mount_path != None:
  225. umount_device(self.dev_mount_path)
  226. self.button(self.FinishButton).setEnabled(True)
  227. def reject(self):
  228. if self.dev_mount_path != None:
  229. umount_device(self.dev_mount_path)
  230. self.done(0)
  231. def has_selected_vms(self):
  232. return self.select_vms_widget.selected_list.count() > 0
  233. def has_selected_dir(self):
  234. return self.backup_dir != None
  235. # Bases on the original code by:
  236. # Copyright (c) 2002-2007 Pascal Varet <p.varet@gmail.com>
  237. def handle_exception( exc_type, exc_value, exc_traceback ):
  238. import sys
  239. import os.path
  240. import traceback
  241. filename, line, dummy, dummy = traceback.extract_tb( exc_traceback ).pop()
  242. filename = os.path.basename( filename )
  243. error = "%s: %s" % ( exc_type.__name__, exc_value )
  244. QMessageBox.critical(None, "Houston, we have a problem...",
  245. "Whoops. A critical error has occured. This is most likely a bug "
  246. "in Qubes Restore VMs application.<br><br>"
  247. "<b><i>%s</i></b>" % error +
  248. "at <b>line %d</b> of file <b>%s</b>.<br/><br/>"
  249. % ( line, filename ))
  250. def main():
  251. global qubes_host
  252. qubes_host = QubesHost()
  253. global app
  254. app = QApplication(sys.argv)
  255. app.setOrganizationName("The Qubes Project")
  256. app.setOrganizationDomain("http://qubes-os.org")
  257. app.setApplicationName("Qubes Backup VMs")
  258. sys.excepthook = handle_exception
  259. qvm_collection = QubesVmCollection()
  260. qvm_collection.lock_db_for_reading()
  261. qvm_collection.load()
  262. qvm_collection.unlock_db()
  263. global backup_window
  264. backup_window = BackupVMsWindow()
  265. backup_window.show()
  266. app.exec_()
  267. app.exit()
  268. if __name__ == "__main__":
  269. main()