U
    Ӈg                     @   s   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 ee	Z
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)utilz/run/cloud-init/tmpz/var/tmp/cloud-initF)	needs_exec                 C   s2   | d k	r| S |rt S t dkr$tS tjddS )Nr   ZTMPDIRz/tmp)_EXE_ROOT_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   sL   t | |}tj|s,t| t|d |rHt|drHt	d| |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 noexec)
r   r   pathisdirmakedirschmodr   Zhas_mount_optLOGZwarning)r
   r   tdirr   r   r   _tempfile_dir_arg   s    

r   c                     s@   t  | d< tjf |  dd }| _ fdd}t d|  S )Ndirc              
   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   tempfileZNamedTemporaryFiler   setattr)kwargsr   r   r   r   r   ExtendedTemporaryFile8   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 | |} tjf d| i|S Nr   )r   r   r$   r   r   r!   r   r   r   r$   `   s    
r$   c                 K   s   t | |} tjf d| i|S r'   )r   r   mkstempr(   r   r   r   r)   e   s    
r)   )NF)NF)F)NF)NF)
contextlibr   Zloggingr   r%   r   Z	cloudinitr   Z	getLogger__name__r   r   r   boolr   r   r"   contextmanagerr&   r$   r)   r   r   r   r   <module>   s    

