File: core.py

package info (click to toggle)
python-oslo.cache 3.10.1-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 776 kB
  • sloc: python: 3,055; sh: 31; makefile: 24
file content (620 lines) | stat: -rw-r--r-- 26,086 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
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
# Copyright 2013 Metacloud
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.

"""Caching Layer Implementation.

To use this library:

You must call :func:`configure`.

Inside your application code, decorate the methods that you want the results
to be cached with a memoization decorator created with
:func:`get_memoization_decorator`. This function takes a group name from the
config. Register [`group`] ``caching`` and [`group`] ``cache_time`` options
for the groups that your decorators use so that caching can be configured.

This library's configuration options must be registered in your application's
:class:`oslo_config.cfg.ConfigOpts` instance. Do this by passing the ConfigOpts
instance to :func:`configure`.

The library has special public value for nonexistent or expired keys called
:data:`NO_VALUE`. To use this value you should import it from oslo_cache.core::

    from oslo_cache import core
    NO_VALUE = core.NO_VALUE
"""
import socket
import ssl
import urllib.parse

import dogpile.cache
from dogpile.cache import api
from dogpile.cache import proxy
from dogpile.cache import util
from oslo_log import log
from oslo_utils import importutils
from oslo_utils import netutils

from oslo_cache._i18n import _
from oslo_cache import _opts
from oslo_cache import exception


__all__ = [
    'configure',
    'configure_cache_region',
    'create_region',
    'get_memoization_decorator',
    'NO_VALUE',
]

NO_VALUE = api.NO_VALUE
"""Value returned for nonexistent or expired keys."""

_LOG = log.getLogger(__name__)


class _DebugProxy(proxy.ProxyBackend):
    """Extra Logging ProxyBackend."""
    # NOTE(morganfainberg): Pass all key/values through repr to ensure we have
    # a clean description of the information.  Without use of repr, it might
    # be possible to run into encode/decode error(s). For logging/debugging
    # purposes encode/decode is irrelevant and we should be looking at the
    # data exactly as it stands.

    def get(self, key):
        value = self.proxied.get(key)
        _LOG.debug('CACHE_GET: Key: "%(key)r" Value: "%(value)r"',
                   {'key': key, 'value': value})
        return value

    def get_multi(self, keys):
        values = self.proxied.get_multi(keys)
        _LOG.debug('CACHE_GET_MULTI: "%(keys)r" Values: "%(values)r"',
                   {'keys': keys, 'values': values})
        return values

    def set(self, key, value):
        _LOG.debug('CACHE_SET: Key: "%(key)r" Value: "%(value)r"',
                   {'key': key, 'value': value})
        return self.proxied.set(key, value)

    def set_multi(self, keys):
        _LOG.debug('CACHE_SET_MULTI: "%r"', keys)
        self.proxied.set_multi(keys)

    def delete(self, key):
        self.proxied.delete(key)
        _LOG.debug('CACHE_DELETE: "%r"', key)

    def delete_multi(self, keys):
        _LOG.debug('CACHE_DELETE_MULTI: "%r"', keys)
        self.proxied.delete_multi(keys)


def _parse_sentinel(sentinel):
    host, port = netutils.parse_host_port(sentinel)
    if host is None or port is None:
        raise exception.ConfigurationError('Malformed sentinel server format')
    return (host, port)


def _build_cache_config(conf):
    """Build the cache region dictionary configuration.

    :returns: dict
    """
    prefix = conf.cache.config_prefix
    conf_dict = {}
    conf_dict[f'{prefix}.backend'] = _opts._DEFAULT_BACKEND
    if conf.cache.enabled is True:
        conf_dict[f'{prefix}.backend'] = conf.cache.backend
    conf_dict[f'{prefix}.expiration_time'] = conf.cache.expiration_time
    for argument in conf.cache.backend_argument:
        try:
            (argname, argvalue) = argument.split(':', 1)
        except ValueError:
            msg = ('Unable to build cache config-key. Expected format '
                   '"<argname>:<value>". Skipping unknown format: %s')
            _LOG.error(msg, argument)
            continue

        arg_key = '.'.join([prefix, 'arguments', argname])
        # NOTE(morgan): The handling of the URL data in memcache is bad and
        # only takes cases where the values are a list. This explicitly
        # checks for the base dogpile.cache.memcached backend and does the
        # split if needed. Other backends such as redis get the same
        # previous behavior. Overall the fact that the backends opaquely
        # take data and do not handle processing/validation as expected
        # directly makes for odd behaviors when wrapping dogpile.cache in
        # a library like oslo.cache
        if (conf.cache.backend
                in ('dogpile.cache.memcached', 'oslo_cache.memcache_pool') and
                argname == 'url'):
            argvalue = argvalue.split(',')
        conf_dict[arg_key] = argvalue

        _LOG.debug('Oslo Cache Config: %s', conf_dict)

    if conf.cache.backend == 'dogpile.cache.redis':
        if conf.cache.redis_password is None:
            netloc = conf.cache.redis_server
        else:
            if conf.cache.redis_username:
                netloc = '{}:{}@{}'.format(conf.cache.redis_username,
                                           conf.cache.redis_password,
                                           conf.cache.redis_server)
            else:
                netloc = ':{}@{}'.format(conf.cache.redis_password,
                                         conf.cache.redis_server)

        parts = urllib.parse.ParseResult(
            scheme=('rediss' if conf.cache.tls_enabled else 'redis'),
            netloc=netloc, path=str(conf.cache.redis_db), params='', query='',
            fragment='')

        conf_dict.setdefault(
            f'{prefix}.arguments.url',
            urllib.parse.urlunparse(parts)
        )
        for arg in ('socket_timeout',):
            value = getattr(conf.cache, 'redis_' + arg)
            conf_dict[f'{prefix}.arguments.{arg}'] = value
    elif conf.cache.backend == 'dogpile.cache.redis_sentinel':
        for arg in ('username', 'password', 'socket_timeout', 'db'):
            value = getattr(conf.cache, 'redis_' + arg)
            conf_dict[f'{prefix}.arguments.{arg}'] = value
        conf_dict[f'{prefix}.arguments.service_name'] = \
            conf.cache.redis_sentinel_service_name
        if conf.cache.redis_sentinels:
            conf_dict[f'{prefix}.arguments.sentinels'] = [
                _parse_sentinel(s) for s in conf.cache.redis_sentinels]
    else:
        # NOTE(yorik-sar): these arguments will be used for memcache-related
        # backends. Use setdefault for url to support old-style setting through
        # backend_argument=url:127.0.0.1:11211
        #
        # NOTE(morgan): If requested by config, 'flush_on_reconnect' will be
        # set for pooled connections. This can ensure that stale data is never
        # consumed from a server that pops in/out due to a network partition
        # or disconnect.
        #
        # See the help from python-memcached:
        #
        # param flush_on_reconnect: optional flag which prevents a
        #        scenario that can cause stale data to be read: If there's more
        #        than one memcached server and the connection to one is
        #        interrupted, keys that mapped to that server will get
        #        reassigned to another. If the first server comes back, those
        #        keys will map to it again. If it still has its data, get()s
        #        can read stale data that was overwritten on another
        #        server. This flag is off by default for backwards
        #        compatibility.
        #
        # The normal non-pooled clients connect explicitly on each use and
        # does not need the explicit flush_on_reconnect
        conf_dict.setdefault(f'{prefix}.arguments.url',
                             conf.cache.memcache_servers)

        for arg in ('dead_retry', 'socket_timeout', 'pool_maxsize',
                    'pool_unused_timeout', 'pool_connection_get_timeout',
                    'pool_flush_on_reconnect', 'sasl_enabled', 'username',
                    'password'):
            value = getattr(conf.cache, 'memcache_' + arg)
            conf_dict[f'{prefix}.arguments.{arg}'] = value

    if conf.cache.backend_expiration_time is not None:
        if conf.cache.expiration_time > conf.cache.backend_expiration_time:
            raise exception.ConfigurationError(
                "backend_expiration_time should not be smaller than "
                "expiration_time.")
        if conf.cache.backend in ('dogpile.cache.pymemcache',
                                  'dogpile.cache.memcached',
                                  'dogpile.cache.pylibmc',
                                  'oslo_cache.memcache_pool'):
            conf_dict[f'{prefix}.arguments.memcached_expire_time'] = \
                conf.cache.backend_expiration_time
        elif conf.cache.backend in ('dogpile.cache.redis',
                                    'dogpile.cache.redis_sentinel'):
            conf_dict[f'{prefix}.arguments.redis_expiration_time'] = \
                conf.cache.backend_expiration_time
        else:
            raise exception.ConfigurationError(
                "Enabling backend expiration is not supported by"
                "the %s driver", conf.cache.backend)

    if conf.cache.tls_enabled:
        if conf.cache.backend in ('dogpile.cache.bmemcache',
                                  'dogpile.cache.pymemcache',
                                  'oslo_cache.memcache_pool'):
            _LOG.debug('Oslo Cache TLS - CA: %s', conf.cache.tls_cafile)
            tls_context = ssl.create_default_context(
                cafile=conf.cache.tls_cafile)

            if conf.cache.enforce_fips_mode:
                if hasattr(ssl, 'FIPS_mode'):
                    _LOG.info("Enforcing the use of the OpenSSL FIPS mode")
                    ssl.FIPS_mode_set(1)
                else:
                    raise exception.ConfigurationError(
                        "OpenSSL FIPS mode is not supported by your Python "
                        "version. You must either change the Python "
                        "executable used to a version with FIPS mode support "
                        "or disable FIPS mode by setting "
                        "the '[cache] enforce_fips_mode' configuration option "
                        "to 'False'.")

            if conf.cache.tls_certfile is not None:
                _LOG.debug('Oslo Cache TLS - cert: %s',
                           conf.cache.tls_certfile)
                _LOG.debug('Oslo Cache TLS - key: %s', conf.cache.tls_keyfile)
                tls_context.load_cert_chain(
                    conf.cache.tls_certfile,
                    conf.cache.tls_keyfile,
                )

            if conf.cache.tls_allowed_ciphers is not None:
                _LOG.debug(
                    'Oslo Cache TLS - ciphers: %s',
                    conf.cache.tls_allowed_ciphers,
                )
                tls_context.set_ciphers(conf.cache.tls_allowed_ciphers)

            conf_dict[f'{prefix}.arguments.tls_context'] = tls_context
        elif conf.cache.backend in ('dogpile.cache.redis',
                                    'dogpile.cache.redis_sentinel'):
            if conf.cache.tls_allowed_ciphers is not None:
                raise exception.ConfigurationError(
                    "Limiting allowed ciphers is not supported by "
                    "the %s backend" % conf.cache.backend)
            if conf.cache.enforce_fips_mode:
                raise exception.ConfigurationError(
                    "FIPS mode is not supported by the %s backend" %
                    conf.cache.backend)

            conn_kwargs = {}
            if conf.cache.tls_cafile is not None:
                _LOG.debug('Oslo Cache TLS - CA: %s', conf.cache.tls_cafile)
                conn_kwargs['ssl_ca_certs'] = conf.cache.tls_cafile
            if conf.cache.tls_certfile is not None:
                _LOG.debug('Oslo Cache TLS - cert: %s',
                           conf.cache.tls_certfile)
                _LOG.debug('Oslo Cache TLS - key: %s', conf.cache.tls_keyfile)
                conn_kwargs.update({
                    'ssl_certfile': conf.cache.tls_certfile,
                    'ssl_keyfile': conf.cache.tls_keyfile
                })
            if conf.cache.backend == 'dogpile.cache.redis_sentinel':
                conn_kwargs.update({'ssl': True})
                conf_dict[f'{prefix}.arguments.connection_kwargs'] = \
                    conn_kwargs
                conf_dict[f'{prefix}.arguments.sentinel_kwargs'] = \
                    conn_kwargs
            else:
                conf_dict[f'{prefix}.arguments.connection_kwargs'] = \
                    conn_kwargs
        else:
            raise exception.ConfigurationError(
                "TLS setting via [cache] tls_enabled is not supported by the "
                "%s backend. Set [cache] tls_enabled=False or use a different "
                "backend." % conf.cache.backend
            )

    # NOTE(hberaud): Pymemcache backend and redis backends support socket
    # keepalive, If it is enable in our config then configure it to enable this
    # feature.
    # The socket keepalive feature means that client will be able to check
    # your connected socket and determine whether the connection is still up
    # and running or if it has broken.
    # This could be used by users who want to handle fine grained failures.
    if conf.cache.enable_socket_keepalive:
        if conf.cache.backend == 'dogpile.cache.pymemcache':
            import pymemcache
            socket_keepalive = pymemcache.KeepaliveOpts(
                idle=conf.cache.socket_keepalive_idle,
                intvl=conf.cache.socket_keepalive_interval,
                cnt=conf.cache.socket_keepalive_count)
            # As with the TLS context above, the config dict below will be
            # consumed by dogpile.cache that will be used as a proxy between
            # oslo.cache and pymemcache.
            conf_dict[f'{prefix}.arguments.socket_keepalive'] = \
                socket_keepalive
        elif conf.cache.backend in ('dogpile.cache.redis',
                                    'dogpile.cache.redis_sentinel'):
            socket_keepalive_options = {
                socket.TCP_KEEPIDLE: conf.cache.socket_keepalive_idle,
                socket.TCP_KEEPINTVL: conf.cache.socket_keepalive_interval,
                socket.TCP_KEEPCNT: conf.cache.socket_keepalive_count
            }
            conf_dict.setdefault(
                f'{prefix}.arguments.connection_kwargs', {}
            ).update({
                'socket_keepalive': True,
                'socket_keepalive_options': socket_keepalive_options
            })
        else:
            raise exception.ConfigurationError(
                "Socket keepalive is not supported by the %s backend"
                % conf.cache.backend
            )

    # NOTE(hberaud): The pymemcache library comes with retry mechanisms that
    # can be used to wrap all kind of pymemcache clients. The retry wrapper
    # allow you to define how many attempts to make and how long to wait
    # between attempts. The section below will pass our config
    # to dogpile.cache to setup the pymemcache retry client wrapper.
    if conf.cache.enable_retry_client:
        if conf.cache.backend != 'dogpile.cache.pymemcache':
            msg = _(
                "Retry client is only supported by the "
                "'dogpile.cache.pymemcache' backend."
            )
            raise exception.ConfigurationError(msg)
        import pymemcache
        conf_dict[f'{prefix}.arguments.enable_retry_client'] = True
        conf_dict[f'{prefix}.arguments.retry_attempts'] = \
            conf.cache.retry_attempts
        conf_dict[f'{prefix}.arguments.retry_delay'] = \
            conf.cache.retry_delay
        conf_dict[f'{prefix}.arguments.hashclient_retry_attempts'] = \
            conf.cache.hashclient_retry_attempts
        conf_dict[f'{prefix}.arguments.hashclient_retry_delay'] = \
            conf.cache.hashclient_retry_delay
        conf_dict[f'{prefix}.arguments.dead_timeout'] = \
            conf.cache.dead_timeout

    return conf_dict


def _sha1_mangle_key(key):
    """Wrapper for dogpile's sha1_mangle_key.

    dogpile's sha1_mangle_key function expects an encoded string, so we
    should take steps to properly handle multiple inputs before passing
    the key through.
    """
    try:
        key = key.encode('utf-8', errors='xmlcharrefreplace')
    except (UnicodeError, AttributeError):
        # NOTE(stevemar): if encoding fails just continue anyway.
        pass
    return util.sha1_mangle_key(key)


def _key_generate_to_str(s):
    # NOTE(morganfainberg): Since we need to stringify all arguments, attempt
    # to stringify and handle the Unicode error explicitly as needed.
    try:
        return str(s)
    except UnicodeEncodeError:
        return s.encode('utf-8')


def function_key_generator(namespace, fn, to_str=_key_generate_to_str):
    # NOTE(morganfainberg): This wraps dogpile.cache's default
    # function_key_generator to change the default to_str mechanism.
    return util.function_key_generator(namespace, fn, to_str=to_str)


def kwarg_function_key_generator(namespace, fn, to_str=_key_generate_to_str):
    # NOTE(ralonsoh): This wraps dogpile.cache's default
    # kwarg_function_key_generator to change the default to_str mechanism.
    return util.kwarg_function_key_generator(namespace, fn, to_str=to_str)


def create_region(function=function_key_generator):
    """Create a region.

    This is just dogpile.cache.make_region, but the key generator has a
    different to_str mechanism.

    .. note::

        You must call :func:`configure_cache_region` with this region before
        a memoized method is called.

    :param function: function used to generate a unique key depending on the
                     arguments of the decorated function
    :type function: function
    :returns: The new region.
    :rtype: :class:`dogpile.cache.region.CacheRegion`

    """

    return dogpile.cache.make_region(function_key_generator=function)


def configure_cache_region(conf, region):
    """Configure a cache region.

    If the cache region is already configured, this function does nothing.
    Otherwise, the region is configured.

    :param conf: config object, must have had :func:`configure` called on it.
    :type conf: oslo_config.cfg.ConfigOpts
    :param region: Cache region to configure (see :func:`create_region`).
    :type region: dogpile.cache.region.CacheRegion
    :raises oslo_cache.exception.ConfigurationError: If the region parameter is
        not a dogpile.cache.CacheRegion.
    :returns: The region.
    :rtype: :class:`dogpile.cache.region.CacheRegion`
    """
    if not isinstance(region, dogpile.cache.CacheRegion):
        raise exception.ConfigurationError(
            _('region not type dogpile.cache.CacheRegion'))

    if not region.is_configured:
        # NOTE(morganfainberg): this is how you tell if a region is configured.
        # There is a request logged with dogpile.cache upstream to make this
        # easier / less ugly.

        config_dict = _build_cache_config(conf)
        region.configure_from_config(config_dict,
                                     f'{conf.cache.config_prefix}.')

        if conf.cache.debug_cache_backend:
            region.wrap(_DebugProxy)

        # NOTE(morganfainberg): if the backend requests the use of a
        # key_mangler, we should respect that key_mangler function.  If a
        # key_mangler is not defined by the backend, use the sha1_mangle_key
        # mangler provided by dogpile.cache. This ensures we always use a fixed
        # size cache-key.
        if region.key_mangler is None:
            region.key_mangler = _sha1_mangle_key

        for class_path in conf.cache.proxies:
            # NOTE(morganfainberg): if we have any proxy wrappers, we should
            # ensure they are added to the cache region's backend.  Since
            # configure_from_config doesn't handle the wrap argument, we need
            # to manually add the Proxies. For information on how the
            # ProxyBackends work, see the dogpile.cache documents on
            # "changing-backend-behavior"
            cls = importutils.import_class(class_path)
            _LOG.debug("Adding cache-proxy '%s' to backend.", class_path)
            region.wrap(cls)

    return region


def _get_should_cache_fn(conf, group):
    """Build a function that returns a config group's caching status.

    For any given object that has caching capabilities, a boolean config option
    for that object's group should exist and default to ``True``. This
    function will use that value to tell the caching decorator if caching for
    that object is enabled. To properly use this with the decorator, pass this
    function the configuration group and assign the result to a variable.
    Pass the new variable to the caching decorator as the named argument
    ``should_cache_fn``.

    :param conf: config object, must have had :func:`configure` called on it.
    :type conf: oslo_config.cfg.ConfigOpts
    :param group: name of the configuration group to examine
    :type group: string
    :returns: function reference
    """
    def should_cache(value):
        if not conf.cache.enabled:
            return False
        conf_group = getattr(conf, group)
        return getattr(conf_group, 'caching', True)
    return should_cache


def _get_expiration_time_fn(conf, group):
    """Build a function that returns a config group's expiration time status.

    For any given object that has caching capabilities, an int config option
    called ``cache_time`` for that driver's group should exist and typically
    default to ``None``. This function will use that value to tell the caching
    decorator of the TTL override for caching the resulting objects. If the
    value of the config option is ``None`` the default value provided in the
    ``[cache] expiration_time`` option will be used by the decorator. The
    default may be set to something other than ``None`` in cases where the
    caching TTL should not be tied to the global default(s).

    To properly use this with the decorator, pass this function the
    configuration group and assign the result to a variable. Pass the new
    variable to the caching decorator as the named argument
    ``expiration_time``.

    :param group: name of the configuration group to examine
    :type group: string
    :rtype: function reference
    """
    def get_expiration_time():
        conf_group = getattr(conf, group)
        return getattr(conf_group, 'cache_time', None)
    return get_expiration_time


def get_memoization_decorator(conf, region, group, expiration_group=None):
    """Build a function based on the `cache_on_arguments` decorator.

    The memoization decorator that gets created by this function is a
    :meth:`dogpile.cache.region.CacheRegion.cache_on_arguments` decorator,
    where

    * The ``should_cache_fn`` is set to a function that returns True if both
      the ``[cache] enabled`` option is true and [`group`] ``caching`` is
      True.

    * The ``expiration_time`` is set from the
      [`expiration_group`] ``cache_time`` option if ``expiration_group``
      is passed in and the value is set, or [`group`] ``cache_time`` if
      ``expiration_group`` is not passed in and the value is set, or
      ``[cache] expiration_time`` otherwise.

    Example usage::

        import oslo_cache.core

        MEMOIZE = oslo_cache.core.get_memoization_decorator(
            conf, region, group='group1')

        @MEMOIZE
        def function(arg1, arg2):
            ...


        ALTERNATE_MEMOIZE = oslo_cache.core.get_memoization_decorator(
            conf, region, group='group2', expiration_group='group3')

        @ALTERNATE_MEMOIZE
        def function2(arg1, arg2):
            ...

    :param conf: config object, must have had :func:`configure` called on it.
    :type conf: oslo_config.cfg.ConfigOpts
    :param region: region as created by :func:`create_region`.
    :type region: dogpile.cache.region.CacheRegion
    :param group: name of the configuration group to examine
    :type group: string
    :param expiration_group: name of the configuration group to examine
                             for the expiration option. This will fall back to
                             using ``group`` if the value is unspecified or
                             ``None``
    :type expiration_group: string
    :rtype: function reference
    """
    if expiration_group is None:
        expiration_group = group
    should_cache = _get_should_cache_fn(conf, group)
    expiration_time = _get_expiration_time_fn(conf, expiration_group)

    memoize = region.cache_on_arguments(should_cache_fn=should_cache,
                                        expiration_time=expiration_time)

    # Make sure the actual "should_cache" and "expiration_time" methods are
    # available. This is potentially interesting/useful to pre-seed cache
    # values.
    memoize.should_cache = should_cache
    memoize.get_expiration_time = expiration_time

    return memoize


def configure(conf):
    """Configure the library.

    Register the required oslo.cache config options into an oslo.config CONF
    object.

    This must be called before :py:func:`configure_cache_region`.

    :param conf: The configuration object.
    :type conf: oslo_config.cfg.ConfigOpts
    """
    _opts.configure(conf)