U
    M8cI                     @   s   d Z ddlZddlZddlmZ ddlmZmZmZ ddl	m
Z
mZ ddlmZ deiZerpddlmZ eed	< eeZd
d ZG dd dZdddZG dd dZG dd dZdS )a  Module for loading various model files.

This module provides the classes that are used to load models used
by botocore.  This can include:

    * Service models (e.g. the model for EC2, S3, DynamoDB, etc.)
    * Service model extras which customize the service models
    * Other models associated with a service (pagination, waiters)
    * Non service-specific config (Endpoint data, retry config)

Loading a module is broken down into several steps:

    * Determining the path to load
    * Search the data_path for files to load
    * The mechanics of loading the file
    * Searching for extras and applying them to the loaded file

The last item is used so that other faster loading mechanism
besides the default JSON loader can be used.

The Search Path
===============

Similar to how the PATH environment variable is to finding executables
and the PYTHONPATH environment variable is to finding python modules
to import, the botocore loaders have the concept of a data path exposed
through AWS_DATA_PATH.

This enables end users to provide additional search paths where we
will attempt to load models outside of the models we ship with
botocore.  When you create a ``Loader``, there are two paths
automatically added to the model search path:

    * <botocore root>/data/
    * ~/.aws/models

The first value is the path where all the model files shipped with
botocore are located.

The second path is so that users can just drop new model files in
``~/.aws/models`` without having to mess around with the AWS_DATA_PATH.

The AWS_DATA_PATH using the platform specific path separator to
separate entries (typically ``:`` on linux and ``;`` on windows).


Directory Layout
================

The Loader expects a particular directory layout.  In order for any
directory specified in AWS_DATA_PATH to be considered, it must have
this structure for service models::

    <root>
      |
      |-- servicename1
      |   |-- 2012-10-25
      |       |-- service-2.json
      |-- ec2
      |   |-- 2014-01-01
      |   |   |-- paginators-1.json
      |   |   |-- service-2.json
      |   |   |-- waiters-2.json
      |   |-- 2015-03-01
      |       |-- paginators-1.json
      |       |-- service-2.json
      |       |-- waiters-2.json
      |       |-- service-2.sdk-extras.json


That is:

    * The root directory contains sub directories that are the name
      of the services.
    * Within each service directory, there's a sub directory for each
      available API version.
    * Within each API version, there are model specific files, including
      (but not limited to): service-2.json, waiters-2.json, paginators-1.json

The ``-1`` and ``-2`` suffix at the end of the model files denote which version
schema is used within the model.  Even though this information is available in
the ``version`` key within the model, this version is also part of the filename
so that code does not need to load the JSON model in order to determine which
version to use.

The ``sdk-extras`` and similar files represent extra data that needs to be
applied to the model after it is loaded. Data in these files might represent
information that doesn't quite fit in the original models, but is still needed
for the sdk. For instance, additional operation parameters might be added here
which don't represent the actual service api.
    N)BOTOCORE_ROOT)HAS_GZIPOrderedDictjson)DataNotFoundErrorUnknownServiceError
deep_mergez.json)openz.json.gzc                    s    fdd}|S )a  Cache the result of a method on a per instance basis.

    This is not a general purpose caching decorator.  In order
    for this to be used, it must be used on methods on an
    instance, and that instance *must* provide a
    ``self._cache`` dictionary.

    c                    sX    j f| }t| D ]}||7 }q|| jkr:| j| S  | f||}|| j|< |S N)__name__sorteditems_cache)selfargskwargskeypairdatafunc 4/tmp/pip-unpacked-wheel-ozje0y8b/botocore/loaders.py_wrapper   s    



z instance_cache.<locals>._wrapperr   )r   r   r   r   r   instance_cache~   s    

r   c                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	JSONFileLoaderzeLoader JSON files.

    This class can load the default format of models, which is a JSON file.

    c                 C   s$   t D ]}tj|| r dS qdS )zChecks if the file exists.

        :type file_path: str
        :param file_path: The full path to the file to load without
            the '.json' extension.

        :return: True if file path exists, False otherwise.

        TF)_JSON_OPEN_METHODSospathisfile)r   	file_pathextr   r   r   exists   s    
zJSONFileLoader.existsc              	   C   sN   t j|sd S ||d}| d}W 5 Q R X td| tj|t	dS )Nrbzutf-8zLoading JSON file: %s)object_pairs_hook)
r   r   r    readdecodeloggerdebugr   loadsr   )r   	full_pathopen_methodfppayloadr   r   r   
_load_file   s    zJSONFileLoader._load_filec                 C   s6   t  D ](\}}| || |}|dk	r|  S qdS )zAttempt to load the file path.

        :type file_path: str
        :param file_path: The full path to the file to load without
            the '.json' extension.

        :return: The loaded data if it exists, otherwise None.

        N)r   r   r/   )r   r!   r"   r,   r   r   r   r   	load_file   s
    

zJSONFileLoader.load_fileN)r   
__module____qualname____doc__r#   r/   r0   r   r   r   r   r      s   r   c                 C   sP   | dkrt  S g }| tj}|D ]"}tjtj|}|| q"t |dS )a  Create a Loader class.

    This factory function creates a loader given a search string path.

    :type search_string_path: str
    :param search_string_path: The AWS_DATA_PATH value.  A string
        of data path values separated by the ``os.path.pathsep`` value,
        which is typically ``:`` on POSIX platforms and ``;`` on
        windows.

    :return: A ``Loader`` instance.

    N)extra_search_paths)Loadersplitr   pathsepr   
expanduser
expandvarsappend)Zsearch_path_stringpathsZextra_pathsr   r   r   r   create_loader   s    r<   c                   @   s   e Zd ZdZeZeje	dZ
ejejdddZdgZd"d	d
Zedd Zedd Zedd Zedd Zedd Zed#ddZdd Zedd Zdd Zd$ddZd d! ZdS )%r5   zFind and load data models.

    This class will handle searching for and loading data models.

    The main method used here is ``load_service_model``, which is a
    convenience method over ``load_data`` and ``determine_latest_version``.

    r   ~z.awsmodelsZsdkNTc                 C   sn   i | _ |d kr|  }|| _|d k	r,|| _ng | _|rJ| j| j| jg g | _|rb| j| j t	 | _
d S r   )r   FILE_LOADER_CLASSfile_loader_search_pathsextendCUSTOMER_DATA_PATHBUILTIN_DATA_PATH_extras_typesBUILTIN_EXTRAS_TYPESExtrasProcessor_extras_processor)r   r4   r@   cacheZinclude_default_search_pathsZinclude_default_extrasr   r   r   __init__   s    
zLoader.__init__c                 C   s   | j S r   )rA   r   r   r   r   search_paths  s    zLoader.search_pathsc                 C   s   | j S r   )rE   rK   r   r   r   extras_types  s    zLoader.extras_typesc           	         s   t  }|  D ]r  fddt D }|D ]P}tj |}t|}|D ].}tj|||}| j|rN||  q.qNq.qt	|S )ap  List all known services.

        This will traverse the search path and look for all known
        services.

        :type type_name: str
        :param type_name: The type of the service (service-2,
            paginators-1, waiters-2, etc).  This is needed because
            the list of available services depends on the service
            type.  For example, the latest API version available for
            a resource-1.json file may not be the latest API version
            available for a services-2.json file.

        :return: A list of all services.  The list of services will
            be sorted.

        c                    s&   g | ]}t jt j |r|qS r   )r   r   isdirjoin).0dpossible_pathr   r   
<listcomp>0  s   z2Loader.list_available_services.<locals>.<listcomp>)
set_potential_locationsr   listdirr   rO   r@   r#   addr   )	r   	type_nameZservicesZpossible_servicesservice_nameZfull_dirnameZapi_versionsapi_versionZfull_load_pathr   rR   r   list_available_services  s$    

  

zLoader.list_available_servicesc                 C   s   t | ||S )a  Find the latest API version available for a service.

        :type service_name: str
        :param service_name: The name of the service.

        :type type_name: str
        :param type_name: The type of the service (service-2,
            paginators-1, waiters-2, etc).  This is needed because
            the latest API version available can depend on the service
            type.  For example, the latest API version available for
            a resource-1.json file may not be the latest API version
            available for a services-2.json file.

        :rtype: str
        :return: The latest API version.  If the service does not exist
            or does not have any available API data, then a
            ``DataNotFoundError`` exception will be raised.

        )maxlist_api_versions)r   rZ   rY   r   r   r   determine_latest_versionA  s    zLoader.determine_latest_versionc                 C   sh   t  }| j|dddD ]:}t|D ]*}tj|||}| j|r$|| q$q|s`t	|dt
|S )ay  List all API versions available for a particular service type

        :type service_name: str
        :param service_name: The name of the service

        :type type_name: str
        :param type_name: The type name for the service (i.e service-2,
            paginators-1, etc.)

        :rtype: list
        :return: A list of API version strings in sorted order.

        T)
must_existis_dirZ	data_path)rU   rV   r   rW   r   rO   r@   r#   rX   r   r   )r   rZ   rY   Zknown_api_versionsrS   dirnamer+   r   r   r   r^   X  s      

zLoader.list_api_versionsc                 C   sv   |  |}||kr(t|dt|d|dkr<| ||}tj|||}| |}| |||}| j	
|| |S )aJ  Load a botocore service model

        This is the main method for loading botocore models (e.g. a service
        model, pagination configs, waiter configs, etc.).

        :type service_name: str
        :param service_name: The name of the service (e.g ``ec2``, ``s3``).

        :type type_name: str
        :param type_name: The model type.  Valid types include, but are not
            limited to: ``service-2``, ``paginators-1``, ``waiters-2``.

        :type api_version: str
        :param api_version: The API version to load.  If this is not
            provided, then the latest API version will be used.

        :type load_extras: bool
        :param load_extras: Whether or not to load the tool extras which
            contain additional data to be added to the model.

        :raises: UnknownServiceError if there is no known service with
            the provided service_name.

        :raises: DataNotFoundError if no data could be found for the
            service_name/type_name/api_version.

        :return: The loaded data, as a python type (e.g. dict, list, etc).
        z, )rZ   Zknown_service_namesN)r\   r   rO   r   r_   r   r   	load_data_find_extrasrH   process)r   rZ   rY   r[   Zknown_servicesr+   modelZextras_datar   r   r   load_service_modelv  s      
 
zLoader.load_service_modelc              	   c   sV   | j D ]J}| d| d}tj|||}z| |V  W q tk
rN   Y qX qdS )z-Creates an iterator over all the extras data..z-extrasN)rM   r   r   rO   rd   r   )r   rZ   rY   r[   Zextras_typeZextras_namer+   r   r   r   re     s    
zLoader._find_extrasc                 C   s>   |  |D ]$}| j|}|dk	r
||f  S q
t|ddS )aj  Same as ``load_data`` but returns file path as second return value.

        :type name: str
        :param name: The data path, i.e ``ec2/2015-03-01/service-2``.

        :return: Tuple of the loaded data and the path to the data file
            where the data was loaded from. If no data could be found then a
            DataNotFoundError is raised.
        Nrb   )rV   r@   r0   r   )r   namerS   foundr   r   r   load_data_with_path  s
    zLoader.load_data_with_pathc                 C   s   |  |\}}|S )a  Load data given a data path.

        This is a low level method that will search through the various
        search paths until it's able to load a value.  This is typically
        only needed to load *non* model files (such as _endpoints and
        _retry).  If you need to load model files, you should prefer
        ``load_service_model``.  Use ``load_data_with_path`` to get the
        data path of the data file as second return value.

        :type name: str
        :param name: The data path, i.e ``ec2/2015-03-01/service-2``.

        :return: The loaded data. If no data could be found then
            a DataNotFoundError is raised.
        )rl   )r   rj   r   _r   r   r   rd     s    zLoader.load_dataFc                 c   sl   | j D ]`}tj|r|}|d k	r0tj||}|s<|V  q|rTtj|rT|V  qtj|r|V  qd S r   )rL   r   r   rN   rO   r#   )r   rj   r`   ra   r   r+   r   r   r   rV     s    
zLoader._potential_locationsc                 C   s    t jt j|}|| jS )a  Whether a given path is within the package's data directory.

        This method can be used together with load_data_with_path(name)
        to determine if data has been loaded from a file bundled with the
        package, as opposed to a file in a separate location.

        :type path: str
        :param path: The file path to check.

        :return: Whether the given path is within the package's data directory.
        )r   r   r8   r9   
startswithrD   )r   r   r   r   r   is_builtin_path  s    zLoader.is_builtin_path)NNNTT)N)NFF)r   r1   r2   r3   r   r?   r   r   rO   r   rD   r8   rC   rF   rJ   propertyrL   rM   r   r\   r_   r^   rh   re   rl   rd   rV   ro   r   r   r   r   r5      sB   	
       



*

2

r5   c                   @   s    e Zd ZdZdd Zdd ZdS )rG   z5Processes data from extras files into service models.c                 C   s   |D ]}|  || qdS )a$  Processes data from a list of loaded extras files into a model

        :type original_model: dict
        :param original_model: The service model to load all the extras into.

        :type extra_models: iterable of dict
        :param extra_models: A list of loaded extras models.
        N)_process)r   Zoriginal_modelZextra_modelsextrasr   r   r   rf     s    	zExtrasProcessor.processc                 C   s   d|krt ||d  dS )z3Process a single extras model into a service model.mergeNr   )r   rg   Zextra_modelr   r   r   rq   	  s    zExtrasProcessor._processN)r   r1   r2   r3   rf   rq   r   r   r   r   rG     s   rG   )N)r3   loggingr   Zbotocorer   Zbotocore.compatr   r   r   Zbotocore.exceptionsr   r   Zbotocore.utilsr	   r
   r   gzipZ	gzip_open	getLoggerr   r(   r   r   r<   r5   rG   r   r   r   r   <module>   s(   [ 
3
  