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mZmZ d dlm	Z	m
Z
 dZeeZe	ddd Ze	dd	d
 ZeddfddZeddfddZdd Ze	ddd ZefddZdS )    N)	b64decode	b64encode)performanceutili  zBase64 decodingc                 C   s2   t | }z|dW S  tk
r,   | Y S X dS )zbase64 decode data

    :param source: a bytes or str to decode
    :return: base64 as a decoded str if utf-8 encoded, otherwise bytes
    utf-8N)r   decodeUnicodeDecodeError)sourceZdecoded r
   9/usr/lib/python3/dist-packages/cloudinit/atomic_helper.pyb64d   s
    r   zBase64 encodingc                 C   s"   t | ts| d} t| dS )zdbase64 encode data

    :param source: a bytes or str to decode
    :return: base64 encoded str
    r   )
isinstancebytesencoder   r   )r	   r
   r
   r   b64e   s    

r   wbFc              
   C   s8   t d|   t| ||||W  5 Q R  S Q R X dS )zCopen filename in mode omode, write content, set permissions to modezWriting N)r   ZTimed_write_file)filenamecontentmodeomodepreserve_moder
   r
   r   
write_file*   s    r   c           	   
   C   s   |r4zt | }t|j}W n tk
r2   Y nX d }zrt j| }t| t	j
|d|d}td| |j||t| || |  t |j| t |j|  W n: tk
r } z|d k	rt |j |W 5 d }~X Y nX d S )NF)dirdeleter   zOAtomically writing to file %s (via temporary file %s) - %s: [%o] %d bytes/chars)osstatS_IMODEst_modeOSErrorpathdirnamer   Z
ensure_dirtempfileZNamedTemporaryFileLOGdebugnamelenwriteclosechmodrename	Exceptionunlink)	r   r   r   r   r   Z	file_statZtfr!   er
   r
   r   r   3   s6    

	
r   c                 C   s8   zd t| W S  tk
r2   d t|  Y S X dS )z1Handler for types which aren't json serializable.z
ci-b64:{0}z)Warning: redacted unserializable type {0}N)formatr   AttributeErrortype)Z_objr
   r
   r   json_serialize_defaultU   s    r1   zDumping jsonc                 C   s   t j| dddtdS )z%Return data in nicely formatted json.   T),z: )indentZ	sort_keysZ
separatorsdefault)jsondumpsr1   )datar
   r
   r   
json_dumps]   s    r9   c                 C   s   t | t|d d|dS )N
w)r   r   )r   r9   )r   r8   r   r
   r
   r   
write_jsoni   s    
r<   )r6   Zloggingr   r   r"   base64r   r   Z	cloudinitr   r   Z
_DEF_PERMSZ	getLogger__name__r#   Ztimedr   r   r   r   r1   r9   r<   r
   r
   r
   r   <module>   s0   


  

  
"
