U
    Ldg                     @   sX  U d dl Z d dlZd dlZd dlmZ d dlmZmZ d dlm	Z	 d dlm
Z d dlmZmZ d dlmZ d dlmZ d d	lmZmZmZ d d
lmZmZ ee ed< zd dlmZ d dlm Z  W n" e!k
r   eZe"dZ Y nX e#e$Z%G dd deZ&G dd deZ'G dd de	j(Z)d"ddZ*d#ddZ+e,ee, dddZ-d$d d!Z.dS )%    N)EACCES)OptionalType)handlers)log)b64d
json_dumps)Paths)
PER_ALWAYS)MISSING_JINJA_PREFIXdetect_templaterender_string)	load_file	load_jsonJUndefinedError)UndefinedError)operator_rez[-.]c                   @   s   e Zd ZdS )JinjaLoadErrorN__name__
__module____qualname__ r   r   C/usr/lib/python3/dist-packages/cloudinit/handlers/jinja_template.pyr   !   s   r   c                   @   s   e Zd ZdS )NotJinjaErrorNr   r   r   r   r   r   %   s   r   c                   @   s(   e Zd ZdgZedddZdd ZdS )JinjaTemplatePartHandlerz## template: jinja)pathsc                 K   sL   t jj| tdd || _i | _|dg D ]}| D ]}|| j|< q6q*d S )N   )versionsub_handlers)r   Handler__init__r
   r   r   getZ
list_types)selfr   Z_kwargsZhandlerctyper   r   r   r!   -   s    z!JinjaTemplatePartHandler.__init__c                 C   s   |t jkrd S | jd}t|||}|s.d S t |}	| j|	}
|
sZt	d||	 d S |
j
dkrz|
|||||| n|
j
dkr|
||||| d S )NZinstance_data_sensitivezPIgnoring jinja template for %s. Could not find supported sub-handler for type %sr      )r   ZCONTENT_SIGNALSr   Zget_runpathrender_jinja_payload_from_fileZtype_from_starts_withr   r"   LOGwarningZhandler_versionhandle_part)r#   datar$   filenamepayloadZ	frequencyZheadersZjinja_json_filerendered_payloadZsubtypeZsub_handlerr   r   r   r)   5   sH    
  

     
    z$JinjaTemplatePartHandler.handle_partN)r   r   r   prefixesr	   r!   r)   r   r   r   r   r   )   s   r   Fc              
   C   s   t | d dkrtdi }d}tj|s8td| ztt|}W nP tk
r } z2d}t	|t
tfr~|jtkr~d| }t||W 5 d}~X Y nX t| |||}|sdS |S )aR  Render a jinja template payload sourcing variables from jinja_vars_path.

    @param payload: String of jinja template content. Should begin with
        ## template: jinja
.
    @param payload_fn: String representing the filename from which the payload
        was read used in error reporting. Generally in part-handling this is
        'part-##'.
    @param instance_data_file: A path to a json file containing variables that
        will be used as jinja template variables.

    @return: A string of jinja-rendered content with the jinja header removed.
        Returns None on error.
    r   ZjinjazPayload is not a jinja templateNzFCannot render jinja template vars. Instance data not yet present at %sz"Loading Jinja instance data failedzGCannot render jinja template vars. No read permission on '%s'. Try sudo)r   r   ospathexistsr   r   r   	Exception
isinstanceIOErrorOSErrorerrnor   render_jinja_payload)r,   
payload_fnZinstance_data_filedebuginstance_datar-   emsgr   r   r   r&   R   s<    
   r&   c              
   C   s   t ||dg dd}|r*tdt| zt| |}W n> ttfk
rv } ztd|t	| W Y d S d }~X Y nX dd t
dt |D }|rtd	|d
| |S )Nzbase64-encoded-keysT)decode_pathsinclude_key_aliaseszConverted jinja variables
%sz"Ignoring jinja template for %s: %sc                 S   s   g | ]}d | td qS )z'%s' )replacer   ).0varr   r   r   
<listcomp>   s   z(render_jinja_payload.<locals>.<listcomp>z%s[^\s]+z:Could not render jinja template variables in file '%s': %sz, )convert_jinja_instance_datar"   r'   r9   r   r   	TypeErrorr   r(   strrefindallr   join)r,   r8   r:   r9   Zinstance_jinja_varsr-   r;   warningsr   r   r   r7      s8    
  r7   )	orig_namereturnc                 C   s   t td| }|| kr|S dS )a  Return a jinja variable alias, replacing any operators with underscores.

    Provide underscore-delimited key aliases to simplify dot-notation
    attribute references for keys which contain operators "." or "-".
    This provides for simpler short-hand jinja attribute notation
    allowing one to avoid quoting keys which contain operators.
    {{ ds.v1_0.config.user_network_config }} instead of
    {{ ds['v1.0'].config["user.network-config"] }}.

    :param orig_name: String representing a jinja variable name to scrub/alias.

    :return: A string with any jinja operators replaced if needed. Otherwise,
        none if no alias required.
    _N)rG   subr   )rK   
alias_namer   r   r   get_jinja_variable_alias   s    rP   r?   /r   c                 C   s   i }dd |D }t |  D ]\}}|r8d|||n|}||krLt|}t|trt|||||d||< td|r||  D ]\}	}
t	
|
||	< qn|||< |rt|}|rt	
|| ||< q|S )zProcess instance-data.json dict for use in jinja templates.

    Replace hyphens with underscores for jinja templates and decode any
    base64_encoded_keys.
    c                 S   s   g | ]}| d dqS )-rM   )r@   )rA   r0   r   r   r   rC      s     z/convert_jinja_instance_data.<locals>.<listcomp>z	{0}{1}{2})sepr=   r>   zv\d+$)sorteditemsformatr   r3   dictrD   rG   matchcopydeepcopyrP   )r*   prefixrS   r=   r>   resultkeyvalueZkey_pathZsubkeyZsubvaluerO   r   r   r   rD      s.    

rD   )F)F)r?   rQ   r   F)/rY   r/   rG   r6   r   typingr   r   Z	cloudinitr   r   ZloggingZcloudinit.atomic_helperr   r   Zcloudinit.helpersr	   Zcloudinit.settingsr
   Zcloudinit.templaterr   r   r   Zcloudinit.utilr   r   r2   __annotations__Zjinja2.exceptionsr   r   Zjinja2.lexerr   ImportErrorcompileZ	getLoggerr   r'   r   r   r    r   r&   r7   rF   rP   rD   r   r   r   r   <module>   s@    
* 
-
       