o
    iP(                     @   sN  U d dl Z d dlZd dlmZ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mZ d dlmZ d dl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)ListOptionalTupleUnion)Redis)DEFAULT_TIMEOUTAsyncHTTPClientWrapper)	NoBackoff)
HttpClient)UnhealthyDatabaseException)Retry      g      ?i  c                   @   s   e Zd ZedefddZdS )HealthCheckreturnc                       dS )z(Function to determine the health status.N )selfdatabaser   r   U/home/ubuntu/.local/lib/python3.10/site-packages/redis/asyncio/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      dS )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                    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__5   s   
z"AbstractHealthCheckPolicy.__init__r   c                 C      | j S N)r/   r!   r   r   r   r"   ;      z-AbstractHealthCheckPolicy.health_check_probesc                 C   r3   r4   )r0   r!   r   r   r   r$   ?   r5   z,AbstractHealthCheckPolicy.health_check_delayr%   c                    s   d S r4   r   r&   r   r   r   r'   C   s   z!AbstractHealthCheckPolicy.executeN)r   r   r   r*   r+   r2   r)   r"   r$   r   r   r   r   r'   r   r   r   r   r,   4   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 r4   superr2   r1   	__class__r   r   r2   M      zHealthyAllPolicy.__init__r%   r   c                    s   |D ]<}t | jD ]4}z||I d H sW   dS W n ty- } ztd||d }~ww || jd k r>t| jI d H  q
qdS )NFUnhealthy databaser-   Tranger"   r   	Exceptionr   asynciosleepr0   )r   r%   r   health_checkattempter   r   r   r'   P   s    
	zHealthyAllPolicy.executer   r   r   r(   r*   r+   r2   r   r   r   r'   __classcell__r   r   r;   r   r7   H       r7   c                       r6   )
HealthyMajorityPolicyzW
    Policy that returns True if a majority of health check probes are successful.
    r"   r$   c                    r8   r4   r9   r1   r;   r   r   r2   c   r=   zHealthyMajorityPolicy.__init__r%   r   c                    s   |D ]f}| j d dkr| j d }n| j d d }t| j D ]J}z||I d H s6|d8 }|dkr6W   dS W n  tyW } z|d8 }|dkrMtd||W Y d }~nd }~ww || j d k rht| jI d H  qqdS )N   r   r-   Fr>   T)r"   r@   r   rA   r   rB   rC   r0   )r   r%   r   rD   allowed_unsuccessful_probesrE   rF   r   r   r   r'   f   s4   
zHealthyMajorityPolicy.executerG   r   r   r;   r   rJ   ^   rI   rJ   c                       r6   )
HealthyAnyPolicyzT
    Policy that returns True if at least one health check probe is successful.
    r"   r$   c                    r8   r4   r9   r1   r;   r   r   r2      r=   zHealthyAnyPolicy.__init__r%   r   c                    s   d}|D ]T}d }t | jD ]<}z||I d H rd}W  n-d}W n ty9 } ztd||}W Y d }~nd }~ww || jd k rJt| jI d H  q|sS|sS|  S |sY|rY|q|S )NFTr>   r-   r?   )r   r%   r   
is_healthyrD   	exceptionrE   rF   r   r   r   r'      s2   zHealthyAnyPolicy.executerG   r   r   r;   r   rM      rI   rM   c                   @   s   e Zd ZeZeZeZdS )HealthCheckPoliciesN)	r   r   r   r7   HEALTHY_ALLrJ   HEALTHY_MAJORITYrM   HEALTHY_ANYr   r   r   r   rP      s    rP   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                    sP   t |jtr|jdI d H S |j }|D ]}|jdI d H 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   rU      s    rU   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   s<   t 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)
ra   rb   retryrc   rd   re   rf   rg   rh   ri   N)r   r   r   r   _http_client_rest_api_port_lag_aware_tolerance)r   r_   r`   ra   rb   rc   rd   re   rf   rg   rh   ri   r   r   r   r2      s     
zLagAwareHealthCheck.__init__r   c           	         s   |j d u r
tdt|jtr|j d }n|jjd j}|j  d| j }|| j	j_
d }| j	dI d H D ]"}|d D ]}|d |krJ|} n|d D ]
}||krX|} nqNq>q8|d u rhtd	 td
d|d  d| j }| j	j|ddI d H  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.   rW   rX   r	   get_connection_kwargsstartup_nodesro   rm   rl   base_urlgetloggerwarningrn   )	r   r   db_hostry   matching_bdbbdbendpointrs   urlr   r   r   r      s>   


z LagAwareHealthCheck.check_health)r   r   r   r(   DEFAULT_LAG_AWARE_TOLERANCEr
   r*   r+   r   r   strr   r   bytesr2   r   r   r   r   r   r^      sJ    	

1r^   ),rB   loggingabcr   r   enumr   typingr   r   r   r   redis.asyncior	   redis.asyncio.http.http_clientr
   r   redis.backoffr   redis.http.http_clientr   redis.multidb.exceptionr   redis.retryr   DEFAULT_HEALTH_CHECK_PROBESDEFAULT_HEALTH_CHECK_INTERVALDEFAULT_HEALTH_CHECK_DELAYr   	getLoggerr   r{   r   r   r,   r7   rJ   rM   rP   rQ   rT   __annotations__rU   r^   r   r   r   r   <module>   s4   
 
!%