o
    w7e                     @   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defdd	Zddefd
dZdd Ze jdddZddefddZddefddZdS )    N)log)utilz/run/cloud-init/tmpz/var/tmp/cloud-initF	needs_exec                 C   s:   | d ur| S |r
t S trtS t dkrtS tjddS )Nr   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 |r$t|dr$t	d| | du r,|s,|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  noexeczDRequested temporal dir with exe permission `%s` is mounted as noexecN)r   r   pathisdirmakedirschmodr   has_mount_optLOGwarningr   )r   r   tdirr   r   r   _tempfile_dir_arg   s   

r   c                     sX   t | dd | dd| d< tjd	i |  dd }| _ fdd}t d|  S )
Ndirr   Fc              
   S   sH   zt |  W d S  ty# } z|jtjkr|W Y d }~d S d }~ww N)r   unlinkOSErrorerrnoENOENT)r   er   r   r   _unlink_if_existsI   s   z0ExtendedTemporaryFile.<locals>._unlink_if_existsc                      s      j d S r   )r   namer   fhr   r   
unlink_nowW   s   z)ExtendedTemporaryFile.<locals>.unlink_nowr&   r   )r   poptempfileNamedTemporaryFiler   setattr)kwargsr"   r&   r   r$   r   ExtendedTemporaryFile@   s   r,   c              
   k   s<    t di |}z|V  W tj|| d d S tj|| d w )N)ignore_errorsr   )mkdtempshutilrmtree)rmtree_ignore_errorsr+   r   r   r   r   tempdir^   s
   "r2   c                 K      t | |} tjdd| i|S Nr   r   )r   r(   r.   r   r   r+   r   r   r   r.   j      
r.   c                 K   r3   r4   )r   r(   mkstempr5   r   r   r   r7   o   r6   r7   )NF)F)
contextlibr   r   r/   r(   	cloudinitr   loggingr   	getLogger__name__r   r   r
   r   boolr   r   r,   contextmanagerr2   r.   r7   r   r   r   r   <module>   s$   
"