Skip to content

Commit 6973dea

Browse files
authored
MINOR: Cleanups in storage module (#20087)
Cleanups including: - Java 17 syntax, record and switch - assertEquals() order - javadoc Reviewers: Andrew Schofield <aschofield@confluent.io>, Jhen-Yung Hsu <jhenyunghsu@gmail.com>, Ken Huang <s7133700@gmail.com>, Chia-Ping Tsai <chia7712@gmail.com>
1 parent 81bdf0b commit 6973dea

File tree

92 files changed

+633
-1595
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

92 files changed

+633
-1595
lines changed

core/src/main/java/kafka/server/share/DelayedShareFetch.java

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -512,11 +512,11 @@ private LogOffsetMetadata endOffsetMetadataForTopicPartition(TopicIdPartition to
512512
// extend it to support other FetchIsolation types.
513513
FetchIsolation isolationType = shareFetch.fetchParams().isolation;
514514
if (isolationType == FetchIsolation.LOG_END)
515-
return offsetSnapshot.logEndOffset;
515+
return offsetSnapshot.logEndOffset();
516516
else if (isolationType == FetchIsolation.HIGH_WATERMARK)
517-
return offsetSnapshot.highWatermark;
517+
return offsetSnapshot.highWatermark();
518518
else
519-
return offsetSnapshot.lastStableOffset;
519+
return offsetSnapshot.lastStableOffset();
520520

521521
}
522522

@@ -835,8 +835,8 @@ private void completeRemoteStorageShareFetchRequest() {
835835
for (RemoteFetch remoteFetch : pendingRemoteFetchesOpt.get().remoteFetches()) {
836836
if (remoteFetch.remoteFetchResult().isDone()) {
837837
RemoteLogReadResult remoteLogReadResult = remoteFetch.remoteFetchResult().get();
838-
if (remoteLogReadResult.error.isPresent()) {
839-
Throwable error = remoteLogReadResult.error.get();
838+
if (remoteLogReadResult.error().isPresent()) {
839+
Throwable error = remoteLogReadResult.error().get();
840840
// If there is any error for the remote fetch topic partition, we populate the error accordingly.
841841
shareFetchPartitionData.add(
842842
new ShareFetchPartitionData(
@@ -846,7 +846,7 @@ private void completeRemoteStorageShareFetchRequest() {
846846
)
847847
);
848848
} else {
849-
FetchDataInfo info = remoteLogReadResult.fetchDataInfo.get();
849+
FetchDataInfo info = remoteLogReadResult.fetchDataInfo().get();
850850
TopicIdPartition topicIdPartition = remoteFetch.topicIdPartition();
851851
LogReadResult logReadResult = remoteFetch.logReadResult();
852852
shareFetchPartitionData.add(

server/src/test/java/org/apache/kafka/server/util/SchedulerTest.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -177,9 +177,9 @@ void testUnscheduleProducerTask() throws IOException {
177177
leaderEpochCache,
178178
producerStateManager,
179179
new ConcurrentHashMap<>(), false).load();
180-
LocalLog localLog = new LocalLog(logDir, logConfig, segments, offsets.recoveryPoint,
181-
offsets.nextOffsetMetadata, scheduler, mockTime, topicPartition, logDirFailureChannel);
182-
UnifiedLog log = new UnifiedLog(offsets.logStartOffset,
180+
LocalLog localLog = new LocalLog(logDir, logConfig, segments, offsets.recoveryPoint(),
181+
offsets.nextOffsetMetadata(), scheduler, mockTime, topicPartition, logDirFailureChannel);
182+
UnifiedLog log = new UnifiedLog(offsets.logStartOffset(),
183183
localLog,
184184
brokerTopicStats,
185185
producerIdExpirationCheckIntervalMs,

storage/src/main/java/org/apache/kafka/server/log/remote/quota/RLMQuotaManagerConfig.java

Lines changed: 8 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -16,44 +16,13 @@
1616
*/
1717
package org.apache.kafka.server.log.remote.quota;
1818

19-
public class RLMQuotaManagerConfig {
19+
/**
20+
* Configuration settings for quota management
21+
*
22+
* @param quotaBytesPerSecond The quota in bytes per second
23+
* @param numQuotaSamples The number of samples to retain in memory
24+
* @param quotaWindowSizeSeconds The time span of each sample
25+
*/
26+
public record RLMQuotaManagerConfig(long quotaBytesPerSecond, int numQuotaSamples, int quotaWindowSizeSeconds) {
2027
public static final int INACTIVE_SENSOR_EXPIRATION_TIME_SECONDS = 3600;
21-
22-
private final long quotaBytesPerSecond;
23-
private final int numQuotaSamples;
24-
private final int quotaWindowSizeSeconds;
25-
26-
/**
27-
* Configuration settings for quota management
28-
*
29-
* @param quotaBytesPerSecond The quota in bytes per second
30-
* @param numQuotaSamples The number of samples to retain in memory
31-
* @param quotaWindowSizeSeconds The time span of each sample
32-
*/
33-
public RLMQuotaManagerConfig(long quotaBytesPerSecond, int numQuotaSamples, int quotaWindowSizeSeconds) {
34-
this.quotaBytesPerSecond = quotaBytesPerSecond;
35-
this.numQuotaSamples = numQuotaSamples;
36-
this.quotaWindowSizeSeconds = quotaWindowSizeSeconds;
37-
}
38-
39-
public long quotaBytesPerSecond() {
40-
return quotaBytesPerSecond;
41-
}
42-
43-
public int numQuotaSamples() {
44-
return numQuotaSamples;
45-
}
46-
47-
public int quotaWindowSizeSeconds() {
48-
return quotaWindowSizeSeconds;
49-
}
50-
51-
@Override
52-
public String toString() {
53-
return "RLMQuotaManagerConfig{" +
54-
"quotaBytesPerSecond=" + quotaBytesPerSecond +
55-
", numQuotaSamples=" + numQuotaSamples +
56-
", quotaWindowSizeSeconds=" + quotaWindowSizeSeconds +
57-
'}';
58-
}
5928
}

storage/src/main/java/org/apache/kafka/server/log/remote/storage/RemoteLogManager.java

Lines changed: 23 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -188,10 +188,11 @@ public class RemoteLogManager implements Closeable, AsyncOffsetReader {
188188
private final KafkaMetricsGroup metricsGroup = new KafkaMetricsGroup("kafka.log.remote", "RemoteLogManager");
189189

190190
// The endpoint for remote log metadata manager to connect to
191-
private Optional<Endpoint> endpoint = Optional.empty();
191+
private final Optional<Endpoint> endpoint;
192+
private final Timer remoteReadTimer;
193+
192194
private boolean closed = false;
193195

194-
private final Timer remoteReadTimer;
195196
private volatile DelayedOperationPurgatory<DelayedRemoteListOffsets> delayedRemoteListOffsetsPurgatory;
196197

197198
/**
@@ -1022,7 +1023,7 @@ private void copyLogSegment(UnifiedLog log, LogSegment segment, RemoteLogSegment
10221023

10231024
List<EpochEntry> epochEntries = getLeaderEpochEntries(log, segment.baseOffset(), nextSegmentBaseOffset);
10241025
Map<Integer, Long> segmentLeaderEpochs = new HashMap<>(epochEntries.size());
1025-
epochEntries.forEach(entry -> segmentLeaderEpochs.put(entry.epoch, entry.startOffset));
1026+
epochEntries.forEach(entry -> segmentLeaderEpochs.put(entry.epoch(), entry.startOffset()));
10261027

10271028
boolean isTxnIdxEmpty = segment.txnIndex().isEmpty();
10281029
RemoteLogSegmentMetadata copySegmentStartedRlsm = new RemoteLogSegmentMetadata(segmentId, segment.baseOffset(), endOffset,
@@ -1083,7 +1084,7 @@ private void copyLogSegment(UnifiedLog log, LogSegment segment, RemoteLogSegment
10831084

10841085
// `epochEntries` cannot be empty, there is a pre-condition validation in RemoteLogSegmentMetadata
10851086
// constructor
1086-
int lastEpochInSegment = epochEntries.get(epochEntries.size() - 1).epoch;
1087+
int lastEpochInSegment = epochEntries.get(epochEntries.size() - 1).epoch();
10871088
copiedOffsetOption = Optional.of(new OffsetAndEpoch(endOffset, lastEpochInSegment));
10881089
// Update the highest offset in remote storage for this partition's log so that the local log segments
10891090
// are not deleted before they are copied to remote storage.
@@ -1222,7 +1223,7 @@ private boolean deleteLogSegmentsDueToLeaderEpochCacheTruncation(EpochEntry earl
12221223
RemoteLogSegmentMetadata metadata)
12231224
throws RemoteStorageException, ExecutionException, InterruptedException {
12241225
boolean isSegmentDeleted = deleteRemoteLogSegment(metadata,
1225-
ignored -> metadata.segmentLeaderEpochs().keySet().stream().allMatch(epoch -> epoch < earliestEpochEntry.epoch));
1226+
ignored -> metadata.segmentLeaderEpochs().keySet().stream().allMatch(epoch -> epoch < earliestEpochEntry.epoch()));
12261227
if (isSegmentDeleted) {
12271228
logger.info("Deleted remote log segment {} due to leader-epoch-cache truncation. " +
12281229
"Current earliest-epoch-entry: {}, segment-end-offset: {} and segment-epochs: {}",
@@ -1391,7 +1392,7 @@ void cleanupExpiredRemoteLogSegments() throws RemoteStorageException, ExecutionE
13911392
if (earliestEpochEntryOptional.isPresent()) {
13921393
EpochEntry earliestEpochEntry = earliestEpochEntryOptional.get();
13931394
Iterator<Integer> epochsToClean = remoteLeaderEpochs.stream()
1394-
.filter(remoteEpoch -> remoteEpoch < earliestEpochEntry.epoch)
1395+
.filter(remoteEpoch -> remoteEpoch < earliestEpochEntry.epoch())
13951396
.iterator();
13961397

13971398
List<RemoteLogSegmentMetadata> listOfSegmentsToBeCleaned = new ArrayList<>();
@@ -1647,11 +1648,11 @@ static NavigableMap<Integer, Long> buildFilteredLeaderEpochMap(NavigableMap<Inte
16471648
}
16481649

16491650
public FetchDataInfo read(RemoteStorageFetchInfo remoteStorageFetchInfo) throws RemoteStorageException, IOException {
1650-
int fetchMaxBytes = remoteStorageFetchInfo.fetchMaxBytes;
1651-
TopicPartition tp = remoteStorageFetchInfo.topicIdPartition.topicPartition();
1652-
FetchRequest.PartitionData fetchInfo = remoteStorageFetchInfo.fetchInfo;
1651+
int fetchMaxBytes = remoteStorageFetchInfo.fetchMaxBytes();
1652+
TopicPartition tp = remoteStorageFetchInfo.topicIdPartition().topicPartition();
1653+
FetchRequest.PartitionData fetchInfo = remoteStorageFetchInfo.fetchInfo();
16531654

1654-
boolean includeAbortedTxns = remoteStorageFetchInfo.fetchIsolation == FetchIsolation.TXN_COMMITTED;
1655+
boolean includeAbortedTxns = remoteStorageFetchInfo.fetchIsolation() == FetchIsolation.TXN_COMMITTED;
16551656

16561657
long offset = fetchInfo.fetchOffset;
16571658
int maxBytes = Math.min(fetchMaxBytes, fetchInfo.maxBytes);
@@ -1703,14 +1704,14 @@ public FetchDataInfo read(RemoteStorageFetchInfo remoteStorageFetchInfo) throws
17031704
// An empty record is sent instead of an incomplete batch when
17041705
// - there is no minimum-one-message constraint and
17051706
// - the first batch size is more than maximum bytes that can be sent and
1706-
if (!remoteStorageFetchInfo.minOneMessage && firstBatchSize > maxBytes) {
1707+
if (!remoteStorageFetchInfo.minOneMessage() && firstBatchSize > maxBytes) {
17071708
LOGGER.debug("Returning empty record for offset {} in partition {} because the first batch size {} " +
17081709
"is greater than max fetch bytes {}", offset, tp, firstBatchSize, maxBytes);
17091710
return new FetchDataInfo(new LogOffsetMetadata(offset), MemoryRecords.EMPTY);
17101711
}
17111712

17121713
int updatedFetchSize =
1713-
remoteStorageFetchInfo.minOneMessage && firstBatchSize > maxBytes ? firstBatchSize : maxBytes;
1714+
remoteStorageFetchInfo.minOneMessage() && firstBatchSize > maxBytes ? firstBatchSize : maxBytes;
17141715

17151716
ByteBuffer buffer = ByteBuffer.allocate(updatedFetchSize);
17161717
int remainingBytes = updatedFetchSize;
@@ -1759,7 +1760,7 @@ private FetchDataInfo addAbortedTransactions(long startOffset,
17591760

17601761
OffsetIndex offsetIndex = indexCache.getIndexEntry(segmentMetadata).offsetIndex();
17611762
long upperBoundOffset = offsetIndex.fetchUpperBoundOffset(startOffsetPosition, fetchSize)
1762-
.map(position -> position.offset).orElse(segmentMetadata.endOffset() + 1);
1763+
.map(OffsetPosition::offset).orElse(segmentMetadata.endOffset() + 1);
17631764

17641765
final Set<FetchResponseData.AbortedTransaction> abortedTransactions = new HashSet<>();
17651766

@@ -1804,8 +1805,8 @@ private void collectAbortedTransactions(long startOffset,
18041805
if (txnIndexOpt.isPresent()) {
18051806
TransactionIndex txnIndex = txnIndexOpt.get();
18061807
TxnIndexSearchResult searchResult = txnIndex.collectAbortedTxns(startOffset, upperBoundOffset);
1807-
accumulator.accept(searchResult.abortedTransactions);
1808-
isSearchComplete = searchResult.isComplete;
1808+
accumulator.accept(searchResult.abortedTransactions());
1809+
isSearchComplete = searchResult.isComplete();
18091810
}
18101811
if (!isSearchComplete) {
18111812
currentMetadataOpt = findNextSegmentWithTxnIndex(tp, currentMetadata.endOffset() + 1, leaderEpochCache);
@@ -1833,8 +1834,8 @@ private void collectAbortedTransactionInLocalSegments(long startOffset,
18331834
TransactionIndex txnIndex = localLogSegments.next().txnIndex();
18341835
if (txnIndex != null) {
18351836
TxnIndexSearchResult searchResult = txnIndex.collectAbortedTxns(startOffset, upperBoundOffset);
1836-
accumulator.accept(searchResult.abortedTransactions);
1837-
if (searchResult.isComplete) {
1837+
accumulator.accept(searchResult.abortedTransactions());
1838+
if (searchResult.isComplete()) {
18381839
return;
18391840
}
18401841
}
@@ -1875,9 +1876,9 @@ Optional<RemoteLogSegmentMetadata> findNextSegmentWithTxnIndex(TopicPartition tp
18751876
}
18761877
int initialEpoch = initialEpochOpt.getAsInt();
18771878
for (EpochEntry epochEntry : leaderEpochCache.epochEntries()) {
1878-
if (epochEntry.epoch >= initialEpoch) {
1879-
long startOffset = Math.max(epochEntry.startOffset, offset);
1880-
Optional<RemoteLogSegmentMetadata> metadataOpt = fetchNextSegmentWithTxnIndex(tp, epochEntry.epoch, startOffset);
1879+
if (epochEntry.epoch() >= initialEpoch) {
1880+
long startOffset = Math.max(epochEntry.startOffset(), offset);
1881+
Optional<RemoteLogSegmentMetadata> metadataOpt = fetchNextSegmentWithTxnIndex(tp, epochEntry.epoch(), startOffset);
18811882
if (metadataOpt.isPresent()) {
18821883
return metadataOpt;
18831884
}
@@ -1906,7 +1907,7 @@ OffsetAndEpoch findHighestRemoteOffset(TopicIdPartition topicIdPartition, Unifie
19061907
LeaderEpochFileCache leaderEpochCache = log.leaderEpochCache();
19071908
Optional<EpochEntry> maybeEpochEntry = leaderEpochCache.latestEntry();
19081909
while (offsetAndEpoch == null && maybeEpochEntry.isPresent()) {
1909-
int epoch = maybeEpochEntry.get().epoch;
1910+
int epoch = maybeEpochEntry.get().epoch();
19101911
Optional<Long> highestRemoteOffsetOpt =
19111912
remoteLogMetadataManagerPlugin.get().highestOffsetForEpoch(topicIdPartition, epoch);
19121913
if (highestRemoteOffsetOpt.isPresent()) {
@@ -1935,7 +1936,7 @@ long findLogStartOffset(TopicIdPartition topicIdPartition, UnifiedLog log) throw
19351936
Optional<Long> logStartOffset = Optional.empty();
19361937
LeaderEpochFileCache leaderEpochCache = log.leaderEpochCache();
19371938
OptionalInt earliestEpochOpt = leaderEpochCache.earliestEntry()
1938-
.map(epochEntry -> OptionalInt.of(epochEntry.epoch))
1939+
.map(epochEntry -> OptionalInt.of(epochEntry.epoch()))
19391940
.orElseGet(OptionalInt::empty);
19401941
while (logStartOffset.isEmpty() && earliestEpochOpt.isPresent()) {
19411942
Iterator<RemoteLogSegmentMetadata> iterator =

storage/src/main/java/org/apache/kafka/server/log/remote/storage/RemoteLogReader.java

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ public RemoteLogReader(RemoteStorageFetchInfo fetchInfo,
5151
this.rlm = rlm;
5252
this.brokerTopicStats = brokerTopicStats;
5353
this.callback = callback;
54-
this.brokerTopicStats.topicStats(fetchInfo.topicIdPartition.topic()).remoteFetchRequestRate().mark();
54+
this.brokerTopicStats.topicStats(fetchInfo.topicIdPartition().topic()).remoteFetchRequestRate().mark();
5555
this.brokerTopicStats.allTopicsStats().remoteFetchRequestRate().mark();
5656
this.quotaManager = quotaManager;
5757
this.remoteReadTimer = remoteReadTimer;
@@ -61,21 +61,21 @@ public RemoteLogReader(RemoteStorageFetchInfo fetchInfo,
6161
public Void call() {
6262
RemoteLogReadResult result;
6363
try {
64-
LOGGER.debug("Reading records from remote storage for topic partition {}", fetchInfo.topicIdPartition);
64+
LOGGER.debug("Reading records from remote storage for topic partition {}", fetchInfo.topicIdPartition());
6565
FetchDataInfo fetchDataInfo = remoteReadTimer.time(() -> rlm.read(fetchInfo));
66-
brokerTopicStats.topicStats(fetchInfo.topicIdPartition.topic()).remoteFetchBytesRate().mark(fetchDataInfo.records.sizeInBytes());
66+
brokerTopicStats.topicStats(fetchInfo.topicIdPartition().topic()).remoteFetchBytesRate().mark(fetchDataInfo.records.sizeInBytes());
6767
brokerTopicStats.allTopicsStats().remoteFetchBytesRate().mark(fetchDataInfo.records.sizeInBytes());
6868
result = new RemoteLogReadResult(Optional.of(fetchDataInfo), Optional.empty());
6969
} catch (OffsetOutOfRangeException e) {
7070
result = new RemoteLogReadResult(Optional.empty(), Optional.of(e));
7171
} catch (Exception e) {
72-
brokerTopicStats.topicStats(fetchInfo.topicIdPartition.topic()).failedRemoteFetchRequestRate().mark();
72+
brokerTopicStats.topicStats(fetchInfo.topicIdPartition().topic()).failedRemoteFetchRequestRate().mark();
7373
brokerTopicStats.allTopicsStats().failedRemoteFetchRequestRate().mark();
74-
LOGGER.error("Error occurred while reading the remote data for {}", fetchInfo.topicIdPartition, e);
74+
LOGGER.error("Error occurred while reading the remote data for {}", fetchInfo.topicIdPartition(), e);
7575
result = new RemoteLogReadResult(Optional.empty(), Optional.of(e));
7676
}
77-
LOGGER.debug("Finished reading records from remote storage for topic partition {}", fetchInfo.topicIdPartition);
78-
quotaManager.record(result.fetchDataInfo.map(fetchDataInfo -> fetchDataInfo.records.sizeInBytes()).orElse(0));
77+
LOGGER.debug("Finished reading records from remote storage for topic partition {}", fetchInfo.topicIdPartition());
78+
quotaManager.record(result.fetchDataInfo().map(fetchDataInfo -> fetchDataInfo.records.sizeInBytes()).orElse(0));
7979
callback.accept(result);
8080
return null;
8181
}

storage/src/main/java/org/apache/kafka/storage/internals/checkpoint/CleanShutdownFileHandler.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ public OptionalLong read() {
9494
Content content = Json.parseStringAs(text, Content.class);
9595
return OptionalLong.of(content.brokerEpoch);
9696
} catch (Exception e) {
97-
logger.debug("Fail to read the clean shutdown file in " + cleanShutdownFile.toPath() + ":" + e);
97+
logger.debug("Fail to read the clean shutdown file in {}", cleanShutdownFile.toPath(), e);
9898
return OptionalLong.empty();
9999
}
100100
}

storage/src/main/java/org/apache/kafka/storage/internals/checkpoint/LeaderEpochCheckpointFile.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ public static File newFile(File dir) {
7474
private static class Formatter implements EntryFormatter<EpochEntry> {
7575

7676
public String toString(EpochEntry entry) {
77-
return entry.epoch + " " + entry.startOffset;
77+
return entry.epoch() + " " + entry.startOffset();
7878
}
7979

8080
public Optional<EpochEntry> fromString(String line) {

storage/src/main/java/org/apache/kafka/storage/internals/checkpoint/OffsetCheckpointFile.java

Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -92,15 +92,7 @@ public Optional<TopicPartitionOffset> fromString(String line) {
9292
}
9393
}
9494

95-
static class TopicPartitionOffset {
96-
97-
final TopicPartition tp;
98-
final long offset;
99-
100-
TopicPartitionOffset(TopicPartition tp, long offset) {
101-
this.tp = tp;
102-
this.offset = offset;
103-
}
95+
record TopicPartitionOffset(TopicPartition tp, long offset) {
10496
}
10597

10698
}

storage/src/main/java/org/apache/kafka/storage/internals/checkpoint/PartitionMetadata.java

Lines changed: 1 addition & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -19,22 +19,7 @@
1919

2020
import org.apache.kafka.common.Uuid;
2121

22-
public class PartitionMetadata {
23-
private final int version;
24-
private final Uuid topicId;
25-
26-
public PartitionMetadata(int version, Uuid topicId) {
27-
this.version = version;
28-
this.topicId = topicId;
29-
}
30-
31-
public int version() {
32-
return version;
33-
}
34-
35-
public Uuid topicId() {
36-
return topicId;
37-
}
22+
public record PartitionMetadata(int version, Uuid topicId) {
3823

3924
public String encode() {
4025
return "version: " + version + "\ntopic_id: " + topicId;

0 commit comments

Comments
 (0)