repository.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861
  1. from configparser import ConfigParser
  2. from binascii import unhexlify
  3. from datetime import datetime
  4. from itertools import islice
  5. import errno
  6. import os
  7. import shutil
  8. import struct
  9. from zlib import crc32
  10. import msgpack
  11. from .logger import create_logger
  12. logger = create_logger()
  13. from .helpers import Error, ErrorWithTraceback, IntegrityError, Location, ProgressIndicatorPercent, bin_to_hex
  14. from .helpers import LIST_SCAN_LIMIT, MAX_OBJECT_SIZE, MAX_DATA_SIZE
  15. from .hashindex import NSIndex
  16. from .locking import Lock, LockError, LockErrorT
  17. from .lrucache import LRUCache
  18. from .platform import sync_dir
  19. MAGIC = b'BORG_SEG'
  20. MAGIC_LEN = len(MAGIC)
  21. TAG_PUT = 0
  22. TAG_DELETE = 1
  23. TAG_COMMIT = 2
  24. class Repository:
  25. """Filesystem based transactional key value store
  26. On disk layout:
  27. dir/README
  28. dir/config
  29. dir/data/<X / SEGMENTS_PER_DIR>/<X>
  30. dir/index.X
  31. dir/hints.X
  32. """
  33. DEFAULT_MAX_SEGMENT_SIZE = 5 * 1024 * 1024
  34. DEFAULT_SEGMENTS_PER_DIR = 10000
  35. class DoesNotExist(Error):
  36. """Repository {} does not exist."""
  37. class AlreadyExists(Error):
  38. """Repository {} already exists."""
  39. class InvalidRepository(Error):
  40. """{} is not a valid repository. Check repo config."""
  41. class CheckNeeded(ErrorWithTraceback):
  42. """Inconsistency detected. Please run "borg check {}"."""
  43. class ObjectNotFound(ErrorWithTraceback):
  44. """Object with key {} not found in repository {}."""
  45. def __init__(self, path, create=False, exclusive=False, lock_wait=None, lock=True, append_only=False):
  46. self.path = os.path.abspath(path)
  47. self._location = Location('file://%s' % self.path)
  48. self.io = None
  49. self.lock = None
  50. self.index = None
  51. self._active_txn = False
  52. self.lock_wait = lock_wait
  53. self.do_lock = lock
  54. self.do_create = create
  55. self.exclusive = exclusive
  56. self.append_only = append_only
  57. def __del__(self):
  58. if self.lock:
  59. self.close()
  60. assert False, "cleanup happened in Repository.__del__"
  61. def __repr__(self):
  62. return '<%s %s>' % (self.__class__.__name__, self.path)
  63. def __enter__(self):
  64. if self.do_create:
  65. self.do_create = False
  66. self.create(self.path)
  67. self.open(self.path, bool(self.exclusive), lock_wait=self.lock_wait, lock=self.do_lock)
  68. return self
  69. def __exit__(self, exc_type, exc_val, exc_tb):
  70. if exc_type is not None:
  71. no_space_left_on_device = exc_type is OSError and exc_val.errno == errno.ENOSPC
  72. # The ENOSPC could have originated somewhere else besides the Repository. The cleanup is always safe, unless
  73. # EIO or FS corruption ensues, which is why we specifically check for ENOSPC.
  74. if self._active_txn and no_space_left_on_device:
  75. logger.warning('No space left on device, cleaning up partial transaction to free space.')
  76. self.io.cleanup(self.io.get_segments_transaction_id())
  77. self.rollback()
  78. self.close()
  79. def create(self, path):
  80. """Create a new empty repository at `path`
  81. """
  82. if os.path.exists(path) and (not os.path.isdir(path) or os.listdir(path)):
  83. raise self.AlreadyExists(path)
  84. if not os.path.exists(path):
  85. os.mkdir(path)
  86. with open(os.path.join(path, 'README'), 'w') as fd:
  87. fd.write('This is a Borg repository\n')
  88. os.mkdir(os.path.join(path, 'data'))
  89. config = ConfigParser(interpolation=None)
  90. config.add_section('repository')
  91. config.set('repository', 'version', '1')
  92. config.set('repository', 'segments_per_dir', str(self.DEFAULT_SEGMENTS_PER_DIR))
  93. config.set('repository', 'max_segment_size', str(self.DEFAULT_MAX_SEGMENT_SIZE))
  94. config.set('repository', 'append_only', str(int(self.append_only)))
  95. config.set('repository', 'id', bin_to_hex(os.urandom(32)))
  96. self.save_config(path, config)
  97. def save_config(self, path, config):
  98. config_path = os.path.join(path, 'config')
  99. with open(config_path, 'w') as fd:
  100. config.write(fd)
  101. def save_key(self, keydata):
  102. assert self.config
  103. keydata = keydata.decode('utf-8') # remote repo: msgpack issue #99, getting bytes
  104. self.config.set('repository', 'key', keydata)
  105. self.save_config(self.path, self.config)
  106. def load_key(self):
  107. keydata = self.config.get('repository', 'key')
  108. return keydata.encode('utf-8') # remote repo: msgpack issue #99, returning bytes
  109. def destroy(self):
  110. """Destroy the repository at `self.path`
  111. """
  112. if self.append_only:
  113. raise ValueError(self.path + " is in append-only mode")
  114. self.close()
  115. os.remove(os.path.join(self.path, 'config')) # kill config first
  116. shutil.rmtree(self.path)
  117. def get_index_transaction_id(self):
  118. indices = sorted(int(fn[6:])
  119. for fn in os.listdir(self.path)
  120. if fn.startswith('index.') and fn[6:].isdigit() and os.stat(os.path.join(self.path, fn)).st_size != 0)
  121. if indices:
  122. return indices[-1]
  123. else:
  124. return None
  125. def get_transaction_id(self):
  126. index_transaction_id = self.get_index_transaction_id()
  127. segments_transaction_id = self.io.get_segments_transaction_id()
  128. if index_transaction_id is not None and segments_transaction_id is None:
  129. # we have a transaction id from the index, but we did not find *any*
  130. # commit in the segment files (thus no segments transaction id).
  131. # this can happen if a lot of segment files are lost, e.g. due to a
  132. # filesystem or hardware malfunction. it means we have no identifiable
  133. # valid (committed) state of the repo which we could use.
  134. msg = '%s" - although likely this is "beyond repair' % self.path # dirty hack
  135. raise self.CheckNeeded(msg)
  136. # Attempt to automatically rebuild index if we crashed between commit
  137. # tag write and index save
  138. if index_transaction_id != segments_transaction_id:
  139. if index_transaction_id is not None and index_transaction_id > segments_transaction_id:
  140. replay_from = None
  141. else:
  142. replay_from = index_transaction_id
  143. self.replay_segments(replay_from, segments_transaction_id)
  144. return self.get_index_transaction_id()
  145. def break_lock(self):
  146. Lock(os.path.join(self.path, 'lock')).break_lock()
  147. def open(self, path, exclusive, lock_wait=None, lock=True):
  148. self.path = path
  149. if not os.path.isdir(path):
  150. raise self.DoesNotExist(path)
  151. if lock:
  152. self.lock = Lock(os.path.join(path, 'lock'), exclusive, timeout=lock_wait).acquire()
  153. else:
  154. self.lock = None
  155. self.config = ConfigParser(interpolation=None)
  156. self.config.read(os.path.join(self.path, 'config'))
  157. if 'repository' not in self.config.sections() or self.config.getint('repository', 'version') != 1:
  158. self.close()
  159. raise self.InvalidRepository(path)
  160. self.max_segment_size = self.config.getint('repository', 'max_segment_size')
  161. self.segments_per_dir = self.config.getint('repository', 'segments_per_dir')
  162. # append_only can be set in the constructor
  163. # it shouldn't be overridden (True -> False) here
  164. self.append_only = self.append_only or self.config.getboolean('repository', 'append_only', fallback=False)
  165. self.id = unhexlify(self.config.get('repository', 'id').strip())
  166. self.io = LoggedIO(self.path, self.max_segment_size, self.segments_per_dir)
  167. def close(self):
  168. if self.lock:
  169. if self.io:
  170. self.io.close()
  171. self.io = None
  172. self.lock.release()
  173. self.lock = None
  174. def commit(self, save_space=False):
  175. """Commit transaction
  176. """
  177. self.io.write_commit()
  178. if not self.append_only:
  179. self.compact_segments(save_space=save_space)
  180. self.write_index()
  181. self.rollback()
  182. def open_index(self, transaction_id):
  183. if transaction_id is None:
  184. return NSIndex()
  185. return NSIndex.read((os.path.join(self.path, 'index.%d') % transaction_id).encode('utf-8'))
  186. def prepare_txn(self, transaction_id, do_cleanup=True):
  187. self._active_txn = True
  188. if not self.lock.got_exclusive_lock():
  189. if self.exclusive is not None:
  190. # self.exclusive is either True or False, thus a new client is active here.
  191. # if it is False and we get here, the caller did not use exclusive=True although
  192. # it is needed for a write operation. if it is True and we get here, something else
  193. # went very wrong, because we should have a exclusive lock, but we don't.
  194. raise AssertionError("bug in code, exclusive lock should exist here")
  195. # if we are here, this is an old client talking to a new server (expecting lock upgrade).
  196. # or we are replaying segments and might need a lock upgrade for that.
  197. try:
  198. self.lock.upgrade()
  199. except (LockError, LockErrorT):
  200. # if upgrading the lock to exclusive fails, we do not have an
  201. # active transaction. this is important for "serve" mode, where
  202. # the repository instance lives on - even if exceptions happened.
  203. self._active_txn = False
  204. raise
  205. if not self.index or transaction_id is None:
  206. self.index = self.open_index(transaction_id)
  207. if transaction_id is None:
  208. self.segments = {} # XXX bad name: usage_count_of_segment_x = self.segments[x]
  209. self.compact = set() # XXX bad name: segments_needing_compaction = self.compact
  210. else:
  211. if do_cleanup:
  212. self.io.cleanup(transaction_id)
  213. with open(os.path.join(self.path, 'hints.%d' % transaction_id), 'rb') as fd:
  214. hints = msgpack.unpack(fd)
  215. hints_version = hints[b'version']
  216. if hints_version not in (1, 2):
  217. raise ValueError('Unknown hints file version: %d' % hints_version)
  218. self.segments = hints[b'segments']
  219. if hints_version == 1:
  220. self.compact = set(hints[b'compact'])
  221. elif hints_version == 2:
  222. self.compact = set(hints[b'compact'].keys())
  223. def write_index(self):
  224. hints = {b'version': 1,
  225. b'segments': self.segments,
  226. b'compact': list(self.compact)}
  227. transaction_id = self.io.get_segments_transaction_id()
  228. assert transaction_id is not None
  229. hints_file = os.path.join(self.path, 'hints.%d' % transaction_id)
  230. with open(hints_file + '.tmp', 'wb') as fd:
  231. msgpack.pack(hints, fd)
  232. fd.flush()
  233. os.fsync(fd.fileno())
  234. os.rename(hints_file + '.tmp', hints_file)
  235. self.index.write(os.path.join(self.path, 'index.tmp'))
  236. os.rename(os.path.join(self.path, 'index.tmp'),
  237. os.path.join(self.path, 'index.%d' % transaction_id))
  238. if self.append_only:
  239. with open(os.path.join(self.path, 'transactions'), 'a') as log:
  240. print('transaction %d, UTC time %s' % (transaction_id, datetime.utcnow().isoformat()), file=log)
  241. # Remove old indices
  242. current = '.%d' % transaction_id
  243. for name in os.listdir(self.path):
  244. if not name.startswith('index.') and not name.startswith('hints.'):
  245. continue
  246. if name.endswith(current):
  247. continue
  248. os.unlink(os.path.join(self.path, name))
  249. self.index = None
  250. def compact_segments(self, save_space=False):
  251. """Compact sparse segments by copying data into new segments
  252. """
  253. if not self.compact:
  254. return
  255. index_transaction_id = self.get_index_transaction_id()
  256. segments = self.segments
  257. unused = [] # list of segments, that are not used anymore
  258. def complete_xfer():
  259. # complete the transfer (usually exactly when some target segment
  260. # is full, or at the very end when everything is processed)
  261. nonlocal unused
  262. # commit the new, compact, used segments
  263. self.io.write_commit()
  264. # get rid of the old, sparse, unused segments. free space.
  265. for segment in unused:
  266. assert self.segments.pop(segment) == 0
  267. self.io.delete_segment(segment)
  268. unused = []
  269. # The first segment compaction creates, if any
  270. first_new_segment = self.io.get_latest_segment() + 1
  271. for segment in sorted(self.compact):
  272. if self.io.segment_exists(segment):
  273. for tag, key, offset, data in self.io.iter_objects(segment, include_data=True):
  274. if tag == TAG_PUT and self.index.get(key, (-1, -1)) == (segment, offset):
  275. try:
  276. new_segment, offset = self.io.write_put(key, data, raise_full=save_space)
  277. except LoggedIO.SegmentFull:
  278. complete_xfer()
  279. new_segment, offset = self.io.write_put(key, data)
  280. self.index[key] = new_segment, offset
  281. segments.setdefault(new_segment, 0)
  282. segments[new_segment] += 1
  283. segments[segment] -= 1
  284. elif tag == TAG_DELETE:
  285. if index_transaction_id is None or segment > index_transaction_id:
  286. # (introduced in 6425d16aa84be1eaaf88)
  287. # This is needed to avoid object un-deletion if we crash between the commit and the deletion
  288. # of old segments in complete_xfer().
  289. #
  290. # However, this only happens if the crash also affects the FS to the effect that file deletions
  291. # did not materialize consistently after journal recovery. If they always materialize in-order
  292. # then this is not a problem, because the old segment containing a deleted object would be deleted
  293. # before the segment containing the delete.
  294. #
  295. # Consider the following series of operations if we would not do this, ie. this entire if:
  296. # would be removed.
  297. # Columns are segments, lines are different keys (line 1 = some key, line 2 = some other key)
  298. # Legend: P=TAG_PUT, D=TAG_DELETE, c=commit, i=index is written for latest commit
  299. #
  300. # Segment | 1 | 2 | 3
  301. # --------+-------+-----+------
  302. # Key 1 | P | D |
  303. # Key 2 | P | | P
  304. # commits | c i | c | c i
  305. # --------+-------+-----+------
  306. # ^- compact_segments starts
  307. # ^- complete_xfer commits, after that complete_xfer deletes
  308. # segments 1 and 2 (and then the index would be written).
  309. #
  310. # Now we crash. But only segment 2 gets deleted, while segment 1 is still around. Now key 1
  311. # is suddenly undeleted (because the delete in segment 2 is now missing).
  312. # Again, note the requirement here. We delete these in the correct order that this doesn't happen,
  313. # and only if the FS materialization of these deletes is reordered or parts dropped this can happen.
  314. # In this case it doesn't cause outright corruption, 'just' an index count mismatch, which will be
  315. # fixed by borg-check --repair.
  316. #
  317. # Note that in this check the index state is the proxy for a "most definitely settled" repository state,
  318. # ie. the assumption is that *all* operations on segments <= index state are completed and stable.
  319. try:
  320. new_segment = self.io.write_delete(key, raise_full=save_space)
  321. except LoggedIO.SegmentFull:
  322. complete_xfer()
  323. new_segment = self.io.write_delete(key)
  324. self.compact.add(new_segment)
  325. self.segments.setdefault(new_segment, 0)
  326. assert segments[segment] == 0
  327. unused.append(segment)
  328. complete_xfer()
  329. # Moving of deletes creates new sparse segments, only store these. All other segments
  330. # are compact now.
  331. self.compact = {segment for segment in self.compact if segment >= first_new_segment}
  332. def replay_segments(self, index_transaction_id, segments_transaction_id):
  333. # fake an old client, so that in case we do not have an exclusive lock yet, prepare_txn will upgrade the lock:
  334. remember_exclusive = self.exclusive
  335. self.exclusive = None
  336. self.prepare_txn(index_transaction_id, do_cleanup=False)
  337. try:
  338. segment_count = sum(1 for _ in self.io.segment_iterator())
  339. pi = ProgressIndicatorPercent(total=segment_count, msg="Replaying segments %3.0f%%", same_line=True)
  340. for i, (segment, filename) in enumerate(self.io.segment_iterator()):
  341. pi.show(i)
  342. if index_transaction_id is not None and segment <= index_transaction_id:
  343. continue
  344. if segment > segments_transaction_id:
  345. break
  346. objects = self.io.iter_objects(segment)
  347. self._update_index(segment, objects)
  348. pi.finish()
  349. self.write_index()
  350. finally:
  351. self.exclusive = remember_exclusive
  352. self.rollback()
  353. def _update_index(self, segment, objects, report=None):
  354. """some code shared between replay_segments and check"""
  355. self.segments[segment] = 0
  356. for tag, key, offset in objects:
  357. if tag == TAG_PUT:
  358. try:
  359. s, _ = self.index[key]
  360. self.compact.add(s)
  361. self.segments[s] -= 1
  362. except KeyError:
  363. pass
  364. self.index[key] = segment, offset
  365. self.segments[segment] += 1
  366. elif tag == TAG_DELETE:
  367. try:
  368. s, _ = self.index.pop(key)
  369. self.segments[s] -= 1
  370. self.compact.add(s)
  371. except KeyError:
  372. pass
  373. self.compact.add(segment)
  374. elif tag == TAG_COMMIT:
  375. continue
  376. else:
  377. msg = 'Unexpected tag {} in segment {}'.format(tag, segment)
  378. if report is None:
  379. raise self.CheckNeeded(msg)
  380. else:
  381. report(msg)
  382. if self.segments[segment] == 0:
  383. self.compact.add(segment)
  384. def check(self, repair=False, save_space=False):
  385. """Check repository consistency
  386. This method verifies all segment checksums and makes sure
  387. the index is consistent with the data stored in the segments.
  388. """
  389. if self.append_only and repair:
  390. raise ValueError(self.path + " is in append-only mode")
  391. error_found = False
  392. def report_error(msg):
  393. nonlocal error_found
  394. error_found = True
  395. logger.error(msg)
  396. logger.info('Starting repository check')
  397. assert not self._active_txn
  398. try:
  399. transaction_id = self.get_transaction_id()
  400. current_index = self.open_index(transaction_id)
  401. except Exception:
  402. transaction_id = self.io.get_segments_transaction_id()
  403. current_index = None
  404. if transaction_id is None:
  405. transaction_id = self.get_index_transaction_id()
  406. if transaction_id is None:
  407. transaction_id = self.io.get_latest_segment()
  408. if transaction_id is None:
  409. report_error('This repository contains no valid data.')
  410. return False
  411. if repair:
  412. self.io.cleanup(transaction_id)
  413. segments_transaction_id = self.io.get_segments_transaction_id()
  414. self.prepare_txn(None) # self.index, self.compact, self.segments all empty now!
  415. segment_count = sum(1 for _ in self.io.segment_iterator())
  416. pi = ProgressIndicatorPercent(total=segment_count, msg="Checking segments %3.1f%%", step=0.1, same_line=True)
  417. for i, (segment, filename) in enumerate(self.io.segment_iterator()):
  418. pi.show(i)
  419. if segment > transaction_id:
  420. continue
  421. try:
  422. objects = list(self.io.iter_objects(segment))
  423. except IntegrityError as err:
  424. report_error(str(err))
  425. objects = []
  426. if repair:
  427. self.io.recover_segment(segment, filename)
  428. objects = list(self.io.iter_objects(segment))
  429. self._update_index(segment, objects, report_error)
  430. pi.finish()
  431. # self.index, self.segments, self.compact now reflect the state of the segment files up to <transaction_id>
  432. # We might need to add a commit tag if no committed segment is found
  433. if repair and segments_transaction_id is None:
  434. report_error('Adding commit tag to segment {}'.format(transaction_id))
  435. self.io.segment = transaction_id + 1
  436. self.io.write_commit()
  437. if current_index and not repair:
  438. # current_index = "as found on disk"
  439. # self.index = "as rebuilt in-memory from segments"
  440. if len(current_index) != len(self.index):
  441. report_error('Index object count mismatch. {} != {}'.format(len(current_index), len(self.index)))
  442. elif current_index:
  443. for key, value in self.index.iteritems():
  444. if current_index.get(key, (-1, -1)) != value:
  445. report_error('Index mismatch for key {}. {} != {}'.format(key, value, current_index.get(key, (-1, -1))))
  446. if repair:
  447. self.compact_segments(save_space=save_space)
  448. self.write_index()
  449. self.rollback()
  450. if error_found:
  451. if repair:
  452. logger.info('Completed repository check, errors found and repaired.')
  453. else:
  454. logger.error('Completed repository check, errors found.')
  455. else:
  456. logger.info('Completed repository check, no problems found.')
  457. return not error_found or repair
  458. def rollback(self):
  459. """
  460. """
  461. self.index = None
  462. self._active_txn = False
  463. def __len__(self):
  464. if not self.index:
  465. self.index = self.open_index(self.get_transaction_id())
  466. return len(self.index)
  467. def __contains__(self, id):
  468. if not self.index:
  469. self.index = self.open_index(self.get_transaction_id())
  470. return id in self.index
  471. def list(self, limit=None, marker=None):
  472. if not self.index:
  473. self.index = self.open_index(self.get_transaction_id())
  474. return [id_ for id_, _ in islice(self.index.iteritems(marker=marker), limit)]
  475. def get(self, id_):
  476. if not self.index:
  477. self.index = self.open_index(self.get_transaction_id())
  478. try:
  479. segment, offset = self.index[id_]
  480. return self.io.read(segment, offset, id_)
  481. except KeyError:
  482. raise self.ObjectNotFound(id_, self.path) from None
  483. def get_many(self, ids, is_preloaded=False):
  484. for id_ in ids:
  485. yield self.get(id_)
  486. def put(self, id, data, wait=True):
  487. if not self._active_txn:
  488. self.prepare_txn(self.get_transaction_id())
  489. try:
  490. segment, _ = self.index[id]
  491. self.segments[segment] -= 1
  492. self.compact.add(segment)
  493. segment = self.io.write_delete(id)
  494. self.segments.setdefault(segment, 0)
  495. self.compact.add(segment)
  496. except KeyError:
  497. pass
  498. segment, offset = self.io.write_put(id, data)
  499. self.segments.setdefault(segment, 0)
  500. self.segments[segment] += 1
  501. self.index[id] = segment, offset
  502. def delete(self, id, wait=True):
  503. if not self._active_txn:
  504. self.prepare_txn(self.get_transaction_id())
  505. try:
  506. segment, offset = self.index.pop(id)
  507. except KeyError:
  508. raise self.ObjectNotFound(id, self.path) from None
  509. self.segments[segment] -= 1
  510. self.compact.add(segment)
  511. segment = self.io.write_delete(id)
  512. self.compact.add(segment)
  513. self.segments.setdefault(segment, 0)
  514. def preload(self, ids):
  515. """Preload objects (only applies to remote repositories)
  516. """
  517. class LoggedIO:
  518. class SegmentFull(Exception):
  519. """raised when a segment is full, before opening next"""
  520. header_fmt = struct.Struct('<IIB')
  521. assert header_fmt.size == 9
  522. put_header_fmt = struct.Struct('<IIB32s')
  523. assert put_header_fmt.size == 41
  524. header_no_crc_fmt = struct.Struct('<IB')
  525. assert header_no_crc_fmt.size == 5
  526. crc_fmt = struct.Struct('<I')
  527. assert crc_fmt.size == 4
  528. _commit = header_no_crc_fmt.pack(9, TAG_COMMIT)
  529. COMMIT = crc_fmt.pack(crc32(_commit)) + _commit
  530. def __init__(self, path, limit, segments_per_dir, capacity=90):
  531. self.path = path
  532. self.fds = LRUCache(capacity,
  533. dispose=lambda fd: fd.close())
  534. self.segment = 0
  535. self.limit = limit
  536. self.segments_per_dir = segments_per_dir
  537. self.offset = 0
  538. self._write_fd = None
  539. def close(self):
  540. self.close_segment()
  541. self.fds.clear()
  542. self.fds = None # Just to make sure we're disabled
  543. def segment_iterator(self, reverse=False):
  544. data_path = os.path.join(self.path, 'data')
  545. dirs = sorted((dir for dir in os.listdir(data_path) if dir.isdigit()), key=int, reverse=reverse)
  546. for dir in dirs:
  547. filenames = os.listdir(os.path.join(data_path, dir))
  548. sorted_filenames = sorted((filename for filename in filenames
  549. if filename.isdigit()), key=int, reverse=reverse)
  550. for filename in sorted_filenames:
  551. yield int(filename), os.path.join(data_path, dir, filename)
  552. def get_latest_segment(self):
  553. for segment, filename in self.segment_iterator(reverse=True):
  554. return segment
  555. return None
  556. def get_segments_transaction_id(self):
  557. """Return last committed segment
  558. """
  559. for segment, filename in self.segment_iterator(reverse=True):
  560. if self.is_committed_segment(segment):
  561. return segment
  562. return None
  563. def cleanup(self, transaction_id):
  564. """Delete segment files left by aborted transactions
  565. """
  566. self.segment = transaction_id + 1
  567. for segment, filename in self.segment_iterator(reverse=True):
  568. if segment > transaction_id:
  569. os.unlink(filename)
  570. else:
  571. break
  572. def is_committed_segment(self, segment):
  573. """Check if segment ends with a COMMIT_TAG tag
  574. """
  575. try:
  576. iterator = self.iter_objects(segment)
  577. except IntegrityError:
  578. return False
  579. with open(self.segment_filename(segment), 'rb') as fd:
  580. try:
  581. fd.seek(-self.header_fmt.size, os.SEEK_END)
  582. except OSError as e:
  583. # return False if segment file is empty or too small
  584. if e.errno == errno.EINVAL:
  585. return False
  586. raise e
  587. if fd.read(self.header_fmt.size) != self.COMMIT:
  588. return False
  589. seen_commit = False
  590. while True:
  591. try:
  592. tag, key, offset = next(iterator)
  593. except IntegrityError:
  594. return False
  595. except StopIteration:
  596. break
  597. if tag == TAG_COMMIT:
  598. seen_commit = True
  599. continue
  600. if seen_commit:
  601. return False
  602. return seen_commit
  603. def segment_filename(self, segment):
  604. return os.path.join(self.path, 'data', str(segment // self.segments_per_dir), str(segment))
  605. def get_write_fd(self, no_new=False, raise_full=False):
  606. if not no_new and self.offset and self.offset > self.limit:
  607. if raise_full:
  608. raise self.SegmentFull
  609. self.close_segment()
  610. if not self._write_fd:
  611. if self.segment % self.segments_per_dir == 0:
  612. dirname = os.path.join(self.path, 'data', str(self.segment // self.segments_per_dir))
  613. if not os.path.exists(dirname):
  614. os.mkdir(dirname)
  615. sync_dir(os.path.join(self.path, 'data'))
  616. # play safe: fail if file exists (do not overwrite existing contents, do not append)
  617. self._write_fd = open(self.segment_filename(self.segment), 'xb')
  618. self._write_fd.write(MAGIC)
  619. self.offset = MAGIC_LEN
  620. return self._write_fd
  621. def get_fd(self, segment):
  622. try:
  623. return self.fds[segment]
  624. except KeyError:
  625. fd = open(self.segment_filename(segment), 'rb')
  626. self.fds[segment] = fd
  627. return fd
  628. def delete_segment(self, segment):
  629. if segment in self.fds:
  630. del self.fds[segment]
  631. try:
  632. os.unlink(self.segment_filename(segment))
  633. except FileNotFoundError:
  634. pass
  635. def segment_exists(self, segment):
  636. return os.path.exists(self.segment_filename(segment))
  637. def iter_objects(self, segment, include_data=False):
  638. fd = self.get_fd(segment)
  639. fd.seek(0)
  640. if fd.read(MAGIC_LEN) != MAGIC:
  641. raise IntegrityError('Invalid segment magic [segment {}, offset {}]'.format(segment, 0))
  642. offset = MAGIC_LEN
  643. header = fd.read(self.header_fmt.size)
  644. while header:
  645. size, tag, key, data = self._read(fd, self.header_fmt, header, segment, offset,
  646. (TAG_PUT, TAG_DELETE, TAG_COMMIT))
  647. if include_data:
  648. yield tag, key, offset, data
  649. else:
  650. yield tag, key, offset
  651. offset += size
  652. # we must get the fd via get_fd() here again as we yielded to our caller and it might
  653. # have triggered closing of the fd we had before (e.g. by calling io.read() for
  654. # different segment(s)).
  655. # by calling get_fd() here again we also make our fd "recently used" so it likely
  656. # does not get kicked out of self.fds LRUcache.
  657. fd = self.get_fd(segment)
  658. fd.seek(offset)
  659. header = fd.read(self.header_fmt.size)
  660. def recover_segment(self, segment, filename):
  661. if segment in self.fds:
  662. del self.fds[segment]
  663. with open(filename, 'rb') as fd:
  664. data = memoryview(fd.read())
  665. os.rename(filename, filename + '.beforerecover')
  666. logger.info('attempting to recover ' + filename)
  667. with open(filename, 'wb') as fd:
  668. fd.write(MAGIC)
  669. while len(data) >= self.header_fmt.size:
  670. crc, size, tag = self.header_fmt.unpack(data[:self.header_fmt.size])
  671. if size < self.header_fmt.size or size > len(data):
  672. data = data[1:]
  673. continue
  674. if crc32(data[4:size]) & 0xffffffff != crc:
  675. data = data[1:]
  676. continue
  677. fd.write(data[:size])
  678. data = data[size:]
  679. def read(self, segment, offset, id):
  680. if segment == self.segment and self._write_fd:
  681. self._write_fd.flush()
  682. fd = self.get_fd(segment)
  683. fd.seek(offset)
  684. header = fd.read(self.put_header_fmt.size)
  685. size, tag, key, data = self._read(fd, self.put_header_fmt, header, segment, offset, (TAG_PUT, ))
  686. if id != key:
  687. raise IntegrityError('Invalid segment entry header, is not for wanted id [segment {}, offset {}]'.format(
  688. segment, offset))
  689. return data
  690. def _read(self, fd, fmt, header, segment, offset, acceptable_tags):
  691. # some code shared by read() and iter_objects()
  692. try:
  693. hdr_tuple = fmt.unpack(header)
  694. except struct.error as err:
  695. raise IntegrityError('Invalid segment entry header [segment {}, offset {}]: {}'.format(
  696. segment, offset, err)) from None
  697. if fmt is self.put_header_fmt:
  698. crc, size, tag, key = hdr_tuple
  699. elif fmt is self.header_fmt:
  700. crc, size, tag = hdr_tuple
  701. key = None
  702. else:
  703. raise TypeError("_read called with unsupported format")
  704. if size > MAX_OBJECT_SIZE:
  705. # if you get this on an archive made with borg < 1.0.7 and millions of files and
  706. # you need to restore it, you can disable this check by using "if False:" above.
  707. raise IntegrityError('Invalid segment entry size {} - too big [segment {}, offset {}]'.format(
  708. size, segment, offset))
  709. if size < fmt.size:
  710. raise IntegrityError('Invalid segment entry size {} - too small [segment {}, offset {}]'.format(
  711. size, segment, offset))
  712. length = size - fmt.size
  713. data = fd.read(length)
  714. if len(data) != length:
  715. raise IntegrityError('Segment entry data short read [segment {}, offset {}]: expected {}, got {} bytes'.format(
  716. segment, offset, length, len(data)))
  717. if crc32(data, crc32(memoryview(header)[4:])) & 0xffffffff != crc:
  718. raise IntegrityError('Segment entry checksum mismatch [segment {}, offset {}]'.format(
  719. segment, offset))
  720. if tag not in acceptable_tags:
  721. raise IntegrityError('Invalid segment entry header, did not get acceptable tag [segment {}, offset {}]'.format(
  722. segment, offset))
  723. if key is None and tag in (TAG_PUT, TAG_DELETE):
  724. key, data = data[:32], data[32:]
  725. return size, tag, key, data
  726. def write_put(self, id, data, raise_full=False):
  727. data_size = len(data)
  728. if data_size > MAX_DATA_SIZE:
  729. # this would push the segment entry size beyond MAX_OBJECT_SIZE.
  730. raise IntegrityError('More than allowed put data [{} > {}]'.format(data_size, MAX_DATA_SIZE))
  731. fd = self.get_write_fd(raise_full=raise_full)
  732. size = data_size + self.put_header_fmt.size
  733. offset = self.offset
  734. header = self.header_no_crc_fmt.pack(size, TAG_PUT)
  735. crc = self.crc_fmt.pack(crc32(data, crc32(id, crc32(header))) & 0xffffffff)
  736. fd.write(b''.join((crc, header, id, data)))
  737. self.offset += size
  738. return self.segment, offset
  739. def write_delete(self, id, raise_full=False):
  740. fd = self.get_write_fd(raise_full=raise_full)
  741. header = self.header_no_crc_fmt.pack(self.put_header_fmt.size, TAG_DELETE)
  742. crc = self.crc_fmt.pack(crc32(id, crc32(header)) & 0xffffffff)
  743. fd.write(b''.join((crc, header, id)))
  744. self.offset += self.put_header_fmt.size
  745. return self.segment
  746. def write_commit(self):
  747. fd = self.get_write_fd(no_new=True)
  748. header = self.header_no_crc_fmt.pack(self.header_fmt.size, TAG_COMMIT)
  749. crc = self.crc_fmt.pack(crc32(header) & 0xffffffff)
  750. # first fsync(fd) here (to ensure data supposedly hits the disk before the commit tag)
  751. fd.flush()
  752. os.fsync(fd.fileno())
  753. fd.write(b''.join((crc, header)))
  754. self.close_segment() # after-commit fsync()
  755. def close_segment(self):
  756. # set self._write_fd to None early to guard against reentry from error handling code pathes:
  757. fd, self._write_fd = self._write_fd, None
  758. if fd is not None:
  759. dirname = None
  760. try:
  761. self.segment += 1
  762. self.offset = 0
  763. dirname = os.path.dirname(fd.name)
  764. fd.flush()
  765. fileno = fd.fileno()
  766. os.fsync(fileno)
  767. if hasattr(os, 'posix_fadvise'): # only on UNIX
  768. try:
  769. # tell the OS that it does not need to cache what we just wrote,
  770. # avoids spoiling the cache for the OS and other processes.
  771. os.posix_fadvise(fileno, 0, 0, os.POSIX_FADV_DONTNEED)
  772. except OSError:
  773. # usually, posix_fadvise can't fail for us, but there seem to
  774. # be failures when running borg under docker on ARM, likely due
  775. # to a bug outside of borg.
  776. # also, there is a python wrapper bug, always giving errno = 0.
  777. # https://github.com/borgbackup/borg/issues/2095
  778. # as this call is not critical for correct function (just to
  779. # optimize cache usage), we ignore these errors.
  780. pass
  781. finally:
  782. fd.close()
  783. if dirname:
  784. sync_dir(dirname)
  785. assert LoggedIO.put_header_fmt.size == 41 # see helpers.MAX_OBJECT_SIZE