archiver.py 63 KB

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