U
    Ld                     @   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 e	e
ZdadZdZdeddd	Zdedd
dZdd Ze jdddZdedddZdedddZdS )    N)log)utilz/run/cloud-init/tmpz/var/tmp/cloud-initF)	needs_exec                 C   s:   | d k	r| S |rt S trtS t dkr,tS tjddS )Nr   ZTMPDIRz/tmp)_EXE_ROOT_TMPDIR_TMPDIRosgetuid_ROOT_TMPDIRenvironget)odirr    r   6/usr/lib/python3/dist-packages/cloudinit/temp_utils.pyget_tmp_ancestor   s    r   c                 C   s\   t | |}tj|s,t| t|d |rHt|drHt	d| | dkrX|sX|a
|S )a%  Return the proper 'dir' argument for tempfile functions.

    When root, cloud-init will use /run/cloud-init/tmp to avoid
    any cleaning that a distro boot might do on /tmp (such as
    systemd-tmpfiles-clean).

    If the caller of this function (mkdtemp or mkstemp) was provided
    with a 'dir' argument, then that is respected.

    @param odir: original 'dir' arg to 'mkdtemp' or other.
    @param needs_exe: Boolean specifying whether or not exe permissions are
        needed for tempdir. This is needed because /run is mounted noexec.
    i  ZnoexeczDRequested temporal dir with exe permission `%s` is mounted as noexecN)r   r   pathisdirmakedirschmodr   Zhas_mount_optLOGZwarningr   )r   r   tdirr   r   r   _tempfile_dir_arg   s    

r   c                     sT   t | dd | dd| d< tjf |  dd }| _ fdd}t d|  S )	Ndirr   Fc              
   S   sF   zt |  W n2 tk
r@ } z|jtjkr0|W 5 d }~X Y nX d S N)r   unlinkOSErrorerrnoZENOENT)r   er   r   r   _unlink_if_existsI   s
    z0ExtendedTemporaryFile.<locals>._unlink_if_existsc                      s      j d S r   )r   namer   Zfhr   r   
unlink_nowW   s    z)ExtendedTemporaryFile.<locals>.unlink_nowr    )r   poptempfileZNamedTemporaryFiler   setattr)kwargsr   r    r   r   r   ExtendedTemporaryFile@   s    
 
r%   c              
   k   s*   t f |}z
|V  W 5 tj|| d X d S )N)ignore_errors)mkdtempshutilZrmtree)Zrmtree_ignore_errorsr$   r   r   r   r   tempdir^   s    

r)   c                 K   s   t | |} tjf d| i|S Nr   )r   r"   r'   r   r   r$   r   r   r   r'   j   s    
r'   c                 K   s   t | |} tjf d| i|S r*   )r   r"   mkstempr+   r   r   r   r,   o   s    
r,   )NF)NF)F)NF)NF)
contextlibr   r   r(   r"   Z	cloudinitr   Zloggingr   Z	getLogger__name__r   r   r	   r   boolr   r   r%   contextmanagerr)   r'   r,   r   r   r   r   <module>   s"   
"