repository.py 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529
  1. import errno
  2. import mmap
  3. import os
  4. import shutil
  5. import struct
  6. import time
  7. from binascii import hexlify, unhexlify
  8. from collections import defaultdict
  9. from configparser import ConfigParser
  10. from datetime import datetime
  11. from functools import partial
  12. from itertools import islice
  13. from .constants import * # NOQA
  14. from .hashindex import NSIndex
  15. from .helpers import Error, ErrorWithTraceback, IntegrityError, format_file_size, parse_file_size
  16. from .helpers import Location
  17. from .helpers import ProgressIndicatorPercent
  18. from .helpers import bin_to_hex
  19. from .helpers import hostname_is_unique
  20. from .helpers import secure_erase, truncate_and_unlink
  21. from .helpers import Manifest
  22. from .helpers import msgpack
  23. from .locking import Lock, LockError, LockErrorT
  24. from .logger import create_logger
  25. from .lrucache import LRUCache
  26. from .platform import SaveFile, SyncFile, sync_dir, safe_fadvise
  27. from .algorithms.checksums import crc32
  28. from .crypto.file_integrity import IntegrityCheckedFile, FileIntegrityError
  29. logger = create_logger(__name__)
  30. MAGIC = b'BORG_SEG'
  31. MAGIC_LEN = len(MAGIC)
  32. ATTIC_MAGIC = b'ATTICSEG'
  33. assert len(ATTIC_MAGIC) == MAGIC_LEN
  34. TAG_PUT = 0
  35. TAG_DELETE = 1
  36. TAG_COMMIT = 2
  37. FreeSpace = partial(defaultdict, int)
  38. class Repository:
  39. """
  40. Filesystem based transactional key value store
  41. Transactionality is achieved by using a log (aka journal) to record changes. The log is a series of numbered files
  42. called segments. Each segment is a series of log entries. The segment number together with the offset of each
  43. entry relative to its segment start establishes an ordering of the log entries. This is the "definition" of
  44. time for the purposes of the log.
  45. Log entries are either PUT, DELETE or COMMIT.
  46. A COMMIT is always the final log entry in a segment and marks all data from the beginning of the log until the
  47. segment ending with the COMMIT as committed and consistent. The segment number of a segment ending with a COMMIT
  48. is called the transaction ID of that commit, and a segment ending with a COMMIT is called committed.
  49. When reading from a repository it is first checked whether the last segment is committed. If it is not, then
  50. all segments after the last committed segment are deleted; they contain log entries whose consistency is not
  51. established by a COMMIT.
  52. Note that the COMMIT can't establish consistency by itself, but only manages to do so with proper support from
  53. the platform (including the hardware). See platform.base.SyncFile for details.
  54. A PUT inserts a key-value pair. The value is stored in the log entry, hence the repository implements
  55. full data logging, meaning that all data is consistent, not just metadata (which is common in file systems).
  56. A DELETE marks a key as deleted.
  57. For a given key only the last entry regarding the key, which is called current (all other entries are called
  58. superseded), is relevant: If there is no entry or the last entry is a DELETE then the key does not exist.
  59. Otherwise the last PUT defines the value of the key.
  60. By superseding a PUT (with either another PUT or a DELETE) the log entry becomes obsolete. A segment containing
  61. such obsolete entries is called sparse, while a segment containing no such entries is called compact.
  62. Sparse segments can be compacted and thereby disk space freed. This destroys the transaction for which the
  63. superseded entries where current.
  64. On disk layout:
  65. dir/README
  66. dir/config
  67. dir/data/<X // SEGMENTS_PER_DIR>/<X>
  68. dir/index.X
  69. dir/hints.X
  70. File system interaction
  71. -----------------------
  72. LoggedIO generally tries to rely on common behaviours across transactional file systems.
  73. Segments that are deleted are truncated first, which avoids problems if the FS needs to
  74. allocate space to delete the dirent of the segment. This mostly affects CoW file systems,
  75. traditional journaling file systems have a fairly good grip on this problem.
  76. Note that deletion, i.e. unlink(2), is atomic on every file system that uses inode reference
  77. counts, which includes pretty much all of them. To remove a dirent the inodes refcount has
  78. to be decreased, but you can't decrease the refcount before removing the dirent nor can you
  79. decrease the refcount after removing the dirent. File systems solve this with a lock,
  80. and by ensuring it all stays within the same FS transaction.
  81. Truncation is generally not atomic in itself, and combining truncate(2) and unlink(2) is of
  82. course never guaranteed to be atomic. Truncation in a classic extent-based FS is done in
  83. roughly two phases, first the extents are removed then the inode is updated. (In practice
  84. this is of course way more complex).
  85. LoggedIO gracefully handles truncate/unlink splits as long as the truncate resulted in
  86. a zero length file. Zero length segments are considered to not exist, while LoggedIO.cleanup()
  87. will still get rid of them.
  88. """
  89. class DoesNotExist(Error):
  90. """Repository {} does not exist."""
  91. class AlreadyExists(Error):
  92. """A repository already exists at {}."""
  93. class PathAlreadyExists(Error):
  94. """There is already something at {}."""
  95. class InvalidRepository(Error):
  96. """{} is not a valid repository. Check repo config."""
  97. class InvalidRepositoryConfig(Error):
  98. """{} does not have a valid configuration. Check repo config [{}]."""
  99. class AtticRepository(Error):
  100. """Attic repository detected. Please run "borg upgrade {}"."""
  101. class CheckNeeded(ErrorWithTraceback):
  102. """Inconsistency detected. Please run "borg check {}"."""
  103. class ObjectNotFound(ErrorWithTraceback):
  104. """Object with key {} not found in repository {}."""
  105. def __init__(self, id, repo):
  106. if isinstance(id, bytes):
  107. id = bin_to_hex(id)
  108. super().__init__(id, repo)
  109. class InsufficientFreeSpaceError(Error):
  110. """Insufficient free space to complete transaction (required: {}, available: {})."""
  111. class StorageQuotaExceeded(Error):
  112. """The storage quota ({}) has been exceeded ({}). Try deleting some archives."""
  113. def __init__(self, path, create=False, exclusive=False, lock_wait=None, lock=True,
  114. append_only=False, storage_quota=None, check_segment_magic=True):
  115. self.path = os.path.abspath(path)
  116. self._location = Location('file://%s' % self.path)
  117. self.io = None # type: LoggedIO
  118. self.lock = None
  119. self.index = None
  120. # This is an index of shadowed log entries during this transaction. Consider the following sequence:
  121. # segment_n PUT A, segment_x DELETE A
  122. # After the "DELETE A" in segment_x the shadow index will contain "A -> [n]".
  123. self.shadow_index = {}
  124. self._active_txn = False
  125. self.lock_wait = lock_wait
  126. self.do_lock = lock
  127. self.do_create = create
  128. self.created = False
  129. self.exclusive = exclusive
  130. self.append_only = append_only
  131. self.storage_quota = storage_quota
  132. self.storage_quota_use = 0
  133. self.transaction_doomed = None
  134. self.check_segment_magic = check_segment_magic
  135. def __del__(self):
  136. if self.lock:
  137. self.close()
  138. assert False, "cleanup happened in Repository.__del__"
  139. def __repr__(self):
  140. return '<%s %s>' % (self.__class__.__name__, self.path)
  141. def __enter__(self):
  142. if self.do_create:
  143. self.do_create = False
  144. self.create(self.path)
  145. self.created = True
  146. self.open(self.path, bool(self.exclusive), lock_wait=self.lock_wait, lock=self.do_lock)
  147. return self
  148. def __exit__(self, exc_type, exc_val, exc_tb):
  149. if exc_type is not None:
  150. no_space_left_on_device = exc_type is OSError and exc_val.errno == errno.ENOSPC
  151. # The ENOSPC could have originated somewhere else besides the Repository. The cleanup is always safe, unless
  152. # EIO or FS corruption ensues, which is why we specifically check for ENOSPC.
  153. if self._active_txn and no_space_left_on_device:
  154. logger.warning('No space left on device, cleaning up partial transaction to free space.')
  155. cleanup = True
  156. else:
  157. cleanup = False
  158. self._rollback(cleanup=cleanup)
  159. self.close()
  160. @property
  161. def id_str(self):
  162. return bin_to_hex(self.id)
  163. @staticmethod
  164. def is_repository(path):
  165. """Check whether there is already a Borg repository at *path*."""
  166. try:
  167. # Use binary mode to avoid troubles if a README contains some stuff not in our locale
  168. with open(os.path.join(path, 'README'), 'rb') as fd:
  169. # Read only the first ~100 bytes (if any), in case some README file we stumble upon is large.
  170. readme_head = fd.read(100)
  171. # The first comparison captures our current variant (REPOSITORY_README), the second comparison
  172. # is an older variant of the README file (used by 1.0.x).
  173. return b'Borg Backup repository' in readme_head or b'Borg repository' in readme_head
  174. except OSError:
  175. # Ignore FileNotFound, PermissionError, ...
  176. return False
  177. def check_can_create_repository(self, path):
  178. """
  179. Raise an exception if a repository already exists at *path* or any parent directory.
  180. Checking parent directories is done for two reasons:
  181. (1) It's just a weird thing to do, and usually not intended. A Borg using the "parent" repository
  182. may be confused, or we may accidentally put stuff into the "data/" or "data/<n>/" directories.
  183. (2) When implementing repository quotas (which we currently don't), it's important to prohibit
  184. folks from creating quota-free repositories. Since no one can create a repository within another
  185. repository, user's can only use the quota'd repository, when their --restrict-to-path points
  186. at the user's repository.
  187. """
  188. if os.path.exists(path):
  189. if self.is_repository(path):
  190. raise self.AlreadyExists(path)
  191. if not os.path.isdir(path) or os.listdir(path):
  192. raise self.PathAlreadyExists(path)
  193. while True:
  194. # Check all parent directories for Borg's repository README
  195. previous_path = path
  196. # Thus, path = previous_path/..
  197. path = os.path.abspath(os.path.join(previous_path, os.pardir))
  198. if path == previous_path:
  199. # We reached the root of the directory hierarchy (/.. = / and C:\.. = C:\).
  200. break
  201. if self.is_repository(path):
  202. raise self.AlreadyExists(path)
  203. def create(self, path):
  204. """Create a new empty repository at `path`
  205. """
  206. self.check_can_create_repository(path)
  207. if not os.path.exists(path):
  208. os.mkdir(path)
  209. with open(os.path.join(path, 'README'), 'w') as fd:
  210. fd.write(REPOSITORY_README)
  211. os.mkdir(os.path.join(path, 'data'))
  212. config = ConfigParser(interpolation=None)
  213. config.add_section('repository')
  214. config.set('repository', 'version', '1')
  215. config.set('repository', 'segments_per_dir', str(DEFAULT_SEGMENTS_PER_DIR))
  216. config.set('repository', 'max_segment_size', str(DEFAULT_MAX_SEGMENT_SIZE))
  217. config.set('repository', 'append_only', str(int(self.append_only)))
  218. if self.storage_quota:
  219. config.set('repository', 'storage_quota', str(self.storage_quota))
  220. else:
  221. config.set('repository', 'storage_quota', '0')
  222. config.set('repository', 'additional_free_space', '0')
  223. config.set('repository', 'id', bin_to_hex(os.urandom(32)))
  224. self.save_config(path, config)
  225. def save_config(self, path, config):
  226. config_path = os.path.join(path, 'config')
  227. old_config_path = os.path.join(path, 'config.old')
  228. if os.path.isfile(old_config_path):
  229. logger.warning("Old config file not securely erased on previous config update")
  230. secure_erase(old_config_path)
  231. if os.path.isfile(config_path):
  232. try:
  233. os.link(config_path, old_config_path)
  234. except OSError as e:
  235. if e.errno in (errno.EMLINK, errno.ENOSYS, errno.EPERM, errno.ENOTSUP):
  236. logger.warning("Failed to securely erase old repository config file (hardlinks not supported>). "
  237. "Old repokey data, if any, might persist on physical storage.")
  238. else:
  239. raise
  240. with SaveFile(config_path) as fd:
  241. config.write(fd)
  242. if os.path.isfile(old_config_path):
  243. secure_erase(old_config_path)
  244. def save_key(self, keydata):
  245. assert self.config
  246. keydata = keydata.decode('utf-8') # remote repo: msgpack issue #99, getting bytes
  247. self.config.set('repository', 'key', keydata)
  248. self.save_config(self.path, self.config)
  249. def load_key(self):
  250. keydata = self.config.get('repository', 'key')
  251. return keydata.encode('utf-8') # remote repo: msgpack issue #99, returning bytes
  252. def get_free_nonce(self):
  253. if not self.lock.got_exclusive_lock():
  254. raise AssertionError("bug in code, exclusive lock should exist here")
  255. nonce_path = os.path.join(self.path, 'nonce')
  256. try:
  257. with open(nonce_path, 'r') as fd:
  258. return int.from_bytes(unhexlify(fd.read()), byteorder='big')
  259. except FileNotFoundError:
  260. return None
  261. def commit_nonce_reservation(self, next_unreserved, start_nonce):
  262. if not self.lock.got_exclusive_lock():
  263. raise AssertionError("bug in code, exclusive lock should exist here")
  264. if self.get_free_nonce() != start_nonce:
  265. raise Exception("nonce space reservation with mismatched previous state")
  266. nonce_path = os.path.join(self.path, 'nonce')
  267. with SaveFile(nonce_path, binary=False) as fd:
  268. fd.write(bin_to_hex(next_unreserved.to_bytes(8, byteorder='big')))
  269. def destroy(self):
  270. """Destroy the repository at `self.path`
  271. """
  272. if self.append_only:
  273. raise ValueError(self.path + " is in append-only mode")
  274. self.close()
  275. os.remove(os.path.join(self.path, 'config')) # kill config first
  276. shutil.rmtree(self.path)
  277. def get_index_transaction_id(self):
  278. indices = sorted(int(fn[6:])
  279. for fn in os.listdir(self.path)
  280. if fn.startswith('index.') and fn[6:].isdigit() and os.stat(os.path.join(self.path, fn)).st_size != 0)
  281. if indices:
  282. return indices[-1]
  283. else:
  284. return None
  285. def check_transaction(self):
  286. index_transaction_id = self.get_index_transaction_id()
  287. segments_transaction_id = self.io.get_segments_transaction_id()
  288. if index_transaction_id is not None and segments_transaction_id is None:
  289. # we have a transaction id from the index, but we did not find *any*
  290. # commit in the segment files (thus no segments transaction id).
  291. # this can happen if a lot of segment files are lost, e.g. due to a
  292. # filesystem or hardware malfunction. it means we have no identifiable
  293. # valid (committed) state of the repo which we could use.
  294. msg = '%s" - although likely this is "beyond repair' % self.path # dirty hack
  295. raise self.CheckNeeded(msg)
  296. # Attempt to automatically rebuild index if we crashed between commit
  297. # tag write and index save
  298. if index_transaction_id != segments_transaction_id:
  299. if index_transaction_id is not None and index_transaction_id > segments_transaction_id:
  300. replay_from = None
  301. else:
  302. replay_from = index_transaction_id
  303. self.replay_segments(replay_from, segments_transaction_id)
  304. def get_transaction_id(self):
  305. self.check_transaction()
  306. return self.get_index_transaction_id()
  307. def break_lock(self):
  308. Lock(os.path.join(self.path, 'lock')).break_lock()
  309. def migrate_lock(self, old_id, new_id):
  310. # note: only needed for local repos
  311. if self.lock is not None:
  312. self.lock.migrate_lock(old_id, new_id)
  313. def open(self, path, exclusive, lock_wait=None, lock=True):
  314. self.path = path
  315. if not os.path.isdir(path):
  316. raise self.DoesNotExist(path)
  317. if lock:
  318. self.lock = Lock(os.path.join(path, 'lock'), exclusive, timeout=lock_wait, kill_stale_locks=hostname_is_unique()).acquire()
  319. else:
  320. self.lock = None
  321. self.config = ConfigParser(interpolation=None)
  322. with open(os.path.join(self.path, 'config')) as fd:
  323. self.config.read_file(fd)
  324. if 'repository' not in self.config.sections() or self.config.getint('repository', 'version') != 1:
  325. self.close()
  326. raise self.InvalidRepository(path)
  327. self.max_segment_size = self.config.getint('repository', 'max_segment_size')
  328. if self.max_segment_size >= MAX_SEGMENT_SIZE_LIMIT:
  329. self.close()
  330. raise self.InvalidRepositoryConfig(path, 'max_segment_size >= %d' % MAX_SEGMENT_SIZE_LIMIT) # issue 3592
  331. self.segments_per_dir = self.config.getint('repository', 'segments_per_dir')
  332. self.additional_free_space = parse_file_size(self.config.get('repository', 'additional_free_space', fallback=0))
  333. # append_only can be set in the constructor
  334. # it shouldn't be overridden (True -> False) here
  335. self.append_only = self.append_only or self.config.getboolean('repository', 'append_only', fallback=False)
  336. if self.storage_quota is None:
  337. # self.storage_quota is None => no explicit storage_quota was specified, use repository setting.
  338. self.storage_quota = self.config.getint('repository', 'storage_quota', fallback=0)
  339. self.id = unhexlify(self.config.get('repository', 'id').strip())
  340. self.io = LoggedIO(self.path, self.max_segment_size, self.segments_per_dir)
  341. if self.check_segment_magic:
  342. # read a segment and check whether we are dealing with a non-upgraded Attic repository
  343. segment = self.io.get_latest_segment()
  344. if segment is not None and self.io.get_segment_magic(segment) == ATTIC_MAGIC:
  345. self.close()
  346. raise self.AtticRepository(path)
  347. def close(self):
  348. if self.lock:
  349. if self.io:
  350. self.io.close()
  351. self.io = None
  352. self.lock.release()
  353. self.lock = None
  354. def commit(self, save_space=False, compact=True, cleanup_commits=False):
  355. """Commit transaction
  356. """
  357. # save_space is not used anymore, but stays for RPC/API compatibility.
  358. if self.transaction_doomed:
  359. exception = self.transaction_doomed
  360. self.rollback()
  361. raise exception
  362. self.check_free_space()
  363. self.log_storage_quota()
  364. segment = self.io.write_commit()
  365. self.segments.setdefault(segment, 0)
  366. self.compact[segment] += LoggedIO.header_fmt.size
  367. if compact and not self.append_only:
  368. if cleanup_commits:
  369. # due to bug #2850, there might be a lot of commit-only segment files.
  370. # this is for a one-time cleanup of these 17byte files.
  371. for segment, filename in self.io.segment_iterator():
  372. if os.path.getsize(filename) == 17:
  373. self.segments[segment] = 0
  374. self.compact[segment] = LoggedIO.header_fmt.size
  375. self.compact_segments()
  376. self.write_index()
  377. self.rollback()
  378. def _read_integrity(self, transaction_id, key):
  379. integrity_file = 'integrity.%d' % transaction_id
  380. integrity_path = os.path.join(self.path, integrity_file)
  381. try:
  382. with open(integrity_path, 'rb') as fd:
  383. integrity = msgpack.unpack(fd)
  384. except FileNotFoundError:
  385. return
  386. if integrity.get(b'version') != 2:
  387. logger.warning('Unknown integrity data version %r in %s', integrity.get(b'version'), integrity_file)
  388. return
  389. return integrity[key].decode()
  390. def open_index(self, transaction_id, auto_recover=True):
  391. if transaction_id is None:
  392. return NSIndex()
  393. index_path = os.path.join(self.path, 'index.%d' % transaction_id)
  394. integrity_data = self._read_integrity(transaction_id, b'index')
  395. try:
  396. with IntegrityCheckedFile(index_path, write=False, integrity_data=integrity_data) as fd:
  397. return NSIndex.read(fd)
  398. except (ValueError, OSError, FileIntegrityError) as exc:
  399. logger.warning('Repository index missing or corrupted, trying to recover from: %s', exc)
  400. os.unlink(index_path)
  401. if not auto_recover:
  402. raise
  403. self.prepare_txn(self.get_transaction_id())
  404. # don't leave an open transaction around
  405. self.commit(compact=False)
  406. return self.open_index(self.get_transaction_id())
  407. def prepare_txn(self, transaction_id, do_cleanup=True):
  408. self._active_txn = True
  409. if not self.lock.got_exclusive_lock():
  410. if self.exclusive is not None:
  411. # self.exclusive is either True or False, thus a new client is active here.
  412. # if it is False and we get here, the caller did not use exclusive=True although
  413. # it is needed for a write operation. if it is True and we get here, something else
  414. # went very wrong, because we should have a exclusive lock, but we don't.
  415. raise AssertionError("bug in code, exclusive lock should exist here")
  416. # if we are here, this is an old client talking to a new server (expecting lock upgrade).
  417. # or we are replaying segments and might need a lock upgrade for that.
  418. try:
  419. self.lock.upgrade()
  420. except (LockError, LockErrorT):
  421. # if upgrading the lock to exclusive fails, we do not have an
  422. # active transaction. this is important for "serve" mode, where
  423. # the repository instance lives on - even if exceptions happened.
  424. self._active_txn = False
  425. raise
  426. if not self.index or transaction_id is None:
  427. try:
  428. self.index = self.open_index(transaction_id, auto_recover=False)
  429. except (ValueError, OSError, FileIntegrityError) as exc:
  430. logger.warning('Checking repository transaction due to previous error: %s', exc)
  431. self.check_transaction()
  432. self.index = self.open_index(transaction_id, auto_recover=False)
  433. if transaction_id is None:
  434. self.segments = {} # XXX bad name: usage_count_of_segment_x = self.segments[x]
  435. self.compact = FreeSpace() # XXX bad name: freeable_space_of_segment_x = self.compact[x]
  436. self.storage_quota_use = 0
  437. self.shadow_index.clear()
  438. else:
  439. if do_cleanup:
  440. self.io.cleanup(transaction_id)
  441. hints_path = os.path.join(self.path, 'hints.%d' % transaction_id)
  442. index_path = os.path.join(self.path, 'index.%d' % transaction_id)
  443. integrity_data = self._read_integrity(transaction_id, b'hints')
  444. try:
  445. with IntegrityCheckedFile(hints_path, write=False, integrity_data=integrity_data) as fd:
  446. hints = msgpack.unpack(fd)
  447. except (msgpack.UnpackException, FileNotFoundError, FileIntegrityError) as e:
  448. logger.warning('Repository hints file missing or corrupted, trying to recover: %s', e)
  449. if not isinstance(e, FileNotFoundError):
  450. os.unlink(hints_path)
  451. # index must exist at this point
  452. os.unlink(index_path)
  453. self.check_transaction()
  454. self.prepare_txn(transaction_id)
  455. return
  456. if hints[b'version'] == 1:
  457. logger.debug('Upgrading from v1 hints.%d', transaction_id)
  458. self.segments = hints[b'segments']
  459. self.compact = FreeSpace()
  460. self.storage_quota_use = 0
  461. for segment in sorted(hints[b'compact']):
  462. logger.debug('Rebuilding sparse info for segment %d', segment)
  463. self._rebuild_sparse(segment)
  464. logger.debug('Upgrade to v2 hints complete')
  465. elif hints[b'version'] != 2:
  466. raise ValueError('Unknown hints file version: %d' % hints[b'version'])
  467. else:
  468. self.segments = hints[b'segments']
  469. self.compact = FreeSpace(hints[b'compact'])
  470. self.storage_quota_use = hints.get(b'storage_quota_use', 0)
  471. self.log_storage_quota()
  472. # Drop uncommitted segments in the shadow index
  473. for key, shadowed_segments in self.shadow_index.items():
  474. for segment in list(shadowed_segments):
  475. if segment > transaction_id:
  476. shadowed_segments.remove(segment)
  477. def write_index(self):
  478. def flush_and_sync(fd):
  479. fd.flush()
  480. os.fsync(fd.fileno())
  481. def rename_tmp(file):
  482. os.rename(file + '.tmp', file)
  483. hints = {
  484. b'version': 2,
  485. b'segments': self.segments,
  486. b'compact': self.compact,
  487. b'storage_quota_use': self.storage_quota_use,
  488. }
  489. integrity = {
  490. # Integrity version started at 2, the current hints version.
  491. # Thus, integrity version == hints version, for now.
  492. b'version': 2,
  493. }
  494. transaction_id = self.io.get_segments_transaction_id()
  495. assert transaction_id is not None
  496. # Log transaction in append-only mode
  497. if self.append_only:
  498. with open(os.path.join(self.path, 'transactions'), 'a') as log:
  499. print('transaction %d, UTC time %s' % (
  500. transaction_id, datetime.utcnow().strftime(ISO_FORMAT)), file=log)
  501. # Write hints file
  502. hints_name = 'hints.%d' % transaction_id
  503. hints_file = os.path.join(self.path, hints_name)
  504. with IntegrityCheckedFile(hints_file + '.tmp', filename=hints_name, write=True) as fd:
  505. msgpack.pack(hints, fd)
  506. flush_and_sync(fd)
  507. integrity[b'hints'] = fd.integrity_data
  508. # Write repository index
  509. index_name = 'index.%d' % transaction_id
  510. index_file = os.path.join(self.path, index_name)
  511. with IntegrityCheckedFile(index_file + '.tmp', filename=index_name, write=True) as fd:
  512. # XXX: Consider using SyncFile for index write-outs.
  513. self.index.write(fd)
  514. flush_and_sync(fd)
  515. integrity[b'index'] = fd.integrity_data
  516. # Write integrity file, containing checksums of the hints and index files
  517. integrity_name = 'integrity.%d' % transaction_id
  518. integrity_file = os.path.join(self.path, integrity_name)
  519. with open(integrity_file + '.tmp', 'wb') as fd:
  520. msgpack.pack(integrity, fd)
  521. flush_and_sync(fd)
  522. # Rename the integrity file first
  523. rename_tmp(integrity_file)
  524. sync_dir(self.path)
  525. # Rename the others after the integrity file is hypothetically on disk
  526. rename_tmp(hints_file)
  527. rename_tmp(index_file)
  528. sync_dir(self.path)
  529. # Remove old auxiliary files
  530. current = '.%d' % transaction_id
  531. for name in os.listdir(self.path):
  532. if not name.startswith(('index.', 'hints.', 'integrity.')):
  533. continue
  534. if name.endswith(current):
  535. continue
  536. os.unlink(os.path.join(self.path, name))
  537. self.index = None
  538. def check_free_space(self):
  539. """Pre-commit check for sufficient free space to actually perform the commit."""
  540. # As a baseline we take four times the current (on-disk) index size.
  541. # At this point the index may only be updated by compaction, which won't resize it.
  542. # We still apply a factor of four so that a later, separate invocation can free space
  543. # (journaling all deletes for all chunks is one index size) or still make minor additions
  544. # (which may grow the index up to twice its current size).
  545. # Note that in a subsequent operation the committed index is still on-disk, therefore we
  546. # arrive at index_size * (1 + 2 + 1).
  547. # In that order: journaled deletes (1), hashtable growth (2), persisted index (1).
  548. required_free_space = self.index.size() * 4
  549. # Conservatively estimate hints file size:
  550. # 10 bytes for each segment-refcount pair, 10 bytes for each segment-space pair
  551. # Assume maximum of 5 bytes per integer. Segment numbers will usually be packed more densely (1-3 bytes),
  552. # as will refcounts and free space integers. For 5 MiB segments this estimate is good to ~20 PB repo size.
  553. # Add 4K to generously account for constant format overhead.
  554. hints_size = len(self.segments) * 10 + len(self.compact) * 10 + 4096
  555. required_free_space += hints_size
  556. required_free_space += self.additional_free_space
  557. if not self.append_only:
  558. full_segment_size = self.max_segment_size + MAX_OBJECT_SIZE
  559. if len(self.compact) < 10:
  560. # This is mostly for the test suite to avoid overestimated free space needs. This can be annoying
  561. # if TMP is a small-ish tmpfs.
  562. compact_working_space = sum(self.io.segment_size(segment) - free for segment, free in self.compact.items())
  563. logger.debug('check_free_space: few segments, not requiring a full free segment')
  564. compact_working_space = min(compact_working_space, full_segment_size)
  565. logger.debug('check_free_space: calculated working space for compact as %d bytes', compact_working_space)
  566. required_free_space += compact_working_space
  567. else:
  568. # Keep one full worst-case segment free in non-append-only mode
  569. required_free_space += full_segment_size
  570. try:
  571. st_vfs = os.statvfs(self.path)
  572. except OSError as os_error:
  573. logger.warning('Failed to check free space before committing: ' + str(os_error))
  574. return
  575. except AttributeError:
  576. # TODO move the call to statvfs to platform
  577. logger.warning('Failed to check free space before committing: no statvfs method available')
  578. return
  579. # f_bavail: even as root - don't touch the Federal Block Reserve!
  580. free_space = st_vfs.f_bavail * st_vfs.f_frsize
  581. logger.debug('check_free_space: required bytes {}, free bytes {}'.format(required_free_space, free_space))
  582. if free_space < required_free_space:
  583. if self.created:
  584. logger.error('Not enough free space to initialize repository at this location.')
  585. self.destroy()
  586. else:
  587. self._rollback(cleanup=True)
  588. formatted_required = format_file_size(required_free_space)
  589. formatted_free = format_file_size(free_space)
  590. raise self.InsufficientFreeSpaceError(formatted_required, formatted_free)
  591. def log_storage_quota(self):
  592. if self.storage_quota:
  593. logger.info('Storage quota: %s out of %s used.',
  594. format_file_size(self.storage_quota_use), format_file_size(self.storage_quota))
  595. def compact_segments(self):
  596. """Compact sparse segments by copying data into new segments
  597. """
  598. if not self.compact:
  599. return
  600. index_transaction_id = self.get_index_transaction_id()
  601. segments = self.segments
  602. unused = [] # list of segments, that are not used anymore
  603. logger = create_logger('borg.debug.compact_segments')
  604. def complete_xfer(intermediate=True):
  605. # complete the current transfer (when some target segment is full)
  606. nonlocal unused
  607. # commit the new, compact, used segments
  608. segment = self.io.write_commit(intermediate=intermediate)
  609. self.segments.setdefault(segment, 0)
  610. self.compact[segment] += LoggedIO.header_fmt.size
  611. logger.debug('complete_xfer: wrote %scommit at segment %d', 'intermediate ' if intermediate else '', segment)
  612. # get rid of the old, sparse, unused segments. free space.
  613. for segment in unused:
  614. logger.debug('complete_xfer: deleting unused segment %d', segment)
  615. count = self.segments.pop(segment)
  616. assert count == 0, 'Corrupted segment reference count - corrupted index or hints'
  617. self.io.delete_segment(segment)
  618. del self.compact[segment]
  619. unused = []
  620. logger.debug('compaction started.')
  621. pi = ProgressIndicatorPercent(total=len(self.compact), msg='Compacting segments %3.0f%%', step=1,
  622. msgid='repository.compact_segments')
  623. for segment, freeable_space in sorted(self.compact.items()):
  624. if not self.io.segment_exists(segment):
  625. logger.warning('segment %d not found, but listed in compaction data', segment)
  626. del self.compact[segment]
  627. pi.show()
  628. continue
  629. segment_size = self.io.segment_size(segment)
  630. if segment_size > 0.2 * self.max_segment_size and freeable_space < 0.15 * segment_size:
  631. logger.debug('not compacting segment %d (only %d bytes are sparse)', segment, freeable_space)
  632. pi.show()
  633. continue
  634. segments.setdefault(segment, 0)
  635. logger.debug('compacting segment %d with usage count %d and %d freeable bytes',
  636. segment, segments[segment], freeable_space)
  637. for tag, key, offset, data in self.io.iter_objects(segment, include_data=True):
  638. if tag == TAG_COMMIT:
  639. continue
  640. in_index = self.index.get(key)
  641. is_index_object = in_index == (segment, offset)
  642. if tag == TAG_PUT and is_index_object:
  643. try:
  644. new_segment, offset = self.io.write_put(key, data, raise_full=True)
  645. except LoggedIO.SegmentFull:
  646. complete_xfer()
  647. new_segment, offset = self.io.write_put(key, data)
  648. self.index[key] = new_segment, offset
  649. segments.setdefault(new_segment, 0)
  650. segments[new_segment] += 1
  651. segments[segment] -= 1
  652. elif tag == TAG_PUT and not is_index_object:
  653. # If this is a PUT shadowed by a later tag, then it will be gone when this segment is deleted after
  654. # this loop. Therefore it is removed from the shadow index.
  655. try:
  656. self.shadow_index[key].remove(segment)
  657. except (KeyError, ValueError):
  658. pass
  659. elif tag == TAG_DELETE and not in_index:
  660. # If the shadow index doesn't contain this key, then we can't say if there's a shadowed older tag,
  661. # therefore we do not drop the delete, but write it to a current segment.
  662. shadowed_put_exists = key not in self.shadow_index or any(
  663. # If the key is in the shadow index and there is any segment with an older PUT of this
  664. # key, we have a shadowed put.
  665. shadowed < segment for shadowed in self.shadow_index[key])
  666. delete_is_not_stable = index_transaction_id is None or segment > index_transaction_id
  667. if shadowed_put_exists or delete_is_not_stable:
  668. # (introduced in 6425d16aa84be1eaaf88)
  669. # This is needed to avoid object un-deletion if we crash between the commit and the deletion
  670. # of old segments in complete_xfer().
  671. #
  672. # However, this only happens if the crash also affects the FS to the effect that file deletions
  673. # did not materialize consistently after journal recovery. If they always materialize in-order
  674. # then this is not a problem, because the old segment containing a deleted object would be deleted
  675. # before the segment containing the delete.
  676. #
  677. # Consider the following series of operations if we would not do this, ie. this entire if:
  678. # would be removed.
  679. # Columns are segments, lines are different keys (line 1 = some key, line 2 = some other key)
  680. # Legend: P=TAG_PUT, D=TAG_DELETE, c=commit, i=index is written for latest commit
  681. #
  682. # Segment | 1 | 2 | 3
  683. # --------+-------+-----+------
  684. # Key 1 | P | D |
  685. # Key 2 | P | | P
  686. # commits | c i | c | c i
  687. # --------+-------+-----+------
  688. # ^- compact_segments starts
  689. # ^- complete_xfer commits, after that complete_xfer deletes
  690. # segments 1 and 2 (and then the index would be written).
  691. #
  692. # Now we crash. But only segment 2 gets deleted, while segment 1 is still around. Now key 1
  693. # is suddenly undeleted (because the delete in segment 2 is now missing).
  694. # Again, note the requirement here. We delete these in the correct order that this doesn't happen,
  695. # and only if the FS materialization of these deletes is reordered or parts dropped this can happen.
  696. # In this case it doesn't cause outright corruption, 'just' an index count mismatch, which will be
  697. # fixed by borg-check --repair.
  698. #
  699. # Note that in this check the index state is the proxy for a "most definitely settled" repository state,
  700. # ie. the assumption is that *all* operations on segments <= index state are completed and stable.
  701. try:
  702. new_segment, size = self.io.write_delete(key, raise_full=True)
  703. except LoggedIO.SegmentFull:
  704. complete_xfer()
  705. new_segment, size = self.io.write_delete(key)
  706. self.compact[new_segment] += size
  707. segments.setdefault(new_segment, 0)
  708. assert segments[segment] == 0, 'Corrupted segment reference count - corrupted index or hints'
  709. unused.append(segment)
  710. pi.show()
  711. pi.finish()
  712. complete_xfer(intermediate=False)
  713. logger.debug('compaction completed.')
  714. def replay_segments(self, index_transaction_id, segments_transaction_id):
  715. # fake an old client, so that in case we do not have an exclusive lock yet, prepare_txn will upgrade the lock:
  716. remember_exclusive = self.exclusive
  717. self.exclusive = None
  718. self.prepare_txn(index_transaction_id, do_cleanup=False)
  719. try:
  720. segment_count = sum(1 for _ in self.io.segment_iterator())
  721. pi = ProgressIndicatorPercent(total=segment_count, msg='Replaying segments %3.0f%%',
  722. msgid='repository.replay_segments')
  723. for i, (segment, filename) in enumerate(self.io.segment_iterator()):
  724. pi.show(i)
  725. if index_transaction_id is not None and segment <= index_transaction_id:
  726. continue
  727. if segment > segments_transaction_id:
  728. break
  729. objects = self.io.iter_objects(segment)
  730. self._update_index(segment, objects)
  731. pi.finish()
  732. self.write_index()
  733. finally:
  734. self.exclusive = remember_exclusive
  735. self.rollback()
  736. def _update_index(self, segment, objects, report=None):
  737. """some code shared between replay_segments and check"""
  738. self.segments[segment] = 0
  739. for tag, key, offset, size in objects:
  740. if tag == TAG_PUT:
  741. try:
  742. # If this PUT supersedes an older PUT, mark the old segment for compaction and count the free space
  743. s, _ = self.index[key]
  744. self.compact[s] += size
  745. self.segments[s] -= 1
  746. except KeyError:
  747. pass
  748. self.index[key] = segment, offset
  749. self.segments[segment] += 1
  750. self.storage_quota_use += size
  751. elif tag == TAG_DELETE:
  752. try:
  753. # if the deleted PUT is not in the index, there is nothing to clean up
  754. s, offset = self.index.pop(key)
  755. except KeyError:
  756. pass
  757. else:
  758. if self.io.segment_exists(s):
  759. # the old index is not necessarily valid for this transaction (e.g. compaction); if the segment
  760. # is already gone, then it was already compacted.
  761. self.segments[s] -= 1
  762. size = self.io.read(s, offset, key, read_data=False)
  763. self.storage_quota_use -= size
  764. self.compact[s] += size
  765. elif tag == TAG_COMMIT:
  766. continue
  767. else:
  768. msg = 'Unexpected tag {} in segment {}'.format(tag, segment)
  769. if report is None:
  770. raise self.CheckNeeded(msg)
  771. else:
  772. report(msg)
  773. if self.segments[segment] == 0:
  774. self.compact[segment] += self.io.segment_size(segment)
  775. def _rebuild_sparse(self, segment):
  776. """Rebuild sparse bytes count for a single segment relative to the current index."""
  777. self.compact[segment] = 0
  778. if self.segments[segment] == 0:
  779. self.compact[segment] += self.io.segment_size(segment)
  780. return
  781. for tag, key, offset, size in self.io.iter_objects(segment, read_data=False):
  782. if tag == TAG_PUT:
  783. if self.index.get(key, (-1, -1)) != (segment, offset):
  784. # This PUT is superseded later
  785. self.compact[segment] += size
  786. elif tag == TAG_DELETE:
  787. # The outcome of the DELETE has been recorded in the PUT branch already
  788. self.compact[segment] += size
  789. def check(self, repair=False, save_space=False):
  790. """Check repository consistency
  791. This method verifies all segment checksums and makes sure
  792. the index is consistent with the data stored in the segments.
  793. """
  794. if self.append_only and repair:
  795. raise ValueError(self.path + " is in append-only mode")
  796. error_found = False
  797. def report_error(msg):
  798. nonlocal error_found
  799. error_found = True
  800. logger.error(msg)
  801. logger.info('Starting repository check')
  802. assert not self._active_txn
  803. try:
  804. transaction_id = self.get_transaction_id()
  805. current_index = self.open_index(transaction_id)
  806. logger.debug('Read committed index of transaction %d', transaction_id)
  807. except Exception as exc:
  808. transaction_id = self.io.get_segments_transaction_id()
  809. current_index = None
  810. logger.debug('Failed to read committed index (%s)', exc)
  811. if transaction_id is None:
  812. logger.debug('No segments transaction found')
  813. transaction_id = self.get_index_transaction_id()
  814. if transaction_id is None:
  815. logger.debug('No index transaction found, trying latest segment')
  816. transaction_id = self.io.get_latest_segment()
  817. if transaction_id is None:
  818. report_error('This repository contains no valid data.')
  819. return False
  820. if repair:
  821. self.io.cleanup(transaction_id)
  822. segments_transaction_id = self.io.get_segments_transaction_id()
  823. logger.debug('Segment transaction is %s', segments_transaction_id)
  824. logger.debug('Determined transaction is %s', transaction_id)
  825. self.prepare_txn(None) # self.index, self.compact, self.segments all empty now!
  826. segment_count = sum(1 for _ in self.io.segment_iterator())
  827. logger.debug('Found %d segments', segment_count)
  828. pi = ProgressIndicatorPercent(total=segment_count, msg='Checking segments %3.1f%%', step=0.1,
  829. msgid='repository.check')
  830. for i, (segment, filename) in enumerate(self.io.segment_iterator()):
  831. pi.show(i)
  832. if segment > transaction_id:
  833. continue
  834. try:
  835. objects = list(self.io.iter_objects(segment))
  836. except IntegrityError as err:
  837. report_error(str(err))
  838. objects = []
  839. if repair:
  840. self.io.recover_segment(segment, filename)
  841. objects = list(self.io.iter_objects(segment))
  842. self._update_index(segment, objects, report_error)
  843. pi.finish()
  844. # self.index, self.segments, self.compact now reflect the state of the segment files up to <transaction_id>
  845. # We might need to add a commit tag if no committed segment is found
  846. if repair and segments_transaction_id is None:
  847. report_error('Adding commit tag to segment {}'.format(transaction_id))
  848. self.io.segment = transaction_id + 1
  849. self.io.write_commit()
  850. logger.info('Starting repository index check')
  851. if current_index and not repair:
  852. # current_index = "as found on disk"
  853. # self.index = "as rebuilt in-memory from segments"
  854. if len(current_index) != len(self.index):
  855. report_error('Index object count mismatch.')
  856. logger.error('committed index: %d objects', len(current_index))
  857. logger.error('rebuilt index: %d objects', len(self.index))
  858. line_format = '%-64s %-16s %-16s'
  859. not_found = '<not found>'
  860. logger.warning(line_format, 'ID', 'rebuilt index', 'committed index')
  861. for key, value in self.index.iteritems():
  862. current_value = current_index.get(key, not_found)
  863. if current_value != value:
  864. logger.warning(line_format, bin_to_hex(key), value, current_value)
  865. for key, current_value in current_index.iteritems():
  866. if key in self.index:
  867. continue
  868. value = self.index.get(key, not_found)
  869. if current_value != value:
  870. logger.warning(line_format, bin_to_hex(key), value, current_value)
  871. elif current_index:
  872. for key, value in self.index.iteritems():
  873. if current_index.get(key, (-1, -1)) != value:
  874. report_error('Index mismatch for key {}. {} != {}'.format(key, value, current_index.get(key, (-1, -1))))
  875. if repair:
  876. self.write_index()
  877. self.rollback()
  878. if error_found:
  879. if repair:
  880. logger.info('Completed repository check, errors found and repaired.')
  881. else:
  882. logger.error('Completed repository check, errors found.')
  883. else:
  884. logger.info('Completed repository check, no problems found.')
  885. return not error_found or repair
  886. def scan_low_level(self):
  887. """Very low level scan over all segment file entries.
  888. It does NOT care about what's committed and what not.
  889. It does NOT care whether an object might be deleted or superceded later.
  890. It just yields anything it finds in the segment files.
  891. This is intended as a last-resort way to get access to all repo contents of damaged repos,
  892. when there is uncommitted, but valuable data in there...
  893. """
  894. for segment, filename in self.io.segment_iterator():
  895. try:
  896. for tag, key, offset, data in self.io.iter_objects(segment, include_data=True):
  897. yield key, data, tag, segment, offset
  898. except IntegrityError as err:
  899. logger.error('Segment %d (%s) has IntegrityError(s) [%s] - skipping.' % (segment, filename, str(err)))
  900. def _rollback(self, *, cleanup):
  901. """
  902. """
  903. if cleanup:
  904. self.io.cleanup(self.io.get_segments_transaction_id())
  905. self.index = None
  906. self._active_txn = False
  907. self.transaction_doomed = None
  908. def rollback(self):
  909. # note: when used in remote mode, this is time limited, see RemoteRepository.shutdown_time.
  910. self._rollback(cleanup=False)
  911. def __len__(self):
  912. if not self.index:
  913. self.index = self.open_index(self.get_transaction_id())
  914. return len(self.index)
  915. def __contains__(self, id):
  916. if not self.index:
  917. self.index = self.open_index(self.get_transaction_id())
  918. return id in self.index
  919. def list(self, limit=None, marker=None):
  920. """
  921. list <limit> IDs starting from after id <marker> - in index (pseudo-random) order.
  922. """
  923. if not self.index:
  924. self.index = self.open_index(self.get_transaction_id())
  925. return [id_ for id_, _ in islice(self.index.iteritems(marker=marker), limit)]
  926. def scan(self, limit=None, marker=None):
  927. """
  928. list <limit> IDs starting from after id <marker> - in on-disk order, so that a client
  929. fetching data in this order does linear reads and reuses stuff from disk cache.
  930. We rely on repository.check() has run already (either now or some time before) and that:
  931. - if we are called from a borg check command, self.index is a valid, fresh, in-sync repo index.
  932. - if we are called from elsewhere, either self.index or the on-disk index is valid and in-sync.
  933. - the repository segments are valid (no CRC errors).
  934. if we encounter CRC errors in segment entry headers, rest of segment is skipped.
  935. """
  936. if limit is not None and limit < 1:
  937. raise ValueError('please use limit > 0 or limit = None')
  938. if not self.index:
  939. transaction_id = self.get_transaction_id()
  940. self.index = self.open_index(transaction_id)
  941. at_start = marker is None
  942. # smallest valid seg is <uint32> 0, smallest valid offs is <uint32> 8
  943. start_segment, start_offset = (0, 0) if at_start else self.index[marker]
  944. result = []
  945. for segment, filename in self.io.segment_iterator(start_segment):
  946. obj_iterator = self.io.iter_objects(segment, start_offset, read_data=False, include_data=False)
  947. while True:
  948. try:
  949. tag, id, offset, size = next(obj_iterator)
  950. except (StopIteration, IntegrityError):
  951. # either end-of-segment or an error - we can not seek to objects at
  952. # higher offsets than one that has an error in the header fields
  953. break
  954. if start_offset > 0:
  955. # we are using a marker and the marker points to the last object we have already
  956. # returned in the previous scan() call - thus, we need to skip this one object.
  957. # also, for the next segment, we need to start at offset 0.
  958. start_offset = 0
  959. continue
  960. if tag == TAG_PUT and (segment, offset) == self.index.get(id):
  961. # we have found an existing and current object
  962. result.append(id)
  963. if len(result) == limit:
  964. return result
  965. return result
  966. def get(self, id):
  967. if not self.index:
  968. self.index = self.open_index(self.get_transaction_id())
  969. try:
  970. segment, offset = self.index[id]
  971. return self.io.read(segment, offset, id)
  972. except KeyError:
  973. raise self.ObjectNotFound(id, self.path) from None
  974. def get_many(self, ids, is_preloaded=False):
  975. for id_ in ids:
  976. yield self.get(id_)
  977. def put(self, id, data, wait=True):
  978. """put a repo object
  979. Note: when doing calls with wait=False this gets async and caller must
  980. deal with async results / exceptions later.
  981. """
  982. if not self._active_txn:
  983. self.prepare_txn(self.get_transaction_id())
  984. try:
  985. segment, offset = self.index[id]
  986. except KeyError:
  987. pass
  988. else:
  989. self.segments[segment] -= 1
  990. size = self.io.read(segment, offset, id, read_data=False)
  991. self.storage_quota_use -= size
  992. self.compact[segment] += size
  993. segment, size = self.io.write_delete(id)
  994. self.compact[segment] += size
  995. self.segments.setdefault(segment, 0)
  996. segment, offset = self.io.write_put(id, data)
  997. self.storage_quota_use += len(data) + self.io.put_header_fmt.size
  998. self.segments.setdefault(segment, 0)
  999. self.segments[segment] += 1
  1000. self.index[id] = segment, offset
  1001. if self.storage_quota and self.storage_quota_use > self.storage_quota:
  1002. self.transaction_doomed = self.StorageQuotaExceeded(
  1003. format_file_size(self.storage_quota), format_file_size(self.storage_quota_use))
  1004. raise self.transaction_doomed
  1005. def delete(self, id, wait=True):
  1006. """delete a repo object
  1007. Note: when doing calls with wait=False this gets async and caller must
  1008. deal with async results / exceptions later.
  1009. """
  1010. if not self._active_txn:
  1011. self.prepare_txn(self.get_transaction_id())
  1012. try:
  1013. segment, offset = self.index.pop(id)
  1014. except KeyError:
  1015. raise self.ObjectNotFound(id, self.path) from None
  1016. self.shadow_index.setdefault(id, []).append(segment)
  1017. self.segments[segment] -= 1
  1018. size = self.io.read(segment, offset, id, read_data=False)
  1019. self.storage_quota_use -= size
  1020. self.compact[segment] += size
  1021. segment, size = self.io.write_delete(id)
  1022. self.compact[segment] += size
  1023. self.segments.setdefault(segment, 0)
  1024. def async_response(self, wait=True):
  1025. """Get one async result (only applies to remote repositories).
  1026. async commands (== calls with wait=False, e.g. delete and put) have no results,
  1027. but may raise exceptions. These async exceptions must get collected later via
  1028. async_response() calls. Repeat the call until it returns None.
  1029. The previous calls might either return one (non-None) result or raise an exception.
  1030. If wait=True is given and there are outstanding responses, it will wait for them
  1031. to arrive. With wait=False, it will only return already received responses.
  1032. """
  1033. def preload(self, ids):
  1034. """Preload objects (only applies to remote repositories)
  1035. """
  1036. class LoggedIO:
  1037. class SegmentFull(Exception):
  1038. """raised when a segment is full, before opening next"""
  1039. header_fmt = struct.Struct('<IIB')
  1040. assert header_fmt.size == 9
  1041. put_header_fmt = struct.Struct('<IIB32s')
  1042. assert put_header_fmt.size == 41
  1043. header_no_crc_fmt = struct.Struct('<IB')
  1044. assert header_no_crc_fmt.size == 5
  1045. crc_fmt = struct.Struct('<I')
  1046. assert crc_fmt.size == 4
  1047. _commit = header_no_crc_fmt.pack(9, TAG_COMMIT)
  1048. COMMIT = crc_fmt.pack(crc32(_commit)) + _commit
  1049. def __init__(self, path, limit, segments_per_dir, capacity=90):
  1050. self.path = path
  1051. self.fds = LRUCache(capacity, dispose=self._close_fd)
  1052. self.segment = 0
  1053. self.limit = limit
  1054. self.segments_per_dir = segments_per_dir
  1055. self.offset = 0
  1056. self._write_fd = None
  1057. def close(self):
  1058. self.close_segment()
  1059. self.fds.clear()
  1060. self.fds = None # Just to make sure we're disabled
  1061. def _close_fd(self, ts_fd):
  1062. ts, fd = ts_fd
  1063. safe_fadvise(fd.fileno(), 0, 0, 'DONTNEED')
  1064. fd.close()
  1065. def segment_iterator(self, segment=None, reverse=False):
  1066. if segment is None:
  1067. segment = 0 if not reverse else 2 ** 32 - 1
  1068. data_path = os.path.join(self.path, 'data')
  1069. start_segment_dir = segment // self.segments_per_dir
  1070. dirs = os.listdir(data_path)
  1071. if not reverse:
  1072. dirs = [dir for dir in dirs if dir.isdigit() and int(dir) >= start_segment_dir]
  1073. else:
  1074. dirs = [dir for dir in dirs if dir.isdigit() and int(dir) <= start_segment_dir]
  1075. dirs = sorted(dirs, key=int, reverse=reverse)
  1076. for dir in dirs:
  1077. filenames = os.listdir(os.path.join(data_path, dir))
  1078. if not reverse:
  1079. filenames = [filename for filename in filenames if filename.isdigit() and int(filename) >= segment]
  1080. else:
  1081. filenames = [filename for filename in filenames if filename.isdigit() and int(filename) <= segment]
  1082. filenames = sorted(filenames, key=int, reverse=reverse)
  1083. for filename in filenames:
  1084. # Note: Do not filter out logically deleted segments (see "File system interaction" above),
  1085. # since this is used by cleanup and txn state detection as well.
  1086. yield int(filename), os.path.join(data_path, dir, filename)
  1087. def get_latest_segment(self):
  1088. for segment, filename in self.segment_iterator(reverse=True):
  1089. return segment
  1090. return None
  1091. def get_segments_transaction_id(self):
  1092. """Return the last committed segment.
  1093. """
  1094. for segment, filename in self.segment_iterator(reverse=True):
  1095. if self.is_committed_segment(segment):
  1096. return segment
  1097. return None
  1098. def cleanup(self, transaction_id):
  1099. """Delete segment files left by aborted transactions
  1100. """
  1101. self.segment = transaction_id + 1
  1102. count = 0
  1103. for segment, filename in self.segment_iterator(reverse=True):
  1104. if segment > transaction_id:
  1105. if segment in self.fds:
  1106. del self.fds[segment]
  1107. truncate_and_unlink(filename)
  1108. count += 1
  1109. else:
  1110. break
  1111. logger.debug('Cleaned up %d uncommitted segment files (== everything after segment %d).',
  1112. count, transaction_id)
  1113. def is_committed_segment(self, segment):
  1114. """Check if segment ends with a COMMIT_TAG tag
  1115. """
  1116. try:
  1117. iterator = self.iter_objects(segment)
  1118. except IntegrityError:
  1119. return False
  1120. with open(self.segment_filename(segment), 'rb') as fd:
  1121. try:
  1122. fd.seek(-self.header_fmt.size, os.SEEK_END)
  1123. except OSError as e:
  1124. # return False if segment file is empty or too small
  1125. if e.errno == errno.EINVAL:
  1126. return False
  1127. raise e
  1128. if fd.read(self.header_fmt.size) != self.COMMIT:
  1129. return False
  1130. seen_commit = False
  1131. while True:
  1132. try:
  1133. tag, key, offset, _ = next(iterator)
  1134. except IntegrityError:
  1135. return False
  1136. except StopIteration:
  1137. break
  1138. if tag == TAG_COMMIT:
  1139. seen_commit = True
  1140. continue
  1141. if seen_commit:
  1142. return False
  1143. return seen_commit
  1144. def segment_filename(self, segment):
  1145. return os.path.join(self.path, 'data', str(segment // self.segments_per_dir), str(segment))
  1146. def get_write_fd(self, no_new=False, want_new=False, raise_full=False):
  1147. if not no_new and (want_new or self.offset and self.offset > self.limit):
  1148. if raise_full:
  1149. raise self.SegmentFull
  1150. self.close_segment()
  1151. if not self._write_fd:
  1152. if self.segment % self.segments_per_dir == 0:
  1153. dirname = os.path.join(self.path, 'data', str(self.segment // self.segments_per_dir))
  1154. if not os.path.exists(dirname):
  1155. os.mkdir(dirname)
  1156. sync_dir(os.path.join(self.path, 'data'))
  1157. self._write_fd = SyncFile(self.segment_filename(self.segment), binary=True)
  1158. self._write_fd.write(MAGIC)
  1159. self.offset = MAGIC_LEN
  1160. if self.segment in self.fds:
  1161. # we may have a cached fd for a segment file we already deleted and
  1162. # we are writing now a new segment file to same file name. get rid of
  1163. # of the cached fd that still refers to the old file, so it will later
  1164. # get repopulated (on demand) with a fd that refers to the new file.
  1165. del self.fds[self.segment]
  1166. return self._write_fd
  1167. def get_fd(self, segment):
  1168. # note: get_fd() returns a fd with undefined file pointer position,
  1169. # so callers must always seek() to desired position afterwards.
  1170. now = time.monotonic()
  1171. def open_fd():
  1172. fd = open(self.segment_filename(segment), 'rb')
  1173. self.fds[segment] = (now, fd)
  1174. return fd
  1175. try:
  1176. ts, fd = self.fds[segment]
  1177. except KeyError:
  1178. fd = open_fd()
  1179. else:
  1180. if now - ts > FD_MAX_AGE:
  1181. # we do not want to touch long-unused file handles to
  1182. # avoid ESTALE issues (e.g. on network filesystems).
  1183. del self.fds[segment]
  1184. fd = open_fd()
  1185. else:
  1186. # fd is fresh enough, so we use it.
  1187. # also, we update the timestamp of the lru cache entry.
  1188. self.fds.upd(segment, (now, fd))
  1189. return fd
  1190. def close_segment(self):
  1191. # set self._write_fd to None early to guard against reentry from error handling code paths:
  1192. fd, self._write_fd = self._write_fd, None
  1193. if fd is not None:
  1194. self.segment += 1
  1195. self.offset = 0
  1196. fd.close()
  1197. def delete_segment(self, segment):
  1198. if segment in self.fds:
  1199. del self.fds[segment]
  1200. try:
  1201. truncate_and_unlink(self.segment_filename(segment))
  1202. except FileNotFoundError:
  1203. pass
  1204. def segment_exists(self, segment):
  1205. filename = self.segment_filename(segment)
  1206. # When deleting segments, they are first truncated. If truncate(2) and unlink(2) are split
  1207. # across FS transactions, then logically deleted segments will show up as truncated.
  1208. return os.path.exists(filename) and os.path.getsize(filename)
  1209. def segment_size(self, segment):
  1210. return os.path.getsize(self.segment_filename(segment))
  1211. def get_segment_magic(self, segment):
  1212. fd = self.get_fd(segment)
  1213. fd.seek(0)
  1214. return fd.read(MAGIC_LEN)
  1215. def iter_objects(self, segment, offset=0, include_data=False, read_data=True):
  1216. """
  1217. Return object iterator for *segment*.
  1218. If read_data is False then include_data must be False as well.
  1219. Integrity checks are skipped: all data obtained from the iterator must be considered informational.
  1220. The iterator returns four-tuples of (tag, key, offset, data|size).
  1221. """
  1222. fd = self.get_fd(segment)
  1223. fd.seek(offset)
  1224. if offset == 0:
  1225. # we are touching this segment for the first time, check the MAGIC.
  1226. # Repository.scan() calls us with segment > 0 when it continues an ongoing iteration
  1227. # from a marker position - but then we have checked the magic before already.
  1228. if fd.read(MAGIC_LEN) != MAGIC:
  1229. raise IntegrityError('Invalid segment magic [segment {}, offset {}]'.format(segment, 0))
  1230. offset = MAGIC_LEN
  1231. header = fd.read(self.header_fmt.size)
  1232. while header:
  1233. size, tag, key, data = self._read(fd, self.header_fmt, header, segment, offset,
  1234. (TAG_PUT, TAG_DELETE, TAG_COMMIT),
  1235. read_data=read_data)
  1236. if include_data:
  1237. yield tag, key, offset, data
  1238. else:
  1239. yield tag, key, offset, size
  1240. offset += size
  1241. # we must get the fd via get_fd() here again as we yielded to our caller and it might
  1242. # have triggered closing of the fd we had before (e.g. by calling io.read() for
  1243. # different segment(s)).
  1244. # by calling get_fd() here again we also make our fd "recently used" so it likely
  1245. # does not get kicked out of self.fds LRUcache.
  1246. fd = self.get_fd(segment)
  1247. fd.seek(offset)
  1248. header = fd.read(self.header_fmt.size)
  1249. def recover_segment(self, segment, filename):
  1250. logger.info('attempting to recover ' + filename)
  1251. if segment in self.fds:
  1252. del self.fds[segment]
  1253. backup_filename = filename + '.beforerecover'
  1254. os.rename(filename, backup_filename)
  1255. if os.path.getsize(backup_filename) < MAGIC_LEN + self.header_fmt.size:
  1256. # this is either a zero-byte file (which would crash mmap() below) or otherwise
  1257. # just too small to be a valid non-empty segment file, so do a shortcut here:
  1258. with open(filename, 'wb') as fd:
  1259. fd.write(MAGIC)
  1260. return
  1261. with open(backup_filename, 'rb') as backup_fd:
  1262. # note: file must not be 0 size or mmap() will crash.
  1263. with mmap.mmap(backup_fd.fileno(), 0, access=mmap.ACCESS_READ) as mm:
  1264. # memoryview context manager is problematic, see https://bugs.python.org/issue35686
  1265. data = memoryview(mm)
  1266. d = data
  1267. try:
  1268. with open(filename, 'wb') as fd:
  1269. fd.write(MAGIC)
  1270. while len(d) >= self.header_fmt.size:
  1271. crc, size, tag = self.header_fmt.unpack(d[:self.header_fmt.size])
  1272. if size < self.header_fmt.size or size > len(d):
  1273. d = d[1:]
  1274. continue
  1275. if crc32(d[4:size]) & 0xffffffff != crc:
  1276. d = d[1:]
  1277. continue
  1278. fd.write(d[:size])
  1279. d = d[size:]
  1280. finally:
  1281. del d
  1282. data.release()
  1283. def read(self, segment, offset, id, read_data=True):
  1284. """
  1285. Read entry from *segment* at *offset* with *id*.
  1286. If read_data is False the size of the entry is returned instead and integrity checks are skipped.
  1287. The return value should thus be considered informational.
  1288. """
  1289. if segment == self.segment and self._write_fd:
  1290. self._write_fd.sync()
  1291. fd = self.get_fd(segment)
  1292. fd.seek(offset)
  1293. header = fd.read(self.put_header_fmt.size)
  1294. size, tag, key, data = self._read(fd, self.put_header_fmt, header, segment, offset, (TAG_PUT, ), read_data)
  1295. if id != key:
  1296. raise IntegrityError('Invalid segment entry header, is not for wanted id [segment {}, offset {}]'.format(
  1297. segment, offset))
  1298. return data if read_data else size
  1299. def _read(self, fd, fmt, header, segment, offset, acceptable_tags, read_data=True):
  1300. # some code shared by read() and iter_objects()
  1301. try:
  1302. hdr_tuple = fmt.unpack(header)
  1303. except struct.error as err:
  1304. raise IntegrityError('Invalid segment entry header [segment {}, offset {}]: {}'.format(
  1305. segment, offset, err)) from None
  1306. if fmt is self.put_header_fmt:
  1307. crc, size, tag, key = hdr_tuple
  1308. elif fmt is self.header_fmt:
  1309. crc, size, tag = hdr_tuple
  1310. key = None
  1311. else:
  1312. raise TypeError("_read called with unsupported format")
  1313. if size > MAX_OBJECT_SIZE:
  1314. # if you get this on an archive made with borg < 1.0.7 and millions of files and
  1315. # you need to restore it, you can disable this check by using "if False:" above.
  1316. raise IntegrityError('Invalid segment entry size {} - too big [segment {}, offset {}]'.format(
  1317. size, segment, offset))
  1318. if size < fmt.size:
  1319. raise IntegrityError('Invalid segment entry size {} - too small [segment {}, offset {}]'.format(
  1320. size, segment, offset))
  1321. length = size - fmt.size
  1322. if read_data:
  1323. data = fd.read(length)
  1324. if len(data) != length:
  1325. raise IntegrityError('Segment entry data short read [segment {}, offset {}]: expected {}, got {} bytes'.format(
  1326. segment, offset, length, len(data)))
  1327. if crc32(data, crc32(memoryview(header)[4:])) & 0xffffffff != crc:
  1328. raise IntegrityError('Segment entry checksum mismatch [segment {}, offset {}]'.format(
  1329. segment, offset))
  1330. if key is None and tag in (TAG_PUT, TAG_DELETE):
  1331. key, data = data[:32], data[32:]
  1332. else:
  1333. if key is None and tag in (TAG_PUT, TAG_DELETE):
  1334. key = fd.read(32)
  1335. length -= 32
  1336. if len(key) != 32:
  1337. raise IntegrityError('Segment entry key short read [segment {}, offset {}]: expected {}, got {} bytes'.format(
  1338. segment, offset, 32, len(key)))
  1339. oldpos = fd.tell()
  1340. seeked = fd.seek(length, os.SEEK_CUR) - oldpos
  1341. data = None
  1342. if seeked != length:
  1343. raise IntegrityError('Segment entry data short seek [segment {}, offset {}]: expected {}, got {} bytes'.format(
  1344. segment, offset, length, seeked))
  1345. if tag not in acceptable_tags:
  1346. raise IntegrityError('Invalid segment entry header, did not get acceptable tag [segment {}, offset {}]'.format(
  1347. segment, offset))
  1348. return size, tag, key, data
  1349. def write_put(self, id, data, raise_full=False):
  1350. data_size = len(data)
  1351. if data_size > MAX_DATA_SIZE:
  1352. # this would push the segment entry size beyond MAX_OBJECT_SIZE.
  1353. raise IntegrityError('More than allowed put data [{} > {}]'.format(data_size, MAX_DATA_SIZE))
  1354. fd = self.get_write_fd(want_new=(id == Manifest.MANIFEST_ID), raise_full=raise_full)
  1355. size = data_size + self.put_header_fmt.size
  1356. offset = self.offset
  1357. header = self.header_no_crc_fmt.pack(size, TAG_PUT)
  1358. crc = self.crc_fmt.pack(crc32(data, crc32(id, crc32(header))) & 0xffffffff)
  1359. fd.write(b''.join((crc, header, id, data)))
  1360. self.offset += size
  1361. return self.segment, offset
  1362. def write_delete(self, id, raise_full=False):
  1363. fd = self.get_write_fd(want_new=(id == Manifest.MANIFEST_ID), raise_full=raise_full)
  1364. header = self.header_no_crc_fmt.pack(self.put_header_fmt.size, TAG_DELETE)
  1365. crc = self.crc_fmt.pack(crc32(id, crc32(header)) & 0xffffffff)
  1366. fd.write(b''.join((crc, header, id)))
  1367. self.offset += self.put_header_fmt.size
  1368. return self.segment, self.put_header_fmt.size
  1369. def write_commit(self, intermediate=False):
  1370. # Intermediate commits go directly into the current segment - this makes checking their validity more
  1371. # expensive, but is faster and reduces clobber. Final commits go into a new segment.
  1372. fd = self.get_write_fd(want_new=not intermediate)
  1373. if intermediate:
  1374. fd.sync()
  1375. header = self.header_no_crc_fmt.pack(self.header_fmt.size, TAG_COMMIT)
  1376. crc = self.crc_fmt.pack(crc32(header) & 0xffffffff)
  1377. fd.write(b''.join((crc, header)))
  1378. self.close_segment()
  1379. return self.segment - 1 # close_segment() increments it
  1380. assert LoggedIO.put_header_fmt.size == 41 # see constants.MAX_OBJECT_SIZE