code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if num is None: # Show None when data is missing return "None" for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']: if abs(num) < 1024.0: return "%3.1f%s%s" % (num, unit, suffix) num /= 1024.0 return "%.1f%s%s" % (num, 'Yi', suffix)
def to_h(num, suffix='B')
Converts a byte value in human readable form.
1.810375
1.692813
1.069448
if sys.stdout.isatty(): return json.dumps(data, indent=4, separators=(',', ': ')) else: return json.dumps(data)
def format_to_json(data)
Converts `data` into json If stdout is a tty it performs a pretty print.
2.407888
2.048075
1.175684
for broker_id, metadata in six.iteritems(brokers): self.brokers[broker_id] = self._create_broker(broker_id, metadata)
def _build_brokers(self, brokers)
Build broker objects using broker-ids.
3.524285
2.850286
1.236467
broker = Broker(broker_id, metadata) if not metadata: broker.mark_inactive() rg_id = self.extract_group(broker) group = self.rgs.setdefault(rg_id, ReplicationGroup(rg_id)) group.add_broker(broker) broker.replication_group = group return broker
def _create_broker(self, broker_id, metadata=None)
Create a broker object and assign to a replication group. A broker object with no metadata is considered inactive. An inactive broker may or may not belong to a group.
4.359276
3.289475
1.325219
self.partitions = {} for partition_name, replica_ids in six.iteritems(assignment): # Get topic topic_id = partition_name[0] partition_id = partition_name[1] topic = self.topics.setdefault( topic_id, Topic(topic_id, ...
def _build_partitions(self, assignment)
Builds all partition objects and update corresponding broker and topic objects.
2.884298
2.68024
1.076134
return { broker for broker in six.itervalues(self.brokers) if not broker.inactive and not broker.decommissioned }
def active_brokers(self)
Set of brokers that are not inactive or decommissioned.
6.097746
3.918907
1.555981
try: source = self.brokers[source_id] dest = self.brokers[dest_id] # Move all partitions from source to destination broker for partition in source.partitions.copy(): # Partitions set changes # We cannot move partition directly since that ...
def replace_broker(self, source_id, dest_id)
Move all partitions in source broker to destination broker. :param source_id: source broker-id :param dest_id: destination broker-id :raises: InvalidBrokerIdError, when either of given broker-ids is invalid.
4.208715
4.074975
1.03282
try: for partition_name, replica_ids in six.iteritems(assignment): try: new_replicas = [self.brokers[b_id] for b_id in replica_ids] except KeyError: self.log.error( "Invalid replicas %s for topic...
def update_cluster_topology(self, assignment)
Modify the cluster-topology with given assignment. Change the replica set of partitions as in given assignment. :param assignment: dict representing actions to be used to update the current cluster-topology :raises: InvalidBrokerIdError when broker-id is invalid :raises: Invali...
2.850398
2.648517
1.076224
assignment = {} for elem in plan['partitions']: assignment[ (elem['topic'], elem['partition']) ] = elem['replicas'] return assignment
def plan_to_assignment(plan)
Convert the plan to the format used by cluster-topology.
6.093931
5.250883
1.160554
return { 'version': 1, 'partitions': [{'topic': t_p[0], 'partition': t_p[1], 'replicas': replica } for t_p, replica in six.iteritems(assignment)] }
def assignment_to_plan(assignment)
Convert an assignment to the format used by Kafka to describe a reassignment plan.
5.196504
4.619957
1.124795
if not _validate_plan(new_plan): _log.error('Invalid proposed-plan.') return False # Validate given plan in reference to base-plan if base_plan: if not _validate_plan(base_plan): _log.error('Invalid assignment from cluster.') return False if not ...
def validate_plan( new_plan, base_plan=None, is_partition_subset=True, allow_rf_change=False, )
Verify that the new plan is valid for execution. Given kafka-reassignment plan should affirm with following rules: - Plan should have at least one partition for re-assignment - Partition-name list should be subset of base-plan partition-list - Replication-factor for each partition of same topic is same...
4.341083
4.698713
0.923888
# Verify that partitions in plan are subset of base plan. new_partitions = set([ (p_data['topic'], p_data['partition']) for p_data in new_plan['partitions'] ]) base_partitions = set([ (p_data['topic'], p_data['partition']) for p_data in base_plan['partitions'] ]...
def _validate_plan_base( new_plan, base_plan, is_partition_subset=True, allow_rf_change=False, )
Validate if given plan is valid comparing with given base-plan. Validate following assertions: - Partition-check: New partition-set should be subset of base-partition set - Replica-count check: Replication-factor for each partition remains same - Broker-check: New broker-set should be subset of base br...
2.112819
2.04128
1.035046
# Verify presence of required keys if set(plan.keys()) != set(['version', 'partitions']): _log.error( 'Invalid or incomplete keys in given plan. Expected: "version", ' '"partitions". Found:{keys}' .format(keys=', '.join(list(plan.keys()))), ) retu...
def _validate_format(plan)
Validate if the format of the plan as expected. Validate format of plan on following rules: a) Verify if it ONLY and MUST have keys and value, 'version' and 'partitions' b) Verify if each value of 'partitions' ONLY and MUST have keys 'replicas', 'partition', 'topic' c) Verify desired type of ea...
2.014891
1.91742
1.050835
# Validate format of plan if not _validate_format(plan): return False # Verify no duplicate partitions partition_names = [ (p_data['topic'], p_data['partition']) for p_data in plan['partitions'] ] duplicate_partitions = [ partition for partition, count in si...
def _validate_plan(plan)
Validate if given plan is valid based on kafka-cluster-assignment protocols. Validate following parameters: - Correct format of plan - Partition-list should be unique - Every partition of a topic should have same replication-factor - Replicas of a partition should have unique broker-set
2.321091
2.224782
1.043289
sorted_offsets = sorted( list(consumer_offsets_metadata.items()), key=lambda topic_offsets: sum([o.highmark - o.current for o in topic_offsets[1]]) ) return OrderedDict(sorted_offsets)
def sort_by_distance(cls, consumer_offsets_metadata)
Receives a dict of (topic_name: ConsumerPartitionOffset) and returns a similar dict where the topics are sorted by total offset distance.
4.468403
3.943188
1.133196
sorted_offsets = sorted( list(consumer_offsets_metadata.items()), key=lambda topic_offsets1: sum( [cls.percentage_distance(o.highmark, o.current) for o in topic_offsets1[1]] ) ) return OrderedDict(sorted_offsets)
def sort_by_distance_percentage(cls, consumer_offsets_metadata)
Receives a dict of (topic_name: ConsumerPartitionOffset) and returns an similar dict where the topics are sorted by average offset distance in percentage.
4.478616
4.519619
0.990928
highmark = int(highmark) current = int(current) if highmark > 0: return round( (highmark - current) * 100.0 / highmark, 2, ) else: return 0.0
def percentage_distance(cls, highmark, current)
Percentage of distance the current offset is behind the highmark.
2.56053
2.419116
1.058457
_log.debug( "ZK: Getting children of {path}".format(path=path), ) return self.zk.get_children(path, watch)
def get_children(self, path, watch=None)
Returns the children of the specified node.
5.809478
5.393952
1.077036
_log.debug( "ZK: Getting {path}".format(path=path), ) return self.zk.get(path, watch)
def get(self, path, watch=None)
Returns the data of the specified node.
7.33235
6.964991
1.052744
_log.debug( "ZK: Setting {path} to {value}".format(path=path, value=value) ) return self.zk.set(path, value)
def set(self, path, value)
Sets and returns new data for the specified node.
4.458139
4.520037
0.986306
data, _ = self.get(path, watch) return load_json(data) if data else None
def get_json(self, path, watch=None)
Reads the data of the specified node and converts it to json.
5.873008
5.649786
1.03951
try: broker_ids = self.get_children("/brokers/ids") except NoNodeError: _log.info( "cluster is empty." ) return {} # Return broker-ids only if names_only: return {int(b_id): None for b_id in broker_ids} ...
def get_brokers(self, names_only=False)
Get information on all the available brokers. :rtype : dict of brokers
3.836635
4.084472
0.939322
try: config_data = load_json( self.get( "/config/topics/{topic}".format(topic=topic) )[0] ) except NoNodeError as e: # Kafka version before 0.8.1 does not have "/config/topics/<topic_name>" path in ZK and ...
def get_topic_config(self, topic)
Get configuration information for specified topic. :rtype : dict of configuration
4.376017
4.418653
0.990351
config_data = dump_json(value) try: # Change value return_value = self.set( "/config/topics/{topic}".format(topic=topic), config_data ) # Create change version = kafka_version[1] # this fea...
def set_topic_config(self, topic, value, kafka_version=(0, 10, ))
Set configuration information for specified topic. :topic : topic whose configuration needs to be changed :value : config value with which the topic needs to be updated with. This would be of the form key=value. Example 'cleanup.policy=compact' :kafka_version :tuple kaf...
3.745776
3.760302
0.996137
try: topic_ids = [topic_name] if topic_name else self.get_children( "/brokers/topics", ) except NoNodeError: _log.error( "Cluster is empty." ) return {} if names_only: return topic_i...
def get_topics( self, topic_name=None, names_only=False, fetch_partition_state=True, )
Get information on all the available topics. Topic-data format with fetch_partition_state as False :- topic_data = { 'version': 1, 'partitions': { <p_id>: { replicas: <broker-ids> } } } Topic-data f...
2.291237
2.099976
1.091078
if consumer_group_id is None: group_ids = self.get_children("/consumers") else: group_ids = [consumer_group_id] # Return consumer-group-ids only if names_only: return {g_id: None for g_id in group_ids} consumer_offsets = {} f...
def get_consumer_groups(self, consumer_group_id=None, names_only=False)
Get information on all the available consumer-groups. If names_only is False, only list of consumer-group ids are sent. If names_only is True, Consumer group offset details are returned for all consumer-groups or given consumer-group if given in dict format as:- { '...
2.67719
2.518602
1.062967
group_offsets = {} try: all_topics = self.get_my_subscribed_topics(group) except NoNodeError: # No offset information of given consumer-group _log.warning( "No topics subscribed to consumer-group {group}.".format( g...
def get_group_offsets(self, group, topic=None)
Fetch group offsets for given topic and partition otherwise all topics and partitions otherwise. { 'topic': { 'partition': offset-value, ... ... } }
2.45608
2.403612
1.021829
state_path = "/brokers/topics/{topic_id}/partitions/{p_id}/state" try: partition_state = self.get( state_path.format(topic_id=topic_id, p_id=partition_id), ) return partition_state except NoNodeError: return {}
def _fetch_partition_state(self, topic_id, partition_id)
Fetch partition-state for given topic-partition.
3.168543
2.989216
1.059991
info_path = "/brokers/topics/{topic_id}/partitions/{p_id}" try: _, partition_info = self.get( info_path.format(topic_id=topic_id, p_id=partition_id), ) return partition_info except NoNodeError: return {}
def _fetch_partition_info(self, topic_id, partition_id)
Fetch partition info for given topic-partition.
3.346204
3.185004
1.050612
path = "/consumers/{group_id}/offsets".format(group_id=groupid) return self.get_children(path)
def get_my_subscribed_topics(self, groupid)
Get the list of topics that a consumer is subscribed to :param: groupid: The consumer group ID for the consumer :returns list of kafka topics :rtype: list
5.859273
6.243835
0.938409
path = "/consumers/{group_id}/offsets/{topic}".format( group_id=groupid, topic=topic, ) return self.get_children(path)
def get_my_subscribed_partitions(self, groupid, topic)
Get the list of partitions of a topic that a consumer is subscribed to :param: groupid: The consumer group ID for the consumer :param: topic: The topic name :returns list of partitions :rtype: list
4.009365
4.398355
0.91156
plan = self.get_cluster_plan() assignment = {} for elem in plan['partitions']: assignment[ (elem['topic'], elem['partition']) ] = elem['replicas'] return assignment
def get_cluster_assignment(self)
Fetch the cluster layout in form of assignment from zookeeper
6.261844
5.28931
1.183868
_log.debug("ZK: Creating node " + path) return self.zk.create(path, value, acl, ephemeral, sequence, makepath)
def create( self, path, value='', acl=None, ephemeral=False, sequence=False, makepath=False )
Creates a Zookeeper node. :param: path: The zookeeper node path :param: value: Zookeeper node value :param: acl: ACL list :param: ephemeral: Boolean indicating where this node is tied to this session. :param: sequence: Boolean indicating whether path is suffixed ...
4.96396
5.080407
0.977079
_log.debug("ZK: Deleting node " + path) return self.zk.delete(path, recursive=recursive)
def delete(self, path, recursive=False)
Deletes a Zookeeper node. :param: path: The zookeeper node path :param: recursive: Recursively delete node and all its children.
7.105911
7.046541
1.008425
reassignment_path = '{admin}/{reassignment_node}'\ .format(admin=ADMIN_PATH, reassignment_node=REASSIGNMENT_NODE) plan_json = dump_json(plan) base_plan = self.get_cluster_plan() if not validate_plan(plan, base_plan, allow_rf_change=allow_rf_change): _log....
def execute_plan(self, plan, allow_rf_change=False)
Submit reassignment plan for execution.
3.699786
3.541151
1.044798
_log.info('Fetching current cluster-topology from Zookeeper...') cluster_layout = self.get_topics(fetch_partition_state=False) # Re-format cluster-layout partitions = [ { 'topic': topic_id, 'partition': int(p_id), 'rep...
def get_cluster_plan(self)
Fetch cluster plan from zookeeper.
4.645053
4.125381
1.12597
reassignment_path = '{admin}/{reassignment_node}'\ .format(admin=ADMIN_PATH, reassignment_node=REASSIGNMENT_NODE) try: result = self.get(reassignment_path) return load_json(result[0]) except NoNodeError: return {}
def get_pending_plan(self)
Read the currently running plan on reassign_partitions node.
5.769791
4.338571
1.329883
out = {} partitions_count = len(partitions) out['raw'] = { 'offline_count': partitions_count, } if partitions_count == 0: out['message'] = 'No offline partitions.' else: out['message'] = "{count} offline partitions.".format(count=partitions_count) if verbose...
def _prepare_output(partitions, verbose)
Returns dict with 'raw' and 'message' keys filled.
3.111928
2.827708
1.100512
offline = get_topic_partition_with_error( self.cluster_config, LEADER_NOT_AVAILABLE_ERROR, ) errcode = status_code.OK if not offline else status_code.CRITICAL out = _prepare_output(offline, self.args.verbose) return errcode, out
def run_command(self)
Checks the number of offline partitions
12.09763
9.383515
1.289243
'''Get the group_id of groups committed into Kafka.''' kafka_group_reader = KafkaGroupReader(cluster_config) return list(kafka_group_reader.read_groups().keys())
def get_kafka_groups(cls, cluster_config)
Get the group_id of groups committed into Kafka.
7.850148
4.393604
1.786722
with closing(SSHClient()) as client: client.set_missing_host_key_policy(AutoAddPolicy()) cfg = { "hostname": host, "timeout": max_timeout, } if ssh_password: cfg['password'] = ssh_password ssh_config = SSHConfig() user_config...
def ssh(host, forward_agent=False, sudoable=False, max_attempts=1, max_timeout=5, ssh_password=None)
Manages a SSH connection to the desired host. Will leverage your ssh config at ~/.ssh/config if available :param host: the server to connect to :type host: str :param forward_agent: forward the local agents :type forward_agent: bool :param sudoable: allow sudo commands :type sudoable: bo...
1.96627
1.963371
1.001477
lines = stdout.readlines() if lines: print("STDOUT from {host}:".format(host=host)) for line in lines: print(line.rstrip(), file=sys.stdout)
def report_stdout(host, stdout)
Take a stdout and print it's lines to output if lines are present. :param host: the host where the process is running :type host: str :param stdout: the std out of that process :type stdout: paramiko.channel.Channel
3.056203
3.422935
0.89286
lines = stderr.readlines() if lines: print("STDERR from {host}:".format(host=host)) for line in lines: print(line.rstrip(), file=sys.stderr)
def report_stderr(host, stderr)
Take a stderr and print it's lines to output if lines are present. :param host: the host where the process is running :type host: str :param stderr: the std error of that process :type stderr: paramiko.channel.Channel
2.985548
3.305669
0.90316
new_command = "sudo {0}".format(command) return self.exec_command(new_command, bufsize)
def sudo_command(self, command, bufsize=-1)
Sudo a command on the SSH server. Delegates to :func`~ssh.Connection.exec_command` :param command: the command to execute :type command: str :param bufsize: interpreted the same way as by the built-in C{file()} function in python :type bufsize: int :returns the stdin, st...
3.409538
5.380651
0.633666
channel = self.transport.open_session() if self.forward_agent: AgentRequestHandler(channel) if self.sudoable: channel.get_pty() channel.exec_command(command) if check_status and channel.recv_exit_status() != 0: raise RuntimeError("Co...
def exec_command(self, command, bufsize=-1, check_status=True)
Execute a command on the SSH server while preserving underling agent forwarding and sudo privileges. https://github.com/paramiko/paramiko/blob/1.8/paramiko/client.py#L348 :param command: the command to execute :type command: str :param bufsize: interpreted the same way as by the...
2.451626
2.419378
1.013329
# Build consumer-offset data in desired format current_consumer_offsets = defaultdict(dict) for topic, topic_offsets in six.iteritems(consumer_offsets_metadata): for partition_offset in topic_offsets: current_consumer_offsets[topic][partition_offset.partition...
def save_offsets( cls, consumer_offsets_metadata, topics_dict, json_file, groupid, )
Built offsets for given topic-partitions in required format from current offsets metadata and write to given json-file. :param consumer_offsets_metadata: Fetched consumer offsets from kafka. :param topics_dict: Dictionary of topic-partitions. :param json_file: Filename to store consumer...
2.999738
2.967907
1.010725
# Save consumer-offsets to file with open(json_file_name, "w") as json_file: try: json.dump(consumer_offsets_data, json_file) except ValueError: print("Error: Invalid json data {data}".format(data=consumer_offsets_data)) ra...
def write_offsets_to_file(cls, json_file_name, consumer_offsets_data)
Save built consumer-offsets data to given json file.
2.821776
2.656767
1.062109
groups = set() for b_id in broker_ids: try: broker = self.cluster_topology.brokers[b_id] except KeyError: self.log.error("Invalid broker id %s.", b_id) # Raise an error for now. As alternative we may ignore the ...
def decommission_brokers(self, broker_ids)
Decommission a list of brokers trying to keep the replication group the brokers belong to balanced. :param broker_ids: list of string representing valid broker ids in the cluster :raises: InvalidBrokerIdError when the id is invalid.
4.209375
3.852952
1.092507
try: group.rebalance_brokers() except EmptyReplicationGroupError: self.log.warning("No active brokers left in replication group %s", group) for broker in group.brokers: if broker.decommissioned and not broker.empty(): # In this case we...
def _decommission_brokers_in_group(self, group)
Decommission the marked brokers of a group.
4.488208
4.450014
1.008583
# Balance replicas over replication-groups for each partition if any(b.inactive for b in six.itervalues(self.cluster_topology.brokers)): self.log.error( "Impossible to rebalance replication groups because of inactive " "brokers." ) ...
def rebalance_replication_groups(self)
Rebalance partitions over replication groups. First step involves rebalancing replica-count for each partition across replication-groups. Second step involves rebalancing partition-count across replication-groups of the cluster.
5.432662
4.419684
1.229197
for rg in six.itervalues(self.cluster_topology.rgs): rg.rebalance_brokers()
def rebalance_brokers(self)
Rebalance partition-count across brokers within each replication-group.
8.712047
6.719898
1.296455
for b_id in broker_ids: try: broker = self.cluster_topology.brokers[b_id] except KeyError: self.log.error("Invalid broker id %s.", b_id) raise InvalidBrokerIdError( "Broker id {} does not exist in cluster".forma...
def revoke_leadership(self, broker_ids)
Revoke leadership for given brokers. :param broker_ids: List of broker-ids whose leadership needs to be revoked.
4.349168
4.397992
0.988899
owned_partitions = list(filter( lambda p: broker is p.leader, broker.partitions, )) for partition in owned_partitions: if len(partition.replicas) == 1: self.log.error( "Cannot be revoked leadership for broker {b} fo...
def _force_revoke_leadership(self, broker)
Revoke the leadership of given broker for any remaining partitions. Algorithm: 1. Find the partitions (owned_partitions) with given broker as leader. 2. For each partition find the eligible followers. Brokers which are not to be revoked from leadership are eligible followers. ...
3.599738
3.17266
1.134612
opt_leader_cnt = len(self.cluster_topology.partitions) // len(self.cluster_topology.brokers) # Balanced brokers transfer leadership to their under-balanced followers self.rebalancing_non_followers(opt_leader_cnt)
def rebalance_leaders(self)
Re-order brokers in replicas such that, every broker is assigned as preferred leader evenly.
13.584264
11.031417
1.231416
# Don't include leaders if they are marked for leadership removal under_brokers = list(filter( lambda b: b.count_preferred_replica() < opt_cnt and not b.revoked_leadership, six.itervalues(self.cluster_topology.brokers), )) if under_brokers: sk...
def rebalancing_non_followers(self, opt_cnt)
Transfer leadership to any under-balanced followers on the pretext that they remain leader-balanced or can be recursively balanced through non-followers (followers of other leaders). Context: Consider a graph G: Nodes: Brokers (e.g. b1, b2, b3) Edges: From b1 to b2 s.t. ...
3.771863
3.501202
1.077305
# Segregate replication-groups based on partition-count total_elements = sum(len(rg.partitions) for rg in six.itervalues(self.cluster_topology.rgs)) over_loaded_rgs, under_loaded_rgs = separate_groups( list(self.cluster_topology.rgs.values()), lambda rg: len(rg.p...
def _rebalance_groups_partition_cnt(self)
Re-balance partition-count across replication-groups. Algorithm: The key constraint is not to create any replica-count imbalance while moving partitions across replication-groups. 1) Divide replication-groups into over and under loaded groups in terms of partition-count. ...
2.828613
2.581626
1.095671
try: partition = self.cluster_topology.partitions[partition_name] except KeyError: raise InvalidPartitionError( "Partition name {name} not found".format(name=partition_name), ) if partition.replication_factor + count > len(self.cluster...
def add_replica(self, partition_name, count=1)
Increase the replication-factor for a partition. The replication-group to add to is determined as follows: 1. Find all replication-groups that have brokers not already replicating the partition. 2. Of these, find replication-groups that have fewer than the ...
2.447947
2.27033
1.078234
try: partition = self.cluster_topology.partitions[partition_name] except KeyError: raise InvalidPartitionError( "Partition name {name} not found".format(name=partition_name), ) if partition.replication_factor <= count: rais...
def remove_replica(self, partition_name, osr_broker_ids, count=1)
Remove one replica of a partition from the cluster. The replication-group to remove from is determined as follows: 1. Find all replication-groups that contain at least one out-of-sync replica for this partition. 2. Of these, find replication-groups with more than the ave...
2.28536
2.183086
1.046848
# Is the new consumer already subscribed to any of these topics? common_topics = [topic for topic in topics_dest_group if topic in source_topics] if common_topics: print( "Error: Consumer Group ID: {groupid} is already " "subscribed to following topics: {topic}.\nPlease ...
def preprocess_topics(source_groupid, source_topics, dest_groupid, topics_dest_group)
Pre-process the topics in source and destination group for duplicates.
3.674887
3.717153
0.98863
# Create new offsets for topic, partition_offsets in six.iteritems(offsets): for partition, offset in six.iteritems(partition_offsets): new_path = "/consumers/{groupid}/offsets/{topic}/{partition}".format( groupid=consumer_group, topic=topic, ...
def create_offsets(zk, consumer_group, offsets)
Create path with offset value for each topic-partition of given consumer group. :param zk: Zookeeper client :param consumer_group: Consumer group id for given offsets :type consumer_group: int :param offsets: Offsets of all topic-partitions :type offsets: dict(topic, dict(partition, offset))
2.487237
2.501552
0.994278
source_offsets = defaultdict(dict) for topic, partitions in six.iteritems(topics): for partition in partitions: offset, _ = zk.get( "/consumers/{groupid}/offsets/{topic}/{partition}".format( groupid=consumer_group, topic=topic, ...
def fetch_offsets(zk, consumer_group, topics)
Fetch offsets for given topics of given consumer group. :param zk: Zookeeper client :param consumer_group: Consumer group id for given offsets :type consumer_group: int :rtype: dict(topic, dict(partition, offset))
2.400267
2.520161
0.952426
metadata = get_topic_partition_metadata(kafka_config.broker_list) if CONSUMER_OFFSET_TOPIC not in metadata: raise UnknownTopic("Consumer offset topic is missing.") return len(metadata[CONSUMER_OFFSET_TOPIC])
def get_offset_topic_partition_count(kafka_config)
Given a kafka cluster configuration, return the number of partitions in the offset topic. It will raise an UnknownTopic exception if the topic cannot be found.
4.386901
3.844715
1.141021
def java_string_hashcode(s): h = 0 for c in s: h = (31 * h + ord(c)) & 0xFFFFFFFF return ((h + 0x80000000) & 0xFFFFFFFF) - 0x80000000 return abs(java_string_hashcode(group)) % partition_count
def get_group_partition(group, partition_count)
Given a group name, return the partition number of the consumer offset topic containing the data associated to that group.
2.286686
2.203542
1.037732
tp_timestamps = {} for topic in topics: topic_partitions = consumer_partitions_for_topic(consumer, topic) for tp in topic_partitions: tp_timestamps[tp] = timestamp return consumer.offsets_for_times(tp_timestamps)
def topic_offsets_for_timestamp(consumer, timestamp, topics)
Given an initialized KafkaConsumer, timestamp, and list of topics, looks up the offsets for the given topics by timestamp. The returned offset for each partition is the earliest offset whose timestamp is greater than or equal to the given timestamp in the corresponding partition. Arguments: con...
3.041888
3.572919
0.851373
topic_partitions = [] partitions = consumer.partitions_for_topic(topic) if partitions is not None: for partition in partitions: topic_partitions.append(TopicPartition(topic, partition)) else: logging.error( "No partitions found for topic {}. Maybe it doesn't ...
def consumer_partitions_for_topic(consumer, topic)
Returns a list of all TopicPartitions for a given topic. Arguments: consumer: an initialized KafkaConsumer topic: a topic name to fetch TopicPartitions for :returns: list(TopicPartition): A list of TopicPartitions that belong to the given topic
2.365952
2.453436
0.964342
no_offsets = set() for tp, offset in six.iteritems(partition_to_offset): if offset is None: logging.error( "No offsets found for topic-partition {tp}. Either timestamps not supported" " for the topic {tp}, or no offsets found after timestamp specified, or...
def consumer_commit_for_times(consumer, partition_to_offset, atomic=False)
Commits offsets to Kafka using the given KafkaConsumer and offsets, a mapping of TopicPartition to Unix Epoch milliseconds timestamps. Arguments: consumer (KafkaConsumer): an initialized kafka-python consumer. partitions_to_offset (dict TopicPartition: OffsetAndTimestamp): Map of TopicPartition...
3.511414
3.577892
0.98142
if not kafka_topology_base_path: config_dirs = get_conf_dirs() else: config_dirs = [kafka_topology_base_path] topology = None for config_dir in config_dirs: try: topology = TopologyConfiguration( cluster_type, config_dir, ...
def get_cluster_config( cluster_type, cluster_name=None, kafka_topology_base_path=None, )
Return the cluster configuration. Use the local cluster if cluster_name is not specified. :param cluster_type: the type of the cluster :type cluster_type: string :param cluster_name: the name of the cluster :type cluster_name: string :param kafka_topology_base_path: base path to look for <clust...
2.545051
2.493117
1.020831
if not kafka_topology_base_path: config_dirs = get_conf_dirs() else: config_dirs = [kafka_topology_base_path] types = set() for config_dir in config_dirs: new_types = [x for x in map( lambda x: os.path.basename(x)[:-5], glob.glob('{0}/*.yaml'.format(...
def iter_configurations(kafka_topology_base_path=None)
Cluster topology iterator. Iterate over all the topologies available in config.
2.813891
2.769552
1.01601
config_path = os.path.join( self.kafka_topology_path, '{id}.yaml'.format(id=self.cluster_type), ) self.log.debug("Loading configuration from %s", config_path) if os.path.isfile(config_path): topology_config = load_yaml_config(config_path) ...
def load_topology_config(self)
Load the topology configuration
2.557699
2.514648
1.01712
error_msg = 'Positive integer or -1 required, {string} given.'.format(string=string) try: value = int(string) except ValueError: raise argparse.ArgumentTypeError(error_msg) if value <= 0 and value != -1: raise argparse.ArgumentTypeError(error_msg) return value
def convert_to_broker_id(string)
Convert string to kafka broker_id.
3.003138
2.842932
1.056353
parser = argparse.ArgumentParser( description='Check kafka current status', ) parser.add_argument( "--cluster-type", "-t", dest='cluster_type', required=True, help='Type of cluster', default=None, ) parser.add_argument( "--cluster-...
def parse_args()
Parse the command line arguments.
3.145116
3.114693
1.009767
args = parse_args() logging.basicConfig(level=logging.WARN) # to prevent flooding for sensu-check. logging.getLogger('kafka').setLevel(logging.CRITICAL) if args.controller_only and args.first_broker_only: terminate( status_code.WARNING, prepare_terminate_messag...
def run()
Verify command-line arguments and run commands
3.169836
3.134746
1.011194
parser = argparse.ArgumentParser( description='Manage and describe partition layout over brokers of' ' a cluster.', ) parser.add_argument( '--cluster-type', '-t', dest='cluster_type', help='Type of the cluster.', type=str, required=True, ...
def parse_args()
Parse the arguments.
2.802136
2.788443
1.004911
if not issubclass(exc_type, KeyboardInterrupt): # do not log Ctrl-C _log.critical( "Uncaught exception:", exc_info=(exc_type, exc_value, exc_traceback) ) sys.__excepthook__(exc_type, exc_value, exc_traceback)
def exception_logger(exc_type, exc_value, exc_traceback)
Log unhandled exceptions
2.288816
2.278615
1.004477
topics_with_wrong_rf = [] for topic_name, partitions in topics.items(): min_isr = get_min_isr(zk, topic_name) or default_min_isr replication_factor = len(partitions[0].replicas) if replication_factor >= min_isr + 1: continue topics_with_wrong_rf.append({ ...
def _find_topics_with_wrong_rp(topics, zk, default_min_isr)
Returns topics with wrong replication factor.
2.279562
2.111926
1.079376
out = {} topics_count = len(topics_with_wrong_rf) out['raw'] = { 'topics_with_wrong_replication_factor_count': topics_count, } if topics_count == 0: out['message'] = 'All topics have proper replication factor.' else: out['message'] = ( "{0} topic(s) have...
def _prepare_output(topics_with_wrong_rf, verbose)
Returns dict with 'raw' and 'message' keys filled.
3.00228
2.816234
1.066062
topics = get_topic_partition_metadata(self.cluster_config.broker_list) topics_with_wrong_rf = _find_topics_with_wrong_rp( topics, self.zk, self.args.default_min_isr, ) errcode = status_code.OK if not topics_with_wrong_rf else status_code.CRI...
def run_command(self)
Replication factor command, checks replication factor settings and compare it with min.isr in the cluster.
6.896889
6.16631
1.118479
return kafka.protocol.commit.OffsetCommitRequest[2]( consumer_group=group, consumer_group_generation_id=kafka.protocol.commit.OffsetCommitRequest[2].DEFAULT_GENERATION_ID, consumer_id='', retention_time=kafka.protocol.commit.OffsetCommitRequest[2].DEFAULT...
def encode_offset_commit_request_kafka(cls, group, payloads)
Encode an OffsetCommitRequest struct Arguments: group: string, the consumer group you are committing offsets for payloads: list of OffsetCommitRequestPayload
3.648733
3.459114
1.054817
return ConsumerMetadataResponse( response.error_code, response.coordinator_id, response.host, response.port, )
def decode_consumer_metadata_response(cls, response)
Decode GroupCoordinatorResponse. Note that ConsumerMetadataResponse is renamed to GroupCoordinatorResponse in 0.9+ Arguments: response: response to decode
5.219951
4.252683
1.227449
if self.args.num_gens < self.args.max_partition_movements: self.log.warning( "num-gens ({num_gens}) is less than max-partition-movements" " ({max_partition_movements}). max-partition-movements will" " never be reached.".format( ...
def rebalance(self)
The genetic rebalancing algorithm runs for a fixed number of generations. Each generation has two phases: exploration and pruning. In exploration, a large set of possible states are found by randomly applying assignment changes to the existing states. In pruning, each state is given a sc...
3.139132
2.975099
1.055135
decommission_brokers = [] for broker_id in broker_ids: try: broker = self.cluster_topology.brokers[broker_id] broker.mark_decommissioned() decommission_brokers.append(broker) except KeyError: raise InvalidBr...
def decommission_brokers(self, broker_ids)
Decommissioning brokers is done by removing all partitions from the decommissioned brokers and adding them, one-by-one, back to the cluster. :param broker_ids: List of broker ids that should be decommissioned.
2.926543
2.823784
1.03639
try: partition = self.cluster_topology.partitions[partition_name] except KeyError: raise InvalidPartitionError( "Partition name {name} not found.".format(name=partition_name), ) active_brokers = self.cluster_topology.active_brokers ...
def add_replica(self, partition_name, count=1)
Adding a replica is done by trying to add the replica to every broker in the cluster and choosing the resulting state with the highest fitness score. :param partition_name: (topic_id, partition_id) of the partition to add replicas of. :param count: The number of replicas to add.
3.092904
3.091048
1.0006
try: partition = self.cluster_topology.partitions[partition_name] except KeyError: raise InvalidPartitionError( "Partition name {name} not found.".format(name=partition_name), ) if partition.replication_factor - count < 1: ...
def remove_replica(self, partition_name, osr_broker_ids, count=1)
Removing a replica is done by trying to remove a replica from every broker and choosing the resulting state with the highest fitness score. Out-of-sync replicas will always be removed before in-sync replicas. :param partition_name: (topic_id, partition_id) of the partition to remove replicas of...
2.754645
2.734431
1.007392
new_pop = set(pop) exploration_per_state = self.args.max_exploration // len(pop) mutations = [] if self.args.brokers: mutations.append(self._move_partition) if self.args.leaders: mutations.append(self._move_leadership) for state in pop: ...
def _explore(self, pop)
Exploration phase: Find a set of candidate states based on the current population. :param pop: The starting population for this generation.
3.796149
3.767831
1.007516
partition = random.randint(0, len(self.cluster_topology.partitions) - 1) # Choose distinct source and destination brokers. source = random.choice(state.replicas[partition]) dest = random.randint(0, len(self.cluster_topology.brokers) - 1) if dest in state.replicas[partit...
def _move_partition(self, state)
Attempt to move a random partition to a random broker. If the chosen movement is not possible, None is returned. :param state: The starting state. :return: The resulting State object if a movement is found. None if no movement is found.
3.152644
3.074427
1.025441
partition = random.randint(0, len(self.cluster_topology.partitions) - 1) # Moving zero weight partitions will not improve balance for any of the # balance criteria. Disallow these movements here to avoid wasted # effort. if state.partition_weights[partition] == 0: ...
def _move_leadership(self, state)
Attempt to move a random partition to a random broker. If the chosen movement is not possible, None is returned. :param state: The starting state. :return: The resulting State object if a leader change is found. None if no change is found.
4.547363
4.381415
1.037876
return set( sorted(pop_candidates, key=self._score, reverse=True) [:self.args.max_pop] )
def _prune(self, pop_candidates)
Choose a subset of the candidate states to continue on to the next generation. :param pop_candidates: The set of candidate states.
6.343013
8.220838
0.771577
score = 0 max_score = 0 if state.total_weight: # Coefficient of variance is a value between 0 and the sqrt(n) # where n is the length of the series (the number of brokers) # so those parameters are scaled by (1 / sqrt(# or brokers)) to # g...
def _score(self, state, score_movement=True)
Score a state based on how balanced it is. A higher score represents a more balanced state. :param state: The state to score.
2.481297
2.494949
0.994528
new_state = copy(self) # Update the partition replica tuple source_index = self.replicas[partition].index(source) new_state.replicas = tuple_alter( self.replicas, (partition, lambda replicas: tuple_replace( replicas, (sour...
def move(self, partition, source, dest)
Return a new state that is the result of moving a single partition. :param partition: The partition index of the partition to move. :param source: The broker index of the broker to move the partition from. :param dest: The broker index of the broker to move the partition to.
2.056271
2.004094
1.026035
new_state = copy(self) # Update the partition replica tuple source = new_state.replicas[partition][0] new_leader_index = self.replicas[partition].index(new_leader) new_state.replicas = tuple_alter( self.replicas, (partition, lambda replicas: tupl...
def move_leadership(self, partition, new_leader)
Return a new state that is the result of changing the leadership of a single partition. :param partition: The partition index of the partition to change the leadership of. :param new_leader: The broker index of the new leader replica.
2.890439
2.902985
0.995678
return { partition.name: [ self.brokers[bid].id for bid in self.replicas[pid] ] for pid, partition in enumerate(self.partitions) }
def assignment(self)
Return the partition assignment that this state represents.
7.590373
5.745683
1.321057
return { self.partitions[pid].name: [ self.brokers[bid].id for bid in self.replicas[pid] ] for pid in set(self.pending_partitions) }
def pending_assignment(self)
Return the pending partition assignment that this state represents.
7.27937
5.36028
1.358021
parser = argparse.ArgumentParser( description='Show available clusters.' ) parser.add_argument( '-v', '--version', action='version', version="%(prog)s {0}".format(__version__), ) parser.add_argument( '--discovery-base-path', dest='discover...
def parse_args()
Parse the arguments.
3.760906
3.598149
1.045233
partitions_count = len(partitions) out = {} out['raw'] = { 'replica_unavailability_count': partitions_count, } if partitions_count == 0: out['message'] = 'All replicas available for communication.' else: out['message'] = "{replica_unavailability} replicas unavailabl...
def _prepare_output(partitions, unavailable_brokers, verbose)
Returns dict with 'raw' and 'message' keys filled.
3.115446
2.894923
1.076176
fetch_unavailable_brokers = True result = get_topic_partition_with_error( self.cluster_config, REPLICA_NOT_AVAILABLE_ERROR, fetch_unavailable_brokers=fetch_unavailable_brokers, ) if fetch_unavailable_brokers: replica_unavailability...
def run_command(self)
replica_unavailability command, checks number of replicas not available for communication over all brokers in the Kafka cluster.
5.079827
4.109071
1.236247
ISR_CONF_NAME = 'min.insync.replicas' try: config = zk.get_topic_config(topic) except NoNodeError: return None if ISR_CONF_NAME in config['config']: return int(config['config'][ISR_CONF_NAME]) else: return None
def get_min_isr(zk, topic)
Return the min-isr for topic, or None if not specified
3.077882
2.674392
1.150871
not_in_sync_partitions = [] for topic_name, partitions in topics.items(): min_isr = get_min_isr(zk, topic_name) or default_min_isr if min_isr is None: continue for metadata in partitions.values(): cur_isr = len(metadata.isr) if cur_isr < min_isr: ...
def _process_metadata_response(topics, zk, default_min_isr)
Returns not in sync partitions.
2.391678
2.02904
1.178724
out = {} partitions_count = len(partitions) out['raw'] = { 'not_enough_replicas_count': partitions_count, } if partitions_count == 0: out['message'] = 'All replicas in sync.' else: out['message'] = ( "{0} partition(s) have the number of replicas in " ...
def _prepare_output(partitions, verbose)
Returns dict with 'raw' and 'message' keys filled.
3.775996
3.537349
1.067465
if partition in self._partitions: # Remove partition from set self._partitions.remove(partition) # Remove broker from replica list of partition partition.replicas.remove(self) else: raise ValueError( 'Partition: {topic_...
def remove_partition(self, partition)
Remove partition from partition list.
3.165676
3.032835
1.043801
assert(partition not in self._partitions) # Add partition to existing set self._partitions.add(partition) # Add broker to replica list partition.add_replica(self)
def add_partition(self, partition)
Add partition to partition list.
6.197332
5.574266
1.111775