archiver.py 45 KB

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