cache.py 19 KB

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