o
    -wi%                     @  s  U d 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ZddlZddl	Z	ddl
mZ ddlmZ ddlmZmZmZmZ ddlZddlmZmZ ddlmZ dd	lmZmZmZ dd
lmZmZmZ G dd deZ dddZ!G dd dZ"da#de$d< dddZ%dS )zArtifact cache.    )annotationsN)Path)NamedTemporaryFile)IOContextManagerIteratorProtocol)envutil)files_in)B64MD5ETagb64_to_hex_id)FilePathStrStrPathURIStrc                   @  s   e Zd Zd	d
ddZdS )Opener.modestrreturnContextManager[IO]c                 C  s   d S N )selfr   r   r   d/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/wandb/sdk/artifacts/artifact_file_cache.py__call__   s   zOpener.__call__N).)r   r   r   r   )__name__
__module____qualname__r   r   r   r   r   r      s    r   r   intc                  C  s   t jddf} tt| S )Nz-czimport os; print(os.umask(22)))sys
executabler   
subprocesscheck_output)	umask_cmdr   r   r   _get_sys_umask_threadsafe   s   r%   c                   @  st   e Zd Zd,ddZd-ddZd.ddZ	d/d0ddZ			d1d2d!d"Zd3d#d$Zd4d%d&Z	d/d5d(d)Z
d6d*d+ZdS )7ArtifactFileCache	cache_dirr   r   Nonec                 C  s<   t || _| jd | _| jd | _|   t | _d | _d S )Nobjtmp)r   
_cache_dir_obj_dir	_temp_dir_ensure_write_permissionsr%   
_sys_umask_override_cache_path)r   r'   r   r   r   __init__&   s   

zArtifactFileCache.__init__b64_md5r   sizer    tuple[FilePathStr, bool, Opener]c                 C  sX   | j d urd}t| j }nd}t|}| jd |d d  |dd   }| j|||dS )NTFmd5   
skip_cache)r0   r   r   r,   _check_or_create)r   r2   r3   r8   pathhex_md5r   r   r   check_md5_obj_path2   s   
"z$ArtifactFileCache.check_md5_obj_pathurlr   etagr   c                 C  s   | j d urd}t| j }n,d}tt|d t|d   }| jd |d d  |dd   }| j|||dS )NTFzutf-8r>   r6   r7   )	r0   r   hashlibsha256encodedigest	hexdigestr,   r9   )r   r=   r>   r3   r8   r:   hexhashr   r   r   check_etag_obj_pathA   s   
"z%ArtifactFileCache.check_etag_obj_pathFr:   r   r8   boolc                 C  s8   | j |||d}| o| j|k}tt|||fS )Nr7   )_openeris_filestatst_sizer   r   )r   r:   r3   r8   openerhitr   r   r   r9   T   s   z"ArtifactFileCache._check_or_createNtarget_size
int | Noneremove_temptarget_fractionfloat | Nonec              	   C  s  |du r
|du r
d}|dur|durt d|dur"|dk r"t d|dur2|dk s.|dkr2t dd}d}d}t| jD ]'}| j}||7 }|r`zt|j ||7 }W q= ty_   Y q=w ||7 }q=|rst	
dt| d g }	t| jD ]}
||
 j7 }|	|
 qz|durt|| }|dusJ t|	d	d
 dD ]*}||kr|  S zt|j W n	 ty   Y nw || j8 }|| j7 }q||krt	d| j d |S )a  Clean up the cache, removing the least recently used files first.

        Args:
            target_size: The target size of the cache in bytes. If the cache is larger
                than this, we will remove the least recently used files until the cache
                is smaller than this size.
            remove_temp: Whether to remove temporary files. Temporary files are files
                that are currently being written to the cache. If remove_temp is True,
                all temp files will be removed, regardless of the target_size or
                target_fraction.
            target_fraction: The target fraction of the cache to reclaim. If the cache
                is larger than this, we will remove the least recently used files until
                the cache is smaller than this fraction of its current size. It is an
                error to specify both target_size and target_fraction.

        Returns:
            The number of bytes reclaimed.
        Nr   z3Cannot specify both target_size and target_fractionz target_size must be non-negative   z'target_fraction must be between 0 and 1zCache contains zO of temporary files. Run `wandb artifact cleanup --remove-temp` to remove them.c                 S  s
   |   jS r   )rI   st_atime)xr   r   r   <lambda>   s   
 z+ArtifactFileCache.cleanup.<locals>.<lambda>)keyz"Failed to reclaim enough space in zU. Try running `wandb artifact cache cleanup --remove-temp` to remove temporary files.)
ValueErrorr   r-   rI   rJ   osremover:   OSErrorwandbtermwarnr
   to_human_sizer,   appendr   sorted	termerrorr+   )r   rM   rO   rP   bytes_reclaimed
total_size	temp_sizeentryr3   entries
file_entryr   r   r   cleanup[   s`   

zArtifactFileCache.cleanupc                 C  s   t | jd S )z@Return the number of bytes of free space in the cache directory.r6   )shutil
disk_usager+   )r   r   r   r   _free_space   s   zArtifactFileCache._free_spacec                 C  sf   ||   krdS td | jdd ||   krdS | jdd ||   kr1ttjd| j dS )zIf a `size` write would exceed disk space, remove cached items to make space.

        Raises:
            OSError: If there is not enough space to write `size` bytes, even after
                removing cached items.
        Nz3Cache size exceeded. Attempting to reclaim space...g      ?)rP   r   )rM   zInsufficient free space in )rj   r[   r\   rg   rZ   errnoENOSPCr+   )r   r3   r   r   r   _reserve_space   s   
z ArtifactFileCache._reserve_spacer   c                   s    t jdd	 fdd}|S )
Nwr   r   r   Iterator[IO]c                 3  s    d| v r	t dr j}n j}|jddd t|| dd}z$|V  |  t|j	dj
 @   jjddd t|j	  W d S  tyW   t|j	  w )Naz)Appending to cache files is not supportedTparentsexist_okF)dirr   deletei  )rW   parentrm   r-   mkdirr   closerX   chmodnamer/   replace	ExceptionrY   )r   temp_dir	temp_filer:   r   r3   r8   r   r   atomic_open   s&   
z.ArtifactFileCache._opener.<locals>.atomic_open)rn   )r   r   r   ro   )
contextlibcontextmanager)r   r:   r3   r8   r   r   r   r   rG      s   zArtifactFileCache._openerc              
   C  s~   z(| j jddd t| j d}|d W d   W dS 1 s!w   Y  W dS  ty> } z
td| j d|d}~ww )z9Raise an error if we cannot write to the cache directory.Trq   )rt   s   wandbNzUnable to write to z5. Ensure that the current user has write permissions.)r-   rw   r   writePermissionErrorr+   )r   fer   r   r   r.      s   &z+ArtifactFileCache._ensure_write_permissions)r'   r   r   r(   )r2   r   r3   r   r   r4   )r=   r   r>   r   r3   r   r   r4   )F)r:   r   r3   r   r8   rF   r   r4   )NFN)rM   rN   rO   rF   rP   rQ   r   r   r   r   )r3   r   r   r(   )r:   r   r3   r   r8   rF   r   r   )r   r(   )r   r   r   r1   r<   rE   r9   rg   rj   rm   rG   r.   r   r   r   r   r&   %   s    


	
S
r&   zArtifactFileCache | None_artifact_file_cachec                  C  s*   t  d } td u stj| krt| atS )N	artifacts)r	   get_cache_dirr   r+   r&   )r'   r   r   r   get_artifact_file_cache   s   r   r   )r   r&   )&__doc__
__future__r   r   rk   r?   rX   rh   r"   r    pathlibr   tempfiler   typingr   r   r   r   r[   r	   r
   wandb.sdk.lib.filesystemr   wandb.sdk.lib.hashutilr   r   r   wandb.sdk.lib.pathsr   r   r   r   r%   r&   r   __annotations__r   r   r   r   r   <module>   s.    
	 K