You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@kafka.apache.org by ju...@apache.org on 2019/02/21 05:50:41 UTC
[kafka] branch trunk updated: KAFKA-7283: Enable lazy mmap on index
files and skip sanity check for segments below recovery point (#5498)
This is an automated email from the ASF dual-hosted git repository.
junrao pushed a commit to branch trunk
in repository https://gitbox.apache.org/repos/asf/kafka.git
The following commit(s) were added to refs/heads/trunk by this push:
new 2932d32 KAFKA-7283: Enable lazy mmap on index files and skip sanity check for segments below recovery point (#5498)
2932d32 is described below
commit 2932d32afb293b2c230a6d73b2eb134ef2828c56
Author: Zhanxiang (Patrick) Huang <hz...@hotmail.com>
AuthorDate: Wed Feb 20 21:50:31 2019 -0800
KAFKA-7283: Enable lazy mmap on index files and skip sanity check for segments below recovery point (#5498)
Per the KIP-263 discussion, we think we can improve broker restart time by avoiding performing costly disk operations when sanity checking index files for segments below recovery point on broker startup.
This PR includes the following changes:
1. Mmap the index file and populate fields of the index file on-demand rather than performing costly disk operations when creating the index object on broker startup.
2. Skip sanity checks on the time index and offset index of segments.
1. For segment with offset below the flushed point (recovery point), these segments are safely flushed so we don't need to sanity check the index files. if there are indeed data corruption on disk, given that we don't sanity check the segment file, sanity checking only the indexes adds little benefit.
2. For segment with offset above the flushed point (recovery point), we will recover these segments in `recoveryLog()` (Log.scala) in any case so sanity checking the index files for these segments is redundant.
We did experiments on a cluster with 15 brokers, each of which has ~3k segments (and there are 31.8k partitions with RF=3 which are evenly distributed across brokers; total bytes-in-rate is around 400 MBps). The results show that rolling bounce time reduces from 135 minutes to 55 minutes.
Reviewers: Ismael Juma <is...@juma.me.uk>, Jun Rao <ju...@gmail.com>
---
core/src/main/scala/kafka/log/LogSegment.scala | 72 ++++++++++++++--------
core/src/main/scala/kafka/log/OffsetIndex.scala | 34 ++++++++++
core/src/main/scala/kafka/log/TimeIndex.scala | 34 ++++++++++
.../test/scala/unit/kafka/log/LogManagerTest.scala | 11 +++-
.../test/scala/unit/kafka/log/LogSegmentTest.scala | 10 +--
core/src/test/scala/unit/kafka/log/LogTest.scala | 43 ++++++++-----
core/src/test/scala/unit/kafka/log/LogUtils.scala | 4 +-
7 files changed, 157 insertions(+), 51 deletions(-)
diff --git a/core/src/main/scala/kafka/log/LogSegment.scala b/core/src/main/scala/kafka/log/LogSegment.scala
index 13093b4..9168ce0 100755
--- a/core/src/main/scala/kafka/log/LogSegment.scala
+++ b/core/src/main/scala/kafka/log/LogSegment.scala
@@ -53,14 +53,18 @@ import scala.math._
*/
@nonthreadsafe
class LogSegment private[log] (val log: FileRecords,
- val offsetIndex: OffsetIndex,
- val timeIndex: TimeIndex,
+ val lazyOffsetIndex: LazyOffsetIndex,
+ val lazyTimeIndex: LazyTimeIndex,
val txnIndex: TransactionIndex,
val baseOffset: Long,
val indexIntervalBytes: Int,
val rollJitterMs: Long,
val time: Time) extends Logging {
+ def offsetIndex: OffsetIndex = lazyOffsetIndex.get
+
+ def timeIndex: TimeIndex = lazyTimeIndex.get
+
def shouldRoll(rollParams: RollParams): Boolean = {
val reachedRollMs = timeWaitedForRoll(rollParams.now, rollParams.maxTimestampInMessages) > rollParams.maxSegmentMs - rollJitterMs
size > rollParams.maxSegmentBytes - rollParams.messagesSize ||
@@ -74,15 +78,16 @@ class LogSegment private[log] (val log: FileRecords,
}
def sanityCheck(timeIndexFileNewlyCreated: Boolean): Unit = {
- if (offsetIndex.file.exists) {
- offsetIndex.sanityCheck()
+ if (lazyOffsetIndex.file.exists) {
// Resize the time index file to 0 if it is newly created.
if (timeIndexFileNewlyCreated)
timeIndex.resize(0)
- timeIndex.sanityCheck()
+ // Sanity checks for time index and offset index are skipped because
+ // we will recover the segments above the recovery point in recoverLog()
+ // in any case so sanity checking them here is redundant.
txnIndex.sanityCheck()
}
- else throw new NoSuchFileException(s"Offset index file ${offsetIndex.file.getAbsolutePath} does not exist")
+ else throw new NoSuchFileException(s"Offset index file ${lazyOffsetIndex.file.getAbsolutePath} does not exist")
}
private var created = time.milliseconds
@@ -94,8 +99,21 @@ class LogSegment private[log] (val log: FileRecords,
private var rollingBasedTimestamp: Option[Long] = None
/* The maximum timestamp we see so far */
- @volatile private var maxTimestampSoFar: Long = timeIndex.lastEntry.timestamp
- @volatile private var offsetOfMaxTimestamp: Long = timeIndex.lastEntry.offset
+ @volatile private var _maxTimestampSoFar: Option[Long] = None
+ def maxTimestampSoFar_=(timestamp: Long): Unit = _maxTimestampSoFar = Some(timestamp)
+ def maxTimestampSoFar: Long = {
+ if (_maxTimestampSoFar.isEmpty)
+ _maxTimestampSoFar = Some(timeIndex.lastEntry.timestamp)
+ _maxTimestampSoFar.get
+ }
+
+ @volatile private var _offsetOfMaxTimestampSoFar: Option[Long] = None
+ def offsetOfMaxTimestampSoFar_=(offset: Long): Unit = _offsetOfMaxTimestampSoFar = Some(offset)
+ def offsetOfMaxTimestampSoFar: Long = {
+ if (_offsetOfMaxTimestampSoFar.isEmpty)
+ _offsetOfMaxTimestampSoFar = Some(timeIndex.lastEntry.offset)
+ _offsetOfMaxTimestampSoFar.get
+ }
/* Return the size in bytes of this log segment */
def size: Int = log.sizeInBytes()
@@ -140,12 +158,12 @@ class LogSegment private[log] (val log: FileRecords,
// Update the in memory max timestamp and corresponding offset.
if (largestTimestamp > maxTimestampSoFar) {
maxTimestampSoFar = largestTimestamp
- offsetOfMaxTimestamp = shallowOffsetOfMaxTimestamp
+ offsetOfMaxTimestampSoFar = shallowOffsetOfMaxTimestamp
}
// append an entry to the index (if needed)
if (bytesSinceLastIndexEntry > indexIntervalBytes) {
offsetIndex.append(largestOffset, physicalPosition)
- timeIndex.maybeAppend(maxTimestampSoFar, offsetOfMaxTimestamp)
+ timeIndex.maybeAppend(maxTimestampSoFar, offsetOfMaxTimestampSoFar)
bytesSinceLastIndexEntry = 0
}
bytesSinceLastIndexEntry += records.sizeInBytes
@@ -345,13 +363,13 @@ class LogSegment private[log] (val log: FileRecords,
// The max timestamp is exposed at the batch level, so no need to iterate the records
if (batch.maxTimestamp > maxTimestampSoFar) {
maxTimestampSoFar = batch.maxTimestamp
- offsetOfMaxTimestamp = batch.lastOffset
+ offsetOfMaxTimestampSoFar = batch.lastOffset
}
// Build offset index
if (validBytes - lastIndexEntry > indexIntervalBytes) {
offsetIndex.append(batch.lastOffset, validBytes)
- timeIndex.maybeAppend(maxTimestampSoFar, offsetOfMaxTimestamp)
+ timeIndex.maybeAppend(maxTimestampSoFar, offsetOfMaxTimestampSoFar)
lastIndexEntry = validBytes
}
validBytes += batch.sizeInBytes()
@@ -376,7 +394,7 @@ class LogSegment private[log] (val log: FileRecords,
log.truncateTo(validBytes)
offsetIndex.trimToValidSize()
// A normally closed segment always appends the biggest timestamp ever seen into log segment, we do this as well.
- timeIndex.maybeAppend(maxTimestampSoFar, offsetOfMaxTimestamp, skipFullCheck = true)
+ timeIndex.maybeAppend(maxTimestampSoFar, offsetOfMaxTimestampSoFar, skipFullCheck = true)
timeIndex.trimToValidSize()
truncated
}
@@ -385,14 +403,14 @@ class LogSegment private[log] (val log: FileRecords,
// Get the last time index entry. If the time index is empty, it will return (-1, baseOffset)
val lastTimeIndexEntry = timeIndex.lastEntry
maxTimestampSoFar = lastTimeIndexEntry.timestamp
- offsetOfMaxTimestamp = lastTimeIndexEntry.offset
+ offsetOfMaxTimestampSoFar = lastTimeIndexEntry.offset
val offsetPosition = offsetIndex.lookup(lastTimeIndexEntry.offset)
// Scan the rest of the messages to see if there is a larger timestamp after the last time index entry.
val maxTimestampOffsetAfterLastEntry = log.largestTimestampAfter(offsetPosition.position)
if (maxTimestampOffsetAfterLastEntry.timestamp > lastTimeIndexEntry.timestamp) {
maxTimestampSoFar = maxTimestampOffsetAfterLastEntry.timestamp
- offsetOfMaxTimestamp = maxTimestampOffsetAfterLastEntry.offset
+ offsetOfMaxTimestampSoFar = maxTimestampOffsetAfterLastEntry.offset
}
}
@@ -475,8 +493,8 @@ class LogSegment private[log] (val log: FileRecords,
*/
def updateDir(dir: File): Unit = {
log.setFile(new File(dir, log.file.getName))
- offsetIndex.file = new File(dir, offsetIndex.file.getName)
- timeIndex.file = new File(dir, timeIndex.file.getName)
+ lazyOffsetIndex.file = new File(dir, lazyOffsetIndex.file.getName)
+ lazyTimeIndex.file = new File(dir, lazyTimeIndex.file.getName)
txnIndex.file = new File(dir, txnIndex.file.getName)
}
@@ -486,8 +504,8 @@ class LogSegment private[log] (val log: FileRecords,
*/
def changeFileSuffixes(oldSuffix: String, newSuffix: String) {
log.renameTo(new File(CoreUtils.replaceSuffix(log.file.getPath, oldSuffix, newSuffix)))
- offsetIndex.renameTo(new File(CoreUtils.replaceSuffix(offsetIndex.file.getPath, oldSuffix, newSuffix)))
- timeIndex.renameTo(new File(CoreUtils.replaceSuffix(timeIndex.file.getPath, oldSuffix, newSuffix)))
+ offsetIndex.renameTo(new File(CoreUtils.replaceSuffix(lazyOffsetIndex.file.getPath, oldSuffix, newSuffix)))
+ timeIndex.renameTo(new File(CoreUtils.replaceSuffix(lazyTimeIndex.file.getPath, oldSuffix, newSuffix)))
txnIndex.renameTo(new File(CoreUtils.replaceSuffix(txnIndex.file.getPath, oldSuffix, newSuffix)))
}
@@ -497,7 +515,7 @@ class LogSegment private[log] (val log: FileRecords,
* The time index entry appended will be used to decide when to delete the segment.
*/
def onBecomeInactiveSegment() {
- timeIndex.maybeAppend(maxTimestampSoFar, offsetOfMaxTimestamp, skipFullCheck = true)
+ timeIndex.maybeAppend(maxTimestampSoFar, offsetOfMaxTimestampSoFar, skipFullCheck = true)
offsetIndex.trimToValidSize()
timeIndex.trimToValidSize()
log.trim()
@@ -559,7 +577,7 @@ class LogSegment private[log] (val log: FileRecords,
* Close this log segment
*/
def close() {
- CoreUtils.swallow(timeIndex.maybeAppend(maxTimestampSoFar, offsetOfMaxTimestamp, skipFullCheck = true), this)
+ CoreUtils.swallow(timeIndex.maybeAppend(maxTimestampSoFar, offsetOfMaxTimestampSoFar, skipFullCheck = true), this)
CoreUtils.swallow(offsetIndex.close(), this)
CoreUtils.swallow(timeIndex.close(), this)
CoreUtils.swallow(log.close(), this)
@@ -594,8 +612,8 @@ class LogSegment private[log] (val log: FileRecords,
CoreUtils.tryAll(Seq(
() => delete(log.deleteIfExists _, "log", log.file, logIfMissing = true),
- () => delete(offsetIndex.deleteIfExists _, "offset index", offsetIndex.file, logIfMissing = true),
- () => delete(timeIndex.deleteIfExists _, "time index", timeIndex.file, logIfMissing = true),
+ () => delete(offsetIndex.deleteIfExists _, "offset index", lazyOffsetIndex.file, logIfMissing = true),
+ () => delete(timeIndex.deleteIfExists _, "time index", lazyTimeIndex.file, logIfMissing = true),
() => delete(txnIndex.deleteIfExists _, "transaction index", txnIndex.file, logIfMissing = false)
))
}
@@ -616,8 +634,8 @@ class LogSegment private[log] (val log: FileRecords,
def lastModified_=(ms: Long) = {
val fileTime = FileTime.fromMillis(ms)
Files.setLastModifiedTime(log.file.toPath, fileTime)
- Files.setLastModifiedTime(offsetIndex.file.toPath, fileTime)
- Files.setLastModifiedTime(timeIndex.file.toPath, fileTime)
+ Files.setLastModifiedTime(lazyOffsetIndex.file.toPath, fileTime)
+ Files.setLastModifiedTime(lazyTimeIndex.file.toPath, fileTime)
}
}
@@ -629,8 +647,8 @@ object LogSegment {
val maxIndexSize = config.maxIndexSize
new LogSegment(
FileRecords.open(Log.logFile(dir, baseOffset, fileSuffix), fileAlreadyExists, initFileSize, preallocate),
- new OffsetIndex(Log.offsetIndexFile(dir, baseOffset, fileSuffix), baseOffset = baseOffset, maxIndexSize = maxIndexSize),
- new TimeIndex(Log.timeIndexFile(dir, baseOffset, fileSuffix), baseOffset = baseOffset, maxIndexSize = maxIndexSize),
+ new LazyOffsetIndex(Log.offsetIndexFile(dir, baseOffset, fileSuffix), baseOffset = baseOffset, maxIndexSize = maxIndexSize),
+ new LazyTimeIndex(Log.timeIndexFile(dir, baseOffset, fileSuffix), baseOffset = baseOffset, maxIndexSize = maxIndexSize),
new TransactionIndex(baseOffset, Log.transactionIndexFile(dir, baseOffset, fileSuffix)),
baseOffset,
indexIntervalBytes = config.indexInterval,
diff --git a/core/src/main/scala/kafka/log/OffsetIndex.scala b/core/src/main/scala/kafka/log/OffsetIndex.scala
index 224475f..876895c 100755
--- a/core/src/main/scala/kafka/log/OffsetIndex.scala
+++ b/core/src/main/scala/kafka/log/OffsetIndex.scala
@@ -202,3 +202,37 @@ class OffsetIndex(_file: File, baseOffset: Long, maxIndexSize: Int = -1, writabl
object OffsetIndex extends Logging {
override val loggerName: String = classOf[OffsetIndex].getName
}
+
+
+
+/**
+ * A thin wrapper on top of the raw OffsetIndex object to avoid initialization on construction. This defers the OffsetIndex
+ * initialization to the time it gets accessed so the cost of the heavy memory mapped operation gets amortized over time.
+ *
+ * Combining with skipping sanity check for safely flushed segments, the startup time of a broker can be reduced, especially
+ * for the the broker with a lot of log segments
+ *
+ */
+class LazyOffsetIndex(@volatile private var _file: File, baseOffset: Long, maxIndexSize: Int = -1, writable: Boolean = true) {
+ @volatile private var offsetIndex: Option[OffsetIndex] = None
+
+ def file: File = {
+ if (offsetIndex.isDefined)
+ offsetIndex.get.file
+ else
+ _file
+ }
+
+ def file_=(f: File) {
+ if (offsetIndex.isDefined)
+ offsetIndex.get.file = f
+ else
+ _file = f
+ }
+
+ def get: OffsetIndex = {
+ if (offsetIndex.isEmpty)
+ offsetIndex = Some(new OffsetIndex(_file, baseOffset, maxIndexSize, writable))
+ offsetIndex.get
+ }
+}
\ No newline at end of file
diff --git a/core/src/main/scala/kafka/log/TimeIndex.scala b/core/src/main/scala/kafka/log/TimeIndex.scala
index 20f4e88..f5c4d90 100644
--- a/core/src/main/scala/kafka/log/TimeIndex.scala
+++ b/core/src/main/scala/kafka/log/TimeIndex.scala
@@ -222,3 +222,37 @@ class TimeIndex(_file: File, baseOffset: Long, maxIndexSize: Int = -1, writable:
object TimeIndex extends Logging {
override val loggerName: String = classOf[TimeIndex].getName
}
+
+
+
+/**
+ * A thin wrapper on top of the raw TimeIndex object to avoid initialization on construction. This defers the TimeIndex
+ * initialization to the time it gets accessed so the cost of the heavy memory mapped operation gets amortized over time.
+ *
+ * Combining with skipping sanity check for safely flushed segments, the startup time of a broker can be reduced, especially
+ * for the the broker with a lot of log segments
+ *
+ */
+class LazyTimeIndex(@volatile private var _file: File, baseOffset: Long, maxIndexSize: Int = -1, writable: Boolean = true) {
+ @volatile private var timeIndex: Option[TimeIndex] = None
+
+ def file: File = {
+ if (timeIndex.isDefined)
+ timeIndex.get.file
+ else
+ _file
+ }
+
+ def file_=(f: File) {
+ if (timeIndex.isDefined)
+ timeIndex.get.file = f
+ else
+ _file = f
+ }
+
+ def get: TimeIndex = {
+ if (timeIndex.isEmpty)
+ timeIndex = Some(new TimeIndex(_file, baseOffset, maxIndexSize, writable))
+ timeIndex.get
+ }
+}
\ No newline at end of file
diff --git a/core/src/test/scala/unit/kafka/log/LogManagerTest.scala b/core/src/test/scala/unit/kafka/log/LogManagerTest.scala
index 812dada..b3ecd23 100755
--- a/core/src/test/scala/unit/kafka/log/LogManagerTest.scala
+++ b/core/src/test/scala/unit/kafka/log/LogManagerTest.scala
@@ -127,6 +127,11 @@ class LogManagerTest {
assertEquals("Now there should only be only one segment in the index.", 1, log.numberOfSegments)
time.sleep(log.config.fileDeleteDelayMs + 1)
+ log.logSegments.foreach(s => {
+ s.lazyOffsetIndex.get
+ s.lazyTimeIndex.get
+ })
+
// there should be a log file, two indexes, one producer snapshot, and the leader epoch checkpoint
assertEquals("Files should have been deleted", log.numberOfSegments * 4 + 1, log.dir.list.length)
assertEquals("Should get empty fetch off new log.", 0, readLog(log, offset + 1).records.sizeInBytes)
@@ -351,12 +356,12 @@ class LogManagerTest {
val removedLog = logManager.asyncDelete(new TopicPartition(name, 0))
val removedSegment = removedLog.activeSegment
- val indexFilesAfterDelete = Seq(removedSegment.offsetIndex.file, removedSegment.timeIndex.file,
+ val indexFilesAfterDelete = Seq(removedSegment.lazyOffsetIndex.file, removedSegment.lazyTimeIndex.file,
removedSegment.txnIndex.file)
assertEquals(new File(removedLog.dir, logName), removedSegment.log.file)
- assertEquals(new File(removedLog.dir, indexName), removedSegment.offsetIndex.file)
- assertEquals(new File(removedLog.dir, timeIndexName), removedSegment.timeIndex.file)
+ assertEquals(new File(removedLog.dir, indexName), removedSegment.lazyOffsetIndex.file)
+ assertEquals(new File(removedLog.dir, timeIndexName), removedSegment.lazyTimeIndex.file)
assertEquals(new File(removedLog.dir, txnIndexName), removedSegment.txnIndex.file)
// Try to detect the case where a new index type was added and we forgot to update the pointer
diff --git a/core/src/test/scala/unit/kafka/log/LogSegmentTest.scala b/core/src/test/scala/unit/kafka/log/LogSegmentTest.scala
index 353e553..0ebc0ef 100644
--- a/core/src/test/scala/unit/kafka/log/LogSegmentTest.scala
+++ b/core/src/test/scala/unit/kafka/log/LogSegmentTest.scala
@@ -279,12 +279,12 @@ class LogSegmentTest {
def testChangeFileSuffixes() {
val seg = createSegment(40)
val logFile = seg.log.file
- val indexFile = seg.offsetIndex.file
+ val indexFile = seg.lazyOffsetIndex.file
seg.changeFileSuffixes("", ".deleted")
assertEquals(logFile.getAbsolutePath + ".deleted", seg.log.file.getAbsolutePath)
- assertEquals(indexFile.getAbsolutePath + ".deleted", seg.offsetIndex.file.getAbsolutePath)
+ assertEquals(indexFile.getAbsolutePath + ".deleted", seg.lazyOffsetIndex.file.getAbsolutePath)
assertTrue(seg.log.file.exists)
- assertTrue(seg.offsetIndex.file.exists)
+ assertTrue(seg.lazyOffsetIndex.file.exists)
}
/**
@@ -296,7 +296,7 @@ class LogSegmentTest {
val seg = createSegment(0)
for(i <- 0 until 100)
seg.append(i, RecordBatch.NO_TIMESTAMP, -1L, records(i, i.toString))
- val indexFile = seg.offsetIndex.file
+ val indexFile = seg.lazyOffsetIndex.file
TestUtils.writeNonsenseToFile(indexFile, 5, indexFile.length.toInt)
seg.recover(new ProducerStateManager(topicPartition, logDir))
for(i <- 0 until 100)
@@ -385,7 +385,7 @@ class LogSegmentTest {
val seg = createSegment(0)
for(i <- 0 until 100)
seg.append(i, i * 10, i, records(i, i.toString))
- val timeIndexFile = seg.timeIndex.file
+ val timeIndexFile = seg.lazyTimeIndex.file
TestUtils.writeNonsenseToFile(timeIndexFile, 5, timeIndexFile.length.toInt)
seg.recover(new ProducerStateManager(topicPartition, logDir))
for(i <- 0 until 100) {
diff --git a/core/src/test/scala/unit/kafka/log/LogTest.scala b/core/src/test/scala/unit/kafka/log/LogTest.scala
index 163001f..6b6dd7c 100755
--- a/core/src/test/scala/unit/kafka/log/LogTest.scala
+++ b/core/src/test/scala/unit/kafka/log/LogTest.scala
@@ -325,7 +325,7 @@ class LogTest {
topicPartition, producerStateManager, new LogDirFailureChannel(10)) {
override def addSegment(segment: LogSegment): LogSegment = {
- val wrapper = new LogSegment(segment.log, segment.offsetIndex, segment.timeIndex, segment.txnIndex, segment.baseOffset,
+ val wrapper = new LogSegment(segment.log, segment.lazyOffsetIndex, segment.lazyTimeIndex, segment.txnIndex, segment.baseOffset,
segment.indexIntervalBytes, segment.rollJitterMs, mockTime) {
override def read(startOffset: Long, maxOffset: Option[Long], maxSize: Int, maxPosition: Long,
@@ -1680,8 +1680,8 @@ class LogTest {
var log = createLog(logDir, logConfig)
for(i <- 0 until numMessages)
log.appendAsLeader(TestUtils.singletonRecords(value = TestUtils.randomBytes(10), timestamp = mockTime.milliseconds + i * 10), leaderEpoch = 0)
- val indexFiles = log.logSegments.map(_.offsetIndex.file)
- val timeIndexFiles = log.logSegments.map(_.timeIndex.file)
+ val indexFiles = log.logSegments.map(_.lazyOffsetIndex.file)
+ val timeIndexFiles = log.logSegments.map(_.lazyTimeIndex.file)
log.close()
// delete all the index files
@@ -1754,7 +1754,7 @@ class LogTest {
for (i <- 0 until numMessages)
log.appendAsLeader(TestUtils.singletonRecords(value = TestUtils.randomBytes(10),
timestamp = mockTime.milliseconds + i * 10, magicValue = RecordBatch.MAGIC_VALUE_V1), leaderEpoch = 0)
- val timeIndexFiles = log.logSegments.map(_.timeIndex.file)
+ val timeIndexFiles = log.logSegments.map(_.lazyTimeIndex.file)
log.close()
// Delete the time index.
@@ -1764,7 +1764,7 @@ class LogTest {
log = createLog(logDir, logConfig, recoveryPoint = numMessages + 1)
for (segment <- log.logSegments.init) {
assertEquals("The time index should be empty", 0, segment.timeIndex.entries)
- assertEquals("The time index file size should be 0", 0, segment.timeIndex.file.length)
+ assertEquals("The time index file size should be 0", 0, segment.lazyTimeIndex.file.length)
}
}
@@ -1779,8 +1779,8 @@ class LogTest {
var log = createLog(logDir, logConfig)
for(i <- 0 until numMessages)
log.appendAsLeader(TestUtils.singletonRecords(value = TestUtils.randomBytes(10), timestamp = mockTime.milliseconds + i * 10), leaderEpoch = 0)
- val indexFiles = log.logSegments.map(_.offsetIndex.file)
- val timeIndexFiles = log.logSegments.map(_.timeIndex.file)
+ val indexFiles = log.logSegments.map(_.lazyOffsetIndex.file)
+ val timeIndexFiles = log.logSegments.map(_.lazyTimeIndex.file)
log.close()
// corrupt all the index files
@@ -1797,8 +1797,8 @@ class LogTest {
bw.close()
}
- // reopen the log
- log = createLog(logDir, logConfig, recoveryPoint = 200L)
+ // reopen the log with recovery point=0 so that the segment recovery can be triggered
+ log = createLog(logDir, logConfig)
assertEquals("Should have %d messages when log is reopened".format(numMessages), numMessages, log.logEndOffset)
for(i <- 0 until numMessages) {
assertEquals(i, readLog(log, i, 100).records.batches.iterator.next().lastOffset)
@@ -1911,10 +1911,19 @@ class LogTest {
val bogusIndex2 = Log.offsetIndexFile(logDir, 5)
val bogusTimeIndex2 = Log.timeIndexFile(logDir, 5)
+ // The files remain absent until we first access it because we are doing lazy loading for time index and offset index
+ // files but in this test case we need to create these files in order to test we will remove them.
+ bogusIndex2.createNewFile()
+ bogusTimeIndex2.createNewFile()
+
def createRecords = TestUtils.singletonRecords(value = "test".getBytes, timestamp = mockTime.milliseconds)
val logConfig = LogTest.createLogConfig(segmentBytes = createRecords.sizeInBytes * 5, segmentIndexBytes = 1000, indexIntervalBytes = 1)
val log = createLog(logDir, logConfig)
+ // Force the segment to access the index files because we are doing index lazy loading.
+ log.logSegments.toSeq.head.offsetIndex
+ log.logSegments.toSeq.head.timeIndex
+
assertTrue("The first index file should have been replaced with a larger file", bogusIndex1.length > 0)
assertTrue("The first time index file should have been replaced with a larger file", bogusTimeIndex1.length > 0)
assertFalse("The second index file should have been deleted.", bogusIndex2.exists)
@@ -1964,20 +1973,20 @@ class LogTest {
// files should be renamed
val segments = log.logSegments.toArray
- val oldFiles = segments.map(_.log.file) ++ segments.map(_.offsetIndex.file)
+ val oldFiles = segments.map(_.log.file) ++ segments.map(_.lazyOffsetIndex.file)
log.onHighWatermarkIncremented(log.logEndOffset)
log.deleteOldSegments()
assertEquals("Only one segment should remain.", 1, log.numberOfSegments)
assertTrue("All log and index files should end in .deleted", segments.forall(_.log.file.getName.endsWith(Log.DeletedFileSuffix)) &&
- segments.forall(_.offsetIndex.file.getName.endsWith(Log.DeletedFileSuffix)))
+ segments.forall(_.lazyOffsetIndex.file.getName.endsWith(Log.DeletedFileSuffix)))
assertTrue("The .deleted files should still be there.", segments.forall(_.log.file.exists) &&
- segments.forall(_.offsetIndex.file.exists))
+ segments.forall(_.lazyOffsetIndex.file.exists))
assertTrue("The original file should be gone.", oldFiles.forall(!_.exists))
// when enough time passes the files should be deleted
- val deletedFiles = segments.map(_.log.file) ++ segments.map(_.offsetIndex.file)
+ val deletedFiles = segments.map(_.log.file) ++ segments.map(_.lazyOffsetIndex.file)
mockTime.sleep(asyncDeleteMs + 1)
assertTrue("Files should all be gone.", deletedFiles.forall(!_.exists))
}
@@ -2104,7 +2113,7 @@ class LogTest {
log.close()
// corrupt index and log by appending random bytes
- TestUtils.appendNonsenseToFile(log.activeSegment.offsetIndex.file, TestUtils.random.nextInt(1024) + 1)
+ TestUtils.appendNonsenseToFile(log.activeSegment.lazyOffsetIndex.file, TestUtils.random.nextInt(1024) + 1)
TestUtils.appendNonsenseToFile(log.activeSegment.log.file, TestUtils.random.nextInt(1024) + 1)
// attempt recovery
@@ -2363,6 +2372,9 @@ class LogTest {
private def testDegenerateSplitSegmentWithOverflow(segmentBaseOffset: Long, records: List[MemoryRecords]): Unit = {
val segment = LogTest.rawSegment(logDir, segmentBaseOffset)
+ // Need to create the offset files explicitly to avoid triggering segment recovery to truncate segment.
+ Log.offsetIndexFile(logDir, segmentBaseOffset).createNewFile()
+ Log.timeIndexFile(logDir, segmentBaseOffset).createNewFile()
records.foreach(segment.append _)
segment.close()
@@ -3797,6 +3809,9 @@ object LogTest {
record(baseOffset + 2)))
segment.append(MemoryRecords.withRecords(baseOffset + Int.MaxValue - 1, CompressionType.NONE, 0,
record(baseOffset + Int.MaxValue - 1)))
+ // Need to create the offset files explicitly to avoid triggering segment recovery to truncate segment.
+ Log.offsetIndexFile(logDir, baseOffset).createNewFile()
+ Log.timeIndexFile(logDir, baseOffset).createNewFile()
baseOffset + Int.MaxValue
}
diff --git a/core/src/test/scala/unit/kafka/log/LogUtils.scala b/core/src/test/scala/unit/kafka/log/LogUtils.scala
index 8652aa5..838a699 100644
--- a/core/src/test/scala/unit/kafka/log/LogUtils.scala
+++ b/core/src/test/scala/unit/kafka/log/LogUtils.scala
@@ -31,8 +31,8 @@ object LogUtils {
indexIntervalBytes: Int = 10,
time: Time = Time.SYSTEM): LogSegment = {
val ms = FileRecords.open(Log.logFile(logDir, offset))
- val idx = new OffsetIndex(Log.offsetIndexFile(logDir, offset), offset, maxIndexSize = 1000)
- val timeIdx = new TimeIndex(Log.timeIndexFile(logDir, offset), offset, maxIndexSize = 1500)
+ val idx = new LazyOffsetIndex(Log.offsetIndexFile(logDir, offset), offset, maxIndexSize = 1000)
+ val timeIdx = new LazyTimeIndex(Log.timeIndexFile(logDir, offset), offset, maxIndexSize = 1500)
val txnIndex = new TransactionIndex(offset, Log.transactionIndexFile(logDir, offset))
new LogSegment(ms, idx, timeIdx, txnIndex, offset, indexIntervalBytes, 0, time)