def __init__(self, kafka_brokers, security_protocol="", sasl_mechanism="", sasl_plain_username="", sasl_plain_password="", ssl_context="", timeout=5000): self.kafka_brokers = kafka_brokers self.security_protocol = security_protocol self.sasl_mechanism = sasl_mechanism self.sasl_plain_username = sasl_plain_username self.sasl_plain_password = sasl_plain_password self.ssl_context = ssl_context self.timeout = timeout if security_protocol: self.client = KafkaClient(bootstrap_servers=kafka_brokers, security_protocol=security_protocol, sasl_mechanism=sasl_mechanism, sasl_plain_username=sasl_plain_username, sasl_plain_password=sasl_plain_password, ssl_context=ssl_context, timeout=timeout) else: self.client = KafkaClient(bootstrap_servers=kafka_brokers, timeout=timeout) self.lag_topics_found = [] self.lag_total = 0
def __init__(self, **configs): self.config = copy.copy(self.DEFAULT_CONFIG) self.config.update(configs) self._client = KafkaClient(**self.config) self._coordinator_id = None self.group_id = configs['group_id'] self.topic = configs['topic']
def test_poll(mocker): mocker.patch.object(KafkaClient, '_bootstrap') metadata = mocker.patch.object(KafkaClient, '_maybe_refresh_metadata') _poll = mocker.patch.object(KafkaClient, '_poll') cli = KafkaClient() tasks = mocker.patch.object(cli._delayed_tasks, 'next_at') # metadata timeout wins metadata.return_value = 1000 tasks.return_value = 2 cli.poll() _poll.assert_called_with(1.0, sleep=True) # user timeout wins cli.poll(250) _poll.assert_called_with(0.25, sleep=True) # tasks timeout wins tasks.return_value = 0 cli.poll(250) _poll.assert_called_with(0, sleep=True) # default is request_timeout_ms metadata.return_value = 1000000 tasks.return_value = 10000 cli.poll() _poll.assert_called_with(cli.config['request_timeout_ms'] / 1000.0, sleep=True)
def __init__(self, **configs): log.debug("Starting KafkaAdminClient with configuration: %s", configs) extra_configs = set(configs).difference(self.DEFAULT_CONFIG) if extra_configs: raise KafkaConfigurationError( "Unrecognized configs: {}".format(extra_configs)) self.config = copy.copy(self.DEFAULT_CONFIG) self.config.update(configs) # Configure metrics metrics_tags = {'client-id': self.config['client_id']} metric_config = MetricConfig( samples=self.config['metrics_num_samples'], time_window_ms=self.config['metrics_sample_window_ms'], tags=metrics_tags) reporters = [ reporter() for reporter in self.config['metric_reporters'] ] self._metrics = Metrics(metric_config, reporters) self._client = KafkaClient(metrics=self._metrics, metric_group_prefix='admin', **self.config) # Get auto-discovered version from client if necessary if self.config['api_version'] is None: self.config['api_version'] = self._client.config['api_version'] self._closed = False self._refresh_controller_id() log.debug("KafkaAdminClient started.")
def _create_kafka_client(self): kafka_conn_str = self.instance.get('kafka_connect_str') if not isinstance(kafka_conn_str, (string_types, list)): raise ConfigurationError('kafka_connect_str should be string or list of strings') kafka_version = self.instance.get('kafka_client_api_version') if isinstance(kafka_version, str): kafka_version = tuple(map(int, kafka_version.split("."))) kafka_client = KafkaClient( bootstrap_servers=kafka_conn_str, client_id='dd-agent', request_timeout_ms=self.init_config.get('kafka_timeout', DEFAULT_KAFKA_TIMEOUT) * 1000, # if `kafka_client_api_version` is not set, then kafka-python automatically probes the cluster for broker # version during the bootstrapping process. Note that probing randomly picks a broker to probe, so in a # mixed-version cluster probing returns a non-deterministic result. api_version=kafka_version, # While we check for SSL params, if not present they will default to the kafka-python values for plaintext # connections security_protocol=self.instance.get('security_protocol', 'PLAINTEXT'), sasl_mechanism=self.instance.get('sasl_mechanism'), sasl_plain_username=self.instance.get('sasl_plain_username'), sasl_plain_password=self.instance.get('sasl_plain_password'), sasl_kerberos_service_name=self.instance.get('sasl_kerberos_service_name', 'kafka'), sasl_kerberos_domain_name=self.instance.get('sasl_kerberos_domain_name'), ssl_cafile=self.instance.get('ssl_cafile'), ssl_check_hostname=self.instance.get('ssl_check_hostname', True), ssl_certfile=self.instance.get('ssl_certfile'), ssl_keyfile=self.instance.get('ssl_keyfile'), ssl_crlfile=self.instance.get('ssl_crlfile'), ssl_password=self.instance.get('ssl_password'), ) # Force initial population of the local cluster metadata cache kafka_client.poll(future=kafka_client.cluster.request_update()) if kafka_client.cluster.topics(exclude_internal_topics=False) is None: raise RuntimeError("Local cluster metadata cache did not populate.") return kafka_client
def test_send(conn): cli = KafkaClient() # Send to unknown node => raises AssertionError try: cli.send(2, None) assert False, 'Exception not raised' except AssertionError: pass # Send to disconnected node => NodeNotReady conn.state = ConnectionStates.DISCONNECTED f = cli.send(0, None) assert f.failed() assert isinstance(f.exception, Errors.NodeNotReadyError) conn.state = ConnectionStates.CONNECTED cli._maybe_connect(0) # ProduceRequest w/ 0 required_acks -> no response request = ProduceRequest[0](0, 0, []) ret = cli.send(0, request) assert conn.send.called_with(request, expect_response=False) assert isinstance(ret, Future) request = MetadataRequest[0]([]) cli.send(0, request) assert conn.send.called_with(request, expect_response=True)
def cli(mocker, conn): mocker.patch('kafka.cluster.dns_lookup', return_value=[(socket.AF_INET, None, None, None, ('localhost', 9092))]) client = KafkaClient(api_version=(0, 9)) client.poll(future=client.cluster.request_update()) return client
def test_poll(mocker): metadata = mocker.patch.object(KafkaClient, '_maybe_refresh_metadata') _poll = mocker.patch.object(KafkaClient, '_poll') ifrs = mocker.patch.object(KafkaClient, 'in_flight_request_count') ifrs.return_value = 1 cli = KafkaClient(api_version=(0, 9)) # metadata timeout wins metadata.return_value = 1000 cli.poll() _poll.assert_called_with(1.0) # user timeout wins cli.poll(250) _poll.assert_called_with(0.25) # default is request_timeout_ms metadata.return_value = 1000000 cli.poll() _poll.assert_called_with(cli.config['request_timeout_ms'] / 1000.0) # If no in-flight-requests, drop timeout to retry_backoff_ms ifrs.return_value = 0 cli.poll() _poll.assert_called_with(cli.config['retry_backoff_ms'] / 1000.0)
def __init__(self, **configs): self.zk_client = None self.zk_configuration = None self.zookeeper_sleep_time = 5 self.zookeeper_max_retries = 5 self.kafka_sleep_time = 5 self.kafka_max_retries = 5 self.client = KafkaClient(**configs) self.refresh()
def test_bootstrap_servers(mocker, bootstrap, expected_hosts): mocker.patch.object(KafkaClient, '_bootstrap') if bootstrap is None: KafkaClient() else: KafkaClient(bootstrap_servers=bootstrap) # host order is randomized internally, so resort before testing (hosts, ), _ = KafkaClient._bootstrap.call_args # pylint: disable=no-member assert sorted(hosts) == sorted(expected_hosts)
def test_poll(mocker): mocker.patch.object(KafkaClient, '_bootstrap') metadata = mocker.patch.object(KafkaClient, '_maybe_refresh_metadata') _poll = mocker.patch.object(KafkaClient, '_poll') cli = KafkaClient(api_version=(0, 9)) tasks = mocker.patch.object(cli._delayed_tasks, 'next_at') # metadata timeout wins metadata.return_value = 1000 tasks.return_value = 2 cli.poll() _poll.assert_called_with(1.0, sleep=True) # user timeout wins cli.poll(250) _poll.assert_called_with(0.25, sleep=True) # tasks timeout wins tasks.return_value = 0 cli.poll(250) _poll.assert_called_with(0, sleep=True) # default is request_timeout_ms metadata.return_value = 1000000 tasks.return_value = 10000 cli.poll() _poll.assert_called_with(cli.config['request_timeout_ms'] / 1000.0, sleep=True)
def test_finish_connect(conn): cli = KafkaClient() try: # Node not in metadata, raises AssertionError cli._initiate_connect(2) except AssertionError: pass else: assert False, 'Exception not raised' assert 0 not in cli._conns cli._initiate_connect(0) conn.connect.return_value = ConnectionStates.CONNECTING state = cli._finish_connect(0) assert 0 in cli._connecting assert state is ConnectionStates.CONNECTING conn.connect.return_value = ConnectionStates.CONNECTED state = cli._finish_connect(0) assert 0 not in cli._connecting assert state is ConnectionStates.CONNECTED # Failure to connect should trigger metadata update assert not cli.cluster._need_update cli._connecting.add(0) conn.connect.return_value = ConnectionStates.DISCONNECTED state = cli._finish_connect(0) assert 0 not in cli._connecting assert state is ConnectionStates.DISCONNECTED assert cli.cluster._need_update
def __init__(self, **configs): # Only check for extra config keys in top-level class extra_configs = set(configs).difference(self.DEFAULT_CONFIG) if extra_configs: raise KafkaConfigurationError("Unrecognized configs: %s" % extra_configs) self.config = copy.copy(self.DEFAULT_CONFIG) self.config.update(configs) self._client = KafkaClient(**self.config)
def __init__(self, *topics, **configs): self.config = copy.copy(self.DEFAULT_CONFIG) for key in self.config: if key in configs: self.config[key] = configs.pop(key) # Only check for extra config keys in top-level class assert not configs, 'Unrecognized configs: %s' % configs deprecated = {'smallest': 'earliest', 'largest': 'latest'} if self.config['auto_offset_reset'] in deprecated: new_config = deprecated[self.config['auto_offset_reset']] log.warning('use auto_offset_reset=%s (%s is deprecated)', new_config, self.config['auto_offset_reset']) self.config['auto_offset_reset'] = new_config metrics_tags = {'client-id': self.config['client_id']} metric_config = MetricConfig(samples=self.config['metrics_num_samples'], time_window_ms=self.config['metrics_sample_window_ms'], tags=metrics_tags) reporters = [reporter() for reporter in self.config['metric_reporters']] self._metrics = Metrics(metric_config, reporters) # TODO _metrics likely needs to be passed to KafkaClient, etc. # api_version was previously a str. Accept old format for now if isinstance(self.config['api_version'], str): str_version = self.config['api_version'] if str_version == 'auto': self.config['api_version'] = None else: self.config['api_version'] = tuple(map(int, str_version.split('.'))) log.warning('use api_version=%s [tuple] -- "%s" as str is deprecated', str(self.config['api_version']), str_version) self._client = KafkaClient(metrics=self._metrics, **self.config) # Get auto-discovered version from client if necessary if self.config['api_version'] is None: self.config['api_version'] = self._client.config['api_version'] self._subscription = SubscriptionState(self.config['auto_offset_reset']) self._fetcher = Fetcher( self._client, self._subscription, self._metrics, **self.config) self._coordinator = ConsumerCoordinator( self._client, self._subscription, self._metrics, assignors=self.config['partition_assignment_strategy'], **self.config) self._closed = False self._iterator = None self._consumer_timeout = float('inf') if topics: self._subscription.subscribe(topics=topics) self._client.set_topics(topics)
def __init__(self, *topics, **configs): self.config = copy.copy(self.DEFAULT_CONFIG) for key in self.config: if key in configs: self.config[key] = configs.pop(key) # Only check for extra config keys in top-level class assert not configs, 'Unrecognized configs: %s' % configs deprecated = {'smallest': 'earliest', 'largest': 'latest' } if self.config['auto_offset_reset'] in deprecated: new_config = deprecated[self.config['auto_offset_reset']] log.warning('use auto_offset_reset=%s (%s is deprecated)', new_config, self.config['auto_offset_reset']) self.config['auto_offset_reset'] = new_config metrics_tags = {'client-id': self.config['client_id']} metric_config = MetricConfig(samples=self.config['metrics_num_samples'], time_window_ms=self.config['metrics_sample_window_ms'], tags=metrics_tags) reporters = [reporter() for reporter in self.config['metric_reporters']] reporters.append(DictReporter('kafka.consumer')) self._metrics = Metrics(metric_config, reporters) metric_group_prefix = 'consumer' # TODO _metrics likely needs to be passed to KafkaClient, etc. self._client = KafkaClient(**self.config) # Check Broker Version if not set explicitly if self.config['api_version'] == 'auto': self.config['api_version'] = self._client.check_version() assert self.config['api_version'] in ('0.9', '0.8.2', '0.8.1', '0.8.0'), 'Unrecognized api version' # Convert api_version config to tuple for easy comparisons self.config['api_version'] = tuple( map(int, self.config['api_version'].split('.'))) self._subscription = SubscriptionState(self.config['auto_offset_reset']) self._fetcher = Fetcher( self._client, self._subscription, self._metrics, metric_group_prefix, **self.config) self._coordinator = ConsumerCoordinator( self._client, self._subscription, self._metrics, metric_group_prefix, assignors=self.config['partition_assignment_strategy'], **self.config) self._closed = False self._iterator = None self._consumer_timeout = float('inf') if topics: self._subscription.subscribe(topics=topics) self._client.set_topics(topics)
def test_maybe_refresh_metadata_ttl(mocker): mocker.patch.object(KafkaClient, '_bootstrap') _poll = mocker.patch.object(KafkaClient, '_poll') cli = KafkaClient(request_timeout_ms=9999999, retry_backoff_ms=2222) tasks = mocker.patch.object(cli._delayed_tasks, 'next_at') tasks.return_value = 9999999 ttl = mocker.patch.object(cli.cluster, 'ttl') ttl.return_value = 1234 cli.poll(timeout_ms=9999999, sleep=True) _poll.assert_called_with(1.234, sleep=True)
def test_initiate_connect(conn): cli = KafkaClient() try: # Node not in metadata, raises AssertionError cli._initiate_connect(2) except AssertionError: pass else: assert False, 'Exception not raised' assert 0 not in cli._conns state = cli._initiate_connect(0) assert cli._conns[0] is conn assert state is conn.state
def test_init(conn): cli = KafkaClient() coordinator = ConsumerCoordinator(cli, SubscriptionState()) # metadata update on init assert cli.cluster._need_update is True assert WeakMethod(coordinator._handle_metadata_update) in cli.cluster._listeners
def test_autocommit_enable_api_version(conn, api_version): coordinator = ConsumerCoordinator( KafkaClient(), SubscriptionState(), api_version=api_version) if api_version < (0, 8, 1): assert coordinator._auto_commit_task is None else: assert coordinator._auto_commit_task is not None
def __init__(self, **configs): log.debug("Starting KafkaAdminClient with configuration: %s", configs) extra_configs = set(configs).difference(self.DEFAULT_CONFIG) if extra_configs: raise KafkaConfigurationError("Unrecognized configs: {}".format(extra_configs)) self.config = copy.copy(self.DEFAULT_CONFIG) self.config.update(configs) # Configure metrics metrics_tags = {'client-id': self.config['client_id']} metric_config = MetricConfig(samples=self.config['metrics_num_samples'], time_window_ms=self.config['metrics_sample_window_ms'], tags=metrics_tags) reporters = [reporter() for reporter in self.config['metric_reporters']] self._metrics = Metrics(metric_config, reporters) self._client = KafkaClient(metrics=self._metrics, metric_group_prefix='admin', **self.config) # Get auto-discovered version from client if necessary if self.config['api_version'] is None: self.config['api_version'] = self._client.config['api_version'] self._closed = False self._refresh_controller_id() log.debug("KafkaAdminClient started.")
def test_maybe_connect(conn): cli = KafkaClient() try: # Node not in metadata, raises AssertionError cli._maybe_connect(2) except AssertionError: pass else: assert False, 'Exception not raised' # New node_id creates a conn object assert 0 not in cli._conns conn.state = ConnectionStates.DISCONNECTED conn.connect.side_effect = lambda: conn._set_conn_state(ConnectionStates.CONNECTING) assert cli._maybe_connect(0) is False assert cli._conns[0] is conn
def test_maybe_auto_commit_offsets_sync(mocker, api_version, group_id, enable, error, has_auto_commit, commit_offsets, warn, exc): mock_warn = mocker.patch('kafka.coordinator.consumer.log.warning') mock_exc = mocker.patch('kafka.coordinator.consumer.log.exception') client = KafkaClient(api_version=api_version) coordinator = ConsumerCoordinator(client, SubscriptionState(), Metrics(), api_version=api_version, session_timeout_ms=30000, max_poll_interval_ms=30000, enable_auto_commit=enable, group_id=group_id) commit_sync = mocker.patch.object(coordinator, 'commit_offsets_sync', side_effect=error) if has_auto_commit: assert coordinator.next_auto_commit_deadline is not None else: assert coordinator.next_auto_commit_deadline is None assert coordinator._maybe_auto_commit_offsets_sync() is None if has_auto_commit: assert coordinator.next_auto_commit_deadline is not None assert commit_sync.call_count == (1 if commit_offsets else 0) assert mock_warn.call_count == (1 if warn else 0) assert mock_exc.call_count == (1 if exc else 0)
def test_maybe_auto_commit_offsets_sync(mocker, api_version, group_id, enable, error, has_auto_commit, commit_offsets, warn, exc): mock_warn = mocker.patch('kafka.coordinator.consumer.log.warning') mock_exc = mocker.patch('kafka.coordinator.consumer.log.exception') coordinator = ConsumerCoordinator(KafkaClient(), SubscriptionState(), Metrics(), 'consumer', api_version=api_version, enable_auto_commit=enable, group_id=group_id) commit_sync = mocker.patch.object(coordinator, 'commit_offsets_sync', side_effect=error) if has_auto_commit: assert coordinator._auto_commit_task is not None coordinator._auto_commit_task.enable() assert coordinator._auto_commit_task._enabled is True else: assert coordinator._auto_commit_task is None assert coordinator._maybe_auto_commit_offsets_sync() is None if has_auto_commit: assert coordinator._auto_commit_task is not None assert coordinator._auto_commit_task._enabled is False assert commit_sync.call_count == (1 if commit_offsets else 0) assert mock_warn.call_count == (1 if warn else 0) assert mock_exc.call_count == (1 if exc else 0)
def send_task(logger, zk_cli): # get next task task = tasks.next_task(zk_cli, TASK_DEFINITION_PATH) topic = JobSourceTopic() # get postfix val, stats = zk_cli.get(KAFKA_POSTFIX_PATH) producer = topic.init_producer() producer.change_postfix(val) kfk_cli = KafkaClient(bootstrap_servers=settings.KAFKA_SERVER) # current topics (error_code, topic, is_internal, partitions) is_fetch_metadata_success = False try: topics_res = kafka_utils.get_metadata(kfk_cli, 10000) if topics_res is not None: topics = (x[1] for x in topics_res.topics) logger.debug("Current topics in kafka: %s" % str(list(topics))) is_fetch_metadata_success = True except Exception: pass if not is_fetch_metadata_success: logger.warn("Failed to fetch metadata from kafka") producer.produce(task) logger.info('sent to Topic %s, feed=%2d. %s' % (producer._topic_name, task['order'], task['name'])) return task
def get_clients(self, cnt=1, client_id=None): if client_id is None: client_id = 'client' return tuple( KafkaClient(client_id='%s_%s' % (client_id, random_string(4)), bootstrap_servers=self.bootstrap_server()) for x in range(cnt))
def init_kafka_client(self): try: self.kafka_client = KafkaClient( api_version_auto_timeout_ms=self.api_version_auto_timeout_ms, bootstrap_servers=self.config["bootstrap_uri"], client_id=self.config["client_id"], security_protocol=self.config["security_protocol"], ssl_cafile=self.config["ssl_cafile"], ssl_certfile=self.config["ssl_certfile"], ssl_keyfile=self.config["ssl_keyfile"], ) return True except (NodeNotReadyError, NoBrokersAvailable): self.log.warning("No Brokers available yet, retrying init_kafka_client()") time.sleep(2.0) return False
def test_bootstrap_failure(conn): conn.state = ConnectionStates.DISCONNECTED cli = KafkaClient() conn.assert_called_once_with('localhost', 9092, **cli.config) conn.connect.assert_called_with() conn.close.assert_called_with() assert cli._bootstrap_fails == 1 assert cli.cluster.brokers() == set()
def test_bootstrap(mocker, conn): conn.state = ConnectionStates.CONNECTED cli = KafkaClient(api_version=(0, 9)) mocker.patch.object(cli, '_selector') future = cli.cluster.request_update() cli.poll(future=future) assert future.succeeded() args, kwargs = conn.call_args assert args == ('localhost', 9092, socket.AF_UNSPEC) kwargs.pop('state_change_callback') kwargs.pop('node_id') assert kwargs == cli.config conn.send.assert_called_once_with(MetadataRequest[0]([]), blocking=False) assert cli._bootstrap_fails == 0 assert cli.cluster.brokers() == set([BrokerMetadata(0, 'foo', 12, None), BrokerMetadata(1, 'bar', 34, None)])
def __init__(self, *topics, **configs): self.config = copy.copy(self.DEFAULT_CONFIG) for key in self.config: if key in configs: self.config[key] = configs.pop(key) # Only check for extra config keys in top-level class assert not configs, 'Unrecognized configs: %s' % configs deprecated = {'smallest': 'earliest', 'largest': 'latest'} if self.config['auto_offset_reset'] in deprecated: new_config = deprecated[self.config['auto_offset_reset']] log.warning('use auto_offset_reset=%s (%s is deprecated)', new_config, self.config['auto_offset_reset']) self.config['auto_offset_reset'] = new_config self._client = KafkaClient(**self.config) # Check Broker Version if not set explicitly if self.config['api_version'] == 'auto': self.config['api_version'] = self._client.check_version() assert self.config['api_version'] in ( '0.9', '0.8.2', '0.8.1', '0.8.0'), 'Unrecognized api version' # Convert api_version config to tuple for easy comparisons self.config['api_version'] = tuple( map(int, self.config['api_version'].split('.'))) self._subscription = SubscriptionState( self.config['auto_offset_reset']) self._fetcher = Fetcher(self._client, self._subscription, **self.config) self._coordinator = ConsumerCoordinator( self._client, self._subscription, assignors=self.config['partition_assignment_strategy'], **self.config) self._closed = False self._iterator = None self._consumer_timeout = float('inf') #self.metrics = None if topics: self._subscription.subscribe(topics=topics) self._client.set_topics(topics)
def test_bootstrap_success(conn): conn.state = ConnectionStates.CONNECTED cli = KafkaClient() conn.assert_called_once_with('localhost', 9092, **cli.config) conn.connect.assert_called_with() conn.send.assert_called_once_with(MetadataRequest([])) assert cli._bootstrap_fails == 0 assert cli.cluster.brokers() == set([BrokerMetadata(0, 'foo', 12), BrokerMetadata(1, 'bar', 34)])
def _determine_kafka_version(cls, init_config, instance): """Return the Kafka cluster version as a tuple.""" kafka_version = instance.get('kafka_client_api_version') if isinstance(kafka_version, str): kafka_version = tuple(map(int, kafka_version.split("."))) if kafka_version is None: # if unspecified by the user, we have to probe the cluster kafka_connect_str = instance.get( 'kafka_connect_str') # TODO call validation method kafka_client = KafkaClient( bootstrap_servers=kafka_connect_str, client_id='dd-agent', request_timeout_ms=init_config.get( 'kafka_timeout', DEFAULT_KAFKA_TIMEOUT) * 1000, # if `kafka_client_api_version` is not set, then kafka-python automatically probes the cluster for # broker version during the bootstrapping process. Note that this returns the first version found, so in # a mixed-version cluster this will be a non-deterministic result. api_version=kafka_version, # While we check for SASL/SSL params, if not present they will default to the kafka-python values for # plaintext connections security_protocol=instance.get('security_protocol', 'PLAINTEXT'), sasl_mechanism=instance.get('sasl_mechanism'), sasl_plain_username=instance.get('sasl_plain_username'), sasl_plain_password=instance.get('sasl_plain_password'), sasl_kerberos_service_name=instance.get( 'sasl_kerberos_service_name', 'kafka'), sasl_kerberos_domain_name=instance.get( 'sasl_kerberos_domain_name'), ssl_cafile=instance.get('ssl_cafile'), ssl_check_hostname=instance.get('ssl_check_hostname', True), ssl_certfile=instance.get('ssl_certfile'), ssl_keyfile=instance.get('ssl_keyfile'), ssl_crlfile=instance.get('ssl_crlfile'), ssl_password=instance.get('ssl_password'), ) # version probing happens automatically as part of KafkaClient's __init__() kafka_version = kafka_client.config['api_version'] # Currently, this client is only used for probing, so we need to close it to avoid stale connections on # older Kafka brokers. We can't re-use in new code path because KafkaAdminClient doesn't currently support # passing in an existing client. # TODO this could be re-used by the legacy version of the check to make maintenance easier... ie, we don't # have multiple sections of code instantiating clients kafka_client.close() return kafka_version
def __init__(self, **configs): log.debug("Starting Kafka administration interface") extra_configs = set(configs).difference(self.DEFAULT_CONFIG) if extra_configs: raise KafkaConfigurationError("Unrecognized configs: %s" % extra_configs) self.config = copy.copy(self.DEFAULT_CONFIG) self.config.update(configs) # api_version was previously a str. accept old format for now if isinstance(self.config['api_version'], str): deprecated = self.config['api_version'] if deprecated == 'auto': self.config['api_version'] = None else: self.config['api_version'] = tuple( map(int, deprecated.split('.'))) log.warning( 'use api_version=%s [tuple] -- "%s" as str is deprecated', str(self.config['api_version']), deprecated) # Configure metrics metrics_tags = {'client-id': self.config['client_id']} metric_config = MetricConfig( samples=self.config['metrics_num_samples'], time_window_ms=self.config['metrics_sample_window_ms'], tags=metrics_tags) reporters = [ reporter() for reporter in self.config['metric_reporters'] ] self._metrics = Metrics(metric_config, reporters) self._client = KafkaClient(metrics=self._metrics, metric_group_prefix='admin', **self.config) # Get auto-discovered version from client if necessary if self.config['api_version'] is None: self.config['api_version'] = self._client.config['api_version'] self._closed = False self._refresh_controller_id() log.debug('Kafka administration interface started')
def test_maybe_refresh_metadata_backoff(mocker): mocker.patch.object(KafkaClient, '_bootstrap') _poll = mocker.patch.object(KafkaClient, '_poll') cli = KafkaClient(request_timeout_ms=9999999, retry_backoff_ms=2222) tasks = mocker.patch.object(cli._delayed_tasks, 'next_at') tasks.return_value = 9999999 ttl = mocker.patch.object(cli.cluster, 'ttl') ttl.return_value = 0 now = time.time() t = mocker.patch('time.time') t.return_value = now cli._last_no_node_available_ms = now * 1000 cli.poll(timeout_ms=9999999, sleep=True) _poll.assert_called_with(2.222, sleep=True)
def __init__(self, *topics, **configs): self.config = copy.copy(self.DEFAULT_CONFIG) for key in self.config: if key in configs: self.config[key] = configs.pop(key) # Only check for extra config keys in top-level class assert not configs, 'Unrecognized configs: %s' % configs deprecated = {'smallest': 'earliest', 'largest': 'latest'} if self.config['auto_offset_reset'] in deprecated: new_config = deprecated[self.config['auto_offset_reset']] log.warning('use auto_offset_reset=%s (%s is deprecated)', new_config, self.config['auto_offset_reset']) self.config['auto_offset_reset'] = new_config metrics_tags = {'client-id': self.config['client_id']} metric_config = MetricConfig(samples=self.config['metrics_num_samples'], time_window_ms=self.config['metrics_sample_window_ms'], tags=metrics_tags) reporters = [reporter() for reporter in self.config['metric_reporters']] self._metrics = Metrics(metric_config, reporters) metric_group_prefix = 'consumer' # TODO _metrics likely needs to be passed to KafkaClient, etc. # api_version was previously a str. accept old format for now if isinstance(self.config['api_version'], str): str_version = self.config['api_version'] if str_version == 'auto': self.config['api_version'] = None else: self.config['api_version'] = tuple(map(int, str_version.split('.'))) log.warning('use api_version=%s (%s is deprecated)', str(self.config['api_version']), str_version) self._client = KafkaClient(**self.config) # Get auto-discovered version from client if necessary if self.config['api_version'] is None: self.config['api_version'] = self._client.config['api_version'] self._subscription = SubscriptionState(self.config['auto_offset_reset']) self._fetcher = Fetcher( self._client, self._subscription, self._metrics, metric_group_prefix, **self.config) self._coordinator = ConsumerCoordinator( self._client, self._subscription, self._metrics, metric_group_prefix, assignors=self.config['partition_assignment_strategy'], **self.config) self._closed = False self._iterator = None self._consumer_timeout = float('inf') if topics: self._subscription.subscribe(topics=topics) self._client.set_topics(topics)
def test_maybe_refresh_metadata_update(mocker): mocker.patch.object(KafkaClient, '_bootstrap') _poll = mocker.patch.object(KafkaClient, '_poll') cli = KafkaClient(request_timeout_ms=9999999, retry_backoff_ms=2222) tasks = mocker.patch.object(cli._delayed_tasks, 'next_at') tasks.return_value = 9999999 ttl = mocker.patch.object(cli.cluster, 'ttl') ttl.return_value = 0 mocker.patch.object(cli, 'least_loaded_node', return_value='foobar') mocker.patch.object(cli, '_can_send_request', return_value=True) send = mocker.patch.object(cli, 'send') cli.poll(timeout_ms=9999999, sleep=True) _poll.assert_called_with(0, sleep=True) assert cli._metadata_refresh_in_progress request = MetadataRequest[0]([]) send.assert_called_with('foobar', request)
def test_maybe_connect(conn): cli = KafkaClient() try: # Node not in metadata, raises AssertionError cli._maybe_connect(2) except AssertionError: pass else: assert False, 'Exception not raised' assert 0 not in cli._conns conn.state = ConnectionStates.DISCONNECTED conn.connect.side_effect = lambda: ConnectionStates.CONNECTING assert cli._maybe_connect(0) is False assert cli._conns[0] is conn assert 0 in cli._connecting conn.state = ConnectionStates.CONNECTING conn.connect.side_effect = lambda: ConnectionStates.CONNECTED assert cli._maybe_connect(0) is True assert 0 not in cli._connecting # Failure to connect should trigger metadata update assert cli.cluster._need_update is False cli._connecting.add(0) conn.state = ConnectionStates.CONNECTING conn.connect.side_effect = lambda: ConnectionStates.DISCONNECTED assert cli._maybe_connect(0) is False assert 0 not in cli._connecting assert cli.cluster._need_update is True
def test_maybe_refresh_metadata_failure(mocker): mocker.patch.object(KafkaClient, '_bootstrap') _poll = mocker.patch.object(KafkaClient, '_poll') cli = KafkaClient(request_timeout_ms=9999999, retry_backoff_ms=2222) tasks = mocker.patch.object(cli._delayed_tasks, 'next_at') tasks.return_value = 9999999 ttl = mocker.patch.object(cli.cluster, 'ttl') ttl.return_value = 0 mocker.patch.object(cli, 'least_loaded_node', return_value='foobar') now = time.time() t = mocker.patch('time.time') t.return_value = now cli.poll(timeout_ms=9999999, sleep=True) _poll.assert_called_with(0, sleep=True) assert cli._last_no_node_available_ms == now * 1000 assert not cli._metadata_refresh_in_progress
def __init__(self, *topics, **configs): self.config = copy.copy(self.DEFAULT_CONFIG) for key in self.config: if key in configs: self.config[key] = configs.pop(key) # Only check for extra config keys in top-level class assert not configs, 'Unrecognized configs: %s' % configs deprecated = {'smallest': 'earliest', 'largest': 'latest' } if self.config['auto_offset_reset'] in deprecated: new_config = deprecated[self.config['auto_offset_reset']] log.warning('use auto_offset_reset=%s (%s is deprecated)', new_config, self.config['auto_offset_reset']) self.config['auto_offset_reset'] = new_config metrics_tags = {'client-id': self.config['client_id']} metric_config = MetricConfig(samples=self.config['metrics_num_samples'], time_window_ms=self.config['metrics_sample_window_ms'], tags=metrics_tags) reporters = [reporter() for reporter in self.config['metric_reporters']] reporters.append(DictReporter('kafka.consumer')) self._metrics = Metrics(metric_config, reporters) metric_group_prefix = 'consumer' # TODO _metrics likely needs to be passed to KafkaClient, etc. self._client = KafkaClient(**self.config) # Check Broker Version if not set explicitly if self.config['api_version'] == 'auto': self.config['api_version'] = self._client.check_version() assert self.config['api_version'] in ('0.10', '0.9', '0.8.2', '0.8.1', '0.8.0'), 'Unrecognized api version' # Convert api_version config to tuple for easy comparisons self.config['api_version'] = tuple( map(int, self.config['api_version'].split('.'))) self._subscription = SubscriptionState(self.config['auto_offset_reset']) self._fetcher = Fetcher( self._client, self._subscription, self._metrics, metric_group_prefix, **self.config) self._coordinator = ConsumerCoordinator( self._client, self._subscription, self._metrics, metric_group_prefix, assignors=self.config['partition_assignment_strategy'], **self.config) self._closed = False self._iterator = None self._consumer_timeout = float('inf') if topics: self._subscription.subscribe(topics=topics) self._client.set_topics(topics)
def test_set_topics(mocker): request_update = mocker.patch.object(ClusterMetadata, 'request_update') request_update.side_effect = lambda: Future() cli = KafkaClient(api_version=(0, 10)) # replace 'empty' with 'non empty' request_update.reset_mock() fut = cli.set_topics(['t1', 't2']) assert not fut.is_done request_update.assert_called_with() # replace 'non empty' with 'same' request_update.reset_mock() fut = cli.set_topics(['t1', 't2']) assert fut.is_done assert fut.value == set(['t1', 't2']) request_update.assert_not_called() # replace 'non empty' with 'empty' request_update.reset_mock() fut = cli.set_topics([]) assert fut.is_done assert fut.value == set() request_update.assert_not_called()
def test_is_disconnected(conn): cli = KafkaClient() # False if not connected yet conn.state = ConnectionStates.DISCONNECTED assert not cli.is_disconnected(0) cli._maybe_connect(0) assert cli.is_disconnected(0) conn.state = ConnectionStates.CONNECTING assert not cli.is_disconnected(0) conn.state = ConnectionStates.CONNECTED assert not cli.is_disconnected(0)
def test_send(conn): cli = KafkaClient() try: cli.send(2, None) except Errors.NodeNotReadyError: pass else: assert False, 'NodeNotReadyError not raised' cli._initiate_connect(0) # ProduceRequest w/ 0 required_acks -> no response request = ProduceRequest(0, 0, []) ret = cli.send(0, request) assert conn.send.called_with(request, expect_response=False) assert isinstance(ret, Future) request = MetadataRequest([]) cli.send(0, request) assert conn.send.called_with(request, expect_response=True)
def test_can_connect(conn): cli = KafkaClient() # Node is not in broker metadata - cant connect assert not cli._can_connect(2) # Node is in broker metadata but not in _conns assert 0 not in cli._conns assert cli._can_connect(0) # Node is connected, can't reconnect cli._initiate_connect(0) assert not cli._can_connect(0) # Node is disconnected, can connect cli._conns[0].state = ConnectionStates.DISCONNECTED assert cli._can_connect(0) # Node is disconnected, but blacked out conn.blacked_out.return_value = True assert not cli._can_connect(0)
def __init__(self, *topics, **configs): self.config = copy.copy(self.DEFAULT_CONFIG) for key in self.config: if key in configs: self.config[key] = configs.pop(key) # Only check for extra config keys in top-level class assert not configs, 'Unrecognized configs: %s' % configs deprecated = {'smallest': 'earliest', 'largest': 'latest' } if self.config['auto_offset_reset'] in deprecated: new_config = deprecated[self.config['auto_offset_reset']] log.warning('use auto_offset_reset=%s (%s is deprecated)', new_config, self.config['auto_offset_reset']) self.config['auto_offset_reset'] = new_config self._client = KafkaClient(**self.config) # Check Broker Version if not set explicitly if self.config['api_version'] == 'auto': self.config['api_version'] = self._client.check_version() assert self.config['api_version'] in ('0.9', '0.8.2', '0.8.1', '0.8.0'), 'Unrecognized api version' # Convert api_version config to tuple for easy comparisons self.config['api_version'] = tuple( map(int, self.config['api_version'].split('.'))) self._subscription = SubscriptionState(self.config['auto_offset_reset']) self._fetcher = Fetcher( self._client, self._subscription, **self.config) self._coordinator = ConsumerCoordinator( self._client, self._subscription, assignors=self.config['partition_assignment_strategy'], **self.config) self._closed = False self._iterator = None self._consumer_timeout = float('inf') #self.metrics = None if topics: self._subscription.subscribe(topics=topics) self._client.set_topics(topics)
def test_poll(mocker): mocker.patch.object(KafkaClient, '_bootstrap') metadata = mocker.patch.object(KafkaClient, '_maybe_refresh_metadata') _poll = mocker.patch.object(KafkaClient, '_poll') cli = KafkaClient(api_version=(0, 9)) # metadata timeout wins metadata.return_value = 1000 cli.poll() _poll.assert_called_with(1.0) # user timeout wins cli.poll(250) _poll.assert_called_with(0.25) # default is request_timeout_ms metadata.return_value = 1000000 cli.poll() _poll.assert_called_with(cli.config['request_timeout_ms'] / 1000.0)
def __init__(self, *topics, **configs): self.config = copy.copy(self.DEFAULT_CONFIG) for key in self.config: if key in configs: self.config[key] = configs.pop(key) # Only check for extra config keys in top-level class assert not configs, "Unrecognized configs: %s" % configs deprecated = {"smallest": "earliest", "largest": "latest"} if self.config["auto_offset_reset"] in deprecated: new_config = deprecated[self.config["auto_offset_reset"]] log.warning("use auto_offset_reset=%s (%s is deprecated)", new_config, self.config["auto_offset_reset"]) self.config["auto_offset_reset"] = new_config self._client = KafkaClient(**self.config) # Check Broker Version if not set explicitly if self.config["api_version"] == "auto": self.config["api_version"] = self._client.check_version() assert self.config["api_version"] in ("0.9", "0.8.2", "0.8.1", "0.8.0") # Convert api_version config to tuple for easy comparisons self.config["api_version"] = tuple(map(int, self.config["api_version"].split("."))) self._subscription = SubscriptionState(self.config["auto_offset_reset"]) self._fetcher = Fetcher(self._client, self._subscription, **self.config) self._coordinator = ConsumerCoordinator( self._client, self._subscription, assignors=self.config["partition_assignment_strategy"], **self.config ) self._closed = False self._iterator = None self._consumer_timeout = float("inf") # self.metrics = None if topics: self._subscription.subscribe(topics=topics) self._client.set_topics(topics)
def test_is_ready(mocker, conn): cli = KafkaClient() cli._maybe_connect(0) cli._maybe_connect(1) # metadata refresh blocks ready nodes assert cli.is_ready(0) assert cli.is_ready(1) cli._metadata_refresh_in_progress = True assert not cli.is_ready(0) assert not cli.is_ready(1) # requesting metadata update also blocks ready nodes cli._metadata_refresh_in_progress = False assert cli.is_ready(0) assert cli.is_ready(1) cli.cluster.request_update() cli.cluster.config['retry_backoff_ms'] = 0 assert not cli._metadata_refresh_in_progress assert not cli.is_ready(0) assert not cli.is_ready(1) cli.cluster._need_update = False # if connection can't send more, not ready assert cli.is_ready(0) conn.can_send_more.return_value = False assert not cli.is_ready(0) conn.can_send_more.return_value = True # disconnected nodes, not ready assert cli.is_ready(0) conn.state = ConnectionStates.DISCONNECTED assert not cli.is_ready(0)
def test_ready(mocker, conn): cli = KafkaClient() maybe_connect = mocker.patch.object(cli, '_maybe_connect') node_id = 1 cli.ready(node_id) maybe_connect.assert_called_with(node_id)
class OffsetsFetcherAsync(object): DEFAULT_CONFIG = { 'session_timeout_ms': 30000, 'heartbeat_interval_ms': 3000, 'retry_backoff_ms': 100, 'api_version': (0, 9), 'metric_group_prefix': '' } def __init__(self, **configs): self.config = copy.copy(self.DEFAULT_CONFIG) self.config.update(configs) self._client = KafkaClient(**self.config) self._coordinator_id = None self.group_id = configs['group_id'] self.topic = configs['topic'] def _ensure_coordinator_known(self): """Block until the coordinator for this group is known (and we have an active connection -- java client uses unsent queue). """ while self._coordinator_unknown(): # Prior to 0.8.2 there was no group coordinator # so we will just pick a node at random and treat # it as the "coordinator" if self.config['api_version'] < (0, 8, 2): self._coordinator_id = self._client.least_loaded_node() self._client.ready(self._coordinator_id) continue future = self._send_group_coordinator_request() self._client.poll(future=future) if future.failed(): if isinstance(future.exception, Errors.GroupCoordinatorNotAvailableError): continue elif future.retriable(): metadata_update = self._client.cluster.request_update() self._client.poll(future=metadata_update) else: raise future.exception # pylint: disable-msg=raising-bad-type def _coordinator_unknown(self): """Check if we know who the coordinator is and have an active connection Side-effect: reset _coordinator_id to None if connection failed Returns: bool: True if the coordinator is unknown """ if self._coordinator_id is None: return True if self._client.is_disconnected(self._coordinator_id): self._coordinator_dead() return True return False def _coordinator_dead(self, error=None): """Mark the current coordinator as dead.""" if self._coordinator_id is not None: log.warning("Marking the coordinator dead (node %s) for group %s: %s.", self._coordinator_id, self.group_id, error) self._coordinator_id = None def _send_group_coordinator_request(self): """Discover the current coordinator for the group. Returns: Future: resolves to the node id of the coordinator """ node_id = self._client.least_loaded_node() if node_id is None: return Future().failure(Errors.NoBrokersAvailable()) log.debug("Sending group coordinator request for group %s to broker %s", self.group_id, node_id) request = GroupCoordinatorRequest[0](self.group_id) future = Future() _f = self._client.send(node_id, request) _f.add_callback(self._handle_group_coordinator_response, future) _f.add_errback(self._failed_request, node_id, request, future) return future def _handle_group_coordinator_response(self, future, response): log.debug("Received group coordinator response %s", response) if not self._coordinator_unknown(): # We already found the coordinator, so ignore the request log.debug("Coordinator already known -- ignoring metadata response") future.success(self._coordinator_id) return error_type = Errors.for_code(response.error_code) if error_type is Errors.NoError: ok = self._client.cluster.add_group_coordinator(self.group_id, response) if not ok: # This could happen if coordinator metadata is different # than broker metadata future.failure(Errors.IllegalStateError()) return self._coordinator_id = response.coordinator_id log.info("Discovered coordinator %s for group %s", self._coordinator_id, self.group_id) self._client.ready(self._coordinator_id) future.success(self._coordinator_id) elif error_type is Errors.GroupCoordinatorNotAvailableError: log.debug("Group Coordinator Not Available; retry") future.failure(error_type()) elif error_type is Errors.GroupAuthorizationFailedError: error = error_type(self.group_id) log.error("Group Coordinator Request failed: %s", error) future.failure(error) else: error = error_type() log.error("Unrecognized failure in Group Coordinator Request: %s", error) future.failure(error) def _failed_request(self, node_id, request, future, error): log.error('Error sending %s to node %s [%s]', request.__class__.__name__, node_id, error) # Marking coordinator dead # unless the error is caused by internal client pipelining if not isinstance(error, (Errors.NodeNotReadyError, Errors.TooManyInFlightRequests)): self._coordinator_dead() future.failure(error) def offsets(self, partitions, timestamp): """Fetch a single offset before the given timestamp for the set of partitions. Blocks until offset is obtained, or a non-retriable exception is raised Arguments: partitions (iterable of TopicPartition) The partition that needs fetching offset. timestamp (int): timestamp for fetching offset. -1 for the latest available, -2 for the earliest available. Otherwise timestamp is treated as epoch seconds. Returns: dict: TopicPartition and message offsets """ retries = 3 while retries > 0: offsets = {} for future in self._send_offset_request(partitions, timestamp): self._client.poll(future=future) if future.succeeded(): for tp, offset in future.value: offsets[tp] = offset continue if not future.retriable(): raise future.exception # pylint: disable-msg=raising-bad-type if future.exception.invalid_metadata: refresh_future = self._client.cluster.request_update() self._client.poll(future=refresh_future) log.warning("Got exception %s and kept the loop", future.exception) if offsets: return offsets retries -= 1 log.warning("Retrying the offsets fetch loop (%d retries left)", retries) log.error("Unsuccessful offsets retrieval") return {} def _send_offset_request(self, partitions, timestamp): """Fetch a single offset before the given timestamp for the partition. Arguments: partitions iterable of TopicPartition: partitions that needs fetching offset timestamp (int): timestamp for fetching offset Returns: list of Future: resolves to the corresponding offset """ topic = partitions[0].topic nodes_per_partitions = {} for partition in partitions: node_id = self._client.cluster.leader_for_partition(partition) if node_id is None: log.debug("Partition %s is unknown for fetching offset," " wait for metadata refresh", partition) return [Future().failure(Errors.StaleMetadata(partition))] elif node_id == -1: log.debug("Leader for partition %s unavailable for fetching offset," " wait for metadata refresh", partition) return [Future().failure(Errors.LeaderNotAvailableError(partition))] nodes_per_partitions.setdefault(node_id, []).append(partition) # Client returns a future that only fails on network issues # so create a separate future and attach a callback to update it # based on response error codes futures = [] for node_id, partitions in six.iteritems(nodes_per_partitions): request = OffsetRequest[0]( -1, [(topic, [(partition.partition, timestamp, 1) for partition in partitions])] ) future_request = Future() _f = self._client.send(node_id, request) _f.add_callback(self._handle_offset_response, partitions, future_request) def errback(e): log.error("Offset request errback error %s", e) future_request.failure(e) _f.add_errback(errback) futures.append(future_request) return futures def _handle_offset_response(self, partitions, future, response): """Callback for the response of the list offset call above. Arguments: partition (TopicPartition): The partition that was fetched future (Future): the future to update based on response response (OffsetResponse): response from the server Raises: AssertionError: if response does not match partition """ topic, partition_info = response.topics[0] assert len(response.topics) == 1, ( 'OffsetResponse should only be for a single topic') partition_ids = set([part.partition for part in partitions]) result = [] for pi in partition_info: part, error_code, offsets = pi assert topic == partitions[0].topic and part in partition_ids, ( 'OffsetResponse partition does not match OffsetRequest partition') error_type = Errors.for_code(error_code) if error_type is Errors.NoError: assert len(offsets) == 1, 'Expected OffsetResponse with one offset' log.debug("Fetched offset %s for partition %d", offsets[0], part) result.append((TopicPartition(topic, part), offsets[0])) elif error_type in (Errors.NotLeaderForPartitionError, Errors.UnknownTopicOrPartitionError): log.debug("Attempt to fetch offsets for partition %s failed due" " to obsolete leadership information, retrying.", str(partitions)) future.failure(error_type(partitions)) else: log.warning("Attempt to fetch offsets for partition %s failed due to:" " %s", partitions, error_type) future.failure(error_type(partitions)) future.success(result) def fetch_committed_offsets(self, partitions): """Fetch the current committed offsets for specified partitions Arguments: partitions (list of TopicPartition): partitions to fetch Returns: dict: {TopicPartition: OffsetAndMetadata} """ if not partitions: return {} while True: self._ensure_coordinator_known() # contact coordinator to fetch committed offsets future = self._send_offset_fetch_request(partitions) self._client.poll(future=future) if future.succeeded(): return future.value if not future.retriable(): raise future.exception # pylint: disable-msg=raising-bad-type time.sleep(self.config['retry_backoff_ms'] / 1000.0) def _send_offset_fetch_request(self, partitions): """Fetch the committed offsets for a set of partitions. This is a non-blocking call. The returned future can be polled to get the actual offsets returned from the broker. Arguments: partitions (list of TopicPartition): the partitions to fetch Returns: Future: resolves to dict of offsets: {TopicPartition: int} """ assert self.config['api_version'] >= (0, 8, 1), 'Unsupported Broker API' assert all(map(lambda k: isinstance(k, TopicPartition), partitions)) if not partitions: return Future().success({}) elif self._coordinator_unknown(): return Future().failure(Errors.GroupCoordinatorNotAvailableError) node_id = self._coordinator_id # Verify node is ready if not self._client.ready(node_id): log.debug("Node %s not ready -- failing offset fetch request", node_id) return Future().failure(Errors.NodeNotReadyError) log.debug("Group %s fetching committed offsets for partitions: %s", self.group_id, partitions) # construct the request topic_partitions = collections.defaultdict(set) for tp in partitions: topic_partitions[tp.topic].add(tp.partition) if self.config['api_version'] >= (0, 8, 2): request = OffsetFetchRequest[1]( self.group_id, list(topic_partitions.items()) ) else: request = OffsetFetchRequest[0]( self.group_id, list(topic_partitions.items()) ) # send the request with a callback future = Future() _f = self._client.send(node_id, request) _f.add_callback(self._handle_offset_fetch_response, future) _f.add_errback(self._failed_request, node_id, request, future) return future def _handle_offset_fetch_response(self, future, response): offsets = {} for topic, partitions in response.topics: for partition, offset, metadata, error_code in partitions: tp = TopicPartition(topic, partition) error_type = Errors.for_code(error_code) if error_type is not Errors.NoError: error = error_type() log.debug("Group %s failed to fetch offset for partition" " %s: %s", self.group_id, tp, error) if error_type is Errors.GroupLoadInProgressError: # just retry future.failure(error) elif error_type is Errors.NotCoordinatorForGroupError: # re-discover the coordinator and retry self._coordinator_dead() future.failure(error) elif error_type in (Errors.UnknownMemberIdError, Errors.IllegalGenerationError): future.failure(error) elif error_type is Errors.UnknownTopicOrPartitionError: log.warning("OffsetFetchRequest -- unknown topic %s" " (have you committed any offsets yet?)", topic) continue else: log.error("Unknown error fetching offsets for %s: %s", tp, error) future.failure(error) return elif offset >= 0: # record the position with the offset # (-1 indicates no committed offset to fetch) offsets[tp] = OffsetAndMetadata(offset, metadata) else: log.debug("Group %s has no committed offset for partition" " %s", self.group_id, tp) future.success(offsets) def get(self): topic_partitions = self._client.cluster.partitions_for_topic(self.topic) if not topic_partitions: future = self._client.cluster.request_update() log.info("No partitions available, performing metadata update.") self._client.poll(future=future) return {} partitions = [TopicPartition(self.topic, partition_id) for partition_id in topic_partitions] offsets = self.offsets(partitions, -1) committed = self.fetch_committed_offsets(partitions) lags = {} for tp, offset in six.iteritems(offsets): commit_offset = committed[tp] if tp in committed else 0 numerical = commit_offset if isinstance(commit_offset, int) else commit_offset.offset lag = offset - numerical pid = tp.partition if isinstance(tp, TopicPartition) else tp log.debug("Lag for %s (%s): %s, %s, %s", self.topic, pid, offset, commit_offset, lag) lags[pid] = lag return lags
def test_conn_state_change(mocker, conn): cli = KafkaClient() sel = mocker.patch.object(cli, '_selector') node_id = 0 conn.state = ConnectionStates.CONNECTING cli._conn_state_change(node_id, conn) assert node_id in cli._connecting sel.register.assert_called_with(conn._sock, selectors.EVENT_WRITE) conn.state = ConnectionStates.CONNECTED cli._conn_state_change(node_id, conn) assert node_id not in cli._connecting sel.unregister.assert_called_with(conn._sock) sel.register.assert_called_with(conn._sock, selectors.EVENT_READ, conn) # Failure to connect should trigger metadata update assert cli.cluster._need_update is False conn.state = ConnectionStates.DISCONNECTING cli._conn_state_change(node_id, conn) assert node_id not in cli._connecting assert cli.cluster._need_update is True sel.unregister.assert_called_with(conn._sock) conn.state = ConnectionStates.CONNECTING cli._conn_state_change(node_id, conn) assert node_id in cli._connecting conn.state = ConnectionStates.DISCONNECTING cli._conn_state_change(node_id, conn) assert node_id not in cli._connecting
class KafkaConsumer(six.Iterator): """Consume records from a Kafka cluster. The consumer will transparently handle the failure of servers in the Kafka cluster, and adapt as topic-partitions are created or migrate between brokers. It also interacts with the assigned kafka Group Coordinator node to allow multiple consumers to load balance consumption of topics (requires kafka >= 0.9.0.0). Arguments: *topics (str): optional list of topics to subscribe to. If not set, call subscribe() or assign() before consuming records. Keyword Arguments: bootstrap_servers: 'host[:port]' string (or list of 'host[:port]' strings) that the consumer should contact to bootstrap initial cluster metadata. This does not have to be the full node list. It just needs to have at least one broker that will respond to a Metadata API Request. Default port is 9092. If no servers are specified, will default to localhost:9092. client_id (str): a name for this client. This string is passed in each request to servers and can be used to identify specific server-side log entries that correspond to this client. Also submitted to GroupCoordinator for logging with respect to consumer group administration. Default: 'kafka-python-{version}' group_id (str or None): name of the consumer group to join for dynamic partition assignment (if enabled), and to use for fetching and committing offsets. If None, auto-partition assignment (via group coordinator) and offset commits are disabled. Default: 'kafka-python-default-group' key_deserializer (callable): Any callable that takes a raw message key and returns a deserialized key. value_deserializer (callable): Any callable that takes a raw message value and returns a deserialized value. fetch_min_bytes (int): Minimum amount of data the server should return for a fetch request, otherwise wait up to fetch_max_wait_ms for more data to accumulate. Default: 1. fetch_max_wait_ms (int): The maximum amount of time in milliseconds the server will block before answering the fetch request if there isn't sufficient data to immediately satisfy the requirement given by fetch_min_bytes. Default: 500. max_partition_fetch_bytes (int): The maximum amount of data per-partition the server will return. The maximum total memory used for a request = #partitions * max_partition_fetch_bytes. This size must be at least as large as the maximum message size the server allows or else it is possible for the producer to send messages larger than the consumer can fetch. If that happens, the consumer can get stuck trying to fetch a large message on a certain partition. Default: 1048576. request_timeout_ms (int): Client request timeout in milliseconds. Default: 40000. retry_backoff_ms (int): Milliseconds to backoff when retrying on errors. Default: 100. reconnect_backoff_ms (int): The amount of time in milliseconds to wait before attempting to reconnect to a given host. Default: 50. max_in_flight_requests_per_connection (int): Requests are pipelined to kafka brokers up to this number of maximum requests per broker connection. Default: 5. auto_offset_reset (str): A policy for resetting offsets on OffsetOutOfRange errors: 'earliest' will move to the oldest available message, 'latest' will move to the most recent. Any other value will raise the exception. Default: 'latest'. enable_auto_commit (bool): If true the consumer's offset will be periodically committed in the background. Default: True. auto_commit_interval_ms (int): milliseconds between automatic offset commits, if enable_auto_commit is True. Default: 5000. default_offset_commit_callback (callable): called as callback(offsets, response) response will be either an Exception or a OffsetCommitResponse struct. This callback can be used to trigger custom actions when a commit request completes. check_crcs (bool): Automatically check the CRC32 of the records consumed. This ensures no on-the-wire or on-disk corruption to the messages occurred. This check adds some overhead, so it may be disabled in cases seeking extreme performance. Default: True metadata_max_age_ms (int): The period of time in milliseconds after which we force a refresh of metadata even if we haven't seen any partition leadership changes to proactively discover any new brokers or partitions. Default: 300000 partition_assignment_strategy (list): List of objects to use to distribute partition ownership amongst consumer instances when group management is used. Default: [RangePartitionAssignor, RoundRobinPartitionAssignor] heartbeat_interval_ms (int): The expected time in milliseconds between heartbeats to the consumer coordinator when using Kafka's group management feature. Heartbeats are used to ensure that the consumer's session stays active and to facilitate rebalancing when new consumers join or leave the group. The value must be set lower than session_timeout_ms, but typically should be set no higher than 1/3 of that value. It can be adjusted even lower to control the expected time for normal rebalances. Default: 3000 session_timeout_ms (int): The timeout used to detect failures when using Kafka's group managementment facilities. Default: 30000 max_poll_records (int): The maximum number of records returned in a single call to poll(). receive_buffer_bytes (int): The size of the TCP receive buffer (SO_RCVBUF) to use when reading data. Default: None (relies on system defaults). The java client defaults to 32768. send_buffer_bytes (int): The size of the TCP send buffer (SO_SNDBUF) to use when sending data. Default: None (relies on system defaults). The java client defaults to 131072. socket_options (list): List of tuple-arguments to socket.setsockopt to apply to broker connection sockets. Default: [(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)] consumer_timeout_ms (int): number of milliseconds to block during message iteration before raising StopIteration (i.e., ending the iterator). Default block forever [float('inf')]. skip_double_compressed_messages (bool): A bug in KafkaProducer <= 1.2.4 caused some messages to be corrupted via double-compression. By default, the fetcher will return these messages as a compressed blob of bytes with a single offset, i.e. how the message was actually published to the cluster. If you prefer to have the fetcher automatically detect corrupt messages and skip them, set this option to True. Default: False. security_protocol (str): Protocol used to communicate with brokers. Valid values are: PLAINTEXT, SSL. Default: PLAINTEXT. ssl_context (ssl.SSLContext): pre-configured SSLContext for wrapping socket connections. If provided, all other ssl_* configurations will be ignored. Default: None. ssl_check_hostname (bool): flag to configure whether ssl handshake should verify that the certificate matches the brokers hostname. default: true. ssl_cafile (str): optional filename of ca file to use in certificate verification. default: none. ssl_certfile (str): optional filename of file in pem format containing the client certificate, as well as any ca certificates needed to establish the certificate's authenticity. default: none. ssl_keyfile (str): optional filename containing the client private key. default: none. ssl_password (str): optional password to be used when loading the certificate chain. default: None. ssl_crlfile (str): optional filename containing the CRL to check for certificate expiration. By default, no CRL check is done. When providing a file, only the leaf certificate will be checked against this CRL. The CRL can only be checked with Python 3.4+ or 2.7.9+. default: none. api_version (tuple): specify which kafka API version to use. If set to None, the client will attempt to infer the broker version by probing various APIs. Default: None Examples: (0, 9) enables full group coordination features with automatic partition assignment and rebalancing, (0, 8, 2) enables kafka-storage offset commits with manual partition assignment only, (0, 8, 1) enables zookeeper-storage offset commits with manual partition assignment only, (0, 8, 0) enables basic functionality but requires manual partition assignment and offset management. For a full list of supported versions, see KafkaClient.API_VERSIONS api_version_auto_timeout_ms (int): number of milliseconds to throw a timeout exception from the constructor when checking the broker api version. Only applies if api_version set to 'auto' metric_reporters (list): A list of classes to use as metrics reporters. Implementing the AbstractMetricsReporter interface allows plugging in classes that will be notified of new metric creation. Default: [] metrics_num_samples (int): The number of samples maintained to compute metrics. Default: 2 metrics_sample_window_ms (int): The maximum age in milliseconds of samples used to compute metrics. Default: 30000 selector (selectors.BaseSelector): Provide a specific selector implementation to use for I/O multiplexing. Default: selectors.DefaultSelector exclude_internal_topics (bool): Whether records from internal topics (such as offsets) should be exposed to the consumer. If set to True the only way to receive records from an internal topic is subscribing to it. Requires 0.10+ Default: True sasl_mechanism (str): string picking sasl mechanism when security_protocol is SASL_PLAINTEXT or SASL_SSL. Currently only PLAIN is supported. Default: None sasl_plain_username (str): username for sasl PLAIN authentication. Default: None sasl_plain_password (str): password for sasl PLAIN authentication. Default: None Note: Configuration parameters are described in more detail at https://kafka.apache.org/0100/configuration.html#newconsumerconfigs """ DEFAULT_CONFIG = { 'bootstrap_servers': 'localhost', 'client_id': 'kafka-python-' + __version__, 'group_id': 'kafka-python-default-group', 'key_deserializer': None, 'value_deserializer': None, 'fetch_max_wait_ms': 500, 'fetch_min_bytes': 1, 'max_partition_fetch_bytes': 1 * 1024 * 1024, 'request_timeout_ms': 40 * 1000, 'retry_backoff_ms': 100, 'reconnect_backoff_ms': 50, 'max_in_flight_requests_per_connection': 5, 'auto_offset_reset': 'latest', 'enable_auto_commit': True, 'auto_commit_interval_ms': 5000, 'default_offset_commit_callback': lambda offsets, response: True, 'check_crcs': True, 'metadata_max_age_ms': 5 * 60 * 1000, 'partition_assignment_strategy': (RangePartitionAssignor, RoundRobinPartitionAssignor), 'heartbeat_interval_ms': 3000, 'session_timeout_ms': 30000, 'max_poll_records': sys.maxsize, 'receive_buffer_bytes': None, 'send_buffer_bytes': None, 'socket_options': [(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)], 'consumer_timeout_ms': float('inf'), 'skip_double_compressed_messages': False, 'security_protocol': 'PLAINTEXT', 'ssl_context': None, 'ssl_check_hostname': True, 'ssl_cafile': None, 'ssl_certfile': None, 'ssl_keyfile': None, 'ssl_crlfile': None, 'ssl_password': None, 'api_version': None, 'api_version_auto_timeout_ms': 2000, 'connections_max_idle_ms': 9 * 60 * 1000, # not implemented yet 'metric_reporters': [], 'metrics_num_samples': 2, 'metrics_sample_window_ms': 30000, 'metric_group_prefix': 'consumer', 'selector': selectors.DefaultSelector, 'exclude_internal_topics': True, 'sasl_mechanism': None, 'sasl_plain_username': None, 'sasl_plain_password': None, } def __init__(self, *topics, **configs): self.config = copy.copy(self.DEFAULT_CONFIG) for key in self.config: if key in configs: self.config[key] = configs.pop(key) # Only check for extra config keys in top-level class assert not configs, 'Unrecognized configs: %s' % configs deprecated = {'smallest': 'earliest', 'largest': 'latest'} if self.config['auto_offset_reset'] in deprecated: new_config = deprecated[self.config['auto_offset_reset']] log.warning('use auto_offset_reset=%s (%s is deprecated)', new_config, self.config['auto_offset_reset']) self.config['auto_offset_reset'] = new_config metrics_tags = {'client-id': self.config['client_id']} metric_config = MetricConfig(samples=self.config['metrics_num_samples'], time_window_ms=self.config['metrics_sample_window_ms'], tags=metrics_tags) reporters = [reporter() for reporter in self.config['metric_reporters']] self._metrics = Metrics(metric_config, reporters) # TODO _metrics likely needs to be passed to KafkaClient, etc. # api_version was previously a str. accept old format for now if isinstance(self.config['api_version'], str): str_version = self.config['api_version'] if str_version == 'auto': self.config['api_version'] = None else: self.config['api_version'] = tuple(map(int, str_version.split('.'))) log.warning('use api_version=%s [tuple] -- "%s" as str is deprecated', str(self.config['api_version']), str_version) self._client = KafkaClient(metrics=self._metrics, **self.config) # Get auto-discovered version from client if necessary if self.config['api_version'] is None: self.config['api_version'] = self._client.config['api_version'] self._subscription = SubscriptionState(self.config['auto_offset_reset']) self._fetcher = Fetcher( self._client, self._subscription, self._metrics, **self.config) self._coordinator = ConsumerCoordinator( self._client, self._subscription, self._metrics, assignors=self.config['partition_assignment_strategy'], **self.config) self._closed = False self._iterator = None self._consumer_timeout = float('inf') if topics: self._subscription.subscribe(topics=topics) self._client.set_topics(topics) def assign(self, partitions): """Manually assign a list of TopicPartitions to this consumer. Arguments: partitions (list of TopicPartition): assignment for this instance. Raises: IllegalStateError: if consumer has already called subscribe() Warning: It is not possible to use both manual partition assignment with assign() and group assignment with subscribe(). Note: This interface does not support incremental assignment and will replace the previous assignment (if there was one). Note: Manual topic assignment through this method does not use the consumer's group management functionality. As such, there will be no rebalance operation triggered when group membership or cluster and topic metadata change. """ self._subscription.assign_from_user(partitions) self._client.set_topics([tp.topic for tp in partitions]) def assignment(self): """Get the TopicPartitions currently assigned to this consumer. If partitions were directly assigned using assign(), then this will simply return the same partitions that were previously assigned. If topics were subscribed using subscribe(), then this will give the set of topic partitions currently assigned to the consumer (which may be none if the assignment hasn't happened yet, or if the partitions are in the process of being reassigned). Returns: set: {TopicPartition, ...} """ return self._subscription.assigned_partitions() def close(self): """Close the consumer, waiting indefinitely for any needed cleanup.""" if self._closed: return log.debug("Closing the KafkaConsumer.") self._closed = True self._coordinator.close() self._metrics.close() self._client.close() try: self.config['key_deserializer'].close() except AttributeError: pass try: self.config['value_deserializer'].close() except AttributeError: pass log.debug("The KafkaConsumer has closed.") def commit_async(self, offsets=None, callback=None): """Commit offsets to kafka asynchronously, optionally firing callback This commits offsets only to Kafka. The offsets committed using this API will be used on the first fetch after every rebalance and also on startup. As such, if you need to store offsets in anything other than Kafka, this API should not be used. To avoid re-processing the last message read if a consumer is restarted, the committed offset should be the next message your application should consume, i.e.: last_offset + 1. This is an asynchronous call and will not block. Any errors encountered are either passed to the callback (if provided) or discarded. Arguments: offsets (dict, optional): {TopicPartition: OffsetAndMetadata} dict to commit with the configured group_id. Defaults to current consumed offsets for all subscribed partitions. callback (callable, optional): called as callback(offsets, response) with response as either an Exception or a OffsetCommitResponse struct. This callback can be used to trigger custom actions when a commit request completes. Returns: kafka.future.Future """ assert self.config['api_version'] >= (0, 8, 1), 'Requires >= Kafka 0.8.1' assert self.config['group_id'] is not None, 'Requires group_id' if offsets is None: offsets = self._subscription.all_consumed_offsets() log.debug("Committing offsets: %s", offsets) future = self._coordinator.commit_offsets_async( offsets, callback=callback) return future def commit(self, offsets=None): """Commit offsets to kafka, blocking until success or error This commits offsets only to Kafka. The offsets committed using this API will be used on the first fetch after every rebalance and also on startup. As such, if you need to store offsets in anything other than Kafka, this API should not be used. To avoid re-processing the last message read if a consumer is restarted, the committed offset should be the next message your application should consume, i.e.: last_offset + 1. Blocks until either the commit succeeds or an unrecoverable error is encountered (in which case it is thrown to the caller). Currently only supports kafka-topic offset storage (not zookeeper) Arguments: offsets (dict, optional): {TopicPartition: OffsetAndMetadata} dict to commit with the configured group_id. Defaults to current consumed offsets for all subscribed partitions. """ assert self.config['api_version'] >= (0, 8, 1), 'Requires >= Kafka 0.8.1' assert self.config['group_id'] is not None, 'Requires group_id' if offsets is None: offsets = self._subscription.all_consumed_offsets() self._coordinator.commit_offsets_sync(offsets) def committed(self, partition): """Get the last committed offset for the given partition This offset will be used as the position for the consumer in the event of a failure. This call may block to do a remote call if the partition in question isn't assigned to this consumer or if the consumer hasn't yet initialized its cache of committed offsets. Arguments: partition (TopicPartition): the partition to check Returns: The last committed offset, or None if there was no prior commit. """ assert self.config['api_version'] >= (0, 8, 1), 'Requires >= Kafka 0.8.1' assert self.config['group_id'] is not None, 'Requires group_id' if not isinstance(partition, TopicPartition): raise TypeError('partition must be a TopicPartition namedtuple') if self._subscription.is_assigned(partition): committed = self._subscription.assignment[partition].committed if committed is None: self._coordinator.refresh_committed_offsets_if_needed() committed = self._subscription.assignment[partition].committed else: commit_map = self._coordinator.fetch_committed_offsets([partition]) if partition in commit_map: committed = commit_map[partition].offset else: committed = None return committed def topics(self): """Get all topics the user is authorized to view. Returns: set: topics """ cluster = self._client.cluster if self._client._metadata_refresh_in_progress and self._client._topics: future = cluster.request_update() self._client.poll(future=future) stash = cluster.need_all_topic_metadata cluster.need_all_topic_metadata = True future = cluster.request_update() self._client.poll(future=future) cluster.need_all_topic_metadata = stash return cluster.topics() def partitions_for_topic(self, topic): """Get metadata about the partitions for a given topic. Arguments: topic (str): topic to check Returns: set: partition ids """ return self._client.cluster.partitions_for_topic(topic) def poll(self, timeout_ms=0, max_records=None): """Fetch data from assigned topics / partitions. Records are fetched and returned in batches by topic-partition. On each poll, consumer will try to use the last consumed offset as the starting offset and fetch sequentially. The last consumed offset can be manually set through seek(partition, offset) or automatically set as the last committed offset for the subscribed list of partitions. Incompatible with iterator interface -- use one or the other, not both. Arguments: timeout_ms (int, optional): milliseconds spent waiting in poll if data is not available in the buffer. If 0, returns immediately with any records that are available currently in the buffer, else returns empty. Must not be negative. Default: 0 max_records (int, optional): The maximum number of records returned in a single call to :meth:`poll`. Default: Inherit value from max_poll_records. Returns: dict: topic to list of records since the last fetch for the subscribed list of topics and partitions """ assert timeout_ms >= 0, 'Timeout must not be negative' if max_records is None: max_records = self.config['max_poll_records'] # poll for new data until the timeout expires start = time.time() remaining = timeout_ms while True: records = self._poll_once(remaining, max_records) if records: return records elapsed_ms = (time.time() - start) * 1000 remaining = timeout_ms - elapsed_ms if remaining <= 0: return {} def _poll_once(self, timeout_ms, max_records): """ Do one round of polling. In addition to checking for new data, this does any needed heart-beating, auto-commits, and offset updates. Arguments: timeout_ms (int): The maximum time in milliseconds to block Returns: dict: map of topic to list of records (may be empty) """ if self._use_consumer_group(): self._coordinator.ensure_coordinator_known() self._coordinator.ensure_active_group() # 0.8.2 brokers support kafka-backed offset storage via group coordinator elif self.config['group_id'] is not None and self.config['api_version'] >= (0, 8, 2): self._coordinator.ensure_coordinator_known() # fetch positions if we have partitions we're subscribed to that we # don't know the offset for if not self._subscription.has_all_fetch_positions(): self._update_fetch_positions(self._subscription.missing_fetch_positions()) # if data is available already, e.g. from a previous network client # poll() call to commit, then just return it immediately records, partial = self._fetcher.fetched_records(max_records) if records: # before returning the fetched records, we can send off the # next round of fetches and avoid block waiting for their # responses to enable pipelining while the user is handling the # fetched records. if not partial: self._fetcher.send_fetches() return records # send any new fetches (won't resend pending fetches) self._fetcher.send_fetches() self._client.poll(timeout_ms=timeout_ms, sleep=True) records, _ = self._fetcher.fetched_records(max_records) return records def position(self, partition): """Get the offset of the next record that will be fetched Arguments: partition (TopicPartition): partition to check Returns: int: offset """ if not isinstance(partition, TopicPartition): raise TypeError('partition must be a TopicPartition namedtuple') assert self._subscription.is_assigned(partition), 'Partition is not assigned' offset = self._subscription.assignment[partition].position if offset is None: self._update_fetch_positions([partition]) offset = self._subscription.assignment[partition].position return offset def highwater(self, partition): """Last known highwater offset for a partition A highwater offset is the offset that will be assigned to the next message that is produced. It may be useful for calculating lag, by comparing with the reported position. Note that both position and highwater refer to the *next* offset -- i.e., highwater offset is one greater than the newest available message. Highwater offsets are returned in FetchResponse messages, so will not be available if no FetchRequests have been sent for this partition yet. Arguments: partition (TopicPartition): partition to check Returns: int or None: offset if available """ if not isinstance(partition, TopicPartition): raise TypeError('partition must be a TopicPartition namedtuple') assert self._subscription.is_assigned(partition), 'Partition is not assigned' return self._subscription.assignment[partition].highwater def pause(self, *partitions): """Suspend fetching from the requested partitions. Future calls to poll() will not return any records from these partitions until they have been resumed using resume(). Note that this method does not affect partition subscription. In particular, it does not cause a group rebalance when automatic assignment is used. Arguments: *partitions (TopicPartition): partitions to pause """ if not all([isinstance(p, TopicPartition) for p in partitions]): raise TypeError('partitions must be TopicPartition namedtuples') for partition in partitions: log.debug("Pausing partition %s", partition) self._subscription.pause(partition) def paused(self): """Get the partitions that were previously paused by a call to pause(). Returns: set: {partition (TopicPartition), ...} """ return self._subscription.paused_partitions() def resume(self, *partitions): """Resume fetching from the specified (paused) partitions. Arguments: *partitions (TopicPartition): partitions to resume """ if not all([isinstance(p, TopicPartition) for p in partitions]): raise TypeError('partitions must be TopicPartition namedtuples') for partition in partitions: log.debug("Resuming partition %s", partition) self._subscription.resume(partition) def seek(self, partition, offset): """Manually specify the fetch offset for a TopicPartition. Overrides the fetch offsets that the consumer will use on the next poll(). If this API is invoked for the same partition more than once, the latest offset will be used on the next poll(). Note that you may lose data if this API is arbitrarily used in the middle of consumption, to reset the fetch offsets. Arguments: partition (TopicPartition): partition for seek operation offset (int): message offset in partition Raises: AssertionError: if offset is not an int >= 0; or if partition is not currently assigned. """ if not isinstance(partition, TopicPartition): raise TypeError('partition must be a TopicPartition namedtuple') assert isinstance(offset, int) and offset >= 0, 'Offset must be >= 0' assert partition in self._subscription.assigned_partitions(), 'Unassigned partition' log.debug("Seeking to offset %s for partition %s", offset, partition) self._subscription.assignment[partition].seek(offset) def seek_to_beginning(self, *partitions): """Seek to the oldest available offset for partitions. Arguments: *partitions: optionally provide specific TopicPartitions, otherwise default to all assigned partitions Raises: AssertionError: if any partition is not currently assigned, or if no partitions are assigned """ if not all([isinstance(p, TopicPartition) for p in partitions]): raise TypeError('partitions must be TopicPartition namedtuples') if not partitions: partitions = self._subscription.assigned_partitions() assert partitions, 'No partitions are currently assigned' else: for p in partitions: assert p in self._subscription.assigned_partitions(), 'Unassigned partition' for tp in partitions: log.debug("Seeking to beginning of partition %s", tp) self._subscription.need_offset_reset(tp, OffsetResetStrategy.EARLIEST) def seek_to_end(self, *partitions): """Seek to the most recent available offset for partitions. Arguments: *partitions: optionally provide specific TopicPartitions, otherwise default to all assigned partitions Raises: AssertionError: if any partition is not currently assigned, or if no partitions are assigned """ if not all([isinstance(p, TopicPartition) for p in partitions]): raise TypeError('partitions must be TopicPartition namedtuples') if not partitions: partitions = self._subscription.assigned_partitions() assert partitions, 'No partitions are currently assigned' else: for p in partitions: assert p in self._subscription.assigned_partitions(), 'Unassigned partition' for tp in partitions: log.debug("Seeking to end of partition %s", tp) self._subscription.need_offset_reset(tp, OffsetResetStrategy.LATEST) def subscribe(self, topics=(), pattern=None, listener=None): """Subscribe to a list of topics, or a topic regex pattern Partitions will be dynamically assigned via a group coordinator. Topic subscriptions are not incremental: this list will replace the current assignment (if there is one). This method is incompatible with assign() Arguments: topics (list): List of topics for subscription. pattern (str): Pattern to match available topics. You must provide either topics or pattern, but not both. listener (ConsumerRebalanceListener): Optionally include listener callback, which will be called before and after each rebalance operation. As part of group management, the consumer will keep track of the list of consumers that belong to a particular group and will trigger a rebalance operation if one of the following events trigger: * Number of partitions change for any of the subscribed topics * Topic is created or deleted * An existing member of the consumer group dies * A new member is added to the consumer group When any of these events are triggered, the provided listener will be invoked first to indicate that the consumer's assignment has been revoked, and then again when the new assignment has been received. Note that this listener will immediately override any listener set in a previous call to subscribe. It is guaranteed, however, that the partitions revoked/assigned through this interface are from topics subscribed in this call. Raises: IllegalStateError: if called after previously calling assign() AssertionError: if neither topics or pattern is provided TypeError: if listener is not a ConsumerRebalanceListener """ # SubscriptionState handles error checking self._subscription.subscribe(topics=topics, pattern=pattern, listener=listener) # regex will need all topic metadata if pattern is not None: self._client.cluster.need_all_topic_metadata = True self._client.set_topics([]) log.debug("Subscribed to topic pattern: %s", pattern) else: self._client.cluster.need_all_topic_metadata = False self._client.set_topics(self._subscription.group_subscription()) log.debug("Subscribed to topic(s): %s", topics) def subscription(self): """Get the current topic subscription. Returns: set: {topic, ...} """ return self._subscription.subscription def unsubscribe(self): """Unsubscribe from all topics and clear all assigned partitions.""" self._subscription.unsubscribe() self._coordinator.close() self._client.cluster.need_all_topic_metadata = False self._client.set_topics([]) log.debug("Unsubscribed all topics or patterns and assigned partitions") def metrics(self, raw=False): """Warning: this is an unstable interface. It may change in future releases without warning""" if raw: return self._metrics.metrics metrics = {} for k, v in self._metrics.metrics.items(): if k.group not in metrics: metrics[k.group] = {} if k.name not in metrics[k.group]: metrics[k.group][k.name] = {} metrics[k.group][k.name] = v.value() return metrics def _use_consumer_group(self): """Return True iff this consumer can/should join a broker-coordinated group.""" if self.config['api_version'] < (0, 9): return False elif self.config['group_id'] is None: return False elif not self._subscription.partitions_auto_assigned(): return False return True def _update_fetch_positions(self, partitions): """ Set the fetch position to the committed position (if there is one) or reset it using the offset reset policy the user has configured. Arguments: partitions (List[TopicPartition]): The partitions that need updating fetch positions Raises: NoOffsetForPartitionError: If no offset is stored for a given partition and no offset reset policy is defined """ if (self.config['api_version'] >= (0, 8, 1) and self.config['group_id'] is not None): # refresh commits for all assigned partitions self._coordinator.refresh_committed_offsets_if_needed() # then do any offset lookups in case some positions are not known self._fetcher.update_fetch_positions(partitions) def _message_generator(self): assert self.assignment() or self.subscription() is not None, 'No topic subscription or manual partition assignment' while time.time() < self._consumer_timeout: if self._use_consumer_group(): self._coordinator.ensure_coordinator_known() self._coordinator.ensure_active_group() # 0.8.2 brokers support kafka-backed offset storage via group coordinator elif self.config['group_id'] is not None and self.config['api_version'] >= (0, 8, 2): self._coordinator.ensure_coordinator_known() # fetch offsets for any subscribed partitions that we arent tracking yet if not self._subscription.has_all_fetch_positions(): partitions = self._subscription.missing_fetch_positions() self._update_fetch_positions(partitions) poll_ms = 1000 * (self._consumer_timeout - time.time()) if not self._fetcher.in_flight_fetches(): poll_ms = 0 self._client.poll(timeout_ms=poll_ms, sleep=True) # We need to make sure we at least keep up with scheduled tasks, # like heartbeats, auto-commits, and metadata refreshes timeout_at = self._next_timeout() # Because the consumer client poll does not sleep unless blocking on # network IO, we need to explicitly sleep when we know we are idle # because we haven't been assigned any partitions to fetch / consume if self._use_consumer_group() and not self.assignment(): sleep_time = max(timeout_at - time.time(), 0) if sleep_time > 0 and not self._client.in_flight_request_count(): log.debug('No partitions assigned; sleeping for %s', sleep_time) time.sleep(sleep_time) continue # Short-circuit the fetch iterator if we are already timed out # to avoid any unintentional interaction with fetcher setup if time.time() > timeout_at: continue for msg in self._fetcher: yield msg if time.time() > timeout_at: log.debug("internal iterator timeout - breaking for poll") break # an else block on a for loop only executes if there was no break # so this should only be called on a StopIteration from the fetcher # and we assume that it is safe to init_fetches when fetcher is done # i.e., there are no more records stored internally else: self._fetcher.send_fetches() def _next_timeout(self): timeout = min(self._consumer_timeout, self._client._delayed_tasks.next_at() + time.time(), self._client.cluster.ttl() / 1000.0 + time.time()) # Although the delayed_tasks timeout above should cover processing # HeartbeatRequests, it is still possible that HeartbeatResponses # are left unprocessed during a long _fetcher iteration without # an intermediate poll(). And because tasks are responsible for # rescheduling themselves, an unprocessed response will prevent # the next heartbeat from being sent. This check should help # avoid that. if self._use_consumer_group(): heartbeat = time.time() + self._coordinator.heartbeat.ttl() timeout = min(timeout, heartbeat) return timeout def __iter__(self): # pylint: disable=non-iterator-returned return self def __next__(self): if not self._iterator: self._iterator = self._message_generator() self._set_consumer_timeout() try: return next(self._iterator) except StopIteration: self._iterator = None raise def _set_consumer_timeout(self): # consumer_timeout_ms can be used to stop iteration early if self.config['consumer_timeout_ms'] >= 0: self._consumer_timeout = time.time() + ( self.config['consumer_timeout_ms'] / 1000.0) # old KafkaConsumer methods are deprecated def configure(self, **configs): raise NotImplementedError( 'deprecated -- initialize a new consumer') def set_topic_partitions(self, *topics): raise NotImplementedError( 'deprecated -- use subscribe() or assign()') def fetch_messages(self): raise NotImplementedError( 'deprecated -- use poll() or iterator interface') def get_partition_offsets(self, topic, partition, request_time_ms, max_num_offsets): raise NotImplementedError( 'deprecated -- send an OffsetRequest with KafkaClient') def offsets(self, group=None): raise NotImplementedError('deprecated -- use committed(partition)') def task_done(self, message): raise NotImplementedError( 'deprecated -- commit offsets manually if needed')
def __init__(self, bootstrap_servers): self.client = KafkaClient(bootstrap_servers=bootstrap_servers) self.client.check_version()
class KafkaConsumerLag: def __init__(self, bootstrap_servers): self.client = KafkaClient(bootstrap_servers=bootstrap_servers) self.client.check_version() def _send(self, broker_id, request, response_type=None): f = self.client.send(broker_id, request) response = self.client.poll(future=f) if response_type: if response and len(response) > 0: for r in response: if isinstance(r, response_type): return r else: if response and len(response) > 0: return response[0] return None def check(self, group_topics=None, discovery=None): """ { "<group>": { "state": <str>, "topics": { "<topic>": { "consumer_lag": <int>, "partitions": { "<partition>": { "offset_first": <int>, "offset_consumed": <int>, "offset_last": <int>, "lag": <int> } } } } } } :param persist_groups: :return: consumer statistics """ cluster = self.client.cluster brokers = cluster.brokers() # Consumer group ID -> list(topics) if group_topics is None: group_topics = {} if discovery is None: discovery = True else: group_topics = copy.deepcopy(group_topics) # Set of consumer group IDs consumer_groups = set(group_topics.iterkeys()) # Set of all known topics topics = set(itertools.chain(*group_topics.itervalues())) # Consumer group ID -> coordinating broker consumer_coordinator = {} # Coordinating broker - > list(consumer group IDs) coordinator_consumers = {} results = {} for consumer_group in group_topics.iterkeys(): results[consumer_group] = {'state': None, 'topics': {}} # Ensure connections to all brokers for broker in brokers: while not self.client.is_ready(broker.nodeId): self.client.ready(broker.nodeId) # Collect all active consumer groups if discovery: for broker in brokers: response = self._send(broker.nodeId, _ListGroupsRequest(), _ListGroupsResponse) if response: for group in response.groups: consumer_groups.add(group[0]) # Identify which broker is coordinating each consumer group for group in consumer_groups: response = self._send(next(iter(brokers)).nodeId, _GroupCoordinatorRequest(group), _GroupCoordinatorResponse) if response: consumer_coordinator[group] = response.coordinator_id if response.coordinator_id not in coordinator_consumers: coordinator_consumers[response.coordinator_id] = [] coordinator_consumers[response.coordinator_id].append(group) # Populate consumer groups into dict for group in consumer_groups: if group not in group_topics: group_topics[group] = [] # Add groups to results dict for group, topic_list in group_topics.iteritems(): results[group] = {'state': None, 'topics': {}} # Identify group information and topics read by each consumer group for coordinator, consumers in coordinator_consumers.iteritems(): response = self._send(coordinator, _DescribeGroupsRequest(consumers), _DescribeGroupsResponse) for group in response.groups: if group[1] in results: results[group[1]]['state'] = group[2] # TODO Also include member data? if discovery: members = group[5] for member in members: try: assignment = MemberAssignment.decode(member[4]) if assignment: for partition in assignment.partition_assignment: topic = partition[0] # Add topic to topic set topics.add(topic) # Add topic to group group_topics[group[1]].append(topic) except: pass # Add topics to groups in results dict for group, topic_list in group_topics.iteritems(): for topic in topic_list: results[group]['topics'][topic] = {'consumer_lag': 0, 'partitions': {}} # For storing the latest offset for all partitions of all topics # topic -> partition -> offset start_offsets = {} end_offsets = {} # Identify all the topic partitions that each broker is leader for # and request next new offset for each partition for broker, partitions in cluster._broker_partitions.iteritems(): # topic -> List(partition, time, max_offsets) request_partitions = {} for tp in partitions: if tp.topic in topics: if tp.topic not in request_partitions: request_partitions[tp.topic] = [] # Time value '-2' is to get the offset for first available message request_partitions[tp.topic].append((tp.partition, -2, 1)) # List(topic, List(partition, time, max_offsets)) topic_partitions = [] for tp in request_partitions.iteritems(): topic_partitions.append(tp) # Request partition start offsets response = self._send(broker, _OffsetRequest(-1, topic_partitions), _OffsetResponse) if response: for offset in response.topics: topic = offset[0] if topic not in start_offsets: start_offsets[topic] = {} for p in offset[1]: start_offsets[topic][p[0]] = p[2][0] for tp in topic_partitions: for i, ptm in enumerate(tp[1]): # Time value '-1' is to get the offset for next new message tp[1][i] = (ptm[0], -1, 1) # Request partition end offsets response = self._send(broker, _OffsetRequest(-1, topic_partitions), _OffsetResponse) if response: for offset in response.topics: topic = offset[0] if topic not in end_offsets: end_offsets[topic] = {} for p in offset[1]: end_offsets[topic][p[0]] = p[2][0] # Populate with offset values for group, topics in group_topics.iteritems(): coordinator = consumer_coordinator[group] # topic -> list(partition) request_partitions = {} for topic in topics: results[group]['topics'][topic]['consumer_lag'] = 0 results[group]['topics'][topic]['partitions'] = {} if topic in start_offsets: for p in start_offsets[topic]: results[group]['topics'][topic]['partitions'][p] = { 'offset_first': start_offsets[topic][p], 'offset_last': end_offsets[topic][p], 'offset_consumed': 0, 'lag' : 0} if topic not in request_partitions: request_partitions[topic] = [] request_partitions[topic].append(p) # List(topic -> list(partition)) topic_partitions = [] for tp in request_partitions.iteritems(): topic_partitions.append(tp) response = self._send(coordinator, _OffsetFetchRequest(group, topic_partitions), _OffsetFetchResponse) if response: for offset in response.topics: topic = offset[0] offsets = offset[1] if topic not in results[group]['topics']: continue for p_offset in offsets: partition = p_offset[0] offset_consumed = p_offset[1] p_results = results[group]['topics'][topic]['partitions'][partition] if offset_consumed != -1: p_results['offset_consumed'] = offset_consumed p_results['lag'] = p_results['offset_last'] - offset_consumed else: p_results['offset_consumed'] = 0 p_results['lag'] = p_results['offset_last'] - p_results['offset_first'] results[group]['topics'][topic]['consumer_lag'] += p_results['lag'] return results def close(self): if self.client: self.client.close()
class KafkaConsumer(six.Iterator): """Consume records from a Kafka cluster. The consumer will transparently handle the failure of servers in the Kafka cluster, and adapt as topic-partitions are created or migrate between brokers. It also interacts with the assigned kafka Group Coordinator node to allow multiple consumers to load balance consumption of topics (requires kafka >= 0.9.0.0). Arguments: *topics (str): optional list of topics to subscribe to. If not set, call subscribe() or assign() before consuming records. Keyword Arguments: bootstrap_servers: 'host[:port]' string (or list of 'host[:port]' strings) that the consumer should contact to bootstrap initial cluster metadata. This does not have to be the full node list. It just needs to have at least one broker that will respond to a Metadata API Request. Default port is 9092. If no servers are specified, will default to localhost:9092. client_id (str): a name for this client. This string is passed in each request to servers and can be used to identify specific server-side log entries that correspond to this client. Also submitted to GroupCoordinator for logging with respect to consumer group administration. Default: 'kafka-python-{version}' group_id (str): name of the consumer group to join for dynamic partition assignment (if enabled), and to use for fetching and committing offsets. Default: 'kafka-python-default-group' key_deserializer (callable): Any callable that takes a raw message key and returns a deserialized key. value_deserializer (callable, optional): Any callable that takes a raw message value and returns a deserialized value. fetch_min_bytes (int): Minimum amount of data the server should return for a fetch request, otherwise wait up to fetch_max_wait_ms for more data to accumulate. Default: 1024. fetch_max_wait_ms (int): The maximum amount of time in milliseconds the server will block before answering the fetch request if there isn't sufficient data to immediately satisfy the requirement given by fetch_min_bytes. Default: 500. max_partition_fetch_bytes (int): The maximum amount of data per-partition the server will return. The maximum total memory used for a request = #partitions * max_partition_fetch_bytes. This size must be at least as large as the maximum message size the server allows or else it is possible for the producer to send messages larger than the consumer can fetch. If that happens, the consumer can get stuck trying to fetch a large message on a certain partition. Default: 1048576. request_timeout_ms (int): Client request timeout in milliseconds. Default: 40000. retry_backoff_ms (int): Milliseconds to backoff when retrying on errors. Default: 100. reconnect_backoff_ms (int): The amount of time in milliseconds to wait before attempting to reconnect to a given host. Default: 50. max_in_flight_requests_per_connection (int): Requests are pipelined to kafka brokers up to this number of maximum requests per broker connection. Default: 5. auto_offset_reset (str): A policy for resetting offsets on OffsetOutOfRange errors: 'earliest' will move to the oldest available message, 'latest' will move to the most recent. Any ofther value will raise the exception. Default: 'latest'. enable_auto_commit (bool): If true the consumer's offset will be periodically committed in the background. Default: True. auto_commit_interval_ms (int): milliseconds between automatic offset commits, if enable_auto_commit is True. Default: 5000. default_offset_commit_callback (callable): called as callback(offsets, response) response will be either an Exception or a OffsetCommitResponse struct. This callback can be used to trigger custom actions when a commit request completes. check_crcs (bool): Automatically check the CRC32 of the records consumed. This ensures no on-the-wire or on-disk corruption to the messages occurred. This check adds some overhead, so it may be disabled in cases seeking extreme performance. Default: True metadata_max_age_ms (int): The period of time in milliseconds after which we force a refresh of metadata even if we haven't seen any partition leadership changes to proactively discover any new brokers or partitions. Default: 300000 partition_assignment_strategy (list): List of objects to use to distribute partition ownership amongst consumer instances when group management is used. Default: [RoundRobinPartitionAssignor] heartbeat_interval_ms (int): The expected time in milliseconds between heartbeats to the consumer coordinator when using Kafka's group management feature. Heartbeats are used to ensure that the consumer's session stays active and to facilitate rebalancing when new consumers join or leave the group. The value must be set lower than session_timeout_ms, but typically should be set no higher than 1/3 of that value. It can be adjusted even lower to control the expected time for normal rebalances. Default: 3000 session_timeout_ms (int): The timeout used to detect failures when using Kafka's group managementment facilities. Default: 30000 send_buffer_bytes (int): The size of the TCP send buffer (SO_SNDBUF) to use when sending data. Default: 131072 receive_buffer_bytes (int): The size of the TCP receive buffer (SO_RCVBUF) to use when reading data. Default: 32768 consumer_timeout_ms (int): number of millisecond to throw a timeout exception to the consumer if no message is available for consumption. Default: -1 (dont throw exception) api_version (str): specify which kafka API version to use. 0.9 enables full group coordination features; 0.8.2 enables kafka-storage offset commits; 0.8.1 enables zookeeper-storage offset commits; 0.8.0 is what is left. If set to 'auto', will attempt to infer the broker version by probing various APIs. Default: auto Note: Configuration parameters are described in more detail at https://kafka.apache.org/090/configuration.html#newconsumerconfigs """ DEFAULT_CONFIG = { "bootstrap_servers": "localhost", "client_id": "kafka-python-" + __version__, "group_id": "kafka-python-default-group", "key_deserializer": None, "value_deserializer": None, "fetch_max_wait_ms": 500, "fetch_min_bytes": 1024, "max_partition_fetch_bytes": 1 * 1024 * 1024, "request_timeout_ms": 40 * 1000, "retry_backoff_ms": 100, "reconnect_backoff_ms": 50, "max_in_flight_requests_per_connection": 5, "auto_offset_reset": "latest", "enable_auto_commit": True, "auto_commit_interval_ms": 5000, "check_crcs": True, "metadata_max_age_ms": 5 * 60 * 1000, "partition_assignment_strategy": (RoundRobinPartitionAssignor,), "heartbeat_interval_ms": 3000, "session_timeout_ms": 30000, "send_buffer_bytes": 128 * 1024, "receive_buffer_bytes": 32 * 1024, "consumer_timeout_ms": -1, "api_version": "auto", "connections_max_idle_ms": 9 * 60 * 1000, # not implemented yet #'metric_reporters': None, #'metrics_num_samples': 2, #'metrics_sample_window_ms': 30000, } def __init__(self, *topics, **configs): self.config = copy.copy(self.DEFAULT_CONFIG) for key in self.config: if key in configs: self.config[key] = configs.pop(key) # Only check for extra config keys in top-level class assert not configs, "Unrecognized configs: %s" % configs deprecated = {"smallest": "earliest", "largest": "latest"} if self.config["auto_offset_reset"] in deprecated: new_config = deprecated[self.config["auto_offset_reset"]] log.warning("use auto_offset_reset=%s (%s is deprecated)", new_config, self.config["auto_offset_reset"]) self.config["auto_offset_reset"] = new_config self._client = KafkaClient(**self.config) # Check Broker Version if not set explicitly if self.config["api_version"] == "auto": self.config["api_version"] = self._client.check_version() assert self.config["api_version"] in ("0.9", "0.8.2", "0.8.1", "0.8.0") # Convert api_version config to tuple for easy comparisons self.config["api_version"] = tuple(map(int, self.config["api_version"].split("."))) self._subscription = SubscriptionState(self.config["auto_offset_reset"]) self._fetcher = Fetcher(self._client, self._subscription, **self.config) self._coordinator = ConsumerCoordinator( self._client, self._subscription, assignors=self.config["partition_assignment_strategy"], **self.config ) self._closed = False self._iterator = None self._consumer_timeout = float("inf") # self.metrics = None if topics: self._subscription.subscribe(topics=topics) self._client.set_topics(topics) def assign(self, partitions): """Manually assign a list of TopicPartitions to this consumer. Arguments: partitions (list of TopicPartition): assignment for this instance. Raises: IllegalStateError: if consumer has already called subscribe() Warning: It is not possible to use both manual partition assignment with assign() and group assignment with subscribe(). Note: This interface does not support incremental assignment and will replace the previous assignment (if there was one). Note: Manual topic assignment through this method does not use the consumer's group management functionality. As such, there will be no rebalance operation triggered when group membership or cluster and topic metadata change. """ self._subscription.assign_from_user(partitions) self._client.set_topics([tp.topic for tp in partitions]) def assignment(self): """Get the TopicPartitions currently assigned to this consumer. If partitions were directly assigned using assign(), then this will simply return the same partitions that were previously assigned. If topics were subscribed using subscribe(), then this will give the set of topic partitions currently assigned to the consumer (which may be none if the assignment hasn't happened yet, or if the partitions are in the process of being reassigned). Returns: set: {TopicPartition, ...} """ return self._subscription.assigned_partitions() def close(self): """Close the consumer, waiting indefinitely for any needed cleanup.""" if self._closed: return log.debug("Closing the KafkaConsumer.") self._closed = True self._coordinator.close() # self.metrics.close() self._client.close() try: self.config["key_deserializer"].close() except AttributeError: pass try: self.config["value_deserializer"].close() except AttributeError: pass log.debug("The KafkaConsumer has closed.") def commit_async(self, offsets=None, callback=None): """Commit offsets to kafka asynchronously, optionally firing callback This commits offsets only to Kafka. The offsets committed using this API will be used on the first fetch after every rebalance and also on startup. As such, if you need to store offsets in anything other than Kafka, this API should not be used. This is an asynchronous call and will not block. Any errors encountered are either passed to the callback (if provided) or discarded. Arguments: offsets (dict, optional): {TopicPartition: OffsetAndMetadata} dict to commit with the configured group_id. Defaults to current consumed offsets for all subscribed partitions. callback (callable, optional): called as callback(offsets, response) with response as either an Exception or a OffsetCommitResponse struct. This callback can be used to trigger custom actions when a commit request completes. Returns: kafka.future.Future """ assert self.config["api_version"] >= (0, 8, 1) if offsets is None: offsets = self._subscription.all_consumed_offsets() log.debug("Committing offsets: %s", offsets) future = self._coordinator.commit_offsets_async(offsets, callback=callback) return future def commit(self, offsets=None): """Commit offsets to kafka, blocking until success or error This commits offsets only to Kafka. The offsets committed using this API will be used on the first fetch after every rebalance and also on startup. As such, if you need to store offsets in anything other than Kafka, this API should not be used. Blocks until either the commit succeeds or an unrecoverable error is encountered (in which case it is thrown to the caller). Currently only supports kafka-topic offset storage (not zookeeper) Arguments: offsets (dict, optional): {TopicPartition: OffsetAndMetadata} dict to commit with the configured group_id. Defaults to current consumed offsets for all subscribed partitions. """ assert self.config["api_version"] >= (0, 8, 1) if offsets is None: offsets = self._subscription.all_consumed_offsets() self._coordinator.commit_offsets_sync(offsets) def committed(self, partition): """Get the last committed offset for the given partition This offset will be used as the position for the consumer in the event of a failure. This call may block to do a remote call if the partition in question isn't assigned to this consumer or if the consumer hasn't yet initialized its cache of committed offsets. Arguments: partition (TopicPartition): the partition to check Returns: The last committed offset, or None if there was no prior commit. """ assert self.config["api_version"] >= (0, 8, 1) if self._subscription.is_assigned(partition): committed = self._subscription.assignment[partition].committed if committed is None: self._coordinator.refresh_committed_offsets_if_needed() committed = self._subscription.assignment[partition].committed else: commit_map = self._coordinator.fetch_committed_offsets([partition]) if partition in commit_map: committed = commit_map[partition].offset else: committed = None return committed def topics(self): """Get all topic metadata topics the user is authorized to view. [Not Implemented Yet] Returns: {topic: [partition_info]} """ raise NotImplementedError("TODO") def partitions_for_topic(self, topic): """Get metadata about the partitions for a given topic. Arguments: topic (str): topic to check Returns: set: partition ids """ return self._client.cluster.partitions_for_topic(topic) def poll(self, timeout_ms=0): """Fetch data from assigned topics / partitions. Records are fetched and returned in batches by topic-partition. On each poll, consumer will try to use the last consumed offset as the starting offset and fetch sequentially. The last consumed offset can be manually set through seek(partition, offset) or automatically set as the last committed offset for the subscribed list of partitions. Incompatible with iterator interface -- use one or the other, not both. Arguments: timeout_ms (int, optional): milliseconds to spend waiting in poll if data is not available. If 0, returns immediately with any records that are available now. Must not be negative. Default: 0 Returns: dict: topic to list of records since the last fetch for the subscribed list of topics and partitions """ assert timeout_ms >= 0, "Timeout must not be negative" assert self._iterator is None, "Incompatible with iterator interface" # poll for new data until the timeout expires start = time.time() remaining = timeout_ms while True: records = self._poll_once(remaining) if records: # before returning the fetched records, we can send off the # next round of fetches and avoid block waiting for their # responses to enable pipelining while the user is handling the # fetched records. self._fetcher.init_fetches() return records elapsed_ms = (time.time() - start) * 1000 remaining = timeout_ms - elapsed_ms if remaining <= 0: return {} def _poll_once(self, timeout_ms): """ Do one round of polling. In addition to checking for new data, this does any needed heart-beating, auto-commits, and offset updates. Arguments: timeout_ms (int): The maximum time in milliseconds to block Returns: dict: map of topic to list of records (may be empty) """ if self.config["api_version"] >= (0, 8, 2): # TODO: Sub-requests should take into account the poll timeout (KAFKA-1894) self._coordinator.ensure_coordinator_known() if self.config["api_version"] >= (0, 9): # ensure we have partitions assigned if we expect to if self._subscription.partitions_auto_assigned(): self._coordinator.ensure_active_group() # fetch positions if we have partitions we're subscribed to that we # don't know the offset for if not self._subscription.has_all_fetch_positions(): self._update_fetch_positions(self._subscription.missing_fetch_positions()) # init any new fetches (won't resend pending fetches) records = self._fetcher.fetched_records() # if data is available already, e.g. from a previous network client # poll() call to commit, then just return it immediately if records: return records self._fetcher.init_fetches() self._client.poll(timeout_ms) return self._fetcher.fetched_records() def position(self, partition): """Get the offset of the next record that will be fetched Arguments: partition (TopicPartition): partition to check """ assert self._subscription.is_assigned(partition) offset = self._subscription.assignment[partition].position if offset is None: self._update_fetch_positions(partition) offset = self._subscription.assignment[partition].position return offset def pause(self, *partitions): """Suspend fetching from the requested partitions. Future calls to poll() will not return any records from these partitions until they have been resumed using resume(). Note that this method does not affect partition subscription. In particular, it does not cause a group rebalance when automatic assignment is used. Arguments: *partitions (TopicPartition): partitions to pause """ for partition in partitions: log.debug("Pausing partition %s", partition) self._subscription.pause(partition) def resume(self, *partitions): """Resume fetching from the specified (paused) partitions. Arguments: *partitions (TopicPartition): partitions to resume """ for partition in partitions: log.debug("Resuming partition %s", partition) self._subscription.resume(partition) def seek(self, partition, offset): """Manually specify the fetch offset for a TopicPartition. Overrides the fetch offsets that the consumer will use on the next poll(). If this API is invoked for the same partition more than once, the latest offset will be used on the next poll(). Note that you may lose data if this API is arbitrarily used in the middle of consumption, to reset the fetch offsets. Arguments: partition (TopicPartition): partition for seek operation offset (int): message offset in partition """ assert offset >= 0 log.debug("Seeking to offset %s for partition %s", offset, partition) self._subscription.assignment[partition].seek(offset) def seek_to_beginning(self, *partitions): """Seek to the oldest available offset for partitions. Arguments: *partitions: optionally provide specific TopicPartitions, otherwise default to all assigned partitions """ if not partitions: partitions = self._subscription.assigned_partitions() for tp in partitions: log.debug("Seeking to beginning of partition %s", tp) self._subscription.need_offset_reset(tp, OffsetResetStrategy.EARLIEST) def seek_to_end(self, *partitions): """Seek to the most recent available offset for partitions. Arguments: *partitions: optionally provide specific TopicPartitions, otherwise default to all assigned partitions """ if not partitions: partitions = self._subscription.assigned_partitions() for tp in partitions: log.debug("Seeking to end of partition %s", tp) self._subscription.need_offset_reset(tp, OffsetResetStrategy.LATEST) def subscribe(self, topics=(), pattern=None, listener=None): """Subscribe to a list of topics, or a topic regex pattern Partitions will be dynamically assigned via a group coordinator. Topic subscriptions are not incremental: this list will replace the current assignment (if there is one). This method is incompatible with assign() Arguments: topics (list): List of topics for subscription. pattern (str): Pattern to match available topics. You must provide either topics or pattern, but not both. listener (ConsumerRebalanceListener): Optionally include listener callback, which will be called before and after each rebalance operation. As part of group management, the consumer will keep track of the list of consumers that belong to a particular group and will trigger a rebalance operation if one of the following events trigger: * Number of partitions change for any of the subscribed topics * Topic is created or deleted * An existing member of the consumer group dies * A new member is added to the consumer group When any of these events are triggered, the provided listener will be invoked first to indicate that the consumer's assignment has been revoked, and then again when the new assignment has been received. Note that this listener will immediately override any listener set in a previous call to subscribe. It is guaranteed, however, that the partitions revoked/assigned through this interface are from topics subscribed in this call. """ if not topics: self.unsubscribe() else: self._subscription.subscribe(topics=topics, pattern=pattern, listener=listener) # regex will need all topic metadata if pattern is not None: self._client.cluster.need_metadata_for_all = True log.debug("Subscribed to topic pattern: %s", topics) else: self._client.set_topics(self._subscription.group_subscription()) log.debug("Subscribed to topic(s): %s", topics) def subscription(self): """Get the current topic subscription. Returns: set: {topic, ...} """ return self._subscription.subscription def unsubscribe(self): """Unsubscribe from all topics and clear all assigned partitions.""" self._subscription.unsubscribe() self._coordinator.close() self._client.cluster.need_metadata_for_all_topics = False log.debug("Unsubscribed all topics or patterns and assigned partitions") def _update_fetch_positions(self, partitions): """ Set the fetch position to the committed position (if there is one) or reset it using the offset reset policy the user has configured. Arguments: partitions (List[TopicPartition]): The partitions that need updating fetch positions Raises: NoOffsetForPartitionError: If no offset is stored for a given partition and no offset reset policy is defined """ if self.config["api_version"] >= (0, 8, 1): # refresh commits for all assigned partitions self._coordinator.refresh_committed_offsets_if_needed() # then do any offset lookups in case some positions are not known self._fetcher.update_fetch_positions(partitions) def _message_generator(self): assert self.assignment() or self.subscription() is not None while time.time() < self._consumer_timeout: if self.config["api_version"] >= (0, 8, 2): self._coordinator.ensure_coordinator_known() if self.config["api_version"] >= (0, 9): # ensure we have partitions assigned if we expect to if self._subscription.partitions_auto_assigned(): self._coordinator.ensure_active_group() # fetch positions if we have partitions we're subscribed to that we # don't know the offset for if not self._subscription.has_all_fetch_positions(): partitions = self._subscription.missing_fetch_positions() self._update_fetch_positions(partitions) # We need to make sure we at least keep up with scheduled tasks, # like heartbeats, auto-commits, and metadata refreshes timeout_at = min( self._consumer_timeout, self._client._delayed_tasks.next_at() + time.time(), self._client.cluster.ttl() / 1000.0 + time.time(), ) if self.config["api_version"] >= (0, 9): if not self.assignment(): sleep_time = time.time() - timeout_at log.debug("No partitions assigned; sleeping for %s", sleep_time) time.sleep(sleep_time) continue poll_ms = 1000 * (time.time() - self._consumer_timeout) # Dont bother blocking if there are no fetches if not self._fetcher.in_flight_fetches(): poll_ms = 0 self._client.poll(poll_ms) if time.time() > timeout_at: continue for msg in self._fetcher: yield msg if time.time() > timeout_at: log.debug("internal iterator timeout - breaking for poll") break # an else block on a for loop only executes if there was no break # so this should only be called on a StopIteration from the fetcher # and we assume that it is safe to init_fetches when fetcher is done # i.e., there are no more records stored internally else: self._fetcher.init_fetches() def __iter__(self): # pylint: disable=non-iterator-returned return self def __next__(self): if not self._iterator: self._iterator = self._message_generator() self._set_consumer_timeout() try: return next(self._iterator) except StopIteration: self._iterator = None raise def _set_consumer_timeout(self): # consumer_timeout_ms can be used to stop iteration early if self.config["consumer_timeout_ms"] >= 0: self._consumer_timeout = time.time() + (self.config["consumer_timeout_ms"] / 1000.0) # old KafkaConsumer methods are deprecated def configure(self, **configs): raise NotImplementedError("deprecated -- initialize a new consumer") def set_topic_partitions(self, *topics): raise NotImplementedError("deprecated -- use subscribe() or assign()") def fetch_messages(self): raise NotImplementedError("deprecated -- use poll() or iterator interface") def get_partition_offsets(self, topic, partition, request_time_ms, max_num_offsets): raise NotImplementedError("deprecated -- send an OffsetRequest with KafkaClient") def offsets(self, group=None): raise NotImplementedError("deprecated -- use committed(partition)") def task_done(self, message): raise NotImplementedError("deprecated -- commit offsets manually if needed")
def test_close(mocker, conn): cli = KafkaClient() mocker.patch.object(cli, '_selector') # Unknown node - silent cli.close(2) # Single node close cli._maybe_connect(0) assert not conn.close.call_count cli.close(0) assert conn.close.call_count == 1 # All node close cli._maybe_connect(1) cli.close() assert conn.close.call_count == 3