o
    `jG                     @   s  d Z ddlZddlZddlZddlZddlZddlmZ ddlm	Z	m
Z
 ddlmZmZ ddlmZ ddlmZmZmZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddl m!Z! ddl"m#Z# ddl$m%Z% e&e'Z(G dd deeeeee!e#e%
Z)dS )z;KafkaAdminClient - high-level Kafka cluster administration.    N)KafkaConfigurationErrorUnrecognizedBrokerVersion)MetricConfigMetrics)KafkaNetClient)MetadataRequestFindCoordinatorRequestCoordinatorType)__version__)ACLAdminMixin)ClusterAdminMixin)ConfigAdminMixin)GroupAdminMixin)PartitionAdminMixin)TopicAdminMixin)TransactionsAdminMixin)UserAdminMixinc                   @   sf  e Zd ZdZi dddde dddd	d
ddddddddddddejejdfgdddddddddddd i d!dd"dd#dd$dd%dd&dd'dd(ej	d)dd*dd+dd,dd-d.d/dd0dd1dd2dg d3de
d4Zd5d6 Zd7d8 Zd9d: Zd;d< Zd=d> ZdJd?d@ZejfdAdBZejfdCdDZdEdF d dGfdHdIZdS )KKafkaAdminClientao!  A class for administering the Kafka cluster.

    Keyword Arguments:
        bootstrap_servers: 'host[:port]' string (or list of 'host[:port]'
            strings) that the consumer should contact to bootstrap initial
            cluster metadata. This does not have to be the full node list.
            It just needs to have at least one broker that will respond to a
            Metadata API Request. Default port is 9092. If no servers are
            specified, will default to localhost:9092.
        client_id (str): a name for this client. This string is passed in
            each request to servers and can be used to identify specific
            server-side log entries that correspond to this client. Also
            submitted to GroupCoordinator for logging with respect to
            consumer group administration. Default: 'kafka-python-{version}'
        reconnect_backoff_ms (int): The amount of time in milliseconds to
            wait before attempting to reconnect to a given host.
            Default: 50.
        reconnect_backoff_max_ms (int): The maximum amount of time in
            milliseconds to backoff/wait when reconnecting to a broker that has
            repeatedly failed to connect. If provided, the backoff per host
            will increase exponentially for each consecutive connection
            failure, up to this maximum. Once the maximum is reached,
            reconnection attempts will continue periodically with this fixed
            rate. To avoid connection storms, a randomization factor of 0.2
            will be applied to the backoff resulting in a random range between
            20% below and 20% above the computed value. Default: 30000.
        request_timeout_ms (int): Client request timeout in milliseconds.
            Default: 30000.
        connections_max_idle_ms: Close idle connections after the number of
            milliseconds specified by this config. The broker closes idle
            connections after connections.max.idle.ms, so this avoids hitting
            unexpected socket disconnected errors on the client.
            Default: 540000
        retry_backoff_ms (int): Milliseconds to backoff when retrying on
            errors. Default: 100.
        max_in_flight_requests_per_connection (int): Requests are pipelined
            to kafka brokers up to this number of maximum requests per
            broker connection. Default: 5.
        receive_message_max_bytes (int): Maximum allowed network frame size.
            Used to avoid OOM when decoding malformed network message header.
            Default: 100_000_000.
        receive_buffer_bytes (int): The size of the TCP receive buffer
            (SO_RCVBUF) to use when reading data. Default: None (relies on
            system defaults). Java client defaults to 32768.
        send_buffer_bytes (int): The size of the TCP send buffer
            (SO_SNDBUF) to use when sending data. Default: None (relies on
            system defaults). Java client defaults to 131072.
        socket_options (list): List of tuple-arguments to socket.setsockopt
            to apply to broker connection sockets. Default:
            [(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)]
        metadata_max_age_ms (int): The period of time in milliseconds after
            which we force a refresh of metadata even if we haven't seen any
            partition leadership changes to proactively discover any new
            brokers or partitions. Default: 300000
        security_protocol (str): Protocol used to communicate with brokers.
            Valid values are: PLAINTEXT, SSL, SASL_PLAINTEXT, SASL_SSL.
            Default: PLAINTEXT.
        ssl_context (ssl.SSLContext): Pre-configured SSLContext for wrapping
            socket connections. If provided, all other ssl_* configurations
            will be ignored. Default: None.
        ssl_check_hostname (bool): Flag to configure whether SSL handshake
            should verify that the certificate matches the broker's hostname.
            Default: True.
        ssl_cafile (str): Optional filename of CA file to use in certificate
            verification. Default: None.
        ssl_certfile (str): Optional filename of file in PEM format containing
            the client certificate, as well as any CA certificates needed to
            establish the certificate's authenticity. Default: None.
        ssl_keyfile (str): Optional filename containing the client private key.
            Default: None.
        ssl_password (str): Optional password to be used when loading the
            certificate chain. Default: None.
        ssl_crlfile (str): Optional filename containing the CRL to check for
            certificate expiration. By default, no CRL check is done. When
            providing a file, only the leaf certificate will be checked against
            this CRL. Default: None.
        api_version (tuple): Specify which Kafka API version to use. If set to
            None, the client will infer the broker version from the results of
            ApiVersionsRequest API. For brokers earlier than 0.10, which do not
            support the ApiVersionsRequest API, api_version is required.
            Note: Dynamic version checking is performed eagerly during __init__
            and can raise KafkaTimeoutError if no connection can be made before
            timeout (see bootstrap_timeout_ms below).
            Different versions enable different functionality.

            Examples::

                (4, 3) most recent broker release, enable all supported features
                (2, 7) support SCRAM user credential apis
                (0, 11) enables message format v2 (internal)
                (0, 10, 0) enables sasl authentication and message format v1
                (0, 9) enables full group coordination features with automatic
                    partition assignment and rebalancing,
                (0, 8, 2) enables kafka-storage offset commits with manual
                    partition assignment only,
                (0, 8, 1) enables zookeeper-storage offset commits with manual
                    partition assignment only,
                (0, 8, 0) enables basic functionality but requires manual
                    partition assignment and offset management.

            Default: None
        bootstrap_timeout_ms (int): number of milliseconds to wait for first
            successful cluster bootstrap. If provided, an attempt to bootstrap
            will raise KafkaTimeoutError if it is unable to fetch cluster
            metadata before the configured timeout. Note that bootstrap is
            called eagerly from __init__().
            Default: 30000
        selector (selectors.BaseSelector): Provide a specific selector
            implementation to use for I/O multiplexing.
            Default: selectors.DefaultSelector
        metrics (kafka.metrics.Metrics): Optionally provide a metrics
            instance for capturing network IO stats. Default: None.
        metric_group_prefix (str): Prefix for metric names. Default: ''
        sasl_mechanism (str): Authentication mechanism when security_protocol
            is configured for SASL_PLAINTEXT or SASL_SSL. Valid values are:
            PLAIN, GSSAPI, OAUTHBEARER, SCRAM-SHA-256, SCRAM-SHA-512.
        sasl_plain_username (str): username for sasl PLAIN and SCRAM authentication.
            Required if sasl_mechanism is PLAIN or one of the SCRAM mechanisms.
        sasl_plain_password (str): password for sasl PLAIN and SCRAM authentication.
            Required if sasl_mechanism is PLAIN or one of the SCRAM mechanisms.
        sasl_kerberos_name (str or gssapi.Name): Constructed gssapi.Name for use with
            sasl mechanism handshake. If provided, sasl_kerberos_service_name and
            sasl_kerberos_domain name are ignored. Default: None.
        sasl_kerberos_service_name (str): Service name to include in GSSAPI
            sasl mechanism handshake. Default: 'kafka'
        sasl_kerberos_domain_name (str): kerberos domain name to use in GSSAPI
            sasl mechanism handshake. Default: one of bootstrap servers
        sasl_oauth_token_provider (kafka.net.sasl.oauth.AbstractTokenProvider): OAuthBearer
            token provider instance. Default: None
        proxy_url (str): URL to proxy socket connections through. Supports SOCKS5 only.
            Requires scheme:// (e.g., socks5://foo.bar/). Default: None
        kafka_client (callable): Custom class / callable for creating KafkaNetClient instances
    bootstrap_servers	localhost	client_idzkafka-python-request_timeout_ms0u  connections_max_idle_msi`= reconnect_backoff_ms2   reconnect_backoff_max_ms%max_in_flight_requests_per_connection   receive_message_max_bytesi receive_buffer_bytesNsend_buffer_bytessocket_options   retry_backoff_msd   metadata_max_age_msi client_dns_lookupuse_all_dns_ipssecurity_protocol	PLAINTEXTssl_contextssl_check_hostnameT
ssl_cafilessl_certfilessl_keyfilessl_passwordssl_crlfileapi_versionbootstrap_timeout_msselectorsasl_mechanismsasl_plain_usernamesasl_plain_passwordsasl_kerberos_namesasl_kerberos_service_namekafkasasl_kerberos_domain_namesasl_oauth_token_provider	proxy_urlsocks5_proxy   )metric_reportersmetrics_num_samplesmetrics_sample_window_mskafka_clientc                 K   s   t d| t|| j}|rtd|t| j| _| j	| d| jd i}t
| jd | jd |d}dd	 | jd
 D }t||| _| jd d| jdd| j| _| jj| _| jj| _| j  | j| jd  d| _d | _t d d S )Nz0Starting KafkaAdminClient with configuration: %szUnrecognized configs: {}z	client-idr   rA   rB   )samplestime_window_mstagsc                 S   s   g | ]}| qS  rG   ).0reporterrG   rG   P/home/djax/ivt_ai_plugin/venv/lib/python3.10/site-packages/kafka/admin/client.py
<listcomp>   s    z-KafkaAdminClient.__init__.<locals>.<listcomp>r@   rC   admin)metricsmetric_group_prefixr3   FzKafkaAdminClient started.rG   )logdebugset
differenceDEFAULT_CONFIGr   formatcopyconfigupdater   r   _metrics_client_manager_netstart	bootstrap_closed_controller_id)selfconfigsextra_configsmetrics_tagsmetric_config	reportersrG   rG   rJ   __init__   s4   




zKafkaAdminClient.__init__c                 C   s   | S NrG   r`   rG   rG   rJ   	__enter__   s   zKafkaAdminClient.__enter__c                 C   s   |    d S rg   )close)r`   exc_typeexc_valexc_tbrG   rG   rJ   __exit__   s   zKafkaAdminClient.__exit__c                 C   sP   t | dr| jrtd dS d| _| j  | j  | j  t	d dS )z:Close the KafkaAdminClient connection to the Kafka broker.r^   z KafkaAdminClient already closed.NTzKafkaAdminClient is now closed.)
hasattrr^   rO   inforX   rj   rY   r[   stoprP   rh   rG   rG   rJ   rj     s   



zKafkaAdminClient.closec                 C   s   |p| j d S )z=Validate the timeout is set or use the configuration default.r   )rV   )r`   
timeout_msrG   rG   rJ   _validate_timeout  s   z"KafkaAdminClient._validate_timeoutc                    s   | j jdk rtdt }t |d  }t |k r=| j |I dH }|j}|dkr;t	d | j
dI dH  q|S td)	z'Determine the Kafka cluster controller.)r   
   zIKafka Admin Client controller requests requires broker version >= (0, 10)i  Nz#Controller ID not available, got -1r#   
controller)rZ   broker_versionr   r   time	monotonicsendcontroller_idrO   warningr[   sleepErrorsNodeNotReadyError)r`   rr   request
timeout_atresponser{   rG   rG   rJ   _refresh_controller_id  s    

z'KafkaAdminClient._refresh_controller_idc                    s  t |}| jj}i }g }|D ]}|||}|dur!|||< q|| q|s+|S | jjtdkr\t|j	|dd}| j
|I dH }	|	jD ]}
|j|
||
jdd}|||
j< qH|S |D ] }t||j	dd}| j
|I dH }	|j|	||dd}|||< q^|S )a(  Find broker node_ids of the coordinators for a set of keys.

        ``key_type`` is the CoordinatorType enum (GROUP=0, TRANSACTION=1,
        SHARE=2). Results are cached in the shared
        ``ClusterMetadata._coordinators`` map; only keys not already in
        the cache hit the network. On brokers supporting FindCoordinator
        v4+ (KIP-699, Apache Kafka 3.0+), all unknown keys are resolved
        in a single batched request; older brokers fall back to one
        request per key.

        Returns a dict mapping key -> node_id.
        N   )key_typecoordinator_keysmin_versionF)synthesize_node_id   )keyr   max_version)r	   
build_fromrZ   clusterget_coordinatorappendbroker_version_datar2   r   valuerz   coordinatorsadd_coordinatorr   )r`   keysr   r   resultunknownr   cachedr   r   coordinatornode_idrG   rG   rJ   _find_coordinator_ids&  sH   



z&KafkaAdminClient._find_coordinator_idsc                    s    | j |g|dI dH }|| S )z.Single-key wrapper for _find_coordinator_ids())r   N)r   )r`   r   r   idsrG   rG   rJ   _find_coordinator_idX  s   z%KafkaAdminClient._find_coordinator_idc                 C   s   dS )NrG   rG   )rrG   rG   rJ   <lambda>]  s    zKafkaAdminClient.<lambda>rG   c                    s   | j du s| j dkr|  I dH | _ | jj|| j dI dH }tj||v r:|  I dH | _ | jj|| j dI dH }||D ]}|tju rFq>|tju rOtd|r]||vr]|d||q>|S )zSend a Kafka protocol message to the cluster controller.

        Retries once on NotControllerError after refreshing the controller id.
        Nru   )r   z$Failed to find active controller id!z'Request '{}' failed with response '{}'.)	r_   r   rZ   rz   r~   NotControllerErrorNoErrorRuntimeErrorrT   )r`   r   get_errors_fnraise_errorsignore_errorsr   
error_typerG   rG   rJ   _send_request_to_controller]  s&   

z,KafkaAdminClient._send_request_to_controller)r   )__name__
__module____qualname____doc__r
   socketIPPROTO_TCPTCP_NODELAY	selectorsDefaultSelectorr   rS   rf   ri   rn   rj   rs   r   r	   GROUPr   r   r   rG   rG   rG   rJ   r      s    
 	
 !"#&,$
2r   )*r   rU   loggingr   r   rx   kafka.errorserrorsr~   r   r   kafka.metricsr   r   kafka.net.compatr   kafka.protocol.metadatar   r   r	   kafka.versionr
   kafka.admin._aclsr   kafka.admin._clusterr   kafka.admin._configsr   kafka.admin._groupsr   kafka.admin._partitionsr   kafka.admin._topicsr   kafka.admin._transactionsr   kafka.admin._usersr   	getLoggerr   rO   r   rG   rG   rG   rJ   <module>   s>    

