INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Encode a MetadataRequest Arguments: topics: list of strings
def encode_metadata_request(cls, topics=(), payloads=None): """ Encode a MetadataRequest Arguments: topics: list of strings """ if payloads is not None: topics = payloads return kafka.protocol.metadata.MetadataRequest[0](topics)
Encode a ConsumerMetadataRequest Arguments: client_id: string correlation_id: int payloads: string (consumer group)
def encode_consumer_metadata_request(cls, client_id, correlation_id, payloads): """ Encode a ConsumerMetadataRequest Arguments: client_id: string correlation_id: int payloads: string (consumer group) """ message = [] message.append(cls...
Decode bytes to a kafka.structs.ConsumerMetadataResponse Arguments: data: bytes to decode
def decode_consumer_metadata_response(cls, data): """ Decode bytes to a kafka.structs.ConsumerMetadataResponse Arguments: data: bytes to decode """ ((correlation_id, error, nodeId), cur) = relative_unpack('>ihi', data, 0) (host, cur) = read_short_string(data,...
Encode an OffsetCommitRequest struct Arguments: group: string, the consumer group you are committing offsets for payloads: list of OffsetCommitRequestPayload
def encode_offset_commit_request(cls, group, payloads): """ Encode an OffsetCommitRequest struct Arguments: group: string, the consumer group you are committing offsets for payloads: list of OffsetCommitRequestPayload """ return kafka.protocol.commit.Offs...
Encode an OffsetFetchRequest struct. The request is encoded using version 0 if from_kafka is false, indicating a request for Zookeeper offsets. It is encoded using version 1 otherwise, indicating a request for Kafka offsets. Arguments: group: string, the consumer group you a...
def encode_offset_fetch_request(cls, group, payloads, from_kafka=False): """ Encode an OffsetFetchRequest struct. The request is encoded using version 0 if from_kafka is false, indicating a request for Zookeeper offsets. It is encoded using version 1 otherwise, indicating a request ...
Decode OffsetFetchResponse to OffsetFetchResponsePayloads Arguments: response: OffsetFetchResponse
def decode_offset_fetch_response(cls, response): """ Decode OffsetFetchResponse to OffsetFetchResponsePayloads Arguments: response: OffsetFetchResponse """ return [ kafka.structs.OffsetFetchResponsePayload( topic, partition, offset, metada...
Return a file descriptor from a file object. This wraps _fileobj_to_fd() to do an exhaustive search in case the object is invalid but we still have it in our map. This is used by unregister() so we can unregister an object that was previously registered even if it is closed. It is als...
def _fileobj_lookup(self, fileobj): """Return a file descriptor from a file object. This wraps _fileobj_to_fd() to do an exhaustive search in case the object is invalid but we still have it in our map. This is used by unregister() so we can unregister an object that was previou...
Validate that this sensor doesn't end up referencing itself.
def _check_forest(self, sensors): """Validate that this sensor doesn't end up referencing itself.""" if self in sensors: raise ValueError('Circular dependency in sensors: %s is its own' 'parent.' % (self.name,)) sensors.add(self) for parent in sel...
Record a value at a known time. Arguments: value (double): The value we are recording time_ms (int): A POSIX timestamp in milliseconds. Default: The time when record() is evaluated (now) Raises: QuotaViolationException: if recording this value moves a...
def record(self, value=1.0, time_ms=None): """ Record a value at a known time. Arguments: value (double): The value we are recording time_ms (int): A POSIX timestamp in milliseconds. Default: The time when record() is evaluated (now) Raises: ...
Check if we have violated our quota for any metric that has a configured quota
def _check_quotas(self, time_ms): """ Check if we have violated our quota for any metric that has a configured quota """ for metric in self._metrics: if metric.config and metric.config.quota: value = metric.value(time_ms) if not metric....
Register a compound statistic with this sensor which yields multiple measurable quantities (like a histogram) Arguments: stat (AbstractCompoundStat): The stat to register config (MetricConfig): The configuration for this stat. If None then the stat will use the d...
def add_compound(self, compound_stat, config=None): """ Register a compound statistic with this sensor which yields multiple measurable quantities (like a histogram) Arguments: stat (AbstractCompoundStat): The stat to register config (MetricConfig): The configura...
Register a metric with this sensor Arguments: metric_name (MetricName): The name of the metric stat (AbstractMeasurableStat): The statistic to keep config (MetricConfig): A special configuration for this metric. If None use the sensor default configuration.
def add(self, metric_name, stat, config=None): """ Register a metric with this sensor Arguments: metric_name (MetricName): The name of the metric stat (AbstractMeasurableStat): The statistic to keep config (MetricConfig): A special configuration for this metr...
Returns list of preferred (protocols, metadata)
def group_protocols(self): """Returns list of preferred (protocols, metadata)""" if self._subscription.subscription is None: raise Errors.IllegalStateError('Consumer has not subscribed to topics') # dpkp note: I really dislike this. # why? because we are using this strange me...
Poll for coordinator events. Only applicable if group_id is set, and broker version supports GroupCoordinators. This ensures that the coordinator is known, and if using automatic partition assignment, ensures that the consumer has joined the group. This also handles periodic offset commi...
def poll(self): """ Poll for coordinator events. Only applicable if group_id is set, and broker version supports GroupCoordinators. This ensures that the coordinator is known, and if using automatic partition assignment, ensures that the consumer has joined the group. This also h...
Return seconds (float) remaining until :meth:`.poll` should be called again
def time_to_next_poll(self): """Return seconds (float) remaining until :meth:`.poll` should be called again""" if not self.config['enable_auto_commit']: return self.time_to_next_heartbeat() if time.time() > self.next_auto_commit_deadline: return 0 return min(sel...
Check whether the group should be rejoined Returns: bool: True if consumer should rejoin group, False otherwise
def need_rejoin(self): """Check whether the group should be rejoined Returns: bool: True if consumer should rejoin group, False otherwise """ if not self._subscription.partitions_auto_assigned(): return False if self._auto_assign_all_partitions(): ...
Fetch committed offsets for assigned partitions.
def refresh_committed_offsets_if_needed(self): """Fetch committed offsets for assigned partitions.""" if self._subscription.needs_fetch_committed_offsets: offsets = self.fetch_committed_offsets(self._subscription.assigned_partitions()) for partition, offset in six.iteritems(offse...
Close the coordinator, leave the current group, and reset local generation / member_id. Keyword Arguments: autocommit (bool): If auto-commit is configured for this consumer, this optional flag causes the consumer to attempt to commit any pending consumed offs...
def close(self, autocommit=True): """Close the coordinator, leave the current group, and reset local generation / member_id. Keyword Arguments: autocommit (bool): If auto-commit is configured for this consumer, this optional flag causes the consumer to attempt to com...
Fetch the current committed offsets for specified partitions Arguments: partitions (list of TopicPartition): partitions to fetch Returns: dict: {TopicPartition: OffsetAndMetadata}
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: ...
Commit specific offsets asynchronously. Arguments: offsets (dict {TopicPartition: OffsetAndMetadata}): what to commit callback (callable, optional): called as callback(offsets, response) response will be either an Exception or a OffsetCommitResponse struc...
def commit_offsets_async(self, offsets, callback=None): """Commit specific offsets asynchronously. Arguments: offsets (dict {TopicPartition: OffsetAndMetadata}): what to commit callback (callable, optional): called as callback(offsets, response) response will be ...
Commit specific offsets synchronously. This method will retry until the commit completes successfully or an unrecoverable error is encountered. Arguments: offsets (dict {TopicPartition: OffsetAndMetadata}): what to commit Raises error on failure
def commit_offsets_sync(self, offsets): """Commit specific offsets synchronously. This method will retry until the commit completes successfully or an unrecoverable error is encountered. Arguments: offsets (dict {TopicPartition: OffsetAndMetadata}): what to commit ...
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: reso...
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 p...
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_from_user() ...
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 o...
Ensures that the topic name is valid according to the kafka source.
def _ensure_valid_topic_name(self, topic): """ Ensures that the topic name is valid according to the kafka source. """ # See Kafka Source: # https://github.com/apache/kafka/blob/39eb31feaeebfb184d98cc5d94da9148c2319d81/clients/src/main/java/org/apache/kafka/common/internals/Topic.java i...
Change the topic subscription. Arguments: topics (list of str): topics for subscription Raises: IllegalStateErrror: if assign_from_user has been used already TypeError: if a topic is None or a non-str ValueError: if a topic is an empty string or ...
def change_subscription(self, topics): """Change the topic subscription. Arguments: topics (list of str): topics for subscription Raises: IllegalStateErrror: if assign_from_user has been used already TypeError: if a topic is None or a non-str Val...
Add topics to the current group subscription. This is used by the group leader to ensure that it receives metadata updates for all topics that any member of the group is subscribed to. Arguments: topics (list of str): topics to add to the group subscription
def group_subscribe(self, topics): """Add topics to the current group subscription. This is used by the group leader to ensure that it receives metadata updates for all topics that any member of the group is subscribed to. Arguments: topics (list of str): topics to add to t...
Reset the group's subscription to only contain topics subscribed by this consumer.
def reset_group_subscription(self): """Reset the group's subscription to only contain topics subscribed by this consumer.""" if self._user_assignment: raise IllegalStateError(self._SUBSCRIPTION_EXCEPTION_MESSAGE) assert self.subscription is not None, 'Subscription required' s...
Manually assign a list of TopicPartitions to this consumer. This interface does not allow for incremental assignment and will replace the previous assignment (if there was one). Manual topic assignment through this method does not use the consumer's group management functionality. As s...
def assign_from_user(self, partitions): """Manually assign a list of TopicPartitions to this consumer. This interface does not allow for incremental assignment and will replace the previous assignment (if there was one). Manual topic assignment through this method does not use the cons...
Update the assignment to the specified partitions This method is called by the coordinator to dynamically assign partitions based on the consumer's topic subscription. This is different from assign_from_user() which directly sets the assignment from a user-supplied TopicPartition list. ...
def assign_from_subscribed(self, assignments): """Update the assignment to the specified partitions This method is called by the coordinator to dynamically assign partitions based on the consumer's topic subscription. This is different from assign_from_user() which directly sets the ass...
Clear all topic subscriptions and partition assignments
def unsubscribe(self): """Clear all topic subscriptions and partition assignments""" self.subscription = None self._user_assignment.clear() self.assignment.clear() self.subscribed_pattern = None
Return current set of paused TopicPartitions.
def paused_partitions(self): """Return current set of paused TopicPartitions.""" return set(partition for partition in self.assignment if self.is_paused(partition))
Return set of TopicPartitions that should be Fetched.
def fetchable_partitions(self): """Return set of TopicPartitions that should be Fetched.""" fetchable = set() for partition, state in six.iteritems(self.assignment): if state.is_fetchable(): fetchable.add(partition) return fetchable
Returns consumed offsets as {TopicPartition: OffsetAndMetadata}
def all_consumed_offsets(self): """Returns consumed offsets as {TopicPartition: OffsetAndMetadata}""" all_consumed = {} for partition, state in six.iteritems(self.assignment): if state.has_valid_position: all_consumed[partition] = OffsetAndMetadata(state.position, '')...
Mark partition for offset reset using specified or default strategy. Arguments: partition (TopicPartition): partition to mark offset_reset_strategy (OffsetResetStrategy, optional)
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. Arguments: timeout (float, optional): timeout in seconds to wait for completion.
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. Arguments: topic (str): topic where the message will be published value (optional): message value. Must be type bytes, or be serializable to bytes via configured value_serializer. If value is None, key is required and message...
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...
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. Arguments: topic (str): topic we want metadata for max_wait (float): maximum time in secs for waiting on the metadata Returns: set: partition ids for the topic Raise...
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. 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 without warning.
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) Arguments: partition (int): the partition for which offsets should be updated Returns: Updated offset on success, None on failure
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 Arguments: offset: how much to modify the offset whence: where to modify it from, default is None * None is an absolute offset * 0 is relative to the earliest available offset (head) ...
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 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 block is a positive integer the API will block until that many mes...
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. Arguments: num (int): Value to encode Returns: bytearray: Encoded presentation of integer with length from 1 to 10 ...
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. Arguments: buffer (bytes-like): any object acceptable by ``memoryview`` pos (int): optional position to read from R...
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. This resolves to the lesser of either the latest api version this library supports, or the max version supported by the broker. :param operation: A list of protocol operation versions from ...
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. Sends a FindCoordinatorRequest message to the cluster. Will block until the FindCoordinatorResponse is received. Any errors are immediately raised. :param group_id: The consumer group ID. This is typically the 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. 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 protocol response for the message. :exception: The exception ...
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. Will block until the message result is received. :param request: The message to send. :return: The Kafka protocol response for the message.
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. :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: If True, don't actually create new topics. Not supported by all versions...
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. :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 class.
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. :param config_resources: An list of ConfigResource objects. Any keys in ConfigResource.configs dict will be used to filter the result. Setting the configs dict to None will get all values. An empty dict will get...
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. 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 the comment in the source code for details. ...
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. :param topic_partitions: A map of topic name strings to NewPartition objects. :param timeout_ms: Milliseconds to wait for new partitions to be created before the broker returns. :param validate_only: If True, don't actually create ...
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. 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: The node_id of the groups' coordinator broker. If set to None, it will quer...
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. 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 offsets in Kafka are returned. The protocol type will be a...
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. Note: This does not verify that the group_id or partitions actually exist in the cluster. As soon as any error is encountered, it is immediately raised. :param group_id: The consumer group id name for which to fetch offsets. :param group_c...
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 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 after it is ready (full or linger.ms has reached). * the batch is in retry...
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. The append result will contain the future metadata, and flag for whether the appended batch is full or a new batch is created Arguments: tp (TopicPartition): The topic/partition to which this record is being...
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. Arguments: request_timeout_ms (int): milliseconds to timeout cluster (ClusterMetadata): current metadata for kafka cluster ...
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. A destination node is ready to send if: * T...
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. Arguments: cluster (ClusterMetadata): The current cluster metadata ...
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...
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...
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....
Append a message to the buffer. Returns: RecordMetadata or None if unable to append
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) :return: either socket.AF_INET or socket.AF_INET6 or socket.AF_UNSPEC if the address family could not be determined
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: * 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] <- IPv6 address literal * [host_or_ip]:po...
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...
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. Arguments: error (Exception, optional): pending in-flight-requests will be failed with this exception. Default: kafka.errors.KafkaConnectionError.
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. Return list of (response, future) tuples
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. Note: This is a blocking call. Returns: version tuple, i.e. (0, 10), (0, 9), (0, 8, 2), ...
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) ...