o
    i)'                     @   sF  U d dl Z d dlmZmZ d dlmZ d dlmZ d dlm	Z	m
Z
mZmZ d dlmZ d dlmZ d dlmZmZ d d	lmZ d d
lmZ dZdZdZdZe eZG dd deZG dd deZ G dd de Z!G dd de!Z"G dd de!Z#G dd de!Z$G dd deZ%e%j&Z'e%e(d< G dd deZ)G d d! d!eZ*dS )"    N)ABCabstractmethod)Enum)sleep)ListOptionalTupleUnion)Redis)	NoBackoff)DEFAULT_TIMEOUT
HttpClient)UnhealthyDatabaseException)Retry      g      ?i  c                   @   s   e Zd ZedefddZdS )HealthCheckreturnc                 C      dS )z(Function to determine the health status.N )selfdatabaser   r   M/home/ubuntu/.local/lib/python3.10/site-packages/redis/multidb/healthcheck.pycheck_health      zHealthCheck.check_healthN)__name__
__module____qualname__r   boolr   r   r   r   r   r      s    r   c                   @   sV   e Zd ZdZeedefddZeedefddZ	ede
e defdd	Zd
S )HealthCheckPolicyz)
    Health checks execution policy.
    r   c                 C   r   )z*Number of probes to execute health checks.Nr   r   r   r   r   health_check_probes!      z%HealthCheckPolicy.health_check_probesc                 C   r   )z"Delay between health check probes.Nr   r    r   r   r   health_check_delay'   r"   z$HealthCheckPolicy.health_check_delayhealth_checksc                 C   r   )z8Execute health checks and return database health status.Nr   r   r$   r   r   r   r   execute-   r   zHealthCheckPolicy.executeN)r   r   r   __doc__propertyr   intr!   floatr#   r   r   r   r&   r   r   r   r   r      s    r   c                   @   s\   e Zd ZdedefddZedefddZedefdd	Ze	d
e
e defddZdS )AbstractHealthCheckPolicyr!   r#   c                 C   s    |dk rt d|| _|| _d S )N   z*health_check_probes must be greater than 0)
ValueError_health_check_probes_health_check_delayr   r!   r#   r   r   r   __init__4   s   
z"AbstractHealthCheckPolicy.__init__r   c                 C      | j S N)r.   r    r   r   r   r!   :      z-AbstractHealthCheckPolicy.health_check_probesc                 C   r2   r3   )r/   r    r   r   r   r#   >   r4   z,AbstractHealthCheckPolicy.health_check_delayr$   c                 C   s   d S r3   r   r%   r   r   r   r&   B   s   z!AbstractHealthCheckPolicy.executeN)r   r   r   r)   r*   r1   r(   r!   r#   r   r   r   r   r&   r   r   r   r   r+   3   s    r+   c                       @   e Zd ZdZdedef fddZdee de	fdd	Z
  ZS )
HealthyAllPolicyzM
    Policy that returns True if all health check probes are successful.
    r!   r#   c                       t  || d S r3   superr1   r0   	__class__r   r   r1   L      zHealthyAllPolicy.__init__r$   r   c                 C   st   |D ]5}t | jD ]-}z||sW   dS W n ty) } ztd||d }~ww || jd k r6t| j q	qdS )NFUnhealthy databaser,   Tranger!   r   	Exceptionr   r   r/   )r   r$   r   health_checkattempter   r   r   r&   O   s   


	zHealthyAllPolicy.executer   r   r   r'   r)   r*   r1   r   r   r   r&   __classcell__r   r   r:   r   r6   G       r6   c                       r5   )
HealthyMajorityPolicyzW
    Policy that returns True if a majority of health check probes are successful.
    r!   r#   c                    r7   r3   r8   r0   r:   r   r   r1   b   r<   zHealthyMajorityPolicy.__init__r$   r   c                 C   s   |D ]_}| j d dkr| j d }n| j d d }t| j D ]C}z||s2|d8 }|dkr2W   dS W n  tyS } z|d8 }|dkrItd||W Y d }~nd }~ww || j d k r`t| j qqdS )N   r   r,   Fr=   T)r!   r?   r   r@   r   r   r/   )r   r$   r   rA   allowed_unsuccessful_probesrB   rC   r   r   r   r&   e   s2   


zHealthyMajorityPolicy.executerD   r   r   r:   r   rG   ]   rF   rG   c                       r5   )
HealthyAnyPolicyzT
    Policy that returns True if at least one health check probe is successful.
    r!   r#   c                    r7   r3   r8   r0   r:   r   r   r1      r<   zHealthyAnyPolicy.__init__r$   r   c                 C   s   d}|D ]M}d }t | jD ]5}z||rd}W  n)d}W n ty5 } ztd||}W Y d }~nd }~ww || jd k rBt| j q|sK|sK|  S |sQ|rQ|q|S )NFTr=   r,   r>   )r   r$   r   
is_healthyrA   	exceptionrB   rC   r   r   r   r&      s0   

zHealthyAnyPolicy.executerD   r   r   r:   r   rJ   ~   rF   rJ   c                   @   s   e Zd ZeZeZeZdS )HealthCheckPoliciesN)	r   r   r   r6   HEALTHY_ALLrG   HEALTHY_MAJORITYrJ   HEALTHY_ANYr   r   r   r   rM      s    rM   DEFAULT_HEALTH_CHECK_POLICYc                   @   s   e Zd ZdZdefddZdS )PingHealthCheckz-
    Health check based on PING command.
    r   c                 C   sB   t |jtr|jdS |j }|D ]}|jds dS qdS )NPINGFT)
isinstanceclientr
   execute_command	get_nodesredis_connection)r   r   	all_nodesnoder   r   r   r      s   
zPingHealthCheck.check_healthN)r   r   r   r'   r   r   r   r   r   r   rR      s    rR   c                   @   s   e Zd ZdZdeeddddddddfdedededee	e
e
f  d	ed
ee
 dee
 deee
ef  dee
 dee
 dee
 fddZdefddZdS )LagAwareHealthCheckz
    Health check available for Redis Enterprise deployments.
    Verify via REST API that the database is healthy based on different lags.
    i$  NTrest_api_portlag_aware_tolerancetimeout
auth_basic
verify_tlsca_fileca_pathca_dataclient_cert_fileclient_key_fileclient_key_passwordc                 C   s8   t ||tt dd|||||	|
|d
| _|| _|| _dS )a  
        Initialize LagAwareHealthCheck with the specified parameters.

        Args:
            rest_api_port: Port number for Redis Enterprise REST API (default: 9443)
            lag_aware_tolerance: Tolerance in lag between databases in MS (default: 100)
            timeout: Request timeout in seconds (default: DEFAULT_TIMEOUT)
            auth_basic: Tuple of (username, password) for basic authentication
            verify_tls: Whether to verify TLS certificates (default: True)
            ca_file: Path to CA certificate file for TLS verification
            ca_path: Path to CA certificates directory for TLS verification
            ca_data: CA certificate data as string or bytes
            client_cert_file: Path to client certificate file for mutual TLS
            client_key_file: Path to client private key file for mutual TLS
            client_key_password: Password for encrypted client private key
        r   )retries)
r^   r_   retryr`   ra   rb   rc   rd   re   rf   N)r   r   r   _http_client_rest_api_port_lag_aware_tolerance)r   r\   r]   r^   r_   r`   ra   rb   rc   rd   re   rf   r   r   r   r1      s    
zLagAwareHealthCheck.__init__r   c           	      C   s   |j d u r	tdt|jtr|j d }n|jjd j}|j  d| j }|| j	_
d }| j	dD ]"}|d D ]}|d |krE|} n|d D ]
}||krS|} nqIq9q3|d u rctd	 td
d|d  d| j }| j	j|dd dS )Nz[Database health check url is not set. Please check DatabaseConfig for the current database.hostr   :z/v1/bdbs	endpointsdns_nameaddrz8LagAwareHealthCheck failed: Couldn't find a matching bdbzCould not find a matching bdbz	/v1/bdbs/uidz=/availability?extend_check=lag&availability_lag_tolerance_ms=F)expect_jsonT)health_check_urlr-   rT   rU   r
   get_connection_kwargsstartup_nodesrl   rj   ri   base_urlgetloggerwarningrk   )	r   r   db_hostrv   matching_bdbbdbendpointrp   urlr   r   r   r      s<   

z LagAwareHealthCheck.check_health)r   r   r   r'   DEFAULT_LAG_AWARE_TOLERANCEr   r)   r*   r   r   strr   r	   bytesr1   r   r   r   r   r   r[      sJ    	

/r[   )+loggingabcr   r   enumr   timer   typingr   r   r   r	   redisr
   redis.backoffr   redis.http.http_clientr   r   redis.multidb.exceptionr   redis.retryr   DEFAULT_HEALTH_CHECK_PROBESDEFAULT_HEALTH_CHECK_INTERVALDEFAULT_HEALTH_CHECK_DELAYr   	getLoggerr   rx   r   r   r+   r6   rG   rJ   rM   rN   rQ   __annotations__rR   r[   r   r   r   r   <module>   s2   
 
!%