Merge "enhance test cases description and provide more info(in progress)"
[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 import yaml
21 import errno
22 import subprocess
23 import logging
24
25 from oslo_utils import importutils
26 from keystoneauth1 import identity
27 from keystoneauth1 import session
28 from neutronclient.v2_0 import client
29
30 import yardstick
31
32 logger = logging.getLogger(__name__)
33 logger.setLevel(logging.DEBUG)
34
35
36 # Decorator for cli-args
37 def cliargs(*args, **kwargs):
38     def _decorator(func):
39         func.__dict__.setdefault('arguments', []).insert(0, (args, kwargs))
40         return func
41     return _decorator
42
43
44 def itersubclasses(cls, _seen=None):
45     """Generator over all subclasses of a given class in depth first order."""
46
47     if not isinstance(cls, type):
48         raise TypeError("itersubclasses must be called with "
49                         "new-style classes, not %.100r" % cls)
50     _seen = _seen or set()
51     try:
52         subs = cls.__subclasses__()
53     except TypeError:   # fails only when cls is type
54         subs = cls.__subclasses__(cls)
55     for sub in subs:
56         if sub not in _seen:
57             _seen.add(sub)
58             yield sub
59             for sub in itersubclasses(sub, _seen):
60                 yield sub
61
62
63 def try_append_module(name, modules):
64     if name not in modules:
65         modules[name] = importutils.import_module(name)
66
67
68 def import_modules_from_package(package):
69     """Import modules from package and append into sys.modules
70
71     :param: package - Full package name. For example: rally.deploy.engines
72     """
73     path = [os.path.dirname(yardstick.__file__), ".."] + package.split(".")
74     path = os.path.join(*path)
75     for root, dirs, files in os.walk(path):
76         for filename in files:
77             if filename.startswith("__") or not filename.endswith(".py"):
78                 continue
79             new_package = ".".join(root.split(os.sep)).split("....")[1]
80             module_name = "%s.%s" % (new_package, filename[:-3])
81             try_append_module(module_name, sys.modules)
82
83
84 def get_para_from_yaml(file_path, args):
85
86     def func(a, b):
87         if a is None:
88             return None
89         return a.get(b)
90
91     if os.path.exists(file_path):
92         with open(file_path) as f:
93             value = yaml.safe_load(f)
94             value = reduce(func, args.split('.'), value)
95
96             if value is None:
97                 print 'parameter not found'
98                 return None
99
100             return value
101     else:
102         print 'file not exist'
103         return None
104
105
106 def makedirs(d):
107     try:
108         os.makedirs(d)
109     except OSError as e:
110         if e.errno != errno.EEXIST:
111             raise
112
113
114 def execute_command(cmd):
115     exec_msg = "Executing command: '%s'" % cmd
116     logger.debug(exec_msg)
117
118     output = subprocess.check_output(cmd.split()).split(os.linesep)
119
120     return output
121
122
123 def source_env(env_file):
124     p = subprocess.Popen(". %s; env" % env_file, stdout=subprocess.PIPE,
125                          shell=True)
126     output = p.communicate()[0]
127     env = dict((line.split('=', 1) for line in output.splitlines()))
128     os.environ.update(env)
129     return env
130
131
132 def get_openstack_session():
133     auth = identity.Password(auth_url=os.environ.get('OS_AUTH_URL'),
134                              username=os.environ.get('OS_USERNAME'),
135                              password=os.environ.get('OS_PASSWORD'),
136                              tenant_name=os.environ.get('OS_TENANT_NAME'))
137     return session.Session(auth=auth)
138
139
140 def get_neutron_client():
141     sess = get_openstack_session()
142     neutron_client = client.Client(session=sess)
143     return neutron_client