archiver.py 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929
  1. import argparse
  2. from binascii import hexlify
  3. from datetime import datetime
  4. from operator import attrgetter
  5. import functools
  6. import inspect
  7. import io
  8. import os
  9. import signal
  10. import stat
  11. import sys
  12. import textwrap
  13. import traceback
  14. from . import __version__
  15. from .archive import Archive, ArchiveChecker, CHUNKER_PARAMS
  16. from .compress import Compressor, COMPR_BUFFER
  17. from .repository import Repository
  18. from .cache import Cache
  19. from .key import key_creator
  20. from .helpers import Error, location_validator, format_time, format_file_size, \
  21. format_file_mode, ExcludePattern, exclude_path, adjust_patterns, to_localtime, timestamp, \
  22. get_cache_dir, get_keys_dir, format_timedelta, prune_within, prune_split, \
  23. Manifest, remove_surrogates, update_excludes, format_archive, check_extension_modules, Statistics, \
  24. is_cachedir, bigint_to_int, ChunkerParams, CompressionSpec
  25. from .remote import RepositoryServer, RemoteRepository
  26. class Archiver:
  27. def __init__(self):
  28. self.exit_code = 0
  29. def open_repository(self, location, create=False, exclusive=False):
  30. if location.proto == 'ssh':
  31. repository = RemoteRepository(location, create=create)
  32. else:
  33. repository = Repository(location.path, create=create, exclusive=exclusive)
  34. repository._location = location
  35. return repository
  36. def print_error(self, msg, *args):
  37. msg = args and msg % args or msg
  38. self.exit_code = 1
  39. print('borg: ' + msg, file=sys.stderr)
  40. def print_verbose(self, msg, *args, **kw):
  41. if self.verbose:
  42. msg = args and msg % args or msg
  43. if kw.get('newline', True):
  44. print(msg)
  45. else:
  46. print(msg, end=' ')
  47. def do_serve(self, args):
  48. """Start in server mode. This command is usually not used manually.
  49. """
  50. return RepositoryServer(restrict_to_paths=args.restrict_to_paths).serve()
  51. def do_init(self, args):
  52. """Initialize an empty repository"""
  53. print('Initializing repository at "%s"' % args.repository.orig)
  54. repository = self.open_repository(args.repository, create=True, exclusive=True)
  55. key = key_creator(repository, args)
  56. manifest = Manifest(key, repository)
  57. manifest.key = key
  58. manifest.write()
  59. repository.commit()
  60. Cache(repository, key, manifest, warn_if_unencrypted=False)
  61. return self.exit_code
  62. def do_check(self, args):
  63. """Check repository consistency"""
  64. repository = self.open_repository(args.repository, exclusive=args.repair)
  65. if args.repair:
  66. while not os.environ.get('BORG_CHECK_I_KNOW_WHAT_I_AM_DOING'):
  67. self.print_error("""Warning: 'check --repair' is an experimental feature that might result
  68. in data loss.
  69. Type "Yes I am sure" if you understand this and want to continue.\n""")
  70. if input('Do you want to continue? ') == 'Yes I am sure':
  71. break
  72. if not args.archives_only:
  73. print('Starting repository check...')
  74. if repository.check(repair=args.repair):
  75. print('Repository check complete, no problems found.')
  76. else:
  77. return 1
  78. if not args.repo_only and not ArchiveChecker().check(
  79. repository, repair=args.repair, archive=args.repository.archive, last=args.last):
  80. return 1
  81. return 0
  82. def do_change_passphrase(self, args):
  83. """Change repository key file passphrase"""
  84. repository = self.open_repository(args.repository)
  85. manifest, key = Manifest.load(repository)
  86. key.change_passphrase()
  87. return 0
  88. def do_create(self, args):
  89. """Create new archive"""
  90. t0 = datetime.now()
  91. repository = self.open_repository(args.archive, exclusive=True)
  92. manifest, key = Manifest.load(repository)
  93. compr_args = dict(buffer=COMPR_BUFFER)
  94. compr_args.update(args.compression)
  95. key.compressor = Compressor(**compr_args)
  96. cache = Cache(repository, key, manifest, do_files=args.cache_files)
  97. archive = Archive(repository, key, manifest, args.archive.archive, cache=cache,
  98. create=True, checkpoint_interval=args.checkpoint_interval,
  99. numeric_owner=args.numeric_owner, progress=args.progress,
  100. chunker_params=args.chunker_params)
  101. # Add cache dir to inode_skip list
  102. skip_inodes = set()
  103. try:
  104. st = os.stat(get_cache_dir())
  105. skip_inodes.add((st.st_ino, st.st_dev))
  106. except IOError:
  107. pass
  108. # Add local repository dir to inode_skip list
  109. if not args.archive.host:
  110. try:
  111. st = os.stat(args.archive.path)
  112. skip_inodes.add((st.st_ino, st.st_dev))
  113. except IOError:
  114. pass
  115. for path in args.paths:
  116. if path == '-': # stdin
  117. path = 'stdin'
  118. self.print_verbose(path)
  119. try:
  120. archive.process_stdin(path, cache)
  121. except IOError as e:
  122. self.print_error('%s: %s', path, e)
  123. continue
  124. path = os.path.normpath(path)
  125. if args.dontcross:
  126. try:
  127. restrict_dev = os.lstat(path).st_dev
  128. except OSError as e:
  129. self.print_error('%s: %s', path, e)
  130. continue
  131. else:
  132. restrict_dev = None
  133. self._process(archive, cache, args.excludes, args.exclude_caches, skip_inodes, path, restrict_dev)
  134. archive.save(timestamp=args.timestamp)
  135. if args.progress:
  136. archive.stats.show_progress(final=True)
  137. if args.stats:
  138. t = datetime.now()
  139. diff = t - t0
  140. print('-' * 78)
  141. print('Archive name: %s' % args.archive.archive)
  142. print('Archive fingerprint: %s' % hexlify(archive.id).decode('ascii'))
  143. print('Start time: %s' % t0.strftime('%c'))
  144. print('End time: %s' % t.strftime('%c'))
  145. print('Duration: %s' % format_timedelta(diff))
  146. print('Number of files: %d' % archive.stats.nfiles)
  147. archive.stats.print_('This archive:', cache)
  148. print('-' * 78)
  149. return self.exit_code
  150. def _process(self, archive, cache, excludes, exclude_caches, skip_inodes, path, restrict_dev):
  151. if exclude_path(path, excludes):
  152. return
  153. try:
  154. st = os.lstat(path)
  155. except OSError as e:
  156. self.print_error('%s: %s', path, e)
  157. return
  158. if (st.st_ino, st.st_dev) in skip_inodes:
  159. return
  160. # Entering a new filesystem?
  161. if restrict_dev and st.st_dev != restrict_dev:
  162. return
  163. status = None
  164. if stat.S_ISREG(st.st_mode):
  165. try:
  166. status = archive.process_file(path, st, cache)
  167. except IOError as e:
  168. self.print_error('%s: %s', path, e)
  169. elif stat.S_ISDIR(st.st_mode):
  170. if exclude_caches and is_cachedir(path):
  171. return
  172. status = archive.process_dir(path, st)
  173. try:
  174. entries = os.listdir(path)
  175. except OSError as e:
  176. self.print_error('%s: %s', path, e)
  177. else:
  178. for filename in sorted(entries):
  179. entry_path = os.path.normpath(os.path.join(path, filename))
  180. self._process(archive, cache, excludes, exclude_caches, skip_inodes,
  181. entry_path, restrict_dev)
  182. elif stat.S_ISLNK(st.st_mode):
  183. status = archive.process_symlink(path, st)
  184. elif stat.S_ISFIFO(st.st_mode):
  185. status = archive.process_fifo(path, st)
  186. elif stat.S_ISCHR(st.st_mode) or stat.S_ISBLK(st.st_mode):
  187. status = archive.process_dev(path, st)
  188. elif stat.S_ISSOCK(st.st_mode):
  189. # Ignore unix sockets
  190. return
  191. else:
  192. self.print_error('Unknown file type: %s', path)
  193. return
  194. # Status output
  195. # A lowercase character means a file type other than a regular file,
  196. # borg usually just stores them. E.g. (d)irectory.
  197. # Hardlinks to already seen content are indicated by (h).
  198. # A uppercase character means a regular file that was (A)dded,
  199. # (M)odified or was (U)nchanged.
  200. # Note: A/M/U is relative to the "files" cache, not to the repo.
  201. # This would be an issue if the files cache is not used.
  202. if status is None:
  203. status = '?' # need to add a status code somewhere
  204. # output ALL the stuff - it can be easily filtered using grep.
  205. # even stuff considered unchanged might be interesting.
  206. self.print_verbose("%1s %s", status, remove_surrogates(path))
  207. def do_extract(self, args):
  208. """Extract archive contents"""
  209. # be restrictive when restoring files, restore permissions later
  210. if sys.getfilesystemencoding() == 'ascii':
  211. print('Warning: File system encoding is "ascii", extracting non-ascii filenames will not be supported.')
  212. repository = self.open_repository(args.archive)
  213. manifest, key = Manifest.load(repository)
  214. archive = Archive(repository, key, manifest, args.archive.archive,
  215. numeric_owner=args.numeric_owner)
  216. patterns = adjust_patterns(args.paths, args.excludes)
  217. dry_run = args.dry_run
  218. stdout = args.stdout
  219. sparse = args.sparse
  220. strip_components = args.strip_components
  221. dirs = []
  222. for item in archive.iter_items(lambda item: not exclude_path(item[b'path'], patterns), preload=True):
  223. orig_path = item[b'path']
  224. if strip_components:
  225. item[b'path'] = os.sep.join(orig_path.split(os.sep)[strip_components:])
  226. if not item[b'path']:
  227. continue
  228. if not args.dry_run:
  229. while dirs and not item[b'path'].startswith(dirs[-1][b'path']):
  230. archive.extract_item(dirs.pop(-1), stdout=stdout)
  231. self.print_verbose(remove_surrogates(orig_path))
  232. try:
  233. if dry_run:
  234. archive.extract_item(item, dry_run=True)
  235. else:
  236. if stat.S_ISDIR(item[b'mode']):
  237. dirs.append(item)
  238. archive.extract_item(item, restore_attrs=False)
  239. else:
  240. archive.extract_item(item, stdout=stdout, sparse=sparse)
  241. except IOError as e:
  242. self.print_error('%s: %s', remove_surrogates(orig_path), e)
  243. if not args.dry_run:
  244. while dirs:
  245. archive.extract_item(dirs.pop(-1))
  246. return self.exit_code
  247. def do_rename(self, args):
  248. """Rename an existing archive"""
  249. repository = self.open_repository(args.archive, exclusive=True)
  250. manifest, key = Manifest.load(repository)
  251. cache = Cache(repository, key, manifest)
  252. archive = Archive(repository, key, manifest, args.archive.archive, cache=cache)
  253. archive.rename(args.name)
  254. manifest.write()
  255. repository.commit()
  256. cache.commit()
  257. return self.exit_code
  258. def do_delete(self, args):
  259. """Delete an existing repository or archive"""
  260. repository = self.open_repository(args.target, exclusive=True)
  261. manifest, key = Manifest.load(repository)
  262. cache = Cache(repository, key, manifest, do_files=args.cache_files)
  263. if args.target.archive:
  264. archive = Archive(repository, key, manifest, args.target.archive, cache=cache)
  265. stats = Statistics()
  266. archive.delete(stats)
  267. manifest.write()
  268. repository.commit()
  269. cache.commit()
  270. if args.stats:
  271. stats.print_('Deleted data:', cache)
  272. else:
  273. print("You requested to completely DELETE the repository *including* all archives it contains:")
  274. for archive_info in manifest.list_archive_infos(sort_by='ts'):
  275. print(format_archive(archive_info))
  276. while not os.environ.get('BORG_CHECK_I_KNOW_WHAT_I_AM_DOING'):
  277. print("""Type "YES" if you understand this and want to continue.\n""")
  278. if input('Do you want to continue? ') == 'YES':
  279. break
  280. repository.destroy()
  281. cache.destroy()
  282. print("Repository and corresponding cache were deleted.")
  283. return self.exit_code
  284. def do_mount(self, args):
  285. """Mount archive or an entire repository as a FUSE fileystem"""
  286. try:
  287. from .fuse import FuseOperations
  288. except ImportError as e:
  289. self.print_error('loading fuse support failed [ImportError: %s]' % str(e))
  290. return self.exit_code
  291. if not os.path.isdir(args.mountpoint) or not os.access(args.mountpoint, os.R_OK | os.W_OK | os.X_OK):
  292. self.print_error('%s: Mountpoint must be a writable directory' % args.mountpoint)
  293. return self.exit_code
  294. repository = self.open_repository(args.src)
  295. manifest, key = Manifest.load(repository)
  296. if args.src.archive:
  297. archive = Archive(repository, key, manifest, args.src.archive)
  298. else:
  299. archive = None
  300. operations = FuseOperations(key, repository, manifest, archive)
  301. self.print_verbose("Mounting filesystem")
  302. try:
  303. operations.mount(args.mountpoint, args.options, args.foreground)
  304. except RuntimeError:
  305. # Relevant error message already printed to stderr by fuse
  306. self.exit_code = 1
  307. return self.exit_code
  308. def do_list(self, args):
  309. """List archive or repository contents"""
  310. repository = self.open_repository(args.src)
  311. manifest, key = Manifest.load(repository)
  312. if args.src.archive:
  313. tmap = {1: 'p', 2: 'c', 4: 'd', 6: 'b', 0o10: '-', 0o12: 'l', 0o14: 's'}
  314. archive = Archive(repository, key, manifest, args.src.archive)
  315. for item in archive.iter_items():
  316. type = tmap.get(item[b'mode'] // 4096, '?')
  317. mode = format_file_mode(item[b'mode'])
  318. size = 0
  319. if type == '-':
  320. try:
  321. size = sum(size for _, size, _ in item[b'chunks'])
  322. except KeyError:
  323. pass
  324. try:
  325. mtime = datetime.fromtimestamp(bigint_to_int(item[b'mtime']) / 1e9)
  326. except ValueError:
  327. # likely a broken mtime and datetime did not want to go beyond year 9999
  328. mtime = datetime(9999, 12, 31, 23, 59, 59)
  329. if b'source' in item:
  330. if type == 'l':
  331. extra = ' -> %s' % item[b'source']
  332. else:
  333. type = 'h'
  334. extra = ' link to %s' % item[b'source']
  335. else:
  336. extra = ''
  337. print('%s%s %-6s %-6s %8d %s %s%s' % (
  338. type, mode, item[b'user'] or item[b'uid'],
  339. item[b'group'] or item[b'gid'], size, format_time(mtime),
  340. remove_surrogates(item[b'path']), extra))
  341. else:
  342. for archive_info in manifest.list_archive_infos(sort_by='ts'):
  343. print(format_archive(archive_info))
  344. return self.exit_code
  345. def do_info(self, args):
  346. """Show archive details such as disk space used"""
  347. repository = self.open_repository(args.archive)
  348. manifest, key = Manifest.load(repository)
  349. cache = Cache(repository, key, manifest, do_files=args.cache_files)
  350. archive = Archive(repository, key, manifest, args.archive.archive, cache=cache)
  351. stats = archive.calc_stats(cache)
  352. print('Name:', archive.name)
  353. print('Fingerprint: %s' % hexlify(archive.id).decode('ascii'))
  354. print('Hostname:', archive.metadata[b'hostname'])
  355. print('Username:', archive.metadata[b'username'])
  356. print('Time: %s' % to_localtime(archive.ts).strftime('%c'))
  357. print('Command line:', remove_surrogates(' '.join(archive.metadata[b'cmdline'])))
  358. print('Number of files: %d' % stats.nfiles)
  359. stats.print_('This archive:', cache)
  360. return self.exit_code
  361. def do_prune(self, args):
  362. """Prune repository archives according to specified rules"""
  363. repository = self.open_repository(args.repository, exclusive=True)
  364. manifest, key = Manifest.load(repository)
  365. cache = Cache(repository, key, manifest, do_files=args.cache_files)
  366. archives = manifest.list_archive_infos(sort_by='ts', reverse=True) # just a ArchiveInfo list
  367. if args.hourly + args.daily + args.weekly + args.monthly + args.yearly == 0 and args.within is None:
  368. self.print_error('At least one of the "within", "keep-hourly", "keep-daily", "keep-weekly", '
  369. '"keep-monthly" or "keep-yearly" settings must be specified')
  370. return 1
  371. if args.prefix:
  372. archives = [archive for archive in archives if archive.name.startswith(args.prefix)]
  373. keep = []
  374. if args.within:
  375. keep += prune_within(archives, args.within)
  376. if args.hourly:
  377. keep += prune_split(archives, '%Y-%m-%d %H', args.hourly, keep)
  378. if args.daily:
  379. keep += prune_split(archives, '%Y-%m-%d', args.daily, keep)
  380. if args.weekly:
  381. keep += prune_split(archives, '%G-%V', args.weekly, keep)
  382. if args.monthly:
  383. keep += prune_split(archives, '%Y-%m', args.monthly, keep)
  384. if args.yearly:
  385. keep += prune_split(archives, '%Y', args.yearly, keep)
  386. keep.sort(key=attrgetter('ts'), reverse=True)
  387. to_delete = [a for a in archives if a not in keep]
  388. stats = Statistics()
  389. for archive in keep:
  390. self.print_verbose('Keeping archive: %s' % format_archive(archive))
  391. for archive in to_delete:
  392. if args.dry_run:
  393. self.print_verbose('Would prune: %s' % format_archive(archive))
  394. else:
  395. self.print_verbose('Pruning archive: %s' % format_archive(archive))
  396. Archive(repository, key, manifest, archive.name, cache).delete(stats)
  397. if to_delete and not args.dry_run:
  398. manifest.write()
  399. repository.commit()
  400. cache.commit()
  401. if args.stats:
  402. stats.print_('Deleted data:', cache)
  403. return self.exit_code
  404. helptext = {}
  405. helptext['patterns'] = '''
  406. Exclude patterns use a variant of shell pattern syntax, with '*' matching any
  407. number of characters, '?' matching any single character, '[...]' matching any
  408. single character specified, including ranges, and '[!...]' matching any
  409. character not specified. For the purpose of these patterns, the path
  410. separator ('\\' for Windows and '/' on other systems) is not treated
  411. specially. For a path to match a pattern, it must completely match from
  412. start to end, or must match from the start to just before a path separator.
  413. Except for the root path, paths will never end in the path separator when
  414. matching is attempted. Thus, if a given pattern ends in a path separator, a
  415. '*' is appended before matching is attempted. Patterns with wildcards should
  416. be quoted to protect them from shell expansion.
  417. Examples:
  418. # Exclude '/home/user/file.o' but not '/home/user/file.odt':
  419. $ borg create -e '*.o' backup /
  420. # Exclude '/home/user/junk' and '/home/user/subdir/junk' but
  421. # not '/home/user/importantjunk' or '/etc/junk':
  422. $ borg create -e '/home/*/junk' backup /
  423. # Exclude the contents of '/home/user/cache' but not the directory itself:
  424. $ borg create -e /home/user/cache/ backup /
  425. # The file '/home/user/cache/important' is *not* backed up:
  426. $ borg create -e /home/user/cache/ backup / /home/user/cache/important
  427. '''
  428. def do_help(self, parser, commands, args):
  429. if not args.topic:
  430. parser.print_help()
  431. elif args.topic in self.helptext:
  432. print(self.helptext[args.topic])
  433. elif args.topic in commands:
  434. if args.epilog_only:
  435. print(commands[args.topic].epilog)
  436. elif args.usage_only:
  437. commands[args.topic].epilog = None
  438. commands[args.topic].print_help()
  439. else:
  440. commands[args.topic].print_help()
  441. else:
  442. parser.error('No help available on %s' % (args.topic,))
  443. return self.exit_code
  444. def preprocess_args(self, args):
  445. deprecations = [
  446. ('--hourly', '--keep-hourly', 'Warning: "--hourly" has been deprecated. Use "--keep-hourly" instead.'),
  447. ('--daily', '--keep-daily', 'Warning: "--daily" has been deprecated. Use "--keep-daily" instead.'),
  448. ('--weekly', '--keep-weekly', 'Warning: "--weekly" has been deprecated. Use "--keep-weekly" instead.'),
  449. ('--monthly', '--keep-monthly', 'Warning: "--monthly" has been deprecated. Use "--keep-monthly" instead.'),
  450. ('--yearly', '--keep-yearly', 'Warning: "--yearly" has been deprecated. Use "--keep-yearly" instead.')
  451. ]
  452. if args and args[0] == 'verify':
  453. print('Warning: "borg verify" has been deprecated. Use "borg extract --dry-run" instead.')
  454. args = ['extract', '--dry-run'] + args[1:]
  455. for i, arg in enumerate(args[:]):
  456. for old_name, new_name, warning in deprecations:
  457. if arg.startswith(old_name):
  458. args[i] = arg.replace(old_name, new_name)
  459. print(warning)
  460. return args
  461. def run(self, args=None):
  462. check_extension_modules()
  463. keys_dir = get_keys_dir()
  464. if not os.path.exists(keys_dir):
  465. os.makedirs(keys_dir)
  466. os.chmod(keys_dir, stat.S_IRWXU)
  467. cache_dir = get_cache_dir()
  468. if not os.path.exists(cache_dir):
  469. os.makedirs(cache_dir)
  470. os.chmod(cache_dir, stat.S_IRWXU)
  471. with open(os.path.join(cache_dir, 'CACHEDIR.TAG'), 'w') as fd:
  472. fd.write(textwrap.dedent("""
  473. Signature: 8a477f597d28d172789f06886806bc55
  474. # This file is a cache directory tag created by Borg.
  475. # For information about cache directory tags, see:
  476. # http://www.brynosaurus.com/cachedir/
  477. """).lstrip())
  478. common_parser = argparse.ArgumentParser(add_help=False)
  479. common_parser.add_argument('-v', '--verbose', dest='verbose', action='store_true',
  480. default=False,
  481. help='verbose output')
  482. common_parser.add_argument('--no-files-cache', dest='cache_files', action='store_false',
  483. help='do not load/update the file metadata cache used to detect unchanged files')
  484. common_parser.add_argument('--umask', dest='umask', type=lambda s: int(s, 8), default=0o077, metavar='M',
  485. help='set umask to M (local and remote, default: 0o077)')
  486. common_parser.add_argument('--remote-path', dest='remote_path', default='borg', metavar='PATH',
  487. help='set remote path to executable (default: "borg")')
  488. # We can't use argparse for "serve" since we don't want it to show up in "Available commands"
  489. if args:
  490. args = self.preprocess_args(args)
  491. parser = argparse.ArgumentParser(description='Borg %s - Deduplicated Backups' % __version__)
  492. subparsers = parser.add_subparsers(title='Available commands')
  493. serve_epilog = textwrap.dedent("""
  494. This command starts a repository server process. This command is usually not used manually.
  495. """)
  496. subparser = subparsers.add_parser('serve', parents=[common_parser],
  497. description=self.do_serve.__doc__, epilog=serve_epilog,
  498. formatter_class=argparse.RawDescriptionHelpFormatter)
  499. subparser.set_defaults(func=self.do_serve)
  500. subparser.add_argument('--restrict-to-path', dest='restrict_to_paths', action='append',
  501. metavar='PATH', help='restrict repository access to PATH')
  502. init_epilog = textwrap.dedent("""
  503. This command initializes an empty repository. A repository is a filesystem
  504. directory containing the deduplicated data from zero or more archives.
  505. Encryption can be enabled at repository init time.
  506. Please note that the 'passphrase' encryption mode is DEPRECATED (instead of it,
  507. consider using 'repokey').
  508. """)
  509. subparser = subparsers.add_parser('init', parents=[common_parser],
  510. description=self.do_init.__doc__, epilog=init_epilog,
  511. formatter_class=argparse.RawDescriptionHelpFormatter)
  512. subparser.set_defaults(func=self.do_init)
  513. subparser.add_argument('repository', metavar='REPOSITORY',
  514. type=location_validator(archive=False),
  515. help='repository to create')
  516. subparser.add_argument('-e', '--encryption', dest='encryption',
  517. choices=('none', 'keyfile', 'repokey', 'passphrase'), default='none',
  518. help='select encryption key mode')
  519. check_epilog = textwrap.dedent("""
  520. The check command verifies the consistency of a repository and the corresponding archives.
  521. First, the underlying repository data files are checked:
  522. - For all segments the segment magic (header) is checked
  523. - For all objects stored in the segments, all metadata (e.g. crc and size) and
  524. all data is read. The read data is checked by size and CRC. Bit rot and other
  525. types of accidental damage can be detected this way.
  526. - If we are in repair mode and a integrity error is detected for a segment,
  527. we try to recover as many objects from the segment as possible.
  528. - In repair mode, it makes sure that the index is consistent with the data
  529. stored in the segments.
  530. - If you use a remote repo server via ssh:, the repo check is executed on the
  531. repo server without causing significant network traffic.
  532. - The repository check can be skipped using the --archives-only option.
  533. Second, the consistency and correctness of the archive metadata is verified:
  534. - Is the repo manifest present? If not, it is rebuilt from archive metadata
  535. chunks (this requires reading and decrypting of all metadata and data).
  536. - Check if archive metadata chunk is present. if not, remove archive from
  537. manifest.
  538. - For all files (items) in the archive, for all chunks referenced by these
  539. files, check if chunk is present (if not and we are in repair mode, replace
  540. it with a same-size chunk of zeros). This requires reading of archive and
  541. file metadata, but not data.
  542. - If we are in repair mode and we checked all the archives: delete orphaned
  543. chunks from the repo.
  544. - if you use a remote repo server via ssh:, the archive check is executed on
  545. the client machine (because if encryption is enabled, the checks will require
  546. decryption and this is always done client-side, because key access will be
  547. required).
  548. - The archive checks can be time consuming, they can be skipped using the
  549. --repository-only option.
  550. """)
  551. subparser = subparsers.add_parser('check', parents=[common_parser],
  552. description=self.do_check.__doc__,
  553. epilog=check_epilog,
  554. formatter_class=argparse.RawDescriptionHelpFormatter)
  555. subparser.set_defaults(func=self.do_check)
  556. subparser.add_argument('repository', metavar='REPOSITORY_OR_ARCHIVE',
  557. type=location_validator(),
  558. help='repository or archive to check consistency of')
  559. subparser.add_argument('--repository-only', dest='repo_only', action='store_true',
  560. default=False,
  561. help='only perform repository checks')
  562. subparser.add_argument('--archives-only', dest='archives_only', action='store_true',
  563. default=False,
  564. help='only perform archives checks')
  565. subparser.add_argument('--repair', dest='repair', action='store_true',
  566. default=False,
  567. help='attempt to repair any inconsistencies found')
  568. subparser.add_argument('--last', dest='last',
  569. type=int, default=None, metavar='N',
  570. help='only check last N archives (Default: all)')
  571. change_passphrase_epilog = textwrap.dedent("""
  572. The key files used for repository encryption are optionally passphrase
  573. protected. This command can be used to change this passphrase.
  574. """)
  575. subparser = subparsers.add_parser('change-passphrase', parents=[common_parser],
  576. description=self.do_change_passphrase.__doc__,
  577. epilog=change_passphrase_epilog,
  578. formatter_class=argparse.RawDescriptionHelpFormatter)
  579. subparser.set_defaults(func=self.do_change_passphrase)
  580. subparser.add_argument('repository', metavar='REPOSITORY',
  581. type=location_validator(archive=False))
  582. create_epilog = textwrap.dedent("""
  583. This command creates a backup archive containing all files found while recursively
  584. traversing all paths specified. The archive will consume almost no disk space for
  585. files or parts of files that have already been stored in other archives.
  586. See the output of the "borg help patterns" command for more help on exclude patterns.
  587. """)
  588. subparser = subparsers.add_parser('create', parents=[common_parser],
  589. description=self.do_create.__doc__,
  590. epilog=create_epilog,
  591. formatter_class=argparse.RawDescriptionHelpFormatter)
  592. subparser.set_defaults(func=self.do_create)
  593. subparser.add_argument('-s', '--stats', dest='stats',
  594. action='store_true', default=False,
  595. help='print statistics for the created archive')
  596. subparser.add_argument('-p', '--progress', dest='progress',
  597. action='store_true', default=False,
  598. help='print progress while creating the archive')
  599. subparser.add_argument('-e', '--exclude', dest='excludes',
  600. type=ExcludePattern, action='append',
  601. metavar="PATTERN", help='exclude paths matching PATTERN')
  602. subparser.add_argument('--exclude-from', dest='exclude_files',
  603. type=argparse.FileType('r'), action='append',
  604. metavar='EXCLUDEFILE', help='read exclude patterns from EXCLUDEFILE, one per line')
  605. subparser.add_argument('--exclude-caches', dest='exclude_caches',
  606. action='store_true', default=False,
  607. help='exclude directories that contain a CACHEDIR.TAG file (http://www.brynosaurus.com/cachedir/spec.html)')
  608. subparser.add_argument('-c', '--checkpoint-interval', dest='checkpoint_interval',
  609. type=int, default=300, metavar='SECONDS',
  610. help='write checkpoint every SECONDS seconds (Default: 300)')
  611. subparser.add_argument('--do-not-cross-mountpoints', dest='dontcross',
  612. action='store_true', default=False,
  613. help='do not cross mount points')
  614. subparser.add_argument('--numeric-owner', dest='numeric_owner',
  615. action='store_true', default=False,
  616. help='only store numeric user and group identifiers')
  617. subparser.add_argument('--timestamp', dest='timestamp',
  618. type=timestamp, default=None,
  619. metavar='yyyy-mm-ddThh:mm:ss',
  620. help='manually specify the archive creation date/time (UTC). '
  621. 'alternatively, give a reference file/directory.')
  622. subparser.add_argument('--chunker-params', dest='chunker_params',
  623. type=ChunkerParams, default=CHUNKER_PARAMS,
  624. metavar='CHUNK_MIN_EXP,CHUNK_MAX_EXP,HASH_MASK_BITS,HASH_WINDOW_SIZE',
  625. help='specify the chunker parameters. default: %d,%d,%d,%d' % CHUNKER_PARAMS)
  626. subparser.add_argument('-C', '--compression', dest='compression',
  627. type=CompressionSpec, default=dict(name='none'), metavar='COMPRESSION',
  628. help='select compression algorithm (and level): '
  629. 'none == no compression (default), '
  630. 'lz4 == lz4, '
  631. 'zlib == zlib (default level 6), '
  632. 'zlib,0 .. zlib,9 == zlib (with level 0..9), '
  633. 'lzma == lzma (default level 6), '
  634. 'lzma,0 .. lzma,9 == lzma (with level 0..9).')
  635. subparser.add_argument('archive', metavar='ARCHIVE',
  636. type=location_validator(archive=True),
  637. help='archive to create')
  638. subparser.add_argument('paths', metavar='PATH', nargs='+', type=str,
  639. help='paths to archive')
  640. extract_epilog = textwrap.dedent("""
  641. This command extracts the contents of an archive. By default the entire
  642. archive is extracted but a subset of files and directories can be selected
  643. by passing a list of ``PATHs`` as arguments. The file selection can further
  644. be restricted by using the ``--exclude`` option.
  645. See the output of the "borg help patterns" command for more help on exclude patterns.
  646. """)
  647. subparser = subparsers.add_parser('extract', parents=[common_parser],
  648. description=self.do_extract.__doc__,
  649. epilog=extract_epilog,
  650. formatter_class=argparse.RawDescriptionHelpFormatter)
  651. subparser.set_defaults(func=self.do_extract)
  652. subparser.add_argument('-n', '--dry-run', dest='dry_run',
  653. default=False, action='store_true',
  654. help='do not actually change any files')
  655. subparser.add_argument('-e', '--exclude', dest='excludes',
  656. type=ExcludePattern, action='append',
  657. metavar="PATTERN", help='exclude paths matching PATTERN')
  658. subparser.add_argument('--exclude-from', dest='exclude_files',
  659. type=argparse.FileType('r'), action='append',
  660. metavar='EXCLUDEFILE', help='read exclude patterns from EXCLUDEFILE, one per line')
  661. subparser.add_argument('--numeric-owner', dest='numeric_owner',
  662. action='store_true', default=False,
  663. help='only obey numeric user and group identifiers')
  664. subparser.add_argument('--strip-components', dest='strip_components',
  665. type=int, default=0, metavar='NUMBER',
  666. help='Remove the specified number of leading path elements. Pathnames with fewer elements will be silently skipped.')
  667. subparser.add_argument('--stdout', dest='stdout',
  668. action='store_true', default=False,
  669. help='write all extracted data to stdout')
  670. subparser.add_argument('--sparse', dest='sparse',
  671. action='store_true', default=False,
  672. help='create holes in output sparse file from all-zero chunks')
  673. subparser.add_argument('archive', metavar='ARCHIVE',
  674. type=location_validator(archive=True),
  675. help='archive to extract')
  676. subparser.add_argument('paths', metavar='PATH', nargs='*', type=str,
  677. help='paths to extract')
  678. rename_epilog = textwrap.dedent("""
  679. This command renames an archive in the repository.
  680. """)
  681. subparser = subparsers.add_parser('rename', parents=[common_parser],
  682. description=self.do_rename.__doc__,
  683. epilog=rename_epilog,
  684. formatter_class=argparse.RawDescriptionHelpFormatter)
  685. subparser.set_defaults(func=self.do_rename)
  686. subparser.add_argument('archive', metavar='ARCHIVE',
  687. type=location_validator(archive=True),
  688. help='archive to rename')
  689. subparser.add_argument('name', metavar='NEWNAME', type=str,
  690. help='the new archive name to use')
  691. delete_epilog = textwrap.dedent("""
  692. This command deletes an archive from the repository or the complete repository.
  693. Disk space is reclaimed accordingly. If you delete the complete repository, the
  694. local cache for it (if any) is also deleted.
  695. """)
  696. subparser = subparsers.add_parser('delete', parents=[common_parser],
  697. description=self.do_delete.__doc__,
  698. epilog=delete_epilog,
  699. formatter_class=argparse.RawDescriptionHelpFormatter)
  700. subparser.set_defaults(func=self.do_delete)
  701. subparser.add_argument('-s', '--stats', dest='stats',
  702. action='store_true', default=False,
  703. help='print statistics for the deleted archive')
  704. subparser.add_argument('target', metavar='TARGET',
  705. type=location_validator(),
  706. help='archive or repository to delete')
  707. list_epilog = textwrap.dedent("""
  708. This command lists the contents of a repository or an archive.
  709. """)
  710. subparser = subparsers.add_parser('list', parents=[common_parser],
  711. description=self.do_list.__doc__,
  712. epilog=list_epilog,
  713. formatter_class=argparse.RawDescriptionHelpFormatter)
  714. subparser.set_defaults(func=self.do_list)
  715. subparser.add_argument('src', metavar='REPOSITORY_OR_ARCHIVE', type=location_validator(),
  716. help='repository/archive to list contents of')
  717. mount_epilog = textwrap.dedent("""
  718. This command mounts an archive as a FUSE filesystem. This can be useful for
  719. browsing an archive or restoring individual files. Unless the ``--foreground``
  720. option is given the command will run in the background until the filesystem
  721. is ``umounted``.
  722. """)
  723. subparser = subparsers.add_parser('mount', parents=[common_parser],
  724. description=self.do_mount.__doc__,
  725. epilog=mount_epilog,
  726. formatter_class=argparse.RawDescriptionHelpFormatter)
  727. subparser.set_defaults(func=self.do_mount)
  728. subparser.add_argument('src', metavar='REPOSITORY_OR_ARCHIVE', type=location_validator(),
  729. help='repository/archive to mount')
  730. subparser.add_argument('mountpoint', metavar='MOUNTPOINT', type=str,
  731. help='where to mount filesystem')
  732. subparser.add_argument('-f', '--foreground', dest='foreground',
  733. action='store_true', default=False,
  734. help='stay in foreground, do not daemonize')
  735. subparser.add_argument('-o', dest='options', type=str,
  736. help='Extra mount options')
  737. info_epilog = textwrap.dedent("""
  738. This command displays some detailed information about the specified archive.
  739. """)
  740. subparser = subparsers.add_parser('info', parents=[common_parser],
  741. description=self.do_info.__doc__,
  742. epilog=info_epilog,
  743. formatter_class=argparse.RawDescriptionHelpFormatter)
  744. subparser.set_defaults(func=self.do_info)
  745. subparser.add_argument('archive', metavar='ARCHIVE',
  746. type=location_validator(archive=True),
  747. help='archive to display information about')
  748. prune_epilog = textwrap.dedent("""
  749. The prune command prunes a repository by deleting archives not matching
  750. any of the specified retention options. This command is normally used by
  751. automated backup scripts wanting to keep a certain number of historic backups.
  752. As an example, "-d 7" means to keep the latest backup on each day for 7 days.
  753. Days without backups do not count towards the total.
  754. The rules are applied from hourly to yearly, and backups selected by previous
  755. rules do not count towards those of later rules. The time that each backup
  756. completes is used for pruning purposes. Dates and times are interpreted in
  757. the local timezone, and weeks go from Monday to Sunday. Specifying a
  758. negative number of archives to keep means that there is no limit.
  759. The "--keep-within" option takes an argument of the form "<int><char>",
  760. where char is "H", "d", "w", "m", "y". For example, "--keep-within 2d" means
  761. to keep all archives that were created within the past 48 hours.
  762. "1m" is taken to mean "31d". The archives kept with this option do not
  763. count towards the totals specified by any other options.
  764. If a prefix is set with -p, then only archives that start with the prefix are
  765. considered for deletion and only those archives count towards the totals
  766. specified by the rules.
  767. """)
  768. subparser = subparsers.add_parser('prune', parents=[common_parser],
  769. description=self.do_prune.__doc__,
  770. epilog=prune_epilog,
  771. formatter_class=argparse.RawDescriptionHelpFormatter)
  772. subparser.set_defaults(func=self.do_prune)
  773. subparser.add_argument('-n', '--dry-run', dest='dry_run',
  774. default=False, action='store_true',
  775. help='do not change repository')
  776. subparser.add_argument('-s', '--stats', dest='stats',
  777. action='store_true', default=False,
  778. help='print statistics for the deleted archive')
  779. subparser.add_argument('--keep-within', dest='within', type=str, metavar='WITHIN',
  780. help='keep all archives within this time interval')
  781. subparser.add_argument('-H', '--keep-hourly', dest='hourly', type=int, default=0,
  782. help='number of hourly archives to keep')
  783. subparser.add_argument('-d', '--keep-daily', dest='daily', type=int, default=0,
  784. help='number of daily archives to keep')
  785. subparser.add_argument('-w', '--keep-weekly', dest='weekly', type=int, default=0,
  786. help='number of weekly archives to keep')
  787. subparser.add_argument('-m', '--keep-monthly', dest='monthly', type=int, default=0,
  788. help='number of monthly archives to keep')
  789. subparser.add_argument('-y', '--keep-yearly', dest='yearly', type=int, default=0,
  790. help='number of yearly archives to keep')
  791. subparser.add_argument('-p', '--prefix', dest='prefix', type=str,
  792. help='only consider archive names starting with this prefix')
  793. subparser.add_argument('repository', metavar='REPOSITORY',
  794. type=location_validator(archive=False),
  795. help='repository to prune')
  796. subparser = subparsers.add_parser('help', parents=[common_parser],
  797. description='Extra help')
  798. subparser.add_argument('--epilog-only', dest='epilog_only',
  799. action='store_true', default=False)
  800. subparser.add_argument('--usage-only', dest='usage_only',
  801. action='store_true', default=False)
  802. subparser.set_defaults(func=functools.partial(self.do_help, parser, subparsers.choices))
  803. subparser.add_argument('topic', metavar='TOPIC', type=str, nargs='?',
  804. help='additional help on TOPIC')
  805. args = parser.parse_args(args or ['-h'])
  806. self.verbose = args.verbose
  807. os.umask(args.umask)
  808. RemoteRepository.remote_path = args.remote_path
  809. RemoteRepository.umask = args.umask
  810. update_excludes(args)
  811. return args.func(args)
  812. def sig_info_handler(signum, stack):
  813. """search the stack for infos about the currently processed file and print them"""
  814. for frame in inspect.getouterframes(stack):
  815. func, loc = frame[3], frame[0].f_locals
  816. if func in ('process_file', '_process', ): # create op
  817. path = loc['path']
  818. try:
  819. pos = loc['fd'].tell()
  820. total = loc['st'].st_size
  821. except Exception:
  822. pos, total = 0, 0
  823. print("{0} {1}/{2}".format(path, format_file_size(pos), format_file_size(total)))
  824. break
  825. if func in ('extract_item', ): # extract op
  826. path = loc['item'][b'path']
  827. try:
  828. pos = loc['fd'].tell()
  829. except Exception:
  830. pos = 0
  831. print("{0} {1}/???".format(path, format_file_size(pos)))
  832. break
  833. def setup_signal_handlers():
  834. sigs = []
  835. if hasattr(signal, 'SIGUSR1'):
  836. sigs.append(signal.SIGUSR1) # kill -USR1 pid
  837. if hasattr(signal, 'SIGINFO'):
  838. sigs.append(signal.SIGINFO) # kill -INFO pid (or ctrl-t)
  839. for sig in sigs:
  840. signal.signal(sig, sig_info_handler)
  841. def main():
  842. # Make sure stdout and stderr have errors='replace') to avoid unicode
  843. # issues when print()-ing unicode file names
  844. sys.stdout = io.TextIOWrapper(sys.stdout.buffer, sys.stdout.encoding, 'replace', line_buffering=True)
  845. sys.stderr = io.TextIOWrapper(sys.stderr.buffer, sys.stderr.encoding, 'replace', line_buffering=True)
  846. setup_signal_handlers()
  847. archiver = Archiver()
  848. try:
  849. exit_code = archiver.run(sys.argv[1:])
  850. except Error as e:
  851. archiver.print_error(e.get_message() + "\n%s" % traceback.format_exc())
  852. exit_code = e.exit_code
  853. except RemoteRepository.RPCError as e:
  854. archiver.print_error('Error: Remote Exception.\n%s' % str(e))
  855. exit_code = 1
  856. except Exception:
  857. archiver.print_error('Error: Local Exception.\n%s' % traceback.format_exc())
  858. exit_code = 1
  859. except KeyboardInterrupt:
  860. archiver.print_error('Error: Keyboard interrupt.\n%s' % traceback.format_exc())
  861. exit_code = 1
  862. if exit_code:
  863. archiver.print_error('Exiting with failure status due to previous errors')
  864. sys.exit(exit_code)
  865. if __name__ == '__main__':
  866. main()