
    hS;                     @   d 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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 Z G d de      Z G d de      Z G d de      Z G d de      Z e        Z!d Z"d Z#d Z$d Z% ejL                  e%       y)z9Class to monitor a MongoDB server on a background thread.    N)PY3)commonperiodic_executor)NotMasterErrorOperationFailure_OperationCancelled)IsMaster)time)_shutdown_executors)MovingAverage)ServerDescription)_SrvResolverc                 <    t         rd| _        d| _        d| _        yy)z'PYTHON-2433 Clear error traceback info.N)r   __traceback____context__	__cause__errors    R/var/www/html/ranktracker/api/venv/lib/python3.12/site-packages/pymongo/monitor.py	_sanitizer   #   s!    
"      c                   2    e Zd Zd Zd Zd Zd ZddZd Zy)	MonitorBasec                     fd}t        j                  ||||      }|| _        dfd	}t        j                  | |j
                        t        j                  ||      | _        t        |        y)zBase class to do periodic work on a background thread.

        The 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>.target4   s    jGLLNr   )intervalmin_intervalr   nameNc                 :            }|r|j                          y y Ngc_safe_close)dummyr   r   s     r   _on_topology_gcz-MonitorBase.__init__.<locals>._on_topology_gcC   s      jG%%' r   r$   )	r   PeriodicExecutor	_executorweakrefrefcloseproxy	_topology	_register)	selftopologyr"   r    r!   r   executorr(   r   s	           @r   __init__zMonitorBase.__init__,   sc    	 %55%	 "	( ;;tX^^4 xA$r   c                 8    | j                   j                          y)z[Start monitoring, or restart after a fork.

        Multiple calls have no effect.
        N)r*   openr1   s    r   r6   zMonitorBase.openO   s    
 	r   c                 8    | j                   j                          y)zGC safe close.N)r*   r-   r7   s    r   r&   zMonitorBase.gc_safe_closeV   s    r   c                 $    | j                          y)zWClose and stop monitoring.

        open() restarts the monitor after closing.
        Nr%   r7   s    r   r-   zMonitorBase.closeZ   s    
 	r   Nc                 :    | j                   j                  |       y)zWait for the monitor to stop.N)r*   join)r1   timeouts     r   r;   zMonitorBase.joina   s    G$r   c                 8    | j                   j                          y)z)If the monitor is sleeping, wake it soon.N)r*   waker7   s    r   request_checkzMonitorBase.request_checke   s    r   r$   )	__name__
__module____qualname__r4   r6   r&   r-   r;   r?    r   r   r   r   +   s!    !F%r   r   c                   T     e Zd Z fdZd Zd Zd Zd Zd Zd Z	d Z
d	 Zd
 Z xZS )Monitorc                    t         t        |   |d|j                  t        j
                         || _        || _        || _        | j                  j                  j                  | _        | j                  du}|xr | j                  j                  | _        d| _        t        |||j!                  |j"                              | _        d| _        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)superrE   r4   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heartbeater)r1   server_descriptionr2   pooltopology_settingspub	__class__s         r   r4   zMonitor.__init__k   s     	gt%+11))		+
 $6 
*..66FFooT)L L L#'')J)J"***,-  r   c                 B    | j                   }|r|j                          yy)zCancel any concurrent isMaster check.

        Note: this is called from a weakref.proxy callback and MUST NOT take
        any locks.
        N)rS   cancel)r1   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)rW   r6   r*   _stoppedr-   r7   s    r   _start_rtt_monitorzMonitor._start_rtt_monitor   s:    
 	 >>""##% #r   c                     | j                   j                          | j                  j                          | j	                          y r$   )r*   r-   rW   r&   ra   r7   s    r   r&   zMonitor.gc_safe_close   s0    '')r   c                 x    | j                          | j                  j                          | j                          y r$   )r&   rW   r-   _reset_connectionr7   s    r   r-   zMonitor.close   s.    ! 	 r   c                 8    | j                   j                          y r$   )rL   resetr7   s    r   rg   zMonitor._reset_connection   s    

r   c                     	 | j                   }	 | j                         | _         | j                  j                  | j                   | j                   j                         | 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)rK   _check_serverr   r   r   rV   is_server_type_knownr*   
skip_sleepr/   	on_changer   topology_versionrd   ReferenceErrorr-   )r1   prev_sdexcs      r   r   zMonitor._run   s4   	..G+/+=+=+?( NN$$T%=%=040H0H0N0N % P ((==-->>'')))+''--'2N2N))+ 3O-+ ' 	#+<,,44C,A(// NN--/	0  	JJL	s;   E! C4 CE! 4	E=AEE! EE! !E=<E=c                    t               }	 	 | j                         S # t        t        f$ r:}| j                  j                  |j                  j                  d              d}~ww xY w# t        $ r  t        $ r}t        |       | j                  }|j                  }t               |z
  }| j                  r8|j                  xr |j                  }| j                   j#                  ||||       | j%                          t'        |t(              r | j*                  j-                          t/        ||      cY d}~S d}~ww xY w)zaCall isMaster or read the next streaming response.

        Returns a ServerDescription.
        z$clusterTimeNr   )_time_check_oncer   r   r/   receive_cluster_timedetailsgetrq   	Exceptionr   rK   rV   rR   rm   rp   rP   publish_server_heartbeat_failedrg   
isinstancer   rW   ri   r   )r1   startrs   r   sdrV   durationawaiteds           r   rl   zMonitor._check_server   s   
 	;''))$n5 33KKOON35	
  	 	;e))BjjGwH}}11Ib6I6I??Xug7""$%!45##%$WE::	;s3    A&5A!!A&&A) )E;B;D<6E<Ec                    | j                   j                  }| j                  r| j                  j	                  |       | j
                  r&| j
                  j                  r| j                          | j                  j                  i       5 }|j                  | _        | j                  |      \  }}|j                  s| j                  j                  |       t        ||| j                  j!                               }| j                  r(| j                  j#                  ||||j                         |cddd       S # 1 sw Y   yxY w)ziA single attempt to call ismaster.

        Returns a ServerDescription, or raises an exception.
        N)rK   rV   rR   rP    publish_server_heartbeat_startedrS   	cancelledrg   rL   
get_socketcancel_context_check_with_socket	awaitablerW   
add_sampler   average"publish_server_heartbeat_succeeded)r1   rV   	sock_inforesponseround_trip_timer~   s         r   rv   zMonitor._check_once   s   
 **22==OO<<WED$8$8$B$B""$ZZ""2& 	)#,#;#;D (,(?(?	(J%Ho%%!!,,_="7H#'#4#4#<#<#>@B}}BB_h8J8JL	 	 	s   B'D<<Ec                    | j                   j                         }t               }|j                  rt	        |j                         d      }ns|j                  rS| j                  j                  r=|j                  || j                  j                  | j                  j                  d      }n|j                  |ddd      }|t               |z
  fS )zfReturn (IsMaster, round_trip_time).

        Can raise ConnectionFailure or OperationFailure.
        T)r   N)r/   max_cluster_timeru   more_to_comer	   _next_replyperformed_handshakerK   rp   	_ismasterrM   rI   )r1   conncluster_timer}   r   s        r   r   zMonitor._check_with_socket	  s    
 ~~668 0 0 2dCH&&&&77~~((9922	H ~~lD$EH5((r   )r@   rA   rB   r4   ra   rd   r&   r-   rg   r   rl   rv   r   __classcell__r]   s   @r   rE   rE   j   s7     >&
!B;@0)r   rE   c                   *     e Zd Z fdZd Zd Z xZS )
SrvMonitorc                     t         t        |   |dt        j                  |j
                         || _        | j                  j                  | _        | j                  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)rH   r   r4   r   MIN_SRV_RESCAN_INTERVALrI   rM   _seeds	_seedlistfqdn_fqdn)r1   r2   r[   r]   s      r   r4   zSrvMonitor.__init__"  sW     	j$((**11		3
 +..^^((
r   c                     | j                         }|r.|| _        	 | j                  j                  | j                         y y # t        $ r | j                          Y y w xY wr$   )_get_seedlistr   r/   on_srv_updaterq   r-   )r1   seedlists     r   r   zSrvMonitor._run2  sT    %%'%DN,,T^^<  " 

s   %A AAc                 "   	 t        | 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   get_hosts_and_min_ttllenrz   r*   update_intervalmaxr   r   r?   )r1   r   ttls      r   r   zSrvMonitor._get_seedlist<  s    
	(4JJLMHc8}! " NN**C778:O  	
  	s   :A2 2BB)r@   rA   rB   r4   r   r   r   r   s   @r   r   r   !  s    ) r   r   c                   B     e Zd Z fdZd Zd Zd Zd Zd Zd Z	 xZ
S )rT   c                     t         t        |   |d|j                  t        j
                         || _        t               | _        t        j                         | _        y)z\Maintain round trip times for a server.

        The Topology is weakly referenced.
        pymongo_server_rtt_threadN)rH   rT   r4   rI   r   rJ   rL   r   _moving_average	threadingLock_lock)r1   r2   r[   rZ   r]   s       r   r4   z_RttMonitor.__init__T  sM    
 	k4)'11))		+ 
,^^%
r   c                 X    | j                          | j                  j                          y r$   )r&   rL   ri   r7   s    r   r-   z_RttMonitor.closec  s      	

r   c                 |    | j                   5  | j                  j                  |       ddd       y# 1 sw Y   yxY w)zAdd a RTT sample.N)r   r   r   )r1   samples     r   r   z_RttMonitor.add_samplei  s2    ZZ 	4  ++F3	4 	4 	4s   2;c                 z    | j                   5  | j                  j                         cddd       S # 1 sw Y   yxY w)z6Get the calculated average, or None if no samples yet.N)r   r   ry   r7   s    r   r   z_RttMonitor.averagen  s0    ZZ 	.''++-	. 	. 	.   1:c                 z    | j                   5  | j                  j                         cddd       S # 1 sw Y   yxY w)zReset the average RTT.N)r   r   ri   r7   s    r   ri   z_RttMonitor.resets  s0    ZZ 	0''--/	0 	0 	0r   c                     	 | j                         }| j                  |       y # t        $ r | j                          Y y t        $ r | j
                  j                          Y y w xY wr$   )_pingr   rq   r-   rz   rL   ri   )r1   rtts     r   r   z_RttMonitor._runx  sP    
	 **,COOC  	JJL 	JJ	s   !$ A$"A$#A$c                     | j                   j                  i       5 }| j                  j                  rt	        d      t               }|j                          t               |z
  cddd       S # 1 sw Y   yxY w)z-Run an "isMaster" command and return the RTT.z_RttMonitor closedN)rL   r   r*   rc   rz   ru   ismaster)r1   r   r}   s      r   r   z_RttMonitor._ping  s`    ZZ""2& 	#)~~&& 455GE 7U?	# 	# 	#s   AA..A7)r@   rA   rB   r4   r-   r   r   ri   r   r   r   r   s   @r   rT   rT   S  s&    &4
.
0
#r   rT   c                 b    t        j                  | t              }t        j	                  |       y r$   )r+   r,   _unregister	_MONITORSadd)r   r,   s     r   r0   r0     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&   )monitorsr,   r   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   )'__doc__atexitr   r+   bson.py3compatr   pymongor   r   pymongo.errorsr   r   r   pymongo.ismasterr	   pymongo.monotonicr
   ru   pymongo.periodic_executorr   pymongo.read_preferencesr   pymongo.server_descriptionr   pymongo.srv_resolverr   r   objectr   rE   r   rT   setr   r0   r   r   r   registerrC   r   r   <module>r      s    @     -1 1 & + 9 2 8 -<& <~t)k t)n/ /d9#+ 9#~ E	
"  # $r   