configprovider.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  1. # Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License"). You
  4. # may not use this file except in compliance with the License. A copy of
  5. # the License is located at
  6. #
  7. # http://aws.amazon.com/apache2.0/
  8. #
  9. # or in the "license" file accompanying this file. This file is
  10. # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
  11. # ANY KIND, either express or implied. See the License for the specific
  12. # language governing permissions and limitations under the License.
  13. """This module contains the inteface for controlling how configuration
  14. is loaded.
  15. """
  16. import logging
  17. import os
  18. from botocore import utils
  19. logger = logging.getLogger(__name__)
  20. #: A default dictionary that maps the logical names for session variables
  21. #: to the specific environment variables and configuration file names
  22. #: that contain the values for these variables.
  23. #: When creating a new Session object, you can pass in your own dictionary
  24. #: to remap the logical names or to add new logical names. You can then
  25. #: get the current value for these variables by using the
  26. #: ``get_config_variable`` method of the :class:`botocore.session.Session`
  27. #: class.
  28. #: These form the keys of the dictionary. The values in the dictionary
  29. #: are tuples of (<config_name>, <environment variable>, <default value>,
  30. #: <conversion func>).
  31. #: The conversion func is a function that takes the configuration value
  32. #: as an argument and returns the converted value. If this value is
  33. #: None, then the configuration value is returned unmodified. This
  34. #: conversion function can be used to type convert config values to
  35. #: values other than the default values of strings.
  36. #: The ``profile`` and ``config_file`` variables should always have a
  37. #: None value for the first entry in the tuple because it doesn't make
  38. #: sense to look inside the config file for the location of the config
  39. #: file or for the default profile to use.
  40. #: The ``config_name`` is the name to look for in the configuration file,
  41. #: the ``env var`` is the OS environment variable (``os.environ``) to
  42. #: use, and ``default_value`` is the value to use if no value is otherwise
  43. #: found.
  44. BOTOCORE_DEFAUT_SESSION_VARIABLES = {
  45. # logical: config_file, env_var, default_value, conversion_func
  46. 'profile': (None, ['AWS_DEFAULT_PROFILE', 'AWS_PROFILE'], None, None),
  47. 'region': ('region', 'AWS_DEFAULT_REGION', None, None),
  48. 'data_path': ('data_path', 'AWS_DATA_PATH', None, None),
  49. 'config_file': (None, 'AWS_CONFIG_FILE', '~/.aws/config', None),
  50. 'ca_bundle': ('ca_bundle', 'AWS_CA_BUNDLE', None, None),
  51. 'api_versions': ('api_versions', None, {}, None),
  52. # This is the shared credentials file amongst sdks.
  53. 'credentials_file': (None, 'AWS_SHARED_CREDENTIALS_FILE',
  54. '~/.aws/credentials', None),
  55. # These variables only exist in the config file.
  56. # This is the number of seconds until we time out a request to
  57. # the instance metadata service.
  58. 'metadata_service_timeout': (
  59. 'metadata_service_timeout',
  60. 'AWS_METADATA_SERVICE_TIMEOUT', 1, int),
  61. # This is the number of request attempts we make until we give
  62. # up trying to retrieve data from the instance metadata service.
  63. 'metadata_service_num_attempts': (
  64. 'metadata_service_num_attempts',
  65. 'AWS_METADATA_SERVICE_NUM_ATTEMPTS', 1, int),
  66. 'ec2_metadata_service_endpoint': (
  67. 'ec2_metadata_service_endpoint',
  68. 'AWS_EC2_METADATA_SERVICE_ENDPOINT',
  69. None, None),
  70. 'imds_use_ipv6': (
  71. 'imds_use_ipv6',
  72. 'AWS_IMDS_USE_IPV6',
  73. False, None),
  74. 'parameter_validation': ('parameter_validation', None, True, None),
  75. # Client side monitoring configurations.
  76. # Note: These configurations are considered internal to botocore.
  77. # Do not use them until publicly documented.
  78. 'csm_enabled': (
  79. 'csm_enabled', 'AWS_CSM_ENABLED', False, utils.ensure_boolean),
  80. 'csm_host': ('csm_host', 'AWS_CSM_HOST', '127.0.0.1', None),
  81. 'csm_port': ('csm_port', 'AWS_CSM_PORT', 31000, int),
  82. 'csm_client_id': ('csm_client_id', 'AWS_CSM_CLIENT_ID', '', None),
  83. # Endpoint discovery configuration
  84. 'endpoint_discovery_enabled': (
  85. 'endpoint_discovery_enabled', 'AWS_ENDPOINT_DISCOVERY_ENABLED',
  86. 'auto', None),
  87. 'sts_regional_endpoints': (
  88. 'sts_regional_endpoints', 'AWS_STS_REGIONAL_ENDPOINTS', 'legacy',
  89. None
  90. ),
  91. 'retry_mode': ('retry_mode', 'AWS_RETRY_MODE', 'legacy', None),
  92. # We can't have a default here for v1 because we need to defer to
  93. # whatever the defaults are in _retry.json.
  94. 'max_attempts': ('max_attempts', 'AWS_MAX_ATTEMPTS', None, int),
  95. }
  96. # A mapping for the s3 specific configuration vars. These are the configuration
  97. # vars that typically go in the s3 section of the config file. This mapping
  98. # follows the same schema as the previous session variable mapping.
  99. DEFAULT_S3_CONFIG_VARS = {
  100. 'addressing_style': (
  101. ('s3', 'addressing_style'), None, None, None),
  102. 'use_accelerate_endpoint': (
  103. ('s3', 'use_accelerate_endpoint'), None, None, utils.ensure_boolean
  104. ),
  105. 'use_dualstack_endpoint': (
  106. ('s3', 'use_dualstack_endpoint'), None, None, utils.ensure_boolean
  107. ),
  108. 'payload_signing_enabled': (
  109. ('s3', 'payload_signing_enabled'), None, None, utils.ensure_boolean
  110. ),
  111. 'use_arn_region': (
  112. ['s3_use_arn_region',
  113. ('s3', 'use_arn_region')],
  114. 'AWS_S3_USE_ARN_REGION', None, utils.ensure_boolean
  115. ),
  116. 'us_east_1_regional_endpoint': (
  117. ['s3_us_east_1_regional_endpoint',
  118. ('s3', 'us_east_1_regional_endpoint')],
  119. 'AWS_S3_US_EAST_1_REGIONAL_ENDPOINT', None, None
  120. )
  121. }
  122. # A mapping for the proxy specific configuration vars. These are
  123. # used to configure how botocore interacts with proxy setups while
  124. # sending requests.
  125. DEFAULT_PROXIES_CONFIG_VARS = {
  126. 'proxy_ca_bundle': ('proxy_ca_bundle', None, None, None),
  127. 'proxy_client_cert': ('proxy_client_cert', None, None, None),
  128. 'proxy_use_forwarding_for_https': (
  129. 'proxy_use_forwarding_for_https', None, None, utils.normalize_boolean),
  130. }
  131. def create_botocore_default_config_mapping(session):
  132. chain_builder = ConfigChainFactory(session=session)
  133. config_mapping = _create_config_chain_mapping(
  134. chain_builder, BOTOCORE_DEFAUT_SESSION_VARIABLES)
  135. config_mapping['s3'] = SectionConfigProvider(
  136. 's3', session, _create_config_chain_mapping(
  137. chain_builder, DEFAULT_S3_CONFIG_VARS)
  138. )
  139. config_mapping['proxies_config'] = SectionConfigProvider(
  140. 'proxies_config', session, _create_config_chain_mapping(
  141. chain_builder, DEFAULT_PROXIES_CONFIG_VARS)
  142. )
  143. return config_mapping
  144. def _create_config_chain_mapping(chain_builder, config_variables):
  145. mapping = {}
  146. for logical_name, config in config_variables.items():
  147. mapping[logical_name] = chain_builder.create_config_chain(
  148. instance_name=logical_name,
  149. env_var_names=config[1],
  150. config_property_names=config[0],
  151. default=config[2],
  152. conversion_func=config[3]
  153. )
  154. return mapping
  155. class ConfigChainFactory(object):
  156. """Factory class to create our most common configuration chain case.
  157. This is a convenience class to construct configuration chains that follow
  158. our most common pattern. This is to prevent ordering them incorrectly,
  159. and to make the config chain construction more readable.
  160. """
  161. def __init__(self, session, environ=None):
  162. """Initialize a ConfigChainFactory.
  163. :type session: :class:`botocore.session.Session`
  164. :param session: This is the session that should be used to look up
  165. values from the config file.
  166. :type environ: dict
  167. :param environ: A mapping to use for environment variables. If this
  168. is not provided it will default to use os.environ.
  169. """
  170. self._session = session
  171. if environ is None:
  172. environ = os.environ
  173. self._environ = environ
  174. def create_config_chain(self, instance_name=None, env_var_names=None,
  175. config_property_names=None, default=None,
  176. conversion_func=None):
  177. """Build a config chain following the standard botocore pattern.
  178. In botocore most of our config chains follow the the precendence:
  179. session_instance_variables, environment, config_file, default_value.
  180. This is a convenience function for creating a chain that follow
  181. that precendence.
  182. :type instance_name: str
  183. :param instance_name: This indicates what session instance variable
  184. corresponds to this config value. If it is None it will not be
  185. added to the chain.
  186. :type env_var_names: str or list of str or None
  187. :param env_var_names: One or more environment variable names to
  188. search for this value. They are searched in order. If it is None
  189. it will not be added to the chain.
  190. :type config_property_names: str/tuple or list of str/tuple or None
  191. :param config_property_names: One of more strings or tuples
  192. representing the name of the key in the config file for this
  193. config option. They are searched in order. If it is None it will
  194. not be added to the chain.
  195. :type default: Any
  196. :param default: Any constant value to be returned.
  197. :type conversion_func: None or callable
  198. :param conversion_func: If this value is None then it has no effect on
  199. the return type. Otherwise, it is treated as a function that will
  200. conversion_func our provided type.
  201. :rvalue: ConfigChain
  202. :returns: A ConfigChain that resolves in the order env_var_names ->
  203. config_property_name -> default. Any values that were none are
  204. omitted form the chain.
  205. """
  206. providers = []
  207. if instance_name is not None:
  208. providers.append(
  209. InstanceVarProvider(
  210. instance_var=instance_name,
  211. session=self._session
  212. )
  213. )
  214. if env_var_names is not None:
  215. providers.extend(self._get_env_providers(env_var_names))
  216. if config_property_names is not None:
  217. providers.extend(
  218. self._get_scoped_config_providers(config_property_names)
  219. )
  220. if default is not None:
  221. providers.append(ConstantProvider(value=default))
  222. return ChainProvider(
  223. providers=providers,
  224. conversion_func=conversion_func,
  225. )
  226. def _get_env_providers(self, env_var_names):
  227. env_var_providers = []
  228. if not isinstance(env_var_names, list):
  229. env_var_names = [env_var_names]
  230. for env_var_name in env_var_names:
  231. env_var_providers.append(
  232. EnvironmentProvider(name=env_var_name, env=self._environ)
  233. )
  234. return env_var_providers
  235. def _get_scoped_config_providers(self, config_property_names):
  236. scoped_config_providers = []
  237. if not isinstance(config_property_names, list):
  238. config_property_names = [config_property_names]
  239. for config_property_name in config_property_names:
  240. scoped_config_providers.append(
  241. ScopedConfigProvider(
  242. config_var_name=config_property_name,
  243. session=self._session,
  244. )
  245. )
  246. return scoped_config_providers
  247. class ConfigValueStore(object):
  248. """The ConfigValueStore object stores configuration values."""
  249. def __init__(self, mapping=None):
  250. """Initialize a ConfigValueStore.
  251. :type mapping: dict
  252. :param mapping: The mapping parameter is a map of string to a subclass
  253. of BaseProvider. When a config variable is asked for via the
  254. get_config_variable method, the corresponding provider will be
  255. invoked to load the value.
  256. """
  257. self._overrides = {}
  258. self._mapping = {}
  259. if mapping is not None:
  260. for logical_name, provider in mapping.items():
  261. self.set_config_provider(logical_name, provider)
  262. def get_config_variable(self, logical_name):
  263. """
  264. Retrieve the value associeated with the specified logical_name
  265. from the corresponding provider. If no value is found None will
  266. be returned.
  267. :type logical_name: str
  268. :param logical_name: The logical name of the session variable
  269. you want to retrieve. This name will be mapped to the
  270. appropriate environment variable name for this session as
  271. well as the appropriate config file entry.
  272. :returns: value of variable or None if not defined.
  273. """
  274. if logical_name in self._overrides:
  275. return self._overrides[logical_name]
  276. if logical_name not in self._mapping:
  277. return None
  278. provider = self._mapping[logical_name]
  279. return provider.provide()
  280. def set_config_variable(self, logical_name, value):
  281. """Set a configuration variable to a specific value.
  282. By using this method, you can override the normal lookup
  283. process used in ``get_config_variable`` by explicitly setting
  284. a value. Subsequent calls to ``get_config_variable`` will
  285. use the ``value``. This gives you per-session specific
  286. configuration values.
  287. ::
  288. >>> # Assume logical name 'foo' maps to env var 'FOO'
  289. >>> os.environ['FOO'] = 'myvalue'
  290. >>> s.get_config_variable('foo')
  291. 'myvalue'
  292. >>> s.set_config_variable('foo', 'othervalue')
  293. >>> s.get_config_variable('foo')
  294. 'othervalue'
  295. :type logical_name: str
  296. :param logical_name: The logical name of the session variable
  297. you want to set. These are the keys in ``SESSION_VARIABLES``.
  298. :param value: The value to associate with the config variable.
  299. """
  300. self._overrides[logical_name] = value
  301. def clear_config_variable(self, logical_name):
  302. """Remove an override config variable from the session.
  303. :type logical_name: str
  304. :param logical_name: The name of the parameter to clear the override
  305. value from.
  306. """
  307. self._overrides.pop(logical_name, None)
  308. def set_config_provider(self, logical_name, provider):
  309. """Set the provider for a config value.
  310. This provides control over how a particular configuration value is
  311. loaded. This replaces the provider for ``logical_name`` with the new
  312. ``provider``.
  313. :type logical_name: str
  314. :param logical_name: The name of the config value to change the config
  315. provider for.
  316. :type provider: :class:`botocore.configprovider.BaseProvider`
  317. :param provider: The new provider that should be responsible for
  318. providing a value for the config named ``logical_name``.
  319. """
  320. self._mapping[logical_name] = provider
  321. class BaseProvider(object):
  322. """Base class for configuration value providers.
  323. A configuration provider has some method of providing a configuration
  324. value.
  325. """
  326. def provide(self):
  327. """Provide a config value."""
  328. raise NotImplementedError('provide')
  329. class ChainProvider(BaseProvider):
  330. """This provider wraps one or more other providers.
  331. Each provider in the chain is called, the first one returning a non-None
  332. value is then returned.
  333. """
  334. def __init__(self, providers=None, conversion_func=None):
  335. """Initalize a ChainProvider.
  336. :type providers: list
  337. :param providers: The initial list of providers to check for values
  338. when invoked.
  339. :type conversion_func: None or callable
  340. :param conversion_func: If this value is None then it has no affect on
  341. the return type. Otherwise, it is treated as a function that will
  342. transform provided value.
  343. """
  344. if providers is None:
  345. providers = []
  346. self._providers = providers
  347. self._conversion_func = conversion_func
  348. def provide(self):
  349. """Provide the value from the first provider to return non-None.
  350. Each provider in the chain has its provide method called. The first
  351. one in the chain to return a non-None value is the returned from the
  352. ChainProvider. When no non-None value is found, None is returned.
  353. """
  354. for provider in self._providers:
  355. value = provider.provide()
  356. if value is not None:
  357. return self._convert_type(value)
  358. return None
  359. def _convert_type(self, value):
  360. if self._conversion_func is not None:
  361. return self._conversion_func(value)
  362. return value
  363. def __repr__(self):
  364. return '[%s]' % ', '.join([str(p) for p in self._providers])
  365. class InstanceVarProvider(BaseProvider):
  366. """This class loads config values from the session instance vars."""
  367. def __init__(self, instance_var, session):
  368. """Initialize InstanceVarProvider.
  369. :type instance_var: str
  370. :param instance_var: The instance variable to load from the session.
  371. :type session: :class:`botocore.session.Session`
  372. :param session: The botocore session to get the loaded configuration
  373. file variables from.
  374. """
  375. self._instance_var = instance_var
  376. self._session = session
  377. def provide(self):
  378. """Provide a config value from the session instance vars."""
  379. instance_vars = self._session.instance_variables()
  380. value = instance_vars.get(self._instance_var)
  381. return value
  382. def __repr__(self):
  383. return 'InstanceVarProvider(instance_var=%s, session=%s)' % (
  384. self._instance_var,
  385. self._session,
  386. )
  387. class ScopedConfigProvider(BaseProvider):
  388. def __init__(self, config_var_name, session):
  389. """Initialize ScopedConfigProvider.
  390. :type config_var_name: str or tuple
  391. :param config_var_name: The name of the config variable to load from
  392. the configuration file. If the value is a tuple, it must only
  393. consist of two items, where the first item represents the section
  394. and the second item represents the config var name in the section.
  395. :type session: :class:`botocore.session.Session`
  396. :param session: The botocore session to get the loaded configuration
  397. file variables from.
  398. """
  399. self._config_var_name = config_var_name
  400. self._session = session
  401. def provide(self):
  402. """Provide a value from a config file property."""
  403. scoped_config = self._session.get_scoped_config()
  404. if isinstance(self._config_var_name, tuple):
  405. section_config = scoped_config.get(self._config_var_name[0])
  406. if not isinstance(section_config, dict):
  407. return None
  408. return section_config.get(self._config_var_name[1])
  409. return scoped_config.get(self._config_var_name)
  410. def __repr__(self):
  411. return 'ScopedConfigProvider(config_var_name=%s, session=%s)' % (
  412. self._config_var_name,
  413. self._session,
  414. )
  415. class EnvironmentProvider(BaseProvider):
  416. """This class loads config values from environment variables."""
  417. def __init__(self, name, env):
  418. """Initialize with the keys in the dictionary to check.
  419. :type name: str
  420. :param name: The key with that name will be loaded and returned.
  421. :type env: dict
  422. :param env: Environment variables dictionary to get variables from.
  423. """
  424. self._name = name
  425. self._env = env
  426. def provide(self):
  427. """Provide a config value from a source dictionary."""
  428. if self._name in self._env:
  429. return self._env[self._name]
  430. return None
  431. def __repr__(self):
  432. return 'EnvironmentProvider(name=%s, env=%s)' % (self._name, self._env)
  433. class SectionConfigProvider(BaseProvider):
  434. """Provides a dictionary from a section in the scoped config
  435. This is useful for retrieving scoped config variables (i.e. s3) that have
  436. their own set of config variables and resolving logic.
  437. """
  438. def __init__(self, section_name, session, override_providers=None):
  439. self._section_name = section_name
  440. self._session = session
  441. self._scoped_config_provider = ScopedConfigProvider(
  442. self._section_name, self._session)
  443. self._override_providers = override_providers
  444. if self._override_providers is None:
  445. self._override_providers = {}
  446. def provide(self):
  447. section_config = self._scoped_config_provider.provide()
  448. if section_config and not isinstance(section_config, dict):
  449. logger.debug("The %s config key is not a dictionary type, "
  450. "ignoring its value of: %s", self._section_name,
  451. section_config)
  452. return None
  453. for section_config_var, provider in self._override_providers.items():
  454. provider_val = provider.provide()
  455. if provider_val is not None:
  456. if section_config is None:
  457. section_config = {}
  458. section_config[section_config_var] = provider_val
  459. return section_config
  460. def __repr__(self):
  461. return (
  462. 'SectionConfigProvider(section_name=%s, '
  463. 'session=%s, override_providers=%s)' % (
  464. self._section_name, self._session,
  465. self._override_providers,
  466. )
  467. )
  468. class ConstantProvider(BaseProvider):
  469. """This provider provides a constant value."""
  470. def __init__(self, value):
  471. self._value = value
  472. def provide(self):
  473. """Provide the constant value given during initialization."""
  474. return self._value
  475. def __repr__(self):
  476. return 'ConstantProvider(value=%s)' % self._value