archiver.py 70 KB

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