You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@kafka.apache.org by ij...@apache.org on 2016/09/30 18:59:03 UTC

kafka git commit: KAFKA-4213; System tests for replication throttling (KIP-73)

Repository: kafka
Updated Branches:
  refs/heads/trunk 5f3746d13 -> 5a989d174


KAFKA-4213; System tests for replication throttling (KIP-73)

In this patch, we test `kafka-reassign-partitions` when throttling is active.

This patch also fixes the following:

  1. KafkaService.verify_reassign_partitions did not check whether
partition reassignment actually completed successfully (KAFKA-4204).
This patch works around those shortcomings so that we get the right
signal from this method.

  2. ProduceConsumeValidateTest.annotate_missing_messages would call
`pop' on the list of missing messages, causing downstream methods to get
incomplete data. We fix that in this patch as well.

Author: Apurva Mehta <ap...@gmail.com>

Reviewers: Geoff Anderson <ge...@confluent.io>, Ben Stopford <be...@gmail.com>, Ismael Juma <is...@juma.me.uk>

Closes #1904 from apurvam/throttling-tests


Project: http://git-wip-us.apache.org/repos/asf/kafka/repo
Commit: http://git-wip-us.apache.org/repos/asf/kafka/commit/5a989d17
Tree: http://git-wip-us.apache.org/repos/asf/kafka/tree/5a989d17
Diff: http://git-wip-us.apache.org/repos/asf/kafka/diff/5a989d17

Branch: refs/heads/trunk
Commit: 5a989d1748426004212d44abad4567f9034a04ef
Parents: 5f3746d
Author: Apurva Mehta <ap...@gmail.com>
Authored: Fri Sep 30 19:58:58 2016 +0100
Committer: Ismael Juma <is...@juma.me.uk>
Committed: Fri Sep 30 19:58:58 2016 +0100

----------------------------------------------------------------------
 .../kafkatest/services/kafka/config_property.py |   2 +-
 tests/kafkatest/services/kafka/kafka.py         |  35 +++-
 .../tests/core/reassign_partitions_test.py      |   4 +-
 tests/kafkatest/tests/core/throttling_test.py   | 174 +++++++++++++++++++
 .../kafkatest/tests/produce_consume_validate.py |  49 ++++--
 5 files changed, 242 insertions(+), 22 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/kafka/blob/5a989d17/tests/kafkatest/services/kafka/config_property.py
----------------------------------------------------------------------
diff --git a/tests/kafkatest/services/kafka/config_property.py b/tests/kafkatest/services/kafka/config_property.py
index e329151..a9ba40d 100644
--- a/tests/kafkatest/services/kafka/config_property.py
+++ b/tests/kafkatest/services/kafka/config_property.py
@@ -42,7 +42,7 @@ ZOOKEEPER_CONNECTION_TIMEOUT_MS = "zookeeper.connection.timeout.ms"
 INTER_BROKER_PROTOCOL_VERSION = "inter.broker.protocol.version"
 MESSAGE_FORMAT_VERSION = "log.message.format.version"
 MESSAGE_TIMESTAMP_TYPE = "message.timestamp.type"
-
+THROTTLING_REPLICATION_RATE_LIMIT = "replication.quota.throttled.rate"
 
 """
 From KafkaConfig.scala

http://git-wip-us.apache.org/repos/asf/kafka/blob/5a989d17/tests/kafkatest/services/kafka/kafka.py
----------------------------------------------------------------------
diff --git a/tests/kafkatest/services/kafka/kafka.py b/tests/kafkatest/services/kafka/kafka.py
index 4ce86b8..a2c044f 100644
--- a/tests/kafkatest/services/kafka/kafka.py
+++ b/tests/kafkatest/services/kafka/kafka.py
@@ -251,15 +251,23 @@ class KafkaService(KafkaPathResolverMixin, JmxMixin, Service):
         """
         if node is None:
             node = self.nodes[0]
-        self.logger.info("Creating topic %s with settings %s", topic_cfg["topic"], topic_cfg)
+        self.logger.info("Creating topic %s with settings %s",
+                         topic_cfg["topic"], topic_cfg)
         kafka_topic_script = self.path.script("kafka-topics.sh", node)
 
         cmd = kafka_topic_script + " "
-        cmd += "--zookeeper %(zk_connect)s --create --topic %(topic)s --partitions %(partitions)d --replication-factor %(replication)d" % {
+        cmd += "--zookeeper %(zk_connect)s --create --topic %(topic)s " % {
                 'zk_connect': self.zk.connect_setting(),
                 'topic': topic_cfg.get("topic"),
-                'partitions': topic_cfg.get('partitions', 1), 
-                'replication': topic_cfg.get('replication-factor', 1)
+           }
+        if 'replica-assignment' in topic_cfg:
+            cmd += " --replica-assignment %(replica-assignment)s" % {
+                'replica-assignment': topic_cfg.get('replica-assignment')
+            }
+        else:
+            cmd += " --partitions %(partitions)d --replication-factor %(replication-factor)d" % {
+                'partitions': topic_cfg.get('partitions', 1),
+                'replication-factor': topic_cfg.get('replication-factor', 1)
             }
 
         if "configs" in topic_cfg.keys() and topic_cfg["configs"] is not None:
@@ -283,7 +291,7 @@ class KafkaService(KafkaPathResolverMixin, JmxMixin, Service):
         for line in node.account.ssh_capture(cmd):
             output += line
         return output
-    
+
     def alter_message_format(self, topic, msg_format_version, node=None):
         if node is None:
             node = self.nodes[0]
@@ -351,12 +359,18 @@ class KafkaService(KafkaPathResolverMixin, JmxMixin, Service):
 
         self.logger.debug(output)
 
-        if re.match(".*is in progress.*", output) is not None:
+        if re.match(".*Reassignment of partition.*failed.*",
+                    output.replace('\n', '')) is not None:
+            return False
+
+        if re.match(".*is still in progress.*",
+                    output.replace('\n', '')) is not None:
             return False
 
         return True
 
-    def execute_reassign_partitions(self, reassignment, node=None):
+    def execute_reassign_partitions(self, reassignment, node=None,
+                                    throttle=None):
         """Run the reassign partitions admin tool in "verify" mode
         """
         if node is None:
@@ -373,6 +387,8 @@ class KafkaService(KafkaPathResolverMixin, JmxMixin, Service):
         cmd += "--zookeeper %s " % self.zk.connect_setting()
         cmd += "--reassignment-json-file %s " % json_file
         cmd += "--execute"
+        if throttle is not None:
+            cmd += " --throttle %d" % throttle
         cmd += " && sleep 1 && rm -f %s" % json_file
 
         # send command
@@ -393,7 +409,8 @@ class KafkaService(KafkaPathResolverMixin, JmxMixin, Service):
         """
         payload_match = "payload: " + "$|payload: ".join(str(x) for x in messages) + "$"
         found = set([])
-
+        self.logger.debug("number of unique missing messages we will search for: %d",
+                          len(messages))
         for node in self.nodes:
             # Grab all .log files in directories prefixed with this topic
             files = node.account.ssh_capture("find %s -regex  '.*/%s-.*/[^/]*.log'" % (KafkaService.DATA_LOG_DIR, topic))
@@ -409,6 +426,8 @@ class KafkaService(KafkaPathResolverMixin, JmxMixin, Service):
                             self.logger.debug("Found %s in data-file [%s] in line: [%s]" % (val, log.strip(), line.strip()))
                             found.add(val)
 
+        self.logger.debug("Number of unique messages found in the log: %d",
+                          len(found))
         missing = list(set(messages) - found)
 
         if len(missing) > 0:

http://git-wip-us.apache.org/repos/asf/kafka/blob/5a989d17/tests/kafkatest/tests/core/reassign_partitions_test.py
----------------------------------------------------------------------
diff --git a/tests/kafkatest/tests/core/reassign_partitions_test.py b/tests/kafkatest/tests/core/reassign_partitions_test.py
index dfff597..850e2aa 100644
--- a/tests/kafkatest/tests/core/reassign_partitions_test.py
+++ b/tests/kafkatest/tests/core/reassign_partitions_test.py
@@ -86,8 +86,8 @@ class ReassignPartitionsTest(ProduceConsumeValidateTest):
         # Wait until finished or timeout
         wait_until(lambda: self.kafka.verify_reassign_partitions(partition_info), timeout_sec=self.timeout_sec, backoff_sec=.5)
 
-    @parametrize(security_protocol="PLAINTEXT", bounce_brokers=False)
     @parametrize(security_protocol="PLAINTEXT", bounce_brokers=True)
+    @parametrize(security_protocol="PLAINTEXT", bounce_brokers=False)
     def test_reassign_partitions(self, bounce_brokers, security_protocol):
         """Reassign partitions tests.
         Setup: 1 zk, 3 kafka nodes, 1 topic with partitions=3, replication-factor=3, and min.insync.replicas=2
@@ -106,5 +106,5 @@ class ReassignPartitionsTest(ProduceConsumeValidateTest):
         self.producer = VerifiableProducer(self.test_context, self.num_producers, self.kafka, self.topic, throughput=self.producer_throughput)
         self.consumer = ConsoleConsumer(self.test_context, self.num_consumers, self.kafka, self.topic, new_consumer=new_consumer, consumer_timeout_ms=60000, message_validator=is_int)
         self.kafka.start()
-        
+
         self.run_produce_consume_validate(core_test_action=lambda: self.reassign_partitions(bounce_brokers))

http://git-wip-us.apache.org/repos/asf/kafka/blob/5a989d17/tests/kafkatest/tests/core/throttling_test.py
----------------------------------------------------------------------
diff --git a/tests/kafkatest/tests/core/throttling_test.py b/tests/kafkatest/tests/core/throttling_test.py
new file mode 100644
index 0000000..efc36d4
--- /dev/null
+++ b/tests/kafkatest/tests/core/throttling_test.py
@@ -0,0 +1,174 @@
+# 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.
+
+import time
+import math
+from ducktape.mark import parametrize
+from ducktape.utils.util import wait_until
+
+from kafkatest.services.performance import ProducerPerformanceService
+from kafkatest.services.zookeeper import ZookeeperService
+from kafkatest.services.kafka import KafkaService
+from kafkatest.services.console_consumer import ConsoleConsumer
+from kafkatest.tests.produce_consume_validate import ProduceConsumeValidateTest
+from kafkatest.services.verifiable_producer import VerifiableProducer
+from kafkatest.utils import is_int
+
+
+class ThrottlingTest(ProduceConsumeValidateTest):
+    """Tests throttled partition reassignment. This is essentially similar
+    to the reassign_partitions_test, except that we throttle the reassignment
+    and verify that it takes a sensible amount of time given the throttle
+    and the amount of data being moved.
+
+    Since the correctness is time dependent, this test also simplifies the
+    cluster topology. In particular, we fix the number of brokers, the
+    replication-factor, the number of partitions, the partition size, and
+    the number of partitions being moved so that we can accurately predict
+    the time throttled reassignment should take.
+    """
+
+    def __init__(self, test_context):
+        """:type test_context: ducktape.tests.test.TestContext"""
+        super(ThrottlingTest, self).__init__(test_context=test_context)
+
+        self.topic = "test_topic"
+        self.zk = ZookeeperService(test_context, num_nodes=1)
+        # Because we are starting the producer/consumer/validate cycle _after_
+        # seeding the cluster with big data (to test throttling), we need to
+        # Start the consumer from the end of the stream. further, we need to
+        # ensure that the consumer is fully started before the producer starts
+        # so that we don't miss any messages. This timeout ensures the sufficient
+        # condition.
+        self.consumer_init_timeout_sec =  10
+        self.num_brokers = 6
+        self.num_partitions = 3
+        self.kafka = KafkaService(test_context,
+                                  num_nodes=self.num_brokers,
+                                  zk=self.zk,
+                                  topics={
+                                      self.topic: {
+                                          "partitions": self.num_partitions,
+                                          "replication-factor": 2,
+                                          "configs": {
+                                              "segment.bytes": 64 * 1024 * 1024
+                                          }
+                                      }
+                                  })
+        self.producer_throughput = 1000
+        self.timeout_sec = 400
+        self.num_records = 2000
+        self.record_size = 4096 * 100  # 400 KB
+        # 1 MB per partition on average.
+        self.partition_size = (self.num_records * self.record_size) / self.num_partitions
+        self.num_producers = 2
+        self.num_consumers = 1
+        self.throttle = 4 * 1024 * 1024  # 4 MB/s
+
+    def setUp(self):
+        self.zk.start()
+
+    def min_cluster_size(self):
+        # Override this since we're adding services outside of the constructor
+        return super(ThrottlingTest, self).min_cluster_size() +\
+            self.num_producers + self.num_consumers
+
+    def clean_bounce_some_brokers(self):
+        """Bounce every other broker"""
+        for node in self.kafka.nodes[::2]:
+            self.kafka.restart_node(node, clean_shutdown=True)
+
+    def reassign_partitions(self, bounce_brokers, throttle):
+        """This method reassigns partitions using a throttle. It makes an
+        assertion about the minimum amount of time the reassignment should take
+        given the value of the throttle, the number of partitions being moved,
+        and the size of each partition.
+        """
+        partition_info = self.kafka.parse_describe_topic(
+            self.kafka.describe_topic(self.topic))
+        self.logger.debug("Partitions before reassignment:" +
+                          str(partition_info))
+        max_num_moves = 0
+        for i in range(0, self.num_partitions):
+            old_replicas = set(partition_info["partitions"][i]["replicas"])
+            new_part = (i+1) % self.num_partitions
+            new_replicas = set(partition_info["partitions"][new_part]["replicas"])
+            max_num_moves = max(len(new_replicas - old_replicas), max_num_moves)
+            partition_info["partitions"][i]["partition"] = new_part
+        self.logger.debug("Jumbled partitions: " + str(partition_info))
+
+        self.kafka.execute_reassign_partitions(partition_info,
+                                               throttle=throttle)
+        start = time.time()
+        if bounce_brokers:
+            # bounce a few brokers at the same time
+            self.clean_bounce_some_brokers()
+
+        # Wait until finished or timeout
+        size_per_broker = max_num_moves * self.partition_size
+        self.logger.debug("Max amount of data transfer per broker: %fb",
+                          size_per_broker)
+        estimated_throttled_time = math.ceil(float(size_per_broker) /
+                                             self.throttle)
+        estimated_time_with_buffer = estimated_throttled_time * 2
+        self.logger.debug("Waiting %ds for the reassignment to complete",
+                          estimated_time_with_buffer)
+        wait_until(lambda: self.kafka.verify_reassign_partitions(partition_info),
+                   timeout_sec=estimated_time_with_buffer, backoff_sec=.5)
+        stop = time.time()
+        time_taken = stop - start
+        self.logger.debug("Transfer took %d second. Estimated time : %ds",
+                          time_taken,
+                          estimated_throttled_time)
+        assert time_taken >= estimated_throttled_time, \
+            ("Expected rebalance to take at least %ds, but it took %ds" % (
+                estimated_throttled_time,
+                time_taken))
+
+    @parametrize(bounce_brokers=False)
+    @parametrize(bounce_brokers=True)
+    def test_throttled_reassignment(self, bounce_brokers):
+        security_protocol = 'PLAINTEXT'
+        self.kafka.security_protocol = security_protocol
+        self.kafka.interbroker_security_protocol = security_protocol
+
+        producer_id = 'bulk_producer'
+        bulk_producer = ProducerPerformanceService(
+            context=self.test_context, num_nodes=1, kafka=self.kafka,
+            topic=self.topic, num_records=self.num_records,
+            record_size=self.record_size, throughput=-1, client_id=producer_id,
+            jmx_object_names=['kafka.producer:type=producer-metrics,client-id=%s' % producer_id],
+            jmx_attributes=['outgoing-byte-rate'])
+
+
+        self.producer = VerifiableProducer(context=self.test_context,
+                                           num_nodes=1,
+                                           kafka=self.kafka, topic=self.topic,
+                                           message_validator=is_int,
+                                           throughput=self.producer_throughput)
+
+        self.consumer = ConsoleConsumer(self.test_context,
+                                        self.num_consumers,
+                                        self.kafka,
+                                        self.topic,
+                                        new_consumer=True,
+                                        consumer_timeout_ms=60000,
+                                        message_validator=is_int,
+                                        from_beginning=False)
+
+        self.kafka.start()
+        bulk_producer.run()
+        self.run_produce_consume_validate(core_test_action=
+                                          lambda: self.reassign_partitions(bounce_brokers, self.throttle))

http://git-wip-us.apache.org/repos/asf/kafka/blob/5a989d17/tests/kafkatest/tests/produce_consume_validate.py
----------------------------------------------------------------------
diff --git a/tests/kafkatest/tests/produce_consume_validate.py b/tests/kafkatest/tests/produce_consume_validate.py
index be7cda4..afb885d 100644
--- a/tests/kafkatest/tests/produce_consume_validate.py
+++ b/tests/kafkatest/tests/produce_consume_validate.py
@@ -28,18 +28,44 @@ class ProduceConsumeValidateTest(Test):
 
     def __init__(self, test_context):
         super(ProduceConsumeValidateTest, self).__init__(test_context=test_context)
+        # How long to wait for the producer to declare itself healthy? This can
+        # be overidden by inheriting classes.
+        self.producer_start_timeout_sec = 20
+
+        # How long to wait for the consumer to start consuming messages?
+        self.consumer_start_timeout_sec = 60
+
+        # How long wait for the consumer process to fork? This
+        # is important in the case when the consumer is starting from the end,
+        # and we don't want it to miss any messages. The race condition this
+        # timeout avoids is that the consumer has not forked even after the
+        # producer begins producing messages, in which case we will miss the
+        # initial set of messages and get spurious test failures.
+        self.consumer_init_timeout_sec = 0
 
     def setup_producer_and_consumer(self):
         raise NotImplementedError("Subclasses should implement this")
 
     def start_producer_and_consumer(self, async=False):
         # Start background producer and consumer
-        self.producer.start()
-        wait_until(lambda: async or self.producer.num_acked > 5, timeout_sec=20,
-             err_msg="Producer failed to start in a reasonable amount of time.")
         self.consumer.start()
-        wait_until(lambda: async or len(self.consumer.messages_consumed[1]) > 0, timeout_sec=60,
-             err_msg="Consumer failed to start in a reasonable amount of time.")
+        if (self.consumer_init_timeout_sec > 0):
+            self.logger.debug("Waiting %ds for the consumer to fork.",
+                              self.consumer_init_timeout_sec)
+            wait_until(lambda: self.consumer.alive(self.consumer.nodes[0]) is True,
+                       timeout_sec=self.consumer_init_timeout_sec,
+                       err_msg="Consumer process took more than %d s to fork" %\
+                       self.consumer_init_timeout_sec)
+
+        self.producer.start()
+        wait_until(lambda: async or self.producer.num_acked > 5,
+                   timeout_sec=self.producer_start_timeout_sec,
+                   err_msg="Producer failed to produce messages for %ds." %\
+                   self.producer_start_timeout_sec)
+        wait_until(lambda: async or len(self.consumer.messages_consumed[1]) > 0,
+                   timeout_sec=self.consumer_start_timeout_sec,
+                   err_msg="Consumer failed to consume messages for %ds." %\
+                   self.consumer_start_timeout_sec)
 
     def check_alive(self):
         msg = ""
@@ -80,14 +106,15 @@ class ProduceConsumeValidateTest(Test):
 
     @staticmethod
     def annotate_missing_msgs(missing, acked, consumed, msg):
-        msg += "%s acked message did not make it to the Consumer. They are: " % len(missing)
-        if len(missing) < 20:
-            msg += str(missing) + ". "
+        missing_list = list(missing)
+        msg += "%s acked message did not make it to the Consumer. They are: " %\
+            len(missing_list)
+        if len(missing_list) < 20:
+            msg += str(missing_list) + ". "
         else:
-            for i in range(20):
-                msg += str(missing.pop()) + ", "
+            msg += ", ".join(str(m) for m in missing_list[:20])
             msg += "...plus %s more. Total Acked: %s, Total Consumed: %s. " \
-                   % (len(missing) - 20, len(set(acked)), len(set(consumed)))
+                   % (len(missing_list) - 20, len(set(acked)), len(set(consumed)))
         return msg
 
     @staticmethod