o .&ai@sdZddlZddlZddlZddlZddlZddlZddlmZddlm Z ddl Zddl Zddl Zddl mZddl mZddl mZddl mZdd lmZmZmZmZdd lmZdd lmZdd lmZmZdd lmZddlmZddl m!Z!ddl"m#Z#ddl$m%Z%ddlm&Z&ddlm'Z'ddlm(Z(ddlm)Z)m*Z*ddl+m,Z,m-Z-ddl.m/Z/m0Z0e1e2Z3Gddde4Z5Gddde4Z6Gddde/Z7Gddde4Z8d"d d!Z9dS)#zV This module contains the main interface to the botocore package, the Session object. N) __version__)UNSIGNED)ConfigValueStore)ConfigChainFactory)&create_botocore_default_config_mapping)!BOTOCORE_DEFAUT_SESSION_VARIABLES)ConfigNotFoundProfileNotFoundUnknownServiceErrorPartialCredentialsError)ClientExceptionsFactory)handlers)HierarchicalEmitterfirst_non_none_response) EventAliaser) create_loader)ResponseParserFactory)EndpointResolver) ServiceModel) monitoring)paginate)waiter) retryhandler translate) EVENT_ALIASESvalidate_region_name)MutableMappingHAS_CRTc@seZdZdZeeZdZ  dpddZddZ d d Z d d Z d dZ ddZ ddZddZddZddZddZddZddZdd Zed!d"Zd#d$Zed%d&Zdqd'd(Zd)d*Zd+d,Zd-d.Zd/d0Zed1d2Zd3d4Z d5d6Z!dqd7d8Z"d9d:Z#d;d<Z$d=d>Z%dqd?d@Z&dqdAdBZ'dqdCdDZ(dqdEdFZ)dGdHZ*drdJdKZ+  dsdLdMZ,drdNdOZ-  PdtdQdRZ.  PdudSdTZ/dUdVZ0dWdXZ1dYdZZ2d[d\Z3d]d^Z4d_d`Z5dadbZ6    dvdcddZ7dedfZ8dgdhZ9didjZ:dkdlZ; m PdwdndoZsz/Session._register_data_loader..r0rMrGr;rGr<r@s zSession._register_data_loadercsfdd}jd|dS)Ncsd}|d}t|S)NrT endpoints) get_component load_datar)loaderrYrGr;r<create_default_resolvers  zDSession._register_endpoint_resolver..create_default_resolverendpoint_resolver)r1rM)r7r]r;rGr<rAs z#Session._register_endpoint_resolvercC|jdtdS)Nresponse_parser_factory)r0rJrrGr;r;r<rCsz)Session._register_response_parser_factorycCr_)Nexceptions_factory)r1rJr rGr;r;r<rDrOz$Session._register_exceptions_factorycCsntjD]1}t|dkr|\}}|||q|\}}}|tjur(|j||q|tjur4|j||qdS)N) r BUILTIN_HANDLERSlenregisterREGISTER_FIRSTr#register_first REGISTER_LAST register_last)r7eventsspec event_namehandler register_typer;r;r<r$s     z"Session._register_builtin_handlerscCs tt|d}|jd|dS)Nmapping config_store)rrr0rJ)r7config_store_componentr;r;r<rEs zSession._register_config_storecCrH)Nmonitor)r1rM_create_csm_monitorrGr;r;r<rFrOzSession._register_monitorc Csd|dr0|d}|d}|d}tjttjttjtj||tj|ddd}|SdS)N csm_enabled csm_client_idcsm_hostcsm_port)rv)sockethostport serializer)adapter publisher) rVrMonitorMonitorEventAdapterSocketPublisherryAF_INET SOCK_DGRAM CSMSerializer)r7 client_idrzr{rmr;r;r<rts"     zSession._create_csm_monitorcCs&zddl}|jWStyYdSw)NrUnknown)awscrtrAttributeError)r7rr;r;r<_get_crt_versions  zSession._get_crt_versioncCst|Sr>)list_build_profile_mapkeysrGr;r;r<available_profilesszSession.available_profilescCs|jdur |jd|_|jS)Nprofiles)r+ full_configrGr;r;r<rs  zSession._build_profile_mapcCs |jdur |d}||_|jS)Nr!)r(rV)r7r!r;r;r<r!s  zSession.profilecCs$|dur |||S|d|S)Nrq)(_get_config_variable_with_custom_methodsrZrV)r7 logical_namemethodsr;r;r<rVs zSession.get_config_variablecCst||d}t|}|jD]1\}}|\}}} } | | d} d|vr&|| d<d|vr.|| d<d|vr6|| d<|jd i| ||<qt|d } | |} | S) N)sessionr)conversion_funcdefaultinstance instance_nameenv env_var_namesconfigconfig_property_nameror;)SubsetChainConfigFactoryrr5itemscreate_config_chainrrV)r7rr chain_builderrpnameconfig_options config_nameenv_varsrtypecastbuild_chain_config_argsrrvaluer;r;r<rs*    z0Session._get_config_variable_with_custom_methodscCstd||||j|<dS)aSet a configuration variable to a specific value. By using this method, you can override the normal lookup process used in ``get_config_variable`` by explicitly setting a value. Subsequent calls to ``get_config_variable`` will use the ``value``. This gives you per-session specific configuration values. :: >>> # Assume logical name 'foo' maps to env var 'FOO' >>> os.environ['FOO'] = 'myvalue' >>> s.get_config_variable('foo') 'myvalue' >>> s.set_config_variable('foo', 'othervalue') >>> s.get_config_variable('foo') 'othervalue' :type logical_name: str :param logical_name: The logical name of the session variable you want to set. These are the keys in ``SESSION_VARIABLES``. :param value: The value to associate with the config variable. z$Setting config variable for %s to %rN)loggerdebugr,)r7rrr;r;r<set_config_variables zSession.set_config_variablecCs t|jSr>)copyr,rGr;r;r<instance_variables5 zSession.instance_variablescCs@|d}|}|dur|diS||vrt|d||S)a5 Returns the config values from the config file scoped to the current profile. The configuration data is loaded **only** from the config file. It does not resolve variables based on different locations (e.g. first from the session instance, then from environment variables, then from the config file). If you want this lookup behavior, use the ``get_config_variable`` method instead. Note that this configuration is specific to a single profile (the ``profile`` session variable). If the ``profile`` session variable is set and the profile does not exist in the config file, a ``ProfileNotFound`` exception will be raised. :raises: ConfigNotFound, ConfigParseError, ProfileNotFound :rtype: dict r!Nr)r!)rVrgetr )r7 profile_name profile_mapr;r;r<get_scoped_config8s   zSession.get_scoped_configcCs|jdur_z|d}tj||_Wnty!dii|_Ynwz1|d}tj|}|D]}||}||jdvrE||jd|<q0|jd||q0W|jSty^Y|jSw|jS)zReturn the parsed config file. The ``get_config`` method returns the config associated with the specified profile. This property returns the contents of the **entire** config file. :rtype: dict N config_filercredentials_file)r)rVrQ configloader load_configrraw_config_parser6)r7r cred_file cred_profilesr! cred_varsr;r;r<r]s0     zSession.full_configcCs|jS)aRetrieves the default config for creating clients :rtype: botocore.client.Config :returns: The default client config object when creating clients. If the value is ``None`` then there is no default config object attached to the session. r-rGr;r;r<get_default_client_configsz!Session.get_default_client_configcCs ||_dS)a1Sets the default config for creating clients :type client_config: botocore.client.Config :param client_config: The default client config object when creating clients. If the value is ``None`` then there is no default config object attached to the session. Nr)r7 client_configr;r;r<set_default_client_configs z!Session.set_default_client_configcCstj||||_dS)aO Manually create credentials for this session. If you would prefer to use botocore without a config file, environment variables, or IAM roles, you can pass explicit credentials into this method to establish credentials for this session. :type access_key: str :param access_key: The access key part of the credentials. :type secret_key: str :param secret_key: The secret key part of the credentials. :type token: str :param token: An option session token used by STS session credentials. N)rQrR Credentialsr*)r7 access_key secret_keytokenr;r;r<set_credentialss zSession.set_credentialscCs"|jdur|jd|_|jS)a$ Return the :class:`botocore.credential.Credential` object associated with this session. If the credentials have not yet been loaded, this will attempt to load them. If they have already been loaded, this will return the cached credentials. NrL)r*r0rZload_credentialsrGr;r;r<get_credentialss zSession.get_credentialscCsrd|j|jtttf}tr|d|7}tj ddur-|dtj d7}|j r7|d|j 7}|S)ak Return a string suitable for use as a User-Agent header. The string will be of the form: / Python/ / Where: - agent_name is the value of the `user_agent_name` attribute of the session object (`Botocore` by default). - agent_version is the value of the `user_agent_version` attribute of the session object (the botocore version by default). by default. - py_ver is the version of the Python interpreter beng used. - plat_name is the name of the platform (e.g. Darwin) - plat_ver is the version of the platform - exec_env is exec-env/$AWS_EXECUTION_ENV If ``user_agent_extra`` is not empty, then this value will be appended to the end of the user agent string. z%s/%s Python/%s %s/%sz awscrt/%sAWS_EXECUTION_ENVNz exec-env/%sz %s) r%r&platformpython_versionsystemreleaserrosenvironrr')r7baser;r;r< user_agentszSession.user_agentcCs|d|S)z Retrieve the data associated with `data_path`. :type data_path: str :param data_path: The path to the data you wish to retrieve. rT)rZr[)r7rUr;r;r<get_dataszSession.get_datacCs|||}t||dS)aGet the service model object. :type service_name: string :param service_name: The service name :type api_version: string :param api_version: The API version of the service. If none is provided, then the latest API version will be used. :rtype: L{botocore.model.ServiceModel} :return: The botocore service model for the service. ) service_name)get_service_datar)r7r api_versionservice_descriptionr;r;r<get_service_models  zSession.get_service_modelcC"|d}||d|}t|S)NrTz waiters-2)rZload_service_modelr WaiterModel)r7rrr\ waiter_configr;r;r<get_waiter_model  zSession.get_waiter_modelcCr)NrTz paginators-1)rZrrPaginatorModel)r7rrr\paginator_configr;r;r<get_paginator_modelrzSession.get_paginator_modelcCsB|}|dj|d|d}t||}|jjd||||d|S)zK Retrieve the fully merged data associated with a service. rT service-2) type_namerzservice-data-loaded.%s) service_datarr)rZrrrr#emit)r7rrrUr service_idr;r;r<rs   zSession.get_service_datacCs|djddS)z? Return a list of names of available services. rTr)r)rZlist_available_servicesrGr;r;r<get_available_servicesszSession.get_available_servicesrQcCs||tjdS)zk Convenience function to quickly configure full debug output to go to the console. N)set_stream_loggerloggingDEBUG)r7 logger_namer;r;r<set_debug_loggerszSession.set_debug_loggercCsZt|}|tjt|}|||dur|j}t|}||||dS)a Convenience method to configure a stream logger. :type logger_name: str :param logger_name: The name of the logger to configure :type log_level: str :param log_level: The log level to set for the logger. This is any param supported by the ``.setLevel()`` method of a ``Log`` object. :type stream: file :param stream: A file like object to log to. If none is provided then sys.stderr will be used. :type format_string: str :param format_string: The format string to use for the log formatter. If none is provided this will default to ``self.LOG_FORMAT``. N) r getLoggersetLevelr StreamHandler LOG_FORMAT Formatter setFormatter addHandler)r7r log_levelstream format_stringlogch formatterr;r;r<r s      zSession.set_stream_loggercCsNt|}|tjt|}||t|j}||||dS)aV Convenience function to quickly configure any level of logging to a file. :type log_level: int :param log_level: A log level as specified in the `logging` module :type path: string :param path: Path to the log file. The file will be created if it doesn't already exist. N) rrrr FileHandlerrrrr)r7rpathrrrrr;r;r<set_file_loggerHs     zSession.set_file_loggerFcC|jj||||ddS)a)Register a handler with an event. :type event_name: str :param event_name: The name of the event. :type handler: callable :param handler: The callback to invoke when the event is emitted. This object must be callable, and must accept ``**kwargs``. If either of these preconditions are not met, a ``ValueError`` will be raised. :type unique_id: str :param unique_id: An optional identifier to associate with the registration. A unique_id can only be used once for the entire session registration (unless it is unregistered). This can be used to prevent an event handler from being registered twice. :param unique_id_uses_count: boolean :param unique_id_uses_count: Specifies if the event should maintain a count when a ``unique_id`` is registered and unregisted. The event can only be completely unregistered once every register call using the unique id has been matched by an ``unregister`` call. If ``unique_id`` is specified, subsequent ``register`` calls must use the same value for ``unique_id_uses_count`` as the ``register`` call that first registered the event. :raises ValueError: If the call to ``register`` uses ``unique_id`` but the value for ``unique_id_uses_count`` differs from the ``unique_id_uses_count`` value declared by the very first ``register`` call for that ``unique_id``. )unique_id_uses_countN)r#rer7rlrm unique_idrr;r;r<reds " zSession.registercCr)aUnregister a handler with an event. :type event_name: str :param event_name: The name of the event. :type handler: callable :param handler: The callback to unregister. :type unique_id: str :param unique_id: A unique identifier identifying the callback to unregister. You can provide either the handler or the unique_id, you do not have to provide both. :param unique_id_uses_count: boolean :param unique_id_uses_count: Specifies if the event should maintain a count when a ``unique_id`` is registered and unregisted. The event can only be completely unregistered once every ``register`` call using the ``unique_id`` has been matched by an ``unregister`` call. If the ``unique_id`` is specified, subsequent ``unregister`` calls must use the same value for ``unique_id_uses_count`` as the ``register`` call that first registered the event. :raises ValueError: If the call to ``unregister`` uses ``unique_id`` but the value for ``unique_id_uses_count`` differs from the ``unique_id_uses_count`` value declared by the very first ``register`` call for that ``unique_id``. )rmrrN)r# unregisterrr;r;r<rs  zSession.unregistercKs|jj|fi|Sr>)r#r)r7rlkwargsr;r;r<rrKz Session.emitcKs|jj|fi|}t|Sr>)r#rr)r7rlr responsesr;r;r<emit_first_non_none_responsesz$Session.emit_first_non_none_responsecCsHz|j|WSty#|dvr"td|t|j|YSw)N)r^razFetching the %s component with the get_component() method is deprecated as the component has always been considered an internal interface of botocore)r0rZ ValueErrorwarningswarnDeprecationWarningr1r7rr;r;r<rZs zSession.get_componentcCs |j|Sr>)r1rZrr;r;r<_get_internal_components zSession._get_internal_componentcCs|j||Sr>)r1rJr7r componentr;r;r<_register_internal_componentsz$Session._register_internal_componentcC|j||dSr>)r0rJrr;r;r<rJzSession.register_componentcCr r>rXrr;r;r<rMr zSession.lazy_register_componentc  Csl|} | dur| dur| | } n| dur| } ||| }|dur'|d}|dur4|d|d}|d} |d} |d}| durO| jturOd}n&|dura|duratj j ||| d}n| ||rqt d| ||d | }|d }|d }|d }tj| ||| tt||| }|j|||||||| |d }|d}|dur||jj|S)aP Create a botocore client. :type service_name: string :param service_name: The name of the service for which a client will be created. You can use the ``Session.get_available_services()`` method to get a list of all available service names. :type region_name: string :param region_name: The name of the region associated with the client. A client is associated with a single region. :type api_version: string :param api_version: The API version to use. By default, botocore will use the latest API version when creating a client. You only need to specify this parameter if you want to use a previous API version of the client. :type use_ssl: boolean :param use_ssl: Whether or not to use SSL. By default, SSL is used. Note that not all services support non-ssl connections. :type verify: boolean/string :param verify: Whether or not to verify SSL certificates. By default SSL certificates are verified. You can provide the following values: * False - do not validate SSL certificates. SSL will still be used (unless use_ssl is False), but SSL certificates will not be verified. * path/to/cert/bundle.pem - A filename of the CA cert bundle to uses. You can specify this argument if you want to use a different CA cert bundle than the one used by botocore. :type endpoint_url: string :param endpoint_url: The complete URL to use for the constructed client. Normally, botocore will automatically construct the appropriate URL to use when communicating with a service. You can specify a complete URL (including the "http/https" scheme) to override this behavior. If this value is provided, then ``use_ssl`` is ignored. :type aws_access_key_id: string :param aws_access_key_id: The access key to use when creating the client. This is entirely optional, and if not provided, the credentials configured for the session will automatically be used. You only need to provide this argument if you want to override the credentials used for this specific client. :type aws_secret_access_key: string :param aws_secret_access_key: The secret key to use when creating the client. Same semantics as aws_access_key_id above. :type aws_session_token: string :param aws_session_token: The session token to use when creating the client. Same semantics as aws_access_key_id above. :type config: botocore.client.Config :param config: Advanced client configuration options. If a value is specified in the client config, its value will take precedence over environment variables and configuration values, but not over a value passed explicitly to the method. If a default config object is set on the session, the config object used when creating the client will be the result of calling ``merge()`` on the default config with the config provided to this call. :rtype: botocore.client.BaseClient :return: A botocore client instance N ca_bundle api_versionsrTrIr`)rrrexplicit)providercred_varr^rarq) rrP is_secure endpoint_urlverifyrR scoped_configrrrs)rmerge_resolve_region_namerVrrZsignature_versionrrQrRr_missing_cred_varsr rrclient ClientCreatorrrr create_clientrremetarj)r7rrPruse_sslrraws_access_key_idaws_secret_access_keyaws_session_tokenrdefault_client_configr\rIr`rRr^rarqclient_creatorrrsr;r;r<rsjI           zSession.create_clientcCs:|dur|r|jdur|j}n|d}t|||_|S)Nregion)rPrVrr.)r7rPrr;r;r<rSs  zSession._resolve_region_namecCs,|dur |dur dS|dur|durdSdS)Nrrr;)r7rrr;r;r<ris zSession._missing_cred_varscCs|d}|S)zLists the available partitions found on disk :rtype: list :return: Returns a list of partition names (e.g., ["aws", "aws-cn"]) r^)rget_available_partitions)r7resolverr;r;r<r#ps z Session.get_available_partitionscCs|d}||S)aLists the partition name of a particular region. :type region_name: string :param region_name: Name of the region to list partition for (e.g., us-east-1). :rtype: string :return: Returns the respective partition name (e.g., aws). r^)rget_partition_for_region)r7rPr$r;r;r<r%ys z Session.get_partition_for_regionawscCsR|d}g}z||}|dd|}||||}W|Sty(Y|Sw)a]Lists the region and endpoint names of a particular partition. :type service_name: string :param service_name: Name of a service to list endpoint for (e.g., s3). This parameter accepts a service name (e.g., "elb") or endpoint prefix (e.g., "elasticloadbalancing"). :type partition_name: string :param partition_name: Name of the partition to limit endpoints to. (e.g., aws for the public AWS endpoints, aws-cn for AWS China endpoints, aws-us-gov for AWS GovCloud (US) Endpoints, etc. :type allow_non_regional: bool :param allow_non_regional: Set to True to include endpoints that are not regional endpoints (e.g., s3-external-1, fips-us-gov-west-1, etc). :return: Returns a list of endpoint names (e.g., ["us-east-1"]). r^metadataendpointPrefix)rrrget_available_endpointsr )r7rpartition_nameallow_non_regionalr$resultsrendpoint_prefixr;r;r<get_available_regionss   zSession.get_available_regions)NNTNr>)rQ)NN)NF)NNF) NNTNNNNNN)r&F)=__name__ __module__ __qualname____doc__rrr4rr=r2rBr?rNr@rArCrDr$rErFrtrpropertyrrr!rVrrrrrrrrrrrrrrrrrrrrerrrrZrrrJrMrrrr#r%r.r;r;r;r<r:s  9     % " %     ( % "    rc@s0eZdZdZddZddZddZdd Zd S) r/z'Service locator for session components.cCsi|_i|_dSr>)r0 _deferredrGr;r;r<r=s zComponentLocator.__init__cCsP||jvr|j|}||j|<|j|=z|j|WSty'td|w)NzUnknown component: %s)r4r0KeyErrorr)r7rfactoryr;r;r<rZs      zComponentLocator.get_componentcC.||j|<z|j|=WdStyYdSwr>)r0r4r5rr;r;r<rJ  z#ComponentLocator.register_componentcCr7r>)r4r0r5)r7rno_arg_factoryr;r;r<rMr8z(ComponentLocator.lazy_register_componentN)r/r0r1r2r=rZrJrMr;r;r;r<r/s  r/c@sDeZdZddZddZddZddZd d Zd d Zd dZ dS)r3cCs||_t||_dSr>)_sessionr_store)r7rr8r;r;r<r=szSessionVarDict.__init__cCs |j|Sr>r;r7keyr;r;r< __getitem__ zSessionVarDict.__getitem__cCs||j|<|||dSr>)r;&_update_config_store_from_session_vars)r7r>rr;r;r< __setitem__s zSessionVarDict.__setitem__cCs |j|=dSr>r<r=r;r;r< __delitem__rzSessionVarDict.__delitem__cC t|jSr>)iterr;rGr;r;r<__iter__r@zSessionVarDict.__iter__cCrDr>)rdr;rGr;r;r<__len__r@zSessionVarDict.__len__c CsDt|jd}|\}}}}|jd}|||j|||||ddS)N)rrqrrconfig_property_namesrr)rr:rZset_config_providerr) r7rrconfig_chain_builderrrrrrqr;r;r<rAs  z5SessionVarDict._update_config_store_from_session_varsN) r/r0r1r=r?rBrCrFrGrAr;r;r;r<r3s r3c@s*eZdZdZdddZ   dddZdS) ra`A class for creating backwards compatible configuration chains. This class can be used instead of :class:`botocore.configprovider.ConfigChainFactory` to make it honor the methods argument to get_config_variable. This class can be used to filter out providers that are not in the methods tuple when creating a new config chain. NcCst|||_||_dSr>)r_factory_supported_methods)r7rrrr;r;r<r=s  z!SubsetChainConfigFactory.__init__cCs@d|jvrd}d|jvrd}d|jvrd}|jj|||||dS)aBuild a config chain following the standard botocore pattern. This config chain factory will omit any providers not in the methods tuple provided at initialization. For example if given the tuple ('instance', 'config',) it will not inject the environment provider into the standard config chain. This lets the botocore session support the custom ``methods`` argument for all the default botocore config variables when calling ``get_config_variable``. rNrrrH)rMrLr)r7rrrrrr;r;r<rs   z,SubsetChainConfigFactory.create_config_chainr>)NNNNN)r/r0r1r2r=rr;r;r;r<rs rcCst|S)z& Return a new session object. )r)rr;r;r< get_sessionsrNr>):r2rrrrryrrQrrbotocore.configloaderbotocore.credentialsbotocore.clientbotocore.configproviderrrrrbotocore.exceptionsrr r r botocore.errorfactoryr r botocore.hooksrrrbotocore.loadersrbotocore.parsersrbotocore.regionsrbotocore.modelrrrrrrbotocore.utilsrrbotocore.compatrrrr/robjectrr/r3rrNr;r;r;r<sV                  s"-(