U
    bŠ  ã                   @   sj   d dl Z d dlZd dlZd dlZd dlZdadZdZddd„Zdd„ Z	e j
dd	d
„ƒZdd„ Zdd„ ZdS )é    Nz/run/cloud-init/tmpz/var/tmp/cloud-initFc                 C   sŒ   | dk	r| S |r:t }tj |¡s6t |¡ t |d¡ |S trBtS t ¡ dkrTt}ntj	 
dd¡}tj |¡s„t |¡ t |d¡ |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.
    Niÿ  r   ZTMPDIRz/tmp)Ú_EXE_ROOT_TMPDIRÚosÚpathÚisdirÚmakedirsÚchmodÚ_TMPDIRÚgetuidÚ_ROOT_TMPDIRÚenvironÚget)ZodirÚ	needs_exeÚtdir© r   ú6/usr/lib/python3/dist-packages/cloudinit/temp_utils.pyÚ_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_exists?   s
    z0ExtendedTemporaryFile.<locals>._unlink_if_existsc                      s   ˆ   ˆ j¡ d S r   )r   Únamer   ©Zfhr   r   Ú
unlink_nowM   s    z)ExtendedTemporaryFile.<locals>.unlink_nowr   )r   ÚpopÚtempfileZNamedTemporaryFiler   Úsetattr)Úkwargsr   r   r   r   r   ÚExtendedTemporaryFile6   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   ÚtempdirT   s    

r$   c                  K   s*   t |  dd ¡|  dd¡ƒ| d< tjf | ŽS ©Nr   r   F)r   r   r   r"   ©r   r   r   r   r"   `   s
    
 
ÿr"   c                  K   s*   t |  dd ¡|  dd¡ƒ| d< tjf | ŽS r%   )r   r   r   Úmkstempr&   r   r   r   r'   g   s
    
 
ÿr'   )NF)F)Ú
contextlibr   r   r#   r   r   r
   r   r   r    Úcontextmanagerr$   r"   r'   r   r   r   r   Ú<module>   s   
(