cache.py 18 KB

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