
    sh                          S SK r S SKrS SKrS SKrS SKrS SKrS SKrS SKrS SKrS SK	J
r
JrJr   S SKr\R                  " \5      rS rSS\
\   4S jjr " S S5      rg! \ a     N4f = f)	    N)OptionalTextIOUnionc                     [         R                  " SS[         R                  [         R                  S9n U  HF  nUu  p#n  n [         R                   " X#U5      nUR	                  S5        UR                  S5        Us  $    [        S5      e! [         a)  nWR                  5         [        SU 35         SnAM  SnAff = f)a}  
Find a free port and binds a temporary socket to it so that the port can be "reserved" until used.

.. note:: the returned socket must be closed before using the port,
          otherwise a ``address already in use`` error will happen.
          The socket should be held and closed as close to the
          consumer of the port as possible since otherwise, there
          is a greater chance of race-condition where a different
          process may see the port as being free and take it.

Returns: a socket binded to the reserved free port

Usage::

sock = find_free_port()
port = sock.getsockname()[1]
sock.close()
use_port(port)
	localhostN)hostportfamilytype)r   r   r   z Socket creation attempt failed: zFailed to create a socket)
socketgetaddrinfo	AF_UNSPECSOCK_STREAMbindlistenOSErrorcloseprintRuntimeError)addrsaddrr
   r   proto_ses           ڄ/Users/tiagomarins/Projetos/claudeai/copy_bank/venv/lib/python3.13/site-packages/torch/distributed/elastic/rendezvous/etcd_server.pyfind_free_portr      s    ( tF,<,<6CUCUE $(!eQ	:fE2AFF#$HHQKH  2
33  	:GGI4QC899	:s   :B
B>B99B>data_dirc                 
   U (       aI  U R                   " 5       c7  [        R                  S5        U R                  " 5         U R                  " 5         U(       a,  [        R                  SU5        [
        R                  " USS9  g g )Nzstopping etcd serverzdeleting etcd data dir: %sTignore_errors)pollloggerinfo	terminatewaitshutilrmtree)
subprocessr   s     r   	stop_etcdr*   C   sY    joo'/*+0(;hd3     c            
           \ rS rSrSrSS\\   4S jjrS\R                  4S jr
S\4S jrS\4S	 jrS\4S
 jr   SS\S\S\\\S4   SS4S jjr SS\S\S\\\S4   SS4S jjrS rSS\SS4S jjrSS jrSrg)
EtcdServerN   aa  
.. note:: tested on etcd server v3.4.3.

Starts and stops a local standalone etcd server on a random free
port. Useful for single node, multi-worker launches or testing,
where a sidecar etcd server is more convenient than having to
separately setup an etcd server.

This class registers a termination handler to shutdown the etcd
subprocess on exit. This termination handler is NOT a substitute for
calling the ``stop()`` method.

The following fallback mechanism is used to find the etcd binary:

1. Uses env var TORCHELASTIC_ETCD_BINARY_PATH
2. Uses ``<this file root>/bin/etcd`` if one exists
3. Uses ``etcd`` from ``PATH``

Usage
::

 server = EtcdServer("/usr/bin/etcd", 2379, "/tmp/default.etcd")
 server.start()
 client = server.get_client()
 # use client
 server.stop()

Args:
    etcd_binary_path: path of etcd server binary (see above for fallback path)
Nr   c                    SU l         SU l        [        R                  R	                  [
        5      n[        R                  R                  US5      n[        R                  R                  SU5      U l	        [        R                  R                  U R                  5      (       d  SU l	        U(       a  UO[        R                  " SS9U l        S U l        S U l        g )Nr   zbin/etcdTORCHELASTIC_ETCD_BINARY_PATHetcdtorchelastic_etcd_data)prefix)_port_hostospathdirname__file__joinenvironget_etcd_binary_pathisfiletempfilemkdtemp_base_data_dir	_etcd_cmd
_etcd_proc)selfr   rootdefault_etcd_bins       r   __init__EtcdServer.__init__n   s    
 
wwx(77<<j9!#+-="
 ww~~d4455%+D" !Hh&6&6>V&W 	 6:r+   returnc                 R    U R                   (       d  [        S5      eU R                   $ )Nz>No etcd server process started. Call etcd_server.start() first)rD   r   rE   s    r   _get_etcd_server_process#EtcdServer._get_etcd_server_process   s%    P  ??"r+   c                     U R                   $ )z)Return the port the server is running on.)r5   rL   s    r   get_portEtcdServer.get_port       zzr+   c                     U R                   $ )z)Return the host the server is running on.)r6   rL   s    r   get_hostEtcdServer.get_host   rR   r+   c                 8    U R                    SU R                   3$ )z,Return the etcd server endpoint (host:port).:)r6   r5   rL   s    r   get_endpointEtcdServer.get_endpoint   s    **Qtzzl++r+   timeoutnum_retriesstderrc                    Sn  [         R                  R                  U R                  [	        U5      5      n[         R
                  " USS9  U R                  XQU5      $ ! [         ah  nUS-  n[        U R                  5        [        R                  S[	        U5      5        XB:  a   [        R                  " U R                  SS9  e  SnAOSnAff = fM  )a  
Start the server, and waits for it to be ready. When this function returns the sever is ready to take requests.

Args:
    timeout: time (in seconds) to wait for the server to be ready
        before giving up.
    num_retries: number of retries to start the server. Each retry
        will wait for max ``timeout`` before considering it as failed.
    stderr: the standard error file handle. Valid values are
        `subprocess.PIPE`, `subprocess.DEVNULL`, an existing file
        descriptor (a positive integer), an existing file object, and
        `None`.

Raises:
    TimeoutError: if the server is not ready within the specified timeout
r   T)exist_ok   z4Failed to start etcd server, got error: %s, retryingr    N)r7   r8   r;   rB   strmakedirs_start	Exceptionr*   rD   r#   warningr'   r(   atexitregister)rE   rZ   r[   r\   curr_retriesr   r   s          r   startEtcdServer.start   s    , 77<<(;(;S=NOHt4{{8f== !$//*JCPQF  .MM$"5"5TJ / s   AA 
C)ACCc                 @   [        5       n[        5       nUR                  5       S   U l        UR                  5       S   n[        R                  " SR                  U R                  SSUSSU R                   SU R                   3SSU R                   SU R                   3S	SU R                   SU 3/
5      5      n[        R                  S
U5        UR                  5         UR                  5         [        R                  " USUS9U l        U R                  U5        g )Nr_    z--enable-v2z
--data-dirz--listen-client-urlszhttp://rW   z--advertise-client-urlsz--listen-peer-urlszStarting etcd server: [%s]T)	close_fdsr\   )r   getsocknamer5   shlexsplitr;   r>   r6   r#   r$   r   r)   PopenrD   _wait_for_ready)rE   r   rZ   r\   sock	sock_peer	peer_portetcd_cmds           r   rb   EtcdServer._start   s    "$	%%'*
))+A.	;;HH**! *djj\4::,7-djj\4::,7(djj\9+6
" 	0(;

$**8tFSW%r+   c                 X    [         R                  " U R                  U R                  SSS9$ )zNReturn an etcd client object that can be used to make requests to this server./v2
   r   r	   version_prefixread_timeout)r2   Clientr6   r5   rL   s    r   
get_clientEtcdServer.get_client   s%    {{$**UQS
 	
r+   c                 (   [         R                  " U R                   U R                  SSS9n[        R                  " 5       U-   n[        R                  " 5       U:  ai  U R                  5       R                  5       b(  U R                  5       R                  n[        SU 35      e [        R                  SUR                  5        g [        S5      e! [         a    [        R                  " S5         Of = f[        R                  " 5       U:  a  M  NM)Nrx      rz   z*Etcd server process exited with the code: zetcd server ready. version: %sr_   z.Timed out waiting for etcd server to be ready!)r2   r}   r6   r5   timerM   r"   
returncoder   r#   r$   versionrc   sleepTimeoutError)rE   rZ   clientmax_timeexitcodes        r   rq   EtcdServer._wait_for_ready   s    JJ<tzz%VW
 99;(iikH$,,.335A88:EE"@
K <fnnM KLL  

1 iikH$s   & C  C54C5c                 n    [         R                  S5        [        U R                  U R                  5        g)zGStop the server and cleans up auto generated resources (e.g. data dir).zEtcdServer stop method calledN)r#   r$   r*   rD   rB   rL   s    r   stopEtcdServer.stop   s#    34$//4#6#67r+   )rB   r>   rC   rD   r6   r5   N)<      N)r   N)r   )rJ   N)__name__
__module____qualname____firstlineno____doc__r   r`   rH   r)   rp   rM   intrP   rT   rX   r   r   rh   rb   r~   rq   r   __static_attributes__ r+   r   r-   r-   N   s    >;# ;$#**:*: ## # ,c , +/	%I%I %I c64'(	%I
 
%IP TX&&&)&8=c64>O8P&	&@
Ms MD M(8r+   r-   r   )re   loggingr7   rn   r'   r   r)   r@   r   typingr   r   r   r2   ModuleNotFoundError	getLoggerr   r#   r   r`   r*   r-   r   r+   r   <module>r      sy      	       * *	
 
		8	$"4J4HSM 4j8 j8o  		s   A   A)(A)