o
    `j<                     @  s   d Z ddlmZ ddlmZ ddlmZ ddlZddlm	Z	 ddl
Z
ddlmZ ddlmZ ddlmZmZ dd	lmZmZmZmZmZ dd
lmZ ddlmZ e	rXddlmZ ee Z!G dd dZ"G dd deeZ#dS )z,Cluster metadata mixin for KafkaAdminClient.    )annotationsdefaultdict)IntEnumN)TYPE_CHECKINGApiKey)ApiVersionsRequestMetadataRequest)AlterReplicaLogDirsRequestDescribeClusterRequestDescribeLogDirsRequestDescribeQuorumRequestUpdateFeaturesRequest)TopicPartitionReplica)
EnumHelper)KafkaConnectionManagerc                   @  s   e Zd ZU dZded< dd Zdd Zdd	 Zd,ddZd-ddZ	e
dd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zd.d!d"Zd.d#d$Ze
d%d& Zd/d(d)Zd/d*d+ZdS )0ClusterAdminMixinz@Mixin providing cluster management methods for KafkaAdminClient.r   _managerc                   sx   t j |du rd}n	 fdd|D }t |dddd}| j|I dH }| }| | |d D ]}| | q2|S )ztopics = [] for no topics, None for all. Items may be topic-name
        strings or :class:`uuid.UUID` topic ids (KIP-516, requires broker
        >= 2.8 / MetadataRequest v12+).Nc                   s.   g | ]}t |tjr d |dn |dqS )N)nametopic_id)r   )
isinstanceuuidUUID).0t_Topic R/home/djax/ivt_ai_plugin/venv/lib/python3.10/site-packages/kafka/admin/_cluster.py
<listcomp>*   s
    z;ClusterAdminMixin._get_cluster_metadata.<locals>.<listcomp>FT)topicsallow_auto_topic_creation%include_cluster_authorized_operations#include_topic_authorized_operationsr!   )r
   MetadataRequestTopicr   sendto_dict_process_acl_operations)selfr!   request_topicsrequestresponsemetadatatopicr   r   r   _get_cluster_metadata"   s&   

z'ClusterAdminMixin._get_cluster_metadatac                   s   z@t ddd}| j|I d H }t|j}|tjur!||j| }|	d |	d |	d |	dd  | 
| |W S  tjyn   | g I d H }|	d |	dd  |d D ]	}|	d	|d
< q`| Y S w )NT)r#   include_fenced_brokers
error_codeerror_messageendpoint_typethrottle_time_msr!   brokersnode_id	broker_id)r   r   r&   Errorsfor_coder1   NoErrorr2   r'   popr(   IncompatibleBrokerVersionr/   )r)   r+   r,   
error_typer-   brokerr   r   r   _describe_cluster<   s2   






z#ClusterAdminMixin._describe_clusterc                 C  s   | j | jS )zFetch cluster-wide metadata such as the list of brokers, the controller ID,
        and the cluster ID.

        Returns:
            A dict with cluster-wide metadata, excluding topic details.
        )r   runr?   r)   r   r   r   describe_clusterW   s   z"ClusterAdminMixin.describe_clusterr   Nc                   sn   t |d}g }|d u rdd | jj D }|D ]}| jj||dI d H }||dd |jD d q|S )Nr!   c                 S  s   g | ]}|j qS r   r6   )r   r>   r   r   r   r    d   s    z>ClusterAdminMixin._async_describe_log_dirs.<locals>.<listcomp>rD   c                 S  s   g | ]}|  qS r   )r'   )r   resultr   r   r   r    g   s    )r>   log_dirs)r   r   clusterr5   r&   appendresults)r)   topic_partitionsr5   r+   	responsesr6   r,   r   r   r   _async_describe_log_dirs`   s   
z*ClusterAdminMixin._async_describe_log_dirsc                 C  s   |  |}| j| j||S )ac  Fetch broker log directory and topic/partition stats

        Keyword Arguments:
            topic_partitions (dict, list, optional):
                Either: dict of {topic_name: [partition ids]}.
                Or:     list of [topic_name], to query all partitions for topic.
                Or:     None, to query all topics / all partitions.
                Default: None
            brokers (list, optional): List of [node_id] for brokers to query.
                If None, query is sent to all brokers. Default: None

        Returns:
            list of dicts, containing per-broker log-dir data
        )_get_topic_partitionsr   r@   rL   )r)   rJ   r5   r   r   r   describe_log_dirsj   s   
z#ClusterAdminMixin.describe_log_dirsc                   sp   t j  jtdd }|  D ]\}}t|tst| }||j | |j 	|j
 q fdd| D S )Nc                   S  s   t dd S )Nc                   S  s   t tS N)r   listr   r   r   r   <lambda>   s    zVClusterAdminMixin._alter_replica_log_dirs_requests.<locals>.<lambda>.<locals>.<lambda>r   r   r   r   r   rQ      s    zDClusterAdminMixin._alter_replica_log_dirs_requests.<locals>.<lambda>c                   s0   i | ]\}}|t  fd d| D dqS )c                   s.   g | ]\}} |fd d|  D dqS )c                   s   g | ]
\}} ||d qS ))r   
partitionsr   )r   r.   partsr   r   r   r       s    
z\ClusterAdminMixin._alter_replica_log_dirs_requests.<locals>.<dictcomp>.<listcomp>.<listcomp>)pathr!   )items)r   rT   r!   _Dirr   r   r   r       s    zQClusterAdminMixin._alter_replica_log_dirs_requests.<locals>.<dictcomp>.<listcomp>)dirs)r   rU   )r   r7   rX   rV   r   r   
<dictcomp>   s    zFClusterAdminMixin._alter_replica_log_dirs_requests.<locals>.<dictcomp>)r   AlterReplicaLogDirAlterReplicaLogDirTopicr   rU   r   r   r7   r.   rH   	partition)replica_assignmentsbroker_to_dirstprlog_dirr   rV   r    _alter_replica_log_dirs_requests|   s   
z2ClusterAdminMixin._alter_replica_log_dirs_requestsc           
        s~   |si S |  |}i }| D ],\}}| jj||dI d H }|jD ]}|jD ]}t|j|j|d}	t	
|j||	< q'q"q|S )NrD   )r.   r\   r7   )ra   rU   r   r&   rI   rR   r   
topic_namepartition_indexr8   r9   r1   )
r)   r]   broker_requestsrE   r7   r+   r,   r.   r\   r_   r   r   r   _async_alter_replica_log_dirs   s$   


z/ClusterAdminMixin._async_alter_replica_log_dirsc                 C     | j | j|S )aM  Move replicas between log directories on their hosting brokers.

        Each entry instructs the targeted broker to move (or place) the
        replica for a given partition into the specified absolute log
        directory path. Requests are sent to each broker in parallel; a
        broker will only act on replicas it currently hosts.

        Arguments:
            replica_assignments: A dict mapping
                :class:`~kafka.TopicPartitionReplica` (``topic``,
                ``partition``, ``broker_id``) to the destination log
                directory path (absolute string). Tuples of
                ``(topic, partition, broker_id)`` are also accepted.

        Returns:
            dict mapping :class:`~kafka.TopicPartitionReplica` to the
            corresponding error class (``kafka.errors.NoError`` on success).
        )r   r@   re   )r)   r]   r   r   r   alter_replica_log_dirs   s   z(ClusterAdminMixin.alter_replica_log_dirsc           
        s   t j}|j}t ||||dgdgd}| j|I d H }t|j}|tjur0||j	p.d|
 }|dd  |dd  |dd  |d D ]'}|d	 D ] }t|d|d}	t|	tjslt|	|d
< qPd |d
< qPqJ|S )N)rc   )rb   rR   rC    r4   r1   r2   r!   rR   error)r   	TopicDataPartitionDatar   r&   r8   r9   r1   r:   r2   r'   r;   r   str)
r)   r.   r\   r   
_Partitionr+   r,   	top_errorrE   ri   r   r   r   _async_describe_quorum   s,   

z(ClusterAdminMixin._async_describe_quorumc                 C  s   | j | jddS )a  Describe the KRaft quorum state for the cluster metadata log.

        Returns quorum info for the ``__cluster_metadata`` topic
        (partition 0), including the current leader, leader epoch, high
        watermark, voters, and observers. On broker version >= 3.8 (KIP-853),
        the response also reports controller node endpoints in ``nodes``.
        Requires a KRaft cluster.

        Returns:
            dict matching the DescribeQuorumResponse shape.
        __cluster_metadatar   )r   r@   ro   rA   r   r   r   describe_metadata_quorum   s   z*ClusterAdminMixin.describe_metadata_quorumc                   s   | j |I d H }|jS rO   )r   get_connectionbroker_version_data)r)   r7   connr   r   r   _async_get_broker_version_data   s   z0ClusterAdminMixin._async_get_broker_version_datac                 C  rf   )z.Return BrokerVersionData for a specific broker)r   r@   ru   )r)   r7   r   r   r   get_broker_version_data   s   z)ClusterAdminMixin.get_broker_version_datac                 C  s   | j jj}dd | D S )Nc                 S  s   i | ]	\}}t ||qS r   r   )r   kvr   r   r   rY      s    z2ClusterAdminMixin.api_versions.<locals>.<dictcomp>)r   rs   api_versionsrU   )r)   ry   r   r   r   ry      s   
zClusterAdminMixin.api_versionsFc                   s   t | jjd | jjd dd}|r| |I d H }n	| j|I d H }t|j}|tjur6|d| t	t
}|j}|d u sE|dk rGd }|jpKg D ]}|j|jf||j d< qL|jp^g D ]}|j|jf||j d< |||j d	< q_t
|S )
Nclient_software_nameclient_software_version   )rz   r{   min_versionzApiVersionsRequest failed: r   	supported	finalizedfinalized_epoch)r	   r   config_send_request_to_controllerr&   r8   r9   r1   r:   r   dictfinalized_features_epochsupported_featuresr}   max_versionr   finalized_featuresmin_version_levelmax_version_level)r)   send_request_to_controllerr+   r,   r=   rE   epochfeaturer   r   r   _async_describe_features   s,   


z*ClusterAdminMixin._async_describe_featuresc                 C  rf   )a  Fetch the cluster's supported and finalized feature flags.

        Features are broker-level capabilities (e.g. ``metadata.version``)
        that can be finalized cluster-wide via ``update_features`` (KIP-584).
        Requires broker >= 2.4.

        Keyword Arguments:
            send_request_to_controller (bool, optional): If True, route the
                request to the active controller. By default the request is
                sent to any available broker. Default: False.

        Returns:
            dict with keys:
                - ``supported_features``: dict of
                  ``{feature_name: (min_version, max_version)}``
                - ``finalized_features``: dict of
                  ``{feature_name: (min_version_level, max_version_level)}``
                - ``finalized_features_epoch``: int, or None if unknown
                  (broker did not report an epoch, or reported -1)
        )r   r@   r   )r)   r   r   r   r   describe_features   s   z#ClusterAdminMixin.describe_featuresc           	   	   C  s   t | ts	tdtj}g }|  D ]/\}}t |tr |\}}ntj}|}t	|}|tj
jtjjfv }|||t|||d q|S )Nzxfeature_updates must be a dict of {feature_name: (max_version_level, upgrade_type)} or {feature_name: max_version_level})r   r   allow_downgradeupgrade_type)r   r   	TypeErrorr   FeatureUpdateKeyrU   tupleUpdateFeatureTypeUPGRADE	value_forSAFE_DOWNGRADEvalueUNSAFE_DOWNGRADErH   int)	feature_updates_FeatureUpdateKeyupdatesr   specr   r   upgrade_code	downgrader   r   r   _build_feature_updates  s*   




z(ClusterAdminMixin._build_feature_updates`  c           
        s   |rdnd}t || |||d}| j|dd dI d H }i }|jp$g D ]}|jdkr2d||j< q%tt|j|j	||j< q%|D ]}	|
|	d qC|S )N   r   )
timeout_msr   validate_onlyr}   c                 S  s   t | jgS rO   )r8   r9   r1   )rr   r   r   rQ   8  s    z:ClusterAdminMixin._async_update_features.<locals>.<lambda>)get_errors_fnOK)r   r   r   rI   r1   r   rl   r8   r9   r2   
setdefault)
r)   r   r   r   r}   r+   r,   retrE   r   r   r   r   _async_update_features.  s(   
z(ClusterAdminMixin._async_update_featuresc                 C  s   | j | j|||S )a  Update cluster-wide finalized feature flags.

        Finalize cluster-wide feature capabilities (e.g. ``metadata.version``).
        The request is always routed to the active controller. See KIP-584.
        Requires broker >= 2.7.

        Arguments:
            feature_updates: A dict of
                ``{feature_name: (upgrade_type, max_version_level)}`` or
                ``{feature_name: max_version_level}`` (implicit UPGRADE).
                ``upgrade_type`` may be a :class:`UpdateFeatureType`,
                its name, or int value. A ``max_version_level < 1`` requests
                deletion of the finalized feature.

        Keyword Arguments:
            validate_only (bool, optional): If True, validate the request but
                do not apply it. Default: False.
            timeout_ms (int, optional): Broker-side timeout in milliseconds.
                Default: 60000.

        Returns:
            dict of {feature_name: 'OK' | error message}
        )r   r@   r   )r)   r   r   r   r   r   r   update_featuresG  s   
z!ClusterAdminMixin.update_features)r   N)NN)F)Fr   )__name__
__module____qualname____doc____annotations__r/   r?   rB   rL   rN   staticmethodra   re   rg   ro   rq   ru   rv   ry   r   r   r   r   r   r   r   r   r   r      s.   
 
	






r   c                   @  s   e Zd ZdZdZdZdZdS )r   r   r      r|   N)r   r   r   UNKNOWNr   r   r   r   r   r   r   r   c  s
    r   )$r   
__future__r   collectionsr   enumr   loggingtypingr   r   kafka.errorserrorsr8   kafka.protocol.api_keyr   kafka.protocol.metadatar	   r
   kafka.protocol.adminr   r   r   r   r   kafka.structsr   
kafka.utilr   kafka.net.managerr   	getLoggerr   logr   r   r   r   r   r   <module>   s(    
  G