|
| 1 | +#!/usr/bin/env python |
| 2 | +# Adapted from https://github.com/mrafayaleem/kafka-jython |
| 3 | + |
| 4 | +from __future__ import absolute_import, print_function |
| 5 | + |
| 6 | +import argparse |
| 7 | +import logging |
| 8 | +import pprint |
| 9 | +import sys |
| 10 | +import threading |
| 11 | +import traceback |
| 12 | + |
| 13 | +from kafka import KafkaConsumer, KafkaProducer |
| 14 | +from test.fixtures import KafkaFixture, ZookeeperFixture |
| 15 | + |
| 16 | +logging.basicConfig(level=logging.ERROR) |
| 17 | + |
| 18 | + |
| 19 | +def start_brokers(n): |
| 20 | + print('Starting {0} {1}-node cluster...'.format(KafkaFixture.kafka_version, n)) |
| 21 | + print('-> 1 Zookeeper') |
| 22 | + zk = ZookeeperFixture.instance() |
| 23 | + print('---> {0}:{1}'.format(zk.host, zk.port)) |
| 24 | + print() |
| 25 | + |
| 26 | + partitions = min(n, 3) |
| 27 | + replicas = min(n, 3) |
| 28 | + print('-> {0} Brokers [{1} partitions / {2} replicas]'.format(n, partitions, replicas)) |
| 29 | + brokers = [ |
| 30 | + KafkaFixture.instance(i, zk.host, zk.port, zk_chroot='', |
| 31 | + partitions=partitions, replicas=replicas) |
| 32 | + for i in range(n) |
| 33 | + ] |
| 34 | + for broker in brokers: |
| 35 | + print('---> {0}:{1}'.format(broker.host, broker.port)) |
| 36 | + print() |
| 37 | + return brokers |
| 38 | + |
| 39 | + |
| 40 | +class ConsumerPerformance(object): |
| 41 | + |
| 42 | + @staticmethod |
| 43 | + def run(args): |
| 44 | + try: |
| 45 | + props = {} |
| 46 | + for prop in args.consumer_config: |
| 47 | + k, v = prop.split('=') |
| 48 | + try: |
| 49 | + v = int(v) |
| 50 | + except ValueError: |
| 51 | + pass |
| 52 | + if v == 'None': |
| 53 | + v = None |
| 54 | + props[k] = v |
| 55 | + |
| 56 | + if args.brokers: |
| 57 | + brokers = start_brokers(args.brokers) |
| 58 | + props['bootstrap_servers'] = ['{0}:{1}'.format(broker.host, broker.port) |
| 59 | + for broker in brokers] |
| 60 | + print('---> bootstrap_servers={0}'.format(props['bootstrap_servers'])) |
| 61 | + print() |
| 62 | + |
| 63 | + print('-> Producing records') |
| 64 | + record = bytes(bytearray(args.record_size)) |
| 65 | + producer = KafkaProducer(compression_type=args.fixture_compression, |
| 66 | + **props) |
| 67 | + for i in xrange(args.num_records): |
| 68 | + producer.send(topic=args.topic, value=record) |
| 69 | + producer.flush() |
| 70 | + producer.close() |
| 71 | + print('-> OK!') |
| 72 | + print() |
| 73 | + |
| 74 | + print('Initializing Consumer...') |
| 75 | + props['auto_offset_reset'] = 'earliest' |
| 76 | + if 'consumer_timeout_ms' not in props: |
| 77 | + props['consumer_timeout_ms'] = 10000 |
| 78 | + props['metrics_sample_window_ms'] = args.stats_interval * 1000 |
| 79 | + for k, v in props.items(): |
| 80 | + print('---> {0}={1}'.format(k, v)) |
| 81 | + consumer = KafkaConsumer(args.topic, **props) |
| 82 | + print('---> group_id={0}'.format(consumer.config['group_id'])) |
| 83 | + print('---> report stats every {0} secs'.format(args.stats_interval)) |
| 84 | + print('---> raw metrics? {0}'.format(args.raw_metrics)) |
| 85 | + timer_stop = threading.Event() |
| 86 | + timer = StatsReporter(args.stats_interval, consumer, |
| 87 | + event=timer_stop, |
| 88 | + raw_metrics=args.raw_metrics) |
| 89 | + timer.start() |
| 90 | + print('-> OK!') |
| 91 | + print() |
| 92 | + |
| 93 | + records = 0 |
| 94 | + for msg in consumer: |
| 95 | + records += 1 |
| 96 | + if records >= args.num_records: |
| 97 | + break |
| 98 | + print('Consumed {0} records'.format(records)) |
| 99 | + |
| 100 | + timer_stop.set() |
| 101 | + |
| 102 | + except Exception: |
| 103 | + exc_info = sys.exc_info() |
| 104 | + traceback.print_exception(*exc_info) |
| 105 | + sys.exit(1) |
| 106 | + |
| 107 | + |
| 108 | +class StatsReporter(threading.Thread): |
| 109 | + def __init__(self, interval, consumer, event=None, raw_metrics=False): |
| 110 | + super(StatsReporter, self).__init__() |
| 111 | + self.interval = interval |
| 112 | + self.consumer = consumer |
| 113 | + self.event = event |
| 114 | + self.raw_metrics = raw_metrics |
| 115 | + |
| 116 | + def print_stats(self): |
| 117 | + metrics = self.consumer.metrics() |
| 118 | + if self.raw_metrics: |
| 119 | + pprint.pprint(metrics) |
| 120 | + else: |
| 121 | + print('{records-consumed-rate} records/sec ({bytes-consumed-rate} B/sec),' |
| 122 | + ' {fetch-latency-avg} latency,' |
| 123 | + ' {fetch-rate} fetch/s,' |
| 124 | + ' {fetch-size-avg} fetch size,' |
| 125 | + ' {records-lag-max} max record lag,' |
| 126 | + ' {records-per-request-avg} records/req' |
| 127 | + .format(**metrics['consumer-fetch-manager-metrics'])) |
| 128 | + |
| 129 | + |
| 130 | + def print_final(self): |
| 131 | + self.print_stats() |
| 132 | + |
| 133 | + def run(self): |
| 134 | + while self.event and not self.event.wait(self.interval): |
| 135 | + self.print_stats() |
| 136 | + else: |
| 137 | + self.print_final() |
| 138 | + |
| 139 | + |
| 140 | +def get_args_parser(): |
| 141 | + parser = argparse.ArgumentParser( |
| 142 | + description='This tool is used to verify the consumer performance.') |
| 143 | + |
| 144 | + parser.add_argument( |
| 145 | + '--topic', type=str, |
| 146 | + help='Topic for consumer test', |
| 147 | + default='kafka-python-benchmark-test') |
| 148 | + parser.add_argument( |
| 149 | + '--num-records', type=long, |
| 150 | + help='number of messages to consume', |
| 151 | + default=1000000) |
| 152 | + parser.add_argument( |
| 153 | + '--record-size', type=int, |
| 154 | + help='message size in bytes', |
| 155 | + default=100) |
| 156 | + parser.add_argument( |
| 157 | + '--consumer-config', type=str, nargs='+', default=(), |
| 158 | + help='kafka consumer related configuaration properties like ' |
| 159 | + 'bootstrap_servers,client_id etc..') |
| 160 | + parser.add_argument( |
| 161 | + '--fixture-compression', type=str, |
| 162 | + help='specify a compression type for use with broker fixtures / producer') |
| 163 | + parser.add_argument( |
| 164 | + '--brokers', type=int, |
| 165 | + help='Number of kafka brokers to start', |
| 166 | + default=0) |
| 167 | + parser.add_argument( |
| 168 | + '--stats-interval', type=int, |
| 169 | + help='Interval in seconds for stats reporting to console', |
| 170 | + default=5) |
| 171 | + parser.add_argument( |
| 172 | + '--raw-metrics', action='store_true', |
| 173 | + help='Enable this flag to print full metrics dict on each interval') |
| 174 | + return parser |
| 175 | + |
| 176 | + |
| 177 | +if __name__ == '__main__': |
| 178 | + args = get_args_parser().parse_args() |
| 179 | + ConsumerPerformance.run(args) |
0 commit comments