dengziming commented on code in PR #12315:
URL: https://github.com/apache/kafka/pull/12315#discussion_r905758022


##########
core/src/main/scala/kafka/tools/MetadataShellTool.scala:
##########
@@ -0,0 +1,199 @@
+/**
+ * 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 kafka.tools
+
+import java.nio.file.{Files, Path}
+import java.util.Collections
+import java.util.concurrent.CompletableFuture
+import kafka.raft.KafkaRaftManager
+import kafka.server.{KafkaConfig, KafkaRaftServer, MetaProperties}
+import kafka.utils.Logging
+import net.sourceforge.argparse4j.ArgumentParsers
+import org.apache.kafka.common.metrics.Metrics
+import org.apache.kafka.common.utils.{Exit, Time, Utils}
+import org.apache.kafka.metadata.MetadataRecordSerde
+import org.apache.kafka.metadata.util.{ClusterMetadataSource, 
SnapshotFileReader}
+import org.apache.kafka.raft.{BatchReader, KafkaRaftClient, LeaderAndEpoch, 
RaftClient, RaftConfig}
+import org.apache.kafka.server.common.ApiMessageAndVersion
+import org.apache.kafka.shell.{InteractiveShell, NonInteractiveShell}
+import org.apache.kafka.snapshot.SnapshotReader
+
+
+object MetadataShellTool {
+  def main(args: Array[String]): Unit = {
+    val parser = ArgumentParsers.newArgumentParser("metadata-tool").
+      defaultHelp(true).
+      description("The Apache Kafka metadata tool")
+    parser.addArgument("--cluster-id", "-t").
+      `type`(classOf[String]).
+      help("The cluster id. Required when using --controllers")
+    val accessGroup = parser.addMutuallyExclusiveGroup().
+      required(true)
+    accessGroup.addArgument("--snapshot", "-s").
+     `type`(classOf[String]).
+      help("The snapshot file to read.")
+    accessGroup.addArgument("--controllers", "-q").
+      `type`(classOf[String]).
+      help(s"The ${RaftConfig.QUORUM_VOTERS_CONFIG}.")
+    parser.addArgument("command").
+      nargs("*").
+      help("The command to run.")
+    val res = parser.parseArgsOrFail(args)
+    val source = if (res.getString("snapshot") != null) {
+      new SnapshotFileReader(res.getString("snapshot"))
+    } else if (res.getString("controllers") != null) {
+      val clusterId = res.getString("cluster_id")
+      if (clusterId == null || clusterId.isEmpty) {
+        throw new RuntimeException("You must provide --cluster-id when 
connecting " +
+          "directly to the controllers.")
+      }
+      val observer = new MetadataShellObserver()
+      observer.setup(res.getString("controllers"), clusterId)
+      observer
+    } else {
+      throw new RuntimeException("You must set either --snapshot or 
--controllers")
+    }
+    try {
+      val args = 
Option(res.getList[String]("command")).getOrElse(Collections.emptyList[String])
+      if (args.isEmpty) {
+        val shell = new InteractiveShell(source)
+        try {
+          shell.run()
+        } finally {
+          shell.close()
+        }
+      } else {
+        val shell = new NonInteractiveShell(source)
+        try {
+          shell.run(System.out, args)
+        } finally {
+          shell.close()
+        }
+      }
+      Exit.exit(0)
+    } catch {
+      case e: Throwable =>
+        System.err.println("Unexpected error: " + (if (e.getMessage == null) ""
+        else e.getMessage))
+        e.printStackTrace(System.err)
+        Exit.exit(1)
+    }
+  }
+}
+
+class HighWaterMarkTrackingRaftClientListener(
+  val caughtUpFuture: CompletableFuture[Void],
+  val raftClient: KafkaRaftClient[ApiMessageAndVersion],
+  val underlying: RaftClient.Listener[ApiMessageAndVersion],
+) extends RaftClient.Listener[ApiMessageAndVersion] {
+  override def handleCommit(reader: BatchReader[ApiMessageAndVersion]): Unit = 
{
+    reader.lastOffset().ifPresent(checkIfCaughtUp(_))
+    underlying.handleCommit(reader)
+  }
+
+  override def handleSnapshot(reader: SnapshotReader[ApiMessageAndVersion]): 
Unit = {
+    checkIfCaughtUp(reader.lastContainedLogOffset())
+    underlying.handleSnapshot(reader)
+  }
+
+  override def handleLeaderChange(leader: LeaderAndEpoch): Unit = {
+    underlying.handleLeaderChange(leader)
+  }
+
+  override def beginShutdown(): Unit = {
+    underlying.beginShutdown()
+  }
+
+  private def checkIfCaughtUp(offset: Long): Unit = {
+    if (!caughtUpFuture.isDone) {
+      raftClient.highWatermark().ifPresent(highWatermark =>
+        if (offset >= highWatermark) {
+          caughtUpFuture.complete(null)
+        })
+    }
+  }
+}
+
+class MetadataShellObserver extends ClusterMetadataSource with Logging {
+  val _caughtUpFuture = new CompletableFuture[Void]()
+  var tempDir: Path = null
+  var raftManager: KafkaRaftManager[ApiMessageAndVersion] = null
+  var _listener: HighWaterMarkTrackingRaftClientListener = null
+
+  def setup(
+    quorumVoters: String,
+    clusterId: String
+  ): Unit = {
+    try {
+      tempDir = Files.createTempDirectory("MetadataShell")
+      val metaProperties = new MetaProperties(clusterId, -1)
+      val configMap = new java.util.HashMap[String, Object]
+      configMap.put(RaftConfig.QUORUM_VOTERS_CONFIG, quorumVoters)
+      configMap.put(KafkaConfig.MetadataLogDirProp, 
tempDir.toAbsolutePath.toString)
+      val config = new KafkaConfig(configMap)

Review Comment:
   We should set `process.roles` here to avoid exception



-- 
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]

Reply via email to