archiver.py 66 KB

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