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