You are viewing a plain text version of this content. The canonical link for it is here.
Posted to jira@kafka.apache.org by GitBox <gi...@apache.org> on 2021/10/20 00:03:23 UTC

[GitHub] [kafka] cmccabe opened a new pull request #11417: KAFKA-13340: Change ZooKeeperTestHarness to QuorumTestHarness

cmccabe opened a new pull request #11417:
URL: https://github.com/apache/kafka/pull/11417


   Change ZooKeeperTestHarness to QuorumTestHarness so that integration tests which inherit from this
   class can test both ZK and KRaft mode. Test cases which do this can specify the modes they support
   by including a ParameterizedTest annotation before each test case, like the following:
   
   @ParameterizedTest
   @valuesource(strings = Array("zk", "kraft"))
   def testValidCreateTopicsRequests(quorum: String): Unit = { ... }
   
   For each value that is specified here (zk, kraft), the test case will be run once in the appropriate
   mode. So the test shown above is run twice. This allows integration tests to be incrementally
   converted over to support KRaft mode, rather than rewritten to support it. As you might expect, test
   cases which do not specify a quorum argument will continue to run only in ZK mode.
   
   JUnit5 makes the quorum annotation visible in the TestInfo object which each @beforeeach function in
   a test can optionally take. Therefore, this PR converts over the setUp function of the quorum base
   class, plus every derived class, to take a TestInfo argument. The TestInfo object gets "passed up
   the chain" to the base class, where it determines which quorum type we create (zk or kraft).
   
   The general approach taken here is to make as much as possible work with KRaft, but to leave some
   things as ZK-only when appropriate. For example, a test that explicitly requests an AdminZkClient
   object will get an exception if it is running in KRaft mode. Similarly, tests which explicitly
   request KafkaServer rather than KafkaBroker will get an exception when running in KRaft mode.
   
   As a proof of concept, this PR converts over MetricsTest to support KRaft.


-- 
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: jira-unsubscribe@kafka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [kafka] hachikuji commented on a change in pull request #11417: KAFKA-13340: Change ZooKeeperTestHarness to QuorumTestHarness

Posted by GitBox <gi...@apache.org>.
hachikuji commented on a change in pull request #11417:
URL: https://github.com/apache/kafka/pull/11417#discussion_r736025333



##########
File path: core/src/test/scala/integration/kafka/server/QuorumTestHarness.scala
##########
@@ -0,0 +1,339 @@
+/**
+ * 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.server
+
+import java.io.{ByteArrayOutputStream, File, PrintStream}
+import java.net.InetSocketAddress
+import java.util
+import java.util.{Collections, Properties}
+import java.util.concurrent.CompletableFuture
+
+import javax.security.auth.login.Configuration
+import kafka.raft.KafkaRaftManager
+import kafka.tools.StorageTool
+import kafka.utils.{CoreUtils, Logging, TestInfoUtils, TestUtils}
+import kafka.zk.{AdminZkClient, EmbeddedZookeeper, KafkaZkClient}
+import org.apache.kafka.common.metrics.Metrics
+import org.apache.kafka.common.{TopicPartition, Uuid}
+import org.apache.kafka.common.security.JaasUtils
+import org.apache.kafka.common.security.auth.SecurityProtocol
+import org.apache.kafka.common.utils.Time
+import org.apache.kafka.metadata.MetadataRecordSerde
+import org.apache.kafka.raft.RaftConfig.{AddressSpec, InetAddressSpec}
+import org.apache.kafka.server.common.ApiMessageAndVersion
+import org.apache.zookeeper.client.ZKClientConfig
+import org.apache.zookeeper.{WatchedEvent, Watcher, ZooKeeper}
+import org.junit.jupiter.api.Assertions._
+import org.junit.jupiter.api.{AfterAll, AfterEach, BeforeAll, BeforeEach, Tag, TestInfo}
+
+import scala.collection.{Seq, immutable}
+
+trait QuorumImplementation {
+  def createAndStartBroker(config: KafkaConfig,
+                           time: Time): KafkaBroker
+
+  def shutdown(): Unit
+}
+
+class ZooKeeperQuorumImplementation(val zookeeper: EmbeddedZookeeper,
+                                    val zkClient: KafkaZkClient,
+                                    val adminZkClient: AdminZkClient,
+                                    val log: Logging) extends QuorumImplementation {
+  override def createAndStartBroker(config: KafkaConfig,
+                                    time: Time): KafkaBroker = {
+    val server = new KafkaServer(config, time, None, false)
+    server.startup()
+    server
+  }
+
+  override def shutdown(): Unit = {
+    CoreUtils.swallow(zkClient.close(), log)
+    CoreUtils.swallow(zookeeper.shutdown(), log)
+  }
+
+  def shutdownZooKeeper(): Unit = {
+    CoreUtils.swallow(zookeeper.shutdown(), log)
+  }
+}
+
+class KRaftQuorumImplementation(val raftManager: KafkaRaftManager[ApiMessageAndVersion],
+                                val controllerServer: ControllerServer,
+                                val metadataDir: File,
+                                val controllerQuorumVotersFuture: CompletableFuture[util.Map[Integer, AddressSpec]],
+                                val clusterId: String,
+                                val log: Logging) extends QuorumImplementation {
+  override def createAndStartBroker(config: KafkaConfig,
+                                    time: Time): KafkaBroker = {
+    val broker = new BrokerServer(config = config,
+      metaProps = new MetaProperties(clusterId, config.nodeId),
+      raftManager = raftManager,
+      time = time,
+      metrics = new Metrics(),
+      threadNamePrefix = Some("Broker%02d_".format(config.nodeId)),
+      initialOfflineDirs = Seq(),
+      controllerQuorumVotersFuture = controllerQuorumVotersFuture,
+      supportedFeatures = Collections.emptyMap())
+    broker.startup()
+    broker
+  }
+
+  override def shutdown(): Unit = {
+    CoreUtils.swallow(raftManager.shutdown(), log)
+    CoreUtils.swallow(controllerServer.shutdown(), log)
+  }
+}
+
+@Tag("integration")
+abstract class QuorumTestHarness extends Logging {
+  val zkConnectionTimeout = 10000
+  val zkSessionTimeout = 15000 // Allows us to avoid ZK session expiration due to GC up to 2/3 * 15000ms = 10 secs
+  val zkMaxInFlightRequests = Int.MaxValue
+
+  protected def zkAclsEnabled: Option[Boolean] = None
+
+  /**
+   * When in KRaft mode, the security protocol to use for the controller listener.
+   * Can be overridden by subclasses.
+   */
+  protected def controllerListenerSecurityProtocol: SecurityProtocol = SecurityProtocol.PLAINTEXT
+
+  protected def kraftControllerConfigs(): Seq[Properties] = {
+    Seq(new Properties())
+  }
+
+  private var implementation: QuorumImplementation = null
+
+  def isKRaftTest(): Boolean = implementation.isInstanceOf[KRaftQuorumImplementation]
+
+  def checkIsZKTest(): Unit = {
+    if (isKRaftTest()) {
+      throw new RuntimeException("This function can't be accessed when running the test " +
+        "in KRaft mode. ZooKeeper mode is required.")
+    }
+  }
+
+  def checkIsKRaftTest(): Unit = {
+    if (!isKRaftTest()) {
+      throw new RuntimeException("This function can't be accessed when running the test " +
+        "in ZooKeeper mode. KRaft mode is required.")
+    }
+  }
+
+  private def asZk(): ZooKeeperQuorumImplementation = {
+    checkIsZKTest()
+    implementation.asInstanceOf[ZooKeeperQuorumImplementation]
+  }
+
+  private def asKRaft(): KRaftQuorumImplementation = {
+    checkIsKRaftTest()
+    implementation.asInstanceOf[KRaftQuorumImplementation]
+  }
+
+  def zookeeper: EmbeddedZookeeper = asZk().zookeeper
+
+  def zkClient: KafkaZkClient = asZk().zkClient
+
+  def zkClientOrNull: KafkaZkClient = if (isKRaftTest()) null else asZk().zkClient
+
+  def adminZkClient: AdminZkClient = asZk().adminZkClient
+
+  def zkPort: Int = asZk().zookeeper.port
+
+  def zkConnect: String = s"127.0.0.1:$zkPort"
+
+  def zkConnectOrNull: String = if (isKRaftTest()) null else s"127.0.0.1:$zkPort"
+
+  def controllerServer: ControllerServer = asKRaft().controllerServer
+
+  @BeforeEach
+  def setUp(testInfo: TestInfo): Unit = {
+    val name = if (testInfo.getTestMethod().isPresent()) {
+      testInfo.getTestMethod().get().toString()
+    } else {
+      "[unspecified]"
+    }
+    if (TestInfoUtils.isKRaft(testInfo)) {
+      info(s"Running KRAFT test ${name}")
+      implementation = newKRaftQuorum(testInfo)
+    } else {
+      info(s"Running ZK test ${name}")
+      implementation = newZooKeeperQuorum()
+    }
+  }
+
+  def createAndStartBroker(config: KafkaConfig,
+                           time: Time = Time.SYSTEM): KafkaBroker = {
+    implementation.createAndStartBroker(config,
+      time)
+  }
+
+  def shutdownZooKeeper(): Unit = asZk().shutdownZooKeeper()
+
+  private def formatDirectories(directories: immutable.Seq[String],
+                                metaProperties: MetaProperties): Unit = {
+    val stream = new ByteArrayOutputStream()
+    var out: PrintStream = null
+    try {
+      out = new PrintStream(stream)
+      if (StorageTool.formatCommand(out, directories, metaProperties, false) != 0) {
+        throw new RuntimeException(out.toString())
+      }
+      debug(s"Formatted storage directory(ies) ${directories}")
+    } finally {
+      if (out != null) out.close()
+      stream.close()
+    }
+  }
+
+  private def newKRaftQuorum(testInfo: TestInfo): KRaftQuorumImplementation = {
+    val clusterId = Uuid.randomUuid().toString
+    val metadataDir = TestUtils.tempDir()
+    val metaProperties = new MetaProperties(clusterId, 0)
+    formatDirectories(immutable.Seq(metadataDir.getAbsolutePath()), metaProperties)
+    val controllerMetrics = new Metrics()
+    val propsList = kraftControllerConfigs()
+    if (propsList.size != 1) {
+      throw new RuntimeException("Only one KRaft controller is supported for now.")
+    }
+    val props = propsList(0)
+    props.setProperty(KafkaConfig.ProcessRolesProp, "controller")
+    props.setProperty(KafkaConfig.NodeIdProp, "1000")
+    props.setProperty(KafkaConfig.MetadataLogDirProp, metadataDir.getAbsolutePath())
+    val proto = controllerListenerSecurityProtocol.toString()
+    props.setProperty(KafkaConfig.ListenerSecurityProtocolMapProp, s"${proto}:${proto}")
+    props.setProperty(KafkaConfig.ListenersProp, s"${proto}://localhost:0")
+    props.setProperty(KafkaConfig.ControllerListenerNamesProp, proto)
+    props.setProperty(KafkaConfig.QuorumVotersProp, "1000@localhost:0")
+    val config = new KafkaConfig(props)
+    val threadNamePrefix = "Controller_" + testInfo.getDisplayName
+    val controllerQuorumVotersFuture = new CompletableFuture[util.Map[Integer, AddressSpec]]
+    val raftManager = new KafkaRaftManager(
+      metaProperties = metaProperties,
+      config = config,
+      recordSerde = MetadataRecordSerde.INSTANCE,
+      topicPartition = new TopicPartition(KafkaRaftServer.MetadataTopic, 0),
+      topicId = KafkaRaftServer.MetadataTopicId,
+      time = Time.SYSTEM,
+      metrics = controllerMetrics,
+      threadNamePrefixOpt = Option(threadNamePrefix),
+      controllerQuorumVotersFuture = controllerQuorumVotersFuture)
+    var controllerServer: ControllerServer = null
+    try {
+      controllerServer = new ControllerServer(
+        metaProperties = metaProperties,
+        config = config,
+        raftManager = raftManager,
+        time = Time.SYSTEM,
+        metrics = controllerMetrics,
+        threadNamePrefix = Option(threadNamePrefix),
+        controllerQuorumVotersFuture = controllerQuorumVotersFuture)
+      controllerServer.socketServerFirstBoundPortFuture.whenComplete((port, e) => {
+        if (e != null) {
+          error("Error completing controller socket server future", e)
+          controllerQuorumVotersFuture.completeExceptionally(e)
+        } else {
+          controllerQuorumVotersFuture.complete(Collections.singletonMap(1000,
+            new InetAddressSpec(new InetSocketAddress("localhost", port))));

Review comment:
       nit: unneeded semicolons here and below




-- 
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: jira-unsubscribe@kafka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [kafka] cmccabe edited a comment on pull request #11417: KAFKA-13340: Change ZooKeeperTestHarness to QuorumTestHarness

Posted by GitBox <gi...@apache.org>.
cmccabe edited a comment on pull request #11417:
URL: https://github.com/apache/kafka/pull/11417#issuecomment-952366646


   > The patch seems ok. I confess it's not obvious to me what this approach buys us over the use of ClusterTestExtensions. Seems like another way we could do this is to let QuorumTestHarness make use of ClusterTestExtensions instead of duplicating all the logic to build the cluster. That would still let us make minor modifications to the extensions in order to enable it. As it is, we're left with two separate approaches for covering kraft and zk which seems less than ideal. It might be fine, but it would be nice to understand what was the gap with ClusterTestExtensions and whether we should fix it.
   
   I did consider reusing one of the other test frameworks, but there just isn't a lot to be gained because of the radically different approach that existing tests take. The code for creating the `BrokerServer` / `ControllerServer` is actually a VERY tiny part of this PR... the majority of the PR is integrating with stuff like the `@BeforeEach` functions in each test, handling the way the control flow bounces around the inheritance hierarchy, etc.
   
   The goal here is to be able to convert existing tests without rewriting them. I have actually done this for about a dozen tests, which I haven't posted here since this PR is big enough. I think this is the only approach that will get us over the finish line for kraft. The effort to move to a saner test structure, not based on N levels of inheritance (which partially duplicate each others' functionality), is a great goal but I think we should pursue it for NEW tests rather than existing.


-- 
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: jira-unsubscribe@kafka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [kafka] cmccabe commented on pull request #11417: KAFKA-13340: Change ZooKeeperTestHarness to QuorumTestHarness

Posted by GitBox <gi...@apache.org>.
cmccabe commented on pull request #11417:
URL: https://github.com/apache/kafka/pull/11417#issuecomment-952366646


   > The patch seems ok. I confess it's not obvious to me what this approach buys us over the use of ClusterTestExtensions. Seems like another way we could do this is to let QuorumTestHarness make use of ClusterTestExtensions instead of duplicating all the logic to build the cluster. That would still let us make minor modifications to the extensions in order to enable it. As it is, we're left with two separate approaches for covering kraft and zk which seems less than ideal. It might be fine, but it would be nice to understand what was the gap with ClusterTestExtensions and whether we should fix it.
   
   I did consider reusing one of the other test frameworks, but there just isn't a lot to be gained because of the radically different approach that existing tests take. The code for creating the `BrokerServer` / `ControllerServer` is actually a VERY tiny part of this PR... the majority of the PR is integrating with stuff like the `@BeforeEach` functions in each test, handling the way the control flow bounces around the inheritance hierarchy, etc.
   
   The goal here is to be able to convert existing tests without rewriting them. I have actually done this for about a dozen tests, which I haven't posted here since this PR is big enough. I think this is the only approach that will get us over the finish line for kraft. The effort to move to a saner test structure, not based on N levels of inheritance (which partially duplicate each others' functionality), is a noble goal, but I think it has to be a separate goal if we want to succeed.


-- 
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: jira-unsubscribe@kafka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [kafka] cmccabe merged pull request #11417: KAFKA-13340: Change ZooKeeperTestHarness to QuorumTestHarness

Posted by GitBox <gi...@apache.org>.
cmccabe merged pull request #11417:
URL: https://github.com/apache/kafka/pull/11417


   


-- 
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: jira-unsubscribe@kafka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [kafka] cmccabe commented on a change in pull request #11417: KAFKA-13340: Change ZooKeeperTestHarness to QuorumTestHarness

Posted by GitBox <gi...@apache.org>.
cmccabe commented on a change in pull request #11417:
URL: https://github.com/apache/kafka/pull/11417#discussion_r736953818



##########
File path: core/src/test/scala/integration/kafka/server/QuorumTestHarness.scala
##########
@@ -0,0 +1,339 @@
+/**
+ * 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.server
+
+import java.io.{ByteArrayOutputStream, File, PrintStream}
+import java.net.InetSocketAddress
+import java.util
+import java.util.{Collections, Properties}
+import java.util.concurrent.CompletableFuture
+
+import javax.security.auth.login.Configuration
+import kafka.raft.KafkaRaftManager
+import kafka.tools.StorageTool
+import kafka.utils.{CoreUtils, Logging, TestInfoUtils, TestUtils}
+import kafka.zk.{AdminZkClient, EmbeddedZookeeper, KafkaZkClient}
+import org.apache.kafka.common.metrics.Metrics
+import org.apache.kafka.common.{TopicPartition, Uuid}
+import org.apache.kafka.common.security.JaasUtils
+import org.apache.kafka.common.security.auth.SecurityProtocol
+import org.apache.kafka.common.utils.Time
+import org.apache.kafka.metadata.MetadataRecordSerde
+import org.apache.kafka.raft.RaftConfig.{AddressSpec, InetAddressSpec}
+import org.apache.kafka.server.common.ApiMessageAndVersion
+import org.apache.zookeeper.client.ZKClientConfig
+import org.apache.zookeeper.{WatchedEvent, Watcher, ZooKeeper}
+import org.junit.jupiter.api.Assertions._
+import org.junit.jupiter.api.{AfterAll, AfterEach, BeforeAll, BeforeEach, Tag, TestInfo}
+
+import scala.collection.{Seq, immutable}
+
+trait QuorumImplementation {
+  def createAndStartBroker(config: KafkaConfig,
+                           time: Time): KafkaBroker
+
+  def shutdown(): Unit
+}
+
+class ZooKeeperQuorumImplementation(val zookeeper: EmbeddedZookeeper,
+                                    val zkClient: KafkaZkClient,
+                                    val adminZkClient: AdminZkClient,
+                                    val log: Logging) extends QuorumImplementation {
+  override def createAndStartBroker(config: KafkaConfig,
+                                    time: Time): KafkaBroker = {
+    val server = new KafkaServer(config, time, None, false)
+    server.startup()
+    server
+  }
+
+  override def shutdown(): Unit = {
+    CoreUtils.swallow(zkClient.close(), log)
+    CoreUtils.swallow(zookeeper.shutdown(), log)
+  }
+
+  def shutdownZooKeeper(): Unit = {
+    CoreUtils.swallow(zookeeper.shutdown(), log)
+  }
+}
+
+class KRaftQuorumImplementation(val raftManager: KafkaRaftManager[ApiMessageAndVersion],
+                                val controllerServer: ControllerServer,
+                                val metadataDir: File,
+                                val controllerQuorumVotersFuture: CompletableFuture[util.Map[Integer, AddressSpec]],
+                                val clusterId: String,
+                                val log: Logging) extends QuorumImplementation {
+  override def createAndStartBroker(config: KafkaConfig,
+                                    time: Time): KafkaBroker = {
+    val broker = new BrokerServer(config = config,
+      metaProps = new MetaProperties(clusterId, config.nodeId),
+      raftManager = raftManager,
+      time = time,
+      metrics = new Metrics(),
+      threadNamePrefix = Some("Broker%02d_".format(config.nodeId)),
+      initialOfflineDirs = Seq(),
+      controllerQuorumVotersFuture = controllerQuorumVotersFuture,
+      supportedFeatures = Collections.emptyMap())
+    broker.startup()
+    broker
+  }
+
+  override def shutdown(): Unit = {
+    CoreUtils.swallow(raftManager.shutdown(), log)
+    CoreUtils.swallow(controllerServer.shutdown(), log)
+  }
+}
+
+@Tag("integration")
+abstract class QuorumTestHarness extends Logging {
+  val zkConnectionTimeout = 10000
+  val zkSessionTimeout = 15000 // Allows us to avoid ZK session expiration due to GC up to 2/3 * 15000ms = 10 secs
+  val zkMaxInFlightRequests = Int.MaxValue
+
+  protected def zkAclsEnabled: Option[Boolean] = None
+
+  /**
+   * When in KRaft mode, the security protocol to use for the controller listener.
+   * Can be overridden by subclasses.
+   */
+  protected def controllerListenerSecurityProtocol: SecurityProtocol = SecurityProtocol.PLAINTEXT
+
+  protected def kraftControllerConfigs(): Seq[Properties] = {
+    Seq(new Properties())
+  }
+
+  private var implementation: QuorumImplementation = null
+
+  def isKRaftTest(): Boolean = implementation.isInstanceOf[KRaftQuorumImplementation]
+
+  def checkIsZKTest(): Unit = {
+    if (isKRaftTest()) {
+      throw new RuntimeException("This function can't be accessed when running the test " +
+        "in KRaft mode. ZooKeeper mode is required.")
+    }
+  }
+
+  def checkIsKRaftTest(): Unit = {
+    if (!isKRaftTest()) {
+      throw new RuntimeException("This function can't be accessed when running the test " +
+        "in ZooKeeper mode. KRaft mode is required.")
+    }
+  }
+
+  private def asZk(): ZooKeeperQuorumImplementation = {
+    checkIsZKTest()
+    implementation.asInstanceOf[ZooKeeperQuorumImplementation]
+  }
+
+  private def asKRaft(): KRaftQuorumImplementation = {
+    checkIsKRaftTest()
+    implementation.asInstanceOf[KRaftQuorumImplementation]
+  }
+
+  def zookeeper: EmbeddedZookeeper = asZk().zookeeper
+
+  def zkClient: KafkaZkClient = asZk().zkClient
+
+  def zkClientOrNull: KafkaZkClient = if (isKRaftTest()) null else asZk().zkClient
+
+  def adminZkClient: AdminZkClient = asZk().adminZkClient
+
+  def zkPort: Int = asZk().zookeeper.port
+
+  def zkConnect: String = s"127.0.0.1:$zkPort"
+
+  def zkConnectOrNull: String = if (isKRaftTest()) null else s"127.0.0.1:$zkPort"
+
+  def controllerServer: ControllerServer = asKRaft().controllerServer
+
+  @BeforeEach
+  def setUp(testInfo: TestInfo): Unit = {
+    val name = if (testInfo.getTestMethod().isPresent()) {
+      testInfo.getTestMethod().get().toString()
+    } else {
+      "[unspecified]"
+    }
+    if (TestInfoUtils.isKRaft(testInfo)) {
+      info(s"Running KRAFT test ${name}")
+      implementation = newKRaftQuorum(testInfo)
+    } else {
+      info(s"Running ZK test ${name}")
+      implementation = newZooKeeperQuorum()
+    }
+  }
+
+  def createAndStartBroker(config: KafkaConfig,
+                           time: Time = Time.SYSTEM): KafkaBroker = {
+    implementation.createAndStartBroker(config,
+      time)
+  }
+
+  def shutdownZooKeeper(): Unit = asZk().shutdownZooKeeper()
+
+  private def formatDirectories(directories: immutable.Seq[String],
+                                metaProperties: MetaProperties): Unit = {
+    val stream = new ByteArrayOutputStream()
+    var out: PrintStream = null
+    try {
+      out = new PrintStream(stream)
+      if (StorageTool.formatCommand(out, directories, metaProperties, false) != 0) {
+        throw new RuntimeException(out.toString())
+      }
+      debug(s"Formatted storage directory(ies) ${directories}")
+    } finally {
+      if (out != null) out.close()
+      stream.close()
+    }
+  }
+
+  private def newKRaftQuorum(testInfo: TestInfo): KRaftQuorumImplementation = {
+    val clusterId = Uuid.randomUuid().toString
+    val metadataDir = TestUtils.tempDir()
+    val metaProperties = new MetaProperties(clusterId, 0)
+    formatDirectories(immutable.Seq(metadataDir.getAbsolutePath()), metaProperties)
+    val controllerMetrics = new Metrics()
+    val propsList = kraftControllerConfigs()
+    if (propsList.size != 1) {
+      throw new RuntimeException("Only one KRaft controller is supported for now.")
+    }
+    val props = propsList(0)
+    props.setProperty(KafkaConfig.ProcessRolesProp, "controller")
+    props.setProperty(KafkaConfig.NodeIdProp, "1000")
+    props.setProperty(KafkaConfig.MetadataLogDirProp, metadataDir.getAbsolutePath())
+    val proto = controllerListenerSecurityProtocol.toString()
+    props.setProperty(KafkaConfig.ListenerSecurityProtocolMapProp, s"${proto}:${proto}")
+    props.setProperty(KafkaConfig.ListenersProp, s"${proto}://localhost:0")
+    props.setProperty(KafkaConfig.ControllerListenerNamesProp, proto)
+    props.setProperty(KafkaConfig.QuorumVotersProp, "1000@localhost:0")
+    val config = new KafkaConfig(props)
+    val threadNamePrefix = "Controller_" + testInfo.getDisplayName
+    val controllerQuorumVotersFuture = new CompletableFuture[util.Map[Integer, AddressSpec]]
+    val raftManager = new KafkaRaftManager(
+      metaProperties = metaProperties,
+      config = config,
+      recordSerde = MetadataRecordSerde.INSTANCE,
+      topicPartition = new TopicPartition(KafkaRaftServer.MetadataTopic, 0),
+      topicId = KafkaRaftServer.MetadataTopicId,
+      time = Time.SYSTEM,
+      metrics = controllerMetrics,
+      threadNamePrefixOpt = Option(threadNamePrefix),
+      controllerQuorumVotersFuture = controllerQuorumVotersFuture)
+    var controllerServer: ControllerServer = null
+    try {
+      controllerServer = new ControllerServer(
+        metaProperties = metaProperties,
+        config = config,
+        raftManager = raftManager,
+        time = Time.SYSTEM,
+        metrics = controllerMetrics,
+        threadNamePrefix = Option(threadNamePrefix),
+        controllerQuorumVotersFuture = controllerQuorumVotersFuture)
+      controllerServer.socketServerFirstBoundPortFuture.whenComplete((port, e) => {
+        if (e != null) {
+          error("Error completing controller socket server future", e)
+          controllerQuorumVotersFuture.completeExceptionally(e)
+        } else {
+          controllerQuorumVotersFuture.complete(Collections.singletonMap(1000,
+            new InetAddressSpec(new InetSocketAddress("localhost", port))));

Review comment:
       fixed




-- 
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: jira-unsubscribe@kafka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [kafka] soarez commented on a change in pull request #11417: KAFKA-13340: Change ZooKeeperTestHarness to QuorumTestHarness

Posted by GitBox <gi...@apache.org>.
soarez commented on a change in pull request #11417:
URL: https://github.com/apache/kafka/pull/11417#discussion_r735951119



##########
File path: core/src/test/scala/kafka/utils/TestInfoUtils.scala
##########
@@ -0,0 +1,46 @@
+/**
+ * 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.utils
+
+import java.lang.reflect.Method
+import java.util
+import java.util.{Collections, Optional}
+
+import org.junit.jupiter.api.TestInfo
+
+class EmptyTestInfo extends TestInfo {
+  override def getDisplayName: String = ""
+  override def getTags: util.Set[String] = Collections.emptySet()
+  override def getTestClass: (Optional[Class[_]]) = Optional.empty()
+  override def getTestMethod: Optional[Method] = Optional.empty()
+}
+
+object TestInfoUtils {
+def isKRaft(testInfo: TestInfo): Boolean = {
+  if (testInfo.getDisplayName().contains("quorum=")) {
+    if (testInfo.getDisplayName().contains("quorum=kraft")) {
+      true
+    } else if (testInfo.getDisplayName().contains("quorum=zk")) {
+      false
+    } else {
+      throw new RuntimeException(s"Unknown quorum value")
+    }
+  } else {
+    false
+  }
+}

Review comment:
       Short indent
   
   ```suggestion
     def isKRaft(testInfo: TestInfo): Boolean = {
       if (testInfo.getDisplayName().contains("quorum=")) {
         if (testInfo.getDisplayName().contains("quorum=kraft")) {
           true
         } else if (testInfo.getDisplayName().contains("quorum=zk")) {
           false
         } else {
           throw new RuntimeException(s"Unknown quorum value")
         }
       } else {
         false
       }
     }
   ```

##########
File path: core/src/test/scala/integration/kafka/server/QuorumTestHarness.scala
##########
@@ -0,0 +1,339 @@
+/**
+ * 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.server
+
+import java.io.{ByteArrayOutputStream, File, PrintStream}
+import java.net.InetSocketAddress
+import java.util
+import java.util.{Collections, Properties}
+import java.util.concurrent.CompletableFuture
+
+import javax.security.auth.login.Configuration
+import kafka.raft.KafkaRaftManager
+import kafka.tools.StorageTool
+import kafka.utils.{CoreUtils, Logging, TestInfoUtils, TestUtils}
+import kafka.zk.{AdminZkClient, EmbeddedZookeeper, KafkaZkClient}
+import org.apache.kafka.common.metrics.Metrics
+import org.apache.kafka.common.{TopicPartition, Uuid}
+import org.apache.kafka.common.security.JaasUtils
+import org.apache.kafka.common.security.auth.SecurityProtocol
+import org.apache.kafka.common.utils.Time
+import org.apache.kafka.metadata.MetadataRecordSerde
+import org.apache.kafka.raft.RaftConfig.{AddressSpec, InetAddressSpec}
+import org.apache.kafka.server.common.ApiMessageAndVersion
+import org.apache.zookeeper.client.ZKClientConfig
+import org.apache.zookeeper.{WatchedEvent, Watcher, ZooKeeper}
+import org.junit.jupiter.api.Assertions._
+import org.junit.jupiter.api.{AfterAll, AfterEach, BeforeAll, BeforeEach, Tag, TestInfo}
+
+import scala.collection.{Seq, immutable}
+
+trait QuorumImplementation {
+  def createAndStartBroker(config: KafkaConfig,
+                           time: Time): KafkaBroker
+
+  def shutdown(): Unit
+}
+
+class ZooKeeperQuorumImplementation(val zookeeper: EmbeddedZookeeper,
+                                    val zkClient: KafkaZkClient,
+                                    val adminZkClient: AdminZkClient,
+                                    val log: Logging) extends QuorumImplementation {
+  override def createAndStartBroker(config: KafkaConfig,
+                                    time: Time): KafkaBroker = {
+    val server = new KafkaServer(config, time, None, false)
+    server.startup()
+    server
+  }
+
+  override def shutdown(): Unit = {
+    CoreUtils.swallow(zkClient.close(), log)
+    CoreUtils.swallow(zookeeper.shutdown(), log)
+  }
+
+  def shutdownZooKeeper(): Unit = {
+    CoreUtils.swallow(zookeeper.shutdown(), log)
+  }
+}
+
+class KRaftQuorumImplementation(val raftManager: KafkaRaftManager[ApiMessageAndVersion],
+                                val controllerServer: ControllerServer,
+                                val metadataDir: File,
+                                val controllerQuorumVotersFuture: CompletableFuture[util.Map[Integer, AddressSpec]],
+                                val clusterId: String,
+                                val log: Logging) extends QuorumImplementation {
+  override def createAndStartBroker(config: KafkaConfig,
+                                    time: Time): KafkaBroker = {
+    val broker = new BrokerServer(config = config,
+      metaProps = new MetaProperties(clusterId, config.nodeId),
+      raftManager = raftManager,
+      time = time,
+      metrics = new Metrics(),
+      threadNamePrefix = Some("Broker%02d_".format(config.nodeId)),
+      initialOfflineDirs = Seq(),
+      controllerQuorumVotersFuture = controllerQuorumVotersFuture,
+      supportedFeatures = Collections.emptyMap())
+    broker.startup()
+    broker
+  }
+
+  override def shutdown(): Unit = {
+    CoreUtils.swallow(raftManager.shutdown(), log)
+    CoreUtils.swallow(controllerServer.shutdown(), log)
+  }
+}
+
+@Tag("integration")
+abstract class QuorumTestHarness extends Logging {
+  val zkConnectionTimeout = 10000
+  val zkSessionTimeout = 15000 // Allows us to avoid ZK session expiration due to GC up to 2/3 * 15000ms = 10 secs
+  val zkMaxInFlightRequests = Int.MaxValue
+
+  protected def zkAclsEnabled: Option[Boolean] = None
+
+  /**
+   * When in KRaft mode, the security protocol to use for the controller listener.
+   * Can be overridden by subclasses.
+   */
+  protected def controllerListenerSecurityProtocol: SecurityProtocol = SecurityProtocol.PLAINTEXT
+
+  protected def kraftControllerConfigs(): Seq[Properties] = {
+    Seq(new Properties())
+  }
+
+  private var implementation: QuorumImplementation = null
+
+  def isKRaftTest(): Boolean = implementation.isInstanceOf[KRaftQuorumImplementation]
+
+  def checkIsZKTest(): Unit = {
+    if (isKRaftTest()) {
+      throw new RuntimeException("This function can't be accessed when running the test " +
+        "in KRaft mode. ZooKeeper mode is required.")
+    }
+  }
+
+  def checkIsKRaftTest(): Unit = {
+    if (!isKRaftTest()) {
+      throw new RuntimeException("This function can't be accessed when running the test " +
+        "in ZooKeeper mode. KRaft mode is required.")
+    }
+  }
+
+  private def asZk(): ZooKeeperQuorumImplementation = {
+    checkIsZKTest()
+    implementation.asInstanceOf[ZooKeeperQuorumImplementation]
+  }
+
+  private def asKRaft(): KRaftQuorumImplementation = {
+    checkIsKRaftTest()
+    implementation.asInstanceOf[KRaftQuorumImplementation]
+  }
+
+  def zookeeper: EmbeddedZookeeper = asZk().zookeeper
+
+  def zkClient: KafkaZkClient = asZk().zkClient
+
+  def zkClientOrNull: KafkaZkClient = if (isKRaftTest()) null else asZk().zkClient
+
+  def adminZkClient: AdminZkClient = asZk().adminZkClient
+
+  def zkPort: Int = asZk().zookeeper.port
+
+  def zkConnect: String = s"127.0.0.1:$zkPort"
+
+  def zkConnectOrNull: String = if (isKRaftTest()) null else s"127.0.0.1:$zkPort"
+
+  def controllerServer: ControllerServer = asKRaft().controllerServer
+
+  @BeforeEach
+  def setUp(testInfo: TestInfo): Unit = {
+    val name = if (testInfo.getTestMethod().isPresent()) {
+      testInfo.getTestMethod().get().toString()
+    } else {
+      "[unspecified]"
+    }
+    if (TestInfoUtils.isKRaft(testInfo)) {
+      info(s"Running KRAFT test ${name}")
+      implementation = newKRaftQuorum(testInfo)
+    } else {
+      info(s"Running ZK test ${name}")
+      implementation = newZooKeeperQuorum()
+    }
+  }
+
+  def createAndStartBroker(config: KafkaConfig,
+                           time: Time = Time.SYSTEM): KafkaBroker = {
+    implementation.createAndStartBroker(config,
+      time)
+  }
+
+  def shutdownZooKeeper(): Unit = asZk().shutdownZooKeeper()
+
+  private def formatDirectories(directories: immutable.Seq[String],
+                                metaProperties: MetaProperties): Unit = {
+    val stream = new ByteArrayOutputStream()
+    var out: PrintStream = null
+    try {
+      out = new PrintStream(stream)
+      if (StorageTool.formatCommand(out, directories, metaProperties, false) != 0) {
+        throw new RuntimeException(out.toString())

Review comment:
       Wrong variable
   
   ```suggestion
           throw new RuntimeException(stream.toString())
   ```

##########
File path: core/src/test/scala/integration/kafka/server/QuorumTestHarness.scala
##########
@@ -0,0 +1,339 @@
+/**
+ * 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.server
+
+import java.io.{ByteArrayOutputStream, File, PrintStream}
+import java.net.InetSocketAddress
+import java.util
+import java.util.{Collections, Properties}
+import java.util.concurrent.CompletableFuture
+
+import javax.security.auth.login.Configuration
+import kafka.raft.KafkaRaftManager
+import kafka.tools.StorageTool
+import kafka.utils.{CoreUtils, Logging, TestInfoUtils, TestUtils}
+import kafka.zk.{AdminZkClient, EmbeddedZookeeper, KafkaZkClient}
+import org.apache.kafka.common.metrics.Metrics
+import org.apache.kafka.common.{TopicPartition, Uuid}
+import org.apache.kafka.common.security.JaasUtils
+import org.apache.kafka.common.security.auth.SecurityProtocol
+import org.apache.kafka.common.utils.Time
+import org.apache.kafka.metadata.MetadataRecordSerde
+import org.apache.kafka.raft.RaftConfig.{AddressSpec, InetAddressSpec}
+import org.apache.kafka.server.common.ApiMessageAndVersion
+import org.apache.zookeeper.client.ZKClientConfig
+import org.apache.zookeeper.{WatchedEvent, Watcher, ZooKeeper}
+import org.junit.jupiter.api.Assertions._
+import org.junit.jupiter.api.{AfterAll, AfterEach, BeforeAll, BeforeEach, Tag, TestInfo}
+
+import scala.collection.{Seq, immutable}
+
+trait QuorumImplementation {
+  def createAndStartBroker(config: KafkaConfig,
+                           time: Time): KafkaBroker
+
+  def shutdown(): Unit
+}
+
+class ZooKeeperQuorumImplementation(val zookeeper: EmbeddedZookeeper,
+                                    val zkClient: KafkaZkClient,
+                                    val adminZkClient: AdminZkClient,
+                                    val log: Logging) extends QuorumImplementation {
+  override def createAndStartBroker(config: KafkaConfig,
+                                    time: Time): KafkaBroker = {
+    val server = new KafkaServer(config, time, None, false)
+    server.startup()
+    server
+  }
+
+  override def shutdown(): Unit = {
+    CoreUtils.swallow(zkClient.close(), log)
+    CoreUtils.swallow(zookeeper.shutdown(), log)
+  }
+
+  def shutdownZooKeeper(): Unit = {
+    CoreUtils.swallow(zookeeper.shutdown(), log)
+  }
+}
+
+class KRaftQuorumImplementation(val raftManager: KafkaRaftManager[ApiMessageAndVersion],
+                                val controllerServer: ControllerServer,
+                                val metadataDir: File,
+                                val controllerQuorumVotersFuture: CompletableFuture[util.Map[Integer, AddressSpec]],
+                                val clusterId: String,
+                                val log: Logging) extends QuorumImplementation {
+  override def createAndStartBroker(config: KafkaConfig,
+                                    time: Time): KafkaBroker = {
+    val broker = new BrokerServer(config = config,
+      metaProps = new MetaProperties(clusterId, config.nodeId),
+      raftManager = raftManager,
+      time = time,
+      metrics = new Metrics(),
+      threadNamePrefix = Some("Broker%02d_".format(config.nodeId)),
+      initialOfflineDirs = Seq(),
+      controllerQuorumVotersFuture = controllerQuorumVotersFuture,
+      supportedFeatures = Collections.emptyMap())
+    broker.startup()
+    broker
+  }
+
+  override def shutdown(): Unit = {
+    CoreUtils.swallow(raftManager.shutdown(), log)
+    CoreUtils.swallow(controllerServer.shutdown(), log)
+  }
+}
+
+@Tag("integration")
+abstract class QuorumTestHarness extends Logging {
+  val zkConnectionTimeout = 10000
+  val zkSessionTimeout = 15000 // Allows us to avoid ZK session expiration due to GC up to 2/3 * 15000ms = 10 secs
+  val zkMaxInFlightRequests = Int.MaxValue
+
+  protected def zkAclsEnabled: Option[Boolean] = None
+
+  /**
+   * When in KRaft mode, the security protocol to use for the controller listener.
+   * Can be overridden by subclasses.
+   */
+  protected def controllerListenerSecurityProtocol: SecurityProtocol = SecurityProtocol.PLAINTEXT
+
+  protected def kraftControllerConfigs(): Seq[Properties] = {
+    Seq(new Properties())
+  }
+
+  private var implementation: QuorumImplementation = null
+
+  def isKRaftTest(): Boolean = implementation.isInstanceOf[KRaftQuorumImplementation]
+
+  def checkIsZKTest(): Unit = {
+    if (isKRaftTest()) {
+      throw new RuntimeException("This function can't be accessed when running the test " +
+        "in KRaft mode. ZooKeeper mode is required.")
+    }
+  }
+
+  def checkIsKRaftTest(): Unit = {
+    if (!isKRaftTest()) {
+      throw new RuntimeException("This function can't be accessed when running the test " +
+        "in ZooKeeper mode. KRaft mode is required.")
+    }
+  }
+
+  private def asZk(): ZooKeeperQuorumImplementation = {
+    checkIsZKTest()
+    implementation.asInstanceOf[ZooKeeperQuorumImplementation]
+  }
+
+  private def asKRaft(): KRaftQuorumImplementation = {
+    checkIsKRaftTest()
+    implementation.asInstanceOf[KRaftQuorumImplementation]
+  }
+
+  def zookeeper: EmbeddedZookeeper = asZk().zookeeper
+
+  def zkClient: KafkaZkClient = asZk().zkClient
+
+  def zkClientOrNull: KafkaZkClient = if (isKRaftTest()) null else asZk().zkClient
+
+  def adminZkClient: AdminZkClient = asZk().adminZkClient
+
+  def zkPort: Int = asZk().zookeeper.port
+
+  def zkConnect: String = s"127.0.0.1:$zkPort"
+
+  def zkConnectOrNull: String = if (isKRaftTest()) null else s"127.0.0.1:$zkPort"

Review comment:
       ```suggestion
     def zkConnectOrNull: String = if (isKRaftTest()) null else zkConnect
   ```




-- 
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: jira-unsubscribe@kafka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



[GitHub] [kafka] cmccabe commented on pull request #11417: KAFKA-13340: Change ZooKeeperTestHarness to QuorumTestHarness

Posted by GitBox <gi...@apache.org>.
cmccabe commented on pull request #11417:
URL: https://github.com/apache/kafka/pull/11417#issuecomment-953409706


   I had to fix a bug where ServerShutdownTest was hanging because we didn't call `zkClient#close`. This was causing Jenkins test runs to go off the rails. Hopefully the next test run will be good.


-- 
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: jira-unsubscribe@kafka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org