archiver.py 79 KB

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