Browse Source

Remove openstack.common package

The openstack.common package is unused, so let's remove it.

Change-Id: I98f7a5be1fea63a9385c03590508da867f6a2ccb
Sergey Vilgelm 3 years ago
parent
commit
910dfcf89f

+ 0
- 0
muranoagent/openstack/__init__.py View File


+ 0
- 17
muranoagent/openstack/common/__init__.py View File

@@ -1,17 +0,0 @@
1
-#
2
-#    Licensed under the Apache License, Version 2.0 (the "License"); you may
3
-#    not use this file except in compliance with the License. You may obtain
4
-#    a copy of the License at
5
-#
6
-#         http://www.apache.org/licenses/LICENSE-2.0
7
-#
8
-#    Unless required by applicable law or agreed to in writing, software
9
-#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
10
-#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
11
-#    License for the specific language governing permissions and limitations
12
-#    under the License.
13
-
14
-import six
15
-
16
-
17
-six.add_move(six.MovedModule('mox', 'mox', 'mox3.mox'))

+ 0
- 0
muranoagent/openstack/common/config/__init__.py View File


+ 0
- 313
muranoagent/openstack/common/config/generator.py View File

@@ -1,313 +0,0 @@
1
-# Copyright 2012 SINA Corporation
2
-# Copyright 2014 Cisco Systems, Inc.
3
-# All Rights Reserved.
4
-#
5
-#    Licensed under the Apache License, Version 2.0 (the "License"); you may
6
-#    not use this file except in compliance with the License. You may obtain
7
-#    a copy of the License at
8
-#
9
-#         http://www.apache.org/licenses/LICENSE-2.0
10
-#
11
-#    Unless required by applicable law or agreed to in writing, software
12
-#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13
-#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14
-#    License for the specific language governing permissions and limitations
15
-#    under the License.
16
-#
17
-
18
-"""Extracts OpenStack config option info from module(s)."""
19
-
20
-from __future__ import print_function
21
-
22
-import argparse
23
-import imp
24
-import os
25
-import re
26
-import socket
27
-import sys
28
-import textwrap
29
-
30
-from oslo_config import cfg
31
-import six
32
-import stevedore.named
33
-
34
-from muranoagent.openstack.common import gettextutils
35
-from muranoagent.openstack.common import importutils
36
-
37
-gettextutils.install('muranoagent')
38
-
39
-STROPT = "StrOpt"
40
-BOOLOPT = "BoolOpt"
41
-INTOPT = "IntOpt"
42
-FLOATOPT = "FloatOpt"
43
-LISTOPT = "ListOpt"
44
-DICTOPT = "DictOpt"
45
-MULTISTROPT = "MultiStrOpt"
46
-
47
-OPT_TYPES = {
48
-    STROPT: 'string value',
49
-    BOOLOPT: 'boolean value',
50
-    INTOPT: 'integer value',
51
-    FLOATOPT: 'floating point value',
52
-    LISTOPT: 'list value',
53
-    DICTOPT: 'dict value',
54
-    MULTISTROPT: 'multi valued',
55
-}
56
-
57
-OPTION_REGEX = re.compile(r"(%s)" % "|".join([STROPT, BOOLOPT, INTOPT,
58
-                                              FLOATOPT, LISTOPT, DICTOPT,
59
-                                              MULTISTROPT]))
60
-
61
-PY_EXT = ".py"
62
-BASEDIR = os.path.abspath(os.path.join(os.path.dirname(__file__),
63
-                                       "../../../../"))
64
-WORDWRAP_WIDTH = 60
65
-
66
-
67
-def raise_extension_exception(extmanager, ep, err):
68
-    raise
69
-
70
-
71
-def generate(argv):
72
-    parser = argparse.ArgumentParser(
73
-        description='generate sample configuration file',
74
-    )
75
-    parser.add_argument('-m', dest='modules', action='append')
76
-    parser.add_argument('-l', dest='libraries', action='append')
77
-    parser.add_argument('srcfiles', nargs='*')
78
-    parsed_args = parser.parse_args(argv)
79
-
80
-    mods_by_pkg = dict()
81
-    for filepath in parsed_args.srcfiles:
82
-        pkg_name = filepath.split(os.sep)[1]
83
-        mod_str = '.'.join(['.'.join(filepath.split(os.sep)[:-1]),
84
-                            os.path.basename(filepath).split('.')[0]])
85
-        mods_by_pkg.setdefault(pkg_name, list()).append(mod_str)
86
-    # NOTE(lzyeval): place top level modules before packages
87
-    pkg_names = sorted(pkg for pkg in mods_by_pkg if pkg.endswith(PY_EXT))
88
-    ext_names = sorted(pkg for pkg in mods_by_pkg if pkg not in pkg_names)
89
-    pkg_names.extend(ext_names)
90
-
91
-    # opts_by_group is a mapping of group name to an options list
92
-    # The options list is a list of (module, options) tuples
93
-    opts_by_group = {'DEFAULT': []}
94
-
95
-    if parsed_args.modules:
96
-        for module_name in parsed_args.modules:
97
-            module = _import_module(module_name)
98
-            if module:
99
-                for group, opts in _list_opts(module):
100
-                    opts_by_group.setdefault(group, []).append((module_name,
101
-                                                                opts))
102
-
103
-    # Look for entry points defined in libraries (or applications) for
104
-    # option discovery, and include their return values in the output.
105
-    #
106
-    # Each entry point should be a function returning an iterable
107
-    # of pairs with the group name (or None for the default group)
108
-    # and the list of Opt instances for that group.
109
-    if parsed_args.libraries:
110
-        loader = stevedore.named.NamedExtensionManager(
111
-            'oslo.config.opts',
112
-            names=list(set(parsed_args.libraries)),
113
-            invoke_on_load=False,
114
-            on_load_failure_callback=raise_extension_exception
115
-        )
116
-        for ext in loader:
117
-            for group, opts in ext.plugin():
118
-                opt_list = opts_by_group.setdefault(group or 'DEFAULT', [])
119
-                opt_list.append((ext.name, opts))
120
-
121
-    for pkg_name in pkg_names:
122
-        mods = mods_by_pkg.get(pkg_name)
123
-        mods.sort()
124
-        for mod_str in mods:
125
-            if mod_str.endswith('.__init__'):
126
-                mod_str = mod_str[:mod_str.rfind(".")]
127
-
128
-            mod_obj = _import_module(mod_str)
129
-            if not mod_obj:
130
-                raise RuntimeError("Unable to import module %s" % mod_str)
131
-
132
-            for group, opts in _list_opts(mod_obj):
133
-                opts_by_group.setdefault(group, []).append((mod_str, opts))
134
-
135
-    print_group_opts('DEFAULT', opts_by_group.pop('DEFAULT', []))
136
-    for group in sorted(opts_by_group.keys()):
137
-        print_group_opts(group, opts_by_group[group])
138
-
139
-
140
-def _import_module(mod_str):
141
-    try:
142
-        if mod_str.startswith('bin.'):
143
-            imp.load_source(mod_str[4:], os.path.join('bin', mod_str[4:]))
144
-            return sys.modules[mod_str[4:]]
145
-        else:
146
-            return importutils.import_module(mod_str)
147
-    except Exception as e:
148
-        sys.stderr.write("Error importing module %s: %s\n" % (mod_str, str(e)))
149
-        return None
150
-
151
-
152
-def _is_in_group(opt, group):
153
-    """Check if opt is in group."""
154
-    for value in group._opts.values():
155
-        # NOTE(llu): Temporary workaround for bug #1262148, wait until
156
-        # newly released oslo.config support '==' operator.
157
-        if not(value['opt'] != opt):
158
-            return True
159
-    return False
160
-
161
-
162
-def _guess_groups(opt):
163
-    # is it in the DEFAULT group?
164
-    if _is_in_group(opt, cfg.CONF):
165
-        return 'DEFAULT'
166
-
167
-    # what other groups is it in?
168
-    for value in cfg.CONF.values():
169
-        if isinstance(value, cfg.CONF.GroupAttr):
170
-            if _is_in_group(opt, value._group):
171
-                return value._group.name
172
-
173
-    raise RuntimeError(
174
-        "Unable to find group for option %s, "
175
-        "maybe it's defined twice in the same group?"
176
-        % opt.name
177
-    )
178
-
179
-
180
-def _list_opts(obj):
181
-    def is_opt(o):
182
-        return (isinstance(o, cfg.Opt) and
183
-                not isinstance(o, cfg.SubCommandOpt))
184
-
185
-    opts = list()
186
-    for attr_str in dir(obj):
187
-        attr_obj = getattr(obj, attr_str)
188
-        if is_opt(attr_obj):
189
-            opts.append(attr_obj)
190
-        elif (isinstance(attr_obj, list) and
191
-              all(map(lambda x: is_opt(x), attr_obj))):
192
-            opts.extend(attr_obj)
193
-
194
-    ret = {}
195
-    for opt in opts:
196
-        ret.setdefault(_guess_groups(opt), []).append(opt)
197
-    return ret.items()
198
-
199
-
200
-def print_group_opts(group, opts_by_module):
201
-    print("[%s]" % group)
202
-    print('')
203
-    for mod, opts in opts_by_module:
204
-        print('#')
205
-        print('# Options defined in %s' % mod)
206
-        print('#')
207
-        print('')
208
-        for opt in opts:
209
-            _print_opt(opt)
210
-        print('')
211
-
212
-
213
-def _get_my_ip():
214
-    try:
215
-        csock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
216
-        csock.connect(('8.8.8.8', 80))
217
-        (addr, port) = csock.getsockname()
218
-        csock.close()
219
-        return addr
220
-    except socket.error:
221
-        return None
222
-
223
-
224
-def _sanitize_default(name, value):
225
-    """Set up a reasonably sensible default for pybasedir, my_ip and host."""
226
-    hostname = socket.gethostname()
227
-    fqdn = socket.getfqdn()
228
-    if value.startswith(sys.prefix):
229
-        # NOTE(jd) Don't use os.path.join, because it is likely to think the
230
-        # second part is an absolute pathname and therefore drop the first
231
-        # part.
232
-        value = os.path.normpath("/usr/" + value[len(sys.prefix):])
233
-    elif value.startswith(BASEDIR):
234
-        return value.replace(BASEDIR, '/usr/lib/python/site-packages')
235
-    elif BASEDIR in value:
236
-        return value.replace(BASEDIR, '')
237
-    elif value == _get_my_ip():
238
-        return '10.0.0.1'
239
-    elif value in (hostname, fqdn):
240
-        if 'host' in name:
241
-            return 'muranoagent'
242
-    elif value.endswith(hostname):
243
-        return value.replace(hostname, 'muranoagent')
244
-    elif value.endswith(fqdn):
245
-        return value.replace(fqdn, 'muranoagent')
246
-    elif value.strip() != value:
247
-        return '"%s"' % value
248
-    return value
249
-
250
-
251
-def _print_opt(opt):
252
-    opt_name, opt_default, opt_help = opt.dest, opt.default, opt.help
253
-    if not opt_help:
254
-        sys.stderr.write('WARNING: "%s" is missing help string.\n' % opt_name)
255
-        opt_help = ""
256
-    try:
257
-        opt_type = OPTION_REGEX.search(str(type(opt))).group(0)
258
-    except (ValueError, AttributeError) as err:
259
-        sys.stderr.write("%s\n" % str(err))
260
-        sys.exit(1)
261
-    opt_help = u'%s (%s)' % (opt_help,
262
-                             OPT_TYPES[opt_type])
263
-    print('#', "\n# ".join(textwrap.wrap(opt_help, WORDWRAP_WIDTH)))
264
-    if opt.deprecated_opts:
265
-        for deprecated_opt in opt.deprecated_opts:
266
-            if deprecated_opt.name:
267
-                deprecated_group = (deprecated_opt.group if
268
-                                    deprecated_opt.group else "DEFAULT")
269
-                print('# Deprecated group/name - [%s]/%s' %
270
-                      (deprecated_group,
271
-                       deprecated_opt.name))
272
-    try:
273
-        if opt_default is None:
274
-            print('#%s=<None>' % opt_name)
275
-        elif opt_type == STROPT:
276
-            assert(isinstance(opt_default, six.string_types))
277
-            print('#%s=%s' % (opt_name, _sanitize_default(opt_name,
278
-                                                          opt_default)))
279
-        elif opt_type == BOOLOPT:
280
-            assert(isinstance(opt_default, bool))
281
-            print('#%s=%s' % (opt_name, str(opt_default).lower()))
282
-        elif opt_type == INTOPT:
283
-            assert(isinstance(opt_default, int) and
284
-                   not isinstance(opt_default, bool))
285
-            print('#%s=%s' % (opt_name, opt_default))
286
-        elif opt_type == FLOATOPT:
287
-            assert(isinstance(opt_default, float))
288
-            print('#%s=%s' % (opt_name, opt_default))
289
-        elif opt_type == LISTOPT:
290
-            assert(isinstance(opt_default, list))
291
-            print('#%s=%s' % (opt_name, ','.join(opt_default)))
292
-        elif opt_type == DICTOPT:
293
-            assert(isinstance(opt_default, dict))
294
-            opt_default_strlist = [str(key) + ':' + str(value)
295
-                                   for (key, value) in opt_default.items()]
296
-            print('#%s=%s' % (opt_name, ','.join(opt_default_strlist)))
297
-        elif opt_type == MULTISTROPT:
298
-            assert(isinstance(opt_default, list))
299
-            if not opt_default:
300
-                opt_default = ['']
301
-            for default in opt_default:
302
-                print('#%s=%s' % (opt_name, default))
303
-        print('')
304
-    except Exception:
305
-        sys.stderr.write('Error in option "%s"\n' % opt_name)
306
-        sys.exit(1)
307
-
308
-
309
-def main():
310
-    generate(sys.argv[1:])
311
-
312
-if __name__ == '__main__':
313
-    main()

+ 0
- 479
muranoagent/openstack/common/gettextutils.py View File

@@ -1,479 +0,0 @@
1
-# Copyright 2012 Red Hat, Inc.
2
-# Copyright 2013 IBM Corp.
3
-# All Rights Reserved.
4
-#
5
-#    Licensed under the Apache License, Version 2.0 (the "License"); you may
6
-#    not use this file except in compliance with the License. You may obtain
7
-#    a copy of the License at
8
-#
9
-#         http://www.apache.org/licenses/LICENSE-2.0
10
-#
11
-#    Unless required by applicable law or agreed to in writing, software
12
-#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13
-#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14
-#    License for the specific language governing permissions and limitations
15
-#    under the License.
16
-
17
-"""
18
-gettext for openstack-common modules.
19
-
20
-Usual usage in an openstack.common module:
21
-
22
-    from muranoagent.openstack.common.gettextutils import _
23
-"""
24
-
25
-import copy
26
-import gettext
27
-import locale
28
-from logging import handlers
29
-import os
30
-
31
-from babel import localedata
32
-import six
33
-
34
-_AVAILABLE_LANGUAGES = {}
35
-
36
-# FIXME(dhellmann): Remove this when moving to oslo.i18n.
37
-USE_LAZY = False
38
-
39
-
40
-class TranslatorFactory(object):
41
-    """Create translator functions
42
-    """
43
-
44
-    def __init__(self, domain, localedir=None):
45
-        """Establish a set of translation functions for the domain.
46
-
47
-        :param domain: Name of translation domain,
48
-                       specifying a message catalog.
49
-        :type domain: str
50
-        :param lazy: Delays translation until a message is emitted.
51
-                     Defaults to False.
52
-        :type lazy: Boolean
53
-        :param localedir: Directory with translation catalogs.
54
-        :type localedir: str
55
-        """
56
-        self.domain = domain
57
-        if localedir is None:
58
-            localedir = os.environ.get(domain.upper() + '_LOCALEDIR')
59
-        self.localedir = localedir
60
-
61
-    def _make_translation_func(self, domain=None):
62
-        """Return a new translation function ready for use.
63
-
64
-        Takes into account whether or not lazy translation is being
65
-        done.
66
-
67
-        The domain can be specified to override the default from the
68
-        factory, but the localedir from the factory is always used
69
-        because we assume the log-level translation catalogs are
70
-        installed in the same directory as the main application
71
-        catalog.
72
-
73
-        """
74
-        if domain is None:
75
-            domain = self.domain
76
-        t = gettext.translation(domain,
77
-                                localedir=self.localedir,
78
-                                fallback=True)
79
-        # Use the appropriate method of the translation object based
80
-        # on the python version.
81
-        m = t.gettext if six.PY3 else t.ugettext
82
-
83
-        def f(msg):
84
-            """oslo.i18n.gettextutils translation function."""
85
-            if USE_LAZY:
86
-                return Message(msg, domain=domain)
87
-            return m(msg)
88
-        return f
89
-
90
-    @property
91
-    def primary(self):
92
-        "The default translation function."
93
-        return self._make_translation_func()
94
-
95
-    def _make_log_translation_func(self, level):
96
-        return self._make_translation_func(self.domain + '-log-' + level)
97
-
98
-    @property
99
-    def log_info(self):
100
-        "Translate info-level log messages."
101
-        return self._make_log_translation_func('info')
102
-
103
-    @property
104
-    def log_warning(self):
105
-        "Translate warning-level log messages."
106
-        return self._make_log_translation_func('warning')
107
-
108
-    @property
109
-    def log_error(self):
110
-        "Translate error-level log messages."
111
-        return self._make_log_translation_func('error')
112
-
113
-    @property
114
-    def log_critical(self):
115
-        "Translate critical-level log messages."
116
-        return self._make_log_translation_func('critical')
117
-
118
-
119
-# NOTE(dhellmann): When this module moves out of the incubator into
120
-# oslo.i18n, these global variables can be moved to an integration
121
-# module within each application.
122
-
123
-# Create the global translation functions.
124
-_translators = TranslatorFactory('muranoagent')
125
-
126
-# The primary translation function using the well-known name "_"
127
-_ = _translators.primary
128
-
129
-# Translators for log levels.
130
-#
131
-# The abbreviated names are meant to reflect the usual use of a short
132
-# name like '_'. The "L" is for "log" and the other letter comes from
133
-# the level.
134
-_LI = _translators.log_info
135
-_LW = _translators.log_warning
136
-_LE = _translators.log_error
137
-_LC = _translators.log_critical
138
-
139
-# NOTE(dhellmann): End of globals that will move to the application's
140
-# integration module.
141
-
142
-
143
-def enable_lazy():
144
-    """Convenience function for configuring _() to use lazy gettext
145
-
146
-    Call this at the start of execution to enable the gettextutils._
147
-    function to use lazy gettext functionality. This is useful if
148
-    your project is importing _ directly instead of using the
149
-    gettextutils.install() way of importing the _ function.
150
-    """
151
-    global USE_LAZY
152
-    USE_LAZY = True
153
-
154
-
155
-def install(domain):
156
-    """Install a _() function using the given translation domain.
157
-
158
-    Given a translation domain, install a _() function using gettext's
159
-    install() function.
160
-
161
-    The main difference from gettext.install() is that we allow
162
-    overriding the default localedir (e.g. /usr/share/locale) using
163
-    a translation-domain-specific environment variable (e.g.
164
-    NOVA_LOCALEDIR).
165
-
166
-    Note that to enable lazy translation, enable_lazy must be
167
-    called.
168
-
169
-    :param domain: the translation domain
170
-    """
171
-    from six import moves
172
-    tf = TranslatorFactory(domain)
173
-    moves.builtins.__dict__['_'] = tf.primary
174
-
175
-
176
-class Message(six.text_type):
177
-    """A Message object is a unicode object that can be translated.
178
-
179
-    Translation of Message is done explicitly using the translate() method.
180
-    For all non-translation intents and purposes, a Message is simply unicode,
181
-    and can be treated as such.
182
-    """
183
-
184
-    def __new__(cls, msgid, msgtext=None, params=None,
185
-                domain='muranoagent', *args):
186
-        """Create a new Message object.
187
-
188
-        In order for translation to work gettext requires a message ID, this
189
-        msgid will be used as the base unicode text. It is also possible
190
-        for the msgid and the base unicode text to be different by passing
191
-        the msgtext parameter.
192
-        """
193
-        # If the base msgtext is not given, we use the default translation
194
-        # of the msgid (which is in English) just in case the system locale is
195
-        # not English, so that the base text will be in that locale by default.
196
-        if not msgtext:
197
-            msgtext = Message._translate_msgid(msgid, domain)
198
-        # We want to initialize the parent unicode with the actual object that
199
-        # would have been plain unicode if 'Message' was not enabled.
200
-        msg = super(Message, cls).__new__(cls, msgtext)
201
-        msg.msgid = msgid
202
-        msg.domain = domain
203
-        msg.params = params
204
-        return msg
205
-
206
-    def translate(self, desired_locale=None):
207
-        """Translate this message to the desired locale.
208
-
209
-        :param desired_locale: The desired locale to translate the message to,
210
-                               if no locale is provided the message will be
211
-                               translated to the system's default locale.
212
-
213
-        :returns: the translated message in unicode
214
-        """
215
-
216
-        translated_message = Message._translate_msgid(self.msgid,
217
-                                                      self.domain,
218
-                                                      desired_locale)
219
-        if self.params is None:
220
-            # No need for more translation
221
-            return translated_message
222
-
223
-        # This Message object may have been formatted with one or more
224
-        # Message objects as substitution arguments, given either as a single
225
-        # argument, part of a tuple, or as one or more values in a dictionary.
226
-        # When translating this Message we need to translate those Messages too
227
-        translated_params = _translate_args(self.params, desired_locale)
228
-
229
-        translated_message = translated_message % translated_params
230
-
231
-        return translated_message
232
-
233
-    @staticmethod
234
-    def _translate_msgid(msgid, domain, desired_locale=None):
235
-        if not desired_locale:
236
-            system_locale = locale.getdefaultlocale()
237
-            # If the system locale is not available to the runtime use English
238
-            if not system_locale[0]:
239
-                desired_locale = 'en_US'
240
-            else:
241
-                desired_locale = system_locale[0]
242
-
243
-        locale_dir = os.environ.get(domain.upper() + '_LOCALEDIR')
244
-        lang = gettext.translation(domain,
245
-                                   localedir=locale_dir,
246
-                                   languages=[desired_locale],
247
-                                   fallback=True)
248
-        if six.PY3:
249
-            translator = lang.gettext
250
-        else:
251
-            translator = lang.ugettext
252
-
253
-        translated_message = translator(msgid)
254
-        return translated_message
255
-
256
-    def __mod__(self, other):
257
-        # When we mod a Message we want the actual operation to be performed
258
-        # by the parent class (i.e. unicode()), the only thing  we do here is
259
-        # save the original msgid and the parameters in case of a translation
260
-        params = self._sanitize_mod_params(other)
261
-        unicode_mod = super(Message, self).__mod__(params)
262
-        modded = Message(self.msgid,
263
-                         msgtext=unicode_mod,
264
-                         params=params,
265
-                         domain=self.domain)
266
-        return modded
267
-
268
-    def _sanitize_mod_params(self, other):
269
-        """Sanitize the object being modded with this Message.
270
-
271
-        - Add support for modding 'None' so translation supports it
272
-        - Trim the modded object, which can be a large dictionary, to only
273
-        those keys that would actually be used in a translation
274
-        - Snapshot the object being modded, in case the message is
275
-        translated, it will be used as it was when the Message was created
276
-        """
277
-        if other is None:
278
-            params = (other,)
279
-        elif isinstance(other, dict):
280
-            # Merge the dictionaries
281
-            # Copy each item in case one does not support deep copy.
282
-            params = {}
283
-            if isinstance(self.params, dict):
284
-                for key, val in self.params.items():
285
-                    params[key] = self._copy_param(val)
286
-            for key, val in other.items():
287
-                params[key] = self._copy_param(val)
288
-        else:
289
-            params = self._copy_param(other)
290
-        return params
291
-
292
-    def _copy_param(self, param):
293
-        try:
294
-            return copy.deepcopy(param)
295
-        except Exception:
296
-            # Fallback to casting to unicode this will handle the
297
-            # python code-like objects that can't be deep-copied
298
-            return six.text_type(param)
299
-
300
-    def __add__(self, other):
301
-        msg = _('Message objects do not support addition.')
302
-        raise TypeError(msg)
303
-
304
-    def __radd__(self, other):
305
-        return self.__add__(other)
306
-
307
-    if six.PY2:
308
-        def __str__(self):
309
-            # NOTE(luisg): Logging in python 2.6 tries to str() log records,
310
-            # and it expects specifically a UnicodeError in order to proceed.
311
-            msg = _('Message objects do not support str() because they may '
312
-                    'contain non-ascii characters. '
313
-                    'Please use unicode() or translate() instead.')
314
-            raise UnicodeError(msg)
315
-
316
-
317
-def get_available_languages(domain):
318
-    """Lists the available languages for the given translation domain.
319
-
320
-    :param domain: the domain to get languages for
321
-    """
322
-    if domain in _AVAILABLE_LANGUAGES:
323
-        return copy.copy(_AVAILABLE_LANGUAGES[domain])
324
-
325
-    localedir = '%s_LOCALEDIR' % domain.upper()
326
-    find = lambda x: gettext.find(domain,
327
-                                  localedir=os.environ.get(localedir),
328
-                                  languages=[x])
329
-
330
-    # NOTE(mrodden): en_US should always be available (and first in case
331
-    # order matters) since our in-line message strings are en_US
332
-    language_list = ['en_US']
333
-    # NOTE(luisg): Babel <1.0 used a function called list(), which was
334
-    # renamed to locale_identifiers() in >=1.0, the requirements master list
335
-    # requires >=0.9.6, uncapped, so defensively work with both. We can remove
336
-    # this check when the master list updates to >=1.0, and update all projects
337
-    list_identifiers = (getattr(localedata, 'list', None) or
338
-                        getattr(localedata, 'locale_identifiers'))
339
-    locale_identifiers = list_identifiers()
340
-
341
-    for i in locale_identifiers:
342
-        if find(i) is not None:
343
-            language_list.append(i)
344
-
345
-    # NOTE(luisg): Babel>=1.0,<1.3 has a bug where some OpenStack supported
346
-    # locales (e.g. 'zh_CN', and 'zh_TW') aren't supported even though they
347
-    # are perfectly legitimate locales:
348
-    #     https://github.com/mitsuhiko/babel/issues/37
349
-    # In Babel 1.3 they fixed the bug and they support these locales, but
350
-    # they are still not explicitly "listed" by locale_identifiers().
351
-    # That is  why we add the locales here explicitly if necessary so that
352
-    # they are listed as supported.
353
-    aliases = {'zh': 'zh_CN',
354
-               'zh_Hant_HK': 'zh_HK',
355
-               'zh_Hant': 'zh_TW',
356
-               'fil': 'tl_PH'}
357
-    for (locale_, alias) in six.iteritems(aliases):
358
-        if locale_ in language_list and alias not in language_list:
359
-            language_list.append(alias)
360
-
361
-    _AVAILABLE_LANGUAGES[domain] = language_list
362
-    return copy.copy(language_list)
363
-
364
-
365
-def translate(obj, desired_locale=None):
366
-    """Gets the translated unicode representation of the given object.
367
-
368
-    If the object is not translatable it is returned as-is.
369
-    If the locale is None the object is translated to the system locale.
370
-
371
-    :param obj: the object to translate
372
-    :param desired_locale: the locale to translate the message to, if None the
373
-                           default system locale will be used
374
-    :returns: the translated object in unicode, or the original object if
375
-              it could not be translated
376
-    """
377
-    message = obj
378
-    if not isinstance(message, Message):
379
-        # If the object to translate is not already translatable,
380
-        # let's first get its unicode representation
381
-        message = six.text_type(obj)
382
-    if isinstance(message, Message):
383
-        # Even after unicoding() we still need to check if we are
384
-        # running with translatable unicode before translating
385
-        return message.translate(desired_locale)
386
-    return obj
387
-
388
-
389
-def _translate_args(args, desired_locale=None):
390
-    """Translates all the translatable elements of the given arguments object.
391
-
392
-    This method is used for translating the translatable values in method
393
-    arguments which include values of tuples or dictionaries.
394
-    If the object is not a tuple or a dictionary the object itself is
395
-    translated if it is translatable.
396
-
397
-    If the locale is None the object is translated to the system locale.
398
-
399
-    :param args: the args to translate
400
-    :param desired_locale: the locale to translate the args to, if None the
401
-                           default system locale will be used
402
-    :returns: a new args object with the translated contents of the original
403
-    """
404
-    if isinstance(args, tuple):
405
-        return tuple(translate(v, desired_locale) for v in args)
406
-    if isinstance(args, dict):
407
-        translated_dict = {}
408
-        for (k, v) in six.iteritems(args):
409
-            translated_v = translate(v, desired_locale)
410
-            translated_dict[k] = translated_v
411
-        return translated_dict
412
-    return translate(args, desired_locale)
413
-
414
-
415
-class TranslationHandler(handlers.MemoryHandler):
416
-    """Handler that translates records before logging them.
417
-
418
-    The TranslationHandler takes a locale and a target logging.Handler object
419
-    to forward LogRecord objects to after translating them. This handler
420
-    depends on Message objects being logged, instead of regular strings.
421
-
422
-    The handler can be configured declaratively in the logging.conf as follows:
423
-
424
-        [handlers]
425
-        keys = translatedlog, translator
426
-
427
-        [handler_translatedlog]
428
-        class = handlers.WatchedFileHandler
429
-        args = ('/var/log/api-localized.log',)
430
-        formatter = context
431
-
432
-        [handler_translator]
433
-        class = openstack.common.log.TranslationHandler
434
-        target = translatedlog
435
-        args = ('zh_CN',)
436
-
437
-    If the specified locale is not available in the system, the handler will
438
-    log in the default locale.
439
-    """
440
-
441
-    def __init__(self, locale=None, target=None):
442
-        """Initialize a TranslationHandler
443
-
444
-        :param locale: locale to use for translating messages
445
-        :param target: logging.Handler object to forward
446
-                       LogRecord objects to after translation
447
-        """
448
-        # NOTE(luisg): In order to allow this handler to be a wrapper for
449
-        # other handlers, such as a FileHandler, and still be able to
450
-        # configure it using logging.conf, this handler has to extend
451
-        # MemoryHandler because only the MemoryHandlers' logging.conf
452
-        # parsing is implemented such that it accepts a target handler.
453
-        handlers.MemoryHandler.__init__(self, capacity=0, target=target)
454
-        self.locale = locale
455
-
456
-    def setFormatter(self, fmt):
457
-        self.target.setFormatter(fmt)
458
-
459
-    def emit(self, record):
460
-        # We save the message from the original record to restore it
461
-        # after translation, so other handlers are not affected by this
462
-        original_msg = record.msg
463
-        original_args = record.args
464
-
465
-        try:
466
-            self._translate_and_log_record(record)
467
-        finally:
468
-            record.msg = original_msg
469
-            record.args = original_args
470
-
471
-    def _translate_and_log_record(self, record):
472
-        record.msg = translate(record.msg, self.locale)
473
-
474
-        # In addition to translating the message, we also need to translate
475
-        # arguments that were passed to the log method that were not part
476
-        # of the main message e.g., log.info(_('Some message %s'), this_one))
477
-        record.args = _translate_args(record.args, self.locale)
478
-
479
-        self.target.emit(record)

+ 0
- 73
muranoagent/openstack/common/importutils.py View File

@@ -1,73 +0,0 @@
1
-# Copyright 2011 OpenStack Foundation.
2
-# All Rights Reserved.
3
-#
4
-#    Licensed under the Apache License, Version 2.0 (the "License"); you may
5
-#    not use this file except in compliance with the License. You may obtain
6
-#    a copy of the License at
7
-#
8
-#         http://www.apache.org/licenses/LICENSE-2.0
9
-#
10
-#    Unless required by applicable law or agreed to in writing, software
11
-#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12
-#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13
-#    License for the specific language governing permissions and limitations
14
-#    under the License.
15
-
16
-"""
17
-Import related utilities and helper functions.
18
-"""
19
-
20
-import sys
21
-import traceback
22
-
23
-
24
-def import_class(import_str):
25
-    """Returns a class from a string including module and class."""
26
-    mod_str, _sep, class_str = import_str.rpartition('.')
27
-    __import__(mod_str)
28
-    try:
29
-        return getattr(sys.modules[mod_str], class_str)
30
-    except AttributeError:
31
-        raise ImportError('Class %s cannot be found (%s)' %
32
-                          (class_str,
33
-                           traceback.format_exception(*sys.exc_info())))
34
-
35
-
36
-def import_object(import_str, *args, **kwargs):
37
-    """Import a class and return an instance of it."""
38
-    return import_class(import_str)(*args, **kwargs)
39
-
40
-
41
-def import_object_ns(name_space, import_str, *args, **kwargs):
42
-    """Tries to import object from default namespace.
43
-
44
-    Imports a class and return an instance of it, first by trying
45
-    to find the class in a default namespace, then failing back to
46
-    a full path if not found in the default namespace.
47
-    """
48
-    import_value = "%s.%s" % (name_space, import_str)
49
-    try:
50
-        return import_class(import_value)(*args, **kwargs)
51
-    except ImportError:
52
-        return import_class(import_str)(*args, **kwargs)
53
-
54
-
55
-def import_module(import_str):
56
-    """Import a module."""
57
-    __import__(import_str)
58
-    return sys.modules[import_str]
59
-
60
-
61
-def import_versioned_module(version, submodule=None):
62
-    module = 'muranoagent.v%s' % version
63
-    if submodule:
64
-        module = '.'.join((module, submodule))
65
-    return import_module(module)
66
-
67
-
68
-def try_import(import_str, default=None):
69
-    """Try to import a module and if it fails return default."""
70
-    try:
71
-        return import_module(import_str)
72
-    except ImportError:
73
-        return default

+ 0
- 2
openstack-common.conf View File

@@ -1,8 +1,6 @@
1 1
 [DEFAULT]
2 2
 
3 3
 # The list of modules to copy from openstack-common
4
-module=exception
5
-module=importutils
6 4
 module=install_venv_common
7 5
 
8 6
 

Loading…
Cancel
Save