qvm_backup_restore.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. #
  2. # The Qubes OS Project, http://www.qubes-os.org
  3. #
  4. # Copyright (C) 2016 Marek Marczykowski-Górecki
  5. # <marmarek@invisiblethingslab.com>
  6. #
  7. # This program is free software; you can redistribute it and/or modify
  8. # it under the terms of the GNU Lesser General Public License as published by
  9. # the Free Software Foundation; either version 2.1 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # This program is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU Lesser General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU Lesser General Public License along
  18. # with this program; if not, write to the Free Software Foundation, Inc.,
  19. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  20. '''Console frontend for backup restore code'''
  21. import getpass
  22. import sys
  23. from qubesadmin.backup.restore import BackupRestore
  24. import qubesadmin.exc
  25. import qubesadmin.tools
  26. import qubesadmin.utils
  27. parser = qubesadmin.tools.QubesArgumentParser()
  28. parser.add_argument("--verify-only", action="store_true",
  29. dest="verify_only", default=False,
  30. help="Verify backup integrity without restoring any "
  31. "data")
  32. parser.add_argument("--skip-broken", action="store_true", dest="skip_broken",
  33. default=False,
  34. help="Do not restore VMs that have missing TemplateVMs "
  35. "or NetVMs")
  36. parser.add_argument("--ignore-missing", action="store_true",
  37. dest="ignore_missing", default=False,
  38. help="Restore VMs even if their associated TemplateVMs "
  39. "and NetVMs are missing")
  40. parser.add_argument("--skip-conflicting", action="store_true",
  41. dest="skip_conflicting", default=False,
  42. help="Do not restore VMs that are already present on "
  43. "the host")
  44. parser.add_argument("--rename-conflicting", action="store_true",
  45. dest="rename_conflicting", default=False,
  46. help="Restore VMs that are already present on the host "
  47. "under different names")
  48. parser.add_argument("-x", "--exclude", action="append", dest="exclude",
  49. default=[],
  50. help="Skip restore of specified VM (may be repeated)")
  51. parser.add_argument("--skip-dom0-home", action="store_false", dest="dom0_home",
  52. default=True,
  53. help="Do not restore dom0 user home directory")
  54. parser.add_argument("--ignore-username-mismatch", action="store_true",
  55. dest="ignore_username_mismatch", default=False,
  56. help="Ignore dom0 username mismatch when restoring home "
  57. "directory")
  58. parser.add_argument("--ignore-size-limit", action="store_true",
  59. dest="ignore_size_limit", default=False,
  60. help="Ignore size limit calculated from backup metadata")
  61. parser.add_argument("--compression-filter", "-Z", action="store",
  62. dest="compression",
  63. help="Force specific compression filter program, "
  64. "instead of the one from the backup header")
  65. parser.add_argument("-d", "--dest-vm", action="store", dest="appvm",
  66. help="Specify VM containing the backup to be restored")
  67. parser.add_argument("-p", "--passphrase-file", action="store",
  68. dest="pass_file", default=None,
  69. help="Read passphrase from file, or use '-' to read from stdin")
  70. parser.add_argument('backup_location', action='store',
  71. help="Backup directory name, or command to pipe from")
  72. parser.add_argument('vms', nargs='*', action='store', default=[],
  73. help='Restore only those VMs')
  74. def handle_broken(app, args, restore_info):
  75. '''Display information about problems with VMs selected for resetore'''
  76. there_are_conflicting_vms = False
  77. there_are_missing_templates = False
  78. there_are_missing_netvms = False
  79. dom0_username_mismatch = False
  80. for vm_info in restore_info.values():
  81. assert isinstance(vm_info, BackupRestore.VMToRestore)
  82. if BackupRestore.VMToRestore.EXCLUDED in \
  83. vm_info.problems:
  84. continue
  85. if BackupRestore.VMToRestore.MISSING_TEMPLATE in \
  86. vm_info.problems:
  87. there_are_missing_templates = True
  88. if BackupRestore.VMToRestore.MISSING_NETVM in \
  89. vm_info.problems:
  90. there_are_missing_netvms = True
  91. if BackupRestore.VMToRestore.ALREADY_EXISTS in \
  92. vm_info.problems:
  93. there_are_conflicting_vms = True
  94. if BackupRestore.Dom0ToRestore.USERNAME_MISMATCH in \
  95. vm_info.problems:
  96. dom0_username_mismatch = True
  97. if there_are_conflicting_vms:
  98. app.log.error(
  99. "*** There are VMs with conflicting names on the host! ***")
  100. if args.skip_conflicting:
  101. app.log.error(
  102. "Those VMs will not be restored. "
  103. "The host VMs will NOT be overwritten.")
  104. else:
  105. raise qubesadmin.exc.QubesException(
  106. "Remove VMs with conflicting names from the host "
  107. "before proceeding.\n"
  108. "Or use --skip-conflicting to restore only those VMs that "
  109. "do not exist on the host.\n"
  110. "Or use --rename-conflicting to restore those VMs under "
  111. "modified names (with numbers at the end).")
  112. if args.verify_only:
  113. app.log.info("The above VM archive(s) will be verified.")
  114. app.log.info("Existing VMs will NOT be removed or altered.")
  115. else:
  116. app.log.info("The above VMs will be copied and added to your system.")
  117. app.log.info("Exisiting VMs will NOT be removed.")
  118. if there_are_missing_templates:
  119. app.log.warning("*** One or more TemplateVMs are missing on the "
  120. "host! ***")
  121. if not (args.skip_broken or args.ignore_missing):
  122. raise qubesadmin.exc.QubesException(
  123. "Install them before proceeding with the restore."
  124. "Or pass: --skip-broken or --ignore-missing.")
  125. if args.skip_broken:
  126. app.log.warning("Skipping broken entries: VMs that depend on "
  127. "missing TemplateVMs will NOT be restored.")
  128. elif args.ignore_missing:
  129. app.log.warning("Ignoring missing entries: VMs that depend "
  130. "on missing TemplateVMs will have default value "
  131. "assigned.")
  132. else:
  133. raise qubesadmin.exc.QubesException(
  134. "INTERNAL ERROR! Please report this to the Qubes OS team!")
  135. if there_are_missing_netvms:
  136. app.log.warning("*** One or more NetVMs are missing on the "
  137. "host! ***")
  138. if not (args.skip_broken or args.ignore_missing):
  139. raise qubesadmin.exc.QubesException(
  140. "Install them before proceeding with the restore."
  141. "Or pass: --skip-broken or --ignore-missing.")
  142. if args.skip_broken:
  143. app.log.warning("Skipping broken entries: VMs that depend on "
  144. "missing NetVMs will NOT be restored.")
  145. elif args.ignore_missing:
  146. app.log.warning("Ignoring missing entries: VMs that depend "
  147. "on missing NetVMs will have default value assigned.")
  148. else:
  149. raise qubesadmin.exc.QubesException(
  150. "INTERNAL ERROR! Please report this to the Qubes OS team!")
  151. if 'dom0' in restore_info.keys() and args.dom0_home \
  152. and not args.verify_only:
  153. if dom0_username_mismatch:
  154. app.log.warning("*** Dom0 username mismatch! This can break "
  155. "some settings! ***")
  156. if not args.ignore_username_mismatch:
  157. raise qubesadmin.exc.QubesException(
  158. "Skip restoring the dom0 home directory "
  159. "(--skip-dom0-home), or pass "
  160. "--ignore-username-mismatch to continue anyway.")
  161. app.log.warning("Continuing as directed.")
  162. app.log.warning("NOTE: The archived dom0 home directory "
  163. "will be restored to a new directory "
  164. "'home-restore-<current-time>' "
  165. "created inside the dom0 home directory. Restored "
  166. "files should be copied or moved out of the new "
  167. "directory before using them.")
  168. def main(args=None, app=None):
  169. '''Main function of qvm-backup-restore'''
  170. # pylint: disable=too-many-return-statements
  171. args = parser.parse_args(args, app=app)
  172. appvm = None
  173. if args.appvm:
  174. try:
  175. appvm = args.app.domains[args.appvm]
  176. except KeyError:
  177. parser.error('no such domain: {!r}'.format(args.appvm))
  178. if args.pass_file is not None:
  179. pass_f = open(args.pass_file) if args.pass_file != "-" else sys.stdin
  180. passphrase = pass_f.readline().rstrip()
  181. if pass_f is not sys.stdin:
  182. pass_f.close()
  183. else:
  184. passphrase = getpass.getpass("Please enter the passphrase to verify "
  185. "and (if encrypted) decrypt the backup: ")
  186. args.app.log.info("Checking backup content...")
  187. try:
  188. backup = BackupRestore(args.app, args.backup_location,
  189. appvm, passphrase,
  190. force_compression_filter=args.compression)
  191. except qubesadmin.exc.QubesException as e:
  192. parser.error_runtime(str(e))
  193. # unreachable - error_runtime will raise SystemExit
  194. return 1
  195. backup.options.use_default_template = args.ignore_missing
  196. backup.options.use_default_netvm = args.ignore_missing
  197. backup.options.rename_conflicting = args.rename_conflicting
  198. backup.options.dom0_home = args.dom0_home
  199. backup.options.ignore_username_mismatch = args.ignore_username_mismatch
  200. backup.options.ignore_size_limit = args.ignore_size_limit
  201. backup.options.exclude = args.exclude
  202. backup.options.verify_only = args.verify_only
  203. restore_info = None
  204. try:
  205. restore_info = backup.get_restore_info()
  206. except qubesadmin.exc.QubesException as e:
  207. parser.error_runtime(str(e))
  208. if args.vms:
  209. # use original name here, not renamed
  210. backup.options.exclude += [vm_info.vm.name
  211. for vm_info in restore_info.values()
  212. if vm_info.vm.name not in args.vms]
  213. restore_info = backup.restore_info_verify(restore_info)
  214. print(backup.get_restore_summary(restore_info))
  215. try:
  216. handle_broken(args.app, args, restore_info)
  217. except qubesadmin.exc.QubesException as e:
  218. parser.error_runtime(str(e))
  219. if args.pass_file is None:
  220. if input("Do you want to proceed? [y/N] ").upper() != "Y":
  221. sys.exit(0)
  222. try:
  223. backup.restore_do(restore_info)
  224. except qubesadmin.exc.QubesException as e:
  225. parser.error_runtime(str(e))
  226. if __name__ == '__main__':
  227. main()