archiver.py 44 KB

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