
    l8'hL                       d Z ddlmZ ddlZddlZddlZddlZddlmZ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mZmZ ddl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) erddl*m+Z+m,Z,m-Z- ddl.m/Z/ ddl0m1Z1 dZ2d#dZ3d$dZ4 G d d      Z5 G d de5      Z6 G d de5      Z7 G d de5      Z8 e9       Z:d%dZ;d&d Z<d'd!Z=d'd"Z> ej~                  e>       y)(z9Class to monitor a MongoDB server on a background thread.    )annotationsN)TYPE_CHECKINGAnyMappingOptionalcast)common)MovingMinimum)NetworkTimeoutNotPrimaryErrorOperationFailure_OperationCancelled)Hello)_create_lock)_SDAM_LOGGER
_debug_log_SDAMStatusMessage)_is_faas)MovingAverage)ServerDescription)_SrvResolver)periodic_executor)_shutdown_executors)
ConnectionPool_CancellationContext)TopologySettings)TopologyTc                .    d| _         d| _        d| _        y)z'PYTHON-2433 Clear error traceback info.N)__traceback____context__	__cause__errors    W/var/www/html/trade_iq/venv/lib/python3.12/site-packages/pymongo/synchronous/monitor.py	_sanitizer&   .   s    EEEO    c                D    t        dt        j                         | z
        S )zReturn the duration since the given start time.

    Accounts for buggy platforms where time.monotonic() is not monotonic.
    See PYTHON-4600.
    g        )maxtime	monotonic)starts    r%   _monotonic_durationr-   5   s     sDNN$u,--r'   c                  >    e Zd ZddZd	dZd	dZd	dZd
ddZd	dZy)MonitorBasec                    dfd}t        j                  ||||      }|| _        ddfd}t        j                  | |j
                        t        j                  ||      | _        t        |        y)zBase class to do periodic work on a background thread.

        The background thread is signaled to stop when the Topology or
        this instance is freed.
        c                 :            } | y| j                          y)NFT)_run)monitorself_refs    r%   targetz$MonitorBase.__init__.<locals>.targetH   s    jGLLNr'   )intervalmin_intervalr5   nameNc                :            }|r|j                          y y Ngc_safe_close)dummyr3   r4   s     r%   _on_topology_gcz-MonitorBase.__init__.<locals>._on_topology_gcU   s      jG%%' r'   )returnboolr:   )r=   zOptional[Topology]r?   None)	r   PeriodicExecutor	_executorweakrefrefcloseproxy	_topology	_register)	selftopologyr8   r6   r7   r5   executorr>   r4   s	           @r%   __init__zMonitorBase.__init__?   s`    	 %55Ld
 "	( ;;tX^^4 xA$r'   c                8    | j                   j                          y)z[Start monitoring, or restart after a fork.

        Multiple calls have no effect.
        N)rC   openrJ   s    r%   rO   zMonitorBase.opena   s    
 	r'   c                8    | j                   j                          y)zGC safe close.N)rC   rF   rP   s    r%   r<   zMonitorBase.gc_safe_closeh   s    r'   c                $    | j                          y)zWClose and stop monitoring.

        open() restarts the monitor after closing.
        Nr;   rP   s    r%   rF   zMonitorBase.closel   s    
 	r'   Nc                :    | j                   j                  |       y)zWait for the monitor to stop.N)rC   join)rJ   timeouts     r%   rT   zMonitorBase.joins   s    G$r'   c                8    | j                   j                          y)z)If the monitor is sleeping, wake it soon.N)rC   wakerP   s    r%   request_checkzMonitorBase.request_checkw   s    r'   )rK   r   r8   strr6   intr7   floatr?   rA   r:   )rU   zOptional[int]r?   rA   )	__name__
__module____qualname__rM   rO   r<   rF   rT   rX    r'   r%   r/   r/   >   s!     D%r'   r/   c                  x     e Zd Z	 	 	 	 	 	 	 	 d f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	Zdd
Z xZS )Monitorc                   t         |   |d|j                  t        j                         || _        || _        || _        | j                  j                  j                  | _
        | j                  duxr | j                  j                  | _        d| _        t        |||j                  |j                               | _        |j$                  dk(  rd| _        y|j$                  dk(  rd| _        yt)                | _        y)a   Class to monitor a MongoDB server on a background thread.

        Pass an initial ServerDescription, a Topology, a Pool, and
        TopologySettings.

        The Topology is weakly referenced. The Pool must be exclusive to this
        Monitor.
        pymongo_server_monitor_threadNstreamTpollF)superrM   heartbeat_frequencyr	   MIN_HEARTBEAT_INTERVAL_server_description_pool	_settings_pool_options_event_listeners
_listenersenabled_for_server_heartbeat_publish_cancel_context_RttMonitor_create_pool_for_monitoraddress_rtt_monitorserver_monitoring_mode_streamr   )rJ   server_descriptionrK   pooltopology_settings	__class__s        r%   rM   zMonitor.__init__}   s     	+11))		
 $6 
*..66GGt3d8d8d?C'--.@.H.HI

 33x?DL55? DL'z>DLr'   c                B    | j                   }|r|j                          yy)zCancel any concurrent hello check.

        Note: this is called from a weakref.proxy callback and MUST NOT take
        any locks.
        N)rr   cancel)rJ   contexts     r%   cancel_checkzMonitor.cancel_check   s#     && NN	 r'   c                    | j                   j                          | j                  j                  r| j                   j	                          yy)z1Start an _RttMonitor that periodically runs ping.N)rv   rO   rC   _stoppedrF   rP   s    r%   _start_rtt_monitorzMonitor._start_rtt_monitor   s:    
 	 >>""##% #r'   c                    | j                   j                          | j                  j                          | j	                          y r:   )rC   rF   rv   r<   r   rP   s    r%   r<   zMonitor.gc_safe_close   s0    '')r'   c                x    | j                          | j                  j                          | j                          y r:   )r<   rv   rF   _reset_connectionrP   s    r%   rF   zMonitor.close   s.    ! 	 r'   c                8    | j                   j                          y r:   )rk   resetrP   s    r%   r   zMonitor._reset_connection   s    

r'   c                ^   	 | j                   }	 | j                         | _         | j                  j                  | j                   | j                   j                  t        | j                   j                  t                     | j                  rV| j                   j                  r@| j                   j                  r*| j!                          | j                  j                          | j                   j                  r(|j                  r| j                  j                          y y y # t        $ ra}t        |       t	        | j                   j
                  |      | _         |j                  r| j                  j                          Y d }~y d }~ww xY w# t"        $ r | j%                          Y y w xY w)Nr#   )
reset_poolinterrupt_connections)rj   _check_serverr   r&   r   ru   is_server_type_knownrC   
skip_sleeprH   	on_changer$   
isinstancer   rx   topology_versionr   ReferenceErrorrF   )rJ   prev_sdexcs      r%   r2   zMonitor._run   sS   $	..G+/+=+=+?( NN$$((3399&01I1I1O1OQ_&` %  ||((==,,=='')))+''--'2N2N))+ 3O-7 ' 
#+<,,44C,( // NN--/
<  	JJL	s;   F D# C<F #	F,AFF FF F,+F,c                   t        j                         }	 	 | j                         S # t        t        f$ rW}t        t        t        t        f   |j                        }| j                  j                  |j                  d              d}~ww xY w# t        $ r  t        $ rN}t        |       | j                   }|j"                  }t%        |      }t'        | j(                  xr |j*                  xr |j,                        }| j.                  r,| j0                  J | j0                  j3                  ||||       t5        j6                  t8        j:                        rBt=        t4        | j                  j>                  |d   |d   ||dz  |t@        jB                         | jE                          tG        |tH              r | jJ                  jM                          tO        ||      cY d}~S d}~ww xY w)z^Call hello or read the next streaming response.

        Returns a ServerDescription.
        z$clusterTimeNr        )
topologyId
serverHost
serverPortawaited
durationMSfailuremessager#   )(r*   r+   _check_oncer   r   r   r   rY   r   detailsrH   receive_cluster_timegetr   	Exceptionr&   rj   ru   r-   r@   rx   r   r   rq   ro   publish_server_heartbeat_failedr   isEnabledForloggingDEBUGr   _topology_idr   HEARTBEAT_FAILr   r   r   rv   r   r   )	rJ   r,   r   r   r$   sdru   durationr   s	            r%   r   zMonitor._check_server   s   
  #	;''))$o6 wsCx0#++>33GKK4OP	
  	 	;e))BjjG*51H4<<[B,C,C[H[H[\G}}222??SXZab((7 #~~::&qz&qz#'$!.==	 ""$%!45##%$WE::3	;s4   ' BABBB G1#EG,&G1,G1c                v   | j                   j                  }| j                   }t        | j                  j                  xr( | j
                  xr |j                  xr |j                        }| j                  r*| j                  J | j                  j                  ||       | j                  r&| j                  j                  r| j                          | j                  j                         5 }t        j                   t"        j$                        rSt'        t        | j(                  j*                  |j,                  |j.                  |d   |d   |t0        j2                         |j4                  | _        | j7                  |      \  }}|j8                  s| j:                  j=                  |       | j:                  j?                         \  }}tA        ||||      }| j                  r6| j                  J | j                  jC                  ||||j8                         t        j                   t"        j$                        rbt'        t        | j(                  j*                  |j,                  |j.                  |d   |d   ||dz  |jD                  t0        jF                  
       |cddd       S # 1 sw Y   yxY w)zfA single attempt to call hello.

        Returns a ServerDescription, or raises an exception.
        Nr   r   )r   driverConnectionIdserverConnectionIdr   r   r   r   )min_round_trip_timer   )	r   r   r   r   r   r   r   replyr   )$rj   ru   r@   rk   connsrx   r   r   rq   ro    publish_server_heartbeat_startedrr   	cancelledr   checkoutr   r   r   r   r   rH   r   idserver_connection_idr   HEARTBEAT_STARTcancel_context_check_with_socket	awaitablerv   
add_sampler   r   "publish_server_heartbeat_succeededdocumentHEARTBEAT_SUCCESS)	rJ   ru   r   r   connresponseround_trip_timeavg_rttmin_rtts	            r%   r   zMonitor._check_once  s4   
 **22%% JJaa"2I2IabNaNa
 ==??...OO<<WgND$8$8$B$B""$ZZ  " &	d((7 #~~::'+ww'+'@'@&qz&qz#.>>	 $(#6#6D (,(?(?(E%Ho%%!!,,_=#00446GW"7HgSZ[B}}222BB_h8J8J ((7 #~~::'+ww'+'@'@&qz&qz#.5"++.@@ M&	 &	 &	s   .F7J//J8c                   | j                   j                         }t        j                         }|j                  rt        |j                         d      }n}| j                  r^|j                  rR| j                  j                  r<|j                  || j                  j                  | j                  j                        }n|j                  |dd      }t        |      }||fS )zcReturn (Hello, round_trip_time).

        Can raise ConnectionFailure or OperationFailure.
        T)r   N)rH   max_cluster_timer*   r+   more_to_comer   _next_replyrx   performed_handshakerj   r   _hellorl   rh   r-   )rJ   r   cluster_timer,   r   r   s         r%   r   zMonitor._check_with_socketW  s    
 ~~668 T--/4@HLLT55$:R:R:c:c {{((9922H {{<t<H&u-!!r'   )ry   r   rK   r   rz   r   r{   r   r\   )r?   r   )r   r   r?   ztuple[Hello, float])r]   r^   r_   rM   r   r   r<   rF   r   r2   r   r   r   __classcell__r|   s   @r%   rb   rb   |   s_    %*-%* %* 	%*
 ,%*N&
!%N);V9v"r'   rb   c                  0     e Zd Zd fdZddZddZ xZS )
SrvMonitorc                R   t         |   |dt        j                  |j                         || _        | j
                  j                  | _        t        | j
                  j                  t              sJ | j
                  j                  | _        t        j                         | _        y)zClass to poll SRV records on a background thread.

        Pass a Topology and a TopologySettings.

        The Topology is weakly referenced.
        pymongo_srv_polling_threadN)rg   rM   r	   MIN_SRV_RESCAN_INTERVALrh   rl   _seeds	_seedlistr   fqdnrY   _fqdnr*   r+   _startup_time)rJ   rK   r{   r|   s      r%   rM   zSrvMonitor.__init__r  s~     	(**11		
 +..$..--s333..--
!^^-r'   c                (   t        j                         | j                  t        j                  z   k  ry | j                         }|r.|| _        	 | j                  j                  | j                         y y # t        $ r | j                          Y y w xY wr:   )r*   r+   r   r	   r   _get_seedlistr   rH   on_srv_updater   rF   )rJ   seedlists     r%   r2   zSrvMonitor._run  sw    >>d0063Q3QQQ%%'%DN,,T^^<  " 

s   %A5 5BBc                   	 t        | j                  | j                  j                  j                  | j                  j
                        }|j                         \  }}t        |      dk(  rt        	 | j                  j                  t        |t        j                               |S # t        $ r | j                          Y yw xY w)zXPoll SRV records for a seedlist.

        Returns a list of ServerDescriptions.
        r   N)r   r   rl   pool_optionsconnect_timeoutsrv_service_nameget_hosts_and_min_ttllenr   rC   update_intervalr)   r	   r   rX   )rJ   resolverr   ttls       r%   r   zSrvMonitor._get_seedlist  s    
	#

++;;//H
 %::<MHc8}! " NN**3sF4R4R+STO  	
  	s   A0B( (CC)rK   r   r{   r   r\   )r?   zOptional[list[tuple[str, Any]]])r]   r^   r_   rM   r2   r   r   r   s   @r%   r   r   q  s    .&r'   r   c                  P     e Zd Zd fdZd	dZd
dZddZd	dZd	dZddZ	 xZ
S )rs   c                    t         |   |d|j                  t        j                         || _        t               | _        t               | _	        t               | _        y)z\Maintain round trip times for a server.

        The Topology is weakly referenced.
        pymongo_server_rtt_threadN)rg   rM   rh   r	   ri   rk   r   _moving_averager
   _moving_minr   _lock)rJ   rK   r{   rz   r|   s       r%   rM   z_RttMonitor.__init__  sP    
 	'11))		
 
,(?!^
r'   c                X    | j                          | j                  j                          y r:   )r<   rk   r   rP   s    r%   rF   z_RttMonitor.close  s      	

r'   c                    | j                   5  | j                  j                  |       | j                  j                  |       ddd       y# 1 sw Y   yxY w)zAdd a RTT sample.N)r   r   r   r   )rJ   samples     r%   r   z_RttMonitor.add_sample  sF    ZZ 	0  ++F3''/	0 	0 	0s   7AAc                    | j                   5  | j                  j                         | j                  j                         fcddd       S # 1 sw Y   yxY w)zBGet the calculated average, or None if no samples yet and the min.N)r   r   r   r   rP   s    r%   r   z_RttMonitor.get  sH    ZZ 	F''++-t/?/?/C/C/EE	F 	F 	Fs   4AAc                    | j                   5  | j                  j                          | j                  j                          ddd       y# 1 sw Y   yxY w)zReset the average RTT.N)r   r   r   r   rP   s    r%   r   z_RttMonitor.reset  sB    ZZ 	%  &&(""$	% 	% 	%s   5AAc                    	 | j                         }| j                  |       y # t        $ r | j                          Y y t        $ r | j
                  j                          Y y w xY wr:   )_pingr   r   rF   r   rk   r   )rJ   rtts     r%   r2   z_RttMonitor._run  sP    
	 **,COOC  	JJL 	JJ	s   !$ A$"A$#A$c                   | j                   j                         5 }| j                  j                  rt	        d      t        j                         }|j                          t        |      cddd       S # 1 sw Y   yxY w)z)Run a "hello" command and return the RTT.z_RttMonitor closedN)	rk   r   rC   r   r   r*   r+   hellor-   )rJ   r   r,   s      r%   r   z_RttMonitor._ping  s_    ZZ  " 	.d~~&& 455NN$EJJL&u-	. 	. 	.s   AA55A>)rK   r   r{   r   rz   r   r\   )r   r[   r?   rA   )r?   ztuple[Optional[float], float])r?   r[   )r]   r^   r_   rM   rF   r   r   r   r2   r   r   r   s   @r%   rs   rs     s'    $"0F
%.r'   rs   c                b    t        j                  | t              }t        j	                  |       y r:   )rD   rE   _unregister	_MONITORSadd)r3   rE   s     r%   rI   rI     s    
++g{
+CMM#r'   c                .    t         j                  |        y r:   )r   remove)monitor_refs    r%   r   r     s    [!r'   c                 v    t         y t        t               } | D ]  } |       }|s|j                           d }y r:   )r   listr<   )monitorsrE   r3   s      r%   _shutdown_monitorsr     sD     IH  $%!!#$
 Gr'   c                 B    t         } | r |         t        } | r |         y y r:   )r   r   )shutdowns    r%   _shutdown_resourcesr    s!    !H
"H
 r'   )r$   r   r?   rA   )r,   r[   r?   r[   )r3   r/   r?   rA   )r   z"weakref.ReferenceType[MonitorBase]r?   rA   r\   )@__doc__
__future__r   atexitr   r*   rD   typingr   r   r   r   r   pymongor	   pymongo._csotr
   pymongo.errorsr   r   r   r   pymongo.hellor   pymongo.lockr   pymongo.loggerr   r   r   pymongo.pool_optionsr   pymongo.read_preferencesr   pymongo.server_descriptionr   pymongo.srv_resolverr   pymongo.synchronousr   %pymongo.synchronous.periodic_executorr   pymongo.synchronous.poolr   r   r   pymongo.synchronous.settingsr   pymongo.synchronous.topologyr   _IS_SYNCr&   r-   r/   rb   r   rs   setr   rI   r   r   r  registerr`   r'   r%   <module>r     s    @ "     > >  ' a a  % G G ) 2 8 - 1 EOO=5.; ;|r"k r"j9 9x=.+ =.F E	
"  # $r'   