archiver.py 67 KB

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