cache.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. import configparser
  2. from .remote import cache_if_remote
  3. from collections import namedtuple
  4. import os
  5. import stat
  6. from binascii import unhexlify
  7. import shutil
  8. from .key import PlaintextKey
  9. from .logger import create_logger
  10. logger = create_logger()
  11. from .helpers import Error, get_cache_dir, decode_dict, int_to_bigint, \
  12. bigint_to_int, format_file_size, yes, bin_to_hex, Location
  13. from .locking import Lock
  14. from .hashindex import ChunkIndex
  15. import msgpack
  16. class Cache:
  17. """Client Side cache
  18. """
  19. class RepositoryIDNotUnique(Error):
  20. """Cache is newer than repository - do you have multiple, independently updated repos with same ID?"""
  21. class RepositoryReplay(Error):
  22. """Cache is newer than repository - this is either an attack or unsafe (multiple repos with same ID)"""
  23. class CacheInitAbortedError(Error):
  24. """Cache initialization aborted"""
  25. class RepositoryAccessAborted(Error):
  26. """Repository access aborted"""
  27. class EncryptionMethodMismatch(Error):
  28. """Repository encryption method changed since last access, refusing to continue"""
  29. @staticmethod
  30. def break_lock(repository, path=None):
  31. path = path or os.path.join(get_cache_dir(), bin_to_hex(repository.id))
  32. Lock(os.path.join(path, 'lock'), exclusive=True).break_lock()
  33. @staticmethod
  34. def destroy(repository, path=None):
  35. """destroy the cache for ``repository`` or at ``path``"""
  36. path = path or os.path.join(get_cache_dir(), bin_to_hex(repository.id))
  37. config = os.path.join(path, 'config')
  38. if os.path.exists(config):
  39. os.remove(config) # kill config first
  40. shutil.rmtree(path)
  41. def __init__(self, repository, key, manifest, path=None, sync=True, do_files=False, warn_if_unencrypted=True,
  42. lock_wait=None):
  43. self.lock = None
  44. self.timestamp = None
  45. self.lock = None
  46. self.txn_active = False
  47. self.repository = repository
  48. self.key = key
  49. self.manifest = manifest
  50. self.path = path or os.path.join(get_cache_dir(), bin_to_hex(repository.id))
  51. self.do_files = do_files
  52. # Warn user before sending data to a never seen before unencrypted repository
  53. if not os.path.exists(self.path):
  54. if warn_if_unencrypted and isinstance(key, PlaintextKey):
  55. msg = ("Warning: Attempting to access a previously unknown unencrypted repository!" +
  56. "\n" +
  57. "Do you want to continue? [yN] ")
  58. if not yes(msg, false_msg="Aborting.", invalid_msg="Invalid answer, aborting.",
  59. retry=False, env_var_override='BORG_UNKNOWN_UNENCRYPTED_REPO_ACCESS_IS_OK'):
  60. raise self.CacheInitAbortedError()
  61. self.create()
  62. self.open(lock_wait=lock_wait)
  63. try:
  64. # Warn user before sending data to a relocated repository
  65. if self.previous_location and self.previous_location != repository._location.canonical_path():
  66. msg = ("Warning: The repository at location {} was previously located at {}".format(repository._location.canonical_path(), self.previous_location) +
  67. "\n" +
  68. "Do you want to continue? [yN] ")
  69. if not yes(msg, false_msg="Aborting.", invalid_msg="Invalid answer, aborting.",
  70. retry=False, env_var_override='BORG_RELOCATED_REPO_ACCESS_IS_OK'):
  71. raise self.RepositoryAccessAborted()
  72. # adapt on-disk config immediately if the new location was accepted
  73. self.begin_txn()
  74. self.commit()
  75. if sync and self.manifest.id != self.manifest_id:
  76. # If repository is older than the cache something fishy is going on
  77. if self.timestamp and self.timestamp > manifest.timestamp:
  78. if isinstance(key, PlaintextKey):
  79. raise self.RepositoryIDNotUnique()
  80. else:
  81. raise self.RepositoryReplay()
  82. # Make sure an encrypted repository has not been swapped for an unencrypted repository
  83. if self.key_type is not None and self.key_type != str(key.TYPE):
  84. raise self.EncryptionMethodMismatch()
  85. self.sync()
  86. self.commit()
  87. except:
  88. self.close()
  89. raise
  90. def __enter__(self):
  91. return self
  92. def __exit__(self, exc_type, exc_val, exc_tb):
  93. self.close()
  94. def __str__(self):
  95. fmt = """\
  96. All archives: {0.total_size:>20s} {0.total_csize:>20s} {0.unique_csize:>20s}
  97. Unique chunks Total chunks
  98. Chunk index: {0.total_unique_chunks:20d} {0.total_chunks:20d}"""
  99. return fmt.format(self.format_tuple())
  100. def format_tuple(self):
  101. # XXX: this should really be moved down to `hashindex.pyx`
  102. Summary = namedtuple('Summary', ['total_size', 'total_csize', 'unique_size', 'unique_csize', 'total_unique_chunks', 'total_chunks'])
  103. stats = Summary(*self.chunks.summarize())._asdict()
  104. for field in ['total_size', 'total_csize', 'unique_csize']:
  105. stats[field] = format_file_size(stats[field])
  106. return Summary(**stats)
  107. def create(self):
  108. """Create a new empty cache at `self.path`
  109. """
  110. os.makedirs(self.path)
  111. with open(os.path.join(self.path, 'README'), 'w') as fd:
  112. fd.write('This is a Borg cache')
  113. config = configparser.ConfigParser(interpolation=None)
  114. config.add_section('cache')
  115. config.set('cache', 'version', '1')
  116. config.set('cache', 'repository', bin_to_hex(self.repository.id))
  117. config.set('cache', 'manifest', '')
  118. with open(os.path.join(self.path, 'config'), 'w') as fd:
  119. config.write(fd)
  120. ChunkIndex().write(os.path.join(self.path, 'chunks').encode('utf-8'))
  121. os.makedirs(os.path.join(self.path, 'chunks.archive.d'))
  122. with open(os.path.join(self.path, 'files'), 'wb') as fd:
  123. pass # empty file
  124. def _check_upgrade(self, config_path):
  125. try:
  126. cache_version = self.config.getint('cache', 'version')
  127. wanted_version = 1
  128. if cache_version != wanted_version:
  129. self.close()
  130. raise Exception('%s has unexpected cache version %d (wanted: %d).' % (
  131. config_path, cache_version, wanted_version))
  132. except configparser.NoSectionError:
  133. self.close()
  134. raise Exception('%s does not look like a Borg cache.' % config_path) from None
  135. # borg < 1.0.8rc1 had different canonicalization for the repo location (see #1655 and #1741).
  136. cache_loc = self.config.get('cache', 'previous_location', fallback=None)
  137. if cache_loc:
  138. repo_loc = self.repository._location.canonical_path()
  139. rl = Location(repo_loc)
  140. cl = Location(cache_loc)
  141. if cl.proto == rl.proto and cl.user == rl.user and cl.host == rl.host and cl.port == rl.port \
  142. and \
  143. cl.path and rl.path and \
  144. cl.path.startswith('/~/') and rl.path.startswith('/./') and cl.path[3:] == rl.path[3:]:
  145. # everything is same except the expected change in relative path canonicalization,
  146. # update previous_location to avoid warning / user query about changed location:
  147. self.config.set('cache', 'previous_location', repo_loc)
  148. def _do_open(self):
  149. self.config = configparser.ConfigParser(interpolation=None)
  150. config_path = os.path.join(self.path, 'config')
  151. self.config.read(config_path)
  152. self._check_upgrade(config_path)
  153. self.id = self.config.get('cache', 'repository')
  154. self.manifest_id = unhexlify(self.config.get('cache', 'manifest'))
  155. self.timestamp = self.config.get('cache', 'timestamp', fallback=None)
  156. self.key_type = self.config.get('cache', 'key_type', fallback=None)
  157. self.previous_location = self.config.get('cache', 'previous_location', fallback=None)
  158. self.chunks = ChunkIndex.read(os.path.join(self.path, 'chunks').encode('utf-8'))
  159. self.files = None
  160. def open(self, lock_wait=None):
  161. if not os.path.isdir(self.path):
  162. raise Exception('%s Does not look like a Borg cache' % self.path)
  163. self.lock = Lock(os.path.join(self.path, 'lock'), exclusive=True, timeout=lock_wait).acquire()
  164. self.rollback()
  165. def close(self):
  166. if self.lock is not None:
  167. self.lock.release()
  168. self.lock = None
  169. def _read_files(self):
  170. self.files = {}
  171. self._newest_mtime = None
  172. logger.debug('Reading files cache ...')
  173. with open(os.path.join(self.path, 'files'), 'rb') as fd:
  174. u = msgpack.Unpacker(use_list=True)
  175. while True:
  176. data = fd.read(64 * 1024)
  177. if not data:
  178. break
  179. u.feed(data)
  180. for path_hash, item in u:
  181. item[0] += 1
  182. # in the end, this takes about 240 Bytes per file
  183. self.files[path_hash] = msgpack.packb(item)
  184. def begin_txn(self):
  185. # Initialize transaction snapshot
  186. txn_dir = os.path.join(self.path, 'txn.tmp')
  187. os.mkdir(txn_dir)
  188. shutil.copy(os.path.join(self.path, 'config'), txn_dir)
  189. shutil.copy(os.path.join(self.path, 'chunks'), txn_dir)
  190. shutil.copy(os.path.join(self.path, 'files'), txn_dir)
  191. os.rename(os.path.join(self.path, 'txn.tmp'),
  192. os.path.join(self.path, 'txn.active'))
  193. self.txn_active = True
  194. def commit(self):
  195. """Commit transaction
  196. """
  197. if not self.txn_active:
  198. return
  199. if self.files is not None:
  200. if self._newest_mtime is None:
  201. # was never set because no files were modified/added
  202. self._newest_mtime = 2 ** 63 - 1 # nanoseconds, good until y2262
  203. ttl = int(os.environ.get('BORG_FILES_CACHE_TTL', 20))
  204. with open(os.path.join(self.path, 'files'), 'wb') as fd:
  205. for path_hash, item in self.files.items():
  206. # Only keep files seen in this backup that are older than newest mtime seen in this backup -
  207. # this is to avoid issues with filesystem snapshots and mtime granularity.
  208. # Also keep files from older backups that have not reached BORG_FILES_CACHE_TTL yet.
  209. item = msgpack.unpackb(item)
  210. age = item[0]
  211. if age == 0 and bigint_to_int(item[3]) < self._newest_mtime or \
  212. age > 0 and age < ttl:
  213. msgpack.pack((path_hash, item), fd)
  214. self.config.set('cache', 'manifest', bin_to_hex(self.manifest.id))
  215. self.config.set('cache', 'timestamp', self.manifest.timestamp)
  216. self.config.set('cache', 'key_type', str(self.key.TYPE))
  217. self.config.set('cache', 'previous_location', self.repository._location.canonical_path())
  218. with open(os.path.join(self.path, 'config'), 'w') as fd:
  219. self.config.write(fd)
  220. self.chunks.write(os.path.join(self.path, 'chunks').encode('utf-8'))
  221. os.rename(os.path.join(self.path, 'txn.active'),
  222. os.path.join(self.path, 'txn.tmp'))
  223. shutil.rmtree(os.path.join(self.path, 'txn.tmp'))
  224. self.txn_active = False
  225. def rollback(self):
  226. """Roll back partial and aborted transactions
  227. """
  228. # Remove partial transaction
  229. if os.path.exists(os.path.join(self.path, 'txn.tmp')):
  230. shutil.rmtree(os.path.join(self.path, 'txn.tmp'))
  231. # Roll back active transaction
  232. txn_dir = os.path.join(self.path, 'txn.active')
  233. if os.path.exists(txn_dir):
  234. shutil.copy(os.path.join(txn_dir, 'config'), self.path)
  235. shutil.copy(os.path.join(txn_dir, 'chunks'), self.path)
  236. shutil.copy(os.path.join(txn_dir, 'files'), self.path)
  237. os.rename(txn_dir, os.path.join(self.path, 'txn.tmp'))
  238. if os.path.exists(os.path.join(self.path, 'txn.tmp')):
  239. shutil.rmtree(os.path.join(self.path, 'txn.tmp'))
  240. self.txn_active = False
  241. self._do_open()
  242. def sync(self):
  243. """Re-synchronize chunks cache with repository.
  244. Maintains a directory with known backup archive indexes, so it only
  245. needs to fetch infos from repo and build a chunk index once per backup
  246. archive.
  247. If out of sync, missing archive indexes get added, outdated indexes
  248. get removed and a new master chunks index is built by merging all
  249. archive indexes.
  250. """
  251. archive_path = os.path.join(self.path, 'chunks.archive.d')
  252. def mkpath(id, suffix=''):
  253. id_hex = bin_to_hex(id)
  254. path = os.path.join(archive_path, id_hex + suffix)
  255. return path.encode('utf-8')
  256. def cached_archives():
  257. if self.do_cache:
  258. fns = os.listdir(archive_path)
  259. # filenames with 64 hex digits == 256bit
  260. return set(unhexlify(fn) for fn in fns if len(fn) == 64)
  261. else:
  262. return set()
  263. def repo_archives():
  264. return set(info[b'id'] for info in self.manifest.archives.values())
  265. def cleanup_outdated(ids):
  266. for id in ids:
  267. os.unlink(mkpath(id))
  268. def fetch_and_build_idx(archive_id, repository, key):
  269. chunk_idx = ChunkIndex()
  270. cdata = repository.get(archive_id)
  271. data = key.decrypt(archive_id, cdata)
  272. chunk_idx.add(archive_id, 1, len(data), len(cdata))
  273. archive = msgpack.unpackb(data)
  274. if archive[b'version'] != 1:
  275. raise Exception('Unknown archive metadata version')
  276. decode_dict(archive, (b'name',))
  277. unpacker = msgpack.Unpacker()
  278. for item_id, chunk in zip(archive[b'items'], repository.get_many(archive[b'items'])):
  279. data = key.decrypt(item_id, chunk)
  280. chunk_idx.add(item_id, 1, len(data), len(chunk))
  281. unpacker.feed(data)
  282. for item in unpacker:
  283. if not isinstance(item, dict):
  284. logger.error('Error: Did not get expected metadata dict - archive corrupted!')
  285. continue
  286. if b'chunks' in item:
  287. for chunk_id, size, csize in item[b'chunks']:
  288. chunk_idx.add(chunk_id, 1, size, csize)
  289. if self.do_cache:
  290. fn = mkpath(archive_id)
  291. fn_tmp = mkpath(archive_id, suffix='.tmp')
  292. try:
  293. chunk_idx.write(fn_tmp)
  294. except Exception:
  295. os.unlink(fn_tmp)
  296. else:
  297. os.rename(fn_tmp, fn)
  298. return chunk_idx
  299. def lookup_name(archive_id):
  300. for name, info in self.manifest.archives.items():
  301. if info[b'id'] == archive_id:
  302. return name
  303. def create_master_idx(chunk_idx):
  304. logger.info('Synchronizing chunks cache...')
  305. cached_ids = cached_archives()
  306. archive_ids = repo_archives()
  307. logger.info('Archives: %d, w/ cached Idx: %d, w/ outdated Idx: %d, w/o cached Idx: %d.' % (
  308. len(archive_ids), len(cached_ids),
  309. len(cached_ids - archive_ids), len(archive_ids - cached_ids), ))
  310. # deallocates old hashindex, creates empty hashindex:
  311. chunk_idx.clear()
  312. cleanup_outdated(cached_ids - archive_ids)
  313. if archive_ids:
  314. chunk_idx = None
  315. for archive_id in archive_ids:
  316. archive_name = lookup_name(archive_id)
  317. if archive_id in cached_ids:
  318. archive_chunk_idx_path = mkpath(archive_id)
  319. logger.info("Reading cached archive chunk index for %s ..." % archive_name)
  320. archive_chunk_idx = ChunkIndex.read(archive_chunk_idx_path)
  321. else:
  322. logger.info('Fetching and building archive index for %s ...' % archive_name)
  323. archive_chunk_idx = fetch_and_build_idx(archive_id, repository, self.key)
  324. logger.info("Merging into master chunks index ...")
  325. if chunk_idx is None:
  326. # we just use the first archive's idx as starting point,
  327. # to avoid growing the hash table from 0 size and also
  328. # to save 1 merge call.
  329. chunk_idx = archive_chunk_idx
  330. else:
  331. chunk_idx.merge(archive_chunk_idx)
  332. logger.info('Done.')
  333. return chunk_idx
  334. def legacy_cleanup():
  335. """bring old cache dirs into the desired state (cleanup and adapt)"""
  336. try:
  337. os.unlink(os.path.join(self.path, 'chunks.archive'))
  338. except:
  339. pass
  340. try:
  341. os.unlink(os.path.join(self.path, 'chunks.archive.tmp'))
  342. except:
  343. pass
  344. try:
  345. os.mkdir(archive_path)
  346. except:
  347. pass
  348. self.begin_txn()
  349. with cache_if_remote(self.repository) as repository:
  350. legacy_cleanup()
  351. # TEMPORARY HACK: to avoid archive index caching, create a FILE named ~/.cache/borg/REPOID/chunks.archive.d -
  352. # this is only recommended if you have a fast, low latency connection to your repo (e.g. if repo is local disk)
  353. self.do_cache = os.path.isdir(archive_path)
  354. self.chunks = create_master_idx(self.chunks)
  355. def add_chunk(self, id, data, stats):
  356. if not self.txn_active:
  357. self.begin_txn()
  358. size = len(data)
  359. if self.seen_chunk(id, size):
  360. return self.chunk_incref(id, stats)
  361. data = self.key.encrypt(data)
  362. csize = len(data)
  363. self.repository.put(id, data, wait=False)
  364. self.chunks[id] = (1, size, csize)
  365. stats.update(size, csize, True)
  366. return id, size, csize
  367. def seen_chunk(self, id, size=None):
  368. refcount, stored_size, _ = self.chunks.get(id, (0, None, None))
  369. if size is not None and stored_size is not None and size != stored_size:
  370. # we already have a chunk with that id, but different size.
  371. # this is either a hash collision (unlikely) or corruption or a bug.
  372. raise Exception("chunk has same id [%r], but different size (stored: %d new: %d)!" % (
  373. id, stored_size, size))
  374. return refcount
  375. def chunk_incref(self, id, stats):
  376. if not self.txn_active:
  377. self.begin_txn()
  378. count, size, csize = self.chunks.incref(id)
  379. stats.update(size, csize, False)
  380. return id, size, csize
  381. def chunk_decref(self, id, stats):
  382. if not self.txn_active:
  383. self.begin_txn()
  384. count, size, csize = self.chunks.decref(id)
  385. if count == 0:
  386. del self.chunks[id]
  387. self.repository.delete(id, wait=False)
  388. stats.update(-size, -csize, True)
  389. else:
  390. stats.update(-size, -csize, False)
  391. def file_known_and_unchanged(self, path_hash, st, ignore_inode=False):
  392. if not (self.do_files and stat.S_ISREG(st.st_mode)):
  393. return None
  394. if self.files is None:
  395. self._read_files()
  396. entry = self.files.get(path_hash)
  397. if not entry:
  398. return None
  399. entry = msgpack.unpackb(entry)
  400. if (entry[2] == st.st_size and bigint_to_int(entry[3]) == st.st_mtime_ns and
  401. (ignore_inode or entry[1] == st.st_ino)):
  402. # reset entry age
  403. entry[0] = 0
  404. self.files[path_hash] = msgpack.packb(entry)
  405. return entry[4]
  406. else:
  407. return None
  408. def memorize_file(self, path_hash, st, ids):
  409. if not (self.do_files and stat.S_ISREG(st.st_mode)):
  410. return
  411. # Entry: Age, inode, size, mtime, chunk ids
  412. mtime_ns = st.st_mtime_ns
  413. self.files[path_hash] = msgpack.packb((0, st.st_ino, st.st_size, int_to_bigint(mtime_ns), ids))
  414. self._newest_mtime = max(self._newest_mtime or 0, mtime_ns)