archiver.py 44 KB

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