TaiJuWu commented on code in PR #21223: URL: https://github.com/apache/kafka/pull/21223#discussion_r2701990003
########## tools/src/main/java/org/apache/kafka/tools/DumpLogSegments.java: ########## @@ -0,0 +1,1018 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.kafka.tools; + +import org.apache.kafka.clients.consumer.internals.ConsumerProtocol; +import org.apache.kafka.common.header.Header; +import org.apache.kafka.common.message.ConsumerProtocolAssignment; +import org.apache.kafka.common.message.ConsumerProtocolAssignmentJsonConverter; +import org.apache.kafka.common.message.ConsumerProtocolSubscription; +import org.apache.kafka.common.message.ConsumerProtocolSubscriptionJsonConverter; +import org.apache.kafka.common.message.KRaftVersionRecordJsonConverter; +import org.apache.kafka.common.message.LeaderChangeMessageJsonConverter; +import org.apache.kafka.common.message.SnapshotFooterRecordJsonConverter; +import org.apache.kafka.common.message.SnapshotHeaderRecordJsonConverter; +import org.apache.kafka.common.message.VotersRecordJsonConverter; +import org.apache.kafka.common.metadata.MetadataJsonConverters; +import org.apache.kafka.common.metadata.MetadataRecordType; +import org.apache.kafka.common.protocol.ApiMessage; +import org.apache.kafka.common.protocol.ByteBufferAccessor; +import org.apache.kafka.common.record.AbstractLegacyRecordBatch; +import org.apache.kafka.common.record.ControlRecordType; +import org.apache.kafka.common.record.ControlRecordUtils; +import org.apache.kafka.common.record.EndTransactionMarker; +import org.apache.kafka.common.record.FileLogInputStream; +import org.apache.kafka.common.record.FileRecords; +import org.apache.kafka.common.record.Record; +import org.apache.kafka.common.record.RecordBatch; +import org.apache.kafka.common.utils.Utils; +import org.apache.kafka.coordinator.common.runtime.CoordinatorRecordSerde; +import org.apache.kafka.coordinator.common.runtime.Deserializer; +import org.apache.kafka.coordinator.group.GroupCoordinatorRecordSerde; +import org.apache.kafka.coordinator.share.ShareCoordinatorRecordSerde; +import org.apache.kafka.coordinator.transaction.TransactionCoordinatorRecordSerde; +import org.apache.kafka.metadata.MetadataRecordSerde; +import org.apache.kafka.metadata.bootstrap.BootstrapDirectory; +import org.apache.kafka.server.log.remote.metadata.storage.serialization.RemoteLogMetadataSerde; +import org.apache.kafka.server.util.CommandDefaultOptions; +import org.apache.kafka.server.util.CommandLineUtils; +import org.apache.kafka.snapshot.SnapshotPath; +import org.apache.kafka.snapshot.Snapshots; +import org.apache.kafka.storage.internals.log.CorruptSnapshotException; +import org.apache.kafka.storage.internals.log.LogFileUtils; +import org.apache.kafka.storage.internals.log.OffsetIndex; +import org.apache.kafka.storage.internals.log.OffsetPosition; +import org.apache.kafka.storage.internals.log.ProducerStateEntry; +import org.apache.kafka.storage.internals.log.ProducerStateManager; +import org.apache.kafka.storage.internals.log.TimeIndex; +import org.apache.kafka.storage.internals.log.TimestampOffset; +import org.apache.kafka.storage.internals.log.TransactionIndex; +import org.apache.kafka.storage.internals.log.UnifiedLog; +import org.apache.kafka.tools.api.Decoder; +import org.apache.kafka.tools.api.StringDecoder; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.IntNode; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.fasterxml.jackson.databind.node.TextNode; + +import java.io.File; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; + +import joptsimple.OptionSpec; + +public class DumpLogSegments { + // Visible for testing + static final String RECORD_INDENT = "|"; + + public static void main(String[] args) { + DumpLogSegmentsOptions opts = new DumpLogSegmentsOptions(args); + CommandLineUtils.maybePrintHelpOrVersion( + opts, + "This tool helps to parse a log file and dump its contents to the console, useful for debugging a seemingly corrupt log segment." + ); + opts.checkArgs(); + + Map<String, List<Pair<Long, Long>>> misMatchesForIndexFilesMap = new HashMap<>(); + TimeIndexDumpErrors timeIndexDumpErrors = new TimeIndexDumpErrors(); + Map<String, List<Pair<Long, Long>>> nonConsecutivePairsForLogFilesMap = new HashMap<>(); + + for (String arg : opts.files()) { + File file = new File(arg); + System.out.println("Dumping " + file); + + String filename = file.getName(); + String suffix = filename.substring(filename.lastIndexOf(".")); + + switch (suffix) { + case UnifiedLog.LOG_FILE_SUFFIX, Snapshots.SUFFIX -> + dumpLog(file, opts.shouldPrintDataLog(), nonConsecutivePairsForLogFilesMap, + opts.isDeepIteration(), opts.messageParser(), opts.skipRecordMetadata(), opts.maxBytes()); + case UnifiedLog.INDEX_FILE_SUFFIX -> dumpIndex(file, opts.indexSanityOnly(), opts.verifyOnly(), + misMatchesForIndexFilesMap, opts.maxMessageSize()); + case UnifiedLog.TIME_INDEX_FILE_SUFFIX -> + dumpTimeIndex(file, opts.indexSanityOnly(), opts.verifyOnly(), timeIndexDumpErrors); + case LogFileUtils.PRODUCER_SNAPSHOT_FILE_SUFFIX -> dumpProducerIdSnapshot(file); + case UnifiedLog.TXN_INDEX_FILE_SUFFIX -> dumpTxnIndex(file); + default -> System.err.println("Ignoring unknown file " + file); + } + } + + misMatchesForIndexFilesMap.forEach((fileName, listOfMismatches) -> { + System.err.println("Mismatches in :" + fileName); + listOfMismatches.forEach(pair -> + System.err.println(" Index offset: " + pair.first + ", log offset: " + pair.second)); + }); + + timeIndexDumpErrors.printErrors(); + + nonConsecutivePairsForLogFilesMap.forEach((fileName, listOfNonConsecutivePairs) -> { + System.err.println("Non-consecutive offsets in " + fileName); + listOfNonConsecutivePairs.forEach(pair -> + System.err.println(" " + pair.first + " is followed by " + pair.second)); + }); + } + + private static void dumpTxnIndex(File file) { + try (TransactionIndex index = new TransactionIndex(UnifiedLog.offsetFromFile(file), file)) { + for (var abortedTxn : index.allAbortedTxns()) { + System.out.println("version: " + abortedTxn.version() + + " producerId: " + abortedTxn.producerId() + + " firstOffset: " + abortedTxn.firstOffset() + + " lastOffset: " + abortedTxn.lastOffset() + + " lastStableOffset: " + abortedTxn.lastStableOffset()); + } + } catch (IOException e) { + sneakyThrow(e); + } + } + + private static void dumpProducerIdSnapshot(File file) { + try { + List<ProducerStateEntry> entries = ProducerStateManager.readSnapshot(file); + for (ProducerStateEntry entry : entries) { + System.out.print("producerId: " + entry.producerId() + + " producerEpoch: " + entry.producerEpoch() + + " coordinatorEpoch: " + entry.coordinatorEpoch() + + " currentTxnFirstOffset: " + entry.currentTxnFirstOffset() + + " lastTimestamp: " + entry.lastTimestamp() + " "); + + if (!entry.batchMetadata().isEmpty()) { + var metadata = entry.batchMetadata().iterator().next(); + System.out.print("firstSequence: " + metadata.firstSeq() + + " lastSequence: " + metadata.lastSeq() + + " lastOffset: " + metadata.lastOffset() + + " offsetDelta: " + metadata.offsetDelta() + + " timestamp: " + metadata.timestamp()); + } + System.out.println(); + } + } catch (CorruptSnapshotException e) { + System.err.println(e.getMessage()); + } catch (IOException e) { + sneakyThrow(e); + } + } + + // Visible for testing + static void dumpIndex(File file, + boolean indexSanityOnly, + boolean verifyOnly, + Map<String, List<Pair<Long, Long>>> misMatchesForIndexFilesMap, + int maxMessageSize) { + long startOffset = Long.parseLong(file.getName().split("\\.")[0]); + File logFile = new File(file.getAbsoluteFile().getParent(), + file.getName().split("\\.")[0] + UnifiedLog.LOG_FILE_SUFFIX); + + try (FileRecords fileRecords = FileRecords.open(logFile, false); + OffsetIndex index = new OffsetIndex(file, startOffset, -1, false)) { + + if (index.entries() == 0) { + System.out.println(file + " is empty."); + return; + } + + // Check that index passes sanityCheck, this is the check that determines if indexes will be rebuilt on startup or not. + if (indexSanityOnly) { + index.sanityCheck(); + System.out.println(file + " passed sanity check."); + return; + } + + for (int i = 0; i < index.entries(); i++) { + OffsetPosition entry = index.entry(i); + + // since it is a sparse file, in the event of a crash there may be many zero entries, stop if we see one + if (entry.offset() == index.baseOffset() && i > 0) { + return; + } + + FileRecords slice = fileRecords.slice(entry.position(), maxMessageSize); + long firstBatchLastOffset = slice.batches().iterator().next().lastOffset(); + if (firstBatchLastOffset != entry.offset()) { + List<Pair<Long, Long>> misMatchesSeq = misMatchesForIndexFilesMap + .computeIfAbsent(file.getAbsolutePath(), k -> new ArrayList<>()); + // Prepend to match Scala behavior (::= operator) + misMatchesSeq.add(0, new Pair<>(entry.offset(), firstBatchLastOffset)); + misMatchesForIndexFilesMap.put(file.getAbsolutePath(), misMatchesSeq); + } + if (!verifyOnly) { + System.out.println("offset: " + entry.offset() + " position: " + entry.position()); + } + } + } catch (IOException e) { + sneakyThrow(e); Review Comment: To throw IOException directly, in Scala version, the exception is throw directly but java requires Exception signature, this make this migration is hard to work if we don't have this one. I don't have good idea to this change. if you have any suggestions, please share it to me . -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
