o
    h_                     @   s  d dl Z d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlZd dl	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 e jZedkrPdd Zndd Zdd Zdd	d
ZdddZG dd deZG dd dZG dd deZG dd deZG dd deZdS )    N)serverversionWindowsc                 C   s   |  dr| S | d S )Nz.exe)endswithname r   c/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/asyncpg/cluster.pyplatform_exe   s   
r	   c                 C   s   | S Nr   r   r   r   r   r	   #      c                  C   s^   t  t jt j} z!z| d |  d W W |   S  ty)   Y W |   d S w |   w )N)	127.0.0.1r      )socketAF_INETSOCK_STREAMbindgetsocknameclose	Exception)sockr   r   r   find_available_port'   s   


r   c                 C   sh   d tjtjdd}|d u rt }|d u rt }| d u r!d} tj	 ||| |  }t
|d |S )N    )ki  )joinrandomchoicesstringascii_lowercasetempfile
gettempdirgettempprefixospathmkdir)suffixprefixdirr   fnr   r   r   _world_readable_mkdtemp2   s   r)   c                 C   s.   t dkrtjdrt| ||S t| ||S )Nr   GITHUB_ACTIONS)_systemr"   environgetr)   r   mkdtempr%   r&   r'   r   r   r   _mkdtemp?   s   r0   c                   @   s   e Zd ZdS )ClusterErrorN)__name__
__module____qualname__r   r   r   r   r1   I   s    r1   c                   @   s  e Zd ZddddZdd Zdd Zd	d
 Zdd Zd<ddZdd Z	d=i dddZ
dd Zd=ddZdd Zdd Zdd Zdd  Zddd!d"d#Zd$d% Zd&ddd'd(d)Zd*d+ Zd,d- Zd.d/ Zd0d1 Zd=d2d3Zd4d5 Zd6d7 Zd8d9 Zd:d; ZdS )>ClusterNpg_config_pathc                C   sH   || _ || _tjdptjd| _d | _d | _d | _d | _	d | _
d S )NPGINSTALLATIONPGBIN)	_data_dir_pg_config_pathr"   r,   r-   _pg_bin_dir_pg_ctl_daemon_pid_daemon_process_connection_addr_connection_spec_override)selfdata_dirr7   r   r   r   __init__N   s   

zCluster.__init__c                 C      | j S r
   )_pg_versionrB   r   r   r   get_pg_version[      zCluster.get_pg_versionc                 C      dS )NTr   rG   r   r   r   
is_managed^   r   zCluster.is_managedc                 C   rE   r
   )r:   rG   r   r   r   get_data_dira   rI   zCluster.get_data_dirc                 C   s   | j d u r	|   tj| j dd| jgtjtjd}|j|j}}|jdks2t	j
| jr2t	| js4dS |jdkr;dS |jdkratd	| }|sStd
| t|d| _| jddS td|j|)Nstatus-Dstdoutstderr   not-initialized   stoppedr   z.*PID\s?:\s+(\d+).*z(could not parse pg_ctl status output: {}r   timeoutz)pg_ctl status exited with status {:d}: {})r=   	_init_env
subprocessrunr:   PIPErP   rQ   
returncoder"   r#   existslistdirrematchdecoder1   formatintgroupr>   _test_connection)rB   processrP   rQ   rr   r   r   
get_statusd   s8   



zCluster.get_statusc                    s.   |   }|| tjdd|i|I d H S )Nloopr   )get_connection_specupdateasyncpgconnect)rB   ri   kwargs	conn_infor   r   r   rm      s   
zCluster.connectc                 K   s   |   dkrtd| jt|}d|vrd|d< |r/dd | D }dgd|g }ng }tj| jd	d
 t	j
| jdd| jg| t	jt	j| jd}|j}|jdkr`td|j| | S )Initialize cluster.rS   ,cluster in {!r} has already been initializedencodingzUTF-8c                 S      g | ]
\}}d  ||qS z--{}={}rb   .0r   vr   r   r   
<listcomp>   s    z Cluster.init.<locals>.<listcomp>-o T)exist_okinitrN   rP   rQ   cwdr   z'pg_ctl init exited with status {:d}:
{})rh   r1   rb   r:   dictitemsr   r"   makedirsrY   rZ   r=   r[   STDOUTrP   r\   ra   )rB   settingssettings_args
extra_argsrf   outputr   r   r   r}      s<   

zCluster.init<   server_settingsc                K   s8  |   }|dkr
dS |dkrtd| j|dd}|dkr#t }dd | D }|d	| |d
}|du rB|d}|du rNt	dkrNt
 }|d}|rqtj| jd}	t||	 t|	d | }|	|d< |dur| jdk r}d}
nd
}
|||
< | D ]\}}|dd||g qt	dkrtdrtj}tdd| jdd| jdd|gtjd ntj}tj| jdd| jdd|g|tj| jd}|jdkr|jrd|j }nd}td|j|n$tdrtj}ntj}tj | j!d| jg||tj| jd| _"| j"j#| _$| j%|d dS ) zStart the cluster.runningNrS   z(cluster in {!r} has not been initializedportdynamicc                 S   rs   rt   ru   rv   r   r   r   ry      s    z!Cluster.start.<locals>.<listcomp>z	--port={}unix_socket_directoriesunix_socket_directoryr   ssl_key_filez
srvkey.pemi  )	   rT   z-c{}={}ASYNCPG_DEBUG_SERVERzasyncpg.cluster: Runningr{   startrN   rz   filer~   r   z:
{}r   z&pg_ctl start exited with status {:d}{}rV   )&rh   r1   rb   r:   popr   r   appendr-   r+   r   r    r"   r#   r   shutilcopychmodrF   extendgetenvsysrP   printr=   rQ   rY   DEVNULLrZ   r   r\   ra   Popen	_postgresr?   pidr>   re   )rB   waitr   optsrM   r   r   sockdirssl_keykeyfilesockdir_optr   rx   rP   rf   rQ   r   r   r   r      s   





	


	
zCluster.startc                 C   sf   |   }|dkrtdtj| jdd| jgtjtj| jd}|j}|jdkr1td	|j|
 dS )	zReload server configuration.r   z%cannot reload: cluster is not runningreloadrN   r~   r   'pg_ctl stop exited with status {:d}: {}N)rh   r1   rY   rZ   r=   r:   r[   rQ   r\   rb   ra   )rB   rM   rf   rQ   r   r   r   r     s"   

zCluster.reloadc              	   C   s   t j| jdd| jdt|ddgt jt j| jd}|j}|jdkr+td	|j|
 | jd ur=| jjd u r?| j  d S d S d S )	NstoprN   z-tz-mfastr~   r   r   )rY   rZ   r=   r:   strr[   rQ   r\   r1   rb   ra   r?   kill)rB   r   rf   rQ   r   r   r   r     s(   


zCluster.stopc                 C   s6   |   }|dks|dkrt| j d S td|)NrU   rS   zcannot destroy {} cluster)rh   r   rmtreer:   r1   rb   rB   rM   r   r   r   destroy.  s   zCluster.destroyc                 C   sH   | j d u r
|  | _ | j d ur"| jr| j  }|| j |S | j S d S r
   )r@   _connection_addr_from_pidfilerA   r   rk   )rB   argsr   r   r   _get_connection_spec5  s   



zCluster._get_connection_specc                 C   s    |   }|dkrtd|  S )Nr   zcluster is not running)rh   r1   r   r   r   r   r   rj   A  s   zCluster.get_connection_specc                 K   
   || _ d S r
   )rA   rB   rn   r   r   r   override_connection_specH     
z Cluster.override_connection_spec)oidxidc                C   s   |   }|dkrtd|dkrtdg }|d ur#|dt|g |d ur0|dt|g |s4d S || j z| d}W n tyO   | d}Y nw tj|g| tj	tj	d	}|j
}|jd
krptd|j| d S )NrS   z4cannot modify WAL status: cluster is not initializedr   z,cannot modify WAL status: cluster is runningrz   z-xpg_resetwalpg_resetxlogrO   r   z'pg_resetwal exited with status {:d}: {})rh   r1   r   r   r   r:   _find_pg_binaryrY   rZ   r[   rQ   r\   rb   ra   )rB   r   r   rM   r   	reset_walrf   rQ   r   r   r   r   K  sD   

zCluster.reset_walc              
   C   s   |   }|dkrtdtj| jd}zt|d
 W d   W dS 1 s'w   Y  W dS  tyB } ztd||d}~ww )z$Remove all records from pg_hba.conf.rS   5cannot modify HBA records: cluster is not initializedpg_hba.confwNcannot modify HBA records: {})	rh   r1   r"   r#   r   r:   openIOErrorrb   )rB   rM   pg_hbaer   r   r   	reset_hbao  s$   &zCluster.reset_hbahosttypeaddressauth_optionsc             
   C   s  |   }|dkrtd|dvrtd|tj| jd}d|||}	|dkr<|du r5td	||	d
|7 }	|	d
|7 }	|durU|	dddd |D  7 }	z t|d}
t	|	|
d W d   W dS 1 snw   Y  W dS  t
y } ztd||d}~ww )zAdd a record to pg_hba.conf.rS   r   >   r   localhostssl	hostnosslzinvalid HBA record type: {!r}r   z{} {} {}r   Nz#{!r} entry requires a valid addressz {}r{   c                 s   s     | ]\}}d  ||V  qdS )r   Nru   rv   r   r   r   	<genexpr>  s    
z(Cluster.add_hba_entry.<locals>.<genexpr>ar   r   )rh   r1   
ValueErrorrb   r"   r#   r   r:   r   r   r   )rB   r   databaseuserr   auth_methodr   rM   r   recordfr   r   r   r   add_hba_entry  s@   &zCluster.add_hba_entryc                 C   sj   |    tdkr| jddddd | jdddddd | jdd	dddd |  }|d
kr3|   d S d S )Nr   r   alltrustr   r   r   r   r   127.0.0.1/32r   r   r   r   r   ::1/128r   )r   r+   r   rh   r   r   r   r   r   trust_local_connections  s"   zCluster.trust_local_connectionsc                 C   sb   t dkr| jdd|dd | jddd|dd | jdd	d|dd |  }|d
kr/|   d S d S )Nr   r   replicationr   r   r   r   r   r   r   )r+   r   rh   r   )rB   r   rM   r   r   r   trust_local_replication_by  s    z"Cluster.trust_local_replication_byc                 C   s\   | j s| | j}| |}|d| _ | j std| d| _| d| _| 	 | _
d S )Nbindirz1pg_config output did not provide the BINDIR valuepg_ctlpostgres)r<   _find_pg_configr;   _run_pg_configr-   r1   r   r=   r   _get_pg_versionrF   )rB   	pg_configpg_config_datar   r   r   rX     s   
zCluster._init_envc           
      C   s  t j| jd}zt|d}| }W d    n1 sw   Y  W n
 ty-   Y d S w | }t|dk r:d S t	|d }| j
rJ|| j
krJd S |d }|d }|d }|rm|d dkrjt jt j| j|}|}	n|}	|	d	krvd
}	n|	dkr}d}	n|	dkrd}	|	|dS )Nzpostmaster.pidrt   r   rT   rR      /*	localhostz0.0.0.0r   z::z::1)r   r   )r"   r#   r   r:   r   readFileNotFoundError
splitlineslenrc   r>   normpath)
rB   pidfiler   piddatalinespmpidportnumr   hostaddrhost_strr   r   r   r     sD   
z%Cluster._connection_addr_from_pidfilec                 C   s   d | _ t }zit|D ]V}| j d u r!|  }|d u r!td qz|tj	dddd|d| j }W n t
tjtjtjfyI   td Y q tjyS   Y  nw ||   W |  dS W |  dS W |  dS |  w )Nr   r   r   )r   r   rW   ri   r   r   )r@   asyncionew_event_loopranger   timesleeprun_until_completerl   rm   OSErrorTimeoutErrorCannotConnectNowErrorPostgresConnectionErrorPostgresErrorr   )rB   rW   ri   i	conn_specconr   r   r   re     sL   




zCluster._test_connectionc           
      C   s   t j|t jt jd}|j|j}}|jdkrtd|j|i }| D ]}|	d
d\}}}	|r>|	 ||  < q%|S )NrO   r   z%pg_config exited with status {:d}: {}utf-8=)rY   rZ   r[   rP   rQ   r\   r1   rb   r   ra   	partitionstriplower)
rB   r7   rf   rP   rQ   configliner   eqrx   r   r   r   r   !  s   

zCluster._run_pg_configc                 C   s   |d u r>t jdpt jd}|rtt j|d}n"t jdt j}|D ]}tt j|d}t j|r; nq(d }|sDt	dt j
|sQt	d||S )Nr8   r9   r   PATHz#could not find pg_config executablez{!r} is not an executable)r"   r,   r-   r	   r#   r   splitpathsepr]   r1   isfilerb   )rB   r7   
pg_installpathenvr#   r   r   r   r   3  s0   
zCluster._find_pg_configc                 C   s<   t tj| j|}tj|std|d| |S )Nzcould not find {} executable: z${!r} does not exist or is not a file)r	   r"   r#   r   r<   r  r1   rb   )rB   binarybpathr   r   r   r   O  s   zCluster._find_pg_binaryc                 C   s   t j| jdgt jt jd}|j|j}}|jdkr"td|j||	d
d}d}||s8td||t|d  }t|S )	Nz	--versionrO   r   z.postgres --version exited with status {:d}: {}r  z 
zpostgres (PostgreSQL) z,could not determine server version from {!r})rY   rZ   r   r[   rP   rQ   r\   r1   rb   ra   r  
startswithr   r   split_server_version_string)rB   rf   rP   rQ   version_stringr&   r   r   r   r   Y  s*   


zCluster._get_pg_versionr
   r   )r2   r3   r4   rD   rH   rK   rL   rh   rm   r}   r   r   r   r   r   rj   r   r   r   r   r   r   rX   r   re   r   r   r   r   r   r   r   r   r5   M   s:    
#_
$#
.%
r5   c                       s(   e Zd Zddddd fdd
Z  ZS )TempClusterNdata_dir_suffixdata_dir_prefixdata_dir_parentr7   c                   s&   t |||d| _t j| j|d d S )Nr/   r6   )r0   r:   superrD   )rB   r!  r"  r#  r7   	__class__r   r   rD   p  s
   zTempCluster.__init__)r2   r3   r4   rD   __classcell__r   r   r%  r   r  o  s    r  c                       sP   e Zd Zddddd fdd
Z fddZdd Zdi d
 fddZ  ZS )HotStandbyClusterNr   c                   s$   || _ || _t j||||d d S )Nr   )_master
_repl_userr$  rD   )rB   masterreplication_userr!  r"  r#  r7   r%  r   r   rD   z  s   
zHotStandbyCluster.__init__c                    s   t    | d| _d S )Npg_basebackup)r$  rX   r   _pg_basebackuprG   r%  r   r   rX     s   
zHotStandbyCluster._init_envc              
   K   s  |   dkrtd| jtj| jd| jd d| jd d| jd| jg	tj	tj
d	}|j}|jd
kr=td|j| | jdk ryttj| jdd }|tdj| jd | jd | jd W d   | S 1 spw   Y  | S ttj| jdd}|  | S )rp   rS   rq   z-hr   z-pr   rN   z-UrO   r   z.pg_basebackup init exited with status {:d}:
{}   r   zrecovery.confr   z                    standby_mode = 'on'
                    primary_conninfo = 'host={host} port={port} user={user}'
                r   r   r   Nzstandby.signal)rh   r1   rb   r:   rY   rZ   r.  r)  r*  r[   r   rP   r\   ra   rF   r   r"   r#   r   writetextwrapdedentr   )rB   r   rf   r   r   r   r   r   r}     sF   




zHotStandbyCluster.initr   r   c                   sP   | j dkr| }dj| jd | jd | jd|d< t jd||d| d S )	Nr/  z%"host={host} port={port} user={user}"r   r   r1  primary_conninfo)r   r   r   )rF   r   rb   r)  r*  r$  r   )rB   r   r   r   r%  r   r   r     s   
zHotStandbyCluster.startr  )r2   r3   r4   rD   rX   r}   r   r'  r   r   r%  r   r(  y  s    #r(  c                   @   sj   e Z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	dd Z
dd ZddddddZdS )RunningClusterc                 K   r   r
   )r	  r   r   r   r   rD     r   zRunningCluster.__init__c                 C   rJ   )NFr   rG   r   r   r   rK     r   zRunningCluster.is_managedc                 C   s
   t | jS r
   )r   r	  rG   r   r   r   rj     r   z"RunningCluster.get_connection_specc                 C   rJ   )Nr   r   rG   r   r   r   rh     r   zRunningCluster.get_statusc                 K      d S r
   r   )rB   r   r   r   r   r}     r   zRunningCluster.initr   c                 K   r7  r
   r   )rB   r   r   r   r   r   r     r   zRunningCluster.startc                 C   r7  r
   r   )rB   r   r   r   r   r     r   zRunningCluster.stopc                 C   r7  r
   r   rG   r   r   r   r     r   zRunningCluster.destroyc                 C      t dNz.cannot modify HBA records of unmanaged clusterr1   rG   r   r   r   r     s   zRunningCluster.reset_hbar   Nr   c                C   r8  r9  r:  )rB   r   r   r   r   r   r   r   r   r   r     s   zRunningCluster.add_hba_entryr  )r2   r3   r4   rD   rK   rj   rh   r}   r   r   r   r   r   r   r   r   r   r6    s    

r6  )NNN)r   r"   os.pathplatformr   r_   r   r   r   rY   r   r   r3  r   rl   r   unamesystemr+   r	   r   r)   r0   r   r1   r5   r  r(  r6  r   r   r   r   <module>   s@   




    &
B