From 26b1a53a3fd4c0b0a74d152e85cf95d6bcbec1e2 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Thu, 20 Nov 2014 10:22:15 -0800 Subject: [PATCH 1/2] KAFKA-1070. Auto-assign node id. --- .../kafka/common/GenerateBrokerIdException.scala | 25 ++++ .../common/InconsistentBrokerIdException.scala | 25 ++++ core/src/main/scala/kafka/server/KafkaConfig.scala | 23 +++- core/src/main/scala/kafka/server/KafkaServer.scala | 114 ++++++++++++++-- core/src/main/scala/kafka/utils/ZkUtils.scala | 38 +++++- .../kafka/server/ServerGenerateBrokerIdTest.scala | 148 +++++++++++++++++++++ .../test/scala/unit/kafka/utils/TestUtils.scala | 9 +- 7 files changed, 362 insertions(+), 20 deletions(-) create mode 100644 core/src/main/scala/kafka/common/GenerateBrokerIdException.scala create mode 100644 core/src/main/scala/kafka/common/InconsistentBrokerIdException.scala create mode 100644 core/src/test/scala/unit/kafka/server/ServerGenerateBrokerIdTest.scala diff --git a/core/src/main/scala/kafka/common/GenerateBrokerIdException.scala b/core/src/main/scala/kafka/common/GenerateBrokerIdException.scala new file mode 100644 index 0000000..6fbbef7 --- /dev/null +++ b/core/src/main/scala/kafka/common/GenerateBrokerIdException.scala @@ -0,0 +1,25 @@ +/** + * 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.common + +/** + * Indicates the brokerId stored in logDirs is not consistent acorss logDirs. + */ +class GenerateBrokerIdException(message: String) extends RuntimeException(message) { + def this() = this(null) +} diff --git a/core/src/main/scala/kafka/common/InconsistentBrokerIdException.scala b/core/src/main/scala/kafka/common/InconsistentBrokerIdException.scala new file mode 100644 index 0000000..fe0c475 --- /dev/null +++ b/core/src/main/scala/kafka/common/InconsistentBrokerIdException.scala @@ -0,0 +1,25 @@ +/** + * 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.common + +/** + * Indicates the brokerId stored in logDirs is not consistent acorss logDirs. + */ +class InconsistentBrokerIdException(message: String) extends RuntimeException(message) { + def this() = this(null) +} diff --git a/core/src/main/scala/kafka/server/KafkaConfig.scala b/core/src/main/scala/kafka/server/KafkaConfig.scala index 6e26c54..f6e7b77 100644 --- a/core/src/main/scala/kafka/server/KafkaConfig.scala +++ b/core/src/main/scala/kafka/server/KafkaConfig.scala @@ -35,13 +35,13 @@ class KafkaConfig private (val props: VerifiableProperties) extends ZKConfig(pro private def getLogRetentionTimeMillis(): Long = { val millisInMinute = 60L * 1000L val millisInHour = 60L * millisInMinute - + if(props.containsKey("log.retention.ms")){ props.getIntInRange("log.retention.ms", (1, Int.MaxValue)) } else if(props.containsKey("log.retention.minutes")){ millisInMinute * props.getIntInRange("log.retention.minutes", (1, Int.MaxValue)) - } + } else { millisInHour * props.getIntInRange("log.retention.hours", 24*7, (1, Int.MaxValue)) } @@ -49,7 +49,7 @@ class KafkaConfig private (val props: VerifiableProperties) extends ZKConfig(pro private def getLogRollTimeMillis(): Long = { val millisInHour = 60L * 60L * 1000L - + if(props.containsKey("log.roll.ms")){ props.getIntInRange("log.roll.ms", (1, Int.MaxValue)) } @@ -71,8 +71,17 @@ class KafkaConfig private (val props: VerifiableProperties) extends ZKConfig(pro /*********** General Configuration ***********/ - /* the broker id for this server */ - val brokerId: Int = props.getIntInRange("broker.id", (0, Int.MaxValue)) + /* Max number that can be used for a broker.id */ + val MaxReservedBrokerId = props.getIntInRange("reserved.broker.max.id", 1000, (0, Int.MaxValue)) + + /* the broker id generation policy , must be either "sequence" or "ip" */ + val brokerIdPolicy = props.getString("broker.id.policy", "sequence") + + /* The broker id for this server. + * To avoid conflicts between zookeeper generated brokerId and user's config.brokerId + * added MaxReservedBrokerId and zookeeper sequence starts from MaxReservedBrokerId + 1. + */ + var brokerId: Int = if (props.containsKey("broker.id")) props.getIntInRange("broker.id", (0, MaxReservedBrokerId)) else -1 /* the maximum size of message that the server can receive */ val messageMaxBytes = props.getIntInRange("message.max.bytes", 1000000 + MessageSet.LogOverhead, (0, Int.MaxValue)) @@ -117,10 +126,10 @@ class KafkaConfig private (val props: VerifiableProperties) extends ZKConfig(pro /* the maximum number of bytes in a socket request */ val socketRequestMaxBytes: Int = props.getIntInRange("socket.request.max.bytes", 100*1024*1024, (1, Int.MaxValue)) - + /* the maximum number of connections we allow from each ip address */ val maxConnectionsPerIp: Int = props.getIntInRange("max.connections.per.ip", Int.MaxValue, (1, Int.MaxValue)) - + /* per-ip or hostname overrides to the default maximum number of connections */ val maxConnectionsPerIpOverrides = props.getMap("max.connections.per.ip.overrides").map(entry => (entry._1, entry._2.toInt)) diff --git a/core/src/main/scala/kafka/server/KafkaServer.scala b/core/src/main/scala/kafka/server/KafkaServer.scala index 1bf7d10..6054900 100644 --- a/core/src/main/scala/kafka/server/KafkaServer.scala +++ b/core/src/main/scala/kafka/server/KafkaServer.scala @@ -25,11 +25,16 @@ import kafka.utils._ import java.util.concurrent._ import atomic.{AtomicInteger, AtomicBoolean} import java.io.File +import java.net.BindException +import java.io.FileOutputStream +import java.io.FileNotFoundException +import java.util.Properties +import collection.mutable import org.I0Itec.zkclient.ZkClient import kafka.controller.{ControllerStats, KafkaController} import kafka.cluster.Broker import kafka.api.{ControlledShutdownResponse, ControlledShutdownRequest} -import kafka.common.ErrorMapping +import kafka.common.{ErrorMapping, InconsistentBrokerIdException, GenerateBrokerIdException} import kafka.network.{Receive, BlockingChannel, SocketServer} import kafka.metrics.KafkaMetricsGroup import com.yammer.metrics.core.Gauge @@ -39,10 +44,11 @@ import com.yammer.metrics.core.Gauge * to start up and shutdown a single Kafka node. */ class KafkaServer(val config: KafkaConfig, time: Time = SystemTime) extends Logging with KafkaMetricsGroup { - this.logIdent = "[Kafka Server " + config.brokerId + "], " private var isShuttingDown = new AtomicBoolean(false) private var shutdownLatch = new CountDownLatch(1) private var startupComplete = new AtomicBoolean(false) + private var brokerId: Int = -1 + private var metaPropsFile = "meta.properties" val brokerState: BrokerState = new BrokerState val correlationId: AtomicInteger = new AtomicInteger(0) var socketServer: SocketServer = null @@ -77,7 +83,7 @@ class KafkaServer(val config: KafkaConfig, time: Time = SystemTime) extends Logg /* start scheduler */ kafkaScheduler.startup() - + /* setup zookeeper */ zkClient = initZk() @@ -85,6 +91,10 @@ class KafkaServer(val config: KafkaConfig, time: Time = SystemTime) extends Logg logManager = createLogManager(zkClient, brokerState) logManager.startup() + /* generate brokerId */ + config.brokerId = getBrokerId(zkClient, config) + this.logIdent = "[Kafka Server " + config.brokerId + "], " + socketServer = new SocketServer(config.brokerId, config.hostName, config.port, @@ -103,26 +113,25 @@ class KafkaServer(val config: KafkaConfig, time: Time = SystemTime) extends Logg offsetManager = createOffsetManager() kafkaController = new KafkaController(config, zkClient, brokerState) - + /* start processing requests */ apis = new KafkaApis(socketServer.requestChannel, replicaManager, offsetManager, zkClient, config.brokerId, config, kafkaController) requestHandlerPool = new KafkaRequestHandlerPool(config.brokerId, socketServer.requestChannel, apis, config.numIoThreads) brokerState.newState(RunningAsBroker) - + Mx4jLoader.maybeLoad() replicaManager.startup() kafkaController.startup() - + topicConfigManager = new TopicConfigManager(zkClient, logManager) topicConfigManager.startup() - + /* tell everyone we are alive */ kafkaHealthcheck = new KafkaHealthcheck(config.brokerId, config.advertisedHostName, config.advertisedPort, config.zkSessionTimeoutMs, zkClient) kafkaHealthcheck.startup() - registerStats() startupComplete.set(true) info("started") @@ -306,7 +315,7 @@ class KafkaServer(val config: KafkaConfig, time: Time = SystemTime) extends Logg def awaitShutdown(): Unit = shutdownLatch.await() def getLogManager(): LogManager = logManager - + private def createLogManager(zkClient: ZkClient, brokerState: BrokerState): LogManager = { val defaultLogConfig = LogConfig(segmentSize = config.logSegmentBytes, segmentMs = config.logRollTimeMillis, @@ -358,5 +367,90 @@ class KafkaServer(val config: KafkaConfig, time: Time = SystemTime) extends Logg new OffsetManager(offsetManagerConfig, replicaManager, zkClient, kafkaScheduler) } -} + /** + * if kafka server config has brokerId and there is no meta.properties file returns the config.brokerId, + * generates a broker id based on broker.id.policy + * stores the generated broker id in meta.properties under logDirs specified in config. + * if config has brokerId and meta.properties contains brokerId if they don't match throws InconsistentBrokerIdException + */ + private def getBrokerId(zkClient: ZkClient, config: KafkaConfig): Int = { + var brokerId = config.brokerId + var logDirsWithoutMetaProps: List[String] = List() + val metaBrokerIdSet = mutable.HashSet[Int]() + + for (logDir <- config.logDirs) { + val metaBrokerIdOpt = readBrokerIdFromMetaProps(logDir) + metaBrokerIdOpt match { + case Some(metaBrokerId) => + metaBrokerIdSet.add(metaBrokerId) + case None => + logDirsWithoutMetaProps ++= List(logDir) + } + + } + + if(metaBrokerIdSet.size > 1) { + throw new InconsistentBrokerIdException("failed to match brokerId across logDirs") + } else if(brokerId >= 0 && metaBrokerIdSet.size == 1 && metaBrokerIdSet.last != brokerId) { + throw new InconsistentBrokerIdException("configured brokerId doesn't match stored brokerId in meta.properties") + } else if(metaBrokerIdSet.size == 0) { + if(brokerId < 0) { + brokerId = generateBrokerId(config) + } else { + return brokerId + } + } else { + brokerId = metaBrokerIdSet.last + } + + if(!logDirsWithoutMetaProps.isEmpty) + storeBrokerId(brokerId, logDirsWithoutMetaProps) + return brokerId + } + + private def generateBrokerId(config: KafkaConfig): Int = { + try { + config.brokerIdPolicy.trim.toLowerCase match { + case "ip" => + Utils.ipToInt(config.hostName) + case _ => + ZkUtils.getBrokerSequenceId(zkClient,config.MaxReservedBrokerId) + } + } catch { + case e: Exception => + error("failed to generate broker.id due to %s".format(e.getMessage)) + throw new GenerateBrokerIdException("failed to generate broker.id") + } + } + + private def readBrokerIdFromMetaProps(logDir: String): Option[Int] = { + try { + val metaProps = new VerifiableProperties(Utils.loadProps(logDir + File.separator + metaPropsFile)) + if (metaProps.containsKey("broker.id")) + return Some(metaProps.getIntInRange("broker.id", (0, Int.MaxValue))) + } catch { + case e: FileNotFoundException => + warn("failed to read meta.properties file under dir %s due to %s".format(logDir, e.getMessage)) + None + case e1: Exception => + error("failed to read meta.properties file under dir %s due to %s".format(logDir, e1.getMessage)) + throw e1 + } + None + } + + private def storeBrokerId(brokerId: Int, logDirs: Seq[String]) { + val metaProps = new Properties() + metaProps.setProperty("broker.id", brokerId.toString); + for(logDir <- logDirs) { + val f = Utils.createFile(logDir + File.separator + metaPropsFile) + val out = new FileOutputStream(f) + metaProps.store(out,"") + out.flush() + out.getFD().sync(); + out.close(); + } + } + +} diff --git a/core/src/main/scala/kafka/utils/ZkUtils.scala b/core/src/main/scala/kafka/utils/ZkUtils.scala index 56e3e88..c14bd45 100644 --- a/core/src/main/scala/kafka/utils/ZkUtils.scala +++ b/core/src/main/scala/kafka/utils/ZkUtils.scala @@ -46,6 +46,7 @@ object ZkUtils extends Logging { val ReassignPartitionsPath = "/admin/reassign_partitions" val DeleteTopicsPath = "/admin/delete_topics" val PreferredReplicaLeaderElectionPath = "/admin/preferred_replica_election" + val BrokerSequenceIdPath = "/brokers/seqid" def getTopicPath(topic: String): String = { BrokerTopicsPath + "/" + topic @@ -87,7 +88,8 @@ object ZkUtils extends Logging { } def setupCommonPaths(zkClient: ZkClient) { - for(path <- Seq(ConsumersPath, BrokerIdsPath, BrokerTopicsPath, TopicConfigChangesPath, TopicConfigPath, DeleteTopicsPath)) + for(path <- Seq(ConsumersPath, BrokerIdsPath, BrokerTopicsPath, TopicConfigChangesPath, TopicConfigPath, + DeleteTopicsPath, BrokerSequenceIdPath)) makeSurePersistentPathExists(zkClient, path) } @@ -122,6 +124,14 @@ object ZkUtils extends Logging { } } + /** returns a sequence id generated by updating BrokerSequenceIdPath in Zk. + * users can provide brokerId in the config , inorder to avoid conflicts between zk generated + * seqId and config.brokerId we increment zk seqId by KafkaConfig.MaxReservedBrokerId. + */ + def getBrokerSequenceId(zkClient: ZkClient, MaxReservedBrokerId: Int): Int = { + getSequenceId(zkClient, BrokerSequenceIdPath) + MaxReservedBrokerId + } + /** * Gets the in-sync replicas (ISR) for a specific topic and partition */ @@ -696,6 +706,32 @@ object ZkUtils extends Logging { } } + /** + * This API produces a sequence number by creating / updating given path in zookeeper + * It uses the stat returned by the zookeeper and return the version. Every time + * client updates the path stat.version gets incremented + */ + def getSequenceId(client: ZkClient, path: String): Int = { + try { + val stat = client.writeDataReturnStat(path, "", -1) + return stat.getVersion + } catch { + case e: ZkNoNodeException => { + createParentPath(client, BrokerSequenceIdPath) + try { + client.createPersistent(BrokerSequenceIdPath, "") + return 0 + } catch { + case e: ZkNodeExistsException => + val stat = client.writeDataReturnStat(BrokerSequenceIdPath, "", -1) + return stat.getVersion + case e2: Throwable => throw e2 + } + } + case e2: Throwable => throw e2 + } + } + def getAllTopics(zkClient: ZkClient): Seq[String] = { val topics = ZkUtils.getChildrenParentMayNotExist(zkClient, BrokerTopicsPath) if(topics == null) diff --git a/core/src/test/scala/unit/kafka/server/ServerGenerateBrokerIdTest.scala b/core/src/test/scala/unit/kafka/server/ServerGenerateBrokerIdTest.scala new file mode 100644 index 0000000..d41db46 --- /dev/null +++ b/core/src/test/scala/unit/kafka/server/ServerGenerateBrokerIdTest.scala @@ -0,0 +1,148 @@ +/** + * 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 kafka.zk.ZooKeeperTestHarness +import kafka.utils.{IntEncoder, TestUtils, Utils, VerifiableProperties} +import kafka.utils.TestUtils._ +import java.io.File +import org.junit.Test +import org.scalatest.junit.JUnit3Suite +import junit.framework.Assert._ + +class ServerGenerateBrokerIdTest extends JUnit3Suite with ZooKeeperTestHarness { + var props1 = TestUtils.createBrokerConfig(-1, TestUtils.choosePort) + var config1 = new KafkaConfig(props1) + var props2 = TestUtils.createBrokerConfig(0, TestUtils.choosePort) + var config2 = new KafkaConfig(props2) + + + @Test + def testAutoGenerateBrokerId() { + var server1 = new KafkaServer(config1) + server1.startup() + // do a clean shutdown and check that offset checkpoint file exists + server1.shutdown() + for(logDir <- config1.logDirs) { + val metaProps = new VerifiableProperties(Utils.loadProps(logDir+"/meta.properties")) + assertTrue(metaProps.containsKey("broker.id")) + assertEquals(metaProps.getInt("broker.id"),1001) + } + // restart the server check to see if it uses the brokerId generated previously + server1 = new KafkaServer(config1) + server1.startup() + assertEquals(server1.config.brokerId, 1001) + server1.shutdown() + Utils.rm(server1.config.logDirs) + TestUtils.verifyNonDaemonThreadsStatus + } + + @Test + def testAutoGenerateBrokerIdWithIPPolicy() { + val props3 = TestUtils.createBrokerConfig(-1, TestUtils.choosePort) + props3.put("broker.id.policy","ip") + val config3 = new KafkaConfig(props3) + var server1 = new KafkaServer(config3) + server1.startup() + // do a clean shutdown and check that offset checkpoint file exists + server1.shutdown() + for(logDir <- config3.logDirs) { + val metaProps = new VerifiableProperties(Utils.loadProps(logDir + File.separator + "meta.properties")) + assertTrue(metaProps.containsKey("broker.id")) + assertEquals(metaProps.getInt("broker.id"),Utils.ipToInt(config3.hostName)) + } + // restart the server check to see if it uses the brokerId generated previously + server1 = new KafkaServer(config3) + server1.startup() + assertEquals(server1.config.brokerId, Utils.ipToInt(config3.hostName)) + server1.shutdown() + Utils.rm(server1.config.logDirs) + TestUtils.verifyNonDaemonThreadsStatus + } + + @Test + def testUserConfigAndGenratedBrokerId() { + // start the server with broker.id as part of config + val server1 = new KafkaServer(config1) + val server2 = new KafkaServer(config2) + val props3 = TestUtils.createBrokerConfig(-1, TestUtils.choosePort) + val config3 = new KafkaConfig(props3) + val server3 = new KafkaServer(config3) + server1.startup() + assertEquals(server1.config.brokerId,1001) + server2.startup() + assertEquals(server2.config.brokerId,0) + server3.startup() + assertEquals(server3.config.brokerId,1002) + server1.shutdown() + server2.shutdown() + server3.shutdown() + Utils.rm(server1.config.logDirs) + Utils.rm(server2.config.logDirs) + TestUtils.verifyNonDaemonThreadsStatus + } + + @Test + def testMultipleLogDirsMetaProps() { + // add multiple logDirs and check if the generate brokerId is stored in all of them + var logDirs = props1.getProperty("log.dir")+ "," + TestUtils.tempDir().getAbsolutePath + + "," + TestUtils.tempDir().getAbsolutePath + props1.setProperty("log.dir",logDirs) + config1 = new KafkaConfig(props1) + var server1 = new KafkaServer(config1) + server1.startup() + server1.shutdown() + for(logDir <- config1.logDirs) { + val metaProps = new VerifiableProperties(Utils.loadProps(logDir+"/meta.properties")) + assertTrue(metaProps.containsKey("broker.id")) + assertEquals(metaProps.getInt("broker.id"),1001) + } + + // addition to log.dirs after generation of a broker.id from zk should be copied over + var newLogDirs = props1.getProperty("log.dir") + "," + TestUtils.tempDir().getAbsolutePath + props1.setProperty("log.dir",newLogDirs) + config1 = new KafkaConfig(props1) + server1 = new KafkaServer(config1) + server1.startup() + server1.shutdown() + for(logDir <- config1.logDirs) { + val metaProps = new VerifiableProperties(Utils.loadProps(logDir+"/meta.properties")) + assertTrue(metaProps.containsKey("broker.id")) + assertEquals(metaProps.getInt("broker.id"),1001) + } + Utils.rm(server1.config.logDirs) + TestUtils.verifyNonDaemonThreadsStatus + } + + @Test + def testConsistentBrokerIdFromUserConfigAndMetaProps() { + // check if configured brokerId and stored brokerId are equal or throw InconsistentBrokerException + var server1 = new KafkaServer(config1) //auto generate broker Id + server1.startup() + server1.shutdown() + server1 = new KafkaServer(config2) // user specified broker id + try { + server1.startup() + } catch { + case e: kafka.common.InconsistentBrokerIdException => //success + } + server1.shutdown() + Utils.rm(server1.config.logDirs) + TestUtils.verifyNonDaemonThreadsStatus + } + +} diff --git a/core/src/test/scala/unit/kafka/utils/TestUtils.scala b/core/src/test/scala/unit/kafka/utils/TestUtils.scala index 0da774d..9b286f5 100644 --- a/core/src/test/scala/unit/kafka/utils/TestUtils.scala +++ b/core/src/test/scala/unit/kafka/utils/TestUtils.scala @@ -94,7 +94,7 @@ object TestUtils extends Logging { Utils.rm(f) } }) - + f } @@ -154,7 +154,7 @@ object TestUtils extends Logging { def createBrokerConfig(nodeId: Int, port: Int = choosePort(), enableControlledShutdown: Boolean = true): Properties = { val props = new Properties - props.put("broker.id", nodeId.toString) + if (nodeId >= 0) props.put("broker.id", nodeId.toString) props.put("host.name", "localhost") props.put("port", port.toString) props.put("log.dir", TestUtils.tempDir().getAbsolutePath) @@ -698,6 +698,11 @@ object TestUtils extends Logging { ZkUtils.pathExists(zkClient, ZkUtils.ReassignPartitionsPath) } + def verifyNonDaemonThreadsStatus() { + assertEquals(0, Thread.getAllStackTraces.keySet().toArray + .map(_.asInstanceOf[Thread]) + .count(t => !t.isDaemon && t.isAlive && t.getClass.getCanonicalName.toLowerCase.startsWith("kafka"))) + } /** * Create new LogManager instance with default configuration for testing -- 1.9.3 (Apple Git-50) From b192c974aa4b9b201c79d69aa59a4af55ea8a39e Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Tue, 25 Nov 2014 19:58:59 -0800 Subject: [PATCH 2/2] KAFKA-1070. Auto-assign node id. --- .../kafka/server/BrokerMetadataFileHandler.scala | 84 ++++++++++++++++ core/src/main/scala/kafka/server/KafkaConfig.scala | 3 - core/src/main/scala/kafka/server/KafkaServer.scala | 111 +++++++-------------- .../kafka/server/ServerGenerateBrokerIdTest.scala | 67 ++++--------- 4 files changed, 142 insertions(+), 123 deletions(-) create mode 100644 core/src/main/scala/kafka/server/BrokerMetadataFileHandler.scala diff --git a/core/src/main/scala/kafka/server/BrokerMetadataFileHandler.scala b/core/src/main/scala/kafka/server/BrokerMetadataFileHandler.scala new file mode 100644 index 0000000..9ac1694 --- /dev/null +++ b/core/src/main/scala/kafka/server/BrokerMetadataFileHandler.scala @@ -0,0 +1,84 @@ +/** + * 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._ +import java.util.Properties +import kafka.utils._ + + +case class BrokerMetadata(brokerId: Int) + +/** + * This class saves broker's metadata to a file + */ +class BrokerMetadataFileHandler() extends Logging { + private val lock = new Object() + private val metaPropsFile = "meta.properties" + + def write(logDirs: Seq[String], brokerMetadata: BrokerMetadata, version: Int = 0) = { + lock synchronized { + try { + version match { + case 0 => + val metaProps = new Properties() + metaProps.setProperty("version", version.toString) + metaProps.setProperty("broker.id", brokerMetadata.brokerId.toString) + for(logDir <- logDirs) { + val f = new File(logDir + File.separator + metaPropsFile) + if (!f.exists) f.createNewFile() + val out = new FileOutputStream(f) + metaProps.store(out,"") + out.flush() + out.getFD().sync() + out.close() + } + case _ => + throw new IllegalArgumentException("Unrecognized version for the server meta.properties file: " + version) + } + } catch { + case ie: IOException => + error("Failed to write meta.properties due to %s".format(ie.getMessage)) + throw ie + } + } + } + + def read(logDir: String): Option[BrokerMetadata] = { + lock synchronized { + try { + val metaProps = new VerifiableProperties(Utils.loadProps(logDir + File.separator + metaPropsFile)) + val version = metaProps.getIntInRange("version", (0, Int.MaxValue)) + version match { + case 0 => + val brokerId = metaProps.getIntInRange("broker.id", (0, Int.MaxValue)) + return Some(BrokerMetadata(brokerId)) + case _ => + throw new IOException("Unrecognized version of the server meta.properties file: " + version) + } + } catch { + case e: FileNotFoundException => + warn("No meta.properties file under dir %s".format(logDir, e.getMessage)) + None + case e1: Exception => + error("Failed to read meta.properties file under dir %s due to %s".format(logDir, e1.getMessage)) + throw e1 + } + } + } +} diff --git a/core/src/main/scala/kafka/server/KafkaConfig.scala b/core/src/main/scala/kafka/server/KafkaConfig.scala index f6e7b77..bbd3fd7 100644 --- a/core/src/main/scala/kafka/server/KafkaConfig.scala +++ b/core/src/main/scala/kafka/server/KafkaConfig.scala @@ -74,9 +74,6 @@ class KafkaConfig private (val props: VerifiableProperties) extends ZKConfig(pro /* Max number that can be used for a broker.id */ val MaxReservedBrokerId = props.getIntInRange("reserved.broker.max.id", 1000, (0, Int.MaxValue)) - /* the broker id generation policy , must be either "sequence" or "ip" */ - val brokerIdPolicy = props.getString("broker.id.policy", "sequence") - /* The broker id for this server. * To avoid conflicts between zookeeper generated brokerId and user's config.brokerId * added MaxReservedBrokerId and zookeeper sequence starts from MaxReservedBrokerId + 1. diff --git a/core/src/main/scala/kafka/server/KafkaServer.scala b/core/src/main/scala/kafka/server/KafkaServer.scala index 6054900..48d358c 100644 --- a/core/src/main/scala/kafka/server/KafkaServer.scala +++ b/core/src/main/scala/kafka/server/KafkaServer.scala @@ -25,10 +25,6 @@ import kafka.utils._ import java.util.concurrent._ import atomic.{AtomicInteger, AtomicBoolean} import java.io.File -import java.net.BindException -import java.io.FileOutputStream -import java.io.FileNotFoundException -import java.util.Properties import collection.mutable import org.I0Itec.zkclient.ZkClient import kafka.controller.{ControllerStats, KafkaController} @@ -48,7 +44,7 @@ class KafkaServer(val config: KafkaConfig, time: Time = SystemTime) extends Logg private var shutdownLatch = new CountDownLatch(1) private var startupComplete = new AtomicBoolean(false) private var brokerId: Int = -1 - private var metaPropsFile = "meta.properties" + val brokerState: BrokerState = new BrokerState val correlationId: AtomicInteger = new AtomicInteger(0) var socketServer: SocketServer = null @@ -92,7 +88,7 @@ class KafkaServer(val config: KafkaConfig, time: Time = SystemTime) extends Logg logManager.startup() /* generate brokerId */ - config.brokerId = getBrokerId(zkClient, config) + config.brokerId = getBrokerId this.logIdent = "[Kafka Server " + config.brokerId + "], " socketServer = new SocketServer(config.brokerId, @@ -189,10 +185,10 @@ class KafkaServer(val config: KafkaConfig, time: Time = SystemTime) extends Logg info("Starting controlled shutdown") var channel : BlockingChannel = null var prevController : Broker = null - var shutdownSuceeded : Boolean = false + var shutdownSucceeded : Boolean = false try { brokerState.newState(PendingControlledShutdown) - while (!shutdownSuceeded && remainingRetries > 0) { + while (!shutdownSucceeded && remainingRetries > 0) { remainingRetries = remainingRetries - 1 // 1. Find the controller and establish a connection to it. @@ -231,7 +227,7 @@ class KafkaServer(val config: KafkaConfig, time: Time = SystemTime) extends Logg val shutdownResponse = ControlledShutdownResponse.readFrom(response.buffer) if (shutdownResponse.errorCode == ErrorMapping.NoError && shutdownResponse.partitionsRemaining != null && shutdownResponse.partitionsRemaining.size == 0) { - shutdownSuceeded = true + shutdownSucceeded = true info ("Controlled shutdown succeeded") } else { @@ -247,7 +243,7 @@ class KafkaServer(val config: KafkaConfig, time: Time = SystemTime) extends Logg // ignore and try again } } - if (!shutdownSuceeded) { + if (!shutdownSucceeded) { Thread.sleep(config.controlledShutdownRetryBackoffMs) warn("Retrying controlled shutdown after the previous attempt failed...") } @@ -259,7 +255,7 @@ class KafkaServer(val config: KafkaConfig, time: Time = SystemTime) extends Logg channel = null } } - if (!shutdownSuceeded) { + if (!shutdownSucceeded) { warn("Proceeding to do an unclean shutdown as all the controlled shutdown attempts failed") } } @@ -368,89 +364,54 @@ class KafkaServer(val config: KafkaConfig, time: Time = SystemTime) extends Logg } /** - * if kafka server config has brokerId and there is no meta.properties file returns the config.brokerId, - * generates a broker id based on broker.id.policy - * stores the generated broker id in meta.properties under logDirs specified in config. - * if config has brokerId and meta.properties contains brokerId if they don't match throws InconsistentBrokerIdException + * Generates new brokerId or reads from meta.properties based on following conditions + *
    + *
  1. config has no broker.id provided , generates a broker.id based on Zookeeper's sequence + *
  2. stored broker.id in meta.properties doesn't match in all the log.dirs throws InconsistentBrokerIdException + *
  3. config has broker.id and meta.properties contains broker.id if they don't match throws InconsistentBrokerIdException + *
  4. config has broker.id and there is no meta.properties file, creates new meta.properties and stores broker.id + *
      + * @returns A brokerId. */ - private def getBrokerId(zkClient: ZkClient, config: KafkaConfig): Int = { + private def getBrokerId: Int = { var brokerId = config.brokerId var logDirsWithoutMetaProps: List[String] = List() - val metaBrokerIdSet = mutable.HashSet[Int]() + val brokerIdSet = mutable.HashSet[Int]() + val brokerMetadataFileHandler = new BrokerMetadataFileHandler() for (logDir <- config.logDirs) { - val metaBrokerIdOpt = readBrokerIdFromMetaProps(logDir) - metaBrokerIdOpt match { - case Some(metaBrokerId) => - metaBrokerIdSet.add(metaBrokerId) + val brokerMetadataOpt = brokerMetadataFileHandler.read(logDir) + brokerMetadataOpt match { + case Some(brokerMetadata: BrokerMetadata) => + brokerIdSet.add(brokerMetadata.brokerId) case None => logDirsWithoutMetaProps ++= List(logDir) } - } - if(metaBrokerIdSet.size > 1) { - throw new InconsistentBrokerIdException("failed to match brokerId across logDirs") - } else if(brokerId >= 0 && metaBrokerIdSet.size == 1 && metaBrokerIdSet.last != brokerId) { - throw new InconsistentBrokerIdException("configured brokerId doesn't match stored brokerId in meta.properties") - } else if(metaBrokerIdSet.size == 0) { - if(brokerId < 0) { - brokerId = generateBrokerId(config) - } else { - return brokerId - } - } else { - brokerId = metaBrokerIdSet.last - } + if(brokerIdSet.size > 1) + throw new InconsistentBrokerIdException("Failed to match brokerId across logDirs") + else if(brokerId >= 0 && brokerIdSet.size == 1 && brokerIdSet.last != brokerId) + throw new InconsistentBrokerIdException("Configured brokerId doesn't match stored brokerId in meta.properties") + else if(brokerIdSet.size == 0 && brokerId < 0) // generate a new brokerId from Zookeeper + brokerId = generateBrokerId + else if(brokerIdSet.size == 1) // pick broker.id from meta.properties + brokerId = brokerIdSet.last + if(!logDirsWithoutMetaProps.isEmpty) - storeBrokerId(brokerId, logDirsWithoutMetaProps) + brokerMetadataFileHandler.write(logDirsWithoutMetaProps, BrokerMetadata(brokerId)) return brokerId } - private def generateBrokerId(config: KafkaConfig): Int = { + private def generateBrokerId: Int = { try { - config.brokerIdPolicy.trim.toLowerCase match { - case "ip" => - Utils.ipToInt(config.hostName) - case _ => - ZkUtils.getBrokerSequenceId(zkClient,config.MaxReservedBrokerId) - } + ZkUtils.getBrokerSequenceId(zkClient, config.MaxReservedBrokerId) } catch { case e: Exception => - error("failed to generate broker.id due to %s".format(e.getMessage)) - throw new GenerateBrokerIdException("failed to generate broker.id") + error("Failed to generate broker.id due to %s".format(e.getMessage)) + throw new GenerateBrokerIdException("Failed to generate broker.id") } } - - private def readBrokerIdFromMetaProps(logDir: String): Option[Int] = { - try { - val metaProps = new VerifiableProperties(Utils.loadProps(logDir + File.separator + metaPropsFile)) - if (metaProps.containsKey("broker.id")) - return Some(metaProps.getIntInRange("broker.id", (0, Int.MaxValue))) - } catch { - case e: FileNotFoundException => - warn("failed to read meta.properties file under dir %s due to %s".format(logDir, e.getMessage)) - None - case e1: Exception => - error("failed to read meta.properties file under dir %s due to %s".format(logDir, e1.getMessage)) - throw e1 - } - None - } - - private def storeBrokerId(brokerId: Int, logDirs: Seq[String]) { - val metaProps = new Properties() - metaProps.setProperty("broker.id", brokerId.toString); - for(logDir <- logDirs) { - val f = Utils.createFile(logDir + File.separator + metaPropsFile) - val out = new FileOutputStream(f) - metaProps.store(out,"") - out.flush() - out.getFD().sync(); - out.close(); - } - } - } diff --git a/core/src/test/scala/unit/kafka/server/ServerGenerateBrokerIdTest.scala b/core/src/test/scala/unit/kafka/server/ServerGenerateBrokerIdTest.scala index d41db46..a2d4536 100644 --- a/core/src/test/scala/unit/kafka/server/ServerGenerateBrokerIdTest.scala +++ b/core/src/test/scala/unit/kafka/server/ServerGenerateBrokerIdTest.scala @@ -17,9 +17,7 @@ package kafka.server import kafka.zk.ZooKeeperTestHarness -import kafka.utils.{IntEncoder, TestUtils, Utils, VerifiableProperties} -import kafka.utils.TestUtils._ -import java.io.File +import kafka.utils.{TestUtils, Utils} import org.junit.Test import org.scalatest.junit.JUnit3Suite import junit.framework.Assert._ @@ -37,11 +35,7 @@ class ServerGenerateBrokerIdTest extends JUnit3Suite with ZooKeeperTestHarness { server1.startup() // do a clean shutdown and check that offset checkpoint file exists server1.shutdown() - for(logDir <- config1.logDirs) { - val metaProps = new VerifiableProperties(Utils.loadProps(logDir+"/meta.properties")) - assertTrue(metaProps.containsKey("broker.id")) - assertEquals(metaProps.getInt("broker.id"),1001) - } + assertTrue(verifyBrokerMetadata(config1.logDirs, 1001)) // restart the server check to see if it uses the brokerId generated previously server1 = new KafkaServer(config1) server1.startup() @@ -52,30 +46,7 @@ class ServerGenerateBrokerIdTest extends JUnit3Suite with ZooKeeperTestHarness { } @Test - def testAutoGenerateBrokerIdWithIPPolicy() { - val props3 = TestUtils.createBrokerConfig(-1, TestUtils.choosePort) - props3.put("broker.id.policy","ip") - val config3 = new KafkaConfig(props3) - var server1 = new KafkaServer(config3) - server1.startup() - // do a clean shutdown and check that offset checkpoint file exists - server1.shutdown() - for(logDir <- config3.logDirs) { - val metaProps = new VerifiableProperties(Utils.loadProps(logDir + File.separator + "meta.properties")) - assertTrue(metaProps.containsKey("broker.id")) - assertEquals(metaProps.getInt("broker.id"),Utils.ipToInt(config3.hostName)) - } - // restart the server check to see if it uses the brokerId generated previously - server1 = new KafkaServer(config3) - server1.startup() - assertEquals(server1.config.brokerId, Utils.ipToInt(config3.hostName)) - server1.shutdown() - Utils.rm(server1.config.logDirs) - TestUtils.verifyNonDaemonThreadsStatus - } - - @Test - def testUserConfigAndGenratedBrokerId() { + def testUserConfigAndGeneratedBrokerId() { // start the server with broker.id as part of config val server1 = new KafkaServer(config1) val server2 = new KafkaServer(config2) @@ -91,39 +62,34 @@ class ServerGenerateBrokerIdTest extends JUnit3Suite with ZooKeeperTestHarness { server1.shutdown() server2.shutdown() server3.shutdown() + assertTrue(verifyBrokerMetadata(server1.config.logDirs,1001)) + assertTrue(verifyBrokerMetadata(server2.config.logDirs,0)) + assertTrue(verifyBrokerMetadata(server3.config.logDirs,1002)) Utils.rm(server1.config.logDirs) Utils.rm(server2.config.logDirs) + Utils.rm(server3.config.logDirs) TestUtils.verifyNonDaemonThreadsStatus } @Test def testMultipleLogDirsMetaProps() { // add multiple logDirs and check if the generate brokerId is stored in all of them - var logDirs = props1.getProperty("log.dir")+ "," + TestUtils.tempDir().getAbsolutePath + + val logDirs = props1.getProperty("log.dir")+ "," + TestUtils.tempDir().getAbsolutePath + "," + TestUtils.tempDir().getAbsolutePath props1.setProperty("log.dir",logDirs) config1 = new KafkaConfig(props1) var server1 = new KafkaServer(config1) server1.startup() server1.shutdown() - for(logDir <- config1.logDirs) { - val metaProps = new VerifiableProperties(Utils.loadProps(logDir+"/meta.properties")) - assertTrue(metaProps.containsKey("broker.id")) - assertEquals(metaProps.getInt("broker.id"),1001) - } - + assertTrue(verifyBrokerMetadata(config1.logDirs, 1001)) // addition to log.dirs after generation of a broker.id from zk should be copied over - var newLogDirs = props1.getProperty("log.dir") + "," + TestUtils.tempDir().getAbsolutePath + val newLogDirs = props1.getProperty("log.dir") + "," + TestUtils.tempDir().getAbsolutePath props1.setProperty("log.dir",newLogDirs) config1 = new KafkaConfig(props1) server1 = new KafkaServer(config1) server1.startup() server1.shutdown() - for(logDir <- config1.logDirs) { - val metaProps = new VerifiableProperties(Utils.loadProps(logDir+"/meta.properties")) - assertTrue(metaProps.containsKey("broker.id")) - assertEquals(metaProps.getInt("broker.id"),1001) - } + assertTrue(verifyBrokerMetadata(config1.logDirs, 1001)) Utils.rm(server1.config.logDirs) TestUtils.verifyNonDaemonThreadsStatus } @@ -145,4 +111,15 @@ class ServerGenerateBrokerIdTest extends JUnit3Suite with ZooKeeperTestHarness { TestUtils.verifyNonDaemonThreadsStatus } + def verifyBrokerMetadata(logDirs: Seq[String], brokerId: Int): Boolean = { + for(logDir <- logDirs) { + val brokerMetadataOpt = (new BrokerMetadataFileHandler).read(logDir) + brokerMetadataOpt match { + case Some(brokerMetadata: BrokerMetadata) => + if (brokerMetadata.brokerId != brokerId) return false + case _ => return false + } + } + true + } } -- 1.9.3 (Apple Git-50)