o
    ci                     @   s  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 d dlmZm	Z	m
Z
mZmZmZmZmZmZ d dl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 edZeeZd	ee d
ee ee! f fddZ"d
ee#e$f fddZ%deded
efddZ&dee#ef fddZ'de	d
e$fddZ(		d%dee	g ef e	ee#ef gef f deee#ef  de
dee# de d
e	g ef fdd Z)G d!d" d"e j*Z+G d#d$ d$Z,dS )&    N)Path)	AnyCallableContextManagerDictListOptionalTupleTypeVarUnion)ActorHandle)StartTracebackStartTracebackWithWorkerRankfind_free_port)RayActorError)	ObjectRefTremote_valuesreturnc                 C   s   |   }t|dkr_t|\}}|D ]E}zt| W q tyB } z| |}td| d d|fW  Y d}~  S d}~w t	yX } z| |}t
|d|d}~ww t|dks
dS )a$  Check for actor failure when retrieving the remote values.

    Args:
        remote_values: List of object references from Ray actor methods.

    Returns:
        A tuple of (bool, Exception). The bool is
        True if evaluating all object references is successful, False otherwise.
    r   zWorker z has failed.FN)worker_rank)TN)copylenraywaitgetr   indexloggerinfo	Exceptionr   )r   
unfinishedfinished
object_refexcfailed_actor_rankfailed_worker_rank r%   M/home/ubuntu/.local/lib/python3.10/site-packages/ray/train/_internal/utils.pycheck_for_failure"   s,   

r'   c                  C   s   t j } t }| |fS )z4Returns the IP address and a free port on this node.)r   utilget_node_ip_addressr   )addrportr%   r%   r&   get_address_and_portH   s   
r,   pathparent_pathc                 C   s*   |    r|    S ||    S )zConstructs a path relative to a parent.

    Args:
        path: A relative or absolute path.
        parent_path: A relative path or absolute path.

    Returns: An absolute path.
    )
expanduseris_absoluteresolvejoinpath)r-   r.   r%   r%   r&   construct_pathP   s   	r3   env_varsc                 C   s"   dd |   D }tj| dS )zyUpdates the environment variables on this worker process.

    Args:
        env_vars: Environment variables to set.
    c                 S   s   i | ]	\}}|t |qS r%   )str).0kvr%   r%   r&   
<dictcomp>e   s    z#update_env_vars.<locals>.<dictcomp>N)itemsosenvironupdate)r4   	sanitizedr%   r%   r&   update_env_vars_   s   r?   fnc                    s<   t | j }t jjt jjt jjh t fdd|D S )a  Counts the number of required parameters of a function.

    NOTE: *args counts as 1 required parameter.

    Examples
    --------

    >>> def fn(a, b, /, c, *args, d=1, e=2, **kwargs):
    ...    pass
    >>> count_required_parameters(fn)
    4

    >>> fn = lambda: 1
    >>> count_required_parameters(fn)
    0

    >>> def fn(config, a, b=1, c=2):
    ...     pass
    >>> from functools import partial
    >>> count_required_parameters(partial(fn, a=0))
    1
    c                    s(   g | ]}|j tjjkr|j v r|qS r%   )defaultinspect	Parameteremptykind)r6   ppositional_param_kindsr%   r&   
<listcomp>   s
    z-count_required_parameters.<locals>.<listcomp>)	rB   	signature
parametersvaluesrC   POSITIONAL_ONLYPOSITIONAL_OR_KEYWORDVAR_POSITIONALr   )r@   paramsr%   rG   r&   count_required_parametersi   s   
rQ   
train_funcFconfigtrain_func_contextfn_arg_namediscard_returnsc           	         s   t }|rtfdd}|n|dkr&| d| d}t||dkrA du r0i n  t fdd}|S tfd	d}|S )
a  Validates and constructs the training function to execute.
    Args:
        train_func: The training function to execute.
            This can either take in no arguments or a ``config`` dict.
        config (Optional[Dict]): Configurations to pass into
            ``train_func``. If None then an empty Dict will be created.
        train_func_context: Context manager for user's `train_func`, which executes
            backend-specific logic before and after the training function.
        fn_arg_name (Optional[str]): The name of training function to use for error
            messages.
        discard_returns: Whether to discard any returns from train_func or not.
    Returns:
        A valid training function.
    Raises:
        ValueError: if the input ``train_func`` is invalid.
    c               
      s4   z
 | i | W d S  t y } zt|d }~ww Nr   r   )argskwargse)rR   r%   r&   discard_return_wrapper   s   z4construct_train_func.<locals>.discard_return_wrapper   z: should take in 0 or 1 required arguments, but it accepts z required arguments instead.Nc               
      sV   z   W  d    W S 1 sw   Y  W d S  t y* }  zt| d } ~ ww rW   rX   r[   )rS   rT   wrapped_train_funcr%   r&   train_fn   s   (z&construct_train_func.<locals>.train_fnc               
      sT   z    W  d    W S 1 sw   Y  W d S  t y) }  zt| d } ~ ww rW   rX   r^   )rT   r_   r%   r&   r`      s   ()rQ   	functoolswraps
ValueError)	rR   rS   rT   rU   rV   num_required_paramsr\   err_msgr`   r%   )rS   rR   rT   r_   r&   construct_train_func   s(   rf   c                       s$   e Zd ZdZi Z fddZ  ZS )	SingletonzSingleton Abstract Base Class

    https://stackoverflow.com/questions/33364070/implementing
    -singleton-as-metaclass-but-for-abstract-classes
    c                    s0   | | j vrtt| j|i || j | < | j |  S rW   )
_instancessuperrg   __call__)clsrY   rZ   	__class__r%   r&   rj      s   

zSingleton.__call__)__name__
__module____qualname____doc__rh   rj   __classcell__r%   r%   rl   r&   rg      s    rg   c                   @   s&   e Zd ZdZdefddZdd ZdS )ActorWrapperzDWraps an actor to provide same API as using the base class directly.actorc                 C   s
   || _ d S rW   )rt   )selfrt   r%   r%   r&   __init__   s   
zActorWrapper.__init__c                    s   t | j|  fddS )Nc                     s   t  j| i |S rW   )r   r   remote)rY   rZ   actor_methodr%   r&   <lambda>   s    z*ActorWrapper.__getattr__.<locals>.<lambda>)getattrrt   )ru   itemr%   rx   r&   __getattr__   s   zActorWrapper.__getattr__N)rn   ro   rp   rq   r   rv   r}   r%   r%   r%   r&   rs      s    rs   )rR   F)-abcra   rB   loggingr;   pathlibr   typingr   r   r   r   r   r   r	   r
   r   r   	ray.actorr   ray.air._internal.utilr   r   r   ray.exceptionsr   	ray.typesr   r   	getLoggerrn   r   boolr   r'   r5   intr,   r3   r?   rQ   rf   ABCMetarg   rs   r%   r%   r%   r&   <module>   sP    ,

&
+$

F