idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
13,700 | def get_topic_partition_metadata ( hosts ) : kafka_client = KafkaToolClient ( hosts , timeout = 10 ) kafka_client . load_metadata_for_topics ( ) topic_partitions = kafka_client . topic_partitions resp = kafka_client . send_metadata_request ( ) for _ , topic , partitions in resp . topics : for partition_error , partition , leader , replicas , isr in partitions : if topic_partitions . get ( topic , { } ) . get ( partition ) is not None : topic_partitions [ topic ] [ partition ] = PartitionMetadata ( topic , partition , leader , replicas , isr , partition_error ) return topic_partitions | Returns topic - partition metadata from Kafka broker . |
13,701 | def get_unavailable_brokers ( zk , partition_metadata ) : topic_data = zk . get_topics ( partition_metadata . topic ) topic = partition_metadata . topic partition = partition_metadata . partition expected_replicas = set ( topic_data [ topic ] [ 'partitions' ] [ str ( partition ) ] [ 'replicas' ] ) available_replicas = set ( partition_metadata . replicas ) return expected_replicas - available_replicas | Returns the set of unavailable brokers from the difference of replica set of given partition to the set of available replicas . |
13,702 | def get_current_consumer_offsets ( kafka_client , group , topics , raise_on_error = True , ) : topics = _verify_topics_and_partitions ( kafka_client , topics , raise_on_error ) group_offset_reqs = [ OffsetFetchRequestPayload ( topic , partition ) for topic , partitions in six . iteritems ( topics ) for partition in partitions ] group_offsets = { } send_api = kafka_client . send_offset_fetch_request_kafka if group_offset_reqs : group_resps = send_api ( group = group , payloads = group_offset_reqs , fail_on_error = False , callback = pluck_topic_offset_or_zero_on_unknown , ) for resp in group_resps : group_offsets . setdefault ( resp . topic , { } , ) [ resp . partition ] = resp . offset return group_offsets | Get current consumer offsets . |
13,703 | def get_topics_watermarks ( kafka_client , topics , raise_on_error = True ) : topics = _verify_topics_and_partitions ( kafka_client , topics , raise_on_error , ) highmark_offset_reqs = [ ] lowmark_offset_reqs = [ ] for topic , partitions in six . iteritems ( topics ) : for partition in partitions : highmark_offset_reqs . append ( OffsetRequestPayload ( topic , partition , - 1 , max_offsets = 1 ) ) lowmark_offset_reqs . append ( OffsetRequestPayload ( topic , partition , - 2 , max_offsets = 1 ) ) watermark_offsets = { } if not ( len ( highmark_offset_reqs ) + len ( lowmark_offset_reqs ) ) : return watermark_offsets highmark_resps = kafka_client . send_offset_request ( highmark_offset_reqs , fail_on_error = False , callback = _check_fetch_response_error , ) lowmark_resps = kafka_client . send_offset_request ( lowmark_offset_reqs , fail_on_error = False , callback = _check_fetch_response_error , ) assert len ( highmark_resps ) == len ( lowmark_resps ) aggregated_offsets = defaultdict ( lambda : defaultdict ( dict ) ) for resp in highmark_resps : aggregated_offsets [ resp . topic ] [ resp . partition ] [ 'highmark' ] = resp . offsets [ 0 ] for resp in lowmark_resps : aggregated_offsets [ resp . topic ] [ resp . partition ] [ 'lowmark' ] = resp . offsets [ 0 ] for topic , partition_watermarks in six . iteritems ( aggregated_offsets ) : for partition , watermarks in six . iteritems ( partition_watermarks ) : watermark_offsets . setdefault ( topic , { } , ) [ partition ] = PartitionOffsets ( topic , partition , watermarks [ 'highmark' ] , watermarks [ 'lowmark' ] , ) return watermark_offsets | Get current topic watermarks . |
13,704 | def set_consumer_offsets ( kafka_client , group , new_offsets , raise_on_error = True , ) : valid_new_offsets = _verify_commit_offsets_requests ( kafka_client , new_offsets , raise_on_error ) group_offset_reqs = [ OffsetCommitRequestPayload ( topic , partition , offset , metadata = '' , ) for topic , new_partition_offsets in six . iteritems ( valid_new_offsets ) for partition , offset in six . iteritems ( new_partition_offsets ) ] send_api = kafka_client . send_offset_commit_request_kafka status = [ ] if group_offset_reqs : status = send_api ( group , group_offset_reqs , raise_on_error , callback = _check_commit_response_error ) return [ _f for _f in status if _f and _f . error != 0 ] | Set consumer offsets to the specified offsets . |
13,705 | def nullify_offsets ( offsets ) : result = { } for topic , partition_offsets in six . iteritems ( offsets ) : result [ topic ] = _nullify_partition_offsets ( partition_offsets ) return result | Modify offsets metadata so that the partition offsets have null payloads . |
13,706 | def display_table ( headers , table ) : assert all ( len ( row ) == len ( headers ) for row in table ) str_headers = [ str ( header ) for header in headers ] str_table = [ [ str ( cell ) for cell in row ] for row in table ] column_lengths = [ max ( len ( header ) , * ( len ( row [ i ] ) for row in str_table ) ) for i , header in enumerate ( str_headers ) ] print ( " | " . join ( str ( header ) . ljust ( length ) for header , length in zip ( str_headers , column_lengths ) ) ) print ( "-+-" . join ( "-" * length for length in column_lengths ) ) for row in str_table : print ( " | " . join ( str ( cell ) . ljust ( length ) for cell , length in zip ( row , column_lengths ) ) ) | Print a formatted table . |
13,707 | def display_replica_imbalance ( cluster_topologies ) : assert cluster_topologies rg_ids = list ( next ( six . itervalues ( cluster_topologies ) ) . rgs . keys ( ) ) assert all ( set ( rg_ids ) == set ( cluster_topology . rgs . keys ( ) ) for cluster_topology in six . itervalues ( cluster_topologies ) ) rg_imbalances = [ stats . get_replication_group_imbalance_stats ( list ( cluster_topology . rgs . values ( ) ) , list ( cluster_topology . partitions . values ( ) ) , ) for cluster_topology in six . itervalues ( cluster_topologies ) ] _display_table_title_multicolumn ( 'Extra Replica Count' , 'Replication Group' , rg_ids , list ( cluster_topologies . keys ( ) ) , [ [ erc [ rg_id ] for rg_id in rg_ids ] for _ , erc in rg_imbalances ] , ) for name , imbalance in zip ( six . iterkeys ( cluster_topologies ) , ( imbalance for imbalance , _ in rg_imbalances ) ) : print ( '\n' '{name}' 'Total extra replica count: {imbalance}' . format ( name = '' if len ( cluster_topologies ) == 1 else name + '\n' , imbalance = imbalance , ) ) | Display replica replication - group distribution imbalance statistics . |
13,708 | def display_partition_imbalance ( cluster_topologies ) : broker_ids = list ( next ( six . itervalues ( cluster_topologies ) ) . brokers . keys ( ) ) assert all ( set ( broker_ids ) == set ( cluster_topology . brokers . keys ( ) ) for cluster_topology in six . itervalues ( cluster_topologies ) ) broker_partition_counts = [ stats . get_broker_partition_counts ( cluster_topology . brokers [ broker_id ] for broker_id in broker_ids ) for cluster_topology in six . itervalues ( cluster_topologies ) ] broker_weights = [ stats . get_broker_weights ( cluster_topology . brokers [ broker_id ] for broker_id in broker_ids ) for cluster_topology in six . itervalues ( cluster_topologies ) ] _display_table_title_multicolumn ( 'Partition Count' , 'Broker' , broker_ids , list ( cluster_topologies . keys ( ) ) , broker_partition_counts , ) print ( '' ) _display_table_title_multicolumn ( 'Partition Weight' , 'Broker' , broker_ids , list ( cluster_topologies . keys ( ) ) , broker_weights , ) for name , bpc , bw in zip ( list ( cluster_topologies . keys ( ) ) , broker_partition_counts , broker_weights ) : print ( '\n' '{name}' 'Partition count imbalance: {net_imbalance}\n' 'Broker weight mean: {weight_mean}\n' 'Broker weight stdev: {weight_stdev}\n' 'Broker weight cv: {weight_cv}' . format ( name = '' if len ( cluster_topologies ) == 1 else name + '\n' , net_imbalance = stats . get_net_imbalance ( bpc ) , weight_mean = stats . mean ( bw ) , weight_stdev = stats . stdevp ( bw ) , weight_cv = stats . coefficient_of_variation ( bw ) , ) ) | Display partition count and weight imbalance statistics . |
13,709 | def display_leader_imbalance ( cluster_topologies ) : broker_ids = list ( next ( six . itervalues ( cluster_topologies ) ) . brokers . keys ( ) ) assert all ( set ( broker_ids ) == set ( cluster_topology . brokers . keys ( ) ) for cluster_topology in six . itervalues ( cluster_topologies ) ) broker_leader_counts = [ stats . get_broker_leader_counts ( cluster_topology . brokers [ broker_id ] for broker_id in broker_ids ) for cluster_topology in six . itervalues ( cluster_topologies ) ] broker_leader_weights = [ stats . get_broker_leader_weights ( cluster_topology . brokers [ broker_id ] for broker_id in broker_ids ) for cluster_topology in six . itervalues ( cluster_topologies ) ] _display_table_title_multicolumn ( 'Leader Count' , 'Brokers' , broker_ids , list ( cluster_topologies . keys ( ) ) , broker_leader_counts , ) print ( '' ) _display_table_title_multicolumn ( 'Leader weight' , 'Brokers' , broker_ids , list ( cluster_topologies . keys ( ) ) , broker_leader_weights , ) for name , blc , blw in zip ( list ( cluster_topologies . keys ( ) ) , broker_leader_counts , broker_leader_weights ) : print ( '\n' '{name}' 'Leader count imbalance: {net_imbalance}\n' 'Broker leader weight mean: {weight_mean}\n' 'Broker leader weight stdev: {weight_stdev}\n' 'Broker leader weight cv: {weight_cv}' . format ( name = '' if len ( cluster_topologies ) == 1 else name + '\n' , net_imbalance = stats . get_net_imbalance ( blc ) , weight_mean = stats . mean ( blw ) , weight_stdev = stats . stdevp ( blw ) , weight_cv = stats . coefficient_of_variation ( blw ) , ) ) | Display leader count and weight imbalance statistics . |
13,710 | def display_topic_broker_imbalance ( cluster_topologies ) : broker_ids = list ( next ( six . itervalues ( cluster_topologies ) ) . brokers . keys ( ) ) assert all ( set ( broker_ids ) == set ( cluster_topology . brokers . keys ( ) ) for cluster_topology in six . itervalues ( cluster_topologies ) ) topic_names = list ( next ( six . itervalues ( cluster_topologies ) ) . topics . keys ( ) ) assert all ( set ( topic_names ) == set ( cluster_topology . topics . keys ( ) ) for cluster_topology in six . itervalues ( cluster_topologies ) ) imbalances = [ stats . get_topic_imbalance_stats ( [ cluster_topology . brokers [ broker_id ] for broker_id in broker_ids ] , [ cluster_topology . topics [ tname ] for tname in topic_names ] , ) for cluster_topology in six . itervalues ( cluster_topologies ) ] weighted_imbalances = [ stats . get_weighted_topic_imbalance_stats ( [ cluster_topology . brokers [ broker_id ] for broker_id in broker_ids ] , [ cluster_topology . topics [ tname ] for tname in topic_names ] , ) for cluster_topology in six . itervalues ( cluster_topologies ) ] _display_table_title_multicolumn ( 'Extra-Topic-Partition Count' , 'Brokers' , broker_ids , list ( cluster_topologies . keys ( ) ) , [ [ i [ 1 ] [ broker_id ] for broker_id in broker_ids ] for i in imbalances ] ) print ( '' ) _display_table_title_multicolumn ( 'Weighted Topic Imbalance' , 'Brokers' , broker_ids , list ( cluster_topologies . keys ( ) ) , [ [ wi [ 1 ] [ broker_id ] for broker_id in broker_ids ] for wi in weighted_imbalances ] ) for name , topic_imbalance , weighted_topic_imbalance in zip ( six . iterkeys ( cluster_topologies ) , ( i [ 0 ] for i in imbalances ) , ( wi [ 0 ] for wi in weighted_imbalances ) , ) : print ( '\n' '{name}' 'Topic partition imbalance count: {topic_imbalance}\n' 'Weighted topic partition imbalance: {weighted_topic_imbalance}' . format ( name = '' if len ( cluster_topologies ) == 1 else name + '\n' , topic_imbalance = topic_imbalance , weighted_topic_imbalance = weighted_topic_imbalance , ) ) | Display topic broker imbalance statistics . |
13,711 | def display_movements_stats ( ct , base_assignment ) : movement_count , movement_size , leader_changes = stats . get_partition_movement_stats ( ct , base_assignment ) print ( 'Total partition movements: {movement_count}\n' 'Total partition movement size: {movement_size}\n' 'Total leader changes: {leader_changes}' . format ( movement_count = movement_count , movement_size = movement_size , leader_changes = leader_changes , ) ) | Display how the amount of movement between two assignments . |
13,712 | def display_assignment_changes ( plan_details , to_log = True ) : curr_plan_list , new_plan_list , total_changes = plan_details action_cnt = '\n[INFO] Total actions required {0}' . format ( total_changes ) _log_or_display ( to_log , action_cnt ) action_cnt = ( '[INFO] Total actions that will be executed {0}' . format ( len ( new_plan_list ) ) ) _log_or_display ( to_log , action_cnt ) changes = ( '[INFO] Proposed Changes in current cluster-layout:\n' ) _log_or_display ( to_log , changes ) tp_str = 'Topic - Partition' curr_repl_str = 'Previous-Assignment' new_rep_str = 'Proposed-Assignment' tp_list = [ tp_repl [ 0 ] for tp_repl in curr_plan_list ] msg = '=' * 80 _log_or_display ( to_log , msg ) row = ( '{tp:^30s}: {curr_rep_str:^20s} ==> {new_rep_str:^20s}' . format ( tp = tp_str , curr_rep_str = curr_repl_str , new_rep_str = new_rep_str , ) ) _log_or_display ( to_log , row ) msg = '=' * 80 _log_or_display ( to_log , msg ) tp_list_sorted = sorted ( tp_list , key = lambda tp : ( tp [ 0 ] , tp [ 1 ] ) ) for tp in tp_list_sorted : curr_repl = [ tp_repl [ 1 ] for tp_repl in curr_plan_list if tp_repl [ 0 ] == tp ] [ 0 ] proposed_repl = [ tp_repl [ 1 ] for tp_repl in new_plan_list if tp_repl [ 0 ] == tp ] [ 0 ] tp_str = '{topic} - {partition:<2d}' . format ( topic = tp [ 0 ] , partition = tp [ 1 ] ) row = ( '{tp:<30s}: {curr_repl:<20s} ==> {proposed_repl:<20s}' . format ( tp = tp_str , curr_repl = curr_repl , proposed_repl = proposed_repl , ) ) _log_or_display ( to_log , row ) | Display current and proposed changes in topic - partition to replica layout over brokers . |
13,713 | def get_net_imbalance ( count_per_broker ) : net_imbalance = 0 opt_count , extra_allowed = compute_optimum ( len ( count_per_broker ) , sum ( count_per_broker ) ) for count in count_per_broker : extra_cnt , extra_allowed = get_extra_element_count ( count , opt_count , extra_allowed ) net_imbalance += extra_cnt return net_imbalance | Calculate and return net imbalance based on given count of partitions or leaders per broker . |
13,714 | def get_extra_element_count ( curr_count , opt_count , extra_allowed_cnt ) : if curr_count > opt_count : if extra_allowed_cnt > 0 : extra_allowed_cnt -= 1 extra_cnt = curr_count - opt_count - 1 else : extra_cnt = curr_count - opt_count else : extra_cnt = 0 return extra_cnt , extra_allowed_cnt | Evaluate and return extra same element count based on given values . |
13,715 | def get_replication_group_imbalance_stats ( rgs , partitions ) : tot_rgs = len ( rgs ) extra_replica_cnt_per_rg = defaultdict ( int ) for partition in partitions : opt_replica_cnt , extra_replicas_allowed = compute_optimum ( tot_rgs , partition . replication_factor ) for rg in rgs : replica_cnt_rg = rg . count_replica ( partition ) extra_replica_cnt , extra_replicas_allowed = get_extra_element_count ( replica_cnt_rg , opt_replica_cnt , extra_replicas_allowed , ) extra_replica_cnt_per_rg [ rg . id ] += extra_replica_cnt net_imbalance = sum ( extra_replica_cnt_per_rg . values ( ) ) return net_imbalance , extra_replica_cnt_per_rg | Calculate extra replica count replica count over each replication - group and net extra - same - replica count . |
13,716 | def get_topic_imbalance_stats ( brokers , topics ) : extra_partition_cnt_per_broker = defaultdict ( int ) tot_brokers = len ( brokers ) sorted_brokers = sorted ( brokers , key = lambda b : b . id ) for topic in topics : total_partition_replicas = len ( topic . partitions ) * topic . replication_factor opt_partition_cnt , extra_partitions_allowed = compute_optimum ( tot_brokers , total_partition_replicas ) for broker in sorted_brokers : partition_cnt_broker = broker . count_partitions ( topic ) extra_partitions , extra_partitions_allowed = get_extra_element_count ( partition_cnt_broker , opt_partition_cnt , extra_partitions_allowed , ) extra_partition_cnt_per_broker [ broker . id ] += extra_partitions net_imbalance = sum ( six . itervalues ( extra_partition_cnt_per_broker ) ) return net_imbalance , extra_partition_cnt_per_broker | Return count of topics and partitions on each broker having multiple partitions of same topic . |
13,717 | def _read_generated_broker_id ( meta_properties_path ) : try : with open ( meta_properties_path , 'r' ) as f : broker_id = _parse_meta_properties_file ( f ) except IOError : raise IOError ( "Cannot open meta.properties file: {path}" . format ( path = meta_properties_path ) , ) except ValueError : raise ValueError ( "Broker id not valid" ) if broker_id is None : raise ValueError ( "Autogenerated broker id missing from data directory" ) return broker_id | reads broker_id from meta . properties file . |
13,718 | def get_broker_id ( data_path ) : META_FILE_PATH = "{data_path}/meta.properties" if not data_path : raise ValueError ( "You need to specify the data_path if broker_id == -1" ) meta_properties_path = META_FILE_PATH . format ( data_path = data_path ) return _read_generated_broker_id ( meta_properties_path ) | This function will look into the data folder to get the automatically created broker_id . |
13,719 | def merge_offsets_metadata ( topics , * offsets_responses ) : result = dict ( ) for topic in topics : partition_offsets = [ response [ topic ] for response in offsets_responses if topic in response ] result [ topic ] = merge_partition_offsets ( * partition_offsets ) return result | Merge the offset metadata dictionaries from multiple responses . |
13,720 | def merge_partition_offsets ( * partition_offsets ) : output = dict ( ) for partition_offset in partition_offsets : for partition , offset in six . iteritems ( partition_offset ) : prev_offset = output . get ( partition , 0 ) output [ partition ] = max ( prev_offset , offset ) return output | Merge the partition offsets of a single topic from multiple responses . |
13,721 | def rebalance_replicas ( self , max_movement_count = None , max_movement_size = None , ) : movement_count = 0 movement_size = 0 for partition in six . itervalues ( self . cluster_topology . partitions ) : count , size = self . _rebalance_partition_replicas ( partition , None if not max_movement_count else max_movement_count - movement_count , None if not max_movement_size else max_movement_size - movement_size , ) movement_count += count movement_size += size return movement_count , movement_size | Balance replicas across replication - groups . |
13,722 | def _rebalance_partition_replicas ( self , partition , max_movement_count = None , max_movement_size = None , ) : total = partition . replication_factor over_replicated_rgs , under_replicated_rgs = separate_groups ( list ( self . cluster_topology . rgs . values ( ) ) , lambda g : g . count_replica ( partition ) , total , ) movement_count = 0 movement_size = 0 while ( under_replicated_rgs and over_replicated_rgs ) and ( max_movement_size is None or movement_size + partition . size <= max_movement_size ) and ( max_movement_count is None or movement_count < max_movement_count ) : rg_source = self . _elect_source_replication_group ( over_replicated_rgs , partition , ) rg_destination = self . _elect_dest_replication_group ( rg_source . count_replica ( partition ) , under_replicated_rgs , partition , ) if rg_source and rg_destination : self . log . debug ( 'Moving partition {p_name} from replication-group ' '{rg_source} to replication-group {rg_dest}' . format ( p_name = partition . name , rg_source = rg_source . id , rg_dest = rg_destination . id , ) , ) rg_source . move_partition ( rg_destination , partition ) movement_count += 1 movement_size += partition . size else : break over_replicated_rgs , under_replicated_rgs = separate_groups ( list ( self . cluster_topology . rgs . values ( ) ) , lambda g : g . count_replica ( partition ) , total , ) return movement_count , movement_size | Rebalance replication groups for given partition . |
13,723 | def _elect_source_replication_group ( self , over_replicated_rgs , partition , ) : return max ( over_replicated_rgs , key = lambda rg : rg . count_replica ( partition ) , ) | Decide source replication - group based as group with highest replica count . |
13,724 | def _elect_dest_replication_group ( self , replica_count_source , under_replicated_rgs , partition , ) : min_replicated_rg = min ( under_replicated_rgs , key = lambda rg : rg . count_replica ( partition ) , ) if min_replicated_rg . count_replica ( partition ) < replica_count_source - 1 : return min_replicated_rg return None | Decide destination replication - group based on replica - count . |
13,725 | def parse_consumer_offsets ( cls , json_file ) : with open ( json_file , 'r' ) as consumer_offsets_json : try : parsed_offsets = { } parsed_offsets_data = json . load ( consumer_offsets_json ) parsed_offsets [ 'groupid' ] = parsed_offsets_data [ 'groupid' ] parsed_offsets [ 'offsets' ] = { } for topic , topic_data in six . iteritems ( parsed_offsets_data [ 'offsets' ] ) : parsed_offsets [ 'offsets' ] [ topic ] = { } for partition , offset in six . iteritems ( topic_data ) : parsed_offsets [ 'offsets' ] [ topic ] [ int ( partition ) ] = offset return parsed_offsets except ValueError : print ( "Error: Given consumer-data json data-file {file} could not be " "parsed" . format ( file = json_file ) , file = sys . stderr , ) raise | Parse current offsets from json - file . |
13,726 | def build_new_offsets ( cls , client , topics_offset_data , topic_partitions , current_offsets ) : new_offsets = defaultdict ( dict ) try : for topic , partitions in six . iteritems ( topic_partitions ) : valid_partitions = set ( ) for topic_partition_offsets in current_offsets [ topic ] : partition = topic_partition_offsets . partition valid_partitions . add ( partition ) if partition not in topic_partitions [ topic ] : continue lowmark = topic_partition_offsets . lowmark highmark = topic_partition_offsets . highmark new_offset = topics_offset_data [ topic ] [ partition ] if new_offset < 0 : print ( "Error: Given offset: {offset} is negative" . format ( offset = new_offset ) , file = sys . stderr , ) sys . exit ( 1 ) if new_offset < lowmark or new_offset > highmark : print ( "Warning: Given offset {offset} for topic-partition " "{topic}:{partition} is outside the range of lowmark " "{lowmark} and highmark {highmark}" . format ( offset = new_offset , topic = topic , partition = partition , lowmark = lowmark , highmark = highmark , ) ) new_offsets [ topic ] [ partition ] = new_offset if not set ( partitions ) . issubset ( valid_partitions ) : print ( "Error: Some invalid partitions {partitions} for topic " "{topic} found. Valid partition-list {valid_partitions}. " "Exiting..." . format ( partitions = ', ' . join ( [ str ( p ) for p in partitions ] ) , valid_partitions = ', ' . join ( [ str ( p ) for p in valid_partitions ] ) , topic = topic , ) , file = sys . stderr , ) sys . exit ( 1 ) except KeyError as ex : print ( "Error: Possible invalid topic or partition. Error msg: {ex}. " "Exiting..." . format ( ex = ex ) , ) sys . exit ( 1 ) return new_offsets | Build complete consumer offsets from parsed current consumer - offsets and lowmarks and highmarks from current - offsets for . |
13,727 | def restore_offsets ( cls , client , parsed_consumer_offsets ) : try : consumer_group = parsed_consumer_offsets [ 'groupid' ] topics_offset_data = parsed_consumer_offsets [ 'offsets' ] topic_partitions = dict ( ( topic , [ partition for partition in offset_data . keys ( ) ] ) for topic , offset_data in six . iteritems ( topics_offset_data ) ) except IndexError : print ( "Error: Given parsed consumer-offset data {consumer_offsets} " "could not be parsed" . format ( consumer_offsets = parsed_consumer_offsets ) , file = sys . stderr , ) raise current_offsets = get_consumer_offsets_metadata ( client , consumer_group , topic_partitions , ) new_offsets = cls . build_new_offsets ( client , topics_offset_data , topic_partitions , current_offsets , ) consumer_group = parsed_consumer_offsets [ 'groupid' ] set_consumer_offsets ( client , consumer_group , new_offsets ) print ( "Restored to new offsets {offsets}" . format ( offsets = dict ( new_offsets ) ) ) | Fetch current offsets from kafka validate them against given consumer - offsets data and commit the new offsets . |
13,728 | def tuple_replace ( tup , * pairs ) : tuple_list = list ( tup ) for index , value in pairs : tuple_list [ index ] = value return tuple ( tuple_list ) | Return a copy of a tuple with some elements replaced . |
13,729 | def tuple_alter ( tup , * pairs ) : tuple_list = list ( tup ) for i , f in pairs : tuple_list [ i ] = f ( tuple_list [ i ] ) return tuple ( tuple_list ) | Return a copy of a tuple with some elements altered . |
13,730 | def tuple_remove ( tup , * items ) : tuple_list = list ( tup ) for item in items : tuple_list . remove ( item ) return tuple ( tuple_list ) | Return a copy of a tuple with some items removed . |
13,731 | def positive_int ( string ) : error_msg = 'Positive integer required, {string} given.' . format ( string = string ) try : value = int ( string ) except ValueError : raise ArgumentTypeError ( error_msg ) if value < 0 : raise ArgumentTypeError ( error_msg ) return value | Convert string to positive integer . |
13,732 | def positive_nonzero_int ( string ) : error_msg = 'Positive non-zero integer required, {string} given.' . format ( string = string ) try : value = int ( string ) except ValueError : raise ArgumentTypeError ( error_msg ) if value <= 0 : raise ArgumentTypeError ( error_msg ) return value | Convert string to positive integer greater than zero . |
13,733 | def positive_float ( string ) : error_msg = 'Positive float required, {string} given.' . format ( string = string ) try : value = float ( string ) except ValueError : raise ArgumentTypeError ( error_msg ) if value < 0 : raise ArgumentTypeError ( error_msg ) return value | Convert string to positive float . |
13,734 | def dict_merge ( set1 , set2 ) : return dict ( list ( set1 . items ( ) ) + list ( set2 . items ( ) ) ) | Joins two dictionaries . |
13,735 | def to_h ( num , suffix = 'B' ) : if num is None : 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 ) | Converts a byte value in human readable form . |
13,736 | def format_to_json ( data ) : if sys . stdout . isatty ( ) : return json . dumps ( data , indent = 4 , separators = ( ',' , ': ' ) ) else : return json . dumps ( data ) | Converts data into json If stdout is a tty it performs a pretty print . |
13,737 | def _build_brokers ( self , brokers ) : for broker_id , metadata in six . iteritems ( brokers ) : self . brokers [ broker_id ] = self . _create_broker ( broker_id , metadata ) | Build broker objects using broker - ids . |
13,738 | def _create_broker ( self , broker_id , metadata = None ) : 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 | 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 . |
13,739 | def _build_partitions ( self , assignment ) : self . partitions = { } for partition_name , replica_ids in six . iteritems ( assignment ) : topic_id = partition_name [ 0 ] partition_id = partition_name [ 1 ] topic = self . topics . setdefault ( topic_id , Topic ( topic_id , replication_factor = len ( replica_ids ) ) ) partition = Partition ( topic , partition_id , weight = self . partition_measurer . get_weight ( partition_name ) , size = self . partition_measurer . get_size ( partition_name ) , ) self . partitions [ partition_name ] = partition topic . add_partition ( partition ) for broker_id in replica_ids : if broker_id not in list ( self . brokers . keys ( ) ) : self . log . warning ( "Broker %s containing partition %s is not in " "active brokers." , broker_id , partition , ) self . brokers [ broker_id ] = self . _create_broker ( broker_id ) self . brokers [ broker_id ] . add_partition ( partition ) | Builds all partition objects and update corresponding broker and topic objects . |
13,740 | def active_brokers ( self ) : return { broker for broker in six . itervalues ( self . brokers ) if not broker . inactive and not broker . decommissioned } | Set of brokers that are not inactive or decommissioned . |
13,741 | def replace_broker ( self , source_id , dest_id ) : try : source = self . brokers [ source_id ] dest = self . brokers [ dest_id ] for partition in source . partitions . copy ( ) : source . partitions . remove ( partition ) dest . partitions . add ( partition ) partition . replace ( source , dest ) except KeyError as e : self . log . error ( "Invalid broker id %s." , e . args [ 0 ] ) raise InvalidBrokerIdError ( "Broker id {} does not exist in cluster" . format ( e . args [ 0 ] ) ) | Move all partitions in source broker to destination broker . |
13,742 | def update_cluster_topology ( self , assignment ) : 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-partition %s-%s." , ', ' . join ( [ str ( id ) for id in replica_ids ] ) , partition_name [ 0 ] , partition_name [ 1 ] , ) raise InvalidBrokerIdError ( "Invalid replicas {0}." . format ( ', ' . join ( [ str ( id ) for id in replica_ids ] ) ) , ) try : partition = self . partitions [ partition_name ] old_replicas = [ broker for broker in partition . replicas ] if new_replicas == old_replicas : continue for broker in old_replicas : broker . remove_partition ( partition ) for broker in new_replicas : broker . add_partition ( partition ) except KeyError : self . log . error ( "Invalid topic-partition %s-%s." , partition_name [ 0 ] , partition_name [ 1 ] , ) raise InvalidPartitionError ( "Invalid topic-partition {0}-{1}." . format ( partition_name [ 0 ] , partition_name [ 1 ] ) , ) except KeyError : self . log . error ( "Could not parse given assignment {0}" . format ( assignment ) ) raise | Modify the cluster - topology with given assignment . |
13,743 | def plan_to_assignment ( plan ) : assignment = { } for elem in plan [ 'partitions' ] : assignment [ ( elem [ 'topic' ] , elem [ 'partition' ] ) ] = elem [ 'replicas' ] return assignment | Convert the plan to the format used by cluster - topology . |
13,744 | def assignment_to_plan ( assignment ) : return { 'version' : 1 , 'partitions' : [ { 'topic' : t_p [ 0 ] , 'partition' : t_p [ 1 ] , 'replicas' : replica } for t_p , replica in six . iteritems ( assignment ) ] } | Convert an assignment to the format used by Kafka to describe a reassignment plan . |
13,745 | def validate_plan ( new_plan , base_plan = None , is_partition_subset = True , allow_rf_change = False , ) : if not _validate_plan ( new_plan ) : _log . error ( 'Invalid proposed-plan.' ) return False if base_plan : if not _validate_plan ( base_plan ) : _log . error ( 'Invalid assignment from cluster.' ) return False if not _validate_plan_base ( new_plan , base_plan , is_partition_subset , allow_rf_change ) : return False return True | Verify that the new plan is valid for execution . |
13,746 | def _validate_plan_base ( new_plan , base_plan , is_partition_subset = True , allow_rf_change = False , ) : 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' ] ] ) if is_partition_subset : invalid_partitions = list ( new_partitions - base_partitions ) else : invalid_partitions = list ( new_partitions . union ( base_partitions ) - new_partitions . intersection ( base_partitions ) , ) if invalid_partitions : _log . error ( 'Invalid partition(s) found: {p_list}' . format ( p_list = invalid_partitions , ) ) return False base_partition_replicas = { ( p_data [ 'topic' ] , p_data [ 'partition' ] ) : p_data [ 'replicas' ] for p_data in base_plan [ 'partitions' ] } new_partition_replicas = { ( p_data [ 'topic' ] , p_data [ 'partition' ] ) : p_data [ 'replicas' ] for p_data in new_plan [ 'partitions' ] } if not allow_rf_change : invalid_replication_factor = False for new_partition , replicas in six . iteritems ( new_partition_replicas ) : base_replica_cnt = len ( base_partition_replicas [ new_partition ] ) if len ( replicas ) != base_replica_cnt : invalid_replication_factor = True _log . error ( 'Replication-factor Mismatch: Partition: {partition}: ' 'Base-replicas: {expected}, Proposed-replicas: {actual}' . format ( partition = new_partition , expected = base_partition_replicas [ new_partition ] , actual = replicas , ) , ) if invalid_replication_factor : return False return True | Validate if given plan is valid comparing with given base - plan . |
13,747 | def _validate_format ( plan ) : 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 ( ) ) ) ) , ) return False if plan [ 'version' ] != 1 : _log . error ( 'Invalid version of plan {version}' . format ( version = plan [ 'version' ] ) , ) return False if not plan [ 'partitions' ] : _log . error ( '"partitions" list found empty"' . format ( version = plan [ 'partitions' ] ) , ) return False if not isinstance ( plan [ 'partitions' ] , list ) : _log . error ( '"partitions" of type list expected.' ) return False for p_data in plan [ 'partitions' ] : if set ( p_data . keys ( ) ) != set ( [ 'topic' , 'partition' , 'replicas' ] ) : _log . error ( 'Invalid keys in partition-data {keys}' . format ( keys = ', ' . join ( list ( p_data . keys ( ) ) ) ) , ) return False if not isinstance ( p_data [ 'topic' ] , six . text_type ) : _log . error ( '"topic" of type unicode expected {p_data}, found {t_type}' . format ( p_data = p_data , t_type = type ( p_data [ 'topic' ] ) ) , ) return False if not isinstance ( p_data [ 'partition' ] , int ) : _log . error ( '"partition" of type int expected {p_data}, found {p_type}' . format ( p_data = p_data , p_type = type ( p_data [ 'partition' ] ) ) , ) return False if not isinstance ( p_data [ 'replicas' ] , list ) : _log . error ( '"replicas" of type list expected {p_data}, found {r_type}' . format ( p_data = p_data , r_type = type ( p_data [ 'replicas' ] ) ) , ) return False if not p_data [ 'replicas' ] : _log . error ( 'Non-empty "replicas" expected: {p_data}' . format ( p_data = p_data ) , ) return False for broker in p_data [ 'replicas' ] : if not isinstance ( broker , int ) : _log . error ( '"replicas" of type integer list expected {p_data}' . format ( p_data = p_data ) , ) return False return True | Validate if the format of the plan as expected . |
13,748 | def _validate_plan ( plan ) : if not _validate_format ( plan ) : return False partition_names = [ ( p_data [ 'topic' ] , p_data [ 'partition' ] ) for p_data in plan [ 'partitions' ] ] duplicate_partitions = [ partition for partition , count in six . iteritems ( Counter ( partition_names ) ) if count > 1 ] if duplicate_partitions : _log . error ( 'Duplicate partitions in plan {p_list}' . format ( p_list = duplicate_partitions ) , ) return False dup_replica_brokers = [ ] for p_data in plan [ 'partitions' ] : dup_replica_brokers = [ broker for broker , count in Counter ( p_data [ 'replicas' ] ) . items ( ) if count > 1 ] if dup_replica_brokers : _log . error ( 'Duplicate brokers: ({topic}, {p_id}) in replicas {replicas}' . format ( topic = p_data [ 'topic' ] , p_id = p_data [ 'partition' ] , replicas = p_data [ 'replicas' ] , ) ) return False topic_replication_factor = { } for partition_info in plan [ 'partitions' ] : topic = partition_info [ 'topic' ] replication_factor = len ( partition_info [ 'replicas' ] ) if topic in list ( topic_replication_factor . keys ( ) ) : if topic_replication_factor [ topic ] != replication_factor : _log . error ( 'Mismatch in replication-factor of partitions for topic ' '{topic}' . format ( topic = topic ) , ) return False else : topic_replication_factor [ topic ] = replication_factor return True | Validate if given plan is valid based on kafka - cluster - assignment protocols . |
13,749 | def percentage_distance ( cls , highmark , current ) : highmark = int ( highmark ) current = int ( current ) if highmark > 0 : return round ( ( highmark - current ) * 100.0 / highmark , 2 , ) else : return 0.0 | Percentage of distance the current offset is behind the highmark . |
13,750 | def get_children ( self , path , watch = None ) : _log . debug ( "ZK: Getting children of {path}" . format ( path = path ) , ) return self . zk . get_children ( path , watch ) | Returns the children of the specified node . |
13,751 | def get ( self , path , watch = None ) : _log . debug ( "ZK: Getting {path}" . format ( path = path ) , ) return self . zk . get ( path , watch ) | Returns the data of the specified node . |
13,752 | def set ( self , path , value ) : _log . debug ( "ZK: Setting {path} to {value}" . format ( path = path , value = value ) ) return self . zk . set ( path , value ) | Sets and returns new data for the specified node . |
13,753 | def get_json ( self , path , watch = None ) : data , _ = self . get ( path , watch ) return load_json ( data ) if data else None | Reads the data of the specified node and converts it to json . |
13,754 | def get_brokers ( self , names_only = False ) : try : broker_ids = self . get_children ( "/brokers/ids" ) except NoNodeError : _log . info ( "cluster is empty." ) return { } if names_only : return { int ( b_id ) : None for b_id in broker_ids } return { int ( b_id ) : self . get_broker_metadata ( b_id ) for b_id in broker_ids } | Get information on all the available brokers . |
13,755 | def get_topic_config ( self , topic ) : try : config_data = load_json ( self . get ( "/config/topics/{topic}" . format ( topic = topic ) ) [ 0 ] ) except NoNodeError as e : topics = self . get_topics ( topic_name = topic , fetch_partition_state = False ) if len ( topics ) > 0 : _log . info ( "Configuration not available for topic {topic}." . format ( topic = topic ) ) config_data = { "config" : { } } else : _log . error ( "topic {topic} not found." . format ( topic = topic ) ) raise e return config_data | Get configuration information for specified topic . |
13,756 | def set_topic_config ( self , topic , value , kafka_version = ( 0 , 10 , ) ) : config_data = dump_json ( value ) try : return_value = self . set ( "/config/topics/{topic}" . format ( topic = topic ) , config_data ) version = kafka_version [ 1 ] assert version in ( 9 , 10 ) , "Feature supported with kafka 9 and kafka 10" if version == 9 : change_node = dump_json ( { "version" : 1 , "entity_type" : "topics" , "entity_name" : topic } ) else : change_node = dump_json ( { "version" : 2 , "entity_path" : "topics/" + topic , } ) self . create ( '/config/changes/config_change_' , change_node , sequence = True ) except NoNodeError as e : _log . error ( "topic {topic} not found." . format ( topic = topic ) ) raise e return return_value | Set configuration information for specified topic . |
13,757 | def get_topics ( self , topic_name = None , names_only = False , fetch_partition_state = True , ) : 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_ids topics_data = { } for topic_id in topic_ids : try : topic_info = self . get ( "/brokers/topics/{id}" . format ( id = topic_id ) ) topic_data = load_json ( topic_info [ 0 ] ) topic_ctime = topic_info [ 1 ] . ctime / 1000.0 topic_data [ 'ctime' ] = topic_ctime except NoNodeError : _log . info ( "topic '{topic}' not found." . format ( topic = topic_id ) , ) return { } partitions_data = { } for p_id , replicas in six . iteritems ( topic_data [ 'partitions' ] ) : partitions_data [ p_id ] = { } if fetch_partition_state : partition_state = self . _fetch_partition_state ( topic_id , p_id ) partitions_data [ p_id ] = load_json ( partition_state [ 0 ] ) partitions_data [ p_id ] [ 'ctime' ] = partition_state [ 1 ] . ctime / 1000.0 else : partition_info = self . _fetch_partition_info ( topic_id , p_id ) partitions_data [ p_id ] [ 'ctime' ] = partition_info . ctime / 1000.0 partitions_data [ p_id ] [ 'replicas' ] = replicas topic_data [ 'partitions' ] = partitions_data topics_data [ topic_id ] = topic_data return topics_data | Get information on all the available topics . |
13,758 | def get_consumer_groups ( self , consumer_group_id = None , names_only = False ) : if consumer_group_id is None : group_ids = self . get_children ( "/consumers" ) else : group_ids = [ consumer_group_id ] if names_only : return { g_id : None for g_id in group_ids } consumer_offsets = { } for g_id in group_ids : consumer_offsets [ g_id ] = self . get_group_offsets ( g_id ) return consumer_offsets | Get information on all the available consumer - groups . |
13,759 | def get_group_offsets ( self , group , topic = None ) : group_offsets = { } try : all_topics = self . get_my_subscribed_topics ( group ) except NoNodeError : _log . warning ( "No topics subscribed to consumer-group {group}." . format ( group = group , ) , ) return group_offsets if topic : if topic in all_topics : topics = [ topic ] else : _log . error ( "Topic {topic} not found in topic list {topics} for consumer" "-group {consumer_group}." . format ( topic = topic , topics = ', ' . join ( topic for topic in all_topics ) , consumer_group = group , ) , ) return group_offsets else : topics = all_topics for topic in topics : group_offsets [ topic ] = { } try : partitions = self . get_my_subscribed_partitions ( group , topic ) except NoNodeError : _log . warning ( "No partition offsets found for topic {topic}. " "Continuing to next one..." . format ( topic = topic ) , ) continue for partition in partitions : path = "/consumers/{group_id}/offsets/{topic}/{partition}" . format ( group_id = group , topic = topic , partition = partition , ) try : offset_json , _ = self . get ( path ) group_offsets [ topic ] [ partition ] = load_json ( offset_json ) except NoNodeError : _log . error ( "Path {path} not found" . format ( path = path ) ) raise return group_offsets | Fetch group offsets for given topic and partition otherwise all topics and partitions otherwise . |
13,760 | def _fetch_partition_state ( self , topic_id , partition_id ) : 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 { } | Fetch partition - state for given topic - partition . |
13,761 | def _fetch_partition_info ( self , topic_id , partition_id ) : 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 { } | Fetch partition info for given topic - partition . |
13,762 | def get_my_subscribed_topics ( self , groupid ) : path = "/consumers/{group_id}/offsets" . format ( group_id = groupid ) return self . get_children ( path ) | Get the list of topics that a consumer is subscribed to |
13,763 | def get_my_subscribed_partitions ( self , groupid , topic ) : path = "/consumers/{group_id}/offsets/{topic}" . format ( group_id = groupid , topic = topic , ) return self . get_children ( path ) | Get the list of partitions of a topic that a consumer is subscribed to |
13,764 | def get_cluster_assignment ( self ) : plan = self . get_cluster_plan ( ) assignment = { } for elem in plan [ 'partitions' ] : assignment [ ( elem [ 'topic' ] , elem [ 'partition' ] ) ] = elem [ 'replicas' ] return assignment | Fetch the cluster layout in form of assignment from zookeeper |
13,765 | def create ( self , path , value = '' , acl = None , ephemeral = False , sequence = False , makepath = False ) : _log . debug ( "ZK: Creating node " + path ) return self . zk . create ( path , value , acl , ephemeral , sequence , makepath ) | Creates a Zookeeper node . |
13,766 | def delete ( self , path , recursive = False ) : _log . debug ( "ZK: Deleting node " + path ) return self . zk . delete ( path , recursive = recursive ) | Deletes a Zookeeper node . |
13,767 | def execute_plan ( self , plan , allow_rf_change = False ) : 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 . error ( 'Given plan is invalid. Aborting new reassignment plan ... {plan}' . format ( plan = plan ) ) return False try : _log . info ( 'Sending plan to Zookeeper...' ) self . create ( reassignment_path , plan_json , makepath = True ) _log . info ( 'Re-assign partitions node in Zookeeper updated successfully ' 'with {plan}' . format ( plan = plan ) , ) return True except NodeExistsError : _log . warning ( 'Previous plan in progress. Exiting..' ) _log . warning ( 'Aborting new reassignment plan... {plan}' . format ( plan = plan ) ) in_progress_plan = load_json ( self . get ( reassignment_path ) [ 0 ] ) in_progress_partitions = [ '{topic}-{p_id}' . format ( topic = p_data [ 'topic' ] , p_id = str ( p_data [ 'partition' ] ) , ) for p_data in in_progress_plan [ 'partitions' ] ] _log . warning ( '{count} partition(s) reassignment currently in progress:-' . format ( count = len ( in_progress_partitions ) ) , ) _log . warning ( '{partitions}. In Progress reassignment plan...' . format ( partitions = ', ' . join ( in_progress_partitions ) , ) , ) return False except Exception as e : _log . error ( 'Could not re-assign partitions {plan}. Error: {e}' . format ( plan = plan , e = e ) , ) return False | Submit reassignment plan for execution . |
13,768 | def get_cluster_plan ( self ) : _log . info ( 'Fetching current cluster-topology from Zookeeper...' ) cluster_layout = self . get_topics ( fetch_partition_state = False ) partitions = [ { 'topic' : topic_id , 'partition' : int ( p_id ) , 'replicas' : partitions_data [ 'replicas' ] } for topic_id , topic_info in six . iteritems ( cluster_layout ) for p_id , partitions_data in six . iteritems ( topic_info [ 'partitions' ] ) ] return { 'version' : 1 , 'partitions' : partitions } | Fetch cluster plan from zookeeper . |
13,769 | def get_pending_plan ( self ) : 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 { } | Read the currently running plan on reassign_partitions node . |
13,770 | def run_command ( self ) : 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 | Checks the number of offline partitions |
13,771 | def get_kafka_groups ( cls , cluster_config ) : kafka_group_reader = KafkaGroupReader ( cluster_config ) return list ( kafka_group_reader . read_groups ( ) . keys ( ) ) | Get the group_id of groups committed into Kafka . |
13,772 | def report_stdout ( host , stdout ) : lines = stdout . readlines ( ) if lines : print ( "STDOUT from {host}:" . format ( host = host ) ) for line in lines : print ( line . rstrip ( ) , file = sys . stdout ) | Take a stdout and print it s lines to output if lines are present . |
13,773 | def report_stderr ( host , stderr ) : lines = stderr . readlines ( ) if lines : print ( "STDERR from {host}:" . format ( host = host ) ) for line in lines : print ( line . rstrip ( ) , file = sys . stderr ) | Take a stderr and print it s lines to output if lines are present . |
13,774 | def save_offsets ( cls , consumer_offsets_metadata , topics_dict , json_file , groupid , ) : 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 ] = partition_offset . current consumer_offsets_data = { 'groupid' : groupid , 'offsets' : current_consumer_offsets } cls . write_offsets_to_file ( json_file , consumer_offsets_data ) | Built offsets for given topic - partitions in required format from current offsets metadata and write to given json - file . |
13,775 | def write_offsets_to_file ( cls , json_file_name , consumer_offsets_data ) : 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 ) ) raise print ( "Consumer offset data saved in json-file {file}" . format ( file = json_file_name ) ) | Save built consumer - offsets data to given json file . |
13,776 | def decommission_brokers ( self , broker_ids ) : 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 InvalidBrokerIdError ( "Broker id {} does not exist in cluster" . format ( b_id ) , ) broker . mark_decommissioned ( ) groups . add ( broker . replication_group ) for group in groups : self . _decommission_brokers_in_group ( group ) | Decommission a list of brokers trying to keep the replication group the brokers belong to balanced . |
13,777 | def _decommission_brokers_in_group ( self , group ) : 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 ( ) : self . log . info ( "Broker %s can't be decommissioned within the same " "replication group %s. Moving partitions to other " "replication groups." , broker , broker . replication_group , ) self . _force_broker_decommission ( broker ) if not broker . empty ( ) : self . log . error ( "Could not decommission broker %s. " "Partitions %s cannot be reassigned." , broker , broker . partitions , ) raise BrokerDecommissionError ( "Broker decommission failed." ) | Decommission the marked brokers of a group . |
13,778 | def rebalance_replication_groups ( self ) : 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." ) raise RebalanceError ( "Impossible to rebalance replication groups because of inactive " "brokers" ) self . rebalance_replicas ( ) self . _rebalance_groups_partition_cnt ( ) | Rebalance partitions over replication groups . |
13,779 | def rebalance_brokers ( self ) : for rg in six . itervalues ( self . cluster_topology . rgs ) : rg . rebalance_brokers ( ) | Rebalance partition - count across brokers within each replication - group . |
13,780 | def revoke_leadership ( self , broker_ids ) : 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" . format ( b_id ) , ) broker . mark_revoked_leadership ( ) assert ( len ( self . cluster_topology . brokers ) - len ( broker_ids ) > 0 ) , "Not " "all brokers can be revoked for leadership" opt_leader_cnt = len ( self . cluster_topology . partitions ) // ( len ( self . cluster_topology . brokers ) - len ( broker_ids ) ) self . rebalancing_non_followers ( opt_leader_cnt ) pending_brokers = [ b for b in six . itervalues ( self . cluster_topology . brokers ) if b . revoked_leadership and b . count_preferred_replica ( ) > 0 ] for b in pending_brokers : self . _force_revoke_leadership ( b ) | Revoke leadership for given brokers . |
13,781 | def _force_revoke_leadership ( self , broker ) : 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} for partition {p}. Replica count: 1" . format ( p = partition , b = broker ) , ) continue eligible_followers = [ follower for follower in partition . followers if not follower . revoked_leadership ] if eligible_followers : best_fit_follower = min ( eligible_followers , key = lambda follower : follower . count_preferred_replica ( ) , ) partition . swap_leader ( best_fit_follower ) else : self . log . error ( "All replicas for partition {p} on broker {b} are to be revoked for leadership." . format ( p = partition , b = broker , ) ) | Revoke the leadership of given broker for any remaining partitions . |
13,782 | def rebalance_leaders ( self ) : opt_leader_cnt = len ( self . cluster_topology . partitions ) // len ( self . cluster_topology . brokers ) self . rebalancing_non_followers ( opt_leader_cnt ) | Re - order brokers in replicas such that every broker is assigned as preferred leader evenly . |
13,783 | def _rebalance_groups_partition_cnt ( self ) : 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 . partitions ) , total_elements , ) if over_loaded_rgs and under_loaded_rgs : self . cluster_topology . log . info ( 'Over-loaded replication-groups {over_loaded}, under-loaded ' 'replication-groups {under_loaded} based on partition-count' . format ( over_loaded = [ rg . id for rg in over_loaded_rgs ] , under_loaded = [ rg . id for rg in under_loaded_rgs ] , ) ) else : self . cluster_topology . log . info ( 'Replication-groups are balanced based on partition-count.' ) return opt_partition_cnt , _ = compute_optimum ( len ( self . cluster_topology . rgs ) , total_elements , ) for over_loaded_rg in over_loaded_rgs : for under_loaded_rg in under_loaded_rgs : eligible_partitions = set ( filter ( lambda partition : over_loaded_rg . count_replica ( partition ) > len ( partition . replicas ) // len ( self . cluster_topology . rgs ) and under_loaded_rg . count_replica ( partition ) <= len ( partition . replicas ) // len ( self . cluster_topology . rgs ) , over_loaded_rg . partitions , ) ) for eligible_partition in eligible_partitions : if len ( over_loaded_rg . partitions ) - len ( under_loaded_rg . partitions ) > 1 : over_loaded_rg . move_partition_replica ( under_loaded_rg , eligible_partition , ) else : break if ( len ( under_loaded_rg . partitions ) == opt_partition_cnt or len ( over_loaded_rg . partitions ) == opt_partition_cnt ) : break if len ( over_loaded_rg . partitions ) == opt_partition_cnt : break | Re - balance partition - count across replication - groups . |
13,784 | def add_replica ( self , partition_name , count = 1 ) : 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_topology . brokers ) : raise InvalidReplicationFactorError ( "Cannot increase replication factor to {0}. There are only " "{1} brokers." . format ( partition . replication_factor + count , len ( self . cluster_topology . brokers ) , ) ) non_full_rgs = [ rg for rg in self . cluster_topology . rgs . values ( ) if rg . count_replica ( partition ) < len ( rg . brokers ) ] for _ in range ( count ) : total_replicas = sum ( rg . count_replica ( partition ) for rg in non_full_rgs ) opt_replicas , _ = compute_optimum ( len ( non_full_rgs ) , total_replicas , ) under_replicated_rgs = [ rg for rg in non_full_rgs if rg . count_replica ( partition ) < opt_replicas ] candidate_rgs = under_replicated_rgs or non_full_rgs rg = min ( candidate_rgs , key = lambda rg : len ( rg . partitions ) ) rg . add_replica ( partition ) if rg . count_replica ( partition ) >= len ( rg . brokers ) : non_full_rgs . remove ( rg ) | Increase the replication - factor for a partition . |
13,785 | def remove_replica ( self , partition_name , osr_broker_ids , count = 1 ) : 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 : raise InvalidReplicationFactorError ( "Cannot remove {0} replicas. Replication factor is only {1}." . format ( count , partition . replication_factor ) ) osr = [ ] for broker_id in osr_broker_ids : try : osr . append ( self . cluster_topology . brokers [ broker_id ] ) except KeyError : raise InvalidBrokerIdError ( "No broker found with id {bid}" . format ( bid = broker_id ) , ) non_empty_rgs = [ rg for rg in self . cluster_topology . rgs . values ( ) if rg . count_replica ( partition ) > 0 ] rgs_with_osr = [ rg for rg in non_empty_rgs if any ( b in osr for b in rg . brokers ) ] for _ in range ( count ) : candidate_rgs = rgs_with_osr or non_empty_rgs total_replicas = sum ( rg . count_replica ( partition ) for rg in candidate_rgs ) opt_replica_cnt , _ = compute_optimum ( len ( candidate_rgs ) , total_replicas , ) over_replicated_rgs = [ rg for rg in candidate_rgs if rg . count_replica ( partition ) > opt_replica_cnt ] candidate_rgs = over_replicated_rgs or candidate_rgs rg = max ( candidate_rgs , key = lambda rg : len ( rg . partitions ) ) osr_in_rg = [ b for b in rg . brokers if b in osr ] rg . remove_replica ( partition , osr_in_rg ) osr = [ b for b in osr if b in partition . replicas ] if rg in rgs_with_osr and len ( osr_in_rg ) == 1 : rgs_with_osr . remove ( rg ) if rg . count_replica ( partition ) == 0 : non_empty_rgs . remove ( rg ) new_leader = min ( partition . replicas , key = lambda broker : broker . count_preferred_replica ( ) , ) partition . swap_leader ( new_leader ) | Remove one replica of a partition from the cluster . |
13,786 | def preprocess_topics ( source_groupid , source_topics , dest_groupid , topics_dest_group ) : 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 delete this " "topics from new group before re-running the " "command." . format ( groupid = dest_groupid , topic = ', ' . join ( common_topics ) , ) , file = sys . stderr , ) sys . exit ( 1 ) if topics_dest_group : in_str = ( "New Consumer Group: {dest_groupid} already " "exists.\nTopics subscribed to by the consumer groups are listed " "below:\n{source_groupid}: {source_group_topics}\n" "{dest_groupid}: {dest_group_topics}\nDo you intend to copy into" "existing consumer destination-group? (y/n)" . format ( source_groupid = source_groupid , source_group_topics = source_topics , dest_groupid = dest_groupid , dest_group_topics = topics_dest_group , ) ) prompt_user_input ( in_str ) | Pre - process the topics in source and destination group for duplicates . |
13,787 | def create_offsets ( zk , consumer_group , 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 , partition = partition , ) try : zk . create ( new_path , value = offset , makepath = True ) except NodeExistsError : print ( "Error: Path {path} already exists. Please re-run the " "command." . format ( path = new_path ) , file = sys . stderr , ) raise | Create path with offset value for each topic - partition of given consumer group . |
13,788 | def fetch_offsets ( zk , consumer_group , topics ) : 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 , partition = partition , ) ) source_offsets [ topic ] [ partition ] = offset return source_offsets | Fetch offsets for given topics of given consumer group . |
13,789 | def get_offset_topic_partition_count ( kafka_config ) : 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 ] ) | 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 . |
13,790 | def get_group_partition ( group , partition_count ) : 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 | Given a group name return the partition number of the consumer offset topic containing the data associated to that group . |
13,791 | def topic_offsets_for_timestamp ( consumer , timestamp , topics ) : 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 ) | 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 . |
13,792 | def consumer_partitions_for_topic ( consumer , topic ) : 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 exist?" . format ( topic ) , ) return topic_partitions | Returns a list of all TopicPartitions for a given topic . |
13,793 | def consumer_commit_for_times ( consumer , partition_to_offset , atomic = False ) : 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 there is no" " data in the topic-partition." . format ( tp = tp ) , ) no_offsets . add ( tp ) if atomic and len ( no_offsets ) > 0 : logging . error ( "Commit aborted; offsets were not found for timestamps in" " topics {}" . format ( "," . join ( [ str ( tp ) for tp in no_offsets ] ) ) , ) return offsets_metadata = { tp : OffsetAndMetadata ( partition_to_offset [ tp ] . offset , metadata = None ) for tp in six . iterkeys ( partition_to_offset ) if tp not in no_offsets } if len ( offsets_metadata ) != 0 : consumer . commit ( offsets_metadata ) | Commits offsets to Kafka using the given KafkaConsumer and offsets a mapping of TopicPartition to Unix Epoch milliseconds timestamps . |
13,794 | def get_cluster_config ( cluster_type , cluster_name = None , kafka_topology_base_path = None , ) : 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 , ) except MissingConfigurationError : pass if not topology : raise MissingConfigurationError ( "No available configuration for type {0}" . format ( cluster_type ) , ) if cluster_name : return topology . get_cluster_by_name ( cluster_name ) else : return topology . get_local_cluster ( ) | Return the cluster configuration . Use the local cluster if cluster_name is not specified . |
13,795 | def iter_configurations ( kafka_topology_base_path = None ) : 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 ( config_dir ) ) , ) if x not in types ] for cluster_type in new_types : try : topology = TopologyConfiguration ( cluster_type , config_dir , ) except ConfigurationError : continue types . add ( cluster_type ) yield topology | Cluster topology iterator . Iterate over all the topologies available in config . |
13,796 | def load_topology_config ( self ) : 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 ) else : raise MissingConfigurationError ( "Topology configuration {0} for cluster {1} " "does not exist" . format ( config_path , self . cluster_type , ) ) self . log . debug ( "Topology configuration %s" , topology_config ) try : self . clusters = topology_config [ 'clusters' ] except KeyError : self . log . exception ( "Invalid topology file" ) raise InvalidConfigurationError ( "Invalid topology file {0}" . format ( config_path ) ) if 'local_config' in topology_config : self . local_config = topology_config [ 'local_config' ] | Load the topology configuration |
13,797 | def convert_to_broker_id ( string ) : 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 | Convert string to kafka broker_id . |
13,798 | def run ( ) : args = parse_args ( ) logging . basicConfig ( level = logging . WARN ) logging . getLogger ( 'kafka' ) . setLevel ( logging . CRITICAL ) if args . controller_only and args . first_broker_only : terminate ( status_code . WARNING , prepare_terminate_message ( "Only one of controller_only and first_broker_only should be used" , ) , args . json , ) if args . controller_only or args . first_broker_only : if args . broker_id is None : terminate ( status_code . WARNING , prepare_terminate_message ( "broker_id is not specified" ) , args . json , ) elif args . broker_id == - 1 : try : args . broker_id = get_broker_id ( args . data_path ) except Exception as e : terminate ( status_code . WARNING , prepare_terminate_message ( "{}" . format ( e ) ) , args . json , ) try : cluster_config = config . get_cluster_config ( args . cluster_type , args . cluster_name , args . discovery_base_path , ) code , msg = args . command ( cluster_config , args ) except ConfigurationError as e : terminate ( status_code . CRITICAL , prepare_terminate_message ( "ConfigurationError {0}" . format ( e ) ) , args . json , ) terminate ( code , msg , args . json ) | Verify command - line arguments and run commands |
13,799 | def exception_logger ( exc_type , exc_value , exc_traceback ) : if not issubclass ( exc_type , KeyboardInterrupt ) : _log . critical ( "Uncaught exception:" , exc_info = ( exc_type , exc_value , exc_traceback ) ) sys . __excepthook__ ( exc_type , exc_value , exc_traceback ) | Log unhandled exceptions |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.