backup.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847
  1. #
  2. # The Qubes OS Project, http://www.qubes-os.org
  3. #
  4. # Copyright (C) 2013-2017 Marek Marczykowski-Górecki
  5. # <marmarek@invisiblethingslab.com>
  6. # Copyright (C) 2013 Olivier Médoc <o_medoc@yahoo.fr>
  7. #
  8. # This library is free software; you can redistribute it and/or
  9. # modify it under the terms of the GNU Lesser General Public
  10. # License as published by the Free Software Foundation; either
  11. # version 2.1 of the License, or (at your option) any later version.
  12. #
  13. # This library 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 GNU
  16. # Lesser General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU Lesser General Public
  19. # License along with this library; if not, see <https://www.gnu.org/licenses/>.
  20. #
  21. #
  22. from __future__ import unicode_literals
  23. import itertools
  24. import logging
  25. import functools
  26. import termios
  27. import asyncio
  28. from qubes.utils import size_to_human
  29. import stat
  30. import os
  31. import fcntl
  32. import subprocess
  33. import re
  34. import shutil
  35. import tempfile
  36. import time
  37. import grp
  38. import pwd
  39. import datetime
  40. import qubes
  41. import qubes.core2migration
  42. import qubes.storage
  43. import qubes.storage.file
  44. import qubes.vm.templatevm
  45. QUEUE_ERROR = "ERROR"
  46. QUEUE_FINISHED = "FINISHED"
  47. HEADER_FILENAME = 'backup-header'
  48. DEFAULT_CRYPTO_ALGORITHM = 'aes-256-cbc'
  49. # 'scrypt' is not exactly HMAC algorithm, but a tool we use to
  50. # integrity-protect the data
  51. DEFAULT_HMAC_ALGORITHM = 'scrypt'
  52. DEFAULT_COMPRESSION_FILTER = 'gzip'
  53. CURRENT_BACKUP_FORMAT_VERSION = '4'
  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. class BackupCanceledError(qubes.exc.QubesException):
  63. def __init__(self, msg, tmpdir=None):
  64. super(BackupCanceledError, self).__init__(msg)
  65. self.tmpdir = tmpdir
  66. class BackupHeader(object):
  67. '''Structure describing backup-header file included as the first file in
  68. backup archive
  69. '''
  70. # pylint: disable=too-few-public-methods
  71. header_keys = {
  72. 'version': 'version',
  73. 'encrypted': 'encrypted',
  74. 'compressed': 'compressed',
  75. 'compression-filter': 'compression_filter',
  76. 'crypto-algorithm': 'crypto_algorithm',
  77. 'hmac-algorithm': 'hmac_algorithm',
  78. 'backup-id': 'backup_id'
  79. }
  80. bool_options = ['encrypted', 'compressed']
  81. int_options = ['version']
  82. def __init__(self,
  83. version=None,
  84. encrypted=None,
  85. compressed=None,
  86. compression_filter=None,
  87. hmac_algorithm=None,
  88. crypto_algorithm=None,
  89. backup_id=None):
  90. # repeat the list to help code completion...
  91. self.version = version
  92. self.encrypted = encrypted
  93. self.compressed = compressed
  94. # Options introduced in backup format 3+, which always have a header,
  95. # so no need for fallback in function parameter
  96. self.compression_filter = compression_filter
  97. self.hmac_algorithm = hmac_algorithm
  98. self.crypto_algorithm = crypto_algorithm
  99. self.backup_id = backup_id
  100. def save(self, filename):
  101. with open(filename, "w") as f_header:
  102. # make sure 'version' is the first key
  103. f_header.write('version={}\n'.format(self.version))
  104. for key, attr in self.header_keys.items():
  105. if key == 'version':
  106. continue
  107. if getattr(self, attr) is None:
  108. continue
  109. f_header.write("{!s}={!s}\n".format(key, getattr(self, attr)))
  110. class SendWorker(object):
  111. # pylint: disable=too-few-public-methods
  112. def __init__(self, queue, base_dir, backup_stdout):
  113. super(SendWorker, self).__init__()
  114. self.queue = queue
  115. self.base_dir = base_dir
  116. self.backup_stdout = backup_stdout
  117. self.log = logging.getLogger('qubes.backup')
  118. @asyncio.coroutine
  119. def run(self):
  120. self.log.debug("Started sending thread")
  121. while True:
  122. filename = yield from self.queue.get()
  123. if filename in (QUEUE_FINISHED, QUEUE_ERROR):
  124. break
  125. self.log.debug("Sending file {}".format(filename))
  126. # This tar used for sending data out need to be as simple, as
  127. # simple, as featureless as possible. It will not be
  128. # verified before untaring.
  129. tar_final_cmd = ["tar", "-cO", "--posix",
  130. "-C", self.base_dir, filename]
  131. final_proc = yield from asyncio.create_subprocess_exec(
  132. *tar_final_cmd,
  133. stdout=self.backup_stdout)
  134. retcode = yield from final_proc.wait()
  135. if retcode >= 2:
  136. # handle only exit code 2 (tar fatal error) or
  137. # greater (call failed?)
  138. raise qubes.exc.QubesException(
  139. "ERROR: Failed to write the backup, out of disk space? "
  140. "Check console output or ~/.xsession-errors for details.")
  141. # Delete the file as we don't need it anymore
  142. self.log.debug("Removing file {}".format(filename))
  143. os.remove(os.path.join(self.base_dir, filename))
  144. self.log.debug("Finished sending thread")
  145. @asyncio.coroutine
  146. def launch_proc_with_pty(args, stdin=None, stdout=None, stderr=None, echo=True):
  147. """Similar to pty.fork, but handle stdin/stdout according to parameters
  148. instead of connecting to the pty
  149. :return tuple (subprocess.Popen, pty_master)
  150. """
  151. def set_ctty(ctty_fd, master_fd):
  152. os.setsid()
  153. os.close(master_fd)
  154. fcntl.ioctl(ctty_fd, termios.TIOCSCTTY, 0)
  155. if not echo:
  156. termios_p = termios.tcgetattr(ctty_fd)
  157. # termios_p.c_lflags
  158. termios_p[3] &= ~termios.ECHO
  159. termios.tcsetattr(ctty_fd, termios.TCSANOW, termios_p)
  160. (pty_master, pty_slave) = os.openpty()
  161. p = yield from asyncio.create_subprocess_exec(*args,
  162. stdin=stdin,
  163. stdout=stdout,
  164. stderr=stderr,
  165. preexec_fn=lambda: set_ctty(pty_slave, pty_master))
  166. os.close(pty_slave)
  167. return p, open(pty_master, 'wb+', buffering=0)
  168. @asyncio.coroutine
  169. def launch_scrypt(action, input_name, output_name, passphrase):
  170. '''
  171. Launch 'scrypt' process, pass passphrase to it and return
  172. subprocess.Popen object.
  173. :param action: 'enc' or 'dec'
  174. :param input_name: input path or '-' for stdin
  175. :param output_name: output path or '-' for stdout
  176. :param passphrase: passphrase
  177. :type passphrase: bytes
  178. :return: subprocess.Popen object
  179. '''
  180. command_line = ['scrypt', action, input_name, output_name]
  181. (p, pty) = yield from launch_proc_with_pty(command_line,
  182. stdin=subprocess.PIPE if input_name == '-' else None,
  183. stdout=subprocess.PIPE if output_name == '-' else None,
  184. stderr=subprocess.PIPE,
  185. echo=False)
  186. if action == 'enc':
  187. prompts = (b'Please enter passphrase: ', b'Please confirm passphrase: ')
  188. else:
  189. prompts = (b'Please enter passphrase: ',)
  190. for prompt in prompts:
  191. actual_prompt = yield from p.stderr.read(len(prompt))
  192. if actual_prompt != prompt:
  193. raise qubes.exc.QubesException(
  194. 'Unexpected prompt from scrypt: {}'.format(actual_prompt))
  195. pty.write(passphrase + b'\n')
  196. pty.flush()
  197. # save it here, so garbage collector would not close it (which would kill
  198. # the child)
  199. p.pty = pty
  200. return p
  201. class Backup(object):
  202. '''Backup operation manager. Usage:
  203. >>> app = qubes.Qubes()
  204. >>> # optional - you can use 'None' to use default list (based on
  205. >>> # vm.include_in_backups property)
  206. >>> vms = [app.domains[name] for name in ['my-vm1', 'my-vm2', 'my-vm3']]
  207. >>> exclude_vms = []
  208. >>> options = {
  209. >>> 'encrypted': True,
  210. >>> 'compressed': True,
  211. >>> 'passphrase': 'This is very weak backup passphrase',
  212. >>> 'target_vm': app.domains['sys-usb'],
  213. >>> 'target_dir': '/media/disk',
  214. >>> }
  215. >>> backup_op = Backup(app, vms, exclude_vms, **options)
  216. >>> print(backup_op.get_backup_summary())
  217. >>> asyncio.get_event_loop().run_until_complete(backup_op.backup_do())
  218. See attributes of this object for all available options.
  219. '''
  220. # pylint: disable=too-many-instance-attributes
  221. class FileToBackup(object):
  222. # pylint: disable=too-few-public-methods
  223. def __init__(self, file_path, subdir=None, name=None, size=None):
  224. if size is None:
  225. size = qubes.storage.file.get_disk_usage(file_path)
  226. if subdir is None:
  227. abs_file_path = os.path.abspath(file_path)
  228. abs_base_dir = os.path.abspath(
  229. qubes.config.system_path["qubes_base_dir"]) + '/'
  230. abs_file_dir = os.path.dirname(abs_file_path) + '/'
  231. (nothing, directory, subdir) = \
  232. abs_file_dir.partition(abs_base_dir)
  233. assert nothing == ""
  234. assert directory == abs_base_dir
  235. else:
  236. if subdir and not subdir.endswith('/'):
  237. subdir += '/'
  238. #: real path to the file
  239. self.path = file_path
  240. #: size of the file
  241. self.size = size
  242. #: directory in backup archive where file should be placed
  243. self.subdir = subdir
  244. #: use this name in the archive (aka rename)
  245. self.name = os.path.basename(file_path)
  246. if name is not None:
  247. self.name = name
  248. class VMToBackup(object):
  249. # pylint: disable=too-few-public-methods
  250. def __init__(self, vm, files, subdir):
  251. self.vm = vm
  252. self.files = files
  253. self.subdir = subdir
  254. @property
  255. def size(self):
  256. return functools.reduce(lambda x, y: x + y.size, self.files, 0)
  257. def __init__(self, app, vms_list=None, exclude_list=None, **kwargs):
  258. """
  259. If vms = None, include all (sensible) VMs;
  260. exclude_list is always applied
  261. """
  262. super(Backup, self).__init__()
  263. #: progress of the backup - bytes handled of the current VM
  264. self.chunk_size = 100 * 1024 * 1024
  265. self._current_vm_bytes = 0
  266. #: progress of the backup - bytes handled of finished VMs
  267. self._done_vms_bytes = 0
  268. #: total backup size (set by :py:meth:`get_files_to_backup`)
  269. self.total_backup_bytes = 0
  270. #: application object
  271. self.app = app
  272. #: directory for temporary files - set after creating the directory
  273. self.tmpdir = None
  274. # Backup settings - defaults
  275. #: should the backup be compressed?
  276. self.compressed = True
  277. #: what passphrase should be used to intergrity protect (and encrypt)
  278. #: the backup; required
  279. self.passphrase = None
  280. #: custom compression filter; a program which process stdin to stdout
  281. self.compression_filter = DEFAULT_COMPRESSION_FILTER
  282. #: VM to which backup should be sent (if any)
  283. self.target_vm = None
  284. #: directory to save backup in (either in dom0 or target VM,
  285. #: depending on :py:attr:`target_vm`
  286. self.target_dir = None
  287. #: callback for progress reporting. Will be called with one argument
  288. #: - progress in percents
  289. self.progress_callback = None
  290. #: backup ID, needs to be unique (for a given user),
  291. #: not necessary unpredictable; automatically generated
  292. self.backup_id = datetime.datetime.now().strftime(
  293. '%Y%m%dT%H%M%S-' + str(os.getpid()))
  294. for key, value in kwargs.items():
  295. if hasattr(self, key):
  296. setattr(self, key, value)
  297. else:
  298. raise AttributeError(key)
  299. self.log = logging.getLogger('qubes.backup')
  300. if exclude_list is None:
  301. exclude_list = []
  302. if vms_list is None:
  303. vms_list = [vm for vm in app.domains if vm.include_in_backups]
  304. # Apply exclude list
  305. self.vms_for_backup = [vm for vm in vms_list
  306. if vm.name not in exclude_list]
  307. self._files_to_backup = self.get_files_to_backup()
  308. def __del__(self):
  309. if self.tmpdir and os.path.exists(self.tmpdir):
  310. shutil.rmtree(self.tmpdir)
  311. def get_files_to_backup(self):
  312. files_to_backup = {}
  313. for vm in self.vms_for_backup:
  314. if vm.qid == 0:
  315. # handle dom0 later
  316. continue
  317. subdir = 'vm%d/' % vm.qid
  318. vm_files = []
  319. for name, volume in vm.volumes.items():
  320. if not volume.save_on_stop:
  321. continue
  322. vm_files.append(self.FileToBackup(
  323. volume.export(),
  324. subdir,
  325. name + '.img',
  326. volume.usage))
  327. vm_files.extend(self.FileToBackup(i, subdir)
  328. for i in vm.fire_event('backup-get-files'))
  329. firewall_conf = os.path.join(vm.dir_path, vm.firewall_conf)
  330. if os.path.exists(firewall_conf):
  331. vm_files.append(self.FileToBackup(firewall_conf, subdir))
  332. files_to_backup[vm.qid] = self.VMToBackup(vm, vm_files, subdir)
  333. # Dom0 user home
  334. if 0 in [vm.qid for vm in self.vms_for_backup]:
  335. local_user = grp.getgrnam('qubes').gr_mem[0]
  336. home_dir = pwd.getpwnam(local_user).pw_dir
  337. # Home dir should have only user-owned files, so fix it now
  338. # to prevent permissions problems - some root-owned files can
  339. # left after 'sudo bash' and similar commands
  340. subprocess.check_call(['sudo', 'chown', '-R', local_user, home_dir])
  341. home_to_backup = [
  342. self.FileToBackup(home_dir, 'dom0-home/')]
  343. vm_files = home_to_backup
  344. files_to_backup[0] = self.VMToBackup(self.app.domains[0],
  345. vm_files,
  346. os.path.join('dom0-home', os.path.basename(home_dir)))
  347. self.total_backup_bytes = functools.reduce(
  348. lambda x, y: x + y.size, files_to_backup.values(), 0)
  349. return files_to_backup
  350. def get_backup_summary(self):
  351. summary = ""
  352. fields_to_display = [
  353. {"name": "VM", "width": 16},
  354. {"name": "type", "width": 12},
  355. {"name": "size", "width": 12}
  356. ]
  357. # Display the header
  358. for field in fields_to_display:
  359. fmt = "{{0:-^{0}}}-+".format(field["width"] + 1)
  360. summary += fmt.format('-')
  361. summary += "\n"
  362. for field in fields_to_display:
  363. fmt = "{{0:>{0}}} |".format(field["width"] + 1)
  364. summary += fmt.format(field["name"])
  365. summary += "\n"
  366. for field in fields_to_display:
  367. fmt = "{{0:-^{0}}}-+".format(field["width"] + 1)
  368. summary += fmt.format('-')
  369. summary += "\n"
  370. files_to_backup = self._files_to_backup
  371. for qid, vm_info in files_to_backup.items():
  372. summary_line = ""
  373. fmt = "{{0:>{0}}} |".format(fields_to_display[0]["width"] + 1)
  374. summary_line += fmt.format(vm_info.vm.name)
  375. fmt = "{{0:>{0}}} |".format(fields_to_display[1]["width"] + 1)
  376. if qid == 0:
  377. summary_line += fmt.format("User home")
  378. elif isinstance(vm_info.vm, qubes.vm.templatevm.TemplateVM):
  379. summary_line += fmt.format("Template VM")
  380. else:
  381. summary_line += fmt.format("VM" + (" + Sys" if
  382. vm_info.vm.updateable else ""))
  383. vm_size = vm_info.size
  384. fmt = "{{0:>{0}}} |".format(fields_to_display[2]["width"] + 1)
  385. summary_line += fmt.format(size_to_human(vm_size))
  386. if qid != 0 and vm_info.vm.is_running():
  387. summary_line += " <-- The VM is running, backup will contain " \
  388. "its state from before its start!"
  389. summary += summary_line + "\n"
  390. for field in fields_to_display:
  391. fmt = "{{0:-^{0}}}-+".format(field["width"] + 1)
  392. summary += fmt.format('-')
  393. summary += "\n"
  394. fmt = "{{0:>{0}}} |".format(fields_to_display[0]["width"] + 1)
  395. summary += fmt.format("Total size:")
  396. fmt = "{{0:>{0}}} |".format(
  397. fields_to_display[1]["width"] + 1 + 2 + fields_to_display[2][
  398. "width"] + 1)
  399. summary += fmt.format(size_to_human(self.total_backup_bytes))
  400. summary += "\n"
  401. for field in fields_to_display:
  402. fmt = "{{0:-^{0}}}-+".format(field["width"] + 1)
  403. summary += fmt.format('-')
  404. summary += "\n"
  405. vms_not_for_backup = [vm.name for vm in self.app.domains
  406. if vm not in self.vms_for_backup]
  407. summary += "VMs not selected for backup:\n - " + "\n - ".join(
  408. sorted(vms_not_for_backup)) + "\n"
  409. return summary
  410. @asyncio.coroutine
  411. def _prepare_backup_header(self):
  412. header_file_path = os.path.join(self.tmpdir, HEADER_FILENAME)
  413. backup_header = BackupHeader(
  414. version=CURRENT_BACKUP_FORMAT_VERSION,
  415. hmac_algorithm=DEFAULT_HMAC_ALGORITHM,
  416. encrypted=True,
  417. compressed=self.compressed,
  418. compression_filter=self.compression_filter,
  419. backup_id=self.backup_id,
  420. )
  421. backup_header.save(header_file_path)
  422. # Start encrypt, scrypt will also handle integrity
  423. # protection
  424. scrypt_passphrase = '{filename}!'.format(
  425. filename=HEADER_FILENAME).encode() + self.passphrase
  426. scrypt = yield from launch_scrypt(
  427. 'enc', header_file_path, header_file_path + '.hmac',
  428. scrypt_passphrase)
  429. retcode = yield from scrypt.wait()
  430. if retcode:
  431. raise qubes.exc.QubesException(
  432. "Failed to compute hmac of header file: "
  433. + scrypt.stderr.read())
  434. return HEADER_FILENAME, HEADER_FILENAME + ".hmac"
  435. def _send_progress_update(self):
  436. if not self.total_backup_bytes:
  437. return
  438. if callable(self.progress_callback):
  439. progress = (
  440. 100 * (self._done_vms_bytes + self._current_vm_bytes) /
  441. self.total_backup_bytes)
  442. # pylint: disable=not-callable
  443. self.progress_callback(progress)
  444. def _add_vm_progress(self, bytes_done):
  445. self._current_vm_bytes += bytes_done
  446. self._send_progress_update()
  447. @asyncio.coroutine
  448. def _split_and_send(self, input_stream, file_basename,
  449. output_queue):
  450. '''Split *input_stream* into parts of max *chunk_size* bytes and send
  451. to *output_queue*.
  452. :param input_stream: stream (asyncio reader stream) of data to split
  453. :param file_basename: basename (i.e. without part number and '.enc')
  454. of output files
  455. :param output_queue: asyncio.Queue instance to put produced files to
  456. - queue will get only filenames of written chunks
  457. '''
  458. # Wait for compressor (tar) process to finish or for any
  459. # error of other subprocesses
  460. i = 0
  461. run_error = "size_limit"
  462. scrypt = None
  463. while run_error == "size_limit":
  464. # Prepare a first chunk
  465. chunkfile = file_basename + ".%03d.enc" % i
  466. i += 1
  467. # Start encrypt, scrypt will also handle integrity
  468. # protection
  469. scrypt_passphrase = \
  470. '{backup_id}!{filename}!'.format(
  471. backup_id=self.backup_id,
  472. filename=os.path.relpath(chunkfile[:-4],
  473. self.tmpdir)).encode() + self.passphrase
  474. try:
  475. scrypt = yield from launch_scrypt(
  476. "enc", "-", chunkfile, scrypt_passphrase)
  477. run_error = yield from handle_streams(
  478. input_stream,
  479. scrypt.stdin,
  480. self.chunk_size,
  481. self._add_vm_progress
  482. )
  483. self.log.debug(
  484. "handle_streams returned: {}".format(run_error))
  485. except:
  486. scrypt.terminate()
  487. raise
  488. scrypt.stdin.close()
  489. yield from scrypt.wait()
  490. self.log.debug("scrypt return code: {}".format(
  491. scrypt.returncode))
  492. # Send the chunk to the backup target
  493. yield from output_queue.put(
  494. os.path.relpath(chunkfile, self.tmpdir))
  495. @asyncio.coroutine
  496. def _wrap_and_send_files(self, files_to_backup, output_queue):
  497. for vm_info in files_to_backup:
  498. for file_info in vm_info.files:
  499. self.log.debug("Backing up {}".format(file_info))
  500. backup_tempfile = os.path.join(
  501. self.tmpdir, file_info.subdir,
  502. file_info.name)
  503. self.log.debug("Using temporary location: {}".format(
  504. backup_tempfile))
  505. # Ensure the temporary directory exists
  506. if not os.path.isdir(os.path.dirname(backup_tempfile)):
  507. os.makedirs(os.path.dirname(backup_tempfile))
  508. # The first tar cmd can use any complex feature as we want.
  509. # Files will be verified before untaring this.
  510. # Prefix the path in archive with filename["subdir"] to have it
  511. # verified during untar
  512. tar_cmdline = (["tar", "-Pc", '--sparse',
  513. '-C', os.path.dirname(file_info.path)] +
  514. (['--dereference'] if
  515. file_info.subdir != "dom0-home/" else []) +
  516. ['--xform=s:^%s:%s\\0:' % (
  517. os.path.basename(file_info.path),
  518. file_info.subdir),
  519. os.path.basename(file_info.path)
  520. ])
  521. file_stat = os.stat(file_info.path)
  522. if stat.S_ISBLK(file_stat.st_mode) or \
  523. file_info.name != os.path.basename(file_info.path):
  524. # tar doesn't handle content of block device, use our
  525. # writer
  526. # also use our tar writer when renaming file
  527. assert not stat.S_ISDIR(file_stat.st_mode), \
  528. "Renaming directories not supported"
  529. tar_cmdline = ['python3', '-m', 'qubes.tarwriter',
  530. '--override-name=%s' % (
  531. os.path.join(file_info.subdir, os.path.basename(
  532. file_info.name))),
  533. file_info.path]
  534. if self.compressed:
  535. tar_cmdline.insert(-2,
  536. "--use-compress-program=%s" % self.compression_filter)
  537. self.log.debug(" ".join(tar_cmdline))
  538. # Pipe: tar-sparse | scrypt | tar | backup_target
  539. # TODO: log handle stderr
  540. tar_sparse = yield from asyncio.create_subprocess_exec(
  541. *tar_cmdline, stdout=subprocess.PIPE)
  542. try:
  543. yield from self._split_and_send(
  544. tar_sparse.stdout,
  545. backup_tempfile,
  546. output_queue)
  547. except:
  548. try:
  549. tar_sparse.terminate()
  550. except ProcessLookupError:
  551. pass
  552. raise
  553. yield from tar_sparse.wait()
  554. if tar_sparse.returncode:
  555. raise qubes.exc.QubesException(
  556. 'Failed to archive {} file'.format(file_info.path))
  557. # This VM done, update progress
  558. self._done_vms_bytes += vm_info.size
  559. self._current_vm_bytes = 0
  560. self._send_progress_update()
  561. yield from output_queue.put(QUEUE_FINISHED)
  562. @staticmethod
  563. @asyncio.coroutine
  564. def _monitor_process(proc, error_message):
  565. try:
  566. yield from proc.wait()
  567. except:
  568. proc.terminate()
  569. raise
  570. if proc.returncode:
  571. raise qubes.exc.QubesException(error_message)
  572. @staticmethod
  573. @asyncio.coroutine
  574. def _cancel_on_error(future, previous_task):
  575. '''If further element of chain fail, cancel previous one to
  576. avoid deadlock.
  577. When earlier element of chain fail, it will be handled by
  578. :py:meth:`backup_do`.
  579. The chain is:
  580. :py:meth:`_wrap_and_send_files` -> :py:class:`SendWorker` -> vmproc
  581. '''
  582. try:
  583. yield from future
  584. except: # pylint: disable=bare-except
  585. previous_task.cancel()
  586. @asyncio.coroutine
  587. def backup_do(self):
  588. # pylint: disable=too-many-statements
  589. if self.passphrase is None:
  590. raise qubes.exc.QubesException("No passphrase set")
  591. if not isinstance(self.passphrase, bytes):
  592. self.passphrase = self.passphrase.encode('utf-8')
  593. qubes_xml = self.app.store
  594. self.tmpdir = tempfile.mkdtemp()
  595. shutil.copy(qubes_xml, os.path.join(self.tmpdir, 'qubes.xml'))
  596. qubes_xml = os.path.join(self.tmpdir, 'qubes.xml')
  597. backup_app = qubes.Qubes(qubes_xml)
  598. backup_app.events_enabled = False
  599. files_to_backup = self._files_to_backup
  600. # make sure backup_content isn't set initially
  601. for vm in backup_app.domains:
  602. vm.events_enabled = False
  603. vm.features['backup-content'] = False
  604. for qid, vm_info in files_to_backup.items():
  605. # VM is included in the backup
  606. backup_app.domains[qid].features['backup-content'] = True
  607. backup_app.domains[qid].features['backup-path'] = vm_info.subdir
  608. backup_app.domains[qid].features['backup-size'] = vm_info.size
  609. backup_app.save()
  610. vmproc = None
  611. if self.target_vm is not None:
  612. # Prepare the backup target (Qubes service call)
  613. # If APPVM, STDOUT is a PIPE
  614. read_fd, write_fd = os.pipe()
  615. vmproc = yield from self.target_vm.run_service('qubes.Backup',
  616. stdin=read_fd, stderr=subprocess.PIPE)
  617. os.close(read_fd)
  618. os.write(write_fd, (self.target_dir.
  619. replace("\r", "").replace("\n", "") + "\n").encode())
  620. backup_stdout = write_fd
  621. else:
  622. # Prepare the backup target (local file)
  623. if os.path.isdir(self.target_dir):
  624. backup_target = self.target_dir + "/qubes-{0}". \
  625. format(time.strftime("%Y-%m-%dT%H%M%S"))
  626. else:
  627. backup_target = self.target_dir
  628. # Create the target directory
  629. if not os.path.exists(os.path.dirname(self.target_dir)):
  630. raise qubes.exc.QubesException(
  631. "ERROR: the backup directory for {0} does not exists".
  632. format(self.target_dir))
  633. # If not APPVM, STDOUT is a local file
  634. backup_stdout = open(backup_target, 'wb')
  635. # Tar with tape length does not deals well with stdout
  636. # (close stdout between two tapes)
  637. # For this reason, we will use named pipes instead
  638. self.log.debug("Working in {}".format(self.tmpdir))
  639. self.log.debug("Will backup: {}".format(files_to_backup))
  640. header_files = yield from self._prepare_backup_header()
  641. # Setup worker to send encrypted data chunks to the backup_target
  642. to_send = asyncio.Queue(10)
  643. send_proc = SendWorker(to_send, self.tmpdir, backup_stdout)
  644. send_task = asyncio.ensure_future(send_proc.run())
  645. vmproc_task = None
  646. if vmproc is not None:
  647. vmproc_task = asyncio.ensure_future(self._cancel_on_error(
  648. self._monitor_process(vmproc,
  649. 'Writing backup to VM {} failed'.format(
  650. self.target_vm.name)),
  651. send_task))
  652. for file_name in header_files:
  653. yield from to_send.put(file_name)
  654. qubes_xml_info = self.VMToBackup(
  655. None,
  656. [self.FileToBackup(qubes_xml, '')],
  657. ''
  658. )
  659. inner_archive_task = asyncio.ensure_future(
  660. self._wrap_and_send_files(
  661. itertools.chain([qubes_xml_info], files_to_backup.values()),
  662. to_send
  663. ))
  664. asyncio.ensure_future(
  665. self._cancel_on_error(send_task, inner_archive_task))
  666. try:
  667. try:
  668. yield from inner_archive_task
  669. except:
  670. yield from to_send.put(QUEUE_ERROR)
  671. # in fact we may be handling CancelledError, induced by
  672. # exception in send_task (and propagated by
  673. # self._cancel_on_error call above); in such a case this
  674. # yield from will raise exception, covering CancelledError -
  675. # this is intended behaviour
  676. yield from send_task
  677. raise
  678. yield from send_task
  679. finally:
  680. if isinstance(backup_stdout, int):
  681. os.close(backup_stdout)
  682. else:
  683. backup_stdout.close()
  684. try:
  685. if vmproc_task:
  686. yield from vmproc_task
  687. finally:
  688. shutil.rmtree(self.tmpdir)
  689. # Save date of last backup, only when backup succeeded
  690. for qid, vm_info in files_to_backup.items():
  691. if vm_info.vm:
  692. vm_info.vm.backup_timestamp = datetime.datetime.now()
  693. self.app.save()
  694. @asyncio.coroutine
  695. def handle_streams(stream_in, stream_out, size_limit=None,
  696. progress_callback=None):
  697. '''
  698. Copy stream_in to all streams_out and monitor all mentioned processes.
  699. If any of them terminate with non-zero code, interrupt the process. Copy
  700. at most `size_limit` data (if given).
  701. :param stream_in: StreamReader object to read data from
  702. :param stream_out: StreamWriter object to write data to
  703. :param size_limit: int maximum data amount to process
  704. :param progress_callback: callable function to report progress, will be
  705. given copied data size (it should accumulate internally)
  706. :return: "size_limit" or None (no error)
  707. '''
  708. buffer_size = 409600
  709. bytes_copied = 0
  710. while True:
  711. if size_limit:
  712. to_copy = min(buffer_size, size_limit - bytes_copied)
  713. if to_copy <= 0:
  714. return "size_limit"
  715. else:
  716. to_copy = buffer_size
  717. buf = yield from stream_in.read(to_copy)
  718. if not buf:
  719. # done
  720. return None
  721. if callable(progress_callback):
  722. progress_callback(len(buf))
  723. stream_out.write(buf)
  724. bytes_copied += len(buf)
  725. # vim:sw=4:et: