Clean the unused files of the obsolete oslo-incubator
blueprint refactoring-terracotta-as-per-requires-of-openstack-project Change-Id: I203fa1de80767257c1c680717e524b91d970b6d4
This commit is contained in:
parent
58d1009f5c
commit
908cbc3216
46
terracotta/i18n.py
Normal file
46
terracotta/i18n.py
Normal file
@ -0,0 +1,46 @@
|
|||||||
|
# Copyright 2014 Huawei Technologies Co., Ltd.
|
||||||
|
#
|
||||||
|
# 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.
|
||||||
|
|
||||||
|
"""oslo.i18n integration module.
|
||||||
|
|
||||||
|
See http://docs.openstack.org/developer/oslo.i18n/usage.html
|
||||||
|
|
||||||
|
"""
|
||||||
|
|
||||||
|
import oslo_i18n
|
||||||
|
|
||||||
|
DOMAIN = 'aodh'
|
||||||
|
|
||||||
|
_translators = oslo_i18n.TranslatorFactory(domain=DOMAIN)
|
||||||
|
|
||||||
|
# The primary translation function using the well-known name "_"
|
||||||
|
_ = _translators.primary
|
||||||
|
|
||||||
|
# Translators for log levels.
|
||||||
|
#
|
||||||
|
# The abbreviated names are meant to reflect the usual use of a short
|
||||||
|
# name like '_'. The "L" is for "log" and the other letter comes from
|
||||||
|
# the level.
|
||||||
|
_LI = _translators.log_info
|
||||||
|
_LW = _translators.log_warning
|
||||||
|
_LE = _translators.log_error
|
||||||
|
_LC = _translators.log_critical
|
||||||
|
|
||||||
|
|
||||||
|
def translate(value, user_locale):
|
||||||
|
return oslo_i18n.translate(value, user_locale)
|
||||||
|
|
||||||
|
|
||||||
|
def get_available_languages():
|
||||||
|
return oslo_i18n.get_available_languages(DOMAIN)
|
@ -1,16 +0,0 @@
|
|||||||
oslo-incubator
|
|
||||||
--------------
|
|
||||||
|
|
||||||
A number of modules from oslo-incubator are imported into this project.
|
|
||||||
You can clone the oslo-incubator repository using the following url:
|
|
||||||
|
|
||||||
git://git.openstack.org/openstack/oslo-incubator
|
|
||||||
|
|
||||||
These modules are "incubating" in oslo-incubator and are kept in sync
|
|
||||||
with the help of oslo-incubator's update.py script. See:
|
|
||||||
|
|
||||||
https://wiki.openstack.org/wiki/Oslo#Syncing_Code_from_Incubator
|
|
||||||
|
|
||||||
The copy of the code should never be directly modified here. Please
|
|
||||||
always update oslo-incubator first and then run the script to copy
|
|
||||||
the changes across.
|
|
@ -1,45 +0,0 @@
|
|||||||
# 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.
|
|
||||||
|
|
||||||
"""oslo.i18n integration module.
|
|
||||||
|
|
||||||
See http://docs.openstack.org/developer/oslo.i18n/usage.html
|
|
||||||
|
|
||||||
"""
|
|
||||||
|
|
||||||
try:
|
|
||||||
import oslo_i18n
|
|
||||||
|
|
||||||
# NOTE(dhellmann): This reference to o-s-l-o will be replaced by the
|
|
||||||
# application name when this module is synced into the separate
|
|
||||||
# repository. It is OK to have more than one translation function
|
|
||||||
# using the same domain, since there will still only be one message
|
|
||||||
# catalog.
|
|
||||||
_translators = oslo_i18n.TranslatorFactory(domain='terracotta')
|
|
||||||
|
|
||||||
# The primary translation function using the well-known name "_"
|
|
||||||
_ = _translators.primary
|
|
||||||
|
|
||||||
# Translators for log levels.
|
|
||||||
#
|
|
||||||
# The abbreviated names are meant to reflect the usual use of a short
|
|
||||||
# name like '_'. The "L" is for "log" and the other letter comes from
|
|
||||||
# the level.
|
|
||||||
_LI = _translators.log_info
|
|
||||||
_LW = _translators.log_warning
|
|
||||||
_LE = _translators.log_error
|
|
||||||
_LC = _translators.log_critical
|
|
||||||
except ImportError:
|
|
||||||
# NOTE(dims): Support for cases where a project wants to use
|
|
||||||
# code from oslo-incubator, but is not ready to be internationalized
|
|
||||||
# (like tempest)
|
|
||||||
_ = _LI = _LW = _LE = _LC = lambda x: x
|
|
@ -1,271 +0,0 @@
|
|||||||
# Copyright 2012 Red Hat, Inc.
|
|
||||||
#
|
|
||||||
# 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.
|
|
||||||
|
|
||||||
# W0603: Using the global statement
|
|
||||||
# W0621: Redefining name %s from outer scope
|
|
||||||
# pylint: disable=W0603,W0621
|
|
||||||
|
|
||||||
from __future__ import print_function
|
|
||||||
|
|
||||||
import getpass
|
|
||||||
import inspect
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
import textwrap
|
|
||||||
|
|
||||||
from oslo_utils import encodeutils
|
|
||||||
from oslo_utils import strutils
|
|
||||||
import prettytable
|
|
||||||
import six
|
|
||||||
from six import moves
|
|
||||||
|
|
||||||
from terracotta.openstack.common._i18n import _
|
|
||||||
|
|
||||||
|
|
||||||
class MissingArgs(Exception):
|
|
||||||
"""Supplied arguments are not sufficient for calling a function."""
|
|
||||||
def __init__(self, missing):
|
|
||||||
self.missing = missing
|
|
||||||
msg = _("Missing arguments: %s") % ", ".join(missing)
|
|
||||||
super(MissingArgs, self).__init__(msg)
|
|
||||||
|
|
||||||
|
|
||||||
def validate_args(fn, *args, **kwargs):
|
|
||||||
"""Check that the supplied args are sufficient for calling a function.
|
|
||||||
|
|
||||||
>>> validate_args(lambda a: None)
|
|
||||||
Traceback (most recent call last):
|
|
||||||
...
|
|
||||||
MissingArgs: Missing argument(s): a
|
|
||||||
>>> validate_args(lambda a, b, c, d: None, 0, c=1)
|
|
||||||
Traceback (most recent call last):
|
|
||||||
...
|
|
||||||
MissingArgs: Missing argument(s): b, d
|
|
||||||
|
|
||||||
:param fn: the function to check
|
|
||||||
:param arg: the positional arguments supplied
|
|
||||||
:param kwargs: the keyword arguments supplied
|
|
||||||
"""
|
|
||||||
argspec = inspect.getargspec(fn)
|
|
||||||
|
|
||||||
num_defaults = len(argspec.defaults or [])
|
|
||||||
required_args = argspec.args[:len(argspec.args) - num_defaults]
|
|
||||||
|
|
||||||
def isbound(method):
|
|
||||||
return getattr(method, '__self__', None) is not None
|
|
||||||
|
|
||||||
if isbound(fn):
|
|
||||||
required_args.pop(0)
|
|
||||||
|
|
||||||
missing = [arg for arg in required_args if arg not in kwargs]
|
|
||||||
missing = missing[len(args):]
|
|
||||||
if missing:
|
|
||||||
raise MissingArgs(missing)
|
|
||||||
|
|
||||||
|
|
||||||
def arg(*args, **kwargs):
|
|
||||||
"""Decorator for CLI args.
|
|
||||||
|
|
||||||
Example:
|
|
||||||
|
|
||||||
>>> @arg("name", help="Name of the new entity")
|
|
||||||
... def entity_create(args):
|
|
||||||
... pass
|
|
||||||
"""
|
|
||||||
def _decorator(func):
|
|
||||||
add_arg(func, *args, **kwargs)
|
|
||||||
return func
|
|
||||||
return _decorator
|
|
||||||
|
|
||||||
|
|
||||||
def env(*args, **kwargs):
|
|
||||||
"""Returns the first environment variable set.
|
|
||||||
|
|
||||||
If all are empty, defaults to '' or keyword arg `default`.
|
|
||||||
"""
|
|
||||||
for arg in args:
|
|
||||||
value = os.environ.get(arg)
|
|
||||||
if value:
|
|
||||||
return value
|
|
||||||
return kwargs.get('default', '')
|
|
||||||
|
|
||||||
|
|
||||||
def add_arg(func, *args, **kwargs):
|
|
||||||
"""Bind CLI arguments to a shell.py `do_foo` function."""
|
|
||||||
|
|
||||||
if not hasattr(func, 'arguments'):
|
|
||||||
func.arguments = []
|
|
||||||
|
|
||||||
# NOTE(sirp): avoid dups that can occur when the module is shared across
|
|
||||||
# tests.
|
|
||||||
if (args, kwargs) not in func.arguments:
|
|
||||||
# Because of the semantics of decorator composition if we just append
|
|
||||||
# to the options list positional options will appear to be backwards.
|
|
||||||
func.arguments.insert(0, (args, kwargs))
|
|
||||||
|
|
||||||
|
|
||||||
def unauthenticated(func):
|
|
||||||
"""Adds 'unauthenticated' attribute to decorated function.
|
|
||||||
|
|
||||||
Usage:
|
|
||||||
|
|
||||||
>>> @unauthenticated
|
|
||||||
... def mymethod(f):
|
|
||||||
... pass
|
|
||||||
"""
|
|
||||||
func.unauthenticated = True
|
|
||||||
return func
|
|
||||||
|
|
||||||
|
|
||||||
def isunauthenticated(func):
|
|
||||||
"""Checks if the function does not require authentication.
|
|
||||||
|
|
||||||
Mark such functions with the `@unauthenticated` decorator.
|
|
||||||
|
|
||||||
:returns: bool
|
|
||||||
"""
|
|
||||||
return getattr(func, 'unauthenticated', False)
|
|
||||||
|
|
||||||
|
|
||||||
def print_list(objs, fields, formatters=None, sortby_index=0,
|
|
||||||
mixed_case_fields=None, field_labels=None):
|
|
||||||
"""Print a list or objects as a table, one row per object.
|
|
||||||
|
|
||||||
:param objs: iterable of :class:`Resource`
|
|
||||||
:param fields: attributes that correspond to columns, in order
|
|
||||||
:param formatters: `dict` of callables for field formatting
|
|
||||||
:param sortby_index: index of the field for sorting table rows
|
|
||||||
:param mixed_case_fields: fields corresponding to object attributes that
|
|
||||||
have mixed case names (e.g., 'serverId')
|
|
||||||
:param field_labels: Labels to use in the heading of the table, default to
|
|
||||||
fields.
|
|
||||||
"""
|
|
||||||
formatters = formatters or {}
|
|
||||||
mixed_case_fields = mixed_case_fields or []
|
|
||||||
field_labels = field_labels or fields
|
|
||||||
if len(field_labels) != len(fields):
|
|
||||||
raise ValueError(_("Field labels list %(labels)s has different number "
|
|
||||||
"of elements than fields list %(fields)s"),
|
|
||||||
{'labels': field_labels, 'fields': fields})
|
|
||||||
|
|
||||||
if sortby_index is None:
|
|
||||||
kwargs = {}
|
|
||||||
else:
|
|
||||||
kwargs = {'sortby': field_labels[sortby_index]}
|
|
||||||
pt = prettytable.PrettyTable(field_labels)
|
|
||||||
pt.align = 'l'
|
|
||||||
|
|
||||||
for o in objs:
|
|
||||||
row = []
|
|
||||||
for field in fields:
|
|
||||||
if field in formatters:
|
|
||||||
row.append(formatters[field](o))
|
|
||||||
else:
|
|
||||||
if field in mixed_case_fields:
|
|
||||||
field_name = field.replace(' ', '_')
|
|
||||||
else:
|
|
||||||
field_name = field.lower().replace(' ', '_')
|
|
||||||
data = getattr(o, field_name, '')
|
|
||||||
row.append(data)
|
|
||||||
pt.add_row(row)
|
|
||||||
|
|
||||||
if six.PY3:
|
|
||||||
print(encodeutils.safe_encode(pt.get_string(**kwargs)).decode())
|
|
||||||
else:
|
|
||||||
print(encodeutils.safe_encode(pt.get_string(**kwargs)))
|
|
||||||
|
|
||||||
|
|
||||||
def print_dict(dct, dict_property="Property", wrap=0):
|
|
||||||
"""Print a `dict` as a table of two columns.
|
|
||||||
|
|
||||||
:param dct: `dict` to print
|
|
||||||
:param dict_property: name of the first column
|
|
||||||
:param wrap: wrapping for the second column
|
|
||||||
"""
|
|
||||||
pt = prettytable.PrettyTable([dict_property, 'Value'])
|
|
||||||
pt.align = 'l'
|
|
||||||
for k, v in six.iteritems(dct):
|
|
||||||
# convert dict to str to check length
|
|
||||||
if isinstance(v, dict):
|
|
||||||
v = six.text_type(v)
|
|
||||||
if wrap > 0:
|
|
||||||
v = textwrap.fill(six.text_type(v), wrap)
|
|
||||||
# if value has a newline, add in multiple rows
|
|
||||||
# e.g. fault with stacktrace
|
|
||||||
if v and isinstance(v, six.string_types) and r'\n' in v:
|
|
||||||
lines = v.strip().split(r'\n')
|
|
||||||
col1 = k
|
|
||||||
for line in lines:
|
|
||||||
pt.add_row([col1, line])
|
|
||||||
col1 = ''
|
|
||||||
else:
|
|
||||||
pt.add_row([k, v])
|
|
||||||
|
|
||||||
if six.PY3:
|
|
||||||
print(encodeutils.safe_encode(pt.get_string()).decode())
|
|
||||||
else:
|
|
||||||
print(encodeutils.safe_encode(pt.get_string()))
|
|
||||||
|
|
||||||
|
|
||||||
def get_password(max_password_prompts=3):
|
|
||||||
"""Read password from TTY."""
|
|
||||||
verify = strutils.bool_from_string(env("OS_VERIFY_PASSWORD"))
|
|
||||||
pw = None
|
|
||||||
if hasattr(sys.stdin, "isatty") and sys.stdin.isatty():
|
|
||||||
# Check for Ctrl-D
|
|
||||||
try:
|
|
||||||
for __ in moves.range(max_password_prompts):
|
|
||||||
pw1 = getpass.getpass("OS Password: ")
|
|
||||||
if verify:
|
|
||||||
pw2 = getpass.getpass("Please verify: ")
|
|
||||||
else:
|
|
||||||
pw2 = pw1
|
|
||||||
if pw1 == pw2 and pw1:
|
|
||||||
pw = pw1
|
|
||||||
break
|
|
||||||
except EOFError:
|
|
||||||
pass
|
|
||||||
return pw
|
|
||||||
|
|
||||||
|
|
||||||
def service_type(stype):
|
|
||||||
"""Adds 'service_type' attribute to decorated function.
|
|
||||||
|
|
||||||
Usage:
|
|
||||||
|
|
||||||
.. code-block:: python
|
|
||||||
|
|
||||||
@service_type('volume')
|
|
||||||
def mymethod(f):
|
|
||||||
...
|
|
||||||
"""
|
|
||||||
def inner(f):
|
|
||||||
f.service_type = stype
|
|
||||||
return f
|
|
||||||
return inner
|
|
||||||
|
|
||||||
|
|
||||||
def get_service_type(f):
|
|
||||||
"""Retrieves service type from function."""
|
|
||||||
return getattr(f, 'service_type', None)
|
|
||||||
|
|
||||||
|
|
||||||
def pretty_choice_list(l):
|
|
||||||
return ', '.join("'%s'" % i for i in l)
|
|
||||||
|
|
||||||
|
|
||||||
def exit(msg=''):
|
|
||||||
if msg:
|
|
||||||
print (msg, file=sys.stderr)
|
|
||||||
sys.exit(1)
|
|
@ -1,149 +0,0 @@
|
|||||||
# Copyright 2011 OpenStack Foundation.
|
|
||||||
# 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. 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.
|
|
||||||
|
|
||||||
import contextlib
|
|
||||||
import errno
|
|
||||||
import logging
|
|
||||||
import os
|
|
||||||
import stat
|
|
||||||
import tempfile
|
|
||||||
|
|
||||||
from oslo_utils import excutils
|
|
||||||
|
|
||||||
LOG = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
_FILE_CACHE = {}
|
|
||||||
DEFAULT_MODE = stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO
|
|
||||||
|
|
||||||
|
|
||||||
def ensure_tree(path, mode=DEFAULT_MODE):
|
|
||||||
"""Create a directory (and any ancestor directories required)
|
|
||||||
|
|
||||||
:param path: Directory to create
|
|
||||||
:param mode: Directory creation permissions
|
|
||||||
"""
|
|
||||||
try:
|
|
||||||
os.makedirs(path, mode)
|
|
||||||
except OSError as exc:
|
|
||||||
if exc.errno == errno.EEXIST:
|
|
||||||
if not os.path.isdir(path):
|
|
||||||
raise
|
|
||||||
else:
|
|
||||||
raise
|
|
||||||
|
|
||||||
|
|
||||||
def read_cached_file(filename, force_reload=False):
|
|
||||||
"""Read from a file if it has been modified.
|
|
||||||
|
|
||||||
:param force_reload: Whether to reload the file.
|
|
||||||
:returns: A tuple with a boolean specifying if the data is fresh
|
|
||||||
or not.
|
|
||||||
"""
|
|
||||||
global _FILE_CACHE
|
|
||||||
|
|
||||||
if force_reload:
|
|
||||||
delete_cached_file(filename)
|
|
||||||
|
|
||||||
reloaded = False
|
|
||||||
mtime = os.path.getmtime(filename)
|
|
||||||
cache_info = _FILE_CACHE.setdefault(filename, {})
|
|
||||||
|
|
||||||
if not cache_info or mtime > cache_info.get('mtime', 0):
|
|
||||||
LOG.debug("Reloading cached file %s" % filename)
|
|
||||||
with open(filename) as fap:
|
|
||||||
cache_info['data'] = fap.read()
|
|
||||||
cache_info['mtime'] = mtime
|
|
||||||
reloaded = True
|
|
||||||
return (reloaded, cache_info['data'])
|
|
||||||
|
|
||||||
|
|
||||||
def delete_cached_file(filename):
|
|
||||||
"""Delete cached file if present.
|
|
||||||
|
|
||||||
:param filename: filename to delete
|
|
||||||
"""
|
|
||||||
global _FILE_CACHE
|
|
||||||
|
|
||||||
if filename in _FILE_CACHE:
|
|
||||||
del _FILE_CACHE[filename]
|
|
||||||
|
|
||||||
|
|
||||||
def delete_if_exists(path, remove=os.unlink):
|
|
||||||
"""Delete a file, but ignore file not found error.
|
|
||||||
|
|
||||||
:param path: File to delete
|
|
||||||
:param remove: Optional function to remove passed path
|
|
||||||
"""
|
|
||||||
|
|
||||||
try:
|
|
||||||
remove(path)
|
|
||||||
except OSError as e:
|
|
||||||
if e.errno != errno.ENOENT:
|
|
||||||
raise
|
|
||||||
|
|
||||||
|
|
||||||
@contextlib.contextmanager
|
|
||||||
def remove_path_on_error(path, remove=delete_if_exists):
|
|
||||||
"""Protect code that wants to operate on PATH atomically.
|
|
||||||
Any exception will cause PATH to be removed.
|
|
||||||
|
|
||||||
:param path: File to work with
|
|
||||||
:param remove: Optional function to remove passed path
|
|
||||||
"""
|
|
||||||
|
|
||||||
try:
|
|
||||||
yield
|
|
||||||
except Exception:
|
|
||||||
with excutils.save_and_reraise_exception():
|
|
||||||
remove(path)
|
|
||||||
|
|
||||||
|
|
||||||
def file_open(*args, **kwargs):
|
|
||||||
"""Open file
|
|
||||||
|
|
||||||
see built-in open() documentation for more details
|
|
||||||
|
|
||||||
Note: The reason this is kept in a separate module is to easily
|
|
||||||
be able to provide a stub module that doesn't alter system
|
|
||||||
state at all (for unit tests)
|
|
||||||
"""
|
|
||||||
return open(*args, **kwargs)
|
|
||||||
|
|
||||||
|
|
||||||
def write_to_tempfile(content, path=None, suffix='', prefix='tmp'):
|
|
||||||
"""Create temporary file or use existing file.
|
|
||||||
|
|
||||||
This util is needed for creating temporary file with
|
|
||||||
specified content, suffix and prefix. If path is not None,
|
|
||||||
it will be used for writing content. If the path doesn't
|
|
||||||
exist it'll be created.
|
|
||||||
|
|
||||||
:param content: content for temporary file.
|
|
||||||
:param path: same as parameter 'dir' for mkstemp
|
|
||||||
:param suffix: same as parameter 'suffix' for mkstemp
|
|
||||||
:param prefix: same as parameter 'prefix' for mkstemp
|
|
||||||
|
|
||||||
For example: it can be used in database tests for creating
|
|
||||||
configuration files.
|
|
||||||
"""
|
|
||||||
if path:
|
|
||||||
ensure_tree(path)
|
|
||||||
|
|
||||||
(fd, path) = tempfile.mkstemp(suffix=suffix, dir=path, prefix=prefix)
|
|
||||||
try:
|
|
||||||
os.write(fd, content)
|
|
||||||
finally:
|
|
||||||
os.close(fd)
|
|
||||||
return path
|
|
@ -1,45 +0,0 @@
|
|||||||
# Copyright 2011 OpenStack Foundation.
|
|
||||||
# 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. 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.
|
|
||||||
|
|
||||||
"""Local storage of variables using weak references"""
|
|
||||||
|
|
||||||
import threading
|
|
||||||
import weakref
|
|
||||||
|
|
||||||
|
|
||||||
class WeakLocal(threading.local):
|
|
||||||
def __getattribute__(self, attr):
|
|
||||||
rval = super(WeakLocal, self).__getattribute__(attr)
|
|
||||||
if rval:
|
|
||||||
# NOTE(mikal): this bit is confusing. What is stored is a weak
|
|
||||||
# reference, not the value itself. We therefore need to lookup
|
|
||||||
# the weak reference and return the inner value here.
|
|
||||||
rval = rval()
|
|
||||||
return rval
|
|
||||||
|
|
||||||
def __setattr__(self, attr, value):
|
|
||||||
value = weakref.ref(value)
|
|
||||||
return super(WeakLocal, self).__setattr__(attr, value)
|
|
||||||
|
|
||||||
|
|
||||||
# NOTE(mikal): the name "store" should be deprecated in the future
|
|
||||||
store = WeakLocal()
|
|
||||||
|
|
||||||
# A "weak" store uses weak references and allows an object to fall out of scope
|
|
||||||
# when it falls out of scope in the code that uses the thread local storage. A
|
|
||||||
# "strong" store will hold a reference to the object so that it never falls out
|
|
||||||
# of scope.
|
|
||||||
weak_store = WeakLocal()
|
|
||||||
strong_store = threading.local()
|
|
@ -1,262 +0,0 @@
|
|||||||
# Copyright (c) 2013 OpenStack Foundation
|
|
||||||
# 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. 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.
|
|
||||||
|
|
||||||
"""
|
|
||||||
Helpers for comparing version strings.
|
|
||||||
"""
|
|
||||||
|
|
||||||
import copy
|
|
||||||
import functools
|
|
||||||
import inspect
|
|
||||||
import logging
|
|
||||||
|
|
||||||
from oslo_config import cfg
|
|
||||||
import pkg_resources
|
|
||||||
import six
|
|
||||||
|
|
||||||
from terracotta.openstack.common._i18n import _
|
|
||||||
|
|
||||||
|
|
||||||
LOG = logging.getLogger(__name__)
|
|
||||||
CONF = cfg.CONF
|
|
||||||
|
|
||||||
|
|
||||||
deprecated_opts = [
|
|
||||||
cfg.BoolOpt('fatal_deprecations',
|
|
||||||
default=False,
|
|
||||||
help='Enables or disables fatal status of deprecations.'),
|
|
||||||
]
|
|
||||||
|
|
||||||
|
|
||||||
def list_opts():
|
|
||||||
"""Entry point for oslo.config-generator.
|
|
||||||
"""
|
|
||||||
return [(None, copy.deepcopy(deprecated_opts))]
|
|
||||||
|
|
||||||
|
|
||||||
class deprecated(object):
|
|
||||||
"""A decorator to mark callables as deprecated.
|
|
||||||
|
|
||||||
This decorator logs a deprecation message when the callable it decorates is
|
|
||||||
used. The message will include the release where the callable was
|
|
||||||
deprecated, the release where it may be removed and possibly an optional
|
|
||||||
replacement.
|
|
||||||
|
|
||||||
Examples:
|
|
||||||
|
|
||||||
1. Specifying the required deprecated release
|
|
||||||
|
|
||||||
>>> @deprecated(as_of=deprecated.ICEHOUSE)
|
|
||||||
... def a(): pass
|
|
||||||
|
|
||||||
2. Specifying a replacement:
|
|
||||||
|
|
||||||
>>> @deprecated(as_of=deprecated.ICEHOUSE, in_favor_of='f()')
|
|
||||||
... def b(): pass
|
|
||||||
|
|
||||||
3. Specifying the release where the functionality may be removed:
|
|
||||||
|
|
||||||
>>> @deprecated(as_of=deprecated.ICEHOUSE, remove_in=+1)
|
|
||||||
... def c(): pass
|
|
||||||
|
|
||||||
4. Specifying the deprecated functionality will not be removed:
|
|
||||||
>>> @deprecated(as_of=deprecated.ICEHOUSE, remove_in=0)
|
|
||||||
... def d(): pass
|
|
||||||
|
|
||||||
5. Specifying a replacement, deprecated functionality will not be removed:
|
|
||||||
>>> @deprecated(as_of=deprecated.ICEHOUSE, in_favor_of='f()', remove_in=0)
|
|
||||||
... def e(): pass
|
|
||||||
|
|
||||||
"""
|
|
||||||
|
|
||||||
# NOTE(morganfainberg): Bexar is used for unit test purposes, it is
|
|
||||||
# expected we maintain a gap between Bexar and Folsom in this list.
|
|
||||||
BEXAR = 'B'
|
|
||||||
FOLSOM = 'F'
|
|
||||||
GRIZZLY = 'G'
|
|
||||||
HAVANA = 'H'
|
|
||||||
ICEHOUSE = 'I'
|
|
||||||
JUNO = 'J'
|
|
||||||
KILO = 'K'
|
|
||||||
LIBERTY = 'L'
|
|
||||||
|
|
||||||
_RELEASES = {
|
|
||||||
# NOTE(morganfainberg): Bexar is used for unit test purposes, it is
|
|
||||||
# expected we maintain a gap between Bexar and Folsom in this list.
|
|
||||||
'B': 'Bexar',
|
|
||||||
'F': 'Folsom',
|
|
||||||
'G': 'Grizzly',
|
|
||||||
'H': 'Havana',
|
|
||||||
'I': 'Icehouse',
|
|
||||||
'J': 'Juno',
|
|
||||||
'K': 'Kilo',
|
|
||||||
'L': 'Liberty',
|
|
||||||
}
|
|
||||||
|
|
||||||
_deprecated_msg_with_alternative = _(
|
|
||||||
'%(what)s is deprecated as of %(as_of)s in favor of '
|
|
||||||
'%(in_favor_of)s and may be removed in %(remove_in)s.')
|
|
||||||
|
|
||||||
_deprecated_msg_no_alternative = _(
|
|
||||||
'%(what)s is deprecated as of %(as_of)s and may be '
|
|
||||||
'removed in %(remove_in)s. It will not be superseded.')
|
|
||||||
|
|
||||||
_deprecated_msg_with_alternative_no_removal = _(
|
|
||||||
'%(what)s is deprecated as of %(as_of)s in favor of %(in_favor_of)s.')
|
|
||||||
|
|
||||||
_deprecated_msg_with_no_alternative_no_removal = _(
|
|
||||||
'%(what)s is deprecated as of %(as_of)s. It will not be superseded.')
|
|
||||||
|
|
||||||
def __init__(self, as_of, in_favor_of=None, remove_in=2, what=None):
|
|
||||||
"""Initialize decorator
|
|
||||||
|
|
||||||
:param as_of: the release deprecating the callable. Constants
|
|
||||||
are define in this class for convenience.
|
|
||||||
:param in_favor_of: the replacement for the callable (optional)
|
|
||||||
:param remove_in: an integer specifying how many releases to wait
|
|
||||||
before removing (default: 2)
|
|
||||||
:param what: name of the thing being deprecated (default: the
|
|
||||||
callable's name)
|
|
||||||
|
|
||||||
"""
|
|
||||||
self.as_of = as_of
|
|
||||||
self.in_favor_of = in_favor_of
|
|
||||||
self.remove_in = remove_in
|
|
||||||
self.what = what
|
|
||||||
|
|
||||||
def __call__(self, func_or_cls):
|
|
||||||
if not self.what:
|
|
||||||
self.what = func_or_cls.__name__ + '()'
|
|
||||||
msg, details = self._build_message()
|
|
||||||
|
|
||||||
if inspect.isfunction(func_or_cls):
|
|
||||||
|
|
||||||
@six.wraps(func_or_cls)
|
|
||||||
def wrapped(*args, **kwargs):
|
|
||||||
report_deprecated_feature(LOG, msg, details)
|
|
||||||
return func_or_cls(*args, **kwargs)
|
|
||||||
return wrapped
|
|
||||||
elif inspect.isclass(func_or_cls):
|
|
||||||
orig_init = func_or_cls.__init__
|
|
||||||
|
|
||||||
# TODO(tsufiev): change `functools` module to `six` as
|
|
||||||
# soon as six 1.7.4 (with fix for passing `assigned`
|
|
||||||
# argument to underlying `functools.wraps`) is released
|
|
||||||
# and added to the oslo-incubator requrements
|
|
||||||
@functools.wraps(orig_init, assigned=('__name__', '__doc__'))
|
|
||||||
def new_init(self, *args, **kwargs):
|
|
||||||
report_deprecated_feature(LOG, msg, details)
|
|
||||||
orig_init(self, *args, **kwargs)
|
|
||||||
func_or_cls.__init__ = new_init
|
|
||||||
return func_or_cls
|
|
||||||
else:
|
|
||||||
raise TypeError('deprecated can be used only with functions or '
|
|
||||||
'classes')
|
|
||||||
|
|
||||||
def _get_safe_to_remove_release(self, release):
|
|
||||||
# TODO(dstanek): this method will have to be reimplemented once
|
|
||||||
# when we get to the X release because once we get to the Y
|
|
||||||
# release, what is Y+2?
|
|
||||||
new_release = chr(ord(release) + self.remove_in)
|
|
||||||
if new_release in self._RELEASES:
|
|
||||||
return self._RELEASES[new_release]
|
|
||||||
else:
|
|
||||||
return new_release
|
|
||||||
|
|
||||||
def _build_message(self):
|
|
||||||
details = dict(what=self.what,
|
|
||||||
as_of=self._RELEASES[self.as_of],
|
|
||||||
remove_in=self._get_safe_to_remove_release(self.as_of))
|
|
||||||
|
|
||||||
if self.in_favor_of:
|
|
||||||
details['in_favor_of'] = self.in_favor_of
|
|
||||||
if self.remove_in > 0:
|
|
||||||
msg = self._deprecated_msg_with_alternative
|
|
||||||
else:
|
|
||||||
# There are no plans to remove this function, but it is
|
|
||||||
# now deprecated.
|
|
||||||
msg = self._deprecated_msg_with_alternative_no_removal
|
|
||||||
else:
|
|
||||||
if self.remove_in > 0:
|
|
||||||
msg = self._deprecated_msg_no_alternative
|
|
||||||
else:
|
|
||||||
# There are no plans to remove this function, but it is
|
|
||||||
# now deprecated.
|
|
||||||
msg = self._deprecated_msg_with_no_alternative_no_removal
|
|
||||||
return msg, details
|
|
||||||
|
|
||||||
|
|
||||||
def is_compatible(requested_version, current_version, same_major=True):
|
|
||||||
"""Determine whether `requested_version` is satisfied by
|
|
||||||
`current_version`; in other words, `current_version` is >=
|
|
||||||
`requested_version`.
|
|
||||||
|
|
||||||
:param requested_version: version to check for compatibility
|
|
||||||
:param current_version: version to check against
|
|
||||||
:param same_major: if True, the major version must be identical between
|
|
||||||
`requested_version` and `current_version`. This is used when a
|
|
||||||
major-version difference indicates incompatibility between the two
|
|
||||||
versions. Since this is the common-case in practice, the default is
|
|
||||||
True.
|
|
||||||
:returns: True if compatible, False if not
|
|
||||||
"""
|
|
||||||
requested_parts = pkg_resources.parse_version(requested_version)
|
|
||||||
current_parts = pkg_resources.parse_version(current_version)
|
|
||||||
|
|
||||||
if same_major and (requested_parts[0] != current_parts[0]):
|
|
||||||
return False
|
|
||||||
|
|
||||||
return current_parts >= requested_parts
|
|
||||||
|
|
||||||
|
|
||||||
# Track the messages we have sent already. See
|
|
||||||
# report_deprecated_feature().
|
|
||||||
_deprecated_messages_sent = {}
|
|
||||||
|
|
||||||
|
|
||||||
def report_deprecated_feature(logger, msg, *args, **kwargs):
|
|
||||||
"""Call this function when a deprecated feature is used.
|
|
||||||
|
|
||||||
If the system is configured for fatal deprecations then the message
|
|
||||||
is logged at the 'critical' level and :class:`DeprecatedConfig` will
|
|
||||||
be raised.
|
|
||||||
|
|
||||||
Otherwise, the message will be logged (once) at the 'warn' level.
|
|
||||||
|
|
||||||
:raises: :class:`DeprecatedConfig` if the system is configured for
|
|
||||||
fatal deprecations.
|
|
||||||
"""
|
|
||||||
stdmsg = _("Deprecated: %s") % msg
|
|
||||||
CONF.register_opts(deprecated_opts)
|
|
||||||
if CONF.fatal_deprecations:
|
|
||||||
logger.critical(stdmsg, *args, **kwargs)
|
|
||||||
raise DeprecatedConfig(msg=stdmsg)
|
|
||||||
|
|
||||||
# Using a list because a tuple with dict can't be stored in a set.
|
|
||||||
sent_args = _deprecated_messages_sent.setdefault(msg, list())
|
|
||||||
|
|
||||||
if args in sent_args:
|
|
||||||
# Already logged this message, so don't log it again.
|
|
||||||
return
|
|
||||||
|
|
||||||
sent_args.append(args)
|
|
||||||
logger.warn(stdmsg, *args, **kwargs)
|
|
||||||
|
|
||||||
|
|
||||||
class DeprecatedConfig(Exception):
|
|
||||||
message = _("Fatal call to deprecated config: %(msg)s")
|
|
||||||
|
|
||||||
def __init__(self, msg):
|
|
||||||
super(Exception, self).__init__(self.message % dict(msg=msg))
|
|
Loading…
x
Reference in New Issue
Block a user