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