
­­­­­­­­­­­­­­­­­­
<!DOCTYPE html>
<html>
3
\mee                 @   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  ddl!m"Z" ddl#m$Z$m%Z% ddl&m'Z' ddl(m)Z)m*Z*m+Z+ yddl,m-Z. e.Z-W n e/k
r.   e0Z-Y nX ej1e2Z3dZ4dZ5dZ6de5ide6idZ7ddddZ8dZ9dZ:dZ;dZ<dZ=dZ>dZ?dZ@eAd d! e$jB D ZCerddlZdd"lDmEZEmFZF G d#d$ d$eFZGneHZGG d%d& d&e-ZIG d'd( d(eZJeeJ ZKG d)d* d*eZLdd+d,eKeeM eMeMd-d.d/ZNG d0d1 d1eOZPd2d3 ZQdeHeMd5d6d7ZRee- d8d9d:ZSeIfeTeHeMee0 d;d<d=ZUeeUdd>ZVeeUd?d>ZWeIfee0 d@dAdBZXeIfee0 d@dCdDZYdEdF ZZdeHdHdIdJZ[deHeeH eMeTeTeTeTdLdMdNZ\G dOdP dPZ]dddQeHeMeHeeK eeK eeMe^f dRdSdTZ_eMeeJ dUdVdWZ`deMeMeMeLdXdYdZZadeMeHeMeTeMeTd[d\d]Zbd^d_ Zcd`da ZdeHeMeeM dbdcddZeeHeHeMdedfdgZfeMd8dhdiZgeHeHdjdkdlZheHdmdndoZieHeMdpdqdrZjdeHeHeMdtdudvZkeGeMdwdxdyZleGeMdwdzd{ZmdeGeeH eMd|d}d~ZneHd8ddZoepeMdddZqeMd8ddZrdeMeHdddZsdddZtdd Zudd Zve2dkrejwev  dS )zFschema.py: Set of module functions for processing cloud-config schema.    N)defaultdict)Iterable)deepcopy)EACCES)partial)chain)TYPE_CHECKINGDefaultDictList
NamedTupleOptionalTypeUnioncast)importersafeyaml)read_cfg_paths)INCLUSION_TYPES_MAPtype_from_starts_with)DataSourceNotFoundException)errorget_modules_from_dir	load_file)ValidationErrorz!versions.schema.cloud-config.jsonzschema-cloud-config-v1.jsonzschema-network-config-v1.jsonlatest)zcloud-configznetwork-configtrueZfalseZnull)TFNap  
{name}
{title_underbar}

{title}

.. tab-set::

{prefix3}.. tab-item:: Summary

{description}

{prefix6}**Internal name:** ``{id}``

{prefix6}**Module frequency:** {frequency}

{prefix6}**Supported distros:** {distros}

{prefix6}{activate_by_schema_keys}

{prefix3}.. tab-item:: Config schema

{property_doc}

{prefix3}.. tab-item:: Examples

{prefix6}::

{examples}
 z5{prefix}* **{prop_name}:** ({prop_type}){description}zJ{prefix}* Each object in **{prop_name}** list supports the following keys:z&
   # --- Example{example_count} ---


deprecatedzDEPRECATED: c             C   s   g | ]}|d  dkr|qS )r   # ).0tr   r   /usr/lib/python3.6/schema.py
<listcomp>p   s    r#   )NotRequired	TypedDictc               @   sB   e Zd ZU eeeeej	e 
ej	e eee	e  dS )
MetaSchemaN)__name__
__module____qualname__strnameidtitledescriptiontypingr
   distrosexamples	frequencyr$   activate_by_schema_keysr   r   r   r"   r&   z   s   


r&   c               @   s   e Zd ZdS )SchemaDeprecationErrorN)r'   r(   r)   r   r   r   r"   r4      s   r4   c               @   s$   e Zd ZU eeedddZdS )SchemaProblem)returnc             C   s   | j  d| j S )Nz: )pathmessage)selfr   r   r"   format   s    zSchemaProblem.formatN)r'   r(   r)   r*   r7   r8   r:   r   r   r   r"   r5      s   
r5   c               @   s   e Zd ZU eedS )UserDataTypeAndDecodedContentN)r'   r(   r)   r*   userdata_typecontentr   r   r   r"   r;      s   
r;   z, )prefix	separator)schema_problemsr>   r?   r6   c            C   s(   |j tdd | }|r$| | }|S )Nc             S   s   | j  S )N)r:   )pr   r   r"   <lambda>   s    z)_format_schema_problems.<locals>.<lambda>)joinmap)r@   r>   r?   Z	formattedr   r   r"   _format_schema_problems   s    rE   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 j  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),)
        r   c                s8   | s| S  r d7  t tt| }  t| |d7  | S )Nz

)r>   )sortedlistsetrE   )problemsr>   )r8   r   r"   handle_problems   s    z7SchemaValidationError.__init__.<locals>.handle_problemszCloud config schema errors: )r>   z"Cloud config schema deprecations: N)rG   rH   super__init__)r9   rG   rH   rM   )	__class__)r8   r"   rO      s    


zSchemaValidationError.__init__)r6   c             C   s
   t | jS )N)boolrG   )r9   r   r   r"   
has_errors   s    z SchemaValidationError.has_errors)NN)
r'   r(   r)   __doc__r   SchemaProblemsrO   rQ   rR   __classcell__r   r   )rP   r"   rF      s    rF   c             C   s@   yddl m} W n tk
r$   dS X |jj|dp>t|tfS )zWTYPE_CHECKER override allowing bytes for string type

    For jsonschema v. 3.0.0+
    r   )Draft4ValidatorFstring)
jsonschemarV   ImportErrorTYPE_CHECKERis_type
isinstancebytes)ZcheckerinstancerV   r   r   r"   is_schema_byte_string   s    r_   F)configr6   c                sR   t d fdd}|r|ndddg}djt||}jdd}| | j 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   j |  sdS j |  dd}j |  dd|  d}| j  d| d| } rbd| S d	|j  d
S )Nr   Z_descriptionZ_versionz	<missing z'_version key, please file a bug report>z in version z.  z

**)get
capitalizestrip)ra   Zkey_descriptionvmsg)annotater`   r   r"   format_message   s    
z:_add_deprecated_changed_or_new_msg.<locals>.format_messager   changednewr   r.   )r*   rC   rD   rd   rstrip)r`   ri   
filter_keyrj   Zfilter_keysZchanged_new_deprecatedr.   r   )ri   r`   r"   "_add_deprecated_changed_or_new_msg   s
    	ro   )r6   c             C   s   g }d}t |tod|k}x| D ]}|r|d |jjdi jdi jdg krT|gS t|dr||jdd dkr|j| q|jr|jd dkr|j| q t|j|kr|j| q t|j|kr t|j}|g}q W |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_path   N)	r\   dictschemard   hasattrrs   appendr7   len)errorsr^   Zbest_matchesZ
path_depthr[   errr   r   r"   cloud_init_deepest_matches  s(    




r}   )r   rw   rn   
error_typec             c   s"   |rt |d|gd}||V  dS )zJsonschema validator for `deprecated` items.

    It raises a instance of `error_type` if deprecated that must be handled,
    otherwise the instance is consider faulty.
    T)ri   rn   N)ro   )
_validatorr   Z	_instancerw   rn   r~   rh   r   r   r"   r   #  s    r   )rn   rk   )r~   c             #   s   ddl m} g }g }d}xt|D ]\}	}
t| j||
|	d}tt fdd|}tt fdd|}|sz|j| P t|trd|krd	|
j	d
dkrd|d  |
d
 krd}|E dH  |j| q"W |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)schema_pathc                s   t |   S )N)r\   )e)r~   r   r"   rB   b  s    z_anyOf.<locals>.<lambda>c                s
   t |  S )N)r\   )r   )r~   r   r"   rB   d  s    rp   Z
anyOf_typez$refr   ZanyOf_type_TNz.%r is not valid under any of the given schemas)context)jsonschema.exceptionsr   	enumeraterJ   descendfilterextendr\   rv   rd   r   )	validatoranyOfr^   _schemar~   r   
all_errorsall_deprecationsZskip_best_matchindex	subschemaall_errserrsdeprecationsr   )r~   r"   _anyOf;  s4    




r   c             #   s   t |}g }g }x~|D ]f\}}	tj|	|d}
tt fdd|
}tt fdd|
}|sr|	}|j| P |j| qW t|E dH  fdd|D }|r|j| dj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 )N)r\   )r   )r~   r   r"   rB     s    z_oneOf.<locals>.<lambda>c                s
   t |  S )N)r\   )r   )r~   r   r"   rB     s    Nc                s    g | ]\}}j  |r|qS r   )is_valid)r    is)r^   r   r   r"   r#     s    z_oneOf.<locals>.<listcomp>z, c             s   s   | ]}t |V  qd S )N)repr)r    rw   r   r   r"   	<genexpr>  s    z_oneOf.<locals>.<genexpr>z%r is valid under each of %s)	r   rJ   r   r   r   r}   ry   rC   r   )r   oneOfr^   r   r~   Z
subschemasr   r   r   r   r   r   r   Zfirst_validZ
more_validZreprsr   )r~   r^   r   r"   _oneOf~  s,    

r   c        
      C   s   ddl m} m} ddlm} t| j}ddi|d d< i }t| drdd	|d
< | jj	dt
}d|i}n| j}ttf|d< d|i}t| j}t|t< t|d< t|d< t|d< |f ||dd|}ddd}	|	|_||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   )rV   FormatChecker)createrp   rW   rq   labelrZ   FadditionalPropertiestype_checkerZdefault_typesrk   r   r   Zdraft4)meta_schema
validatorsversionNc             [   s$   t dd | j||}t|ddkS )zgOverride version of `is_valid`.

        It does ignore instances of `SchemaDeprecationError`.
        c             S   s   t | t S )N)r\   r4   )r   r   r   r"   rB     s   z<get_jsonschema_validator.<locals>.is_valid.<locals>.<lambda>N)r   iter_errorsnext)r9   r^   r   __r{   r   r   r"   r     s    z*get_jsonschema_validator.<locals>.is_valid)N)rX   rV   r   Zjsonschema.validatorsr   r   ZMETA_SCHEMArx   rZ   Zredefiner_   ZDEFAULT_TYPESr*   r]   rv   Z
VALIDATORS_validator_deprecatedDEPRECATED_KEY_validator_changedr   r   r   )
rV   r   r   r   Zvalidator_kwargsr   typesr   cloudinitValidatorr   r   r   r"   get_jsonschema_validator  s4    




r   T)rw   c             C   sz   ddl m} y| j| W nZ |k
rt } z>|rXttdjdd |jD |jgd|tj	d| W Y dd}~X 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    rA   r   r   r"   r#     s    z3validate_cloudconfig_metaschema.<locals>.<listcomp>)rG   zGMeta-schema validation failed, attempting to validate config anyway: %sN)
r   r   Zcheck_schemarF   r5   rC   r7   r8   LOGwarning)r   rw   throwr   r|   r   r   r"   validate_cloudconfig_metaschema  s     r   cloud-config)r`   rw   schema_typestrictstrict_metaschemalog_detailslog_deprecationsc             C   sx  |dkrt |}y t \}}|r.t||dd W n tk
rN   tjd dS X ||| d}	g }
g }xt|	j| dd dD ]x}d	jd
d |j	D }| r|j
dkr|j|krtjd|j}|r|d }t||jf}t|tr||7 }q~|
|7 }
q~W |r|rt|ddd}tj| |r:|
s0|r:t|
||
rt|r^t|
d| ddd}nd| d}tj| dS )a  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 string. One of: cloud-config, network-config
       Default: 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
    NF)r   z5Ignoring schema validation. jsonschema is not present)Zformat_checkerc             S   s   | j S )N)r7   )r   r   r   r"   rB   I  s    z-validate_cloudconfig_schema.<locals>.<lambda>)ra   r   c             S   s   g | ]}t |qS r   )r*   )r    rA   r   r   r"   r#   K  s    z/validate_cloudconfig_schema.<locals>.<listcomp>r   z#.*\('(?P<name>.*)' was unexpected\)r+   z"Deprecated cloud-config provided:

)r>   r?   zInvalid z provided:
zQ provided: Please run 'sudo cloud-init schema --system' to see the schema errors.T)
get_schemar   r   rY   r   debugrI   r   rC   r7   r   rw   rematchr8   r5   r\   r4   rE   r   rF   r   )r`   rw   r   r   r   r   r   r   r   r   r{   r   schema_errorr7   Z
prop_matchproblemr8   Zdetailsr   r   r"   validate_cloudconfig_schema  sZ    !










r   c            	   @   s   e Zd Ze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)cloudconfigoriginal_contentschemamarksc             C   s   || _ || _|| _d S )N)_cloudconfig_original_content_schemamarks)r9   r   r   r   r   r   r"   rO   |  s    z_Annotator.__init__)r-   r=   r6   c             C   s   dj |}d|  d| dS )Nr   z# z: -------------
z

)rC   )r-   r=   Zbodyr   r   r"   _build_footer  s    
z_Annotator._build_footer)r@   c             C   s~   t t}xp|D ]h\}}tjd|}|rF|j \}}|t| j| nd }|| j|  j| |d k	rdj|||d}qW |S )Nz&format-l(?P<line>\d+)\.c(?P<col>\d+).*zLine {line} column {col}: {msg})linecolrh   )	r   rJ   r   r   groupsintry   r   r:   )r9   r@   errors_by_liner7   rh   r   r   r   r   r   r"   _build_errors_by_line  s    z _Annotator._build_errors_by_liner   )rL   labelsfooterr   label_prefixr6   c             C   sF   x@| D ]8}| | }|j | |j d| d|  |d7 }qW |S )Nz# z:    )ry   )rL   r   r   r   r   r   r   r   r   r"   _add_problems  s    

z_Annotator._add_problems)linesr   deprecations_by_liner6   c                s   g }g }g }d}d}x~t |dD ]p\}	}
||	 }||	 }|s@|rg } j||||dd} j||||dd}|j|
d dj|  q |j|
 q W |jt fddtd	d d
|fd|ff |S )Nr   E)r   Dz		# ,c                s
    j |  S )N)r   )seq)r9   r   r"   rB     s    z._Annotator._annotate_content.<locals>.<lambda>c             S   s   t | d S )Nr   )rQ   )r   r   r   r"   rB     s    ErrorsZDeprecations)r   r   ry   rC   r   rD   r   )r9   r   r   r   annotated_contentZerror_footerZdeprecation_footerZerror_indexZdeprecation_indexZline_numberr   r{   r   r   r   )r9   r"   _annotate_content  s8    
z_Annotator._annotate_content)rG   rH   r6   c             C   sp   | r| r| j S | j jd}t| jtsDdj|| jddgg S | j|}| j|}| j|||}dj|S )Nr   r   z&# E1: Cloud-config is not a YAML dict.)	r   splitr\   r   rv   rC   r   r   r   )r9   rG   rH   r   r   r   r   r   r   r"   ri     s    


z_Annotator.annotateN)r   )r'   r(   r)   rv   r*   rO   staticmethodr
   r   rT   r   r   r   r   ri   r   r   r   r"   r   {  s    
)r   )rG   rH   )r   r   r   rG   rH   r6   c            C   s   t | ||j|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 unparseable.
    @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   ri   )r   r   r   rG   rH   r   r   r"   annotated_cloudconfig_file  s    r   )r=   r6   c             C   sf   ddl m} || krg S g }xDt| j dD ]2\}}|j|r,|jtd| d|j|d q,W |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 hanlder.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
startswithry   r5   replace)r=   r   r{   Zline_numr   r   r   r"   )process_merged_cloud_config_part_problems  s    

r   )config_pathr=   instance_data_pathr6   c             C   s  ddl m}m}m} t|}d}|dkry||| |}W nd |k
rl } ztt|dg|W Y dd}~X n2 |k
r } ztt|dd W Y dd}~X nX d	}t|}|s|j	d
\}	}
}
tt|d|  d|	 ddj
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.
    r   )JinjaLoadErrorNotJinjaErrorrender_jinja_payload_from_filezformat-l1.c1ztext/jinja2zRDetected type '{user_data_type}' from header. But, content is not a jinja templateNT)sys_exitzformat-l2.c1r   z!Unrecognized user-data header in z: "z%".
Expected first line to be one of: z, ztext/cloud-configzUser-data type 'z.' not currently evaluated by cloud-init schema)Z!cloudinit.handlers.jinja_templater   r   r   r   rF   r5   r   r*   	partitionrC   USERDATA_VALID_HEADERSprintr;   )r   r=   r   r   r   r   Zuser_data_typeZschema_positionr   Zheader_line_r   r   r"   &_get_config_type_and_rendered_userdata&  s6    "$
r   )r   rw   r   ri   r   r6   c          "   C   s  t | dd}|s$td|| f  dS |dkr8t||}nt| ||}|jdkrRdS |j}t|}y&|rvtj|\}	}
ntj	|}	i }
W n t
jk
r` } zd }}d}t|d	rt|d	rt|d	}nt|d
rt|d
rt|d
}|r |jd }|jd }|jtdj||ddj| t| t|}|rJtti |i |jd ||W Y dd}~X nX t|	ts|st| d|  d|dkr|	jd|	}|std dS |jddkrtd|jd  dS y*t|	|ddds td| d dS W n tk
r } zl|j r*||j7 }|rJtt|	||
||jd n |jrjt|jddd}t| |r|t|d|W Y dd}~X 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 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.
    T)decodez,Empty '%s' found at %s. Nothing to validate.Fnetwork-configtext/cloud-configr   NZcontext_markZproblem_markzformat-l{line}.c{col})r   r   zFile {0} is not valid YAML. {1})rG   rb   z is not a YAML dict.Znetworkz:Skipping network-config schema validation on empty config.r   zJSkipping network-config schema validation. No network schema for version: )r   r   z	Skipping z2 schema validation. Jsonschema dependency missing.)rG   rH   z"Cloud config schema deprecations: z, )r>   r?   )r   )r   r   )r   r   r;   r   r<   r=   r   r   Zload_with_marksloadyamlZ	YAMLErrorrx   getattrr   columnry   r5   r:   r*   rF   r   rG   r\   rv   RuntimeErrorrd   r   rR   rH   rE   )r   rw   r   ri   r   Zdecoded_contentZdecoded_configr=   r{   r   Zmarksr   r   r   Zmarkr   Znetcfgr8   r   r   r"   validate_cloudconfig_filec  s    

 






r   c             C   s   | dkrdS | dkrdS dS )zProvide a sorting weight for documentation of property types.

    Weight values ensure 'array' sorted after 'object' which is sorted
    after anything else which remains unsorted.
    Zarray   objectr   r   r   )valuer   r   r"   _sort_property_order  s
    r   c             c   sB   x<| D ]4}t |tr4t |ttf r4t|E d H  q|V  qW d S )N)r\   r   r*   r]   _flatten)Zxsxr   r   r"   r     s    
r   )property_dict	multi_keyr6   c             C   sr   g }x`| j |i D ]P}|j tr"q|j drJ|jdd |j dg D  q|j dr|j|d  qW tt|S )Nrr   c             S   s    g | ]}d t j|| d qS )z``)	_YAML_MAPrd   )r    Z
enum_valuer   r   r"   r#      s   z,_collect_subschema_types.<locals>.<listcomp>rp   )rd   r   r   ry   rJ   r   )r   r   property_typesr   r   r   r"   _collect_subschema_types  s    


r  )r   defsr6   c       
      C   s|  t | | | jdg }t|ts&|g}| jdrDdd | d D }n6| jdr`|jt| d n| jdrz|jt| d t|dkr|d }n|jtd	 d
j	|}| jdi }|jdg }t|ts|g}t
|}xHt|jdi |jdi D ]*}t||}|r|dkrq|j| qW |rrt|dkrF| d|d  S |jtd	 dd
j	| d}	| d|	 S |pzdS )zNReturn a string representing a property type from a given
    jsonschema.
    rp   rr   c             S   s    g | ]}d t j|| d qS )z``)r   rd   )r    kr   r   r"   r#     s    z&_get_property_type.<locals>.<listcomp>r   r   r   r   )ra   /itemsZ	UNDEFINEDz of ())_flatten_schema_refsrd   r\   rJ   r   r  rz   sortr   rC   rQ   r   _get_property_typery   )
r   r  r  Zproperty_typer  Zsub_property_typesZprune_undefinedsub_itemZsub_typeZsub_property_docr   r   r"   r  	  s>    







 
r  c             C   s>   |}t jdd| } t jddj|| } t jddj|| } | S )a  Parse description from the meta in a format that we can better
    display in our docs. This parser does three things:

    - Guarantee that a paragraph will be in a single line
    - Guarantee that each new paragraph will be aligned with
      the first paragraph
    - Proper align lists of items

    @param description: The original description in the meta.
    @param prefix: The number of spaces used to align the current description
    z
(\S)\n(\S)z\1 \2z\n\nz\n\n{}z\n( +)-z\n{}-)r   subr:   )r.   r>   Zlist_paragraphr   r   r"   _parse_description5  s    r  )src_cfgr  c             C   s  d| kr(| j djdd}| j||  d| krd| d krd| d j djdd}| d j||  d| d krx<| d d D ],}d|kr~|j djdd}|j||  q~W xTt| jdg | jdg | jdg D ],}d|kr|j djdd}|j||  qW dS )	zEFlatten schema: replace $refs in src_cfg with definitions from $defs.z$refz#/$defs/r   r  r   r   allOfN)popr   updater   rd   )r  r  Z	reference
sub_schemar   r   r"   r	  K  s&    

r	  )r  c             C   s0   | j dd}|sdS x|D ]}| j| qW dS )zFlatten schema: Merge allOf.

    If a schema as allOf, then all of the sub-schemas must hold. Therefore
    it is safe to merge them.
    r  N)r  r  )r  Zsub_schemasr  r   r   r"   _flatten_schema_all_ofe  s
    
r  )prop_configr6   c             C   s   t ttddd}| jdi }| jdi }g }g }|| || xt||D ]}|||| qJW djt||}|r|d| }|S )aG  Return accumulated property description.

    Account for the following keys:
    - top-level description key
    - any description key present in each subitem under anyOf or allOf

    Order and deprecated property description after active descriptions.
    Add a trailing stop "." to any description not ending with ":".
    )r`   descriptionsdeprecated_descriptionsc             S   s<   t t| jdr |jt|  n| jdr8|jt|  d S )Ndeprecated_versionchanged_versionnew_versionr.   )r  r  r  )anyrD   rd   ry   ro   )r`   r  r  r   r   r"   assign_descriptions}  s    
z6_get_property_description.<locals>.assign_descriptionsr   r   z. rb   )rv   rJ   rd   r   rC   )r  r  r   r   r  r  r  r.   r   r   r"   _get_property_descriptionr  s    
r     )rw   r  r6   c          
      s  |d }g } j ddkrdS  fdddD } fd	d|D }x\|D ]R}xJ|j D ]<\}}	t|	| t|	 |	j ddkrq\t|	}
|	j d
|}|jtj||t|
|d t	|	|d |	j d}|rtt|| |j ds|j dr|jt
j||d |jt|||d xV|j dg D ]F}|j dsF|j dr*|jt
j||d |jt|||d q*W d|	ksd|	kr\|jt|	||d q\W qJW dj|S )zDReturn restructured text describing the supported schema properties.z  hiddenTr   c                s$   g | ]}d  ks| d  kr|qS )r  r   )r    ra   )rw   r   r"   r#     s   z%_get_property_doc.<locals>.<listcomp>rq   patternPropertiesc                s   g | ]} j |i qS r   )rd   )r    ra   )rw   r   r"   r#     s    r   )r>   	prop_namer.   Z	prop_typer  )r>   r!  )r  r>   r   z

)rq   r   )rd   r  r	  r  r  ry   SCHEMA_PROPERTY_TMPLr:   r  r  SCHEMA_LIST_ITEM_TMPL_get_property_docrC   )rw   r  r>   Z
new_prefixrq   Zproperty_keysZproperty_schemasZprop_schemaZprop_keyr  r.   r   r  Z
alt_schemar   )rw   r"   r$    sZ    




r$  )metar6   c             C   sb   | j d}|sdS t}xFt|dD ]8\}}|tj|d7 }tj|djd}|dj|7 }q"W |S )zAReturn restructured text describing the meta examples if present.r1   r   r   )Zexample_countz   r   )	rd   SCHEMA_EXAMPLES_HEADERr   SCHEMA_EXAMPLES_SPACER_TEMPLATEr:   textwrapindentr   rC   )r%  r1   Zrst_contentcountZexampleZindented_linesr   r   r"   _get_examples  s    

r+  c             C   s2   | j dsdS djdd | d D }d| dS )Nr3   r   z, c             s   s   | ]}d | d V  qdS )z``Nr   )r    r  r   r   r"   r     s    z3_get_activate_by_schema_keys_doc.<locals>.<genexpr>z**Activate only on keys:** z

)rd   rC   )r%  Zschema_keysr   r   r"    _get_activate_by_schema_keys_doc  s
    
r,  )r%  rw   r6   c       	      C   s  |dkrt dd}|  s| r&tdt| j }ddddd	d
dh}dh}d}|| rfdj|| }n|| | rdj|| }|rt|tt| }d|d< d|d< d|d< tj	t
t|d
 d|d
< |jdi }|j| d r|j| d i }t
t|}t|d j rPyt||dd|d< W n( tk
rN   tjd d|d< Y nX |jddsfd|d< tj	t| d|d< |d sd|d< dj| d	 |d	< tjdd| d |d< t| |d< tjf |}|S ) zReturn reStructured text rendering the provided metadata.

    @param meta: Dict of metadata to render.
    @param schema: Optional module schema, if absent, read global schema.
    @raise KeyError: If metadata lacks an expected key.
    Nzcloud-config)r   z"Expected non-empty meta and schemar,   r-   r1   r2   r0   r.   r+   r3   r   z(Missing required keys in module meta: {}z3Additional unexpected keys found in module meta: {}Zproperty_headerz      Zprefix6z   Zprefix3z$defsrq   )r  r>   Zproperty_docz3Unable to render property_doc due to invalid schemaz+      No schema definitions for this modulez$         No examples for this modulez, r   -Ztitle_underbar)r   
ValueErrorrK   keysr:   KeyErrorrv   r   r(  r)  r   r*   rd   r  valuesr$  AttributeErrorr   r   r+  rC   r   r  r,  SCHEMA_DOC_TMPL)	r%  rw   r/  Zrequired_keysZoptional_keysZerror_messageZ	meta_copyr  templater   r   r"   get_meta_doc  sd    





r5  c              C   s   t jjt jjt} t| S )N)osr7   dirnameabspath__file__r   )Zconfigs_dirr   r   r"   get_modulesD  s    r:  )requested_modulesr6   c             C   s   d}t t j dg }t| jt|}|rLtdjt |dj|dd xR|D ]J}d| ksf|| krRtj	|dgdg\}}|rRtj
|d	 }||jpd7 }qRW |S )
zaLoad module docstrings

    Docstrings are generated on module load. Reduce, reuse, recycle.
    r   allz+Invalid --docs value {}. Must be one of: {}z, T)r   zcloudinit.configr%  r   )rJ   r:  r1  rK   
differencer   r:   rC   r   find_moduleimport_modulerS   )r;  docsZall_modulesZinvalid_docsZmod_nameZmod_locsr   modr   r   r"   load_docI  s"    

rB  c               C   s   t jjt jjt jjtdS )NZschemas)r6  r7   rC   r7  r8  r9  r   r   r   r"   get_schema_dird  s    rC  )r   r6   c             C   sZ   t jjt t|  d }d}ytjt|}W n& tt	fk
rT   t
jd| | i S X |S )ziReturn jsonschema for a specific type.

    Return empty schema when no specific schema file exists.
    r   Nz;Skipping %s schema valiation. No JSON schema file found %s.)r6  r7   rC   rC  SCHEMA_FILES_BY_TYPEjsonloadsr   IOErrorOSErrorr   r   )r   Zschema_filefull_schemar   r   r"   r   h  s    r   c             C   s   | st jddd} | jdddd | jdd	td
dgdd | jddtdt jd d | jddddd | jddddd | jddddd | S )z0Return a parser for supported cmdline arguments.z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-typezcloud-configznetwork-configz_When providing --config-file, the schema type to validate config against. Default: cloud-config)rp   choicesrK  z-iz--instance-datazbPath to instance-data.json file for variable expansion of '##template: jinja' user-data. Default: instance_data)rp   rK  z--system
store_trueFzVValidate the system instance-data provided as vendor-data user-data and network-config)actiondefaultrK  z-dz--docs+zCPrint schema module docs. Choices: all or space-delimited cc_names.)nargsrK  z
--annotatez;Annotate existing instance-data files any discovered errors)argparseArgumentParseradd_argumentr*   r   get_runpath)parserr   r   r"   
get_parser}  sF    rX  c          )   C   sJ  |j |j|jg}tdd |D dkr2tddd t|j|jgrP|jrPtd |jrh|jrhtddd t	d	d
}|jrtt
|j dS ytdd}W nf ttfk
r } z$|jtkrtjd t }n W Y dd}~X n$ tk
r   t }tjd Y nX |jr|j}n$tj dkr*|jd}n
|jd}|j rL|j|j ff}ntj dkrftddd |jd}|stddd dS y2tj|jdkr|jd}	tj|	jr|	}W n tk
r   Y nX d|ff}d|jdfd|jdfd|jdff}
x4|
D ],\}}|rtjj|r|||ff7 }qW tjj|d d sltd|d d  dd dd! d"}tt|dk}|rtd#d$jd%d& |D   d'}g }xtt |dD ]d\}\}}d(}|rtd)| d*| d+| d, |dkrt	|}|}n|}|d	krdn|}d	}yt!||||j|}W n t"k
r } zN|sRd-}|jst| d.| d/|  tt#||d0 d1 |j$| W Y dd}~X n| t%k
r } z6t| d.|  tt#||d0 d1 |j$| W Y dd}~X n*X |r|j r|n|}t| d2|  qW |rFtd$jd3d& |D d4dd! dS )5z@Handle provided schema args and perform the appropriate actions.c             S   s   g | ]}|r|qS r   r   )r    argr   r   r"   r#     s    z&handle_schema_args.<locals>.<listcomp>r   z;Expected one of --config-file, --system or --docs argumentsT)r   z[WARNING: The --schema-type parameter is inapplicable when either --system or --docs presentz;Invalid flag combination. Cannot use --annotate with --docszcloud-config)r   NZtrust)Zfetch_existing_datasourcez=Using default instance-data/user-data paths for non-root userzEdatasource not detected, using default instance-data/user-data paths.r   rM  Zinstance_data_sensitivezNUnable to read system userdata or vendordata as non-root user. Try using sudo.Zcloud_configz;Unable to obtain user data file. No instance data availableZuserdata_rawz	user-datazvendor-dataZvendor_cloud_configzvendor2-dataZvendor2_cloud_configznetwork-configZnetwork_configzConfig file z does not existz	Error: {})fmtr   r   z!Found cloud-config data types: %sz, c             s   s   | ]\}}|V  qd S )Nr   )r    cfg_typer   r   r   r"   r     s    z%handle_schema_args.<locals>.<genexpr>z  Fr   z. z at :ZUNKNOWN_CONFIG_HEADERzInvalid rb   z
Error: {}
)rZ  zValid schema c             s   s   | ]
}|V  qd S )Nr   )r    r~   r   r   r"   r   H  s    zError: Invalid schema: {}
)&Zconfig_filer@  systemrz   r   r  r   r   ri   r   rB  r   rG  rH  errnor   r   r   r   r   rM  r6  getuidrV  Z	get_ipathstatst_sizeFileNotFoundErrorr7   existsrQ   rC   r   r   rF   r*   ry   r   )r+   argsZexclusive_argsrI  pathsr   r   Zconfig_filesZuserdata_fileZraw_userdata_fileZsupplemental_config_filesr[  Zcfg_fileZnested_output_prefixZmulti_config_outputZerror_typesidxZperformed_schema_validationZ
cfg_schemar   Zcfgr   r   r"   handle_schema_args  s    







rg  c              C   s   t  } td| j  dS )zDTool to validate schema of a cloud-config file or print schema docs.zcloudconfig-schemar   )rX  rg  
parse_args)rW  r   r   r"   mainN  s    ri  __main__)FN)T)Nr   FFTF)N)r   FN)r  )N)r   )N)xrS   rS  rE  Zloggingr6  r   sysr(  collectionsr   collections.abcr   copyr   r^  r   	functoolsr   	itertoolsr   r/   r   r	   r
   r   r   r   r   r   r   Z	cloudinitr   r   Zcloudinit.cmd.develr   Zcloudinit.handlersr   r   Zcloudinit.sourcesr   Zcloudinit.utilr   r   r   rX   r   Z_ValidationErrorrY   	ExceptionZ	getLoggerr'   r   ZVERSIONED_USERDATA_SCHEMA_FILEZUSERDATA_SCHEMA_FILEZNETWORK_CONFIG_V1_SCHEMA_FILErD  r   r3  ZSCHEMA_PROPERTY_HEADERr"  r#  r&  r'  r   ZDEPRECATED_PREFIXrI   r/  r   Ztyping_extensionsr$   r%   r&   rv   r4   r5   rT   r;   r*   rE   r.  rF   r_   ro   r}   rQ   r   r   r   r   r   r   r   r   r   r]   r   r   r   r   r   r   r  r  r  r	  r  r  r$  r+  r,  r5  r:  rJ   rB  rC  r   rX  rg  ri  exitr   r   r   r"   <module>   s   (

)!'C%L%      ]z<  z,*F	J
A 
