restore.py 75 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908
  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. class BackupRestore(object):
  659. """Usage:
  660. >>> restore_op = BackupRestore(...)
  661. >>> # adjust restore_op.options here
  662. >>> restore_info = restore_op.get_restore_info()
  663. >>> # manipulate restore_info to select VMs to restore here
  664. >>> restore_op.restore_do(restore_info)
  665. """
  666. class VMToRestore(object):
  667. '''Information about a single VM to be restored'''
  668. # pylint: disable=too-few-public-methods
  669. #: VM excluded from restore by user
  670. EXCLUDED = object()
  671. #: VM with such name already exists on the host
  672. ALREADY_EXISTS = object()
  673. #: NetVM used by the VM does not exists on the host
  674. MISSING_NETVM = object()
  675. #: TemplateVM used by the VM does not exists on the host
  676. MISSING_TEMPLATE = object()
  677. #: Kernel used by the VM does not exists on the host
  678. MISSING_KERNEL = object()
  679. def __init__(self, vm):
  680. assert isinstance(vm, BackupVM)
  681. self.vm = vm
  682. self.name = vm.name
  683. self.subdir = vm.backup_path
  684. self.size = vm.size
  685. self.problems = set()
  686. self.template = vm.template
  687. if vm.properties.get('netvm', None):
  688. self.netvm = vm.properties['netvm']
  689. else:
  690. self.netvm = None
  691. self.orig_template = None
  692. self.restored_vm = None
  693. @property
  694. def good_to_go(self):
  695. '''Is the VM ready for restore?'''
  696. return len(self.problems) == 0
  697. class Dom0ToRestore(VMToRestore):
  698. '''Information about dom0 home to restore'''
  699. # pylint: disable=too-few-public-methods
  700. #: backup was performed on system with different dom0 username
  701. USERNAME_MISMATCH = object()
  702. def __init__(self, vm, subdir=None):
  703. super(BackupRestore.Dom0ToRestore, self).__init__(vm)
  704. if subdir:
  705. self.subdir = subdir
  706. self.username = os.path.basename(subdir)
  707. def __init__(self, app, backup_location, backup_vm, passphrase):
  708. super(BackupRestore, self).__init__()
  709. #: qubes.Qubes instance
  710. self.app = app
  711. #: options how the backup should be restored
  712. self.options = BackupRestoreOptions()
  713. #: VM from which backup should be retrieved
  714. self.backup_vm = backup_vm
  715. if backup_vm and backup_vm.qid == 0:
  716. self.backup_vm = None
  717. #: backup path, inside VM pointed by :py:attr:`backup_vm`
  718. self.backup_location = backup_location
  719. #: passphrase protecting backup integrity and optionally decryption
  720. self.passphrase = passphrase
  721. #: temporary directory used to extract the data before moving to the
  722. # final location
  723. self.tmpdir = tempfile.mkdtemp(prefix="restore", dir="/var/tmp")
  724. #: list of processes (Popen objects) to kill on cancel
  725. self.processes_to_kill_on_cancel = []
  726. #: is the backup operation canceled
  727. self.canceled = False
  728. #: report restore progress, called with one argument - percents of
  729. # data restored
  730. # FIXME: convert to float [0,1]
  731. self.progress_callback = None
  732. self.log = logging.getLogger('qubesadmin.backup')
  733. #: basic information about the backup
  734. self.header_data = self._retrieve_backup_header()
  735. #: VMs included in the backup
  736. self.backup_app = self._process_qubes_xml()
  737. def _start_retrieval_process(self, filelist, limit_count, limit_bytes):
  738. """Retrieve backup stream and extract it to :py:attr:`tmpdir`
  739. :param filelist: list of files to extract; listing directory name
  740. will extract the whole directory; use empty list to extract the whole
  741. archive
  742. :param limit_count: maximum number of files to extract
  743. :param limit_bytes: maximum size of extracted data
  744. :return: a touple of (Popen object of started process, file-like
  745. object for reading extracted files list, file-like object for reading
  746. errors)
  747. """
  748. vmproc = None
  749. if self.backup_vm is not None:
  750. # If APPVM, STDOUT is a PIPE
  751. vmproc = self.backup_vm.run_service('qubes.Restore')
  752. vmproc.stdin.write(
  753. (self.backup_location.replace("\r", "").replace("\n",
  754. "") + "\n").encode())
  755. vmproc.stdin.flush()
  756. # Send to tar2qfile the VMs that should be extracted
  757. vmproc.stdin.write((" ".join(filelist) + "\n").encode())
  758. vmproc.stdin.flush()
  759. self.processes_to_kill_on_cancel.append(vmproc)
  760. backup_stdin = vmproc.stdout
  761. tar1_command = ['/usr/libexec/qubes/qfile-dom0-unpacker',
  762. str(os.getuid()), self.tmpdir, '-v']
  763. else:
  764. backup_stdin = open(self.backup_location, 'rb')
  765. tar1_command = ['tar',
  766. '-ixv',
  767. '-C', self.tmpdir] + filelist
  768. tar1_env = os.environ.copy()
  769. tar1_env['UPDATES_MAX_BYTES'] = str(limit_bytes)
  770. tar1_env['UPDATES_MAX_FILES'] = str(limit_count)
  771. self.log.debug("Run command" + str(tar1_command))
  772. command = subprocess.Popen(
  773. tar1_command,
  774. stdin=backup_stdin,
  775. stdout=vmproc.stdin if vmproc else subprocess.PIPE,
  776. stderr=subprocess.PIPE,
  777. env=tar1_env)
  778. backup_stdin.close()
  779. self.processes_to_kill_on_cancel.append(command)
  780. # qfile-dom0-unpacker output filelist on stderr
  781. # and have stdout connected to the VM), while tar output filelist
  782. # on stdout
  783. if self.backup_vm:
  784. filelist_pipe = command.stderr
  785. # let qfile-dom0-unpacker hold the only open FD to the write end of
  786. # pipe, otherwise qrexec-client will not receive EOF when
  787. # qfile-dom0-unpacker terminates
  788. vmproc.stdin.close()
  789. else:
  790. filelist_pipe = command.stdout
  791. if self.backup_vm:
  792. error_pipe = vmproc.stderr
  793. else:
  794. error_pipe = command.stderr
  795. return command, filelist_pipe, error_pipe
  796. def _verify_hmac(self, filename, hmacfile, algorithm=None):
  797. '''Verify hmac of a file using given algorithm.
  798. If algorithm is not specified, use the one from backup header (
  799. :py:attr:`header_data`).
  800. Raise :py:exc:`QubesException` on failure, return :py:obj:`True` on
  801. success.
  802. 'scrypt' algorithm is supported only for header file; hmac file is
  803. encrypted (and integrity protected) version of plain header.
  804. :param filename: path to file to be verified
  805. :param hmacfile: path to hmac file for *filename*
  806. :param algorithm: override algorithm
  807. '''
  808. def load_hmac(hmac_text):
  809. '''Parse hmac output by openssl.
  810. Return just hmac, without filename and other metadata.
  811. '''
  812. if any(ord(x) not in range(128) for x in hmac_text):
  813. raise QubesException(
  814. "Invalid content of {}".format(hmacfile))
  815. hmac_text = hmac_text.strip().split("=")
  816. if len(hmac_text) > 1:
  817. hmac_text = hmac_text[1].strip()
  818. else:
  819. raise QubesException(
  820. "ERROR: invalid hmac file content")
  821. return hmac_text
  822. if algorithm is None:
  823. algorithm = self.header_data.hmac_algorithm
  824. passphrase = self.passphrase.encode('utf-8')
  825. self.log.debug("Verifying file %s", filename)
  826. if os.stat(os.path.join(self.tmpdir, hmacfile)).st_size > \
  827. HMAC_MAX_SIZE:
  828. raise QubesException('HMAC file {} too large'.format(
  829. hmacfile))
  830. if hmacfile != filename + ".hmac":
  831. raise QubesException(
  832. "ERROR: expected hmac for {}, but got {}".
  833. format(filename, hmacfile))
  834. if algorithm == 'scrypt':
  835. # in case of 'scrypt' _verify_hmac is only used for backup header
  836. assert filename == HEADER_FILENAME
  837. self._verify_and_decrypt(hmacfile, HEADER_FILENAME + '.dec')
  838. f_name = os.path.join(self.tmpdir, filename)
  839. with open(f_name, 'rb') as f_one:
  840. with open(f_name + '.dec', 'rb') as f_two:
  841. if f_one.read() != f_two.read():
  842. raise QubesException(
  843. 'Invalid hmac on {}'.format(filename))
  844. else:
  845. return True
  846. with open(os.path.join(self.tmpdir, filename), 'rb') as f_input:
  847. hmac_proc = subprocess.Popen(
  848. ["openssl", "dgst", "-" + algorithm, "-hmac", passphrase],
  849. stdin=f_input,
  850. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  851. hmac_stdout, hmac_stderr = hmac_proc.communicate()
  852. if hmac_stderr:
  853. raise QubesException(
  854. "ERROR: verify file {0}: {1}".format(filename, hmac_stderr))
  855. else:
  856. self.log.debug("Loading hmac for file %s", filename)
  857. with open(os.path.join(self.tmpdir, hmacfile), 'r',
  858. encoding='ascii') as f_hmac:
  859. hmac = load_hmac(f_hmac.read())
  860. if hmac and load_hmac(hmac_stdout.decode('ascii')) == hmac:
  861. os.unlink(os.path.join(self.tmpdir, hmacfile))
  862. self.log.debug(
  863. "File verification OK -> Sending file %s", filename)
  864. return True
  865. else:
  866. raise QubesException(
  867. "ERROR: invalid hmac for file {0}: {1}. "
  868. "Is the passphrase correct?".
  869. format(filename, load_hmac(hmac_stdout.decode('ascii'))))
  870. def _verify_and_decrypt(self, filename, output=None):
  871. '''Handle scrypt-wrapped file
  872. Decrypt the file, and verify its integrity - both tasks handled by
  873. 'scrypt' tool. Filename (without extension) is also validated.
  874. :param filename: Input file name (relative to :py:attr:`tmpdir`),
  875. needs to have `.enc` or `.hmac` extension
  876. :param output: Output file name (relative to :py:attr:`tmpdir`),
  877. use :py:obj:`None` to use *filename* without extension
  878. :return: *filename* without extension
  879. '''
  880. assert filename.endswith('.enc') or filename.endswith('.hmac')
  881. fullname = os.path.join(self.tmpdir, filename)
  882. (origname, _) = os.path.splitext(filename)
  883. if output:
  884. fulloutput = os.path.join(self.tmpdir, output)
  885. else:
  886. fulloutput = os.path.join(self.tmpdir, origname)
  887. if origname == HEADER_FILENAME:
  888. passphrase = u'{filename}!{passphrase}'.format(
  889. filename=origname,
  890. passphrase=self.passphrase)
  891. else:
  892. passphrase = u'{backup_id}!{filename}!{passphrase}'.format(
  893. backup_id=self.header_data.backup_id,
  894. filename=origname,
  895. passphrase=self.passphrase)
  896. try:
  897. p = launch_scrypt('dec', fullname, fulloutput, passphrase)
  898. except OSError as err:
  899. raise QubesException('failed to decrypt {}: {!s}'.format(
  900. fullname, err))
  901. (_, stderr) = p.communicate()
  902. if hasattr(p, 'pty'):
  903. p.pty.close()
  904. if p.returncode != 0:
  905. os.unlink(fulloutput)
  906. raise QubesException('failed to decrypt {}: {}'.format(
  907. fullname, stderr))
  908. # encrypted file is no longer needed
  909. os.unlink(fullname)
  910. return origname
  911. def _retrieve_backup_header_files(self, files, allow_none=False):
  912. '''Retrieve backup header.
  913. Start retrieval process (possibly involving network access from
  914. another VM). Returns a collection of retrieved file paths.
  915. '''
  916. (retrieve_proc, filelist_pipe, error_pipe) = \
  917. self._start_retrieval_process(
  918. files, len(files), 1024 * 1024)
  919. filelist = filelist_pipe.read()
  920. filelist_pipe.close()
  921. retrieve_proc_returncode = retrieve_proc.wait()
  922. if retrieve_proc in self.processes_to_kill_on_cancel:
  923. self.processes_to_kill_on_cancel.remove(retrieve_proc)
  924. extract_stderr = error_pipe.read(MAX_STDERR_BYTES)
  925. error_pipe.close()
  926. # wait for other processes (if any)
  927. for proc in self.processes_to_kill_on_cancel:
  928. if proc.wait() != 0:
  929. raise QubesException(
  930. "Backup header retrieval failed (exit code {})".format(
  931. proc.wait())
  932. )
  933. if retrieve_proc_returncode != 0:
  934. if not filelist and 'Not found in archive' in extract_stderr:
  935. if allow_none:
  936. return None
  937. else:
  938. raise QubesException(
  939. "unable to read the qubes backup file {0} ({1}): {2}".
  940. format(
  941. self.backup_location,
  942. retrieve_proc.wait(),
  943. extract_stderr
  944. ))
  945. actual_files = filelist.decode('ascii').splitlines()
  946. if sorted(actual_files) != sorted(files):
  947. raise QubesException(
  948. 'unexpected files in archive: got {!r}, expected {!r}'.format(
  949. actual_files, files
  950. ))
  951. for fname in files:
  952. if not os.path.exists(os.path.join(self.tmpdir, fname)):
  953. if allow_none:
  954. return None
  955. else:
  956. raise QubesException(
  957. 'Unable to retrieve file {} from backup {}: {}'.format(
  958. fname, self.backup_location, extract_stderr
  959. )
  960. )
  961. return files
  962. def _retrieve_backup_header(self):
  963. """Retrieve backup header and qubes.xml. Only backup header is
  964. analyzed, qubes.xml is left as-is
  965. (not even verified/decrypted/uncompressed)
  966. :return header_data
  967. :rtype :py:class:`BackupHeader`
  968. """
  969. if not self.backup_vm and os.path.exists(
  970. os.path.join(self.backup_location, 'qubes.xml')):
  971. # backup format version 1 doesn't have header
  972. header_data = BackupHeader()
  973. header_data.version = 1
  974. return header_data
  975. header_files = self._retrieve_backup_header_files(
  976. ['backup-header', 'backup-header.hmac'], allow_none=True)
  977. if not header_files:
  978. # R2-Beta3 didn't have backup header, so if none is found,
  979. # assume it's version=2 and use values present at that time
  980. header_data = BackupHeader(
  981. version=2,
  982. # place explicitly this value, because it is what format_version
  983. # 2 have
  984. hmac_algorithm='SHA1',
  985. crypto_algorithm='aes-256-cbc',
  986. # TODO: set encrypted to something...
  987. )
  988. else:
  989. filename = HEADER_FILENAME
  990. hmacfile = HEADER_FILENAME + '.hmac'
  991. self.log.debug("Got backup header and hmac: %s, %s",
  992. filename, hmacfile)
  993. file_ok = False
  994. hmac_algorithm = DEFAULT_HMAC_ALGORITHM
  995. for hmac_algo in get_supported_hmac_algo(hmac_algorithm):
  996. try:
  997. if self._verify_hmac(filename, hmacfile, hmac_algo):
  998. file_ok = True
  999. break
  1000. except QubesException as err:
  1001. self.log.debug(
  1002. 'Failed to verify %s using %s: %r',
  1003. hmacfile, hmac_algo, err)
  1004. # Ignore exception here, try the next algo
  1005. if not file_ok:
  1006. raise QubesException(
  1007. "Corrupted backup header (hmac verification "
  1008. "failed). Is the password correct?")
  1009. filename = os.path.join(self.tmpdir, filename)
  1010. with open(filename, 'rb') as f_header:
  1011. header_data = BackupHeader(f_header.read())
  1012. os.unlink(filename)
  1013. return header_data
  1014. def _start_inner_extraction_worker(self, queue, handlers):
  1015. """Start a worker process, extracting inner layer of bacup archive,
  1016. extract them to :py:attr:`tmpdir`.
  1017. End the data by pushing QUEUE_FINISHED or QUEUE_ERROR to the queue.
  1018. :param queue :py:class:`Queue` object to handle files from
  1019. """
  1020. # Setup worker to extract encrypted data chunks to the restore dirs
  1021. # Create the process here to pass it options extracted from
  1022. # backup header
  1023. extractor_params = {
  1024. 'queue': queue,
  1025. 'base_dir': self.tmpdir,
  1026. 'passphrase': self.passphrase,
  1027. 'encrypted': self.header_data.encrypted,
  1028. 'compressed': self.header_data.compressed,
  1029. 'crypto_algorithm': self.header_data.crypto_algorithm,
  1030. 'verify_only': self.options.verify_only,
  1031. 'progress_callback': self.progress_callback,
  1032. 'handlers': handlers,
  1033. }
  1034. self.log.debug(
  1035. 'Starting extraction worker in %s, file handlers map: %s',
  1036. self.tmpdir, repr(handlers))
  1037. format_version = self.header_data.version
  1038. if format_version in [3, 4]:
  1039. extractor_params['compression_filter'] = \
  1040. self.header_data.compression_filter
  1041. if format_version == 4:
  1042. # encryption already handled
  1043. extractor_params['encrypted'] = False
  1044. extract_proc = ExtractWorker3(**extractor_params)
  1045. else:
  1046. raise NotImplementedError(
  1047. "Backup format version %d not supported" % format_version)
  1048. extract_proc.start()
  1049. return extract_proc
  1050. @staticmethod
  1051. def _save_qubes_xml(path, stream):
  1052. '''Handler for qubes.xml.000 content - just save the data to a file'''
  1053. with open(path, 'wb') as f_qubesxml:
  1054. f_qubesxml.write(stream.read())
  1055. def _process_qubes_xml(self):
  1056. """Verify, unpack and load qubes.xml. Possibly convert its format if
  1057. necessary. It expect that :py:attr:`header_data` is already populated,
  1058. and :py:meth:`retrieve_backup_header` was called.
  1059. """
  1060. if self.header_data.version == 1:
  1061. raise NotImplementedError('Backup format version 1 not supported')
  1062. elif self.header_data.version in [2, 3]:
  1063. self._retrieve_backup_header_files(
  1064. ['qubes.xml.000', 'qubes.xml.000.hmac'])
  1065. self._verify_hmac("qubes.xml.000", "qubes.xml.000.hmac")
  1066. else:
  1067. self._retrieve_backup_header_files(['qubes.xml.000.enc'])
  1068. self._verify_and_decrypt('qubes.xml.000.enc')
  1069. queue = Queue()
  1070. queue.put("qubes.xml.000")
  1071. queue.put(QUEUE_FINISHED)
  1072. qubes_xml_path = os.path.join(self.tmpdir, 'qubes-restored.xml')
  1073. handlers = {
  1074. 'qubes.xml': (
  1075. functools.partial(self._save_qubes_xml, qubes_xml_path),
  1076. None)
  1077. }
  1078. extract_proc = self._start_inner_extraction_worker(queue, handlers)
  1079. extract_proc.join()
  1080. if extract_proc.exitcode != 0:
  1081. raise QubesException(
  1082. "unable to extract the qubes backup. "
  1083. "Check extracting process errors.")
  1084. if self.header_data.version in [2, 3]:
  1085. backup_app = Core2Qubes(qubes_xml_path)
  1086. elif self.header_data.version in [4]:
  1087. backup_app = Core3Qubes(qubes_xml_path)
  1088. else:
  1089. raise QubesException(
  1090. 'Unsupported qubes.xml format version: {}'.format(
  1091. self.header_data.version))
  1092. # Not needed anymore - all the data stored in backup_app
  1093. os.unlink(qubes_xml_path)
  1094. return backup_app
  1095. def _restore_vm_data(self, vms_dirs, vms_size, handlers):
  1096. '''Restore data of VMs
  1097. :param vms_dirs: list of directories to extract (skip others)
  1098. :param vms_size: expected size (abort if source stream exceed this
  1099. value)
  1100. :param handlers: handlers for restored files - see
  1101. :py:class:`ExtractWorker3` for details
  1102. '''
  1103. # Currently each VM consists of at most 7 archives (count
  1104. # file_to_backup calls in backup_prepare()), but add some safety
  1105. # margin for further extensions. Each archive is divided into 100MB
  1106. # chunks. Additionally each file have own hmac file. So assume upper
  1107. # limit as 2*(10*COUNT_OF_VMS+TOTAL_SIZE/100MB)
  1108. limit_count = str(2 * (10 * len(vms_dirs) +
  1109. int(vms_size / (100 * 1024 * 1024))))
  1110. self.log.debug("Working in temporary dir: %s", self.tmpdir)
  1111. self.log.info("Extracting data: %s to restore", size_to_human(vms_size))
  1112. # retrieve backup from the backup stream (either VM, or dom0 file)
  1113. (retrieve_proc, filelist_pipe, error_pipe) = \
  1114. self._start_retrieval_process(
  1115. vms_dirs, limit_count, vms_size)
  1116. to_extract = Queue()
  1117. # extract data retrieved by retrieve_proc
  1118. extract_proc = self._start_inner_extraction_worker(
  1119. to_extract, handlers)
  1120. try:
  1121. filename = None
  1122. hmacfile = None
  1123. nextfile = None
  1124. while True:
  1125. if self.canceled:
  1126. break
  1127. if not extract_proc.is_alive():
  1128. retrieve_proc.terminate()
  1129. retrieve_proc.wait()
  1130. if retrieve_proc in self.processes_to_kill_on_cancel:
  1131. self.processes_to_kill_on_cancel.remove(retrieve_proc)
  1132. # wait for other processes (if any)
  1133. for proc in self.processes_to_kill_on_cancel:
  1134. proc.wait()
  1135. break
  1136. if nextfile is not None:
  1137. filename = nextfile
  1138. else:
  1139. filename = filelist_pipe.readline().decode('ascii').strip()
  1140. self.log.debug("Getting new file: %s", filename)
  1141. if not filename or filename == "EOF":
  1142. break
  1143. # if reading archive directly with tar, wait for next filename -
  1144. # tar prints filename before processing it, so wait for
  1145. # the next one to be sure that whole file was extracted
  1146. if not self.backup_vm:
  1147. nextfile = filelist_pipe.readline().decode('ascii').strip()
  1148. if self.header_data.version in [2, 3]:
  1149. if not self.backup_vm:
  1150. hmacfile = nextfile
  1151. nextfile = filelist_pipe.readline().\
  1152. decode('ascii').strip()
  1153. else:
  1154. hmacfile = filelist_pipe.readline().\
  1155. decode('ascii').strip()
  1156. if self.canceled:
  1157. break
  1158. self.log.debug("Getting hmac: %s", hmacfile)
  1159. if not hmacfile or hmacfile == "EOF":
  1160. # Premature end of archive, either of tar1_command or
  1161. # vmproc exited with error
  1162. break
  1163. else: # self.header_data.version == 4
  1164. if not filename.endswith('.enc'):
  1165. raise qubesadmin.exc.QubesException(
  1166. 'Invalid file extension found in archive: {}'.
  1167. format(filename))
  1168. if not any(filename.startswith(x) for x in vms_dirs):
  1169. self.log.debug("Ignoring VM not selected for restore")
  1170. os.unlink(os.path.join(self.tmpdir, filename))
  1171. if hmacfile:
  1172. os.unlink(os.path.join(self.tmpdir, hmacfile))
  1173. continue
  1174. if self.header_data.version in [2, 3]:
  1175. self._verify_hmac(filename, hmacfile)
  1176. else:
  1177. # _verify_and_decrypt will write output to a file with
  1178. # '.enc' extension cut off. This is safe because:
  1179. # - `scrypt` tool will override output, so if the file was
  1180. # already there (received from the VM), it will be removed
  1181. # - incoming archive extraction will refuse to override
  1182. # existing file, so if `scrypt` already created one,
  1183. # it can not be manipulated by the VM
  1184. # - when the file is retrieved from the VM, it appears at
  1185. # the final form - if it's visible, VM have no longer
  1186. # influence over its content
  1187. #
  1188. # This all means that if the file was correctly verified
  1189. # + decrypted, we will surely access the right file
  1190. filename = self._verify_and_decrypt(filename)
  1191. to_extract.put(os.path.join(self.tmpdir, filename))
  1192. if self.canceled:
  1193. raise BackupCanceledError("Restore canceled",
  1194. tmpdir=self.tmpdir)
  1195. if retrieve_proc.wait() != 0:
  1196. raise QubesException(
  1197. "unable to read the qubes backup file {0}: {1}"
  1198. .format(self.backup_location, error_pipe.read(
  1199. MAX_STDERR_BYTES)))
  1200. # wait for other processes (if any)
  1201. for proc in self.processes_to_kill_on_cancel:
  1202. proc.wait()
  1203. if proc.returncode != 0:
  1204. raise QubesException(
  1205. "Backup completed, "
  1206. "but VM sending it reported an error (exit code {})".
  1207. format(proc.returncode))
  1208. if filename and filename != "EOF":
  1209. raise QubesException(
  1210. "Premature end of archive, the last file was %s" % filename)
  1211. except:
  1212. to_extract.put(QUEUE_ERROR)
  1213. extract_proc.join()
  1214. raise
  1215. else:
  1216. to_extract.put(QUEUE_FINISHED)
  1217. finally:
  1218. error_pipe.close()
  1219. filelist_pipe.close()
  1220. self.log.debug("Waiting for the extraction process to finish...")
  1221. extract_proc.join()
  1222. self.log.debug("Extraction process finished with code: %s",
  1223. extract_proc.exitcode)
  1224. if extract_proc.exitcode != 0:
  1225. raise QubesException(
  1226. "unable to extract the qubes backup. "
  1227. "Check extracting process errors.")
  1228. def new_name_for_conflicting_vm(self, orig_name, restore_info):
  1229. '''Generate new name for conflicting VM
  1230. Add a number suffix, until the name is unique. If no unique name can
  1231. be found using this strategy, return :py:obj:`None`
  1232. '''
  1233. number = 1
  1234. if len(orig_name) > 29:
  1235. orig_name = orig_name[0:29]
  1236. new_name = orig_name
  1237. while (new_name in restore_info.keys() or
  1238. new_name in [x.name for x in restore_info.values()] or
  1239. new_name in self.app.domains):
  1240. new_name = str('{}{}'.format(orig_name, number))
  1241. number += 1
  1242. if number == 100:
  1243. # give up
  1244. return None
  1245. return new_name
  1246. def restore_info_verify(self, restore_info):
  1247. '''Verify restore info - validate VM dependencies, name conflicts
  1248. etc.
  1249. '''
  1250. for vm in restore_info.keys():
  1251. if vm in ['dom0']:
  1252. continue
  1253. vm_info = restore_info[vm]
  1254. assert isinstance(vm_info, self.VMToRestore)
  1255. vm_info.problems.clear()
  1256. if vm in self.options.exclude:
  1257. vm_info.problems.add(self.VMToRestore.EXCLUDED)
  1258. if not self.options.verify_only and \
  1259. vm_info.name in self.app.domains:
  1260. if self.options.rename_conflicting:
  1261. new_name = self.new_name_for_conflicting_vm(
  1262. vm, restore_info
  1263. )
  1264. if new_name is not None:
  1265. vm_info.name = new_name
  1266. else:
  1267. vm_info.problems.add(self.VMToRestore.ALREADY_EXISTS)
  1268. else:
  1269. vm_info.problems.add(self.VMToRestore.ALREADY_EXISTS)
  1270. # check template
  1271. if vm_info.template:
  1272. template_name = vm_info.template
  1273. try:
  1274. host_template = self.app.domains[template_name]
  1275. except KeyError:
  1276. host_template = None
  1277. present_on_host = (host_template and
  1278. isinstance(host_template, qubesadmin.vm.TemplateVM))
  1279. present_in_backup = (template_name in restore_info.keys() and
  1280. restore_info[template_name].good_to_go and
  1281. restore_info[template_name].vm.klass ==
  1282. 'TemplateVM')
  1283. if not present_on_host and not present_in_backup:
  1284. if self.options.use_default_template and \
  1285. self.app.default_template:
  1286. if vm_info.orig_template is None:
  1287. vm_info.orig_template = template_name
  1288. vm_info.template = self.app.default_template.name
  1289. else:
  1290. vm_info.problems.add(
  1291. self.VMToRestore.MISSING_TEMPLATE)
  1292. # check netvm
  1293. if vm_info.vm.properties.get('netvm', None) is not None:
  1294. netvm_name = vm_info.netvm
  1295. try:
  1296. netvm_on_host = self.app.domains[netvm_name]
  1297. except KeyError:
  1298. netvm_on_host = None
  1299. present_on_host = (netvm_on_host is not None
  1300. and netvm_on_host.provides_network)
  1301. present_in_backup = (netvm_name in restore_info.keys() and
  1302. restore_info[netvm_name].good_to_go and
  1303. restore_info[netvm_name].vm.properties.get(
  1304. 'provides_network', False))
  1305. if not present_on_host and not present_in_backup:
  1306. if self.options.use_default_netvm:
  1307. del vm_info.vm.properties['netvm']
  1308. elif self.options.use_none_netvm:
  1309. vm_info.netvm = None
  1310. else:
  1311. vm_info.problems.add(self.VMToRestore.MISSING_NETVM)
  1312. return restore_info
  1313. def get_restore_info(self):
  1314. '''Get restore info
  1315. Return information about what is included in the backup.
  1316. That dictionary can be adjusted to select what VM should be restore.
  1317. '''
  1318. # Format versions:
  1319. # 1 - Qubes R1, Qubes R2 beta1, beta2
  1320. # 2 - Qubes R2 beta3+
  1321. # 3 - Qubes R2+
  1322. # 4 - Qubes R4+
  1323. vms_to_restore = {}
  1324. for vm in self.backup_app.domains.values():
  1325. if vm.klass == 'AdminVM':
  1326. # Handle dom0 as special case later
  1327. continue
  1328. if vm.included_in_backup:
  1329. self.log.debug("%s is included in backup", vm.name)
  1330. vms_to_restore[vm.name] = self.VMToRestore(vm)
  1331. if vm.template is not None:
  1332. templatevm_name = vm.template
  1333. vms_to_restore[vm.name].template = templatevm_name
  1334. vms_to_restore = self.restore_info_verify(vms_to_restore)
  1335. # ...and dom0 home
  1336. if self.options.dom0_home and \
  1337. self.backup_app.domains['dom0'].included_in_backup:
  1338. vm = self.backup_app.domains['dom0']
  1339. vms_to_restore['dom0'] = self.Dom0ToRestore(vm)
  1340. local_user = grp.getgrnam('qubes').gr_mem[0]
  1341. if vms_to_restore['dom0'].username != local_user:
  1342. if not self.options.ignore_username_mismatch:
  1343. vms_to_restore['dom0'].problems.add(
  1344. self.Dom0ToRestore.USERNAME_MISMATCH)
  1345. return vms_to_restore
  1346. @staticmethod
  1347. def get_restore_summary(restore_info):
  1348. '''Return a ASCII formatted table with restore info summary'''
  1349. fields = {
  1350. "name": {'func': lambda vm: vm.name},
  1351. "type": {'func': lambda vm: vm.klass},
  1352. "template": {'func': lambda vm:
  1353. 'n/a' if vm.template is None else vm.template},
  1354. "netvm": {'func': lambda vm:
  1355. '(default)' if 'netvm' not in vm.properties else
  1356. '-' if vm.properties['netvm'] is None else
  1357. vm.properties['netvm']},
  1358. "label": {'func': lambda vm: vm.label},
  1359. }
  1360. fields_to_display = ['name', 'type', 'template',
  1361. 'netvm', 'label']
  1362. # First calculate the maximum width of each field we want to display
  1363. total_width = 0
  1364. for field in fields_to_display:
  1365. fields[field]['max_width'] = len(field)
  1366. for vm_info in restore_info.values():
  1367. if vm_info.vm:
  1368. # noinspection PyUnusedLocal
  1369. field_len = len(str(fields[field]["func"](vm_info.vm)))
  1370. if field_len > fields[field]['max_width']:
  1371. fields[field]['max_width'] = field_len
  1372. total_width += fields[field]['max_width']
  1373. summary = ""
  1374. summary += "The following VMs are included in the backup:\n"
  1375. summary += "\n"
  1376. # Display the header
  1377. for field in fields_to_display:
  1378. # noinspection PyTypeChecker
  1379. fmt = "{{0:-^{0}}}-+".format(fields[field]["max_width"] + 1)
  1380. summary += fmt.format('-')
  1381. summary += "\n"
  1382. for field in fields_to_display:
  1383. # noinspection PyTypeChecker
  1384. fmt = "{{0:>{0}}} |".format(fields[field]["max_width"] + 1)
  1385. summary += fmt.format(field)
  1386. summary += "\n"
  1387. for field in fields_to_display:
  1388. # noinspection PyTypeChecker
  1389. fmt = "{{0:-^{0}}}-+".format(fields[field]["max_width"] + 1)
  1390. summary += fmt.format('-')
  1391. summary += "\n"
  1392. for vm_info in restore_info.values():
  1393. assert isinstance(vm_info, BackupRestore.VMToRestore)
  1394. # Skip non-VM here
  1395. if not vm_info.vm:
  1396. continue
  1397. # noinspection PyUnusedLocal
  1398. summary_line = ""
  1399. for field in fields_to_display:
  1400. # noinspection PyTypeChecker
  1401. fmt = "{{0:>{0}}} |".format(fields[field]["max_width"] + 1)
  1402. summary_line += fmt.format(fields[field]["func"](vm_info.vm))
  1403. if BackupRestore.VMToRestore.EXCLUDED in vm_info.problems:
  1404. summary_line += " <-- Excluded from restore"
  1405. elif BackupRestore.VMToRestore.ALREADY_EXISTS in vm_info.problems:
  1406. summary_line += \
  1407. " <-- A VM with the same name already exists on the host!"
  1408. elif BackupRestore.VMToRestore.MISSING_TEMPLATE in \
  1409. vm_info.problems:
  1410. summary_line += " <-- No matching template on the host " \
  1411. "or in the backup found!"
  1412. elif BackupRestore.VMToRestore.MISSING_NETVM in \
  1413. vm_info.problems:
  1414. summary_line += " <-- No matching netvm on the host " \
  1415. "or in the backup found!"
  1416. else:
  1417. if vm_info.template != vm_info.vm.template:
  1418. summary_line += " <-- Template change to '{}'".format(
  1419. vm_info.template)
  1420. if vm_info.name != vm_info.vm.name:
  1421. summary_line += " <-- Will be renamed to '{}'".format(
  1422. vm_info.name)
  1423. summary += summary_line + "\n"
  1424. if 'dom0' in restore_info.keys():
  1425. summary_line = ""
  1426. for field in fields_to_display:
  1427. # noinspection PyTypeChecker
  1428. fmt = "{{0:>{0}}} |".format(fields[field]["max_width"] + 1)
  1429. if field == "name":
  1430. summary_line += fmt.format("Dom0")
  1431. elif field == "type":
  1432. summary_line += fmt.format("Home")
  1433. else:
  1434. summary_line += fmt.format("")
  1435. if BackupRestore.Dom0ToRestore.USERNAME_MISMATCH in \
  1436. restore_info['dom0'].problems:
  1437. summary_line += " <-- username in backup and dom0 mismatch"
  1438. summary += summary_line + "\n"
  1439. return summary
  1440. @staticmethod
  1441. def _templates_first(vms):
  1442. '''Sort templates befor other VM types (AppVM etc)'''
  1443. def key_function(instance):
  1444. '''Key function for :py:func:`sorted`'''
  1445. if isinstance(instance, BackupVM):
  1446. return instance.klass == 'TemplateVM'
  1447. elif hasattr(instance, 'vm'):
  1448. return key_function(instance.vm)
  1449. return 0
  1450. return sorted(vms,
  1451. key=key_function,
  1452. reverse=True)
  1453. def _handle_dom0(self, backup_path):
  1454. '''Extract dom0 home'''
  1455. local_user = grp.getgrnam('qubes').gr_mem[0]
  1456. home_dir = pwd.getpwnam(local_user).pw_dir
  1457. backup_dom0_home_dir = os.path.join(self.tmpdir, backup_path)
  1458. restore_home_backupdir = "home-pre-restore-{0}".format(
  1459. time.strftime("%Y-%m-%d-%H%M%S"))
  1460. self.log.info("Restoring home of user '%s'...", local_user)
  1461. self.log.info("Existing files/dirs backed up in '%s' dir",
  1462. restore_home_backupdir)
  1463. os.mkdir(home_dir + '/' + restore_home_backupdir)
  1464. for f_name in os.listdir(backup_dom0_home_dir):
  1465. home_file = home_dir + '/' + f_name
  1466. if os.path.exists(home_file):
  1467. os.rename(home_file,
  1468. home_dir + '/' + restore_home_backupdir + '/' + f_name)
  1469. if self.header_data.version == 1:
  1470. subprocess.call(
  1471. ["cp", "-nrp", "--reflink=auto",
  1472. backup_dom0_home_dir + '/' + f_name, home_file])
  1473. elif self.header_data.version >= 2:
  1474. shutil.move(backup_dom0_home_dir + '/' + f_name, home_file)
  1475. retcode = subprocess.call(['sudo', 'chown', '-R',
  1476. local_user, home_dir])
  1477. if retcode != 0:
  1478. self.log.error("*** Error while setting home directory owner")
  1479. def _handle_appmenus_list(self, vm, stream):
  1480. '''Handle whitelisted-appmenus.list file'''
  1481. try:
  1482. subprocess.check_call(
  1483. ['qvm-appmenus', '--set-whitelist=-', vm.name],
  1484. stdin=stream)
  1485. except subprocess.CalledProcessError:
  1486. self.log.error('Failed to set application list for %s', vm.name)
  1487. def _handle_volume_data(self, vm, volume, stream):
  1488. '''Wrap volume data import with logging'''
  1489. try:
  1490. volume.import_data(stream)
  1491. except Exception as err: # pylint: disable=broad-except
  1492. self.log.error('Failed to restore volume %s of VM %s: %s',
  1493. volume.name, vm.name, err)
  1494. def _handle_volume_size(self, vm, volume, size):
  1495. '''Wrap volume resize with logging'''
  1496. try:
  1497. volume.resize(size)
  1498. except Exception as err: # pylint: disable=broad-except
  1499. self.log.error('Failed to resize volume %s of VM %s: %s',
  1500. volume.name, vm.name, err)
  1501. def restore_do(self, restore_info):
  1502. '''
  1503. High level workflow:
  1504. 1. Create VMs object in host collection (qubes.xml)
  1505. 2. Create them on disk (vm.create_on_disk)
  1506. 3. Restore VM data, overriding/converting VM files
  1507. 4. Apply possible fixups and save qubes.xml
  1508. :param restore_info:
  1509. :return:
  1510. '''
  1511. if self.header_data.version == 1:
  1512. raise NotImplementedError('Backup format version 1 not supported')
  1513. restore_info = self.restore_info_verify(restore_info)
  1514. self._restore_vms_metadata(restore_info)
  1515. # Perform VM restoration in backup order
  1516. vms_dirs = []
  1517. handlers = {}
  1518. vms_size = 0
  1519. for vm_info in self._templates_first(restore_info.values()):
  1520. vm = vm_info.restored_vm
  1521. if vm and vm_info.subdir:
  1522. vms_size += int(vm_info.size)
  1523. vms_dirs.append(vm_info.subdir)
  1524. for name, volume in vm.volumes.items():
  1525. if not volume.save_on_stop:
  1526. continue
  1527. data_func = functools.partial(
  1528. self._handle_volume_data, vm, volume)
  1529. size_func = functools.partial(
  1530. self._handle_volume_size, vm, volume)
  1531. handlers[os.path.join(vm_info.subdir, name + '.img')] = \
  1532. (data_func, size_func)
  1533. handlers[os.path.join(vm_info.subdir, 'firewall.xml')] = (
  1534. functools.partial(vm_info.vm.handle_firewall_xml, vm), None)
  1535. handlers[os.path.join(vm_info.subdir,
  1536. 'whitelisted-appmenus.list')] = (
  1537. functools.partial(self._handle_appmenus_list, vm), None)
  1538. if 'dom0' in restore_info.keys() and \
  1539. restore_info['dom0'].good_to_go:
  1540. vms_dirs.append(os.path.dirname(restore_info['dom0'].subdir))
  1541. vms_size += restore_info['dom0'].size
  1542. handlers[restore_info['dom0'].subdir] = (self._handle_dom0, None)
  1543. try:
  1544. self._restore_vm_data(vms_dirs=vms_dirs, vms_size=vms_size,
  1545. handlers=handlers)
  1546. except QubesException:
  1547. if self.options.verify_only:
  1548. raise
  1549. else:
  1550. self.log.warning(
  1551. "Some errors occurred during data extraction, "
  1552. "continuing anyway to restore at least some "
  1553. "VMs")
  1554. if self.options.verify_only:
  1555. shutil.rmtree(self.tmpdir)
  1556. return
  1557. if self.canceled:
  1558. raise BackupCanceledError("Restore canceled",
  1559. tmpdir=self.tmpdir)
  1560. shutil.rmtree(self.tmpdir)
  1561. self.log.info("-> Done. Please install updates for all the restored "
  1562. "templates.")
  1563. def _restore_vms_metadata(self, restore_info):
  1564. '''Restore VM metadata
  1565. Create VMs, set their properties etc.
  1566. '''
  1567. vms = {}
  1568. for vm_info in restore_info.values():
  1569. assert isinstance(vm_info, self.VMToRestore)
  1570. if not vm_info.vm:
  1571. continue
  1572. if not vm_info.good_to_go:
  1573. continue
  1574. vm = vm_info.vm
  1575. vms[vm.name] = vm
  1576. # First load templates, then other VMs
  1577. for vm in self._templates_first(vms.values()):
  1578. if self.canceled:
  1579. return
  1580. self.log.info("-> Restoring %s...", vm.name)
  1581. kwargs = {}
  1582. if vm.template:
  1583. template = restore_info[vm.name].template
  1584. # handle potentially renamed template
  1585. if template in restore_info \
  1586. and restore_info[template].good_to_go:
  1587. template = restore_info[template].name
  1588. kwargs['template'] = template
  1589. new_vm = None
  1590. vm_name = restore_info[vm.name].name
  1591. try:
  1592. # first only create VMs, later setting may require other VMs
  1593. # be already created
  1594. new_vm = self.app.add_new_vm(
  1595. vm.klass,
  1596. name=vm_name,
  1597. label=vm.label,
  1598. pool=self.options.override_pool,
  1599. **kwargs)
  1600. except Exception as err: # pylint: disable=broad-except
  1601. self.log.error('Error restoring VM %s, skipping: %s',
  1602. vm.name, err)
  1603. if new_vm:
  1604. del self.app.domains[new_vm.name]
  1605. continue
  1606. restore_info[vm.name].restored_vm = new_vm
  1607. for vm in vms.values():
  1608. if self.canceled:
  1609. return
  1610. new_vm = restore_info[vm.name].restored_vm
  1611. if not new_vm:
  1612. # skipped/failed
  1613. continue
  1614. for prop, value in vm.properties.items():
  1615. # exclude VM references - handled manually according to
  1616. # restore options
  1617. if prop in ['template', 'netvm', 'default_dispvm']:
  1618. continue
  1619. try:
  1620. setattr(new_vm, prop, value)
  1621. except Exception as err: # pylint: disable=broad-except
  1622. self.log.error('Error setting %s.%s to %s: %s',
  1623. vm.name, prop, value, err)
  1624. for feature, value in vm.features.items():
  1625. try:
  1626. new_vm.features[feature] = value
  1627. except Exception as err: # pylint: disable=broad-except
  1628. self.log.error('Error setting %s.features[%s] to %s: %s',
  1629. vm.name, feature, value, err)
  1630. for tag in vm.tags:
  1631. try:
  1632. new_vm.tags.add(tag)
  1633. except Exception as err: # pylint: disable=broad-except
  1634. self.log.error('Error adding tag %s to %s: %s',
  1635. tag, vm.name, err)
  1636. for bus in vm.devices:
  1637. for backend_domain, ident in vm.devices[bus]:
  1638. options = vm.devices[bus][(backend_domain, ident)]
  1639. assignment = DeviceAssignment(
  1640. backend_domain=backend_domain,
  1641. ident=ident,
  1642. options=options,
  1643. persistent=True)
  1644. try:
  1645. new_vm.devices[bus].attach(assignment)
  1646. except Exception as err: # pylint: disable=broad-except
  1647. self.log.error('Error attaching device %s:%s to %s: %s',
  1648. bus, ident, vm.name, err)
  1649. # Set VM dependencies - only non-default setting
  1650. for vm in vms.values():
  1651. vm_info = restore_info[vm.name]
  1652. vm_name = vm_info.name
  1653. try:
  1654. host_vm = self.app.domains[vm_name]
  1655. except KeyError:
  1656. # Failed/skipped VM
  1657. continue
  1658. if 'netvm' in vm.properties:
  1659. if vm_info.netvm in restore_info:
  1660. value = restore_info[vm_info.netvm].name
  1661. else:
  1662. value = vm_info.netvm
  1663. try:
  1664. host_vm.netvm = value
  1665. except Exception as err: # pylint: disable=broad-except
  1666. self.log.error('Error setting %s.%s to %s: %s',
  1667. vm.name, 'netvm', value, err)
  1668. if 'default_dispvm' in vm.properties:
  1669. if vm.properties['default_dispvm'] in restore_info:
  1670. value = restore_info[vm.properties[
  1671. 'default_dispvm']].name
  1672. else:
  1673. value = vm.properties['default_dispvm']
  1674. try:
  1675. host_vm.default_dispvm = value
  1676. except Exception as err: # pylint: disable=broad-except
  1677. self.log.error('Error setting %s.%s to %s: %s',
  1678. vm.name, 'default_dispvm', value, err)