├── .gitignore ├── LICENSE ├── README.rst ├── kafka_replayer.py ├── setup.py └── test ├── __init__.py └── test_kafka_replayer.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.py[cod] 2 | 3 | # C extensions 4 | *.so 5 | 6 | # Packages 7 | *.egg 8 | *.egg-info 9 | dist 10 | build 11 | eggs 12 | parts 13 | bin 14 | var 15 | sdist 16 | develop-eggs 17 | .installed.cfg 18 | lib 19 | lib64 20 | __pycache__ 21 | 22 | # Installer logs 23 | pip-log.txt 24 | 25 | # Unit test / coverage reports 26 | .coverage 27 | .tox 28 | nosetests.xml 29 | 30 | # Translations 31 | *.mo 32 | 33 | # Mr Developer 34 | .mr.developer.cfg 35 | .project 36 | .pydevproject 37 | 38 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | 204 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | ********************* 2 | Python Kafka Replayer 3 | ********************* 4 | 5 | .. image:: https://circleci.com/gh/SiftScience/python-kafka-replayer/tree/master.svg?style=svg 6 | :target: https://circleci.com/gh/SiftScience/python-kafka-replayer/tree/master 7 | 8 | kafka_replayer is a library that helps consume time ranges of messages from Kafka topics. While the 9 | standard Kafka consumer API allows seeking to a specific offset and replaying from there, using 10 | offsets as the replay abstraction is cumbersome and potentially error-prone. This library does the 11 | translation from timestamps to offsets transparently. 12 | 13 | This library is written in Python, and leverages `kafka-python`_'s consumer to poll Kafka for messages. 14 | 15 | ========== 16 | Installing 17 | ========== 18 | .. code-block:: bash 19 | 20 | $ pip install kafka_replayer 21 | 22 | ===== 23 | Using 24 | ===== 25 | .. code-block:: python 26 | 27 | import json 28 | import kafka_replayer 29 | 30 | des_fn = lambda x: json.loads(x) if x else None 31 | replayer = kafka_replayer.KafkaReplayer('my-topic', 32 | bootstrap_servers=['localhost:9092'], 33 | key_deserializer=des_fn, 34 | value_deserializer=des_fn) 35 | 36 | # Replay all records between the start and end millis timestamps 37 | for record in replayer.replay(1469467314341, 1469467907549): 38 | print record 39 | 40 | ============= 41 | Documentation 42 | ============= 43 | 44 | http://pythonhosted.org/kafka_replayer/ 45 | 46 | ======= 47 | License 48 | ======= 49 | 50 | See `LICENSE `_. 51 | 52 | .. _kafka-python: https://github.com/dpkp/kafka-python 53 | -------------------------------------------------------------------------------- /kafka_replayer.py: -------------------------------------------------------------------------------- 1 | import kafka 2 | import logging 3 | import six 4 | import time 5 | 6 | class KafkaReplayer(object): 7 | """A utility that allows replaying Kafka records by time range.""" 8 | 9 | def __init__(self, topic_name, partitions=None, **configs): 10 | """Create the replayer. 11 | 12 | Args: 13 | topic_name: The topic to replay 14 | partitions: Optionally specify the set of partitions (ints) to replay 15 | configs: The configuration kwargs to pass forward to kafka.KafkaConsumer 16 | """ 17 | if not topic_name: 18 | raise ValueError('topic_name is required') 19 | self._topic_name = topic_name 20 | self._partitions = partitions 21 | self._configs = self._configs_with_defaults(configs) 22 | self._log_interval = 10000 23 | self._logger = self._create_logger() 24 | 25 | def _create_logger(self): 26 | self._logger = logging.getLogger(__name__) 27 | null_handler = logging.NullHandler() 28 | null_handler.setLevel(logging.DEBUG) 29 | self._logger.addHandler(null_handler) 30 | return self._logger 31 | 32 | def _configs_with_defaults(self, configs): 33 | if 'group_id' not in configs: 34 | configs['group_id'] = None 35 | if 'consumer_timeout_ms' not in configs: 36 | configs['consumer_timeout_ms'] = 10000 37 | return configs 38 | 39 | def _get_time_millis(self): 40 | return int(round(time.time() * 1000)) 41 | 42 | def _create_consumer(self): 43 | return kafka.KafkaConsumer(**(self._configs)) 44 | 45 | def _find_seek_points(self, start_time): 46 | seek_points = {} 47 | consumer = self._create_consumer() 48 | try: 49 | topic_partitions = self._topic_partitions_for_set(self._all_partitions_set(consumer)) 50 | for topic_partition in topic_partitions: 51 | # We need to compute the offset independently for each partition via binary search 52 | consumer.assign([topic_partition]) 53 | consumer.seek_to_end(topic_partition) 54 | end_offset = consumer.position(topic_partition) 55 | consumer.seek_to_beginning(topic_partition) 56 | start_offset = consumer.position(topic_partition) 57 | target_offset = self._binary_search(consumer, topic_partition, start_offset, 58 | end_offset, start_time) 59 | seek_points[topic_partition] = target_offset 60 | self._logger.debug('Start offset for {0} is {1}'.format( 61 | topic_partition, target_offset)) 62 | self._logger.info('Start offsets: {0}'.format(seek_points)) 63 | return seek_points 64 | finally: 65 | consumer.close() 66 | 67 | def _all_partitions_set(self, consumer): 68 | all_partitions = consumer.partitions_for_topic(self._topic_name) 69 | partitions = None 70 | if self._partitions: 71 | partitions = all_partitions.intersection(self._partitions) 72 | else: 73 | partitions = all_partitions 74 | return partitions 75 | 76 | def _topic_partitions_for_set(self, partition_set): 77 | return [kafka.TopicPartition(self._topic_name, p) for p in partition_set] 78 | 79 | def _get_next_if_available(self, consumer): 80 | record = None 81 | try: 82 | record = next(consumer) 83 | except StopIteration: 84 | self._logger.debug('Got StopIteration, leaving the record as None') 85 | return record 86 | 87 | def _binary_search(self, consumer, tp, start, end, target_time): 88 | # Overall goal: find the earliest offset that is no earlier than the target time 89 | if start == end: 90 | return start 91 | insertion_point = int(start + ((end - start) / 2)) 92 | consumer.seek(tp, insertion_point) 93 | record = self._get_next_if_available(consumer) 94 | if record: 95 | ts = record.timestamp 96 | if insertion_point == start: 97 | return start if target_time <= ts else end 98 | elif ts < target_time: 99 | return self._binary_search(consumer, tp, insertion_point + 1, end, target_time) 100 | else: 101 | return self._binary_search(consumer, tp, start, insertion_point, target_time) 102 | return start 103 | 104 | def replay(self, start_time, end_time): 105 | """Replay all specified partitions over the specified time range (inclusive). 106 | 107 | Args: 108 | start_time: The start timestamp in milliseconds 109 | end_time: The end timestamp in milliseconds 110 | 111 | Yields: 112 | The next ConsumerRecord found within the given time range 113 | 114 | Raises: 115 | ValueError: If the specified start or end time is invalid 116 | """ 117 | if start_time < 0: 118 | raise ValueError('start_time must be non-negative') 119 | if end_time < 0: 120 | raise ValueError('end_time must be non-negative') 121 | if start_time > self._get_time_millis(): 122 | raise ValueError('start_time must not be in the future') 123 | if start_time > end_time: 124 | raise ValueError('end_time must be at least start_time') 125 | count = 0 126 | last_timestamp = 0 127 | seek_points = self._find_seek_points(start_time) 128 | consumer = self._create_consumer() 129 | try: 130 | # Set up a the consumer to fetch all desired partitions from their seek points 131 | partitions = self._all_partitions_set(consumer) 132 | partition_list = self._topic_partitions_for_set(partitions) 133 | consumer.assign(partition_list) 134 | for tp, offset in six.iteritems(seek_points): 135 | consumer.seek(tp, offset) 136 | while len(partitions) > 0: 137 | record = self._get_next_if_available(consumer) 138 | if not record: 139 | self._logger.info('No more records available. Terminating.') 140 | partitions = set() 141 | else: 142 | last_timestamp = record.timestamp 143 | if last_timestamp > end_time: 144 | # Since partitions are ordered, if we see a too-new timestamp, mark the 145 | # partition complete. 146 | partitions.discard(record.partition) 147 | tp = kafka.TopicPartition(topic=record.topic, partition=record.partition) 148 | if tp not in consumer.paused(): 149 | consumer.pause(tp) 150 | self._logger.debug('Completed partition {0}'.format(tp)) 151 | elif (record.partition in partitions and last_timestamp >= start_time 152 | and last_timestamp <= end_time): 153 | # Send the record to the client if it's within the specified time range 154 | yield record 155 | count += 1 156 | if count % self._log_interval == 0: 157 | self._logger.debug('Processed {0} offsets, last timestamp: {1}'.format( 158 | count, last_timestamp)) 159 | except Exception as e: 160 | self._logger.error('Unexpected exception: {0}'.format(str(e))) 161 | finally: 162 | self._logger.info('Processed {0} offsets, last timestamp: {1}'.format( 163 | count, last_timestamp)) 164 | consumer.close() 165 | 166 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, find_packages 2 | from codecs import open 3 | from os import path 4 | 5 | here = path.abspath(path.dirname(__file__)) 6 | with open(path.join(here, 'README.rst'), encoding='utf-8') as f: 7 | long_description = f.read() 8 | 9 | setup( 10 | name='kafka_replayer', 11 | version='1.0.1', 12 | description='Timestamp-based Kafka topic replayer', 13 | long_description=long_description, 14 | url='https://github.com/SiftScience/python-kafka-replayer', 15 | author='Sift Science', 16 | author_email='opensource@siftscience.com', 17 | license='Apache License 2.0', 18 | classifiers=[ 19 | 'Development Status :: 5 - Production/Stable', 20 | 'Intended Audience :: Developers', 21 | 'Topic :: System :: Distributed Computing', 22 | 'Topic :: System :: Clustering', 23 | 'License :: OSI Approved :: Apache Software License', 24 | 'Programming Language :: Python :: 2.7', 25 | 'Programming Language :: Python :: 3.4', 26 | 'Programming Language :: Python :: 3.5' 27 | ], 28 | keywords='kafka consumer replayer replay', 29 | packages=find_packages(exclude=['contrib', 'docs', 'tests']), 30 | py_modules=['kafka_replayer'], 31 | install_requires=['kafka', 'six'], 32 | test_suite='test', 33 | zip_safe=False, 34 | include_package_data=True 35 | ) 36 | -------------------------------------------------------------------------------- /test/__init__.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | sys.path.append(os.path.dirname(os.path.realpath(__file__)) + "/..") 4 | -------------------------------------------------------------------------------- /test/test_kafka_replayer.py: -------------------------------------------------------------------------------- 1 | import collections 2 | import kafka_replayer 3 | import unittest 4 | 5 | FakeConsumerRecord = collections.namedtuple('FakeConsumerRecord', 6 | ['offset', 'timestamp', 'topic', 'partition']) 7 | 8 | class FakeConsumer(object): 9 | def __init__(self, advance=False): 10 | self._records = [self._fake_record(0, 0), 11 | self._fake_record(1, 1), 12 | self._fake_record(1, 2), 13 | self._fake_record(2, 3), 14 | self._fake_record(3, 4), 15 | self._fake_record(4, 5), 16 | self._fake_record(5, 6)] 17 | self._advance = advance 18 | self._index = 0 19 | self.seek_count = 0 20 | self.pause_set = set() 21 | 22 | def _fake_record(self, ts, offset): 23 | return FakeConsumerRecord(offset, ts, 'fake', 0) 24 | 25 | def seek(self, tp, offset): 26 | self._index = offset 27 | self.seek_count += 1 28 | 29 | def pause(self, tp): 30 | self.pause_set.add(tp) 31 | 32 | def paused(self): 33 | return self.pause_set 34 | 35 | def assign(self, partitions): 36 | pass 37 | 38 | def close(self): 39 | pass 40 | 41 | def __iter__(self): 42 | return self 43 | 44 | def __next__(self): 45 | return self.next() 46 | 47 | def next(self): 48 | if self._index >= 0 and self._index < len(self._records): 49 | record = self._records[self._index] 50 | if self._advance: 51 | self._index += 1 52 | return record 53 | raise StopIteration 54 | 55 | class TestKafkaReplayer(unittest.TestCase): 56 | def test_binary_search(self): 57 | replayer = kafka_replayer.KafkaReplayer('fake') 58 | # search for timestamp 1, which should return offset 1, the first offset with ts = 1 59 | consumer = FakeConsumer() 60 | offset = replayer._binary_search(consumer, ('fake', 0), 0, 6, 1) 61 | self.assertEqual(offset, 1) 62 | self.assertEqual(consumer.seek_count, 3) # 3, 1, and 0 63 | 64 | def test_replay(self): 65 | replayer = kafka_replayer.KafkaReplayer('fake') 66 | consumer = FakeConsumer(advance=True) 67 | replayer._find_seek_points = lambda x : {0: 1} 68 | replayer._create_consumer = lambda: consumer 69 | replayer._all_partitions_set = lambda x : set([0]) 70 | # search between timestamps 1 and 4, which is 5 records 71 | records = [x for x in replayer.replay(1, 4)] 72 | self.assertEqual(len(records), 5) 73 | self.assertEqual(records[0].offset, 1) 74 | self.assertEqual(records[1].offset, 2) 75 | self.assertEqual(records[2].offset, 3) 76 | self.assertEqual(records[3].offset, 4) 77 | self.assertEqual(records[4].offset, 5) 78 | --------------------------------------------------------------------------------