2
0

cache.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. from configparser import RawConfigParser
  2. from .remote import cache_if_remote
  3. import errno
  4. import msgpack
  5. import os
  6. import sys
  7. from binascii import hexlify
  8. import shutil
  9. import tarfile
  10. import tempfile
  11. from .key import PlaintextKey
  12. from .helpers import Error, get_cache_dir, decode_dict, st_mtime_ns, unhexlify, UpgradableLock, int_to_bigint, \
  13. bigint_to_int
  14. from .hashindex import ChunkIndex
  15. class Cache:
  16. """Client Side cache
  17. """
  18. class RepositoryReplay(Error):
  19. """Cache is newer than repository, refusing to continue"""
  20. class CacheInitAbortedError(Error):
  21. """Cache initialization aborted"""
  22. class RepositoryAccessAborted(Error):
  23. """Repository access aborted"""
  24. class EncryptionMethodMismatch(Error):
  25. """Repository encryption method changed since last acccess, refusing to continue
  26. """
  27. def __init__(self, repository, key, manifest, path=None, sync=True, do_files=False, warn_if_unencrypted=True):
  28. self.lock = None
  29. self.timestamp = None
  30. self.lock = None
  31. self.txn_active = False
  32. self.repository = repository
  33. self.key = key
  34. self.manifest = manifest
  35. self.path = path or os.path.join(get_cache_dir(), hexlify(repository.id).decode('ascii'))
  36. self.do_files = do_files
  37. # Warn user before sending data to a never seen before unencrypted repository
  38. if not os.path.exists(self.path):
  39. if warn_if_unencrypted and isinstance(key, PlaintextKey):
  40. if not self._confirm('Warning: Attempting to access a previously unknown unencrypted repository',
  41. 'BORG_UNKNOWN_UNENCRYPTED_REPO_ACCESS_IS_OK'):
  42. raise self.CacheInitAbortedError()
  43. self.create()
  44. self.open()
  45. # Warn user before sending data to a relocated repository
  46. if self.previous_location and self.previous_location != repository._location.canonical_path():
  47. msg = 'Warning: The repository at location {} was previously located at {}'.format(repository._location.canonical_path(), self.previous_location)
  48. if not self._confirm(msg, 'BORG_RELOCATED_REPO_ACCESS_IS_OK'):
  49. raise self.RepositoryAccessAborted()
  50. if sync and self.manifest.id != self.manifest_id:
  51. # If repository is older than the cache something fishy is going on
  52. if self.timestamp and self.timestamp > manifest.timestamp:
  53. raise self.RepositoryReplay()
  54. # Make sure an encrypted repository has not been swapped for an unencrypted repository
  55. if self.key_type is not None and self.key_type != str(key.TYPE):
  56. raise self.EncryptionMethodMismatch()
  57. self.sync()
  58. self.commit()
  59. def __del__(self):
  60. self.close()
  61. def _confirm(self, message, env_var_override=None):
  62. print(message, file=sys.stderr)
  63. if env_var_override and os.environ.get(env_var_override):
  64. print("Yes (From {})".format(env_var_override))
  65. return True
  66. if not sys.stdin.isatty():
  67. return False
  68. try:
  69. answer = input('Do you want to continue? [yN] ')
  70. except EOFError:
  71. return False
  72. return answer and answer in 'Yy'
  73. def create(self):
  74. """Create a new empty cache at `self.path`
  75. """
  76. os.makedirs(self.path)
  77. with open(os.path.join(self.path, 'README'), 'w') as fd:
  78. fd.write('This is a Borg cache')
  79. config = RawConfigParser()
  80. config.add_section('cache')
  81. config.set('cache', 'version', '1')
  82. config.set('cache', 'repository', hexlify(self.repository.id).decode('ascii'))
  83. config.set('cache', 'manifest', '')
  84. with open(os.path.join(self.path, 'config'), 'w') as fd:
  85. config.write(fd)
  86. ChunkIndex().write(os.path.join(self.path, 'chunks').encode('utf-8'))
  87. with open(os.path.join(self.path, 'chunks.archive'), 'wb') as fd:
  88. pass # empty file
  89. with open(os.path.join(self.path, 'files'), 'wb') as fd:
  90. pass # empty file
  91. def destroy(self):
  92. """destroy the cache at `self.path`
  93. """
  94. self.close()
  95. os.remove(os.path.join(self.path, 'config')) # kill config first
  96. shutil.rmtree(self.path)
  97. def _do_open(self):
  98. self.config = RawConfigParser()
  99. self.config.read(os.path.join(self.path, 'config'))
  100. if self.config.getint('cache', 'version') != 1:
  101. raise Exception('%s Does not look like a Borg cache')
  102. self.id = self.config.get('cache', 'repository')
  103. self.manifest_id = unhexlify(self.config.get('cache', 'manifest'))
  104. self.timestamp = self.config.get('cache', 'timestamp', fallback=None)
  105. self.key_type = self.config.get('cache', 'key_type', fallback=None)
  106. self.previous_location = self.config.get('cache', 'previous_location', fallback=None)
  107. self.chunks = ChunkIndex.read(os.path.join(self.path, 'chunks').encode('utf-8'))
  108. self.files = None
  109. def open(self):
  110. if not os.path.isdir(self.path):
  111. raise Exception('%s Does not look like a Borg cache' % self.path)
  112. self.lock = UpgradableLock(os.path.join(self.path, 'config'), exclusive=True)
  113. self.rollback()
  114. def close(self):
  115. if self.lock:
  116. self.lock.release()
  117. self.lock = None
  118. def _read_files(self):
  119. self.files = {}
  120. self._newest_mtime = 0
  121. with open(os.path.join(self.path, 'files'), 'rb') as fd:
  122. u = msgpack.Unpacker(use_list=True)
  123. while True:
  124. data = fd.read(64 * 1024)
  125. if not data:
  126. break
  127. u.feed(data)
  128. for path_hash, item in u:
  129. item[0] += 1
  130. # in the end, this takes about 240 Bytes per file
  131. self.files[path_hash] = msgpack.packb(item)
  132. def begin_txn(self):
  133. # Initialize transaction snapshot
  134. txn_dir = os.path.join(self.path, 'txn.tmp')
  135. os.mkdir(txn_dir)
  136. shutil.copy(os.path.join(self.path, 'config'), txn_dir)
  137. shutil.copy(os.path.join(self.path, 'chunks'), txn_dir)
  138. shutil.copy(os.path.join(self.path, 'chunks.archive'), txn_dir)
  139. shutil.copy(os.path.join(self.path, 'files'), txn_dir)
  140. os.rename(os.path.join(self.path, 'txn.tmp'),
  141. os.path.join(self.path, 'txn.active'))
  142. self.txn_active = True
  143. def commit(self):
  144. """Commit transaction
  145. """
  146. if not self.txn_active:
  147. return
  148. if self.files is not None:
  149. with open(os.path.join(self.path, 'files'), 'wb') as fd:
  150. for path_hash, item in self.files.items():
  151. # Discard cached files with the newest mtime to avoid
  152. # issues with filesystem snapshots and mtime precision
  153. item = msgpack.unpackb(item)
  154. if item[0] < 10 and bigint_to_int(item[3]) < self._newest_mtime:
  155. msgpack.pack((path_hash, item), fd)
  156. self.config.set('cache', 'manifest', hexlify(self.manifest.id).decode('ascii'))
  157. self.config.set('cache', 'timestamp', self.manifest.timestamp)
  158. self.config.set('cache', 'key_type', str(self.key.TYPE))
  159. self.config.set('cache', 'previous_location', self.repository._location.canonical_path())
  160. with open(os.path.join(self.path, 'config'), 'w') as fd:
  161. self.config.write(fd)
  162. self.chunks.write(os.path.join(self.path, 'chunks').encode('utf-8'))
  163. os.rename(os.path.join(self.path, 'txn.active'),
  164. os.path.join(self.path, 'txn.tmp'))
  165. shutil.rmtree(os.path.join(self.path, 'txn.tmp'))
  166. self.txn_active = False
  167. def rollback(self):
  168. """Roll back partial and aborted transactions
  169. """
  170. # Remove partial transaction
  171. if os.path.exists(os.path.join(self.path, 'txn.tmp')):
  172. shutil.rmtree(os.path.join(self.path, 'txn.tmp'))
  173. # Roll back active transaction
  174. txn_dir = os.path.join(self.path, 'txn.active')
  175. if os.path.exists(txn_dir):
  176. shutil.copy(os.path.join(txn_dir, 'config'), self.path)
  177. shutil.copy(os.path.join(txn_dir, 'chunks'), self.path)
  178. shutil.copy(os.path.join(txn_dir, 'chunks.archive'), self.path)
  179. shutil.copy(os.path.join(txn_dir, 'files'), self.path)
  180. os.rename(txn_dir, os.path.join(self.path, 'txn.tmp'))
  181. if os.path.exists(os.path.join(self.path, 'txn.tmp')):
  182. shutil.rmtree(os.path.join(self.path, 'txn.tmp'))
  183. self.txn_active = False
  184. self._do_open()
  185. def sync(self):
  186. """Re-synchronize chunks cache with repository.
  187. If present, uses a compressed tar archive of known backup archive
  188. indices, so it only needs to fetch infos from repo and build a chunk
  189. index once per backup archive.
  190. If out of sync, the tar gets rebuilt from known + fetched chunk infos,
  191. so it has complete and current information about all backup archives.
  192. Finally, it builds the master chunks index by merging all indices from
  193. the tar.
  194. Note: compression (esp. xz) is very effective in keeping the tar
  195. relatively small compared to the files it contains.
  196. """
  197. in_archive_path = os.path.join(self.path, 'chunks.archive')
  198. out_archive_path = os.path.join(self.path, 'chunks.archive.tmp')
  199. def open_in_archive():
  200. try:
  201. tf = tarfile.open(in_archive_path, 'r')
  202. except OSError as e:
  203. if e.errno != errno.ENOENT:
  204. raise
  205. # file not found
  206. tf = None
  207. except tarfile.ReadError:
  208. # empty file?
  209. tf = None
  210. return tf
  211. def open_out_archive():
  212. for compression in ('xz', 'bz2', 'gz'):
  213. # xz needs py 3.3, bz2 and gz also work on 3.2
  214. try:
  215. tf = tarfile.open(out_archive_path, 'w:'+compression, format=tarfile.PAX_FORMAT)
  216. break
  217. except tarfile.CompressionError:
  218. continue
  219. else: # shouldn't happen
  220. tf = None
  221. return tf
  222. def close_archive(tf):
  223. if tf:
  224. tf.close()
  225. def delete_in_archive():
  226. os.unlink(in_archive_path)
  227. def rename_out_archive():
  228. os.rename(out_archive_path, in_archive_path)
  229. def add(chunk_idx, id, size, csize, incr=1):
  230. try:
  231. count, size, csize = chunk_idx[id]
  232. chunk_idx[id] = count + incr, size, csize
  233. except KeyError:
  234. chunk_idx[id] = incr, size, csize
  235. def transfer_known_idx(archive_id, tf_in, tf_out):
  236. archive_id_hex = hexlify(archive_id).decode('ascii')
  237. tarinfo = tf_in.getmember(archive_id_hex)
  238. archive_name = tarinfo.pax_headers['archive_name']
  239. print('Already known archive:', archive_name)
  240. f_in = tf_in.extractfile(archive_id_hex)
  241. tf_out.addfile(tarinfo, f_in)
  242. return archive_name
  243. def fetch_and_build_idx(archive_id, repository, key, tmp_dir, tf_out):
  244. chunk_idx = ChunkIndex()
  245. cdata = repository.get(archive_id)
  246. data = key.decrypt(archive_id, cdata)
  247. add(chunk_idx, archive_id, len(data), len(cdata))
  248. archive = msgpack.unpackb(data)
  249. if archive[b'version'] != 1:
  250. raise Exception('Unknown archive metadata version')
  251. decode_dict(archive, (b'name',))
  252. print('Analyzing new archive:', archive[b'name'])
  253. unpacker = msgpack.Unpacker()
  254. for item_id, chunk in zip(archive[b'items'], repository.get_many(archive[b'items'])):
  255. data = key.decrypt(item_id, chunk)
  256. add(chunk_idx, item_id, len(data), len(chunk))
  257. unpacker.feed(data)
  258. for item in unpacker:
  259. if b'chunks' in item:
  260. for chunk_id, size, csize in item[b'chunks']:
  261. add(chunk_idx, chunk_id, size, csize)
  262. archive_id_hex = hexlify(archive_id).decode('ascii')
  263. file_tmp = os.path.join(tmp_dir, archive_id_hex).encode('utf-8')
  264. chunk_idx.write(file_tmp)
  265. tarinfo = tf_out.gettarinfo(file_tmp, archive_id_hex)
  266. tarinfo.pax_headers['archive_name'] = archive[b'name']
  267. with open(file_tmp, 'rb') as f:
  268. tf_out.addfile(tarinfo, f)
  269. os.unlink(file_tmp)
  270. def create_master_idx(chunk_idx, tf_in, tmp_dir):
  271. chunk_idx.clear()
  272. for tarinfo in tf_in:
  273. archive_id_hex = tarinfo.name
  274. tf_in.extract(archive_id_hex, tmp_dir)
  275. chunk_idx_path = os.path.join(tmp_dir, archive_id_hex).encode('utf-8')
  276. archive_chunk_idx = ChunkIndex.read(chunk_idx_path)
  277. for chunk_id, (count, size, csize) in archive_chunk_idx.iteritems():
  278. add(chunk_idx, chunk_id, size, csize, incr=count)
  279. os.unlink(chunk_idx_path)
  280. self.begin_txn()
  281. print('Synchronizing chunks cache...')
  282. # XXX we have to do stuff on disk due to lacking ChunkIndex api
  283. with tempfile.TemporaryDirectory() as tmp_dir:
  284. repository = cache_if_remote(self.repository)
  285. out_archive = open_out_archive()
  286. in_archive = open_in_archive()
  287. if in_archive:
  288. known_ids = set(unhexlify(hexid) for hexid in in_archive.getnames())
  289. else:
  290. known_ids = set()
  291. archive_ids = set(info[b'id'] for info in self.manifest.archives.values())
  292. print('Rebuilding archive collection. Known: %d Repo: %d Unknown: %d' % (
  293. len(known_ids), len(archive_ids), len(archive_ids - known_ids), ))
  294. for archive_id in archive_ids & known_ids:
  295. transfer_known_idx(archive_id, in_archive, out_archive)
  296. close_archive(in_archive)
  297. delete_in_archive() # free disk space
  298. for archive_id in archive_ids - known_ids:
  299. fetch_and_build_idx(archive_id, repository, self.key, tmp_dir, out_archive)
  300. close_archive(out_archive)
  301. rename_out_archive()
  302. print('Merging collection into master chunks cache...')
  303. in_archive = open_in_archive()
  304. create_master_idx(self.chunks, in_archive, tmp_dir)
  305. close_archive(in_archive)
  306. print('Done.')
  307. def add_chunk(self, id, data, stats):
  308. if not self.txn_active:
  309. self.begin_txn()
  310. if self.seen_chunk(id):
  311. return self.chunk_incref(id, stats)
  312. size = len(data)
  313. data = self.key.encrypt(data)
  314. csize = len(data)
  315. self.repository.put(id, data, wait=False)
  316. self.chunks[id] = (1, size, csize)
  317. stats.update(size, csize, True)
  318. return id, size, csize
  319. def seen_chunk(self, id):
  320. return self.chunks.get(id, (0, 0, 0))[0]
  321. def chunk_incref(self, id, stats):
  322. if not self.txn_active:
  323. self.begin_txn()
  324. count, size, csize = self.chunks[id]
  325. self.chunks[id] = (count + 1, size, csize)
  326. stats.update(size, csize, False)
  327. return id, size, csize
  328. def chunk_decref(self, id, stats):
  329. if not self.txn_active:
  330. self.begin_txn()
  331. count, size, csize = self.chunks[id]
  332. if count == 1:
  333. del self.chunks[id]
  334. self.repository.delete(id, wait=False)
  335. stats.update(-size, -csize, True)
  336. else:
  337. self.chunks[id] = (count - 1, size, csize)
  338. stats.update(-size, -csize, False)
  339. def file_known_and_unchanged(self, path_hash, st):
  340. if not self.do_files:
  341. return None
  342. if self.files is None:
  343. self._read_files()
  344. entry = self.files.get(path_hash)
  345. if not entry:
  346. return None
  347. entry = msgpack.unpackb(entry)
  348. if entry[2] == st.st_size and bigint_to_int(entry[3]) == st_mtime_ns(st) and entry[1] == st.st_ino:
  349. # reset entry age
  350. entry[0] = 0
  351. self.files[path_hash] = msgpack.packb(entry)
  352. return entry[4]
  353. else:
  354. return None
  355. def memorize_file(self, path_hash, st, ids):
  356. if not self.do_files:
  357. return
  358. # Entry: Age, inode, size, mtime, chunk ids
  359. mtime_ns = st_mtime_ns(st)
  360. self.files[path_hash] = msgpack.packb((0, st.st_ino, st.st_size, int_to_bigint(mtime_ns), ids))
  361. self._newest_mtime = max(self._newest_mtime, mtime_ns)