U
    Ӈgn                     @   s  d Z 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Zddlm	Z	 ddl
mZ ddlmZ ddlmZ ddlmZ ddlmZ dd	lmZmZmZmZmZmZmZmZ ddlZdd
lmZm Z 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- ddl.m/Z/ ddl0m1Z1m2Z2 zddl3m4Z4 W n e5k
rR   e6Z4Y nX zddl7m8Z8m9Z9 dZ:W n e5k
r   dZ:Y nX e;e<Z=dZ>dZ?dZ@dZAeBdd e&C D ZDerddlZddlEmFZFmGZG G dd deGZHneIZHG dd  d e4ZJG d!d" d"eZKeeK ZLG d#d$ d$eZMeMjNd%e>ieMjOd%e@ieMjPd%e?ieMjQd%e@iiZRG d&d' d'eZSG d(d) d)eZTG d*d+ d+eZUdd,d-eLeeV eVeVd.d/d0ZWG d1d2 d2eXZYG d3d4 d4eYZZd5d6 Z[dweIeVd7d8d9Z\ee4 d:d;d<Z]eJfe^eIeVee6 d=d>d?Z_ee_dd@Z`ee_dAd@ZaeJfee6 dBdCdDZbeJfee6 dBdEdFZcdGdH ZddxeIdIdJdKZeeIeef dLdMdNZgdyeIe^e^e^e^dOdPdQZhe!idRdeMjNddddfeIeeI eMe^e^e^e^e^dSdTdUZjG dVdW dWZkdddXeVeIeeL eeL eeVelf dYdZd[ZmeVeeK d\d]d^ZndzeVeVeeV eUd_d`daZoeMjNddfeVeIeMe^eeV e^dbdcddZpeVd:dedfZqeMjNfeMeIdgdhdiZrd{djdkZsdldm ZteeVeeT f d:dndoZudpdq ZveVd:drdsZwdtdu Zxe<dvkreyex  dS )|zFschema.py: Set of module functions for processing cloud-config schema.    N)defaultdict)suppress)deepcopy)Enum)EACCES)partial)TYPE_CHECKINGDefaultDictList
NamedTupleOptionalTupleTypeUnion)features	lifecycleperformancesafeyaml)read_cfg_paths)INCLUSION_TYPES_MAPtype_from_starts_with)Paths)error)DataSourceNotFoundException)mkdtemp)load_text_file
write_file)ValidationError)NetplanParserExceptionParserTFzschema-cloud-config-v1.jsonzschema-network-config-v1.jsonzschema-network-config-v2.json
deprecatedc                 C   s   g | ]}|d  dkr|qS )r   # ).0tr"   r"   9/usr/lib/python3/dist-packages/cloudinit/config/schema.py
<listcomp>G   s      r&   )NotRequired	TypedDictc                   @   s<   e Zd ZU eed< eje ed< eed< eee  ed< dS )
MetaSchemaidZdistrosZ	frequencyZactivate_by_schema_keysN)__name__
__module____qualname__str__annotations__typingr
   r'   r"   r"   r"   r%   r)   Q   s   
r)   c                       s$   e Zd Zeed fddZ  ZS )SchemaDeprecationError)messageversionc                    s   t  j|f| || _d S N)super__init__r3   )selfr2   r3   kwargs	__class__r"   r%   r6   \   s    zSchemaDeprecationError.__init__)r+   r,   r-   r.   r6   __classcell__r"   r"   r9   r%   r1   [   s   r1   c                   @   s,   e Zd ZU eed< eed< edddZdS )SchemaProblempathr2   returnc                 C   s   | j  d| j S )N: )r=   r2   r7   r"   r"   r%   formatj   s    zSchemaProblem.formatN)r+   r,   r-   r.   r/   rB   r"   r"   r"   r%   r<   f   s   
r<   c                   @   s    e Zd ZdZdZdZdZdZdS )
SchemaTypea  Supported schema types are either cloud-config or network-config.

    Vendordata and Vendordata2 format adheres to cloud-config schema type.
    Cloud Metadata is unique schema to each cloud platform and likely will not
    be represented in this enum.
    zcloud-confignetwork-configznetwork-config-v1znetwork-config-v2N)r+   r,   r-   __doc__CLOUD_CONFIGNETWORK_CONFIGNETWORK_CONFIG_V1NETWORK_CONFIG_V2r"   r"   r"   r%   rC   q   s
   rC   latestc                   @   s(   e Zd ZdZdZdZdZdZdd ZdS )	InstanceDataTypez-Types of instance data provided to cloud-initz	user-datarD   zvendor-datazvendor2-datac                 C   s   | j S r4   )valuerA   r"   r"   r%   __str__   s    zInstanceDataType.__str__N)	r+   r,   r-   rE   USERDATArG   
VENDORDATAVENDOR2DATArM   r"   r"   r"   r%   rK      s   rK   c                   @   s&   e Zd ZU eed< eed< eed< dS )InstanceDataPartconfig_typeschema_typeconfig_pathN)r+   r,   r-   rK   r/   rC   r.   r"   r"   r"   r%   rQ      s   
rQ   c                   @   s   e Zd ZU eed< eed< dS )UserDataTypeAndDecodedContentuserdata_typecontentN)r+   r,   r-   r.   r/   r"   r"   r"   r%   rU      s   
rU   , prefix	separator)schema_problemsrZ   r[   r?   c                C   s(   | tdd | }|r$| | }|S )Nc                 S   s   |   S r4   )rB   )pr"   r"   r%   <lambda>       z)_format_schema_problems.<locals>.<lambda>)joinmap)r\   rZ   r[   Z	formattedr"   r"   r%   _format_schema_problems   s    rb   c                       s@   e Zd ZdZd	ee ee d fddZedddZ  Z	S )
SchemaValidationErrorz<Raised when validating a cloud-config file against a schema.Nschema_errorsschema_deprecationsc                    s<   d  fdd}||dd| _ ||dd| _t   dS )zInit the exception an n-tuple of schema errors.

        @param schema_errors: An n-tuple of the format:
            ((flat.config.key, msg),)
        @param schema_deprecations: An n-tuple of the format:
            ((flat.config.key, msg),)
         c                    s8   | s| S  r d7  t tt| }  t| |d7  | S )N

rZ   )sortedlistsetrb   )problemsrZ   r2   r"   r%   handle_problems   s    z7SchemaValidationError.__init__.<locals>.handle_problemszCloud config schema errors: ri   "Cloud config schema deprecations: N)re   rf   r5   r6   )r7   re   rf   ro   r9   rn   r%   r6      s    
zSchemaValidationError.__init__r>   c                 C   s
   t | jS r4   )boolre   rA   r"   r"   r%   
has_errors   s    z SchemaValidationError.has_errors)NN)
r+   r,   r-   rE   r   SchemaProblemsr6   rq   rr   r;   r"   r"   r9   r%   rc      s     "rc   c                   @   s   e Zd ZdZdS )"SchemaValidationInvalidHeaderErrorz>Raised when no valid header is declared in the user-data file.N)r+   r,   r-   rE   r"   r"   r"   r%   rt      s   rt   c                 C   sB   zddl m} W n tk
r&   Y dS X |j|dp@t|tfS )zWTYPE_CHECKER override allowing bytes for string type

    For jsonschema v. 3.0.0+
    r   )Draft4ValidatorFstring)
jsonschemaru   ImportErrorTYPE_CHECKERis_type
isinstancebytes)Zcheckerinstanceru   r"   r"   r%   is_schema_byte_string   s     
r~   )configr?   c                    sR   t d fdd}|r|ndddg}dt||}dd}| |  S )	zcombine description with new/changed/deprecated message

    deprecated/changed/new keys require a _version key (this is verified
    in a unittest), a _description key is optional
    keyc                    sr    |  sdS  |  dd} |  dd|  d}|   d| d| } rbd| S d	|  d
S )Nrg   Z_descriptionZ_versionz	<missing z'_version key, please file a bug report>z in version .  z

**)get
capitalizestrip)r   Zkey_descriptionvmsgannotater   r"   r%   format_message   s    

z:_add_deprecated_changed_or_new_msg.<locals>.format_messager    changednewrg   description)r.   r`   ra   r   rstrip)r   r   
filter_keyr   Zfilter_keysZchanged_new_deprecatedr   r"   r   r%   "_add_deprecated_changed_or_new_msg   s    	r   r>   c                 C   s   g }d}t |tod|k}| D ]}|r|d |jdi di dg krV|g  S t|dr~|jdd dkr|| q|jr|jd dkr|| qt|j|kr|| qt|j|krt|j}|g}q|S )zReturn the best_match errors based on the deepest match in the json_path

    This is useful for anyOf and oneOf subschemas where the most-specific error
    tends to be the most appropriate.
    r   type
propertiesenum	json_pathN)	r{   dictschemar   hasattrr   appendr=   len)errorsr}   Zbest_matchesZ
path_depthrz   errr"   r"   r%   cloud_init_deepest_matches  s0      


r   )r    r   r   
error_typec                 c   s,   |r(t |d|gd}|||ddV  dS )zJsonschema validator for `deprecated` items.

    It yields an instance of `error_type` if deprecated that must be handled,
    otherwise the instance is consider faulty.
    T)r   r   Zdeprecated_versiondevelN)r   r   )
_validatorr    Z	_instancer   r   r   r   r"   r"   r%   r   4  s      r   )r   r   r   c                 #   s   ddl m} g }g }d}t|D ]\}	}
t| j||
|	d}tt fdd|}tt fdd|}|sz||  qt|trd|krd	|
	d
dkrd|d  |
d
 krd}|E dH  || q |s||V  t
d|f |dV  |E dH  dS )a  Jsonschema validator for `anyOf`.

    It treats occurrences of `error_type` as non-errors, but yield them for
    external processing. Useful to process schema annotations, as `deprecated`.

    Cloud-init's network schema under the `config` key has a complexity of
    allowing each list dict item to declare it's type with a `type` key which
    can contain the values: bond, bridge, nameserver, physical, route, vlan.

    This schema 'flexibility' makes it hard for the default
    jsonschema.exceptions.best_match function to find the correct schema
    failure because it typically returns the failing schema error based on
    the schema of greatest match depth. Since each anyOf dict matches the
    same depth into the network schema path, `best_match` just returns the
    first set of schema errors, which is almost always incorrect.

    To find a better schema match when encountering schema validation errors,
    cloud-init network schema introduced schema $defs with the prefix
    `anyOf_type_`. If the object we are validating contains a 'type' key, and
    one of the failing schema objects in an anyOf clause has a name of the
    format anyOf_type_XXX, raise those schema errors instead of calling
    best_match.
    r   )
best_matchFZschema_pathc                    s   t |   S r4   r{   er   r"   r%   r^   s  r_   z_anyOf.<locals>.<lambda>c                    s
   t |  S r4   r   r   r   r"   r%   r^   u  r_   r   Z
anyOf_typez$refrg   ZanyOf_type_TNz.%r is not valid under any of the given schemas)context)jsonschema.exceptionsr   	enumeraterk   descendfilterextendr{   r   r   r   )	validatoranyOfr}   _schemar   r   
all_errorsall_deprecationsZskip_best_matchindex	subschemaall_errserrsdeprecationsr"   r   r%   _anyOfL  s@    


r   c                 #   s   t |}g }g }|D ]h\}}	tj|	|d}
tt fdd|
}tt fdd|
}|sr|	}||  q|| qt|E dH  fdd|D }|r|| dd	d
 |D }td|f V  n
|E dH  dS )zJsonschema validator for `oneOf`.

    It treats occurrences of `error_type` as non-errors, but yield them for
    external processing. Useful to process schema annotations, as `deprecated`.
    r   c                    s   t |   S r4   r   r   r   r"   r%   r^     r_   z_oneOf.<locals>.<lambda>c                    s
   t |  S r4   r   r   r   r"   r%   r^     r_   Nc                    s    g | ]\}}  |r|qS r"   )is_valid)r#   is)r}   r   r"   r%   r&     s      z_oneOf.<locals>.<listcomp>rX   c                 s   s   | ]}t |V  qd S r4   )repr)r#   r   r"   r"   r%   	<genexpr>  s     z_oneOf.<locals>.<genexpr>z%r is valid under each of %s)	r   rk   r   r   r   r   r   r`   r   )r   oneOfr}   r   r   Z
subschemasr   r   r   r   r   r   r   Zfirst_validZ
more_validZreprsr"   )r   r}   r   r%   _oneOf  s2    


r   c                  C   s   ddl m} m} ddlm} t| j}ddi|d d< i }d|d	< | jdt	}d
|i}t
| j}t|t< t|d< t|d< t|d< |f ||dd|}ddd}ddd}	|}
t|dr|	}
|
|_||fS )zGet metaschema validator and format checker

    Older versions of jsonschema require some compatibility changes.

    @returns: Tuple: (jsonschema.Validator, FormatChecker)
    @raises: ImportError when jsonschema is not present
    r   )ru   FormatChecker)creater   rv   r   labelFadditionalPropertiestype_checkerr   r   r   Zdraft4)meta_schema
validatorsr3   Nc                 [   s$   t dd | ||}t|ddkS )gOverride version of `is_valid`.

        It does ignore instances of `SchemaDeprecationError`.
        c                 S   s   t | t S r4   r{   r1   r   r"   r"   r%   r^     s    zFget_jsonschema_validator.<locals>.is_valid_pre_4_0_0.<locals>.<lambda>N)r   iter_errorsnextr7   r}   r   __r   r"   r"   r%   is_valid_pre_4_0_0  s
    
z4get_jsonschema_validator.<locals>.is_valid_pre_4_0_0c                 [   s*   t dd | j|d|}t|ddkS )r   c                 S   s   t | t S r4   r   r   r"   r"   r%   r^     s    z<get_jsonschema_validator.<locals>.is_valid.<locals>.<lambda>r   N)r   evolver   r   r   r"   r"   r%   r     s
    z*get_jsonschema_validator.<locals>.is_validr   )N)N)rw   ru   r   Zjsonschema.validatorsr   r   ZMETA_SCHEMAry   Zredefiner~   r   Z
VALIDATORS_validator_deprecatedDEPRECATED_KEY_validator_changedr   r   r   r   )ru   r   r   r   Zvalidator_kwargsr   r   cloudinitValidatorr   r   Zis_valid_fnr"   r"   r%   get_jsonschema_validator  s@    
  



r   r   c              
   C   sz   ddl m} z| | W nZ |k
rt } z<|rXttddd |jD |jgd|t	d| W 5 d}~X Y nX dS )	a   Validate provided schema meets the metaschema definition. Return strict
    Validator and FormatChecker for use in validation
    @param validator: Draft4Validator instance used to validate the schema
    @param schema: schema to validate
    @param throw: Sometimes the validator and checker are required, even if
        the schema is invalid. Toggle for whether to raise
        SchemaValidationError or log warnings.

    @raises: ImportError when jsonschema is not present
    @raises: SchemaValidationError when the schema is invalid
    r   )SchemaError.c                 S   s   g | ]}t |qS r"   r.   r#   r]   r"   r"   r%   r&   '  s     z3validate_cloudconfig_metaschema.<locals>.<listcomp>re   zGMeta-schema validation failed, attempting to validate config anyway: %sN)
r   r   Zcheck_schemarc   r<   r`   r=   r2   LOGwarning)r   r   throwr   r   r"   r"   r%   validate_cloudconfig_metaschema  s$     r   )network_configr?   c                 C   s    d| kr| d  dS |  dS )z6Return the version of the network schema when present.networkr3   )r   )r   r"   r"   r%   network_schema_version2  s    r   )r   strictr   log_detailsr?   c              
   C   sP  t rtd ntd dS t }tj|d}t| }d|krJd|i}t	|}t
||dd t }g }	z|| W nH tk
r }
 z*|	tdj|
j|
jd	d
|
j  W 5 d}
~
X Y nX tj|rt| |	rL|r|rt|\}}tt|||	d t|	|r4t|	tjj ddd}ntjj d}t| dS )aj  On systems with netplan, validate network_config schema for file

    Leverage NetplanParser for error annotation line, column and detailed
    errors.

    @param network_config: Dict of network configuration settings validated
        against
    @param strict: Boolean, when True raise SchemaValidationErrors instead of
       logging warnings.
    @param annotate: Boolean, when True, print original network_config_file
        content with error annotations
    @param log_details: Boolean, when True logs details of validation errors.
       If there are concerns about logging sensitive userdata, this should
       be set to False.

    @return: True when schema validation was performed. False when not on a
        system with netplan and netplan python support.
    @raises: SchemaValidationError when netplan's parser raises
        NetplanParserExceptions.
    z*Validating network-config with netplan APIz<Skipping netplan schema validation. No netplan API availableFzetc/netplan/network-config.yamlr   i  )modeformat-l{line}.c{col}linecolzInvalid netplan schema. Nr    failed schema validation!

rY   ^ failed schema validation! You may run 'sudo cloud-init schema --system' to check the details.T) LIBNETPLAN_AVAILABLEr   debugr   osr=   r`   r   r   dumpsr   r   Zload_yaml_hierarchyr   r   r<   rB   r   columnr2   existsshutilZrmtreeload_with_marksprintannotated_cloudconfig_filerc   rb   rC   rG   rL   r   )r   r   r   r   Z	parse_dirZnetplan_fileZnet_cfgZsrc_contentparserr   r   _marksr2   r"   r"   r%   netplan_validate_network_schema9  s`    




r   zValidating schema)r   r   rS   r   strict_metaschemar   log_deprecationsr?   c                 C   sH  ddl m} |tjkrDt| }|dkr.tj}n|dkr<tj}t|}|tjkrjt| ||dr`dS | rjdS |dkrzt|}z t	 \}	}
|rt
|	|dd	 W n  tk
r   td
 Y dS X |	||
 d}g }g }g }t|| dd dD ]}ddd |jD }|s@|jdkr@|j|kr@td|j}|r@|d }t|tr|jdksjt|jtjr~|t||j n|t||j q|t||j q|r|rt |dd}t!| |rt |dd}t"| |r
|s|s|r
t#||| |rD|r.t ||j$ ddd}n|j$ d}t%| dS )aP  Validate provided config meets the schema definition.

    @param config: Dict of cloud configuration settings validated against
        schema. Ignored if strict_metaschema=True
    @param schema: jsonschema dict describing the supported schema definition
       for the cloud config module (config.cc_*). If None, validate against
       global schema.
    @param schema_type: Optional SchemaType.
       One of: SchemaType.CLOUD_CONFIG or SchemaType.NETWORK_CONFIG_V1 or
            SchemaType.NETWORK_CONFIG_V2
       Default: SchemaType.CLOUD_CONFIG
    @param strict: Boolean, when True raise SchemaValidationErrors instead of
       logging warnings.
    @param strict_metaschema: Boolean, when True validates schema using strict
       metaschema definition at runtime (currently unused)
    @param log_details: Boolean, when True logs details of validation errors.
       If there are concerns about logging sensitive userdata, this should
       be set to False.
    @param log_deprecations: Controls whether to log deprecations or not.

    @raises: SchemaValidationError when provided config does not validate
        against the provided schema.
    @raises: RuntimeError when provided config sourced from YAML is not a dict.
    @raises: ValueError on invalid schema_type not in CLOUD_CONFIG or
        NETWORK_CONFIG_V1 or NETWORK_CONFIG_V2
    r   	available      )r   r   r   TFN)r   z5Ignoring schema validation. jsonschema is not present)Zformat_checkerc                 S   s   | j S r4   )r=   r   r"   r"   r%   r^     r_   z-validate_cloudconfig_schema.<locals>.<lambda>r   r   c                 S   s   g | ]}t |qS r"   r   r   r"   r"   r%   r&     s     z/validate_cloudconfig_schema.<locals>.<listcomp>r   z#.*\('(?P<name>.*)' was unexpected\)namer   z"Deprecated cloud-config provided: ri   r   r   rY   r   )&cloudinit.net.netplanr   rC   rG   r   rI   rH   
get_schemar   r   r   rx   r   r   rj   r   r`   r=   r   r   rematchr2   r{   r1   r3   r   Zshould_log_deprecationr   ZDEPRECATION_INFO_BOUNDARYr   r<   rb   infor    rc   rL   r   )r   r   rS   r   r   r   r   netplan_availablenetwork_versionr   r   r   r   r   Zinfo_deprecationsschema_errorr=   Z
prop_matchr2   Zdetailsr"   r"   r%   validate_cloudconfig_schema  s    $

  
  

 
   





r	  c                	   @   s   e Zd ZeedddZeeee edddZe	ddd	Z
edee ee ee eeedddZee eeee dddZe	e	edddZdS )
_Annotator)original_contentschemamarksc                 C   s   || _ || _d S r4   )_original_content_schemamarks)r7   r  r  r"   r"   r%   r6   )  s    z_Annotator.__init__)titlerW   r?   c                 C   s   d |}d|  d| dS )Nr   # z: -------------
rh   )r`   )r  rW   Zbodyr"   r"   r%   _build_footer1  s    
z_Annotator._build_footer)r\   c                 C   sz   t t}|D ]h\}}td|}|rD| \}}|t| | nd }|| j|  | |d k	rdj|||d}q|S )Nz&format-l(?P<line>\d+)\.c(?P<col>\d+).*zLine {line} column {col}: {msg})r   r   r   )	r   rk   r  r  groupsintr   r  rB   )r7   r\   errors_by_liner=   r   r  r   r   r"   r"   r%   _build_errors_by_line6  s      z _Annotator._build_errors_by_linerg   )rm   labelsfooterr   label_prefixr?   c                 C   sB   | D ]8}| | }| | | d| d|  |d7 }q|S )Nr  r@   r   )r   )rm   r  r  r   r  Zproblemr   r"   r"   r%   _add_problemsF  s    

z_Annotator._add_problems)linesr  deprecations_by_liner?   c              	      s   g }g }g }d}d}t |dD ]p\}	}
||	 }||	 }|s>|rg } j||||dd} j||||dd}||
d d|  q||
 q|t fddtd	d d
|fd|ff |S )Nr   E)r  Dz		# ,c                    s
    j |  S r4   )r  seqrA   r"   r%   r^   u  r_   z._Annotator._annotate_content.<locals>.<lambda>c                 S   s   t | d S )Nr   )rq   r  r"   r"   r%   r^   w  r_   ZErrorsZDeprecations)r   r  r   r`   r   ra   r   )r7   r  r  r  annotated_contentZerror_footerZdeprecation_footerZerror_indexZdeprecation_indexZline_numberr   r   r   r  r"   rA   r%   _annotate_contentU  sL        
z_Annotator._annotate_content)re   rf   r?   c                 C   sF   |s|s| j S | j d}| |}| |}| |||}d|S )Nr   )r  splitr  r"  r`   )r7   re   rf   r  r  r  r!  r"   r"   r%   r     s    

  z_Annotator.annotateN)rg   )r+   r,   r-   r.   r   r6   staticmethodr
   r  rs   r  r  r  r"  r   r"   r"   r"   r%   r
  (  s2    .r
  rd   )r  r  re   rf   r?   c                C   s   t | ||pg |pg S )a  Return contents of the cloud-config file annotated with schema errors.

    @param cloudconfig: YAML-loaded dict from the original_content or empty
        dict if unparsable.
    @param original_content: The contents of a cloud-config file
    @param schemamarks: Dict with schema marks.
    @param schema_errors: Instance of `SchemaProblems`.
    @param schema_deprecations: Instance of `SchemaProblems`.

    @return Annotated schema
    )r
  r   )r  r  re   rf   r"   r"   r%   r     s    
 r   )rW   r?   c              	   C   sb   ddl m} || krg S g }t|  dD ]2\}}||r*|td| d||d q*|S )a  Annotate and return schema validation errors in merged cloud-config.txt

    When merging multiple cloud-config parts cloud-init logs an error and
    ignores any user-data parts which are declared as #cloud-config but
    cannot be processed. the handler.cloud_config module also leaves comments
    in the final merged config for every invalid part file which begin with
    MERGED_CONFIG_SCHEMA_ERROR_PREFIX to aid in triage.
    r   )MERGED_PART_SCHEMA_ERROR_PREFIXr   zformat-lz.c1zIgnored invalid user-data: )Zcloudinit.handlers.cloud_configr%  r   
splitlines
startswithr   r<   replace)rW   r%  r   Zline_numr   r"   r"   r%   )process_merged_cloud_config_part_problems  s     

	r)  )rT   rW   instance_data_pathr?   c                 C   sF  ddl m}m}m}m} t|}d}|dkrz||| |}W n |k
rp }	 ztt|dg|	W 5 d}	~	X Y nf |k
r }	 ztdt	|	 dd	 W 5 d}	~	X Y n2 |k
r }	 ztt	|	dd	 W 5 d}	~	X Y nX d
}t|}|s"|
d\}
}}tt|d|  d|
 ddt gn|dkr<td| d t||S )a  
    Return tuple of user-data-type and rendered content.

    When encountering jinja user-data, render said content.

    :return: UserDataTypeAndDecodedContent
    :raises: SchemaValidationError when non-jinja content found but
        header declared ## template: jinja.
    :raises JinjaSyntaxParsingException when jinja syntax error found.
    :raises JinjaLoadError when jinja template fails to load.
    r   )JinjaLoadErrorJinjaSyntaxParsingExceptionNotJinjaErrorrender_jinja_payload_from_filezformat-l1.c1ztext/jinja2zRDetected type '{user_data_type}' from header. But, content is not a jinja templateNz&Failed to render templated user-data. Tsys_exitzformat-l2.c1r   z!Unrecognized user-data header in z: "z%".
Expected first line to be one of: rX   text/cloud-configzUser-data type 'z.' not currently evaluated by cloud-init schema)Z!cloudinit.handlers.jinja_templater+  r,  r-  r.  r   rc   r<   r   r.   	partitionrt   r`   USERDATA_VALID_HEADERSr   rU   )rT   rW   r*  r+  r,  r-  r.  Zuser_data_typeZschema_positionr   Zheader_liner   r"   r"   r%   &_get_config_type_and_rendered_userdata  sV      	
"


r4  )rT   r   rS   r   r*  r?   c                 C   s  ddl m} t| }|s.td|j| f  dS |tjfkrHt|j|}nt| ||}|j	dkrbdS |j
}t|}	z&|rt|\}
}nt|}
i }W n tjk
rn } zd }}d}t|drt|drt|d}nt|d	rt|d	rt|d	}|r|jd }|jd }|	td
j||dd| t| t|	}|rXtt|i |jd ||W 5 d}~X Y nX t|
ts|st|j d|  d|tjkr|
d|
std dS t |
}|dkr tj!}t"|
d|drdS | rtd dS n|dkrtj#}t$|}z0t%|
||dddsFtd|j d W dS W n tk
r } zh|& rp|	|j7 }	|rtt|||	|j'd n |j'rt(|j'ddd}t| |	rt|	d|W 5 d}~X Y nX dS )a  Validate cloudconfig file adheres to a specific jsonschema.

    @param config_path: Path to the yaml cloud-config file to parse, or None
        to default to system userdata from Paths object.
    @param schema: Dict describing a valid jsonschema to validate against.
    @param schema_type: One of SchemaType.NETWORK_CONFIG or CLOUD_CONFIG
    @param annotate: Boolean set True to print original config file with error
        annotations on the offending lines.
    @param instance_data_path: Path to instance_data JSON, used for text/jinja
        rendering.

    :return: True when validation was performed successfully
    :raises SchemaValidationError containing any of schema_errors encountered.
    :raises RuntimeError when config_path does not exist.
    r   r   z,Empty '%s' found at %s. Nothing to validate.F)rD   r1  r   NZcontext_markZproblem_markr   r   zFile {0} is not valid YAML. {1}r   r   z is not a YAML dict.r   z:Skipping network-config schema validation on empty config.r   T)r   r   r   zSSkipping network-config schema validation for version: 2. No netplan API available.)r   rS   r   r   z	Skipping z2 schema validation. Jsonschema dependency missing.rd   rp   rX   rY   ))r  r   r   r   rL   rC   rG   rU   r4  rV   rW   r)  r   r   yamlZ	safe_loadZ	YAMLErrorr   getattrr   r   r   r<   rB   r.   rc   r   re   r{   r   RuntimeErrorr   r   rI   r   rH   r  r	  rr   rf   rb   )rT   r   rS   r   r*  r  Zdecoded_contentZdecoded_configrW   r   Zcloudconfigr   r   r   r   Zmarkr  r  r2   r"   r"   r%   validate_cloudconfig_file  s       




  
  



r8  c                   C   s   t jt jt jtdS )NZschemas)r   r=   r`   dirnameabspath__file__r"   r"   r"   r%   get_schema_dir  s    r<  )rS   r?   c              	   C   s`   t jt t|  d }d}ztt|}W n, tt	fk
rZ   t
d| j| i  Y S X |S )ziReturn jsonschema for a specific type.

    Return empty schema when no specific schema file exists.
    rJ   Nz<Skipping %s schema validation. No JSON schema file found %s.)r   r=   r`   r<  SCHEMA_FILES_BY_TYPEjsonloadsr   IOErrorOSErrorr   r   rL   )rS   Zschema_filefull_schemar"   r"   r%   r    s     

r  c                 C   s   | st jddd} | jdddd | jdd	ttjjtjjgd
tj d | jddtdt 	d d | jddddd | jddddd | S )z0Return a parser for supported cmdline arguments.cloudconfig-schemazSchema validation and documentation of instance-data configuration provided to cloud-init. This includes: user-data, vendor-data and network-config)progr   z-cz--config-filez@Path of the cloud-config or network-config YAML file to validate)helpz-tz--schema-typezSWhen providing --config-file, the schema type to validate config against. Default: )r   choicesrE  z-iz--instance-datazbPath to instance-data.json file for variable expansion of '##template: jinja' user-data. Default: instance_data)r   rE  z--system
store_trueFzVValidate the system instance-data provided as vendor-data user-data and network-config)actiondefaultrE  z
--annotatez;Annotate existing instance-data files any discovered errors)
argparseArgumentParseradd_argumentr.   rC   rF   rL   rG   r   get_runpathr   r"   r"   r%   
get_parser  sL    

	rP  c                 C   sF   | j | jg}tdd |D dkr.tddd | jrB| jrBtd dS )	z:Error or warn on invalid exclusive parameter combinations.c                 S   s   g | ]}|r|qS r"   r"   )r#   argr"   r"   r%   r&     s      z*_assert_exclusive_args.<locals>.<listcomp>r   z3Expected one of --config-file or --system argumentsTr/  zMWARNING: The --schema-type parameter is inapplicable when --system is presentN)config_filesystemr   r   rS   r   )argsZexclusive_argsr"   r"   r%   _assert_exclusive_args  s    rU  c              
   C   s  t tttddd}ztdd}W nf ttfk
rf } z"|jtkrTtd t }n W 5 d}~X Y n$ t	k
r   t }t
d Y nX | jr| j}n"t d	kr|d
}n
|d}g }| jr| jrt| j}ntj}|tjkrtj}ntj}|t||| j nt d	kr&tddd ||dd}|ttjtj| ttjtj||ddttjtj||ddttjtj|dpdg}	|	D ](}
|
jrtj|
jr||
 qtj|d	 jstd|d	 j dddd ||fS )a  Return appropriate instance-data.json and instance data parts

    Based on command line args, and user permissions, determine the
    appropriate instance-data.json to source for jinja templates and
    a list of applicable InstanceDataParts such as user-data, vendor-data
    and network-config for which to validate schema. Avoid returning any
    InstanceDataParts when the expected config_path does not exist.

    :return: A tuple of the instance-data.json path and a list of
        viable InstanceDataParts present on the system.
    )pathsprimary_path_keyraw_fallback_path_keyr?   c              
   S   s\   |  |pd}tt< t|jsN|  |p0d}t|jrN|W  5 Q R  S W 5 Q R X |S )ak  Get processed data path when non-empty of fallback to raw data path.

        - When primary path and raw path exist and are empty, prefer primary
          path.
        - When primary path is empty but the raw fallback path is non-empty,
          this indicates an invalid and ignored raw user-data was provided and
          cloud-init emitted a warning and did not process unknown raw
          user-data.
          In the case of invalid raw user-data header, prefer
          raw_fallback_path_key so actionable sensible warnings can be
          reported to the user about the raw unparsable user-data.
        rg   )	get_ipathr   FileNotFoundErrorr   statst_size)rV  rW  rX  Zprimary_datapathZraw_pathr"   r"   r%   get_processed_or_fallback_path
  s    
zBget_config_paths_from_args.<locals>.get_processed_or_fallback_pathZtrust)Zfetch_existing_datasourcez=Using default instance-data/user-data paths for non-root userNzEdatasource not detected, using default instance-data/user-data paths.r   rG  Zinstance_data_sensitivezNUnable to read system userdata or vendordata as non-root user. Try using sudo.Tr/  Zcloud_configZuserdata_rawZvendor_cloud_configZvendordata_rawZvendor2_cloud_configZvendordata2_rawr   rg   zConfig file z does not existz	Error: {}fmtr0  )r   r.   r   r@  rA  errnor   r   r   r   r   rG  r   getuidrN  rR  rS   rC   rF   rG   rK   rN   r   rQ   r   rO   rP   rY  rT   r=   r   )rT  r]  rV  r   r*  config_filesrS   Zinstancedata_typeZuserdata_fileZsupplemental_config_filesZ	data_partr"   r"   r%   get_config_paths_from_args  s    



      rc  c                 C   s  t | t }t|\}}d}tt|dk}|rRtdddd |D   d}g }t|dD ]V\}}	d}
|rtd	| d
|	j d|	j	 d |	j
tjkrt|	j
}n|}zt|	j	||	j
|j|}
W n tk
r0 } zH|jst| d|	j d|	j	  tt||d d ||	j W 5 d}~X Y q` tk
r } z8t| d|	j tt||d d ||	j W 5 d}~X Y q`X |
r`|jr|	j	}n
t|	j}t| d| q`|rtddd |D ddd dS )z@Handle provided schema args and perform the appropriate actions.rg   r   z!Found cloud-config data types: %srX   c                 s   s   | ]}t |jV  qd S r4   )r.   rR   )r#   cfg_partr"   r"   r%   r     s     z%handle_schema_args.<locals>.<genexpr>z  Fr   r   z at :zInvalid r   z
Error: {}
)r_  NzValid schema c                 s   s   | ]}t |V  qd S r4   r   )r#   r   r"   r"   r%   r     s     zError: Invalid schema: {}
Tr^  )rU  r  rc  rq   r   r   r`   r   rR   rT   rS   rC   rG   r8  r   rc   r   r.   r   r7  rR  )r   rT  rB  r*  rb  Znested_output_prefixZmulti_config_outputZerror_typesidxrd  Zperformed_schema_validationZ
cfg_schemar   Zcfgr"   r"   r%   handle_schema_argsx  sn    
rg  c                  O   s   t jtdtjddd dS )zProvide a stub for backwards compatibility.

    This function is no longer used, but earlier versions of modules
    required this function for documentation purposes. This is a stub so
    that custom modules do not break on upgrade.
    z24.4zbThe 'get_meta_doc()' function is deprecated and will be removed in a future version of cloud-init.r"   )Zloggerr3   Zrequested_levelr   rT  rg   )r   Zlog_with_downgradable_levelr   loggingZWARNING)Z_argsZ_kwargsr"   r"   r%   get_meta_doc  s    
ri  c                  C   s   t  } td|   dS )zDTool to validate schema of a cloud-config file or print schema docs.rC  r   )rP  rg  
parse_argsrO  r"   r"   r%   main  s    rk  __main__)FN)T)FFT)N)N)zrE   rK  r>  rh  r   r  r   syscollectionsr   
contextlibr   copyr   r   r   r`  r   	functoolsr   r0   r   r	   r
   r   r   r   r   r   r5  Z	cloudinitr   r   r   r   Zcloudinit.cmd.develr   Zcloudinit.handlersr   r   Zcloudinit.helpersr   Zcloudinit.log.log_utilr   Zcloudinit.sourcesr   Zcloudinit.temp_utilsr   Zcloudinit.utilr   r   rw   r   rx   	ExceptionZnetplanr   r   r   Z	getLoggerr+   r   ZUSERDATA_SCHEMA_FILEZNETWORK_CONFIG_V1_SCHEMA_FILEZNETWORK_CONFIG_V2_SCHEMA_FILEr   rj   keysr3  Ztyping_extensionsr'   r(   r)   r   r1   r<   rs   rC   rF   rG   rH   rI   r=  rK   rQ   rU   r.   rb   
ValueErrorrc   rt   r~   r   r   rq   r   r   r   r   r   r   r   r  r   r   Ztimedr	  r
  r|   r   r)  r4  r8  r<  r  rP  rU  rc  rg  ri  rk  exitr"   r"   r"   r%   <module>   sd  (


    )   #'H*V#	   _ m
! H 
;}@
