PageRenderTime 30ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/tests/kafkatest/tests/connect/connect_distributed_test.py

https://gitlab.com/JHUDevOpsFall2016/kafka-alex
Python | 481 lines | 297 code | 105 blank | 79 comment | 57 complexity | 41578934e34cfa34caefa52d694ab918 MD5 | raw file
  1. # Licensed to the Apache Software Foundation (ASF) under one or more
  2. # contributor license agreements. See the NOTICE file distributed with
  3. # this work for additional information regarding copyright ownership.
  4. # The ASF licenses this file to You under the Apache License, Version 2.0
  5. # (the "License"); you may not use this file except in compliance with
  6. # the License. You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. from ducktape.tests.test import Test
  16. from kafkatest.services.zookeeper import ZookeeperService
  17. from kafkatest.services.kafka import KafkaService
  18. from kafkatest.services.connect import ConnectDistributedService, VerifiableSource, VerifiableSink, ConnectRestError, MockSink, MockSource
  19. from kafkatest.services.console_consumer import ConsoleConsumer
  20. from kafkatest.services.security.security_config import SecurityConfig
  21. from ducktape.utils.util import wait_until
  22. from ducktape.mark import matrix
  23. import subprocess, itertools, time
  24. from collections import Counter, namedtuple
  25. import operator
  26. class ConnectDistributedTest(Test):
  27. """
  28. Simple test of Kafka Connect in distributed mode, producing data from files on one cluster and consuming it on
  29. another, validating the total output is identical to the input.
  30. """
  31. FILE_SOURCE_CONNECTOR = 'org.apache.kafka.connect.file.FileStreamSourceConnector'
  32. FILE_SINK_CONNECTOR = 'org.apache.kafka.connect.file.FileStreamSinkConnector'
  33. INPUT_FILE = "/mnt/connect.input"
  34. OUTPUT_FILE = "/mnt/connect.output"
  35. TOPIC = "test"
  36. OFFSETS_TOPIC = "connect-offsets"
  37. CONFIG_TOPIC = "connect-configs"
  38. STATUS_TOPIC = "connect-status"
  39. # Since tasks can be assigned to any node and we're testing with files, we need to make sure the content is the same
  40. # across all nodes.
  41. FIRST_INPUT_LIST = ["foo", "bar", "baz"]
  42. FIRST_INPUTS = "\n".join(FIRST_INPUT_LIST) + "\n"
  43. SECOND_INPUT_LIST = ["razz", "ma", "tazz"]
  44. SECOND_INPUTS = "\n".join(SECOND_INPUT_LIST) + "\n"
  45. SCHEMA = { "type": "string", "optional": False }
  46. def __init__(self, test_context):
  47. super(ConnectDistributedTest, self).__init__(test_context)
  48. self.num_zk = 1
  49. self.num_brokers = 1
  50. self.topics = {
  51. 'test' : { 'partitions': 1, 'replication-factor': 1 }
  52. }
  53. self.zk = ZookeeperService(test_context, self.num_zk)
  54. self.key_converter = "org.apache.kafka.connect.json.JsonConverter"
  55. self.value_converter = "org.apache.kafka.connect.json.JsonConverter"
  56. self.schemas = True
  57. def setup_services(self, security_protocol=SecurityConfig.PLAINTEXT):
  58. self.kafka = KafkaService(self.test_context, self.num_brokers, self.zk,
  59. security_protocol=security_protocol, interbroker_security_protocol=security_protocol,
  60. topics=self.topics)
  61. self.cc = ConnectDistributedService(self.test_context, 3, self.kafka, [self.INPUT_FILE, self.OUTPUT_FILE])
  62. self.cc.log_level = "DEBUG"
  63. self.zk.start()
  64. self.kafka.start()
  65. def _start_connector(self, config_file):
  66. connector_props = self.render(config_file)
  67. connector_config = dict([line.strip().split('=', 1) for line in connector_props.split('\n') if line.strip() and not line.strip().startswith('#')])
  68. self.cc.create_connector(connector_config)
  69. def _connector_status(self, connector, node=None):
  70. try:
  71. return self.cc.get_connector_status(connector, node)
  72. except ConnectRestError:
  73. return None
  74. def _connector_has_state(self, status, state):
  75. return status is not None and status['connector']['state'] == state
  76. def _task_has_state(self, task_id, status, state):
  77. if not status:
  78. return False
  79. tasks = status['tasks']
  80. if not tasks:
  81. return False
  82. for task in tasks:
  83. if task['id'] == task_id:
  84. return task['state'] == state
  85. return False
  86. def _all_tasks_have_state(self, status, task_count, state):
  87. if status is None:
  88. return False
  89. tasks = status['tasks']
  90. if len(tasks) != task_count:
  91. return False
  92. return reduce(operator.and_, [task['state'] == state for task in tasks], True)
  93. def is_running(self, connector, node=None):
  94. status = self._connector_status(connector.name, node)
  95. return self._connector_has_state(status, 'RUNNING') and self._all_tasks_have_state(status, connector.tasks, 'RUNNING')
  96. def is_paused(self, connector, node=None):
  97. status = self._connector_status(connector.name, node)
  98. return self._connector_has_state(status, 'PAUSED') and self._all_tasks_have_state(status, connector.tasks, 'PAUSED')
  99. def connector_is_running(self, connector, node=None):
  100. status = self._connector_status(connector.name, node)
  101. return self._connector_has_state(status, 'RUNNING')
  102. def connector_is_failed(self, connector, node=None):
  103. status = self._connector_status(connector.name, node)
  104. return self._connector_has_state(status, 'FAILED')
  105. def task_is_failed(self, connector, task_id, node=None):
  106. status = self._connector_status(connector.name, node)
  107. return self._task_has_state(task_id, status, 'FAILED')
  108. def task_is_running(self, connector, task_id, node=None):
  109. status = self._connector_status(connector.name, node)
  110. return self._task_has_state(task_id, status, 'RUNNING')
  111. def test_restart_failed_connector(self):
  112. self.setup_services()
  113. self.cc.set_configs(lambda node: self.render("connect-distributed.properties", node=node))
  114. self.cc.start()
  115. self.sink = MockSink(self.cc, self.topics.keys(), mode='connector-failure', delay_sec=5)
  116. self.sink.start()
  117. wait_until(lambda: self.connector_is_failed(self.sink), timeout_sec=15,
  118. err_msg="Failed to see connector transition to the FAILED state")
  119. self.cc.restart_connector(self.sink.name)
  120. wait_until(lambda: self.connector_is_running(self.sink), timeout_sec=10,
  121. err_msg="Failed to see connector transition to the RUNNING state")
  122. @matrix(delete_before_reconfig=[False, True])
  123. def test_bad_connector_class(self, delete_before_reconfig):
  124. """
  125. For the same connector name, first configure it with a bad connector class name such that it fails to start, verify that it enters a FAILED state.
  126. Restart should also fail.
  127. Then try to rectify by reconfiguring it as a MockConnector and verifying it successfully transitions to RUNNING.
  128. """
  129. self.setup_services()
  130. self.cc.set_configs(lambda node: self.render("connect-distributed.properties", node=node))
  131. self.cc.start()
  132. connector_name = 'bad-to-good-test'
  133. connector = namedtuple('BadConnector', ['name', 'tasks'])(connector_name, 1)
  134. config = {
  135. 'name': connector.name,
  136. 'tasks.max': connector.tasks,
  137. 'connector.class': 'java.util.HashMap'
  138. }
  139. self.cc.create_connector(config)
  140. wait_until(lambda: self.connector_is_failed(connector), timeout_sec=10, err_msg="Failed to see connector transition to FAILED state")
  141. try:
  142. self.cc.restart_connector(connector_name)
  143. except ConnectRestError:
  144. pass
  145. else:
  146. raise AssertionError("Expected restart of %s to fail" % connector_name)
  147. if delete_before_reconfig:
  148. self.cc.delete_connector(connector_name)
  149. config['connector.class'] = 'org.apache.kafka.connect.tools.MockSourceConnector'
  150. self.cc.set_connector_config(connector_name, config)
  151. wait_until(lambda: self.connector_is_running(connector), timeout_sec=10, err_msg="Failed to see connector transition to the RUNNING state")
  152. @matrix(connector_type=["source", "sink"])
  153. def test_restart_failed_task(self, connector_type):
  154. self.setup_services()
  155. self.cc.set_configs(lambda node: self.render("connect-distributed.properties", node=node))
  156. self.cc.start()
  157. connector = None
  158. if connector_type == "sink":
  159. connector = MockSink(self.cc, self.topics.keys(), mode='task-failure', delay_sec=5)
  160. else:
  161. connector = MockSource(self.cc, mode='task-failure', delay_sec=5)
  162. connector.start()
  163. task_id = 0
  164. wait_until(lambda: self.task_is_failed(connector, task_id), timeout_sec=20,
  165. err_msg="Failed to see task transition to the FAILED state")
  166. self.cc.restart_task(connector.name, task_id)
  167. wait_until(lambda: self.task_is_running(connector, task_id), timeout_sec=10,
  168. err_msg="Failed to see task transition to the RUNNING state")
  169. def test_pause_and_resume_source(self):
  170. """
  171. Verify that source connectors stop producing records when paused and begin again after
  172. being resumed.
  173. """
  174. self.setup_services()
  175. self.cc.set_configs(lambda node: self.render("connect-distributed.properties", node=node))
  176. self.cc.start()
  177. self.source = VerifiableSource(self.cc)
  178. self.source.start()
  179. wait_until(lambda: self.is_running(self.source), timeout_sec=30,
  180. err_msg="Failed to see connector transition to the RUNNING state")
  181. self.cc.pause_connector(self.source.name)
  182. # wait until all nodes report the paused transition
  183. for node in self.cc.nodes:
  184. wait_until(lambda: self.is_paused(self.source, node), timeout_sec=30,
  185. err_msg="Failed to see connector transition to the PAUSED state")
  186. # verify that we do not produce new messages while paused
  187. num_messages = len(self.source.messages())
  188. time.sleep(10)
  189. assert num_messages == len(self.source.messages()), "Paused source connector should not produce any messages"
  190. self.cc.resume_connector(self.source.name)
  191. for node in self.cc.nodes:
  192. wait_until(lambda: self.is_running(self.source, node), timeout_sec=30,
  193. err_msg="Failed to see connector transition to the RUNNING state")
  194. # after resuming, we should see records produced again
  195. wait_until(lambda: len(self.source.messages()) > num_messages, timeout_sec=30,
  196. err_msg="Failed to produce messages after resuming source connector")
  197. def test_pause_and_resume_sink(self):
  198. """
  199. Verify that sink connectors stop consuming records when paused and begin again after
  200. being resumed.
  201. """
  202. self.setup_services()
  203. self.cc.set_configs(lambda node: self.render("connect-distributed.properties", node=node))
  204. self.cc.start()
  205. # use the verifiable source to produce a steady stream of messages
  206. self.source = VerifiableSource(self.cc)
  207. self.source.start()
  208. self.sink = VerifiableSink(self.cc)
  209. self.sink.start()
  210. wait_until(lambda: self.is_running(self.sink), timeout_sec=30,
  211. err_msg="Failed to see connector transition to the RUNNING state")
  212. self.cc.pause_connector(self.sink.name)
  213. # wait until all nodes report the paused transition
  214. for node in self.cc.nodes:
  215. wait_until(lambda: self.is_paused(self.sink, node), timeout_sec=30,
  216. err_msg="Failed to see connector transition to the PAUSED state")
  217. # verify that we do not consume new messages while paused
  218. num_messages = len(self.sink.received_messages())
  219. time.sleep(10)
  220. assert num_messages == len(self.sink.received_messages()), "Paused sink connector should not consume any messages"
  221. self.cc.resume_connector(self.sink.name)
  222. for node in self.cc.nodes:
  223. wait_until(lambda: self.is_running(self.sink, node), timeout_sec=30,
  224. err_msg="Failed to see connector transition to the RUNNING state")
  225. # after resuming, we should see records consumed again
  226. wait_until(lambda: len(self.sink.received_messages()) > num_messages, timeout_sec=30,
  227. err_msg="Failed to consume messages after resuming source connector")
  228. def test_pause_state_persistent(self):
  229. """
  230. Verify that paused state is preserved after a cluster restart.
  231. """
  232. self.setup_services()
  233. self.cc.set_configs(lambda node: self.render("connect-distributed.properties", node=node))
  234. self.cc.start()
  235. self.source = VerifiableSource(self.cc)
  236. self.source.start()
  237. wait_until(lambda: self.is_running(self.source), timeout_sec=30,
  238. err_msg="Failed to see connector transition to the RUNNING state")
  239. self.cc.pause_connector(self.source.name)
  240. self.cc.restart()
  241. # we should still be paused after restarting
  242. for node in self.cc.nodes:
  243. wait_until(lambda: self.is_paused(self.source, node), timeout_sec=30,
  244. err_msg="Failed to see connector startup in PAUSED state")
  245. @matrix(security_protocol=[SecurityConfig.PLAINTEXT, SecurityConfig.SASL_SSL])
  246. def test_file_source_and_sink(self, security_protocol):
  247. """
  248. Tests that a basic file connector works across clean rolling bounces. This validates that the connector is
  249. correctly created, tasks instantiated, and as nodes restart the work is rebalanced across nodes.
  250. """
  251. self.setup_services(security_protocol=security_protocol)
  252. self.cc.set_configs(lambda node: self.render("connect-distributed.properties", node=node))
  253. self.cc.start()
  254. self.logger.info("Creating connectors")
  255. self._start_connector("connect-file-source.properties")
  256. self._start_connector("connect-file-sink.properties")
  257. # Generating data on the source node should generate new records and create new output on the sink node. Timeouts
  258. # here need to be more generous than they are for standalone mode because a) it takes longer to write configs,
  259. # do rebalancing of the group, etc, and b) without explicit leave group support, rebalancing takes awhile
  260. for node in self.cc.nodes:
  261. node.account.ssh("echo -e -n " + repr(self.FIRST_INPUTS) + " >> " + self.INPUT_FILE)
  262. wait_until(lambda: self._validate_file_output(self.FIRST_INPUT_LIST), timeout_sec=70, err_msg="Data added to input file was not seen in the output file in a reasonable amount of time.")
  263. # Restarting both should result in them picking up where they left off,
  264. # only processing new data.
  265. self.cc.restart()
  266. for node in self.cc.nodes:
  267. node.account.ssh("echo -e -n " + repr(self.SECOND_INPUTS) + " >> " + self.INPUT_FILE)
  268. wait_until(lambda: self._validate_file_output(self.FIRST_INPUT_LIST + self.SECOND_INPUT_LIST), timeout_sec=70, err_msg="Sink output file never converged to the same state as the input file")
  269. @matrix(clean=[True, False])
  270. def test_bounce(self, clean):
  271. """
  272. Validates that source and sink tasks that run continuously and produce a predictable sequence of messages
  273. run correctly and deliver messages exactly once when Kafka Connect workers undergo clean rolling bounces.
  274. """
  275. num_tasks = 3
  276. self.setup_services()
  277. self.cc.set_configs(lambda node: self.render("connect-distributed.properties", node=node))
  278. self.cc.start()
  279. self.source = VerifiableSource(self.cc, tasks=num_tasks, throughput=100)
  280. self.source.start()
  281. self.sink = VerifiableSink(self.cc, tasks=num_tasks)
  282. self.sink.start()
  283. for _ in range(3):
  284. for node in self.cc.nodes:
  285. started = time.time()
  286. self.logger.info("%s bouncing Kafka Connect on %s", clean and "Clean" or "Hard", str(node.account))
  287. self.cc.stop_node(node, clean_shutdown=clean)
  288. with node.account.monitor_log(self.cc.LOG_FILE) as monitor:
  289. self.cc.start_node(node)
  290. monitor.wait_until("Starting connectors and tasks using config offset", timeout_sec=90,
  291. err_msg="Kafka Connect worker didn't successfully join group and start work")
  292. self.logger.info("Bounced Kafka Connect on %s and rejoined in %f seconds", node.account, time.time() - started)
  293. # Give additional time for the consumer groups to recover. Even if it is not a hard bounce, there are
  294. # some cases where a restart can cause a rebalance to take the full length of the session timeout
  295. # (e.g. if the client shuts down before it has received the memberId from its initial JoinGroup).
  296. # If we don't give enough time for the group to stabilize, the next bounce may cause consumers to
  297. # be shut down before they have any time to process data and we can end up with zero data making it
  298. # through the test.
  299. time.sleep(15)
  300. self.source.stop()
  301. self.sink.stop()
  302. self.cc.stop()
  303. # Validate at least once delivery of everything that was reported as written since we should have flushed and
  304. # cleanly exited. Currently this only tests at least once delivery because the sink task may not have consumed
  305. # all the messages generated by the source task. This needs to be done per-task since seqnos are not unique across
  306. # tasks.
  307. success = True
  308. errors = []
  309. allow_dups = not clean
  310. src_messages = self.source.messages()
  311. sink_messages = self.sink.messages()
  312. for task in range(num_tasks):
  313. # Validate source messages
  314. src_seqnos = [msg['seqno'] for msg in src_messages if msg['task'] == task]
  315. # Every seqno up to the largest one we ever saw should appear. Each seqno should only appear once because clean
  316. # bouncing should commit on rebalance.
  317. src_seqno_max = max(src_seqnos)
  318. self.logger.debug("Max source seqno: %d", src_seqno_max)
  319. src_seqno_counts = Counter(src_seqnos)
  320. missing_src_seqnos = sorted(set(range(src_seqno_max)).difference(set(src_seqnos)))
  321. duplicate_src_seqnos = sorted([seqno for seqno,count in src_seqno_counts.iteritems() if count > 1])
  322. if missing_src_seqnos:
  323. self.logger.error("Missing source sequence numbers for task " + str(task))
  324. errors.append("Found missing source sequence numbers for task %d: %s" % (task, missing_src_seqnos))
  325. success = False
  326. if not allow_dups and duplicate_src_seqnos:
  327. self.logger.error("Duplicate source sequence numbers for task " + str(task))
  328. errors.append("Found duplicate source sequence numbers for task %d: %s" % (task, duplicate_src_seqnos))
  329. success = False
  330. # Validate sink messages
  331. sink_seqnos = [msg['seqno'] for msg in sink_messages if msg['task'] == task and 'flushed' in msg]
  332. # Every seqno up to the largest one we ever saw should appear. Each seqno should only appear once because
  333. # clean bouncing should commit on rebalance.
  334. sink_seqno_max = max(sink_seqnos)
  335. self.logger.debug("Max sink seqno: %d", sink_seqno_max)
  336. sink_seqno_counts = Counter(sink_seqnos)
  337. missing_sink_seqnos = sorted(set(range(sink_seqno_max)).difference(set(sink_seqnos)))
  338. duplicate_sink_seqnos = sorted([seqno for seqno,count in sink_seqno_counts.iteritems() if count > 1])
  339. if missing_sink_seqnos:
  340. self.logger.error("Missing sink sequence numbers for task " + str(task))
  341. errors.append("Found missing sink sequence numbers for task %d: %s" % (task, missing_sink_seqnos))
  342. success = False
  343. if not allow_dups and duplicate_sink_seqnos:
  344. self.logger.error("Duplicate sink sequence numbers for task " + str(task))
  345. errors.append("Found duplicate sink sequence numbers for task %d: %s" % (task, duplicate_sink_seqnos))
  346. success = False
  347. # Validate source and sink match
  348. if sink_seqno_max > src_seqno_max:
  349. self.logger.error("Found sink sequence number greater than any generated sink sequence number for task %d: %d > %d", task, sink_seqno_max, src_seqno_max)
  350. errors.append("Found sink sequence number greater than any generated sink sequence number for task %d: %d > %d" % (task, sink_seqno_max, src_seqno_max))
  351. success = False
  352. if src_seqno_max < 1000 or sink_seqno_max < 1000:
  353. errors.append("Not enough messages were processed: source:%d sink:%d" % (src_seqno_max, sink_seqno_max))
  354. success = False
  355. if not success:
  356. self.mark_for_collect(self.cc)
  357. # Also collect the data in the topic to aid in debugging
  358. consumer_validator = ConsoleConsumer(self.test_context, 1, self.kafka, self.source.topic, consumer_timeout_ms=1000, print_key=True)
  359. consumer_validator.run()
  360. self.mark_for_collect(consumer_validator, "consumer_stdout")
  361. assert success, "Found validation errors:\n" + "\n ".join(errors)
  362. def _validate_file_output(self, input):
  363. input_set = set(input)
  364. # Output needs to be collected from all nodes because we can't be sure where the tasks will be scheduled.
  365. # Between the first and second rounds, we might even end up with half the data on each node.
  366. output_set = set(itertools.chain(*[
  367. [line.strip() for line in self._file_contents(node, self.OUTPUT_FILE)] for node in self.cc.nodes
  368. ]))
  369. return input_set == output_set
  370. def _file_contents(self, node, file):
  371. try:
  372. # Convert to a list here or the CalledProcessError may be returned during a call to the generator instead of
  373. # immediately
  374. return list(node.account.ssh_capture("cat " + file))
  375. except subprocess.CalledProcessError:
  376. return []