INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Mark partition for offset reset using specified or default strategy.
def need_offset_reset(self, partition, offset_reset_strategy=None): """Mark partition for offset reset using specified or default strategy. Arguments: partition (TopicPartition): partition to mark offset_reset_strategy (OffsetResetStrategy, optional) """ if offse...
Build a cleanup clojure that doesn t increase our ref count
def _cleanup_factory(self): """Build a cleanup clojure that doesn't increase our ref count""" _self = weakref.proxy(self) def wrapper(): try: _self.close(timeout=0) except (ReferenceError, AttributeError): pass return wrapper
Close this producer.
def close(self, timeout=None): """Close this producer. Arguments: timeout (float, optional): timeout in seconds to wait for completion. """ # drop our atexit handler now to avoid leaks self._unregister_cleanup() if not hasattr(self, '_closed') or self._clos...
Returns set of all known partitions for the topic.
def partitions_for(self, topic): """Returns set of all known partitions for the topic.""" max_wait = self.config['max_block_ms'] / 1000.0 return self._wait_on_metadata(topic, max_wait)
Publish a message to a topic.
def send(self, topic, value=None, key=None, headers=None, partition=None, timestamp_ms=None): """Publish a message to a topic. Arguments: topic (str): topic where the message will be published value (optional): message value. Must be type bytes, or be serializabl...
Invoking this method makes all buffered records immediately available to send ( even if linger_ms is greater than 0 ) and blocks on the completion of the requests associated with these records. The post - condition of: meth: ~kafka. KafkaProducer. flush is that any previously sent record will have completed ( e. g. Fut...
def flush(self, timeout=None): """ Invoking this method makes all buffered records immediately available to send (even if linger_ms is greater than 0) and blocks on the completion of the requests associated with these records. The post-condition of :meth:`~kafka.KafkaProducer.flu...
Validate that the record size isn t too large.
def _ensure_valid_record_size(self, size): """Validate that the record size isn't too large.""" if size > self.config['max_request_size']: raise Errors.MessageSizeTooLargeError( "The message is %d bytes when serialized which is larger than" " the maximum reque...
Wait for cluster metadata including partitions for the given topic to be available.
def _wait_on_metadata(self, topic, max_wait): """ Wait for cluster metadata including partitions for the given topic to be available. Arguments: topic (str): topic we want metadata for max_wait (float): maximum time in secs for waiting on the metadata Re...
Get metrics on producer performance.
def metrics(self, raw=False): """Get metrics on producer performance. This is ported from the Java Producer, for details see: https://kafka.apache.org/documentation/#producer_monitoring Warning: This is an unstable interface. It may change in future releases wit...
Update offsets using auto_offset_reset policy ( smallest|largest )
def reset_partition_offset(self, partition): """Update offsets using auto_offset_reset policy (smallest|largest) Arguments: partition (int): the partition for which offsets should be updated Returns: Updated offset on success, None on failure """ LATEST = -1 ...
Alter the current offset in the consumer similar to fseek
def seek(self, offset, whence=None, partition=None): """ Alter the current offset in the consumer, similar to fseek Arguments: offset: how much to modify the offset whence: where to modify it from, default is None * None is an absolute offset ...
Fetch the specified number of messages
def get_messages(self, count=1, block=True, timeout=0.1): """ Fetch the specified number of messages Keyword Arguments: count: Indicates the maximum number of messages to be fetched block: If True, the API will block till all messages are fetched. If bloc...
If no messages can be fetched returns None. If get_partition_info is None it defaults to self. partition_info If get_partition_info is True returns ( partition message ) If get_partition_info is False returns message
def _get_message(self, block=True, timeout=0.1, get_partition_info=None, update_offset=True): """ If no messages can be fetched, returns None. If get_partition_info is None, it defaults to self.partition_info If get_partition_info is True, returns (partition, message...
Encode an integer to a varint presentation. See https:// developers. google. com/ protocol - buffers/ docs/ encoding?csw = 1#varints on how those can be produced.
def encode_varint_1(num): """ Encode an integer to a varint presentation. See https://developers.google.com/protocol-buffers/docs/encoding?csw=1#varints on how those can be produced. Arguments: num (int): Value to encode Returns: bytearray: Encoded presentation of i...
Number of bytes needed to encode an integer in variable - length format.
def size_of_varint_1(value): """ Number of bytes needed to encode an integer in variable-length format. """ value = (value << 1) ^ (value >> 63) res = 0 while True: res += 1 value = value >> 7 if value == 0: break return res
Number of bytes needed to encode an integer in variable - length format.
def size_of_varint_2(value): """ Number of bytes needed to encode an integer in variable-length format. """ value = (value << 1) ^ (value >> 63) if value <= 0x7f: return 1 if value <= 0x3fff: return 2 if value <= 0x1fffff: return 3 if value <= 0xfffffff: retur...
Decode an integer from a varint presentation. See https:// developers. google. com/ protocol - buffers/ docs/ encoding?csw = 1#varints on how those can be produced.
def decode_varint_1(buffer, pos=0): """ Decode an integer from a varint presentation. See https://developers.google.com/protocol-buffers/docs/encoding?csw=1#varints on how those can be produced. Arguments: buffer (bytes-like): any object acceptable by ``memoryview`` pos (int...
Timeout any windows that have expired in the absence of any events
def purge_obsolete_samples(self, config, now): """ Timeout any windows that have expired in the absence of any events """ expire_age = config.samples * config.time_window_ms for sample in self._samples: if now - sample.last_window_ms >= expire_age: sam...
Close the KafkaAdminClient connection to the Kafka broker.
def close(self): """Close the KafkaAdminClient connection to the Kafka broker.""" if not hasattr(self, '_closed') or self._closed: log.info("KafkaAdminClient already closed.") return self._metrics.close() self._client.close() self._closed = True l...
Find the latest version of the protocol operation supported by both this library and the broker.
def _matching_api_version(self, operation): """Find the latest version of the protocol operation supported by both this library and the broker. This resolves to the lesser of either the latest api version this library supports, or the max version supported by the broker. :param...
Determine the Kafka cluster controller.
def _refresh_controller_id(self): """Determine the Kafka cluster controller.""" version = self._matching_api_version(MetadataRequest) if 1 <= version <= 6: request = MetadataRequest[version]() response = self._send_request_to_node(self._client.least_loaded_node(), request...
Find the broker node_id of the coordinator of the given group.
def _find_group_coordinator_id(self, group_id): """Find the broker node_id of the coordinator of the given group. Sends a FindCoordinatorRequest message to the cluster. Will block until the FindCoordinatorResponse is received. Any errors are immediately raised. :param group_id:...
Send a Kafka protocol message to a specific broker.
def _send_request_to_node(self, node_id, request): """Send a Kafka protocol message to a specific broker. Will block until the message result is received. :param node_id: The broker id to which to send the message. :param request: The message to send. :return: The Kafka protoco...
Send a Kafka protocol message to the cluster controller.
def _send_request_to_controller(self, request): """Send a Kafka protocol message to the cluster controller. Will block until the message result is received. :param request: The message to send. :return: The Kafka protocol response for the message. """ tries = 2 # in ca...
Create new topics in the cluster.
def create_topics(self, new_topics, timeout_ms=None, validate_only=False): """Create new topics in the cluster. :param new_topics: A list of NewTopic objects. :param timeout_ms: Milliseconds to wait for new topics to be created before the broker returns. :param validate_only...
Delete topics from the cluster.
def delete_topics(self, topics, timeout_ms=None): """Delete topics from the cluster. :param topics: A list of topic name strings. :param timeout_ms: Milliseconds to wait for topics to be deleted before the broker returns. :return: Appropriate version of DeleteTopicsResponse ...
Fetch configuration parameters for one or more Kafka resources.
def describe_configs(self, config_resources, include_synonyms=False): """Fetch configuration parameters for one or more Kafka resources. :param config_resources: An list of ConfigResource objects. Any keys in ConfigResource.configs dict will be used to filter the result. Setting...
Alter configuration parameters of one or more Kafka resources.
def alter_configs(self, config_resources): """Alter configuration parameters of one or more Kafka resources. Warning: This is currently broken for BROKER resources because those must be sent to that specific broker, versus this always picks the least-loaded node. See...
Create additional partitions for an existing topic.
def create_partitions(self, topic_partitions, timeout_ms=None, validate_only=False): """Create additional partitions for an existing topic. :param topic_partitions: A map of topic name strings to NewPartition objects. :param timeout_ms: Milliseconds to wait for new partitions to be ...
Describe a set of consumer groups.
def describe_consumer_groups(self, group_ids, group_coordinator_id=None): """Describe a set of consumer groups. Any errors are immediately raised. :param group_ids: A list of consumer group IDs. These are typically the group names as strings. :param group_coordinator_id: Th...
List all consumer groups known to the cluster.
def list_consumer_groups(self, broker_ids=None): """List all consumer groups known to the cluster. This returns a list of Consumer Group tuples. The tuples are composed of the consumer group name and the consumer group protocol type. Only consumer groups that store their offset...
Fetch Consumer Group Offsets.
def list_consumer_group_offsets(self, group_id, group_coordinator_id=None, partitions=None): """Fetch Consumer Group Offsets. Note: This does not verify that the group_id or partitions actually exist in the cluster. As soon as any error is en...
Update CRC - 32C checksum with data. Args: crc: 32 - bit checksum to update as long. data: byte array string or iterable over bytes. Returns: 32 - bit updated CRC - 32C as long.
def crc_update(crc, data): """Update CRC-32C checksum with data. Args: crc: 32-bit checksum to update as long. data: byte array, string or iterable over bytes. Returns: 32-bit updated CRC-32C as long. """ if type(data) != array.array or data.itemsize != 1: buf = array...
Expire batches if metadata is not available
def maybe_expire(self, request_timeout_ms, retry_backoff_ms, linger_ms, is_full): """Expire batches if metadata is not available A batch whose metadata is not available should be expired if one of the following is true: * the batch is not in retry AND request timeout has elapsed afte...
Add a record to the accumulator return the append result.
def append(self, tp, timestamp_ms, key, value, headers, max_time_to_block_ms, estimated_size=0): """Add a record to the accumulator, return the append result. The append result will contain the future metadata, and flag for whether the appended batch is full or a new batch is cre...
Abort the batches that have been sitting in RecordAccumulator for more than the configured request_timeout due to metadata being unavailable.
def abort_expired_batches(self, request_timeout_ms, cluster): """Abort the batches that have been sitting in RecordAccumulator for more than the configured request_timeout due to metadata being unavailable. Arguments: request_timeout_ms (int): milliseconds to timeout ...
Re - enqueue the given record batch in the accumulator to retry.
def reenqueue(self, batch): """Re-enqueue the given record batch in the accumulator to retry.""" now = time.time() batch.attempts += 1 batch.last_attempt = now batch.last_append = now batch.set_retry() assert batch.topic_partition in self._tp_locks, 'TopicPartitio...
Get a list of nodes whose partitions are ready to be sent and the earliest time at which any non - sendable partition will be ready ; Also return the flag for whether there are any unknown leaders for the accumulated partition batches.
def ready(self, cluster): """ Get a list of nodes whose partitions are ready to be sent, and the earliest time at which any non-sendable partition will be ready; Also return the flag for whether there are any unknown leaders for the accumulated partition batches. A desti...
Return whether there is any unsent record in the accumulator.
def has_unsent(self): """Return whether there is any unsent record in the accumulator.""" for tp in list(self._batches.keys()): with self._tp_locks[tp]: dq = self._batches[tp] if len(dq): return True return False
Drain all the data for the given nodes and collate them into a list of batches that will fit within the specified size on a per - node basis. This method attempts to avoid choosing the same topic - node repeatedly.
def drain(self, cluster, nodes, max_size): """ Drain all the data for the given nodes and collate them into a list of batches that will fit within the specified size on a per-node basis. This method attempts to avoid choosing the same topic-node repeatedly. Arguments: ...
Deallocate the record batch.
def deallocate(self, batch): """Deallocate the record batch.""" self._incomplete.remove(batch) self._free.deallocate(batch.buffer())
Mark all partitions as ready to send and block until the send is complete
def await_flush_completion(self, timeout=None): """ Mark all partitions as ready to send and block until the send is complete """ try: for batch in self._incomplete.all(): log.debug('Waiting on produce to %s', batch.produce_future.top...
This function is only called when sender is closed forcefully. It will fail all the incomplete batches and return.
def abort_incomplete_batches(self): """ This function is only called when sender is closed forcefully. It will fail all the incomplete batches and return. """ # We need to keep aborting the incomplete batch until no thread is trying to append to # 1. Avoid losing batches....
Go through incomplete batches and abort them.
def _abort_batches(self): """Go through incomplete batches and abort them.""" error = Errors.IllegalStateError("Producer is closed forcefully.") for batch in self._incomplete.all(): tp = batch.topic_partition # Close the batch before aborting with self._tp_loc...
Append a message to the buffer.
def append(self, timestamp, key, value, headers=[]): """ Append a message to the buffer. Returns: RecordMetadata or None if unable to append """ if self._closed: return None offset = self._next_offset metadata = self._builder.append(offset, timestamp, key, v...
Write message to messageset buffer with MsgVersion 2
def append(self, offset, timestamp, key, value, headers, # Cache for LOAD_FAST opcodes encode_varint=encode_varint, size_of_varint=size_of_varint, get_type=type, type_int=int, time_time=time.time, byte_like=(bytes, bytearray, memoryview), bytear...
Get the upper bound estimate on the size of record
def estimate_size_in_bytes(cls, key, value, headers): """ Get the upper bound estimate on the size of record """ return ( cls.HEADER_STRUCT.size + cls.MAX_RECORD_OVERHEAD + cls.size_of(key, value, headers) )
Returns seconds ( float ) remaining before next heartbeat should be sent
def time_to_next_heartbeat(self): """Returns seconds (float) remaining before next heartbeat should be sent""" time_since_last_heartbeat = time.time() - max(self.last_send, self.last_reset) if self.heartbeat_failed: delay_to_next_heartbeat = self.config['retry_backoff_ms'] / 1000 ...
Attempt to determine the family of an address ( or hostname )
def _address_family(address): """ Attempt to determine the family of an address (or hostname) :return: either socket.AF_INET or socket.AF_INET6 or socket.AF_UNSPEC if the address family could not be determined """ if address.startswith('[') and address.endswith(']'): ...
Parse the IP and port from a string in the format of:
def get_ip_port_afi(host_and_port_str): """ Parse the IP and port from a string in the format of: * host_or_ip <- Can be either IPv4 address literal or hostname/fqdn * host_or_ipv4:port <- Can be either IPv4 address literal or hostname/fqdn * [host_or_ip] ...
Collects a comma - separated set of hosts ( host: port ) and optionally randomize the returned list.
def collect_hosts(hosts, randomize=True): """ Collects a comma-separated set of hosts (host:port) and optionally randomize the returned list. """ if isinstance(hosts, six.string_types): hosts = hosts.strip().split(',') result = [] afi = socket.AF_INET for host_port in hosts: ...
Returns a list of getaddrinfo structs optionally filtered to an afi ( ipv4/ ipv6 )
def dns_lookup(host, port, afi=socket.AF_UNSPEC): """Returns a list of getaddrinfo structs, optionally filtered to an afi (ipv4 / ipv6)""" # XXX: all DNS functions in Python are blocking. If we really # want to be non-blocking here, we need to use a 3rd-party # library like python-adns, or move resoluti...
Attempt to connect and return ConnectionState
def connect(self): """Attempt to connect and return ConnectionState""" if self.state is ConnectionStates.DISCONNECTED and not self.blacked_out(): self.last_attempt = time.time() next_lookup = self._next_afi_sockaddr() if not next_lookup: self.close(Err...
Return a string representation of the OPTIONAL key - value pairs that can be sent with an OAUTHBEARER initial request.
def _token_extensions(self): """ Return a string representation of the OPTIONAL key-value pairs that can be sent with an OAUTHBEARER initial request. """ token_provider = self.config['sasl_oauth_token_provider'] # Only run if the #extensions() method is implemented by th...
Return true if we are disconnected from the given node and can t re - establish a connection yet
def blacked_out(self): """ Return true if we are disconnected from the given node and can't re-establish a connection yet """ if self.state is ConnectionStates.DISCONNECTED: if time.time() < self.last_attempt + self._reconnect_backoff: return True ...
Return the number of milliseconds to wait based on the connection state before attempting to send data. When disconnected this respects the reconnect backoff time. When connecting returns 0 to allow non - blocking connect to finish. When connected returns a very large number to handle slow/ stalled connections.
def connection_delay(self): """ Return the number of milliseconds to wait, based on the connection state, before attempting to send data. When disconnected, this respects the reconnect backoff time. When connecting, returns 0 to allow non-blocking connect to finish. When connecte...
Returns True if still connecting ( this may encompass several different states such as SSL handshake authorization etc ).
def connecting(self): """Returns True if still connecting (this may encompass several different states, such as SSL handshake, authorization, etc).""" return self.state in (ConnectionStates.CONNECTING, ConnectionStates.HANDSHAKE, Connec...
Close socket and fail all in - flight - requests.
def close(self, error=None): """Close socket and fail all in-flight-requests. Arguments: error (Exception, optional): pending in-flight-requests will be failed with this exception. Default: kafka.errors.KafkaConnectionError. """ if self.state ...
Queue request for async network send return Future ()
def send(self, request, blocking=True): """Queue request for async network send, return Future()""" future = Future() if self.connecting(): return future.failure(Errors.NodeNotReadyError(str(self))) elif not self.connected(): return future.failure(Errors.KafkaConn...
Can block on network if request is larger than send_buffer_bytes
def send_pending_requests(self): """Can block on network if request is larger than send_buffer_bytes""" try: with self._lock: if not self._can_send_recv(): return Errors.NodeNotReadyError(str(self)) # In the future we might manage an intern...
Non - blocking network receive.
def recv(self): """Non-blocking network receive. Return list of (response, future) tuples """ responses = self._recv() if not responses and self.requests_timed_out(): log.warning('%s timed out after %s ms. Closing connection.', self, self.conf...
Take all available bytes from socket return list of any responses from parser
def _recv(self): """Take all available bytes from socket, return list of any responses from parser""" recvd = [] self._lock.acquire() if not self._can_send_recv(): log.warning('%s cannot recv: socket not connected', self) self._lock.release() return ()...
Attempt to guess the broker version.
def check_version(self, timeout=2, strict=False, topics=[]): """Attempt to guess the broker version. Note: This is a blocking call. Returns: version tuple, i.e. (0, 10), (0, 9), (0, 8, 2), ... """ timeout_at = time.time() + timeout log.info('Probing node %s broker versi...
The main run loop for the sender thread.
def run(self): """The main run loop for the sender thread.""" log.debug("Starting Kafka producer I/O thread.") # main loop, runs until close is called while self._running: try: self.run_once() except Exception: log.exception("Uncau...
Run a single iteration of sending.
def run_once(self): """Run a single iteration of sending.""" while self._topics_to_add: self._client.add_topic(self._topics_to_add.pop()) # get the list of partitions with data ready to send result = self._accumulator.ready(self._metadata) ready_nodes, next_ready_che...
Start closing the sender ( won t complete until all data is sent ).
def initiate_close(self): """Start closing the sender (won't complete until all data is sent).""" self._running = False self._accumulator.close() self.wakeup()
Handle a produce response.
def _handle_produce_response(self, node_id, send_time, batches, response): """Handle a produce response.""" # if we have a response, parse it log.debug('Parsing produce response: %r', response) if response: batches_by_partition = dict([(batch.topic_partition, batch) ...
Complete or retry the given batch of records.
def _complete_batch(self, batch, error, base_offset, timestamp_ms=None): """Complete or retry the given batch of records. Arguments: batch (RecordBatch): The record batch error (Exception): The error (or None if none) base_offset (int): The base offset assigned to th...
We can retry a send if the error is transient and the number of attempts taken is fewer than the maximum allowed
def _can_retry(self, batch, error): """ We can retry a send if the error is transient and the number of attempts taken is fewer than the maximum allowed """ return (batch.attempts < self.config['retries'] and getattr(error, 'retriable', False))
Transfer the record batches into a list of produce requests on a per - node basis.
def _create_produce_requests(self, collated): """ Transfer the record batches into a list of produce requests on a per-node basis. Arguments: collated: {node_id: [RecordBatch]} Returns: dict: {node_id: ProduceRequest} (version depends on api_version) ...
Create a produce request from the given record batches.
def _produce_request(self, node_id, acks, timeout, batches): """Create a produce request from the given record batches. Returns: ProduceRequest (version depends on api_version) """ produce_records_by_partition = collections.defaultdict(dict) for batch in batches: ...
Encodes the given data with snappy compression.
def snappy_encode(payload, xerial_compatible=True, xerial_blocksize=32*1024): """Encodes the given data with snappy compression. If xerial_compatible is set then the stream is encoded in a fashion compatible with the xerial snappy library. The block size (xerial_blocksize) controls how frequent the bl...
Detects if the data given might have been encoded with the blocking mode of the xerial snappy library.
def _detect_xerial_stream(payload): """Detects if the data given might have been encoded with the blocking mode of the xerial snappy library. This mode writes a magic header of the format: +--------+--------------+------------+---------+--------+ | Marker | Magic String | Nu...
Decode payload using interoperable LZ4 framing. Requires Kafka > = 0. 10
def lz4f_decode(payload): """Decode payload using interoperable LZ4 framing. Requires Kafka >= 0.10""" # pylint: disable-msg=no-member ctx = lz4f.createDecompContext() data = lz4f.decompressFrame(payload, ctx) lz4f.freeDecompContext(ctx) # lz4f python module does not expose how much of the payl...
Encode payload for 0. 8/ 0. 9 brokers -- requires an incorrect header checksum.
def lz4_encode_old_kafka(payload): """Encode payload for 0.8/0.9 brokers -- requires an incorrect header checksum.""" assert xxhash is not None data = lz4_encode(payload) header_size = 7 flg = data[4] if not isinstance(flg, int): flg = ord(flg) content_size_bit = ((flg >> 3) & 1) ...
Get all BrokerMetadata
def brokers(self): """Get all BrokerMetadata Returns: set: {BrokerMetadata, ...} """ return set(self._brokers.values()) or set(self._bootstrap_brokers.values())
Get BrokerMetadata
def broker_metadata(self, broker_id): """Get BrokerMetadata Arguments: broker_id (int): node_id for a broker to check Returns: BrokerMetadata or None if not found """ return self._brokers.get(broker_id) or self._bootstrap_brokers.get(broker_id)
Return set of all partitions for topic ( whether available or not )
def partitions_for_topic(self, topic): """Return set of all partitions for topic (whether available or not) Arguments: topic (str): topic to check for partitions Returns: set: {partition (int), ...} """ if topic not in self._partitions: retur...
Return set of partitions with known leaders
def available_partitions_for_topic(self, topic): """Return set of partitions with known leaders Arguments: topic (str): topic to check for partitions Returns: set: {partition (int), ...} None if topic not found. """ if topic not in self._part...
Return node_id of leader - 1 unavailable None if unknown.
def leader_for_partition(self, partition): """Return node_id of leader, -1 unavailable, None if unknown.""" if partition.topic not in self._partitions: return None elif partition.partition not in self._partitions[partition.topic]: return None return self._partitio...
Milliseconds until metadata should be refreshed
def ttl(self): """Milliseconds until metadata should be refreshed""" now = time.time() * 1000 if self._need_update: ttl = 0 else: metadata_age = now - self._last_successful_refresh_ms ttl = self.config['metadata_max_age_ms'] - metadata_age ret...
Flags metadata for update return Future ()
def request_update(self): """Flags metadata for update, return Future() Actual update must be handled separately. This method will only change the reported ttl() Returns: kafka.future.Future (value will be the cluster object after update) """ with self._lock...
Get set of known topics.
def topics(self, exclude_internal_topics=True): """Get set of known topics. Arguments: 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 fro...
Update cluster state given a failed MetadataRequest.
def failed_update(self, exception): """Update cluster state given a failed MetadataRequest.""" f = None with self._lock: if self._future: f = self._future self._future = None if f: f.failure(exception) self._last_refresh_ms ...
Update cluster state given a MetadataResponse.
def update_metadata(self, metadata): """Update cluster state given a MetadataResponse. Arguments: metadata (MetadataResponse): broker response to a metadata request Returns: None """ # In the common case where we ask for a single topic and get back an # erro...
Update with metadata for a group coordinator
def add_group_coordinator(self, group, response): """Update with metadata for a group coordinator Arguments: group (str): name of group from GroupCoordinatorRequest response (GroupCoordinatorResponse): broker response Returns: bool: True if metadata is updat...
Returns a copy of cluster metadata with partitions added
def with_partitions(self, partitions_to_add): """Returns a copy of cluster metadata with partitions added""" new_metadata = ClusterMetadata(**self.config) new_metadata._brokers = copy.deepcopy(self._brokers) new_metadata._partitions = copy.deepcopy(self._partitions) new_metadata....
Manually assign a list of TopicPartitions to this consumer.
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 :meth:`~kafka.KafkaConsumer.s...
Close the consumer waiting indefinitely for any needed cleanup.
def close(self, autocommit=True): """Close the consumer, waiting indefinitely for any needed cleanup. Keyword Arguments: autocommit (bool): If auto-commit is configured for this consumer, this optional flag causes the consumer to attempt to commit any pending...
Commit offsets to kafka asynchronously optionally firing callback.
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...
Commit offsets to kafka blocking until success or error.
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 anyth...
Get the last committed offset for the given partition.
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...
Get all topics the user is authorized to view.
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....
Fetch data from assigned topics/ partitions.
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 consum...
Do one round of polling. In addition to checking for new data this does any needed heart - beating auto - commits and offset updates.
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: ...
Get the offset of the next record that will be fetched
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('partiti...
Last known highwater offset for a partition.
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 ...
Suspend fetching from the requested partitions.
def pause(self, *partitions): """Suspend fetching from the requested partitions. Future calls to :meth:`~kafka.KafkaConsumer.poll` will not return any records from these partitions until they have been resumed using :meth:`~kafka.KafkaConsumer.resume`. Note: This method does no...
Manually specify the fetch offset for a TopicPartition.
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 :meth:`~kafka.KafkaConsumer.poll`. If this API is invoked for the same partition more than once, the latest offset will be use...
Seek to the oldest available offset for partitions.
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 i...