- 發送到Kafka的消息最終都是要落盤存儲到磁盤上;
- 本章涉及到的類:
- OffsetIndex;
- LogSegment;
OffsetIndex類
- 所在文件: core/src/main/scala/kafka/log/OffsetIndex.scala
-
作用: 我們知道所有發送到kafka的消息都是以
Record
的結構(Kafka中Message存儲相關類大揭密)寫入到本地文件, 有寫就要有讀,讀取時一般是從給定的offset開始讀取,這個offset是邏輯offset, 需要轉換成文件的實際偏移量, 為了加速這個轉換, kafka針對每個log文件,提供了index文件, index文件采用稀疏索引的方式, 只記錄部分log offset到file position的轉換, 然后還需要在log文件中進行少量的順序遍歷, 來精確定位到需要的Record
; - index文件結構: 文件里存的是一條條的log offset與file position的映射, 每條記錄8個字節,前4個字節是log offset, 后4個字節是file position, 這樣的每一條映射信息我們可以稱為是一個slot
- 讀寫方式: 為了加速index文件的讀寫, 采用了文件內存映射的方式:
/* initialize the memory mapping for this index */
private var mmap: MappedByteBuffer =
{
val newlyCreated = file.createNewFile()
val raf = new RandomAccessFile(file, "rw")
try {
/* pre-allocate the file if necessary */
if(newlyCreated) {
if(maxIndexSize < 8)
throw new IllegalArgumentException("Invalid max index size: " + maxIndexSize)
raf.setLength(roundToExactMultiple(maxIndexSize, 8))
}
/* memory-map the file */
val len = raf.length()
val idx = raf.getChannel.map(FileChannel.MapMode.READ_WRITE, 0, len)
/* set the position in the index for the next entry */
if(newlyCreated)
idx.position(0)
else
// if this is a pre-existing index, assume it is all valid and set position to last entry
idx.position(roundToExactMultiple(idx.limit, 8))
idx
} finally {
CoreUtils.swallow(raf.close())
}
}
- 主要方法:
-
def lookup(targetOffset: Long): OffsetPosition
: 查找小于或等于targetOffset
的最大Offset;
-
maybeLock(lock) {
val idx = mmap.duplicate
val slot = indexSlotFor(idx, targetOffset)
if(slot == -1)
OffsetPosition(baseOffset, 0)
else
OffsetPosition(baseOffset + relativeOffset(idx, slot), physical(idx, slot))
}
-
private def indexSlotFor(idx: ByteBuffer, targetOffset: Long): Int
:采用二分法查找到對于targetOffset
在index文件中的slot
// binary search for the entry 二分查找法
var lo = 0
var hi = entries-1
while(lo < hi) {
val mid = ceil(hi/2.0 + lo/2.0).toInt
val found = relativeOffset(idx, mid)
if(found == relOffset)
return mid
else if(found < relOffset)
lo = mid
else
hi = mid - 1
}
-
def append(offset: Long, position: Int)
: 向index文件中追加一個offset/location的映射信息 -
def truncateTo(offset: Long)
: 按給定的offset,找到對應的slot, 然后截斷 -
def resize(newSize: Int)
: 重新設置index文件size, 但保持當前mmap的position不變
inLock(lock) {
val raf = new RandomAccessFile(file, "rw")
val roundedNewSize = roundToExactMultiple(newSize, 8)
val position = this.mmap.position
/* Windows won't let us modify the file length while the file is mmapped :-( */
if(Os.isWindows)
forceUnmap(this.mmap)
try {
raf.setLength(roundedNewSize)
this.mmap = raf.getChannel().map(FileChannel.MapMode.READ_WRITE, 0, roundedNewSize)
this.maxEntries = this.mmap.limit / 8
this.mmap.position(position)
} finally {
CoreUtils.swallow(raf.close())
}
}
- 有意思的一件事:
上面我們說過這個index文件的讀取是使用了內存文件映射MappedByteBuffer
, 然后并沒有找到相應的unmap(實際上是沒有這方法)的調用, 這個會不會有問題呢?遇到google了一下, 果然有發現: Long GC pause harming broker performance which is caused by mmap objects created for OffsetIndex,
在實際應用中確實遇到了這樣的問題,一直沒搞明白為什么IO會升高.
LogSegment
- 所在文件: core/src/main/scala/kafka/log/LogSegment.scala
- 作用: 封裝對消息落地后的log和index文件的所有操作
- 類定義:
class LogSegment(val log: FileMessageSet,
val index: OffsetIndex,
val baseOffset: Long,
val indexIntervalBytes: Int,
val rollJitterMs: Long,
time: Time) extends Loggin
可以看到使用FileMessageSet來操作Log文件, 使用OffsetIndex
來操作Index文件
- 主要方法:
-
def size: Long = log.sizeInBytes()
: 返回當前log文件的大小 -
def append(offset: Long, messages: ByteBufferMessageSet)
:追加msg到log文件尾部,必要時更新index文件
-
if (messages.sizeInBytes > 0) {
// append an entry to the index (if needed)
// index采用的是稀疏索引, 所以先判斷是否需要寫入
if(bytesSinceLastIndexEntry > indexIntervalBytes) {
index.append(offset, log.sizeInBytes())
this.bytesSinceLastIndexEntry = 0
}
// append the messages
log.append(messages) //追加msg到log文件尾部
this.bytesSinceLastIndexEntry += messages.sizeInBytes
}
-
def read(startOffset: Long, maxOffset: Option[Long], maxSize: Int, maxPosition: Long = size): FetchDataInfo
: 根據給定的offset信息等讀取相應的msg 和offset信息,構成FetchDataInfo
返回
val offsetMetadata = new LogOffsetMetadata(startOffset, this.baseOffset, startPosition.position)
// if the size is zero, still return a log segment but with zero size
if(maxSize == 0)
return FetchDataInfo(offsetMetadata, MessageSet.Empty)
// calculate the length of the message set to read based on whether or not they gave us a maxOffset
val length =
maxOffset match {
case None =>
// no max offset, just read until the max position
min((maxPosition - startPosition.position).toInt, maxSize)
case Some(offset) => {
// there is a max offset, translate it to a file position and use that to calculate the max read size
if(offset < startOffset)
throw new IllegalArgumentException("Attempt to read with a maximum offset (%d) less than the start offset (%d).".format(offset, startOffset))
val mapping = translateOffset(offset, startPosition.position)
val endPosition =
if(mapping == null)
logSize // the max offset is off the end of the log, use the end of the file
else
mapping.position
min(min(maxPosition, endPosition) - startPosition.position, maxSize).toInt
}
}
FetchDataInfo(offsetMetadata, log.read(startPosition.position, length))
實際上最終是調用FileMessageSet
的read
方法讀取
-
def recover(maxMessageSize: Int): Int
:讀取當前的log文件內容,重新構建index文件
//逐條讀取log里的msg, 然后構建index文件
val iter = log.iterator(maxMessageSize)
try {
while(iter.hasNext) {
val entry = iter.next
entry.message.ensureValid()
if(validBytes - lastIndexEntry > indexIntervalBytes) {
// we need to decompress the message, if required, to get the offset of the first uncompressed message
val startOffset =
entry.message.compressionCodec match {
case NoCompressionCodec =>
entry.offset
case _ =>
ByteBufferMessageSet.deepIterator(entry.message).next().offset
}
index.append(startOffset, validBytes)
lastIndexEntry = validBytes
}
validBytes += MessageSet.entrySize(entry.message)
}
} catch {
case e: InvalidMessageException =>
logger.warn("Found invalid messages in log segment %s at byte offset %d: %s.".format(log.file.getAbsolutePath, validBytes, e.getMessage))
}
-
def truncateTo(offset: Long): Int
: 根據給定的offset截斷log和index文件
val mapping = translateOffset(offset)
if(mapping == null)
return 0
index.truncateTo(offset)
// after truncation, reset and allocate more space for the (new currently active) index
index.resize(index.maxIndexSize)
val bytesTruncated = log.truncateTo(mapping.position)
if(log.sizeInBytes == 0)
created = time.milliseconds
bytesSinceLastIndexEntry = 0
bytesTruncated
-
def nextOffset(): Long
: 獲取下一個offset值, 其實就是當前最大的offset + 1
val ms = read(index.lastOffset, None, log.sizeInBytes)
if(ms == null) {
baseOffset
} else {
ms.messageSet.lastOption match {
case None => baseOffset
case Some(last) => last.nextOffset
}
}