4de0fcfd596839d8081ba12733bf37963c6ca46d
[yardstick.git] / yardstick / common / utils.py
1 # Copyright 2013: Mirantis Inc.
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 # yardstick comment: this is a modified copy of rally/rally/common/utils.py
17
18 import os
19 import sys
20 from oslo_utils import importutils
21
22 import yardstick
23
24
25 def itersubclasses(cls, _seen=None):
26     """Generator over all subclasses of a given class in depth first order."""
27
28     if not isinstance(cls, type):
29         raise TypeError("itersubclasses must be called with "
30                         "new-style classes, not %.100r" % cls)
31     _seen = _seen or set()
32     try:
33         subs = cls.__subclasses__()
34     except TypeError:   # fails only when cls is type
35         subs = cls.__subclasses__(cls)
36     for sub in subs:
37         if sub not in _seen:
38             _seen.add(sub)
39             yield sub
40             for sub in itersubclasses(sub, _seen):
41                 yield sub
42
43
44 def try_append_module(name, modules):
45     if name not in modules:
46         modules[name] = importutils.import_module(name)
47
48
49 def import_modules_from_package(package):
50     """Import modules from package and append into sys.modules
51
52     :param: package - Full package name. For example: rally.deploy.engines
53     """
54     path = [os.path.dirname(yardstick.__file__), ".."] + package.split(".")
55     path = os.path.join(*path)
56     for root, dirs, files in os.walk(path):
57         for filename in files:
58             if filename.startswith("__") or not filename.endswith(".py"):
59                 continue
60             new_package = ".".join(root.split(os.sep)).split("....")[1]
61             module_name = "%s.%s" % (new_package, filename[:-3])
62             try_append_module(module_name, sys.modules)