archiver.py 51 KB

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