
    x[h                        U 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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mZ d d	lmZmZ ee   ed
<   	 d dlmZ d dlm Z   ejF                  e$      Z% G d de      Z& G d de      Z' G d de
jP                        Z)	 ddZ*ddZ+de,dee,   fdZ-	 ddZ.y# e!$ r eZ ejD                  d      Z Y rw xY w)    N)EACCES)OptionalType)handlers)b64d
json_dumps)Paths)
PER_ALWAYS)MISSING_JINJA_PREFIXJinjaSyntaxParsingExceptiondetect_templaterender_string)	load_jsonload_text_fileJUndefinedError)UndefinedError)operator_rez[-.]c                       e Zd Zy)JinjaLoadErrorN__name__
__module____qualname__     C/usr/lib/python3/dist-packages/cloudinit/handlers/jinja_template.pyr   r   "       r   r   c                       e Zd Zy)NotJinjaErrorNr   r   r   r   r   r   &   r   r   r   c                   $    e Zd ZdgZdefdZd Zy)JinjaTemplatePartHandlerz## template: jinjapathsc                     t         j                  j                  | t        d       || _        i | _        |j                  dg       D ]&  }|j                         D ]  }|| j
                  |<    ( y )N   )versionsub_handlers)r   Handler__init__r
   r"   r&   get
list_types)selfr"   _kwargshandlerctypes        r   r(   z!JinjaTemplatePartHandler.__init__.   sn    !!$
A!>
{{>26 	3G ++- 3+2!!%(3	3r   c                    |t         j                  v ry | j                  j                  d      }	 t	        |||      }|sy t        j                  |      }
| j                  j                  |
      }|st        j                  d||
       y |j                  dk(  r|j                  ||||||       y |j                  dk(  r|j                  |||||       y y # t
        $ r*}	t        j                  d|t        |	             Y d }	~	y d }	~	ww xY w)Ninstance_data_sensitivez=Ignoring jinja template for %s. Failed to render template. %szPIgnoring jinja template for %s. Could not find supported sub-handler for type %sr$      )r   CONTENT_SIGNALSr"   get_runpathrender_jinja_payload_from_filer   LOGwarningstrtype_from_starts_withr&   r)   handler_versionhandle_part)r+   datar.   filenamepayload	frequencyheadersjinja_json_filerendered_payloadesubtypesub_handlers               r   r:   z$JinjaTemplatePartHandler.handle_part6   s   H,,,**001JK	=?   001AB''++G4KK+	 &&!+##eX'7G ((A-##eX'7 .3 + 	KK0A	 	s   C 	D	 DD	N)r   r   r   prefixesr	   r(   r:   r   r   r   r!   r!   *   s    $%H3e 3$r   r!   c                    t        |       d   dk7  rt        d      i }d}t        j                  j	                  |      st        d|z        	 t        t        |            }t        | |||      }|sy|S # t        $ rA}d}t        |t        t        f      r|j                  t        k(  rd|z  }t        |      |d}~ww xY w)aK  Render a jinja template sourcing variables from jinja_vars_path.

    @param payload: String of jinja template content. Should begin with
        ## template: jinja\n.
    @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   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_fninstance_data_filedebuginstance_datarA   rB   msgs           r   r4   r4   ]   s      w"g-=>>M77>>,-12
 	

)!.1C"DE ,]E   )2a'7+,ww& &(:;  S!q()s   A6 6	C ?<B;;C c                    t        ||j                  dg       d      }|rt        j                  dt	        |             	 t        | |      }t        j                  dt        z  |      D cg c]  }d|j                  t        d      z   }}|r&t        j                  d	|d
j                  |             |S # t        t        f$ r*}t        j                  d|t        |             Y d }~y d }~ww xY wc c}w )Nzbase64-encoded-keysT)decode_pathsinclude_key_aliaseszConverted jinja variables
%sz"Ignoring jinja template for %s: %sz%s[^\s]+z'%s' z:Could not render jinja template variables in file '%s': %sz, )convert_jinja_instance_datar)   r5   rS   r   r   	TypeErrorr   r6   r7   refindallr   replacejoin)	r=   rQ   rT   rS   instance_jinja_varsrA   rB   varwarningss	            r   rP   rP      s    5"&&'<bA 
 		+Z8K-L	
(2EF ::..0@
 	1266H  HIIh	

  ' 8*c!fMs   B8 , C48C1 C,,C1	orig_namereturnc                 H    t        j                  t        d|       }|| k7  r|S y)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)r\   subr   )rc   
alias_names     r   get_jinja_variable_aliasri      s'     S)4JYr   c                    i }|D cg c]  }|j                  dd       }}t        | j                               D ]  \  }}|rdj                  |||      n|}	|	|v rt	        |      }t        |t              r]t        ||	|||      ||<   t        j                  d|      r9||   j                         D ]  \  }
}t        j                  |      ||
<    n|||<   |st        |      }|st        j                  ||         ||<    |S c c}w )zProcess instance-data.json dict for use in jinja templates.

    Replace hyphens with underscores for jinja templates and decode any
    base64_encoded_keys.
    -rf   z	{0}{1}{2})seprW   rX   zv\d+$)r^   sorteditemsformatr   rL   dictrZ   r\   matchcopydeepcopyri   )r;   prefixrl   rW   rX   resultrI   keyvaluekey_pathsubkeysubvaluerh   s                r   rZ   rZ      s    F7CDtDLLc*DLDTZZ\* @
U;A;%%fc37s|#KEeT"5)$7F3K xx#&(.s(9(9(; =$FH%)]]8%<F6N=  F3K1#6J%)]]6#;%?z"+@, M/ Es   D	)F)rY   /r   F)/rr   loggingrH   r\   rO   r   typingr   r   	cloudinitr   cloudinit.atomic_helperr   r   cloudinit.helpersr	   cloudinit.settingsr
   cloudinit.templaterr   r   r   r   cloudinit.utilr   r   rK   __annotations__jinja2.exceptionsr   r   jinja2.lexerr   ImportErrorcompile	getLoggerr   r5   r   r   r'   r!   r4   rP   r7   ri   rZ   r   r   r   <module>r      s      	 	  !  4 # )  5i  &C( g!	Y 		I 	0x// 0h 49*Z<  , DI G  &O"**W%K&s   B: :CC