restore.py 76 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921
  1. # -*- encoding: utf8 -*-
  2. #
  3. # The Qubes OS Project, http://www.qubes-os.org
  4. #
  5. # Copyright (C) 2017 Marek Marczykowski-Górecki
  6. # <marmarek@invisiblethingslab.com>
  7. #
  8. # This program is free software; you can redistribute it and/or modify
  9. # it under the terms of the GNU Lesser General Public License as published by
  10. # the Free Software Foundation; either version 2.1 of the License, or
  11. # (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 Lesser 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. '''Backup restore module'''
  21. import errno
  22. import fcntl
  23. import functools
  24. import grp
  25. import logging
  26. import multiprocessing
  27. from multiprocessing import Queue, Process
  28. import os
  29. import pwd
  30. import re
  31. import shutil
  32. import subprocess
  33. import sys
  34. import tempfile
  35. import termios
  36. import time
  37. import qubesadmin
  38. import qubesadmin.vm
  39. from qubesadmin.backup import BackupVM
  40. from qubesadmin.backup.core2 import Core2Qubes
  41. from qubesadmin.backup.core3 import Core3Qubes
  42. from qubesadmin.devices import DeviceAssignment
  43. from qubesadmin.exc import QubesException
  44. from qubesadmin.utils import size_to_human
  45. # must be picklable
  46. QUEUE_FINISHED = "!!!FINISHED"
  47. QUEUE_ERROR = "!!!ERROR"
  48. HEADER_FILENAME = 'backup-header'
  49. DEFAULT_CRYPTO_ALGORITHM = 'aes-256-cbc'
  50. # 'scrypt' is not exactly HMAC algorithm, but a tool we use to
  51. # integrity-protect the data
  52. DEFAULT_HMAC_ALGORITHM = 'scrypt'
  53. DEFAULT_COMPRESSION_FILTER = 'gzip'
  54. # Maximum size of error message get from process stderr (including VM process)
  55. MAX_STDERR_BYTES = 1024
  56. # header + qubes.xml max size
  57. HEADER_QUBES_XML_MAX_SIZE = 1024 * 1024
  58. # hmac file max size - regardless of backup format version!
  59. HMAC_MAX_SIZE = 4096
  60. BLKSIZE = 512
  61. _re_alphanum = re.compile(r'^[A-Za-z0-9-]*$')
  62. _tar_msg_re = re.compile(r".*#[0-9].*restore_pipe")
  63. _tar_file_size_re = re.compile(r"^[^ ]+ [^ ]+/[^ ]+ *([0-9]+) .*")
  64. class BackupCanceledError(QubesException):
  65. '''Exception raised when backup/restore was cancelled'''
  66. def __init__(self, msg, tmpdir=None):
  67. super(BackupCanceledError, self).__init__(msg)
  68. self.tmpdir = tmpdir
  69. class BackupHeader(object):
  70. '''Structure describing backup-header file included as the first file in
  71. backup archive
  72. '''
  73. header_keys = {
  74. 'version': 'version',
  75. 'encrypted': 'encrypted',
  76. 'compressed': 'compressed',
  77. 'compression-filter': 'compression_filter',
  78. 'crypto-algorithm': 'crypto_algorithm',
  79. 'hmac-algorithm': 'hmac_algorithm',
  80. 'backup-id': 'backup_id'
  81. }
  82. bool_options = ['encrypted', 'compressed']
  83. int_options = ['version']
  84. def __init__(self,
  85. header_data=None,
  86. version=None,
  87. encrypted=None,
  88. compressed=None,
  89. compression_filter=None,
  90. hmac_algorithm=None,
  91. crypto_algorithm=None,
  92. backup_id=None):
  93. # repeat the list to help code completion...
  94. self.version = version
  95. self.encrypted = encrypted
  96. self.compressed = compressed
  97. # Options introduced in backup format 3+, which always have a header,
  98. # so no need for fallback in function parameter
  99. self.compression_filter = compression_filter
  100. self.hmac_algorithm = hmac_algorithm
  101. self.crypto_algorithm = crypto_algorithm
  102. self.backup_id = backup_id
  103. if header_data is not None:
  104. self.load(header_data)
  105. def load(self, untrusted_header_text):
  106. """Parse backup header file.
  107. :param untrusted_header_text: header content
  108. :type untrusted_header_text: basestring
  109. .. warning::
  110. This function may be exposed to not yet verified header,
  111. so is security critical.
  112. """
  113. try:
  114. untrusted_header_text = untrusted_header_text.decode('ascii')
  115. except UnicodeDecodeError:
  116. raise QubesException(
  117. "Non-ASCII characters in backup header")
  118. for untrusted_line in untrusted_header_text.splitlines():
  119. if untrusted_line.count('=') != 1:
  120. raise QubesException("Invalid backup header")
  121. key, value = untrusted_line.strip().split('=', 1)
  122. if not _re_alphanum.match(key):
  123. raise QubesException("Invalid backup header ("
  124. "key)")
  125. if key not in self.header_keys.keys():
  126. # Ignoring unknown option
  127. continue
  128. if not _re_alphanum.match(value):
  129. raise QubesException("Invalid backup header ("
  130. "value)")
  131. if getattr(self, self.header_keys[key]) is not None:
  132. raise QubesException(
  133. "Duplicated header line: {}".format(key))
  134. if key in self.bool_options:
  135. value = value.lower() in ["1", "true", "yes"]
  136. elif key in self.int_options:
  137. value = int(value)
  138. setattr(self, self.header_keys[key], value)
  139. self.validate()
  140. def validate(self):
  141. '''Validate header data, according to header version'''
  142. if self.version == 1:
  143. # header not really present
  144. pass
  145. elif self.version in [2, 3, 4]:
  146. expected_attrs = ['version', 'encrypted', 'compressed',
  147. 'hmac_algorithm']
  148. if self.encrypted and self.version < 4:
  149. expected_attrs += ['crypto_algorithm']
  150. if self.version >= 3 and self.compressed:
  151. expected_attrs += ['compression_filter']
  152. if self.version >= 4:
  153. expected_attrs += ['backup_id']
  154. for key in expected_attrs:
  155. if getattr(self, key) is None:
  156. raise QubesException(
  157. "Backup header lack '{}' info".format(key))
  158. else:
  159. raise QubesException(
  160. "Unsupported backup version {}".format(self.version))
  161. def save(self, filename):
  162. '''Save backup header into a file'''
  163. with open(filename, "w") as f_header:
  164. # make sure 'version' is the first key
  165. f_header.write('version={}\n'.format(self.version))
  166. for key, attr in self.header_keys.items():
  167. if key == 'version':
  168. continue
  169. if getattr(self, attr) is None:
  170. continue
  171. f_header.write("{!s}={!s}\n".format(key, getattr(self, attr)))
  172. def launch_proc_with_pty(args, stdin=None, stdout=None, stderr=None, echo=True):
  173. """Similar to pty.fork, but handle stdin/stdout according to parameters
  174. instead of connecting to the pty
  175. :return tuple (subprocess.Popen, pty_master)
  176. """
  177. def set_ctty(ctty_fd, master_fd):
  178. '''Set controlling terminal'''
  179. os.setsid()
  180. os.close(master_fd)
  181. fcntl.ioctl(ctty_fd, termios.TIOCSCTTY, 0)
  182. if not echo:
  183. termios_p = termios.tcgetattr(ctty_fd)
  184. # termios_p.c_lflags
  185. termios_p[3] &= ~termios.ECHO
  186. termios.tcsetattr(ctty_fd, termios.TCSANOW, termios_p)
  187. (pty_master, pty_slave) = os.openpty()
  188. p = subprocess.Popen(args, stdin=stdin, stdout=stdout,
  189. stderr=stderr,
  190. preexec_fn=lambda: set_ctty(pty_slave, pty_master))
  191. os.close(pty_slave)
  192. return p, open(pty_master, 'wb+', buffering=0)
  193. def launch_scrypt(action, input_name, output_name, passphrase):
  194. '''
  195. Launch 'scrypt' process, pass passphrase to it and return
  196. subprocess.Popen object.
  197. :param action: 'enc' or 'dec'
  198. :param input_name: input path or '-' for stdin
  199. :param output_name: output path or '-' for stdout
  200. :param passphrase: passphrase
  201. :return: subprocess.Popen object
  202. '''
  203. command_line = ['scrypt', action, input_name, output_name]
  204. (p, pty) = launch_proc_with_pty(command_line,
  205. stdin=subprocess.PIPE if input_name == '-' else None,
  206. stdout=subprocess.PIPE if output_name == '-' else None,
  207. stderr=subprocess.PIPE,
  208. echo=False)
  209. if action == 'enc':
  210. prompts = (b'Please enter passphrase: ', b'Please confirm passphrase: ')
  211. else:
  212. prompts = (b'Please enter passphrase: ',)
  213. for prompt in prompts:
  214. actual_prompt = p.stderr.read(len(prompt))
  215. if actual_prompt != prompt:
  216. raise QubesException(
  217. 'Unexpected prompt from scrypt: {}'.format(actual_prompt))
  218. pty.write(passphrase.encode('utf-8') + b'\n')
  219. pty.flush()
  220. # save it here, so garbage collector would not close it (which would kill
  221. # the child)
  222. p.pty = pty
  223. return p
  224. class ExtractWorker3(Process):
  225. '''Process for handling inner tar layer of backup archive'''
  226. # pylint: disable=too-many-instance-attributes
  227. def __init__(self, queue, base_dir, passphrase, encrypted,
  228. progress_callback, vmproc=None,
  229. compressed=False, crypto_algorithm=DEFAULT_CRYPTO_ALGORITHM,
  230. compression_filter=None, verify_only=False, handlers=None):
  231. '''Start inner tar extraction worker
  232. The purpose of this class is to process files extracted from outer
  233. archive layer and pass to appropriate handlers. Input files are given
  234. through a queue. Insert :py:obj:`QUEUE_FINISHED` or
  235. :py:obj:`QUEUE_ERROR` to end data processing (either cleanly,
  236. or forcefully).
  237. Handlers are given as a map filename -> (data_func, size_func),
  238. where data_func is called with file-like object to process,
  239. and size_func is called with file size as argument. Note that
  240. data_func and size_func may be called simultaneusly, in a different
  241. processes.
  242. :param multiprocessing.Queue queue: a queue with filenames to
  243. process; those files needs to be given as full path, inside *base_dir*
  244. :param str base_dir: directory where all files to process live
  245. :param str passphrase: passphrase to decrypt the data
  246. :param bool encrypted: is encryption applied?
  247. :param callable progress_callback: report extraction progress
  248. :param subprocess.Popen vmproc: process extracting outer layer,
  249. given here to monitor
  250. it for failures (when it exits with non-zero exit code, inner layer
  251. processing is stopped)
  252. :param bool compressed: is the data compressed?
  253. :param str crypto_algorithm: encryption algorithm, either `scrypt` or an
  254. algorithm supported by openssl
  255. :param str compression_filter: compression program, `gzip` by default
  256. :param bool verify_only: only verify data integrity, do not extract
  257. :param dict handlers: handlers for actual data
  258. '''
  259. super(ExtractWorker3, self).__init__()
  260. #: queue with files to extract
  261. self.queue = queue
  262. #: paths on the queue are relative to this dir
  263. self.base_dir = base_dir
  264. #: passphrase to decrypt/authenticate data
  265. self.passphrase = passphrase
  266. #: handlers for files; it should be dict filename -> (data_function,
  267. # size_function),
  268. # where data_function will get file-like object as the only argument and
  269. # might be called in a separate process (multiprocessing.Process),
  270. # and size_function will get file size (when known) in bytes
  271. self.handlers = handlers
  272. #: is the backup encrypted?
  273. self.encrypted = encrypted
  274. #: is the backup compressed?
  275. self.compressed = compressed
  276. #: what crypto algorithm is used for encryption?
  277. self.crypto_algorithm = crypto_algorithm
  278. #: only verify integrity, don't extract anything
  279. self.verify_only = verify_only
  280. #: progress
  281. self.blocks_backedup = 0
  282. #: inner tar layer extraction (subprocess.Popen instance)
  283. self.tar2_process = None
  284. #: current inner tar archive name
  285. self.tar2_current_file = None
  286. #: cat process feeding tar2_process
  287. self.tar2_feeder = None
  288. #: decompressor subprocess.Popen instance
  289. self.decompressor_process = None
  290. #: decryptor subprocess.Popen instance
  291. self.decryptor_process = None
  292. #: data import multiprocessing.Process instance
  293. self.import_process = None
  294. #: callback reporting progress to UI
  295. self.progress_callback = progress_callback
  296. #: process (subprocess.Popen instance) feeding the data into
  297. # extraction tool
  298. self.vmproc = vmproc
  299. self.log = logging.getLogger('qubesadmin.backup.extract')
  300. self.stderr_encoding = sys.stderr.encoding or 'utf-8'
  301. self.tar2_stderr = []
  302. self.compression_filter = compression_filter
  303. def collect_tar_output(self):
  304. '''Retrieve tar stderr and handle it appropriately
  305. Log errors, process file size if requested.
  306. This use :py:attr:`tar2_process`.
  307. '''
  308. if not self.tar2_process.stderr:
  309. return
  310. if self.tar2_process.poll() is None:
  311. try:
  312. new_lines = self.tar2_process.stderr \
  313. .read(MAX_STDERR_BYTES).splitlines()
  314. except IOError as e:
  315. if e.errno == errno.EAGAIN:
  316. return
  317. else:
  318. raise
  319. else:
  320. new_lines = self.tar2_process.stderr.readlines()
  321. new_lines = [x.decode(self.stderr_encoding) for x in new_lines]
  322. debug_msg = [msg for msg in new_lines if _tar_msg_re.match(msg)]
  323. self.log.debug('tar2_stderr: %s', '\n'.join(debug_msg))
  324. new_lines = [msg for msg in new_lines if not _tar_msg_re.match(msg)]
  325. self.tar2_stderr += new_lines
  326. def run(self):
  327. try:
  328. self.__run__()
  329. except Exception:
  330. # Cleanup children
  331. for process in [self.decompressor_process,
  332. self.decryptor_process,
  333. self.tar2_process]:
  334. if process:
  335. try:
  336. process.terminate()
  337. except OSError:
  338. pass
  339. process.wait()
  340. self.log.exception('ERROR')
  341. raise
  342. def handle_dir(self, dirname):
  343. ''' Relocate files in given director when it's already extracted
  344. :param dirname: directory path to handle (relative to backup root),
  345. without trailing slash
  346. '''
  347. for fname, (data_func, size_func) in self.handlers.items():
  348. if not fname.startswith(dirname + '/'):
  349. continue
  350. if not os.path.exists(fname):
  351. # for example firewall.xml
  352. continue
  353. if size_func is not None:
  354. size_func(os.path.getsize(fname))
  355. with open(fname, 'rb') as input_file:
  356. data_func(input_file)
  357. os.unlink(fname)
  358. shutil.rmtree(dirname)
  359. def cleanup_tar2(self, wait=True, terminate=False):
  360. '''Cleanup running :py:attr:`tar2_process`
  361. :param wait: wait for it termination, otherwise method exit early if
  362. process is still running
  363. :param terminate: terminate the process if still running
  364. '''
  365. if self.tar2_process is None:
  366. return
  367. if terminate:
  368. if self.import_process is not None:
  369. self.tar2_process.terminate()
  370. self.import_process.terminate()
  371. if wait:
  372. self.tar2_process.wait()
  373. if self.import_process is not None:
  374. self.import_process.join()
  375. elif self.tar2_process.poll() is None:
  376. return
  377. self.collect_tar_output()
  378. if self.tar2_process.stderr:
  379. self.tar2_process.stderr.close()
  380. if self.tar2_process.returncode != 0:
  381. self.log.error(
  382. "ERROR: unable to extract files for %s, tar "
  383. "output:\n %s",
  384. self.tar2_current_file,
  385. "\n ".join(self.tar2_stderr))
  386. else:
  387. # Finished extracting the tar file
  388. # if that was whole-directory archive, handle
  389. # relocated files now
  390. inner_name = self.tar2_current_file.rsplit('.', 1)[0] \
  391. .replace(self.base_dir + '/', '')
  392. if os.path.basename(inner_name) == '.':
  393. self.handle_dir(
  394. os.path.dirname(inner_name))
  395. self.tar2_current_file = None
  396. self.tar2_process = None
  397. def _data_import_wrapper(self, close_fds, data_func, size_func,
  398. tar2_process):
  399. '''Close not needed file descriptors, handle output size reported
  400. by tar (if needed) then call data_func(tar2_process.stdout).
  401. This is to prevent holding write end of a pipe in subprocess,
  402. preventing EOF transfer.
  403. '''
  404. for fd in close_fds:
  405. if fd in (tar2_process.stdout.fileno(),
  406. tar2_process.stderr.fileno()):
  407. continue
  408. try:
  409. os.close(fd)
  410. except OSError:
  411. pass
  412. # retrieve file size from tar's stderr; warning: we do
  413. # not read data from tar's stdout at this point, it will
  414. # hang if it tries to output file content before
  415. # reporting its size on stderr first
  416. if size_func:
  417. # process lines on stderr until we get file size
  418. # search for first file size reported by tar -
  419. # this is used only when extracting single-file archive, so don't
  420. # bother with checking file name
  421. # Also, this needs to be called before anything is retrieved
  422. # from tar stderr, otherwise the process may deadlock waiting for
  423. # size (at this point nothing is retrieving data from tar stdout
  424. # yet, so it will hang on write() when the output pipe fill up).
  425. while True:
  426. line = tar2_process.stderr.readline()
  427. line = line.decode()
  428. if _tar_msg_re.match(line):
  429. self.log.debug('tar2_stderr: %s', line)
  430. else:
  431. match = _tar_file_size_re.match(line)
  432. if match:
  433. file_size = match.groups()[0]
  434. size_func(file_size)
  435. break
  436. else:
  437. self.log.warning(
  438. 'unexpected tar output (no file size report): %s',
  439. line)
  440. return data_func(tar2_process.stdout)
  441. def feed_tar2(self, filename, input_pipe):
  442. '''Feed data from *filename* to *input_pipe*
  443. Start a cat process to do that (do not block this process). Cat
  444. subprocess instance will be in :py:attr:`tar2_feeder`
  445. '''
  446. assert self.tar2_feeder is None
  447. self.tar2_feeder = subprocess.Popen(['cat', filename],
  448. stdout=input_pipe)
  449. def check_processes(self, processes):
  450. '''Check if any process failed.
  451. And if so, wait for other relevant processes to cleanup.
  452. '''
  453. run_error = None
  454. for name, proc in processes.items():
  455. if proc is None:
  456. continue
  457. if isinstance(proc, Process):
  458. if not proc.is_alive() and proc.exitcode != 0:
  459. run_error = name
  460. break
  461. elif proc.poll():
  462. run_error = name
  463. break
  464. if run_error:
  465. if run_error == "target":
  466. self.collect_tar_output()
  467. details = "\n".join(self.tar2_stderr)
  468. else:
  469. details = "%s failed" % run_error
  470. if self.decryptor_process:
  471. self.decryptor_process.terminate()
  472. self.decryptor_process.wait()
  473. self.decryptor_process = None
  474. self.log.error('Error while processing \'%s\': %s',
  475. self.tar2_current_file, details)
  476. self.cleanup_tar2(wait=True, terminate=True)
  477. def __run__(self):
  478. self.log.debug("Started sending thread")
  479. self.log.debug("Moving to dir " + self.base_dir)
  480. os.chdir(self.base_dir)
  481. filename = None
  482. input_pipe = None
  483. for filename in iter(self.queue.get, None):
  484. if filename in (QUEUE_FINISHED, QUEUE_ERROR):
  485. break
  486. assert isinstance(filename, str)
  487. self.log.debug("Extracting file " + filename)
  488. if filename.endswith('.000'):
  489. # next file
  490. if self.tar2_process is not None:
  491. input_pipe.close()
  492. self.cleanup_tar2(wait=True, terminate=False)
  493. inner_name = filename[:-len('.000')].replace(
  494. self.base_dir + '/', '')
  495. redirect_stdout = None
  496. if os.path.basename(inner_name) == '.':
  497. if (inner_name in self.handlers or
  498. any(x.startswith(os.path.dirname(inner_name) + '/')
  499. for x in self.handlers)):
  500. tar2_cmdline = ['tar',
  501. '-%s' % ("t" if self.verify_only else "x"),
  502. inner_name]
  503. else:
  504. # ignore this directory
  505. tar2_cmdline = None
  506. elif inner_name in self.handlers:
  507. tar2_cmdline = ['tar',
  508. '-%svvO' % ("t" if self.verify_only else "x"),
  509. inner_name]
  510. redirect_stdout = subprocess.PIPE
  511. else:
  512. # no handlers for this file, ignore it
  513. tar2_cmdline = None
  514. if tar2_cmdline is None:
  515. # ignore the file
  516. os.remove(filename)
  517. continue
  518. if self.compressed:
  519. if self.compression_filter:
  520. tar2_cmdline.insert(-1,
  521. "--use-compress-program=%s" %
  522. self.compression_filter)
  523. else:
  524. tar2_cmdline.insert(-1, "--use-compress-program=%s" %
  525. DEFAULT_COMPRESSION_FILTER)
  526. self.log.debug("Running command " + str(tar2_cmdline))
  527. if self.encrypted:
  528. # Start decrypt
  529. self.decryptor_process = subprocess.Popen(
  530. ["openssl", "enc",
  531. "-d",
  532. "-" + self.crypto_algorithm,
  533. "-pass",
  534. "pass:" + self.passphrase],
  535. stdin=subprocess.PIPE,
  536. stdout=subprocess.PIPE)
  537. self.tar2_process = subprocess.Popen(
  538. tar2_cmdline,
  539. stdin=self.decryptor_process.stdout,
  540. stdout=redirect_stdout,
  541. stderr=subprocess.PIPE)
  542. self.decryptor_process.stdout.close()
  543. input_pipe = self.decryptor_process.stdin
  544. else:
  545. self.tar2_process = subprocess.Popen(
  546. tar2_cmdline,
  547. stdin=subprocess.PIPE,
  548. stdout=redirect_stdout,
  549. stderr=subprocess.PIPE)
  550. input_pipe = self.tar2_process.stdin
  551. self.feed_tar2(filename, input_pipe)
  552. if inner_name in self.handlers:
  553. assert redirect_stdout is subprocess.PIPE
  554. data_func, size_func = self.handlers[inner_name]
  555. self.import_process = multiprocessing.Process(
  556. target=self._data_import_wrapper,
  557. args=([input_pipe.fileno()],
  558. data_func, size_func, self.tar2_process))
  559. self.import_process.start()
  560. self.tar2_process.stdout.close()
  561. self.tar2_stderr = []
  562. elif not self.tar2_process:
  563. # Extracting of the current archive failed, skip to the next
  564. # archive
  565. os.remove(filename)
  566. continue
  567. else:
  568. (basename, ext) = os.path.splitext(self.tar2_current_file)
  569. previous_chunk_number = int(ext[1:])
  570. expected_filename = basename + '.%03d' % (
  571. previous_chunk_number+1)
  572. if expected_filename != filename:
  573. self.cleanup_tar2(wait=True, terminate=True)
  574. self.log.error(
  575. 'Unexpected file in archive: %s, expected %s',
  576. filename, expected_filename)
  577. os.remove(filename)
  578. continue
  579. self.log.debug("Releasing next chunck")
  580. self.feed_tar2(filename, input_pipe)
  581. self.tar2_current_file = filename
  582. self.tar2_feeder.wait()
  583. # check if any process failed
  584. processes = {
  585. 'target': self.tar2_feeder,
  586. 'vmproc': self.vmproc,
  587. 'addproc': self.tar2_process,
  588. 'data_import': self.import_process,
  589. 'decryptor': self.decryptor_process,
  590. }
  591. self.check_processes(processes)
  592. self.tar2_feeder = None
  593. if callable(self.progress_callback):
  594. self.progress_callback(os.path.getsize(filename))
  595. # Delete the file as we don't need it anymore
  596. self.log.debug('Removing file %s', filename)
  597. os.remove(filename)
  598. if self.tar2_process is not None:
  599. input_pipe.close()
  600. if filename == QUEUE_ERROR:
  601. if self.decryptor_process:
  602. self.decryptor_process.terminate()
  603. self.decryptor_process.wait()
  604. self.decryptor_process = None
  605. self.cleanup_tar2(terminate=(filename == QUEUE_ERROR))
  606. self.log.debug('Finished extracting thread')
  607. def get_supported_hmac_algo(hmac_algorithm=None):
  608. '''Generate a list of supported hmac algorithms
  609. :param hmac_algorithm: default algorithm, if given, it is placed as a
  610. first element
  611. '''
  612. # Start with provided default
  613. if hmac_algorithm:
  614. yield hmac_algorithm
  615. if hmac_algorithm != 'scrypt':
  616. yield 'scrypt'
  617. proc = subprocess.Popen(['openssl', 'list-message-digest-algorithms'],
  618. stdout=subprocess.PIPE)
  619. try:
  620. for algo in proc.stdout.readlines():
  621. algo = algo.decode('ascii')
  622. if '=>' in algo:
  623. continue
  624. yield algo.strip()
  625. finally:
  626. proc.terminate()
  627. proc.wait()
  628. proc.stdout.close()
  629. class BackupRestoreOptions(object):
  630. '''Options for restore operation'''
  631. # pylint: disable=too-few-public-methods
  632. def __init__(self):
  633. #: use default NetVM if the one referenced in backup do not exists on
  634. # the host
  635. self.use_default_netvm = True
  636. #: set NetVM to "none" if the one referenced in backup do not exists
  637. # on the host
  638. self.use_none_netvm = False
  639. #: set template to default if the one referenced in backup do not
  640. # exists on the host
  641. self.use_default_template = True
  642. #: use default kernel if the one referenced in backup do not exists
  643. # on the host
  644. self.use_default_kernel = True
  645. #: restore dom0 home
  646. self.dom0_home = True
  647. #: restore dom0 home even if username is different
  648. self.ignore_username_mismatch = False
  649. #: do not restore data, only verify backup integrity
  650. self.verify_only = False
  651. #: automatically rename VM during restore, when it would conflict
  652. # with existing one
  653. self.rename_conflicting = True
  654. #: list of VM names to exclude
  655. self.exclude = []
  656. #: restore VMs into selected storage pool
  657. self.override_pool = None
  658. #: ignore size limit calculated from backup metadata
  659. self.ignore_size_limit = False
  660. class BackupRestore(object):
  661. """Usage:
  662. >>> restore_op = BackupRestore(...)
  663. >>> # adjust restore_op.options here
  664. >>> restore_info = restore_op.get_restore_info()
  665. >>> # manipulate restore_info to select VMs to restore here
  666. >>> restore_op.restore_do(restore_info)
  667. """
  668. class VMToRestore(object):
  669. '''Information about a single VM to be restored'''
  670. # pylint: disable=too-few-public-methods
  671. #: VM excluded from restore by user
  672. EXCLUDED = object()
  673. #: VM with such name already exists on the host
  674. ALREADY_EXISTS = object()
  675. #: NetVM used by the VM does not exists on the host
  676. MISSING_NETVM = object()
  677. #: TemplateVM used by the VM does not exists on the host
  678. MISSING_TEMPLATE = object()
  679. #: Kernel used by the VM does not exists on the host
  680. MISSING_KERNEL = object()
  681. def __init__(self, vm):
  682. assert isinstance(vm, BackupVM)
  683. self.vm = vm
  684. self.name = vm.name
  685. self.subdir = vm.backup_path
  686. self.size = vm.size
  687. self.problems = set()
  688. self.template = vm.template
  689. if vm.properties.get('netvm', None):
  690. self.netvm = vm.properties['netvm']
  691. else:
  692. self.netvm = None
  693. self.orig_template = None
  694. self.restored_vm = None
  695. @property
  696. def good_to_go(self):
  697. '''Is the VM ready for restore?'''
  698. return len(self.problems) == 0
  699. class Dom0ToRestore(VMToRestore):
  700. '''Information about dom0 home to restore'''
  701. # pylint: disable=too-few-public-methods
  702. #: backup was performed on system with different dom0 username
  703. USERNAME_MISMATCH = object()
  704. def __init__(self, vm, subdir=None):
  705. super(BackupRestore.Dom0ToRestore, self).__init__(vm)
  706. if subdir:
  707. self.subdir = subdir
  708. self.username = os.path.basename(subdir)
  709. def __init__(self, app, backup_location, backup_vm, passphrase):
  710. super(BackupRestore, self).__init__()
  711. #: qubes.Qubes instance
  712. self.app = app
  713. #: options how the backup should be restored
  714. self.options = BackupRestoreOptions()
  715. #: VM from which backup should be retrieved
  716. self.backup_vm = backup_vm
  717. if backup_vm and backup_vm.qid == 0:
  718. self.backup_vm = None
  719. #: backup path, inside VM pointed by :py:attr:`backup_vm`
  720. self.backup_location = backup_location
  721. #: passphrase protecting backup integrity and optionally decryption
  722. self.passphrase = passphrase
  723. #: temporary directory used to extract the data before moving to the
  724. # final location
  725. self.tmpdir = tempfile.mkdtemp(prefix="restore", dir="/var/tmp")
  726. #: list of processes (Popen objects) to kill on cancel
  727. self.processes_to_kill_on_cancel = []
  728. #: is the backup operation canceled
  729. self.canceled = False
  730. #: report restore progress, called with one argument - percents of
  731. # data restored
  732. # FIXME: convert to float [0,1]
  733. self.progress_callback = None
  734. self.log = logging.getLogger('qubesadmin.backup')
  735. #: basic information about the backup
  736. self.header_data = self._retrieve_backup_header()
  737. #: VMs included in the backup
  738. self.backup_app = self._process_qubes_xml()
  739. def _start_retrieval_process(self, filelist, limit_count, limit_bytes):
  740. """Retrieve backup stream and extract it to :py:attr:`tmpdir`
  741. :param filelist: list of files to extract; listing directory name
  742. will extract the whole directory; use empty list to extract the whole
  743. archive
  744. :param limit_count: maximum number of files to extract
  745. :param limit_bytes: maximum size of extracted data
  746. :return: a touple of (Popen object of started process, file-like
  747. object for reading extracted files list, file-like object for reading
  748. errors)
  749. """
  750. vmproc = None
  751. if self.backup_vm is not None:
  752. # If APPVM, STDOUT is a PIPE
  753. vmproc = self.backup_vm.run_service('qubes.Restore')
  754. vmproc.stdin.write(
  755. (self.backup_location.replace("\r", "").replace("\n",
  756. "") + "\n").encode())
  757. vmproc.stdin.flush()
  758. # Send to tar2qfile the VMs that should be extracted
  759. vmproc.stdin.write((" ".join(filelist) + "\n").encode())
  760. vmproc.stdin.flush()
  761. self.processes_to_kill_on_cancel.append(vmproc)
  762. backup_stdin = vmproc.stdout
  763. # FIXME use /usr/lib/qubes/qfile-unpacker in non-dom0
  764. tar1_command = ['/usr/libexec/qubes/qfile-dom0-unpacker',
  765. str(os.getuid()), self.tmpdir, '-v']
  766. else:
  767. backup_stdin = open(self.backup_location, 'rb')
  768. tar1_command = ['tar',
  769. '-ixv',
  770. '-C', self.tmpdir] + filelist
  771. tar1_env = os.environ.copy()
  772. tar1_env['UPDATES_MAX_BYTES'] = str(limit_bytes)
  773. tar1_env['UPDATES_MAX_FILES'] = str(limit_count)
  774. self.log.debug("Run command" + str(tar1_command))
  775. command = subprocess.Popen(
  776. tar1_command,
  777. stdin=backup_stdin,
  778. stdout=vmproc.stdin if vmproc else subprocess.PIPE,
  779. stderr=subprocess.PIPE,
  780. env=tar1_env)
  781. backup_stdin.close()
  782. self.processes_to_kill_on_cancel.append(command)
  783. # qfile-dom0-unpacker output filelist on stderr
  784. # and have stdout connected to the VM), while tar output filelist
  785. # on stdout
  786. if self.backup_vm:
  787. filelist_pipe = command.stderr
  788. # let qfile-dom0-unpacker hold the only open FD to the write end of
  789. # pipe, otherwise qrexec-client will not receive EOF when
  790. # qfile-dom0-unpacker terminates
  791. vmproc.stdin.close()
  792. else:
  793. filelist_pipe = command.stdout
  794. if self.backup_vm:
  795. error_pipe = vmproc.stderr
  796. else:
  797. error_pipe = command.stderr
  798. return command, filelist_pipe, error_pipe
  799. def _verify_hmac(self, filename, hmacfile, algorithm=None):
  800. '''Verify hmac of a file using given algorithm.
  801. If algorithm is not specified, use the one from backup header (
  802. :py:attr:`header_data`).
  803. Raise :py:exc:`QubesException` on failure, return :py:obj:`True` on
  804. success.
  805. 'scrypt' algorithm is supported only for header file; hmac file is
  806. encrypted (and integrity protected) version of plain header.
  807. :param filename: path to file to be verified
  808. :param hmacfile: path to hmac file for *filename*
  809. :param algorithm: override algorithm
  810. '''
  811. def load_hmac(hmac_text):
  812. '''Parse hmac output by openssl.
  813. Return just hmac, without filename and other metadata.
  814. '''
  815. if any(ord(x) not in range(128) for x in hmac_text):
  816. raise QubesException(
  817. "Invalid content of {}".format(hmacfile))
  818. hmac_text = hmac_text.strip().split("=")
  819. if len(hmac_text) > 1:
  820. hmac_text = hmac_text[1].strip()
  821. else:
  822. raise QubesException(
  823. "ERROR: invalid hmac file content")
  824. return hmac_text
  825. if algorithm is None:
  826. algorithm = self.header_data.hmac_algorithm
  827. passphrase = self.passphrase.encode('utf-8')
  828. self.log.debug("Verifying file %s", filename)
  829. if os.stat(os.path.join(self.tmpdir, hmacfile)).st_size > \
  830. HMAC_MAX_SIZE:
  831. raise QubesException('HMAC file {} too large'.format(
  832. hmacfile))
  833. if hmacfile != filename + ".hmac":
  834. raise QubesException(
  835. "ERROR: expected hmac for {}, but got {}".
  836. format(filename, hmacfile))
  837. if algorithm == 'scrypt':
  838. # in case of 'scrypt' _verify_hmac is only used for backup header
  839. assert filename == HEADER_FILENAME
  840. self._verify_and_decrypt(hmacfile, HEADER_FILENAME + '.dec')
  841. f_name = os.path.join(self.tmpdir, filename)
  842. with open(f_name, 'rb') as f_one:
  843. with open(f_name + '.dec', 'rb') as f_two:
  844. if f_one.read() != f_two.read():
  845. raise QubesException(
  846. 'Invalid hmac on {}'.format(filename))
  847. else:
  848. return True
  849. with open(os.path.join(self.tmpdir, filename), 'rb') as f_input:
  850. hmac_proc = subprocess.Popen(
  851. ["openssl", "dgst", "-" + algorithm, "-hmac", passphrase],
  852. stdin=f_input,
  853. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  854. hmac_stdout, hmac_stderr = hmac_proc.communicate()
  855. if hmac_stderr:
  856. raise QubesException(
  857. "ERROR: verify file {0}: {1}".format(filename, hmac_stderr))
  858. else:
  859. self.log.debug("Loading hmac for file %s", filename)
  860. try:
  861. with open(os.path.join(self.tmpdir, hmacfile), 'r',
  862. encoding='ascii') as f_hmac:
  863. hmac = load_hmac(f_hmac.read())
  864. except UnicodeDecodeError as err:
  865. raise QubesException('Cannot load hmac file: ' + str(err))
  866. if hmac and load_hmac(hmac_stdout.decode('ascii')) == hmac:
  867. os.unlink(os.path.join(self.tmpdir, hmacfile))
  868. self.log.debug(
  869. "File verification OK -> Sending file %s", filename)
  870. return True
  871. else:
  872. raise QubesException(
  873. "ERROR: invalid hmac for file {0}: {1}. "
  874. "Is the passphrase correct?".
  875. format(filename, load_hmac(hmac_stdout.decode('ascii'))))
  876. def _verify_and_decrypt(self, filename, output=None):
  877. '''Handle scrypt-wrapped file
  878. Decrypt the file, and verify its integrity - both tasks handled by
  879. 'scrypt' tool. Filename (without extension) is also validated.
  880. :param filename: Input file name (relative to :py:attr:`tmpdir`),
  881. needs to have `.enc` or `.hmac` extension
  882. :param output: Output file name (relative to :py:attr:`tmpdir`),
  883. use :py:obj:`None` to use *filename* without extension
  884. :return: *filename* without extension
  885. '''
  886. assert filename.endswith('.enc') or filename.endswith('.hmac')
  887. fullname = os.path.join(self.tmpdir, filename)
  888. (origname, _) = os.path.splitext(filename)
  889. if output:
  890. fulloutput = os.path.join(self.tmpdir, output)
  891. else:
  892. fulloutput = os.path.join(self.tmpdir, origname)
  893. if origname == HEADER_FILENAME:
  894. passphrase = u'{filename}!{passphrase}'.format(
  895. filename=origname,
  896. passphrase=self.passphrase)
  897. else:
  898. passphrase = u'{backup_id}!{filename}!{passphrase}'.format(
  899. backup_id=self.header_data.backup_id,
  900. filename=origname,
  901. passphrase=self.passphrase)
  902. try:
  903. p = launch_scrypt('dec', fullname, fulloutput, passphrase)
  904. except OSError as err:
  905. raise QubesException('failed to decrypt {}: {!s}'.format(
  906. fullname, err))
  907. (_, stderr) = p.communicate()
  908. if hasattr(p, 'pty'):
  909. p.pty.close()
  910. if p.returncode != 0:
  911. os.unlink(fulloutput)
  912. raise QubesException('failed to decrypt {}: {}'.format(
  913. fullname, stderr))
  914. # encrypted file is no longer needed
  915. os.unlink(fullname)
  916. return origname
  917. def _retrieve_backup_header_files(self, files, allow_none=False):
  918. '''Retrieve backup header.
  919. Start retrieval process (possibly involving network access from
  920. another VM). Returns a collection of retrieved file paths.
  921. '''
  922. (retrieve_proc, filelist_pipe, error_pipe) = \
  923. self._start_retrieval_process(
  924. files, len(files), 1024 * 1024)
  925. filelist = filelist_pipe.read()
  926. filelist_pipe.close()
  927. retrieve_proc_returncode = retrieve_proc.wait()
  928. if retrieve_proc in self.processes_to_kill_on_cancel:
  929. self.processes_to_kill_on_cancel.remove(retrieve_proc)
  930. extract_stderr = error_pipe.read(MAX_STDERR_BYTES)
  931. error_pipe.close()
  932. # wait for other processes (if any)
  933. for proc in self.processes_to_kill_on_cancel:
  934. if proc.wait() != 0:
  935. raise QubesException(
  936. "Backup header retrieval failed (exit code {})".format(
  937. proc.wait())
  938. )
  939. if retrieve_proc_returncode != 0:
  940. if not filelist and 'Not found in archive' in extract_stderr:
  941. if allow_none:
  942. return None
  943. else:
  944. raise QubesException(
  945. "unable to read the qubes backup file {0} ({1}): {2}".
  946. format(
  947. self.backup_location,
  948. retrieve_proc.wait(),
  949. extract_stderr
  950. ))
  951. actual_files = filelist.decode('ascii').splitlines()
  952. if sorted(actual_files) != sorted(files):
  953. raise QubesException(
  954. 'unexpected files in archive: got {!r}, expected {!r}'.format(
  955. actual_files, files
  956. ))
  957. for fname in files:
  958. if not os.path.exists(os.path.join(self.tmpdir, fname)):
  959. if allow_none:
  960. return None
  961. else:
  962. raise QubesException(
  963. 'Unable to retrieve file {} from backup {}: {}'.format(
  964. fname, self.backup_location, extract_stderr
  965. )
  966. )
  967. return files
  968. def _retrieve_backup_header(self):
  969. """Retrieve backup header and qubes.xml. Only backup header is
  970. analyzed, qubes.xml is left as-is
  971. (not even verified/decrypted/uncompressed)
  972. :return header_data
  973. :rtype :py:class:`BackupHeader`
  974. """
  975. if not self.backup_vm and os.path.exists(
  976. os.path.join(self.backup_location, 'qubes.xml')):
  977. # backup format version 1 doesn't have header
  978. header_data = BackupHeader()
  979. header_data.version = 1
  980. return header_data
  981. header_files = self._retrieve_backup_header_files(
  982. ['backup-header', 'backup-header.hmac'], allow_none=True)
  983. if not header_files:
  984. # R2-Beta3 didn't have backup header, so if none is found,
  985. # assume it's version=2 and use values present at that time
  986. header_data = BackupHeader(
  987. version=2,
  988. # place explicitly this value, because it is what format_version
  989. # 2 have
  990. hmac_algorithm='SHA1',
  991. crypto_algorithm='aes-256-cbc',
  992. # TODO: set encrypted to something...
  993. )
  994. else:
  995. filename = HEADER_FILENAME
  996. hmacfile = HEADER_FILENAME + '.hmac'
  997. self.log.debug("Got backup header and hmac: %s, %s",
  998. filename, hmacfile)
  999. file_ok = False
  1000. hmac_algorithm = DEFAULT_HMAC_ALGORITHM
  1001. for hmac_algo in get_supported_hmac_algo(hmac_algorithm):
  1002. try:
  1003. if self._verify_hmac(filename, hmacfile, hmac_algo):
  1004. file_ok = True
  1005. break
  1006. except QubesException as err:
  1007. self.log.debug(
  1008. 'Failed to verify %s using %s: %r',
  1009. hmacfile, hmac_algo, err)
  1010. # Ignore exception here, try the next algo
  1011. if not file_ok:
  1012. raise QubesException(
  1013. "Corrupted backup header (hmac verification "
  1014. "failed). Is the password correct?")
  1015. filename = os.path.join(self.tmpdir, filename)
  1016. with open(filename, 'rb') as f_header:
  1017. header_data = BackupHeader(f_header.read())
  1018. os.unlink(filename)
  1019. return header_data
  1020. def _start_inner_extraction_worker(self, queue, handlers):
  1021. """Start a worker process, extracting inner layer of bacup archive,
  1022. extract them to :py:attr:`tmpdir`.
  1023. End the data by pushing QUEUE_FINISHED or QUEUE_ERROR to the queue.
  1024. :param queue :py:class:`Queue` object to handle files from
  1025. """
  1026. # Setup worker to extract encrypted data chunks to the restore dirs
  1027. # Create the process here to pass it options extracted from
  1028. # backup header
  1029. extractor_params = {
  1030. 'queue': queue,
  1031. 'base_dir': self.tmpdir,
  1032. 'passphrase': self.passphrase,
  1033. 'encrypted': self.header_data.encrypted,
  1034. 'compressed': self.header_data.compressed,
  1035. 'crypto_algorithm': self.header_data.crypto_algorithm,
  1036. 'verify_only': self.options.verify_only,
  1037. 'progress_callback': self.progress_callback,
  1038. 'handlers': handlers,
  1039. }
  1040. self.log.debug(
  1041. 'Starting extraction worker in %s, file handlers map: %s',
  1042. self.tmpdir, repr(handlers))
  1043. format_version = self.header_data.version
  1044. if format_version in [3, 4]:
  1045. extractor_params['compression_filter'] = \
  1046. self.header_data.compression_filter
  1047. if format_version == 4:
  1048. # encryption already handled
  1049. extractor_params['encrypted'] = False
  1050. extract_proc = ExtractWorker3(**extractor_params)
  1051. else:
  1052. raise NotImplementedError(
  1053. "Backup format version %d not supported" % format_version)
  1054. extract_proc.start()
  1055. return extract_proc
  1056. @staticmethod
  1057. def _save_qubes_xml(path, stream):
  1058. '''Handler for qubes.xml.000 content - just save the data to a file'''
  1059. with open(path, 'wb') as f_qubesxml:
  1060. f_qubesxml.write(stream.read())
  1061. def _process_qubes_xml(self):
  1062. """Verify, unpack and load qubes.xml. Possibly convert its format if
  1063. necessary. It expect that :py:attr:`header_data` is already populated,
  1064. and :py:meth:`retrieve_backup_header` was called.
  1065. """
  1066. if self.header_data.version == 1:
  1067. raise NotImplementedError('Backup format version 1 not supported')
  1068. elif self.header_data.version in [2, 3]:
  1069. self._retrieve_backup_header_files(
  1070. ['qubes.xml.000', 'qubes.xml.000.hmac'])
  1071. self._verify_hmac("qubes.xml.000", "qubes.xml.000.hmac")
  1072. else:
  1073. self._retrieve_backup_header_files(['qubes.xml.000.enc'])
  1074. self._verify_and_decrypt('qubes.xml.000.enc')
  1075. queue = Queue()
  1076. queue.put("qubes.xml.000")
  1077. queue.put(QUEUE_FINISHED)
  1078. qubes_xml_path = os.path.join(self.tmpdir, 'qubes-restored.xml')
  1079. handlers = {
  1080. 'qubes.xml': (
  1081. functools.partial(self._save_qubes_xml, qubes_xml_path),
  1082. None)
  1083. }
  1084. extract_proc = self._start_inner_extraction_worker(queue, handlers)
  1085. extract_proc.join()
  1086. if extract_proc.exitcode != 0:
  1087. raise QubesException(
  1088. "unable to extract the qubes backup. "
  1089. "Check extracting process errors.")
  1090. if self.header_data.version in [2, 3]:
  1091. backup_app = Core2Qubes(qubes_xml_path)
  1092. elif self.header_data.version in [4]:
  1093. backup_app = Core3Qubes(qubes_xml_path)
  1094. else:
  1095. raise QubesException(
  1096. 'Unsupported qubes.xml format version: {}'.format(
  1097. self.header_data.version))
  1098. # Not needed anymore - all the data stored in backup_app
  1099. os.unlink(qubes_xml_path)
  1100. return backup_app
  1101. def _restore_vm_data(self, vms_dirs, vms_size, handlers):
  1102. '''Restore data of VMs
  1103. :param vms_dirs: list of directories to extract (skip others)
  1104. :param vms_size: expected size (abort if source stream exceed this
  1105. value)
  1106. :param handlers: handlers for restored files - see
  1107. :py:class:`ExtractWorker3` for details
  1108. '''
  1109. # Currently each VM consists of at most 7 archives (count
  1110. # file_to_backup calls in backup_prepare()), but add some safety
  1111. # margin for further extensions. Each archive is divided into 100MB
  1112. # chunks. Additionally each file have own hmac file. So assume upper
  1113. # limit as 2*(10*COUNT_OF_VMS+TOTAL_SIZE/100MB)
  1114. limit_count = str(2 * (10 * len(vms_dirs) +
  1115. int(vms_size / (100 * 1024 * 1024))))
  1116. if self.options.ignore_size_limit:
  1117. limit_count = '0'
  1118. vms_size = 0
  1119. self.log.debug("Working in temporary dir: %s", self.tmpdir)
  1120. self.log.info("Extracting data: %s to restore", size_to_human(vms_size))
  1121. # retrieve backup from the backup stream (either VM, or dom0 file)
  1122. (retrieve_proc, filelist_pipe, error_pipe) = \
  1123. self._start_retrieval_process(
  1124. vms_dirs, limit_count, vms_size)
  1125. to_extract = Queue()
  1126. # extract data retrieved by retrieve_proc
  1127. extract_proc = self._start_inner_extraction_worker(
  1128. to_extract, handlers)
  1129. try:
  1130. filename = None
  1131. hmacfile = None
  1132. nextfile = None
  1133. while True:
  1134. if self.canceled:
  1135. break
  1136. if not extract_proc.is_alive():
  1137. retrieve_proc.terminate()
  1138. retrieve_proc.wait()
  1139. if retrieve_proc in self.processes_to_kill_on_cancel:
  1140. self.processes_to_kill_on_cancel.remove(retrieve_proc)
  1141. # wait for other processes (if any)
  1142. for proc in self.processes_to_kill_on_cancel:
  1143. proc.wait()
  1144. break
  1145. if nextfile is not None:
  1146. filename = nextfile
  1147. else:
  1148. filename = filelist_pipe.readline().decode('ascii').strip()
  1149. self.log.debug("Getting new file: %s", filename)
  1150. if not filename or filename == "EOF":
  1151. break
  1152. # if reading archive directly with tar, wait for next filename -
  1153. # tar prints filename before processing it, so wait for
  1154. # the next one to be sure that whole file was extracted
  1155. if not self.backup_vm:
  1156. nextfile = filelist_pipe.readline().decode('ascii').strip()
  1157. if self.header_data.version in [2, 3]:
  1158. if not self.backup_vm:
  1159. hmacfile = nextfile
  1160. nextfile = filelist_pipe.readline().\
  1161. decode('ascii').strip()
  1162. else:
  1163. hmacfile = filelist_pipe.readline().\
  1164. decode('ascii').strip()
  1165. if self.canceled:
  1166. break
  1167. self.log.debug("Getting hmac: %s", hmacfile)
  1168. if not hmacfile or hmacfile == "EOF":
  1169. # Premature end of archive, either of tar1_command or
  1170. # vmproc exited with error
  1171. break
  1172. else: # self.header_data.version == 4
  1173. if not filename.endswith('.enc'):
  1174. raise qubesadmin.exc.QubesException(
  1175. 'Invalid file extension found in archive: {}'.
  1176. format(filename))
  1177. if not any(filename.startswith(x) for x in vms_dirs):
  1178. self.log.debug("Ignoring VM not selected for restore")
  1179. os.unlink(os.path.join(self.tmpdir, filename))
  1180. if hmacfile:
  1181. os.unlink(os.path.join(self.tmpdir, hmacfile))
  1182. continue
  1183. if self.header_data.version in [2, 3]:
  1184. self._verify_hmac(filename, hmacfile)
  1185. else:
  1186. # _verify_and_decrypt will write output to a file with
  1187. # '.enc' extension cut off. This is safe because:
  1188. # - `scrypt` tool will override output, so if the file was
  1189. # already there (received from the VM), it will be removed
  1190. # - incoming archive extraction will refuse to override
  1191. # existing file, so if `scrypt` already created one,
  1192. # it can not be manipulated by the VM
  1193. # - when the file is retrieved from the VM, it appears at
  1194. # the final form - if it's visible, VM have no longer
  1195. # influence over its content
  1196. #
  1197. # This all means that if the file was correctly verified
  1198. # + decrypted, we will surely access the right file
  1199. filename = self._verify_and_decrypt(filename)
  1200. to_extract.put(os.path.join(self.tmpdir, filename))
  1201. if self.canceled:
  1202. raise BackupCanceledError("Restore canceled",
  1203. tmpdir=self.tmpdir)
  1204. if retrieve_proc.wait() != 0:
  1205. if retrieve_proc.returncode == errno.EDQUOT:
  1206. raise QubesException(
  1207. 'retrieved backup size exceed expected size, if you '
  1208. 'believe this is ok, use --ignore-size-limit option')
  1209. else:
  1210. raise QubesException(
  1211. "unable to read the qubes backup file {} ({}): {}"
  1212. .format(self.backup_location,
  1213. retrieve_proc.returncode, error_pipe.read(
  1214. MAX_STDERR_BYTES)))
  1215. # wait for other processes (if any)
  1216. for proc in self.processes_to_kill_on_cancel:
  1217. proc.wait()
  1218. if proc.returncode != 0:
  1219. raise QubesException(
  1220. "Backup completed, "
  1221. "but VM sending it reported an error (exit code {})".
  1222. format(proc.returncode))
  1223. if filename and filename != "EOF":
  1224. raise QubesException(
  1225. "Premature end of archive, the last file was %s" % filename)
  1226. except:
  1227. to_extract.put(QUEUE_ERROR)
  1228. extract_proc.join()
  1229. raise
  1230. else:
  1231. to_extract.put(QUEUE_FINISHED)
  1232. finally:
  1233. error_pipe.close()
  1234. filelist_pipe.close()
  1235. self.log.debug("Waiting for the extraction process to finish...")
  1236. extract_proc.join()
  1237. self.log.debug("Extraction process finished with code: %s",
  1238. extract_proc.exitcode)
  1239. if extract_proc.exitcode != 0:
  1240. raise QubesException(
  1241. "unable to extract the qubes backup. "
  1242. "Check extracting process errors.")
  1243. def new_name_for_conflicting_vm(self, orig_name, restore_info):
  1244. '''Generate new name for conflicting VM
  1245. Add a number suffix, until the name is unique. If no unique name can
  1246. be found using this strategy, return :py:obj:`None`
  1247. '''
  1248. number = 1
  1249. if len(orig_name) > 29:
  1250. orig_name = orig_name[0:29]
  1251. new_name = orig_name
  1252. while (new_name in restore_info.keys() or
  1253. new_name in [x.name for x in restore_info.values()] or
  1254. new_name in self.app.domains):
  1255. new_name = str('{}{}'.format(orig_name, number))
  1256. number += 1
  1257. if number == 100:
  1258. # give up
  1259. return None
  1260. return new_name
  1261. def restore_info_verify(self, restore_info):
  1262. '''Verify restore info - validate VM dependencies, name conflicts
  1263. etc.
  1264. '''
  1265. for vm in restore_info.keys():
  1266. if vm in ['dom0']:
  1267. continue
  1268. vm_info = restore_info[vm]
  1269. assert isinstance(vm_info, self.VMToRestore)
  1270. vm_info.problems.clear()
  1271. if vm in self.options.exclude:
  1272. vm_info.problems.add(self.VMToRestore.EXCLUDED)
  1273. if not self.options.verify_only and \
  1274. vm_info.name in self.app.domains:
  1275. if self.options.rename_conflicting:
  1276. new_name = self.new_name_for_conflicting_vm(
  1277. vm, restore_info
  1278. )
  1279. if new_name is not None:
  1280. vm_info.name = new_name
  1281. else:
  1282. vm_info.problems.add(self.VMToRestore.ALREADY_EXISTS)
  1283. else:
  1284. vm_info.problems.add(self.VMToRestore.ALREADY_EXISTS)
  1285. # check template
  1286. if vm_info.template:
  1287. template_name = vm_info.template
  1288. try:
  1289. host_template = self.app.domains[template_name]
  1290. except KeyError:
  1291. host_template = None
  1292. present_on_host = (host_template and
  1293. isinstance(host_template, qubesadmin.vm.TemplateVM))
  1294. present_in_backup = (template_name in restore_info.keys() and
  1295. restore_info[template_name].good_to_go and
  1296. restore_info[template_name].vm.klass ==
  1297. 'TemplateVM')
  1298. if not present_on_host and not present_in_backup:
  1299. if self.options.use_default_template and \
  1300. self.app.default_template:
  1301. if vm_info.orig_template is None:
  1302. vm_info.orig_template = template_name
  1303. vm_info.template = self.app.default_template.name
  1304. else:
  1305. vm_info.problems.add(
  1306. self.VMToRestore.MISSING_TEMPLATE)
  1307. # check netvm
  1308. if vm_info.vm.properties.get('netvm', None) is not None:
  1309. netvm_name = vm_info.netvm
  1310. try:
  1311. netvm_on_host = self.app.domains[netvm_name]
  1312. except KeyError:
  1313. netvm_on_host = None
  1314. present_on_host = (netvm_on_host is not None
  1315. and netvm_on_host.provides_network)
  1316. present_in_backup = (netvm_name in restore_info.keys() and
  1317. restore_info[netvm_name].good_to_go and
  1318. restore_info[netvm_name].vm.properties.get(
  1319. 'provides_network', False))
  1320. if not present_on_host and not present_in_backup:
  1321. if self.options.use_default_netvm:
  1322. del vm_info.vm.properties['netvm']
  1323. elif self.options.use_none_netvm:
  1324. vm_info.netvm = None
  1325. else:
  1326. vm_info.problems.add(self.VMToRestore.MISSING_NETVM)
  1327. return restore_info
  1328. def get_restore_info(self):
  1329. '''Get restore info
  1330. Return information about what is included in the backup.
  1331. That dictionary can be adjusted to select what VM should be restore.
  1332. '''
  1333. # Format versions:
  1334. # 1 - Qubes R1, Qubes R2 beta1, beta2
  1335. # 2 - Qubes R2 beta3+
  1336. # 3 - Qubes R2+
  1337. # 4 - Qubes R4+
  1338. vms_to_restore = {}
  1339. for vm in self.backup_app.domains.values():
  1340. if vm.klass == 'AdminVM':
  1341. # Handle dom0 as special case later
  1342. continue
  1343. if vm.included_in_backup:
  1344. self.log.debug("%s is included in backup", vm.name)
  1345. vms_to_restore[vm.name] = self.VMToRestore(vm)
  1346. if vm.template is not None:
  1347. templatevm_name = vm.template
  1348. vms_to_restore[vm.name].template = templatevm_name
  1349. vms_to_restore = self.restore_info_verify(vms_to_restore)
  1350. # ...and dom0 home
  1351. if self.options.dom0_home and \
  1352. self.backup_app.domains['dom0'].included_in_backup:
  1353. vm = self.backup_app.domains['dom0']
  1354. vms_to_restore['dom0'] = self.Dom0ToRestore(vm)
  1355. local_user = grp.getgrnam('qubes').gr_mem[0]
  1356. if vms_to_restore['dom0'].username != local_user:
  1357. if not self.options.ignore_username_mismatch:
  1358. vms_to_restore['dom0'].problems.add(
  1359. self.Dom0ToRestore.USERNAME_MISMATCH)
  1360. return vms_to_restore
  1361. @staticmethod
  1362. def get_restore_summary(restore_info):
  1363. '''Return a ASCII formatted table with restore info summary'''
  1364. fields = {
  1365. "name": {'func': lambda vm: vm.name},
  1366. "type": {'func': lambda vm: vm.klass},
  1367. "template": {'func': lambda vm:
  1368. 'n/a' if vm.template is None else vm.template},
  1369. "netvm": {'func': lambda vm:
  1370. '(default)' if 'netvm' not in vm.properties else
  1371. '-' if vm.properties['netvm'] is None else
  1372. vm.properties['netvm']},
  1373. "label": {'func': lambda vm: vm.label},
  1374. }
  1375. fields_to_display = ['name', 'type', 'template',
  1376. 'netvm', 'label']
  1377. # First calculate the maximum width of each field we want to display
  1378. total_width = 0
  1379. for field in fields_to_display:
  1380. fields[field]['max_width'] = len(field)
  1381. for vm_info in restore_info.values():
  1382. if vm_info.vm:
  1383. # noinspection PyUnusedLocal
  1384. field_len = len(str(fields[field]["func"](vm_info.vm)))
  1385. if field_len > fields[field]['max_width']:
  1386. fields[field]['max_width'] = field_len
  1387. total_width += fields[field]['max_width']
  1388. summary = ""
  1389. summary += "The following VMs are included in the backup:\n"
  1390. summary += "\n"
  1391. # Display the header
  1392. for field in fields_to_display:
  1393. # noinspection PyTypeChecker
  1394. fmt = "{{0:-^{0}}}-+".format(fields[field]["max_width"] + 1)
  1395. summary += fmt.format('-')
  1396. summary += "\n"
  1397. for field in fields_to_display:
  1398. # noinspection PyTypeChecker
  1399. fmt = "{{0:>{0}}} |".format(fields[field]["max_width"] + 1)
  1400. summary += fmt.format(field)
  1401. summary += "\n"
  1402. for field in fields_to_display:
  1403. # noinspection PyTypeChecker
  1404. fmt = "{{0:-^{0}}}-+".format(fields[field]["max_width"] + 1)
  1405. summary += fmt.format('-')
  1406. summary += "\n"
  1407. for vm_info in restore_info.values():
  1408. assert isinstance(vm_info, BackupRestore.VMToRestore)
  1409. # Skip non-VM here
  1410. if not vm_info.vm:
  1411. continue
  1412. # noinspection PyUnusedLocal
  1413. summary_line = ""
  1414. for field in fields_to_display:
  1415. # noinspection PyTypeChecker
  1416. fmt = "{{0:>{0}}} |".format(fields[field]["max_width"] + 1)
  1417. summary_line += fmt.format(fields[field]["func"](vm_info.vm))
  1418. if BackupRestore.VMToRestore.EXCLUDED in vm_info.problems:
  1419. summary_line += " <-- Excluded from restore"
  1420. elif BackupRestore.VMToRestore.ALREADY_EXISTS in vm_info.problems:
  1421. summary_line += \
  1422. " <-- A VM with the same name already exists on the host!"
  1423. elif BackupRestore.VMToRestore.MISSING_TEMPLATE in \
  1424. vm_info.problems:
  1425. summary_line += " <-- No matching template on the host " \
  1426. "or in the backup found!"
  1427. elif BackupRestore.VMToRestore.MISSING_NETVM in \
  1428. vm_info.problems:
  1429. summary_line += " <-- No matching netvm on the host " \
  1430. "or in the backup found!"
  1431. else:
  1432. if vm_info.template != vm_info.vm.template:
  1433. summary_line += " <-- Template change to '{}'".format(
  1434. vm_info.template)
  1435. if vm_info.name != vm_info.vm.name:
  1436. summary_line += " <-- Will be renamed to '{}'".format(
  1437. vm_info.name)
  1438. summary += summary_line + "\n"
  1439. if 'dom0' in restore_info.keys():
  1440. summary_line = ""
  1441. for field in fields_to_display:
  1442. # noinspection PyTypeChecker
  1443. fmt = "{{0:>{0}}} |".format(fields[field]["max_width"] + 1)
  1444. if field == "name":
  1445. summary_line += fmt.format("Dom0")
  1446. elif field == "type":
  1447. summary_line += fmt.format("Home")
  1448. else:
  1449. summary_line += fmt.format("")
  1450. if BackupRestore.Dom0ToRestore.USERNAME_MISMATCH in \
  1451. restore_info['dom0'].problems:
  1452. summary_line += " <-- username in backup and dom0 mismatch"
  1453. summary += summary_line + "\n"
  1454. return summary
  1455. @staticmethod
  1456. def _templates_first(vms):
  1457. '''Sort templates befor other VM types (AppVM etc)'''
  1458. def key_function(instance):
  1459. '''Key function for :py:func:`sorted`'''
  1460. if isinstance(instance, BackupVM):
  1461. return instance.klass == 'TemplateVM'
  1462. elif hasattr(instance, 'vm'):
  1463. return key_function(instance.vm)
  1464. return 0
  1465. return sorted(vms,
  1466. key=key_function,
  1467. reverse=True)
  1468. def _handle_dom0(self, backup_path):
  1469. '''Extract dom0 home'''
  1470. local_user = grp.getgrnam('qubes').gr_mem[0]
  1471. home_dir = pwd.getpwnam(local_user).pw_dir
  1472. backup_dom0_home_dir = os.path.join(self.tmpdir, backup_path)
  1473. restore_home_backupdir = "home-pre-restore-{0}".format(
  1474. time.strftime("%Y-%m-%d-%H%M%S"))
  1475. self.log.info("Restoring home of user '%s'...", local_user)
  1476. self.log.info("Existing files/dirs backed up in '%s' dir",
  1477. restore_home_backupdir)
  1478. os.mkdir(home_dir + '/' + restore_home_backupdir)
  1479. for f_name in os.listdir(backup_dom0_home_dir):
  1480. home_file = home_dir + '/' + f_name
  1481. if os.path.exists(home_file):
  1482. os.rename(home_file,
  1483. home_dir + '/' + restore_home_backupdir + '/' + f_name)
  1484. if self.header_data.version == 1:
  1485. subprocess.call(
  1486. ["cp", "-nrp", "--reflink=auto",
  1487. backup_dom0_home_dir + '/' + f_name, home_file])
  1488. elif self.header_data.version >= 2:
  1489. shutil.move(backup_dom0_home_dir + '/' + f_name, home_file)
  1490. retcode = subprocess.call(['sudo', 'chown', '-R',
  1491. local_user, home_dir])
  1492. if retcode != 0:
  1493. self.log.error("*** Error while setting home directory owner")
  1494. def _handle_appmenus_list(self, vm, stream):
  1495. '''Handle whitelisted-appmenus.list file'''
  1496. try:
  1497. subprocess.check_call(
  1498. ['qvm-appmenus', '--set-whitelist=-', vm.name],
  1499. stdin=stream)
  1500. except subprocess.CalledProcessError:
  1501. self.log.error('Failed to set application list for %s', vm.name)
  1502. def _handle_volume_data(self, vm, volume, stream):
  1503. '''Wrap volume data import with logging'''
  1504. try:
  1505. volume.import_data(stream)
  1506. except Exception as err: # pylint: disable=broad-except
  1507. self.log.error('Failed to restore volume %s of VM %s: %s',
  1508. volume.name, vm.name, err)
  1509. def _handle_volume_size(self, vm, volume, size):
  1510. '''Wrap volume resize with logging'''
  1511. try:
  1512. volume.resize(size)
  1513. except Exception as err: # pylint: disable=broad-except
  1514. self.log.error('Failed to resize volume %s of VM %s: %s',
  1515. volume.name, vm.name, err)
  1516. def restore_do(self, restore_info):
  1517. '''
  1518. High level workflow:
  1519. 1. Create VMs object in host collection (qubes.xml)
  1520. 2. Create them on disk (vm.create_on_disk)
  1521. 3. Restore VM data, overriding/converting VM files
  1522. 4. Apply possible fixups and save qubes.xml
  1523. :param restore_info:
  1524. :return:
  1525. '''
  1526. if self.header_data.version == 1:
  1527. raise NotImplementedError('Backup format version 1 not supported')
  1528. restore_info = self.restore_info_verify(restore_info)
  1529. self._restore_vms_metadata(restore_info)
  1530. # Perform VM restoration in backup order
  1531. vms_dirs = []
  1532. handlers = {}
  1533. vms_size = 0
  1534. for vm_info in self._templates_first(restore_info.values()):
  1535. vm = vm_info.restored_vm
  1536. if vm and vm_info.subdir:
  1537. vms_size += int(vm_info.size)
  1538. vms_dirs.append(vm_info.subdir)
  1539. for name, volume in vm.volumes.items():
  1540. if not volume.save_on_stop:
  1541. continue
  1542. data_func = functools.partial(
  1543. self._handle_volume_data, vm, volume)
  1544. size_func = functools.partial(
  1545. self._handle_volume_size, vm, volume)
  1546. handlers[os.path.join(vm_info.subdir, name + '.img')] = \
  1547. (data_func, size_func)
  1548. handlers[os.path.join(vm_info.subdir, 'firewall.xml')] = (
  1549. functools.partial(vm_info.vm.handle_firewall_xml, vm), None)
  1550. handlers[os.path.join(vm_info.subdir,
  1551. 'whitelisted-appmenus.list')] = (
  1552. functools.partial(self._handle_appmenus_list, vm), None)
  1553. if 'dom0' in restore_info.keys() and \
  1554. restore_info['dom0'].good_to_go:
  1555. vms_dirs.append(os.path.dirname(restore_info['dom0'].subdir))
  1556. vms_size += restore_info['dom0'].size
  1557. handlers[restore_info['dom0'].subdir] = (self._handle_dom0, None)
  1558. try:
  1559. self._restore_vm_data(vms_dirs=vms_dirs, vms_size=vms_size,
  1560. handlers=handlers)
  1561. except QubesException as err:
  1562. if self.options.verify_only:
  1563. raise
  1564. else:
  1565. self.log.error('Error extracting data: ' + str(err))
  1566. self.log.warning(
  1567. "Continuing anyway to restore at least some VMs")
  1568. if self.options.verify_only:
  1569. shutil.rmtree(self.tmpdir)
  1570. return
  1571. if self.canceled:
  1572. raise BackupCanceledError("Restore canceled",
  1573. tmpdir=self.tmpdir)
  1574. shutil.rmtree(self.tmpdir)
  1575. self.log.info("-> Done. Please install updates for all the restored "
  1576. "templates.")
  1577. def _restore_vms_metadata(self, restore_info):
  1578. '''Restore VM metadata
  1579. Create VMs, set their properties etc.
  1580. '''
  1581. vms = {}
  1582. for vm_info in restore_info.values():
  1583. assert isinstance(vm_info, self.VMToRestore)
  1584. if not vm_info.vm:
  1585. continue
  1586. if not vm_info.good_to_go:
  1587. continue
  1588. vm = vm_info.vm
  1589. vms[vm.name] = vm
  1590. # First load templates, then other VMs
  1591. for vm in self._templates_first(vms.values()):
  1592. if self.canceled:
  1593. return
  1594. self.log.info("-> Restoring %s...", vm.name)
  1595. kwargs = {}
  1596. if vm.template:
  1597. template = restore_info[vm.name].template
  1598. # handle potentially renamed template
  1599. if template in restore_info \
  1600. and restore_info[template].good_to_go:
  1601. template = restore_info[template].name
  1602. kwargs['template'] = template
  1603. new_vm = None
  1604. vm_name = restore_info[vm.name].name
  1605. try:
  1606. # first only create VMs, later setting may require other VMs
  1607. # be already created
  1608. new_vm = self.app.add_new_vm(
  1609. vm.klass,
  1610. name=vm_name,
  1611. label=vm.label,
  1612. pool=self.options.override_pool,
  1613. **kwargs)
  1614. except Exception as err: # pylint: disable=broad-except
  1615. self.log.error('Error restoring VM %s, skipping: %s',
  1616. vm.name, err)
  1617. if new_vm:
  1618. del self.app.domains[new_vm.name]
  1619. continue
  1620. restore_info[vm.name].restored_vm = new_vm
  1621. for vm in vms.values():
  1622. if self.canceled:
  1623. return
  1624. new_vm = restore_info[vm.name].restored_vm
  1625. if not new_vm:
  1626. # skipped/failed
  1627. continue
  1628. for prop, value in vm.properties.items():
  1629. # exclude VM references - handled manually according to
  1630. # restore options
  1631. if prop in ['template', 'netvm', 'default_dispvm']:
  1632. continue
  1633. try:
  1634. setattr(new_vm, prop, value)
  1635. except Exception as err: # pylint: disable=broad-except
  1636. self.log.error('Error setting %s.%s to %s: %s',
  1637. vm.name, prop, value, err)
  1638. for feature, value in vm.features.items():
  1639. try:
  1640. new_vm.features[feature] = value
  1641. except Exception as err: # pylint: disable=broad-except
  1642. self.log.error('Error setting %s.features[%s] to %s: %s',
  1643. vm.name, feature, value, err)
  1644. for tag in vm.tags:
  1645. try:
  1646. new_vm.tags.add(tag)
  1647. except Exception as err: # pylint: disable=broad-except
  1648. self.log.error('Error adding tag %s to %s: %s',
  1649. tag, vm.name, err)
  1650. for bus in vm.devices:
  1651. for backend_domain, ident in vm.devices[bus]:
  1652. options = vm.devices[bus][(backend_domain, ident)]
  1653. assignment = DeviceAssignment(
  1654. backend_domain=backend_domain,
  1655. ident=ident,
  1656. options=options,
  1657. persistent=True)
  1658. try:
  1659. new_vm.devices[bus].attach(assignment)
  1660. except Exception as err: # pylint: disable=broad-except
  1661. self.log.error('Error attaching device %s:%s to %s: %s',
  1662. bus, ident, vm.name, err)
  1663. # Set VM dependencies - only non-default setting
  1664. for vm in vms.values():
  1665. vm_info = restore_info[vm.name]
  1666. vm_name = vm_info.name
  1667. try:
  1668. host_vm = self.app.domains[vm_name]
  1669. except KeyError:
  1670. # Failed/skipped VM
  1671. continue
  1672. if 'netvm' in vm.properties:
  1673. if vm_info.netvm in restore_info:
  1674. value = restore_info[vm_info.netvm].name
  1675. else:
  1676. value = vm_info.netvm
  1677. try:
  1678. host_vm.netvm = value
  1679. except Exception as err: # pylint: disable=broad-except
  1680. self.log.error('Error setting %s.%s to %s: %s',
  1681. vm.name, 'netvm', value, err)
  1682. if 'default_dispvm' in vm.properties:
  1683. if vm.properties['default_dispvm'] in restore_info:
  1684. value = restore_info[vm.properties[
  1685. 'default_dispvm']].name
  1686. else:
  1687. value = vm.properties['default_dispvm']
  1688. try:
  1689. host_vm.default_dispvm = value
  1690. except Exception as err: # pylint: disable=broad-except
  1691. self.log.error('Error setting %s.%s to %s: %s',
  1692. vm.name, 'default_dispvm', value, err)