
    1Vh?                     j   d 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 ddlmZ ddlmZ  ej                   d       G d d	             Zd
 Zd Zd Zd Zd Zd Zd Zd Zd Z ej                   d       G d d             Z ej                   d       G d d             Z ej                   d       G d d             Z ej                   d       G d d             Z ej                   d       G d d             Z ej@                  d      fdZ!d  Z"d! Z#y)"z>Private utilities for managing multiple TensorBoard processes.    N)Optional)version)
tb_loggingT)frozenc                   b    e Zd ZU dZeed<   eed<   eed<   eed<   eed<   eed<   eed<   eed	<   y
)TensorBoardInfoa  Holds the information about a running TensorBoard instance.

    Attributes:
      version: Version of the running TensorBoard.
      start_time: Seconds since epoch.
      pid: ID of the process running TensorBoard.
      port: Port on which TensorBoard is running.
      path_prefix: Relative prefix to the path, may be empty.
      logdir: Data location used by the TensorBoard server, may be empty.
      db: Database connection used by the TensorBoard server, may be empty.
      cache_key: Opaque, as given by `cache_key` below.
    r   
start_timepidportpath_prefixlogdirdb	cache_keyN)__name__
__module____qualname____doc__str__annotations__int     C/home/dcms/DCMS/lib/python3.12/site-packages/tensorboard/manager.pyr   r   #   s2     LO	H
IKGNr   r   c                 V    | j                   rd| j                   z  S d| j                  z  S )zFormat the data location for the given TensorBoardInfo.

    Args:
      info: A TensorBoardInfo value.

    Returns:
      A human-readable string describing the logdir or database connection
      used by the server: e.g., "logdir /tmp/logs".
    zdb %sz	logdir %s)r   r   infos    r   data_source_from_infor   <   s)     ww  T[[((r   c                    t        j                  t              }|j                         D ]9  \  }}t	        t        | |      |      rt        d|d|dt        | |             | j                  t        j                  k7  r)t        dt        j                  d| j                        t        j                  |       }t        j                  |dd      S )a  Convert a `TensorBoardInfo` to string form to be stored on disk.

    The format returned by this function is opaque and should only be
    interpreted by `_info_from_string`.

    Args:
      info: A valid `TensorBoardInfo` object.

    Raises:
      ValueError: If any field on `info` is not of the correct type.

    Returns:
      A string representation of the provided `TensorBoardInfo`.
    	expected 	 of type , but found: zexpected 'version' to be T   )	sort_keysindent)typingget_type_hintsr   items
isinstancegetattr
ValueErrorr   VERSIONdataclassesasdictjsondumps)r   field_name_to_typekey
field_type
json_values        r   _info_to_stringr4   L   s      ..?-335 Z'$,j9
GD#$68  ||w&.
 	
 ##D)J::jD;;r   c           
         t        j                  t              }	 t        j                  |       }t        |t              st        d|      t        |j                               }t        |      }||z
  }|rt        dt        |            i }|j                         D ]3  \  }}t        ||   |      st        d|d|d||         ||   ||<   5 t        di |S # t
        $ r t        d|       w xY w)a  Parse a `TensorBoardInfo` object from its string representation.

    Args:
      info_string: A string representation of a `TensorBoardInfo`, as
        produced by a previous call to `_info_to_string`.

    Returns:
      A `TensorBoardInfo` value.

    Raises:
      ValueError: If the provided string is not valid JSON, or if it is
        missing any required fields, or if any field is of incorrect type.
    zinvalid JSON: znot a JSON object: zTensorBoardInfo missing keys: r   r    r!   r   )r%   r&   r   r.   loadsr*   r(   dict	frozensetkeyssortedr'   )	info_stringr0   r3   expected_keysactual_keysmissing_keysfieldsr1   r2   s	            r   _info_from_stringr@   k   s     ..?>ZZ,
 j$'J@AA05578MJ'K ;.L282FH
 	
 F-335 &Z*S/:6
JsO5  !os& $V$$/  >{<==>s   C# #C;c                     t        |t        t        f      st        d|d      | ||d}t	        j
                  t        j                  |dd      j                  d            }t        |j                  d            S )	a  Compute a `TensorBoardInfo.cache_key` field.

    The format returned by this function is opaque. Clients may only
    inspect it by comparing it for equality with other results from this
    function.

    Args:
      working_directory: The directory from which TensorBoard was launched
        and relative to which paths like `--logdir` and `--db` are
        resolved.
      arguments: The command-line args to TensorBoard, as `sys.argv[1:]`.
        Should be a list (or tuple), not an unparsed string. If you have a
        raw shell command, use `shlex.split` before passing it to this
        function.
      configure_kwargs: A dictionary of additional argument values to
        override the textual `arguments`, with the same semantics as in
        `tensorboard.program.TensorBoard.configure`. May be an empty
        dictionary.

    Returns:
      A string such that if two (prospective or actual) TensorBoard
      invocations have the same cache key then it is safe to use one in
      place of the other. The converse is not guaranteed: it is often safe
      to change the order of TensorBoard arguments, or to explicitly set
      them to their default values, or to move them between `arguments`
      and `configure_kwargs`, but such invocations may yield distinct
      cache keys.
    z6'arguments' should be a list of arguments, but found: z& (use `shlex.split` if given a string)working_directory	argumentsconfigure_kwargsT),:)r#   
separatorszutf-8ascii)r(   listtuple	TypeErrorbase64	b64encoder.   r/   encoder   decode)rC   rD   rE   datumraws        r   r   r      s}    : i$/7@C
 	

 /,E
 



5DZ@GGPC
 szz'"##r   c                  l   t         j                  j                  t        j                         d      } 	 t        j
                  |        t        j                  | d       | S # t        $ rI}|j                  t        j                  k(  r t         j                  j                  |       rn Y d}~| S d}~ww xY w)aE  Get path to directory in which to store info files.

    The directory returned by this function is "owned" by this module. If
    the contents of the directory are modified other than via the public
    functions of this module, subsequent behavior is undefined.

    The directory will be created if it does not exist.
    z.tensorboard-infoi  N)ospathjointempfile
gettempdirmakedirschmodOSErrorerrnoEEXISTisdir)rU   es     r   _get_info_dirr`      s     77<<++-/BCD
D 	uK  77ell"rww}}T': 
 Ks   A! !	B3*>B..B3c                  |    t         j                  j                  t               dt        j                         z        S )zGet path to info file for the current process.

    As with `_get_info_dir`, the info directory will be created if it
    does not exist.
    zpid-%d.info)rT   rU   rV   r`   getpidr   r   r   _get_info_file_pathrc      s&     77<<)DEEr   c                     dt        |       z  }t        t               d      5 }|j                  |       ddd       y# 1 sw Y   yxY w)aY  Write TensorBoardInfo to the current process's info file.

    This should be called by `main` once the server is ready. When the
    server shuts down, `remove_info_file` should be called.

    Args:
      tensorboard_info: A valid `TensorBoardInfo` object.

    Raises:
      ValueError: If any field on `info` is not of the correct type.
    z%s
wN)r4   openrc   write)tensorboard_infopayloadoutfiles      r   write_info_filerk      sE     '788G	!#S	) Wg  s	   >Ac                      	 t        j                  t                      y# t        $ r)} | j                  t        j
                  k(  rn Y d} ~ yd} ~ ww xY w)zRemove the current process's TensorBoardInfo file, if it exists.

    If the file does not exist, no action is taken and no error is
    raised.
    N)rT   unlinkrc   r[   r\   ENOENT)r_   s    r   remove_info_filero      sD    
		%'( 77ell"  	s     	AAAc                      t               } g }t        j                  |       D ]d  }t        j                  j	                  | |      }	 t        |      5 }|j                         }ddd       	 t              }|j                  |       f |S # 1 sw Y   *xY w# t        $ r(}|j                  t        j                  k(  rY d}~ d}~ww xY w# t        $ r) t        j                         j                  d|d       Y w xY w)aF  Return TensorBoardInfo values for running TensorBoard processes.

    This function may not provide a perfect snapshot of the set of running
    processes. Its result set may be incomplete if the user has cleaned
    their /tmp/ directory while TensorBoard processes are running. It may
    contain extraneous entries if TensorBoard processes exited uncleanly
    (e.g., with SIGKILL or SIGQUIT).

    Entries in the info directory that do not represent valid
    `TensorBoardInfo` values will be silently ignored.

    Returns:
      A fresh list of `TensorBoardInfo` objects.
    Nzinvalid info file: %rT)exc_info)r`   rT   listdirrU   rV   rf   readIOErrorr\   EACCESr@   appendr*   r   
get_loggerdebug)info_dirresultsfilenamefilepathinfilecontentsr_   r   s           r   get_allr     s     HGJJx( !77<<(3		h )6!;;=)
	!$X.D NN4 -!. N)) ) 	ww%,,& 	  	!!#))' * 	sH   BB"B+CB	B	C CCC/C=<C=c                       e Zd ZU dZeed<   y)StartReuseda  Possible return value of the `start` function.

    Indicates that a call to `start` was compatible with an existing
    TensorBoard process, which can be reused according to the provided
    info.

    Attributes:
      info: A `TensorBoardInfo` object.
    r   Nr   r   r   r   r   r   r   r   r   r   r   1  s     r   r   c                       e Zd ZU dZeed<   y)StartLaunchedzPossible return value of the `start` function.

    Indicates that a call to `start` successfully launched a new
    TensorBoard process, which is available with the provided info.

    Attributes:
      info: A `TensorBoardInfo` object.
    r   Nr   r   r   r   r   r   @  s     r   r   c                   <    e Zd ZU dZeed<   ee   ed<   ee   ed<   y)StartFailedaT  Possible return value of the `start` function.

    Indicates that a call to `start` tried to launch a new TensorBoard
    instance, but the subprocess exited with the given exit code and
    output streams. (If the contents of the output streams are no longer
    available---e.g., because the user has emptied /tmp/---then the
    corresponding values will be `None`.)

    Attributes:
      exit_code: As `Popen.returncode` (negative for signal).
      stdout: Error message to stdout if the stream could not be read.
      stderr: Error message to stderr if the stream could not be read.
    	exit_codestdoutstderrN)r   r   r   r   r   r   r   r   r   r   r   r   r   N  s"     NSMSMr   r   c                   ,    e Zd ZU dZeed<   ee   ed<   y)StartExecFaileda  Possible return value of the `start` function.

    Indicates that a call to `start` failed to invoke the subprocess.

    Attributes:
      os_error: `OSError` due to `Popen` invocation.
      explicit_binary: If the TensorBoard executable was chosen via the
        `TENSORBOARD_BINARY` environment variable, then this field contains
        the path to that binary; otherwise `None`.
    os_errorexplicit_binaryN)r   r   r   r   r[   r   r   r   r   r   r   r   r   c  s    	 c]"r   r   c                       e Zd ZU dZeed<   y)StartTimedOuta\  Possible return value of the `start` function.

    Indicates that a call to `start` launched a TensorBoard process, but
    that process neither exited nor wrote its info file within the allowed
    timeout period. The process may still be running under the included
    PID.

    Attributes:
      pid: ID of the process running TensorBoard.
    r
   N)r   r   r   r   r   r   r   r   r   r   r   t  s    	 
Hr   r   <   )secondsc                 D   t        t        j                         | i       }t        |      }|rt	        |      S t        j                  d      \  }}t        j                  d      \  }}t        j                         }t        j                  j                  dd      }		 t        j                  |	dn|	g| z   ||	      }
	 t        j                  |       t        j                  |       d}||j                         z   }t        j                         |k  rxt        j                   |       |
j#                         }| t%        |t'        |      t'        |            S t        |      }|rt)        |      S t        j                         |k  rxt+        |
j,                        S # t        $ rA}t        ||	
      cY d}~t        j                  |       t        j                  |       S d}~ww xY w# t        j                  |       t        j                  |       w xY w)a  Start a new TensorBoard instance, or reuse a compatible one.

    If the cache key determined by the provided arguments and the current
    working directory (see `cache_key`) matches the cache key of a running
    TensorBoard process (see `get_all`), that process will be reused.

    Otherwise, a new TensorBoard process will be spawned with the provided
    arguments, using the `tensorboard` binary from the system path.

    Args:
      arguments: List of strings to be passed as arguments to
        `tensorboard`. (If you have a raw command-line string, see
        `shlex.split`.)
      timeout: `datetime.timedelta` object describing how long to wait for
        the subprocess to initialize a TensorBoard server and write its
        `TensorBoardInfo` file. If the info file is not written within
        this time period, `start` will assume that the subprocess is stuck
        in a bad state, and will give up on waiting for it and return a
        `StartTimedOut` result. Note that in such a case the subprocess
        will not be killed. Default value is 60 seconds.

    Returns:
      A `StartReused`, `StartLaunched`, `StartFailed`, or `StartTimedOut`
      object.
    rB   r   z.tensorboard-stdout-)prefixz.tensorboard-stderr-TENSORBOARD_BINARYNtensorboard)r   r   )r   r   g      ?)r   r   r   )r
   )r   rT   getcwd_find_matching_instancer   rW   mkstemptimeenvironget
subprocessPopenr[   r   closetotal_secondssleeppollr   _maybe_read_filer   r   r
   )rD   timeoutthis_cache_keymatch	stdout_fdstdout_path	stderr_fdstderr_pathstart_time_secondsexplicit_tbpr_   poll_interval_secondsend_time_secondssubprocess_resultr   s                   r   startr     s   4 ))+N
 $N3E&&'//7MNY'//7MNY**..!5t<K
)1]{CiO
 	
)G,A,A,CC
))+(
(

()FFH(+'4'4 
 '~6 !d++ ))+(
( ''/  H;GG

	H 	
s0   ! F& &	G0/G+;G0<G3 +G00G3 3,Hc                     t               }|D cg c]  }|j                  | k(  s| }}t        |d       D ]  }|c S  yc c}w )zFind a running TensorBoard instance compatible with the cache key.

    Returns:
      A `TensorBoardInfo` object, or `None` if none matches the cache key.
    c                     | j                   S )N)r   )xs    r   <lambda>z)_find_matching_instance.<locals>.<lambda>  s
    aff r   )r1   N)r   r   r:   )r   infosr   
candidates	candidates        r   r   r     sQ     IE#(H4DNNi,G$HJHJ,<= 	 	 Is
   AAc                     	 t        |       5 }|j                         cddd       S # 1 sw Y   yxY w# t        $ r,}|j                  t        j                  k(  rY d}~yY d}~yd}~ww xY w)zRead the given file, if it exists.

    Args:
      filename: A path to a file.

    Returns:
      A string containing the file contents, or `None` if the file does
      not exist.
    N)rf   rs   rt   r\   rn   )r{   r}   r_   s      r   r   r     sU    (^ 	!v;;=	! 	! 	! 77ell" #s(   3 '	3 03 3 	A(A##A()$r   rM   r,   datetimer\   r.   rT   r   rW   r   r%   r   r   r   tensorboard.utilr   	dataclassr   r   r4   r@   r   r`   rc   rk   ro   r   r   r   r   r   r   	timedeltar   r   r   r   r   r   <module>r      sl   E      	       ' d#  $0) <>(%V,$^,F""(V d#  $ d#
 
 $
 d#  $( d## # $#  d#  $ 0X//; D(Nr   