
    (^ie1                       d dl mZ d dlZd dlmZ d dlm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 d dlZd dlZd dlmZ d dlmZ d	Zd
Z G d de      Z G d dej.                        Z G d de      Z G d de      Zed#d       Z eddd       G d de             Z edddd       G d de             Z edddd        G d! d"e             Zy)$    )annotationsN)	Generator)Iterator)contextmanager)Any)deprecated_class)BaseJournalBackendz.lockz.renamec                  *    e Zd ZdZdddZddZd	dZy)
JournalFileBackenda  File storage class for Journal log backend.

    Compared to SQLite3, the benefit of this backend is that it is more suitable for
    environments where the file system does not support ``fcntl()`` file locking.
    For example, as written in the `SQLite3 FAQ <https://www.sqlite.org/faq.html#q5>`__,
    SQLite3 might not work on NFS (Network File System) since ``fcntl()`` file locking
    is broken on many NFS implementations. In such scenarios, this backend provides
    several workarounds for locking files. For more details, refer to the `Medium blog post`_.

    .. _Medium blog post: https://medium.com/optuna/distributed-optimization-via-nfs    -using-optunas-new-operation-based-logging-storage-9815f9c3f932

    It's important to note that, similar to SQLite3, this class doesn't support a high
    level of write concurrency, as outlined in the `SQLAlchemy documentation`_. However,
    in typical situations where the objective function is computationally expensive, Optuna
    users don't need to be concerned about this limitation. The reason being, the write
    operations are not the bottleneck as long as the objective function doesn't invoke
    :meth:`~optuna.trial.Trial.report` and :meth:`~optuna.trial.Trial.set_user_attr` excessively.

    .. _SQLAlchemy documentation: https://docs.sqlalchemy.org/en/20/dialects/sqlite.html    #database-locking-behavior-concurrency

    Args:
        file_path:
            Path of file to persist the log to.

        lock_obj:
            Lock object for process exclusivity. An instance of
            :class:`~optuna.storages.journal.JournalFileSymlinkLock` and
            :class:`~optuna.storages.journal.JournalFileOpenLock` can be passed.
    Nc                    || _         |xs t        | j                         | _        t        j                  j                  | j                         s$t        | j                   d      j                          ddi| _        y )Nabr   )	
_file_pathJournalFileSymlinkLock_lockospathexistsopenclose_log_number_offset)self	file_pathlock_objs      ^/var/www/html/hubwallet-dev/venv/lib/python3.12/site-packages/optuna/storages/journal/_file.py__init__zJournalFileBackend.__init__8   sV    (H!7!H
ww~~doo.$'--/34a&    c              #    K   t        | j                  d      5 }t        j                  | j                        j                  }d}|| j
                  v r2|j                  | j
                  |          |}|| j
                  |   z  }d }t        ||      D ]  \  }}t        |      }||z  }|dk  r n|||dz   | j
                  vr"| j
                  |   |z   | j
                  |dz   <   ||k  rZ|j                  d      st        d      }| j
                  |dz   = 	 t        j                  |        d d d        y # t        j                  $ r}	|	}| j
                  |dz   = Y d }	~	d }	~	ww xY w# 1 sw Y   y xY ww)Nrbr   )start      
zInvalid log format.)r   r   r   statst_sizer   seek	enumeratelenendswith
ValueErrorjsonloadsJSONDecodeError)
r   log_number_fromfremaining_log_sizelog_number_startlast_decode_error
log_numberlinebyte_lenerrs
             r   	read_logszJournalFileBackend.read_logs?   s    $//4( "	@A "$!9!A!A $"9"99t..?@#2 "d&=&=o&NN" $$-a7G$H @ 
Dt9"h."%)$0++>)@)@@//
;hF ++JN; / }}U+(23H(I%//
Q?@**T**)@"	@ "	@@ ++ @(+%//
Q?@A"	@ "	@sG   E<DE0D>3E05	E<>E-E(#E0(E--E00E95E<c           
        t        | j                        5  dj                  |D cg c]  }t        j                  |d       c}      dz   }t        | j                  d      5 }|j                  |j                  d             |j                          t        j                  |j                                d d d        d d d        y c c}w # 1 sw Y   xY w# 1 sw Y   y xY w)N
),:)
separatorsr   zutf-8)get_lock_filer   joinr)   dumpsr   r   writeencodeflushr   fsyncfileno)r   logslogwhat_to_writer-   s        r   append_logszJournalFileBackend.append_logsd   s    4::& 	%		TRc4::cjARSVZZ  doot, %,,W56	$%		% 	%R% %		% 	%s5   CC	
 C$AC8C	CC	CC#N)r   strr   zBaseJournalFileLock | NonereturnNone)r,   intrI   z%Generator[dict[str, Any], None, None])rC   zlist[dict[str, Any]]rI   rJ   )__name__
__module____qualname____doc__r   r5   rF    r   r   r   r      s    @9#@J%r   r   c                  X    e Zd Zej                  dd       Zej                  dd       Zy)BaseJournalFileLockc                    t         rG   NotImplementedErrorr   s    r   acquirezBaseJournalFileLock.acquirep       !!r   c                    t         rG   rT   rV   s    r   releasezBaseJournalFileLock.releaset   rX   r   NrI   boolrI   rJ   )rL   rM   rN   abcabstractmethodrW   rZ   rP   r   r   rR   rR   o   s4    " " 	" "r   rR   c                  *    e Zd ZdZdddZddZd	dZy)
r   a  Lock class for synchronizing processes for NFSv2 or later.

    On acquiring the lock, link system call is called to create an exclusive file. The file is
    deleted when the lock is released. In NFS environments prior to NFSv3, use this instead of
    :class:`~optuna.storages.journal.JournalFileOpenLock`.

    Args:
        filepath:
            The path of the file whose race condition must be protected.
        grace_period:
            Grace period before an existing lock is forcibly released.
    c                    || _         |t        z   | _        |*|dk  rt        d      |dk  rt	        j
                  d       || _        y Nr   z9The value of `grace_period` should be a positive integer.   z0The value of `grace_period` might be too small. )_lock_target_fileLOCK_FILE_SUFFIX
_lock_filer(   warningswarngrace_periodr   filepathri   s      r   r   zJournalFileSymlinkLock.__init__   sN    !)"%55#q  !\]]aPQ(r   c                    d}t        j                         }d}	 	 t        j                  | j                  | j
                         y# t        $ r}|j                  t        j                  k(  r| j                  	 t        j                  | j
                        j                  }n# t        $ r Y Y d}~w xY w||k7  r|}t        j                         }t        j                         |z
  | j                  kD  r=t        j                  d       	 | j                          d}n# t        $ r Y Y d}~w xY wt        j                   |       t#        |dz  d      }Y d}~D|d}~wt$        $ r | j                           w xY w)zAcquire a lock in a blocking way by creating a symbolic link of a file.

        Returns:
            :obj:`True` if it succeeded in creating a symbolic link of ``self._lock_target_file``.
        MbP?NTfThe existing lock file has not been released for an extended period. Forcibly releasing the lock file.   r    )time	monotonicr   symlinkrd   rf   OSErrorerrnoEEXISTri   r"   st_mtimerg   rh   rZ   RuntimeErrorsleepminBaseException)r   
sleep_secslast_update_monotonic_timemtimer4   current_mtimes         r   rW   zJournalFileSymlinkLock.acquire   s?    
%)^^%5"

4114??C 99,((4%,.GGDOO,D,M,MM& %$%(E1$1E9=9I6>>+.HH4K\K\\$MM!\) $-2
#/ ) () JJz*!$Z!^Q!7J	  sf   *A 
E=)E:)B$#E$	B4-E3B44AEDE	D0(E/D00'EEE=c                >   | j                   t        t        j                               z   t        z   }	 t        j                  | j                   |       t        j                  |       y# t        $ r t        d      t        $ r t        j                  |        w xY w)z-Release a lock by removing the symbolic link.Error: did not possess lockNrf   rH   uuiduuid4RENAME_FILE_SUFFIXr   renameunlinkrs   rw   rz   r   lock_rename_files     r   rZ   zJournalFileSymlinkLock.release   |      ??S->>ASS	IIdoo'78II&' 	><== 	II&'	   5A) )3BN   rk   rH   ri   z
int | NonerI   rJ   r[   r]   rL   rM   rN   rO   r   rW   rZ   rP   r   r   r   r   y   s    ))Vr   r   c                  *    e Zd ZdZdddZddZd	dZy)
JournalFileOpenLockaP  Lock class for synchronizing processes for NFSv3 or later.

    On acquiring the lock, open system call is called with the O_EXCL option to create an exclusive
    file. The file is deleted when the lock is released. This class is only supported when using
    NFSv3 or later on kernel 2.6 or later. In prior NFS environments, use
    :class:`~optuna.storages.journal.JournalFileSymlinkLock`.

    Args:
        filepath:
            The path of the file whose race condition must be protected.
        grace_period:
            Grace period before an existing lock is forcibly released.
    c                    |t         z   | _        |*|dk  rt        d      |dk  rt        j                  d       || _        y rb   )re   rf   r(   rg   rh   ri   rj   s      r   r   zJournalFileOpenLock.__init__   sF    "%55#q  !\]]aPQ(r   c                v   d}t        j                         }d}	 	 t        j                  t        j                  z  t        j
                  z  }t        j                  t        j                  | j                  |             y# t        $ r}|j                  t        j                  k(  r| j                  	 t        j                  | j                        j                  }n# t        $ r Y Y d}~w xY w||k7  r|}t        j                         }t        j                         |z
  | j                  kD  r=t        j                   d       	 | j#                          d}n# t$        $ r Y Y d}~Qw xY wt        j&                  |       t)        |dz  d      }Y d}~|d}~wt*        $ r | j#                           w xY w)zAcquire a lock in a blocking way by creating a lock file.

        Returns:
            :obj:`True` if it succeeded in creating a ``self._lock_file``.

        rm   NTrn   ro   r    )rp   rq   r   O_CREATO_EXCLO_WRONLYr   r   rf   rs   rt   ru   ri   r"   rv   rg   rh   rZ   rw   rx   ry   rz   )r   r{   r|   r}   
open_flagsr4   r~   s          r   rW   zJournalFileOpenLock.acquire   s]    
%)^^%5" ZZ"))3bkkA
*=> 99,((4%,.GGDOO,D,M,MM& %$%(E1$1E9=9I6>>+.HH4K\K\\$MM!\) $-2
#/ ) () JJz*!$Z!^Q!7J	  sg   A%B 
F8)F5)CF	C/(F.C//AFEF	E+#F*E++'FFF8c                >   | j                   t        t        j                               z   t        z   }	 t        j                  | j                   |       t        j                  |       y# t        $ r t        d      t        $ r t        j                  |        w xY w)z,Release a lock by removing the created file.r   Nr   r   s     r   rZ   zJournalFileOpenLock.release  r   r   Nr   r   r[   r]   r   rP   r   r   r   r      s    )+Zr   r   c              #     K   | j                          	 d  | j                          y # | j                          w xY wwrG   )rW   rZ   )r   s    r   r;   r;     s2     s   >) >;>z4.0.0z6.0.0zAUse :class:`~optuna.storages.journal.JournalFileBackend` instead.)textc                      e Zd Zy)JournalFileStorageNrL   rM   rN   rP   r   r   r   r   &  s     	r   r   z=The import path :class:`~optuna.storages.JournalFileOpenLock`zBUse :class:`~optuna.storages.journal.JournalFileOpenLock` instead.)deprecated_versionremoved_versionnamer   c                      e Zd Zy)DeprecatedJournalFileOpenLockNr   rP   r   r   r   r   -       	r   r   z@The import path :class:`~optuna.storages.JournalFileSymlinkLock`zEUse :class:`~optuna.storages.journal.JournalFileSymlinkLock` instead.c                      e Zd Zy) DeprecatedJournalFileSymlinkLockNr   rP   r   r   r   r   7  r   r   r   )r   rR   rI   zIterator[None])
__future__r   r^   collections.abcr   r   
contextlibr   rt   r)   r   rp   typingr   r   rg   optuna._deprecatedr   optuna.storages.journal._baser	   re   r   r   ABCrR   r   r   r;   r   r   r   rP   r   r   <module>r      s   " 
 % $ %   	     / <   U%+ U%p"#'' "N0 NbP- Pf   W^	+ 		 	H	M		$7 		 	K	P		'= 		r   