File: configprovider.py

package info (click to toggle)
python-botocore 1.20.0%2Brepack-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 60,608 kB
  • sloc: python: 50,632; xml: 15,052; makefile: 131
file content (560 lines) | stat: -rw-r--r-- 22,235 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
"""This module contains the inteface for controlling how configuration
is loaded.
"""
import logging
import os

from botocore import utils


logger = logging.getLogger(__name__)


#: A default dictionary that maps the logical names for session variables
#: to the specific environment variables and configuration file names
#: that contain the values for these variables.
#: When creating a new Session object, you can pass in your own dictionary
#: to remap the logical names or to add new logical names.  You can then
#: get the current value for these variables by using the
#: ``get_config_variable`` method of the :class:`botocore.session.Session`
#: class.
#: These form the keys of the dictionary.  The values in the dictionary
#: are tuples of (<config_name>, <environment variable>, <default value>,
#: <conversion func>).
#: The conversion func is a function that takes the configuration value
#: as an argument and returns the converted value.  If this value is
#: None, then the configuration value is returned unmodified.  This
#: conversion function can be used to type convert config values to
#: values other than the default values of strings.
#: The ``profile`` and ``config_file`` variables should always have a
#: None value for the first entry in the tuple because it doesn't make
#: sense to look inside the config file for the location of the config
#: file or for the default profile to use.
#: The ``config_name`` is the name to look for in the configuration file,
#: the ``env var`` is the OS environment variable (``os.environ``) to
#: use, and ``default_value`` is the value to use if no value is otherwise
#: found.
BOTOCORE_DEFAUT_SESSION_VARIABLES = {
    # logical:  config_file, env_var,        default_value, conversion_func
    'profile': (None, ['AWS_DEFAULT_PROFILE', 'AWS_PROFILE'], None, None),
    'region': ('region', 'AWS_DEFAULT_REGION', None, None),
    'data_path': ('data_path', 'AWS_DATA_PATH', None, None),
    'config_file': (None, 'AWS_CONFIG_FILE', '~/.aws/config', None),
    'ca_bundle': ('ca_bundle', 'AWS_CA_BUNDLE', None, None),
    'api_versions': ('api_versions', None, {}, None),

    # This is the shared credentials file amongst sdks.
    'credentials_file': (None, 'AWS_SHARED_CREDENTIALS_FILE',
                         '~/.aws/credentials', None),

    # These variables only exist in the config file.

    # This is the number of seconds until we time out a request to
    # the instance metadata service.
    'metadata_service_timeout': (
        'metadata_service_timeout',
        'AWS_METADATA_SERVICE_TIMEOUT', 1, int),
    # This is the number of request attempts we make until we give
    # up trying to retrieve data from the instance metadata service.
    'metadata_service_num_attempts': (
        'metadata_service_num_attempts',
        'AWS_METADATA_SERVICE_NUM_ATTEMPTS', 1, int),
    'ec2_metadata_service_endpoint': (
        'ec2_metadata_service_endpoint',
        'AWS_EC2_METADATA_SERVICE_ENDPOINT',
        None, None),
    'imds_use_ipv6': (
        'imds_use_ipv6',
        'AWS_IMDS_USE_IPV6',
        False, None),
    'parameter_validation': ('parameter_validation', None, True, None),
    # Client side monitoring configurations.
    # Note: These configurations are considered internal to botocore.
    # Do not use them until publicly documented.
    'csm_enabled': (
            'csm_enabled', 'AWS_CSM_ENABLED', False, utils.ensure_boolean),
    'csm_host': ('csm_host', 'AWS_CSM_HOST', '127.0.0.1', None),
    'csm_port': ('csm_port', 'AWS_CSM_PORT', 31000, int),
    'csm_client_id': ('csm_client_id', 'AWS_CSM_CLIENT_ID', '', None),
    # Endpoint discovery configuration
    'endpoint_discovery_enabled': (
        'endpoint_discovery_enabled', 'AWS_ENDPOINT_DISCOVERY_ENABLED',
        'auto', None),
    'sts_regional_endpoints': (
        'sts_regional_endpoints', 'AWS_STS_REGIONAL_ENDPOINTS', 'legacy',
        None
    ),
    'retry_mode': ('retry_mode', 'AWS_RETRY_MODE', 'legacy', None),
    # We can't have a default here for v1 because we need to defer to
    # whatever the defaults are in _retry.json.
    'max_attempts': ('max_attempts', 'AWS_MAX_ATTEMPTS', None, int),
}
# A mapping for the s3 specific configuration vars. These are the configuration
# vars that typically go in the s3 section of the config file. This mapping
# follows the same schema as the previous session variable mapping.
DEFAULT_S3_CONFIG_VARS = {
    'addressing_style': (
        ('s3', 'addressing_style'), None, None, None),
    'use_accelerate_endpoint': (
        ('s3', 'use_accelerate_endpoint'), None, None, utils.ensure_boolean
    ),
    'use_dualstack_endpoint': (
        ('s3', 'use_dualstack_endpoint'), None, None, utils.ensure_boolean
    ),
    'payload_signing_enabled': (
        ('s3', 'payload_signing_enabled'), None, None, utils.ensure_boolean
    ),
    'use_arn_region': (
        ['s3_use_arn_region',
         ('s3', 'use_arn_region')],
        'AWS_S3_USE_ARN_REGION', None, utils.ensure_boolean
    ),
    'us_east_1_regional_endpoint': (
        ['s3_us_east_1_regional_endpoint',
         ('s3', 'us_east_1_regional_endpoint')],
        'AWS_S3_US_EAST_1_REGIONAL_ENDPOINT', None, None
    )
}
# A mapping for the proxy specific configuration vars. These are
# used to configure how botocore interacts with proxy setups while
# sending requests.
DEFAULT_PROXIES_CONFIG_VARS = {
    'proxy_ca_bundle': ('proxy_ca_bundle', None, None, None),
    'proxy_client_cert': ('proxy_client_cert', None, None, None),
    'proxy_use_forwarding_for_https': (
        'proxy_use_forwarding_for_https', None, None, utils.normalize_boolean),
}

def create_botocore_default_config_mapping(session):
    chain_builder = ConfigChainFactory(session=session)
    config_mapping = _create_config_chain_mapping(
        chain_builder, BOTOCORE_DEFAUT_SESSION_VARIABLES)
    config_mapping['s3'] = SectionConfigProvider(
        's3', session, _create_config_chain_mapping(
            chain_builder, DEFAULT_S3_CONFIG_VARS)
    )
    config_mapping['proxies_config'] = SectionConfigProvider(
        'proxies_config', session, _create_config_chain_mapping(
            chain_builder, DEFAULT_PROXIES_CONFIG_VARS)
    )
    return config_mapping


def _create_config_chain_mapping(chain_builder, config_variables):
    mapping = {}
    for logical_name, config in config_variables.items():
        mapping[logical_name] = chain_builder.create_config_chain(
            instance_name=logical_name,
            env_var_names=config[1],
            config_property_names=config[0],
            default=config[2],
            conversion_func=config[3]
        )
    return mapping


class ConfigChainFactory(object):
    """Factory class to create our most common configuration chain case.

    This is a convenience class to construct configuration chains that follow
    our most common pattern. This is to prevent ordering them incorrectly,
    and to make the config chain construction more readable.
    """
    def __init__(self, session, environ=None):
        """Initialize a ConfigChainFactory.

        :type session: :class:`botocore.session.Session`
        :param session: This is the session that should be used to look up
            values from the config file.

        :type environ: dict
        :param environ: A mapping to use for environment variables. If this
            is not provided it will default to use os.environ.
        """
        self._session = session
        if environ is None:
            environ = os.environ
        self._environ = environ

    def create_config_chain(self, instance_name=None, env_var_names=None,
                            config_property_names=None, default=None,
                            conversion_func=None):
        """Build a config chain following the standard botocore pattern.

        In botocore most of our config chains follow the the precendence:
        session_instance_variables, environment, config_file, default_value.

        This is a convenience function for creating a chain that follow
        that precendence.

        :type instance_name: str
        :param instance_name: This indicates what session instance variable
            corresponds to this config value. If it is None it will not be
            added to the chain.

        :type env_var_names: str or list of str or None
        :param env_var_names: One or more environment variable names to
            search for this value. They are searched in order. If it is None
            it will not be added to the chain.

        :type config_property_names: str/tuple or list of str/tuple or None
        :param config_property_names: One of more strings or tuples
            representing the name of the key in the config file for this
            config option. They are searched in order. If it is None it will
            not be added to the chain.

        :type default: Any
        :param default: Any constant value to be returned.

        :type conversion_func: None or callable
        :param conversion_func: If this value is None then it has no effect on
            the return type. Otherwise, it is treated as a function that will
            conversion_func our provided type.

        :rvalue: ConfigChain
        :returns: A ConfigChain that resolves in the order env_var_names ->
            config_property_name -> default. Any values that were none are
            omitted form the chain.
        """
        providers = []
        if instance_name is not None:
            providers.append(
                InstanceVarProvider(
                    instance_var=instance_name,
                    session=self._session
                )
            )
        if env_var_names is not None:
            providers.extend(self._get_env_providers(env_var_names))
        if config_property_names is not None:
            providers.extend(
                self._get_scoped_config_providers(config_property_names)
            )
        if default is not None:
            providers.append(ConstantProvider(value=default))

        return ChainProvider(
            providers=providers,
            conversion_func=conversion_func,
        )

    def _get_env_providers(self, env_var_names):
        env_var_providers = []
        if not isinstance(env_var_names, list):
            env_var_names = [env_var_names]
        for env_var_name in env_var_names:
            env_var_providers.append(
                EnvironmentProvider(name=env_var_name, env=self._environ)
            )
        return env_var_providers

    def _get_scoped_config_providers(self, config_property_names):
        scoped_config_providers = []
        if not isinstance(config_property_names, list):
            config_property_names = [config_property_names]
        for config_property_name in config_property_names:
            scoped_config_providers.append(
                ScopedConfigProvider(
                    config_var_name=config_property_name,
                    session=self._session,
                )
            )
        return scoped_config_providers


class ConfigValueStore(object):
    """The ConfigValueStore object stores configuration values."""
    def __init__(self, mapping=None):
        """Initialize a ConfigValueStore.

        :type mapping: dict
        :param mapping: The mapping parameter is a map of string to a subclass
            of BaseProvider. When a config variable is asked for via the
            get_config_variable method, the corresponding provider will be
            invoked to load the value.
        """
        self._overrides = {}
        self._mapping = {}
        if mapping is not None:
            for logical_name, provider in mapping.items():
                self.set_config_provider(logical_name, provider)

    def get_config_variable(self, logical_name):
        """
        Retrieve the value associeated with the specified logical_name
        from the corresponding provider. If no value is found None will
        be returned.

        :type logical_name: str
        :param logical_name: The logical name of the session variable
            you want to retrieve.  This name will be mapped to the
            appropriate environment variable name for this session as
            well as the appropriate config file entry.

        :returns: value of variable or None if not defined.
        """
        if logical_name in self._overrides:
            return self._overrides[logical_name]
        if logical_name not in self._mapping:
            return None
        provider = self._mapping[logical_name]
        return provider.provide()

    def set_config_variable(self, logical_name, value):
        """Set 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.
        """
        self._overrides[logical_name] = value

    def clear_config_variable(self, logical_name):
        """Remove an override config variable from the session.

        :type logical_name: str
        :param logical_name: The name of the parameter to clear the override
            value from.
        """
        self._overrides.pop(logical_name, None)

    def set_config_provider(self, logical_name, provider):
        """Set the provider for a config value.

        This provides control over how a particular configuration value is
        loaded. This replaces the provider for ``logical_name`` with the new
        ``provider``.

        :type logical_name: str
        :param logical_name: The name of the config value to change the config
            provider for.

        :type provider: :class:`botocore.configprovider.BaseProvider`
        :param provider: The new provider that should be responsible for
            providing a value for the config named ``logical_name``.
        """
        self._mapping[logical_name] = provider


class BaseProvider(object):
    """Base class for configuration value providers.

    A configuration provider has some method of providing a configuration
    value.
    """
    def provide(self):
        """Provide a config value."""
        raise NotImplementedError('provide')


class ChainProvider(BaseProvider):
    """This provider wraps one or more other providers.

    Each provider in the chain is called, the first one returning a non-None
    value is then returned.
    """
    def __init__(self, providers=None, conversion_func=None):
        """Initalize a ChainProvider.

        :type providers: list
        :param providers: The initial list of providers to check for values
            when invoked.

        :type conversion_func: None or callable
        :param conversion_func: If this value is None then it has no affect on
            the return type. Otherwise, it is treated as a function that will
            transform provided value.
        """
        if providers is None:
            providers = []
        self._providers = providers
        self._conversion_func = conversion_func

    def provide(self):
        """Provide the value from the first provider to return non-None.

        Each provider in the chain has its provide method called. The first
        one in the chain to return a non-None value is the returned from the
        ChainProvider. When no non-None value is found, None is returned.
        """
        for provider in self._providers:
            value = provider.provide()
            if value is not None:
                return self._convert_type(value)
        return None

    def _convert_type(self, value):
        if self._conversion_func is not None:
            return self._conversion_func(value)
        return value

    def __repr__(self):
        return '[%s]' % ', '.join([str(p) for p in self._providers])


class InstanceVarProvider(BaseProvider):
    """This class loads config values from the session instance vars."""
    def __init__(self, instance_var, session):
        """Initialize InstanceVarProvider.

        :type instance_var: str
        :param instance_var: The instance variable to load from the session.

        :type session: :class:`botocore.session.Session`
        :param session: The botocore session to get the loaded configuration
            file variables from.
        """
        self._instance_var = instance_var
        self._session = session

    def provide(self):
        """Provide a config value from the session instance vars."""
        instance_vars = self._session.instance_variables()
        value = instance_vars.get(self._instance_var)
        return value

    def __repr__(self):
        return 'InstanceVarProvider(instance_var=%s, session=%s)' % (
            self._instance_var,
            self._session,
        )


class ScopedConfigProvider(BaseProvider):
    def __init__(self, config_var_name, session):
        """Initialize ScopedConfigProvider.

        :type config_var_name: str or tuple
        :param config_var_name: The name of the config variable to load from
            the configuration file. If the value is a tuple, it must only
            consist of two items, where the first item represents the section
            and the second item represents the config var name in the section.

        :type session: :class:`botocore.session.Session`
        :param session: The botocore session to get the loaded configuration
            file variables from.
        """
        self._config_var_name = config_var_name
        self._session = session

    def provide(self):
        """Provide a value from a config file property."""
        scoped_config = self._session.get_scoped_config()
        if isinstance(self._config_var_name, tuple):
            section_config = scoped_config.get(self._config_var_name[0])
            if not isinstance(section_config, dict):
                return None
            return section_config.get(self._config_var_name[1])
        return scoped_config.get(self._config_var_name)

    def __repr__(self):
        return 'ScopedConfigProvider(config_var_name=%s, session=%s)' % (
            self._config_var_name,
            self._session,
        )


class EnvironmentProvider(BaseProvider):
    """This class loads config values from environment variables."""
    def __init__(self, name, env):
        """Initialize with the keys in the dictionary to check.

        :type name: str
        :param name: The key with that name will be loaded and returned.

        :type env: dict
        :param env: Environment variables dictionary to get variables from.
        """
        self._name = name
        self._env = env

    def provide(self):
        """Provide a config value from a source dictionary."""
        if self._name in self._env:
            return self._env[self._name]
        return None

    def __repr__(self):
        return 'EnvironmentProvider(name=%s, env=%s)' % (self._name, self._env)


class SectionConfigProvider(BaseProvider):
    """Provides a dictionary from a section in the scoped config

    This is useful for retrieving scoped config variables (i.e. s3) that have
    their own set of config variables and resolving logic.
    """
    def __init__(self, section_name, session, override_providers=None):
        self._section_name = section_name
        self._session = session
        self._scoped_config_provider = ScopedConfigProvider(
            self._section_name, self._session)
        self._override_providers = override_providers
        if self._override_providers is None:
            self._override_providers = {}

    def provide(self):
        section_config = self._scoped_config_provider.provide()
        if section_config and not isinstance(section_config, dict):
            logger.debug("The %s config key is not a dictionary type, "
                         "ignoring its value of: %s", self._section_name,
                         section_config)
            return None
        for section_config_var, provider in self._override_providers.items():
            provider_val = provider.provide()
            if provider_val is not None:
                if section_config is None:
                    section_config = {}
                section_config[section_config_var] = provider_val
        return section_config

    def __repr__(self):
        return (
            'SectionConfigProvider(section_name=%s, '
            'session=%s, override_providers=%s)' % (
                self._section_name, self._session,
                self._override_providers,
            )
        )


class ConstantProvider(BaseProvider):
    """This provider provides a constant value."""
    def __init__(self, value):
        self._value = value

    def provide(self):
        """Provide the constant value given during initialization."""
        return self._value

    def __repr__(self):
        return 'ConstantProvider(value=%s)' % self._value