qvm-backup-restore 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. #!/usr/bin/python2
  2. # -*- encoding: utf8 -*-
  3. #
  4. # The Qubes OS Project, http://www.qubes-os.org
  5. #
  6. # Copyright (C) 2010 Joanna Rutkowska <joanna@invisiblethingslab.com>
  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. from multiprocessing import Event
  24. from qubes.qubes import QubesVmCollection
  25. from qubes.qubes import QubesException
  26. from qubes.backup import backup_restore_header
  27. from qubes.backup import backup_restore_prepare
  28. from qubes.backup import backup_restore_print_summary
  29. from qubes.backup import backup_restore_do
  30. import qubes.backup
  31. import sys
  32. from optparse import OptionParser
  33. from locale import getpreferredencoding
  34. import os
  35. import sys
  36. import getpass
  37. def main():
  38. usage = "usage: %prog [options] <backup-dir> [vms-to-be-restored ...]"
  39. parser = OptionParser (usage)
  40. parser.add_option ("--verify-only", action="store_true",
  41. dest="verify_only", default=False,
  42. help="Verify backup integrity without restoring any "
  43. "data")
  44. parser.add_option ("--skip-broken", action="store_true", dest="skip_broken", default=False,
  45. help="Do not restore VMs that have missing TemplateVMs "
  46. "or NetVMs")
  47. parser.add_option ("--ignore-missing", action="store_true", dest="ignore_missing", default=False,
  48. help="Restore VMs even if their associated TemplateVMs "
  49. "and NetVMs are missing")
  50. parser.add_option ("--skip-conflicting", action="store_true", dest="skip_conflicting", default=False,
  51. help="Do not restore VMs that are already present on "
  52. "the host")
  53. parser.add_option ("--rename-conflicting", action="store_true",
  54. dest="rename_conflicting", default=False,
  55. help="Restore VMs that are already present on the host "
  56. "under different names")
  57. parser.add_option ("--force-root", action="store_true", dest="force_root", default=False,
  58. help="Force to run with root privileges")
  59. parser.add_option ("--replace-template", action="append", dest="replace_template", default=[],
  60. help="Restore VMs using another TemplateVM; syntax: "
  61. "old-template-name:new-template-name (may be "
  62. "repeated)")
  63. parser.add_option ("-x", "--exclude", action="append", dest="exclude", default=[],
  64. help="Skip restore of specified VM (may be repeated)")
  65. parser.add_option ("--skip-dom0-home", action="store_false", dest="dom0_home", default=True,
  66. help="Do not restore dom0 user home directory")
  67. parser.add_option ("--ignore-username-mismatch", action="store_true", dest="ignore_username_mismatch", default=False,
  68. help="Ignore dom0 username mismatch when restoring home "
  69. "directory")
  70. parser.add_option ("-d", "--dest-vm", action="store", dest="appvm",
  71. help="Specify VM containing the backup to be restored")
  72. parser.add_option ("-e", "--encrypted", action="store_true", dest="decrypt", default=False,
  73. help="The backup is encrypted")
  74. parser.add_option ("-p", "--passphrase-file", action="store",
  75. dest="pass_file", default=None,
  76. help="Read passphrase from file, or use '-' to read from stdin")
  77. parser.add_option ("-z", "--compressed", action="store_true", dest="compressed", default=False,
  78. help="The backup is compressed")
  79. parser.add_option ("--debug", action="store_true", dest="debug",
  80. default=False, help="Enable (a lot of) debug output")
  81. (options, args) = parser.parse_args ()
  82. if (len (args) < 1):
  83. print >> sys.stderr, "You must specify the backup directory "\
  84. "(e.g. /mnt/backup/qubes-2010-12-01-235959)"
  85. exit (0)
  86. backup_dir = args[0]
  87. vmlist = args[1:]
  88. #if not os.path.exists (backup_dir):
  89. # print >> sys.stderr, "The backup directory doesn't exist!"
  90. # exit(1)
  91. host_collection = QubesVmCollection()
  92. host_collection.lock_db_for_writing()
  93. host_collection.load()
  94. restore_options = {}
  95. if options.ignore_missing:
  96. restore_options['use-default-template'] = True
  97. restore_options['use-default-netvm'] = True
  98. if options.replace_template:
  99. restore_options['replace-template'] = options.replace_template
  100. if options.rename_conflicting:
  101. restore_options['rename-conflicting'] = True
  102. if not options.dom0_home:
  103. restore_options['dom0-home'] = False
  104. if options.ignore_username_mismatch:
  105. restore_options['ignore-username-mismatch'] = True
  106. if options.exclude:
  107. restore_options['exclude'] = options.exclude
  108. if options.verify_only:
  109. restore_options['verify-only'] = True
  110. if options.debug:
  111. qubes.backup.BACKUP_DEBUG = True
  112. appvm = None
  113. if options.appvm is not None:
  114. appvm = host_collection.get_vm_by_name(options.appvm)
  115. if appvm is None:
  116. print >>sys.stderr, "ERROR: VM {0} does not exist".format(options.appvm)
  117. exit(1)
  118. if options.pass_file is not None:
  119. f = open(options.pass_file) if options.pass_file != "-" else sys.stdin
  120. passphrase = f.readline().rstrip()
  121. if f is not sys.stdin:
  122. f.close()
  123. else:
  124. passphrase = getpass.getpass("Please enter the passphrase to verify "
  125. "and (if encrypted) decrypt the backup: ")
  126. encoding = sys.stdin.encoding or getpreferredencoding()
  127. passphrase = passphrase.decode(encoding)
  128. print >> sys.stderr, "Checking backup content..."
  129. error_detected = Event()
  130. def error_callback(message):
  131. error_detected.set()
  132. print >> sys.stderr, message
  133. restore_info = None
  134. try:
  135. restore_info = backup_restore_prepare(
  136. backup_dir,
  137. passphrase=passphrase,
  138. options=restore_options,
  139. host_collection=host_collection,
  140. encrypted=options.decrypt,
  141. compressed=options.compressed,
  142. appvm=appvm,
  143. error_callback=error_callback)
  144. except QubesException as e:
  145. print >> sys.stderr, "ERROR: %s" % str(e)
  146. exit(1)
  147. if len(vmlist) > 0:
  148. for vm in restore_info.keys():
  149. if vm.startswith('$'):
  150. continue
  151. if not vm in vmlist:
  152. restore_info.pop(vm)
  153. backup_restore_print_summary(restore_info)
  154. there_are_conflicting_vms = False
  155. there_are_missing_templates = False
  156. there_are_missing_netvms = False
  157. dom0_username_mismatch = False
  158. for vm_info in restore_info.values():
  159. if 'excluded' in vm_info and vm_info['excluded']:
  160. continue
  161. if 'missing-template' in vm_info.keys():
  162. there_are_missing_templates = True
  163. if 'missing-netvm' in vm_info.keys():
  164. there_are_missing_netvms = True
  165. if 'already-exists' in vm_info.keys():
  166. there_are_conflicting_vms = True
  167. if 'username-mismatch' in vm_info.keys():
  168. dom0_username_mismatch = True
  169. print
  170. if hasattr(os, "geteuid") and os.geteuid() == 0:
  171. print >> sys.stderr, "*** Running this tool as root is strongly "\
  172. "discouraged. This will lead to permissions "\
  173. "problems."
  174. if options.force_root:
  175. print >> sys.stderr, "Continuing as commanded. You have been "\
  176. "warned."
  177. else:
  178. print >> sys.stderr, "Retry as an unprivileged user, or use "\
  179. "--force-root to continue anyway."
  180. exit(1)
  181. if there_are_conflicting_vms:
  182. print >> sys.stderr, "*** There are VMs with conflicting names on the "\
  183. "host! ***"
  184. if options.skip_conflicting:
  185. print >> sys.stderr, "Those VMs will not be restored. The host "\
  186. "VMs will NOT be overwritten."
  187. else:
  188. print >> sys.stderr, "Remove VMs with conflicting names from the "\
  189. "host before proceeding."
  190. print >> sys.stderr, "Or use --skip-conflicting to restore only "\
  191. "those VMs that do not exist on the host."
  192. print >> sys.stderr, "Or use --rename-conflicting to restore " \
  193. "those VMs under modified names (with "\
  194. "numbers at the end)."
  195. exit (1)
  196. print "The above VMs will be copied and added to your system."
  197. print "Exisiting VMs will NOT be removed."
  198. if there_are_missing_templates:
  199. print >> sys.stderr, "*** One or more TemplateVMs are missing on the"\
  200. "host! ***"
  201. if not (options.skip_broken or options.ignore_missing):
  202. print >> sys.stderr, "Install them before proceeding with the "\
  203. "restore."
  204. print >> sys.stderr, "Or pass: --skip-broken or --ignore-missing."
  205. exit (1)
  206. elif options.skip_broken:
  207. print >> sys.stderr, "Skipping broken entries: VMs that depend on "\
  208. "missing TemplateVMs will NOT be restored."
  209. elif options.ignore_missing:
  210. print >> sys.stderr, "Ignoring missing entries: VMs that depend "\
  211. "on missing TemplateVMs will NOT be restored."
  212. else:
  213. print >> sys.stderr, "INTERNAL ERROR! Please report this to the "\
  214. "Qubes OS team!"
  215. exit (1)
  216. if there_are_missing_netvms:
  217. print >> sys.stderr, "*** One or more NetVMs are missing on the "\
  218. "host! ***"
  219. if not (options.skip_broken or options.ignore_missing):
  220. print >> sys.stderr, "Install them before proceeding with the "\
  221. "restore."
  222. print >> sys.stderr, "Or pass: --skip-broken or --ignore-missing."
  223. exit (1)
  224. elif options.skip_broken:
  225. print >> sys.stderr, "Skipping broken entries: VMs that depend on "\
  226. "missing NetVMs will NOT be restored."
  227. elif options.ignore_missing:
  228. print >> sys.stderr, "Ignoring missing entries: VMs that depend "\
  229. "on missing NetVMs will NOT be restored."
  230. else:
  231. print >> sys.stderr, "INTERNAL ERROR! Please report this to the "\
  232. "Qubes OS team!"
  233. exit (1)
  234. if 'dom0' in restore_info.keys() and options.dom0_home:
  235. if dom0_username_mismatch:
  236. print >> sys.stderr, "*** Dom0 username mismatch! This can break "\
  237. "some settings! ***"
  238. if not options.ignore_username_mismatch:
  239. print >> sys.stderr, "Skip restoring the dom0 home directory "\
  240. "(--skip-dom0-home), or pass "\
  241. "--ignore-username-mismatch to continue "\
  242. "anyway."
  243. exit(1)
  244. else:
  245. print >> sys.stderr, "Continuing as directed."
  246. print >> sys.stderr, "NOTE: Before restoring the dom0 home directory, "\
  247. "a new directory named "\
  248. "'home-pre-restore-<current-time>' will be "\
  249. "created inside the dom0 home directory. If any "\
  250. "restored files conflict with existing files, "\
  251. "the existing files will be moved to this new "\
  252. "directory."
  253. if options.pass_file is None:
  254. if raw_input("Do you want to proceed? [y/N] ").upper() != "Y":
  255. exit(0)
  256. try:
  257. backup_restore_do(restore_info,
  258. host_collection=host_collection,
  259. error_callback=error_callback)
  260. except QubesException as e:
  261. print >> sys.stderr, "ERROR: %s" % str(e)
  262. host_collection.unlock_db()
  263. if error_detected.is_set():
  264. print "-> Completed with errors!"
  265. exit(1)
  266. else:
  267. print "-> Done."
  268. main()