1 # Copyright 2013: Mirantis Inc.
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
8 # http://www.apache.org/licenses/LICENSE-2.0
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
16 # yardstick comment: this is a modified copy of rally/rally/common/utils.py
18 from __future__ import absolute_import
19 from __future__ import print_function
31 from contextlib import closing
35 from flask import jsonify
36 from six.moves import configparser
37 from oslo_utils import importutils
38 from oslo_serialization import jsonutils
42 logger = logging.getLogger(__name__)
43 logger.setLevel(logging.DEBUG)
46 # Decorator for cli-args
47 def cliargs(*args, **kwargs):
49 func.__dict__.setdefault('arguments', []).insert(0, (args, kwargs))
54 def itersubclasses(cls, _seen=None):
55 """Generator over all subclasses of a given class in depth first order."""
57 if not isinstance(cls, type):
58 raise TypeError("itersubclasses must be called with "
59 "new-style classes, not %.100r" % cls)
60 _seen = _seen or set()
62 subs = cls.__subclasses__()
63 except TypeError: # fails only when cls is type
64 subs = cls.__subclasses__(cls)
69 for sub in itersubclasses(sub, _seen):
73 def try_append_module(name, modules):
74 if name not in modules:
75 modules[name] = importutils.import_module(name)
78 def import_modules_from_package(package):
79 """Import modules from package and append into sys.modules
81 :param: package - Full package name. For example: rally.deploy.engines
83 path = [os.path.dirname(yardstick.__file__), ".."] + package.split(".")
84 path = os.path.join(*path)
85 for root, dirs, files in os.walk(path):
86 for filename in files:
87 if filename.startswith("__") or not filename.endswith(".py"):
89 new_package = ".".join(root.split(os.sep)).split("....")[1]
90 module_name = "%s.%s" % (new_package, filename[:-3])
92 try_append_module(module_name, sys.modules)
94 logger.exception("unable to import %s", module_name)
97 def parse_yaml(file_path):
99 with open(file_path) as f:
100 value = yaml.safe_load(f)
104 if e.errno != errno.EEXIST:
114 if e.errno != errno.EEXIST:
118 def remove_file(path):
122 if e.errno != errno.ENOENT:
126 def execute_command(cmd):
127 exec_msg = "Executing command: '%s'" % cmd
128 logger.debug(exec_msg)
130 output = subprocess.check_output(cmd.split()).split(os.linesep)
135 def source_env(env_file):
136 p = subprocess.Popen(". %s; env" % env_file, stdout=subprocess.PIPE,
138 output = p.communicate()[0]
139 env = dict(line.split('=', 1) for line in output.splitlines() if '=' in line)
140 os.environ.update(env)
144 def read_json_from_file(path):
145 with open(path, 'r') as f:
147 # don't use jsonutils.load() it conflicts with already decoded input
148 return jsonutils.loads(j)
151 def write_json_to_file(path, data, mode='w'):
152 with open(path, mode) as f:
153 jsonutils.dump(data, f)
156 def write_file(path, data, mode='w'):
157 with open(path, mode) as f:
161 def parse_ini_file(path):
162 parser = configparser.ConfigParser()
165 files = parser.read(path)
166 except configparser.MissingSectionHeaderError:
167 logger.exception('invalid file type')
171 raise RuntimeError('file not exist')
174 default = {k: v for k, v in parser.items('DEFAULT')}
175 except configparser.NoSectionError:
178 config = dict(DEFAULT=default,
179 **{s: {k: v for k, v in parser.items(
180 s)} for s in parser.sections()})
185 def get_port_mac(sshclient, port):
186 cmd = "ifconfig |grep HWaddr |grep %s |awk '{print $5}' " % port
187 status, stdout, stderr = sshclient.execute(cmd)
190 raise RuntimeError(stderr)
191 return stdout.rstrip()
194 def get_port_ip(sshclient, port):
195 cmd = "ifconfig %s |grep 'inet addr' |awk '{print $2}' " \
196 "|cut -d ':' -f2 " % port
197 status, stdout, stderr = sshclient.execute(cmd)
200 raise RuntimeError(stderr)
201 return stdout.rstrip()
204 def flatten_dict_key(data):
207 # use list, because iterable is too generic
208 if not any(isinstance(v, (collections.Mapping, list))
209 for v in data.values()):
212 for k, v in data.items():
213 if isinstance(v, collections.Mapping):
214 for n_k, n_v in v.items():
215 next_data["%s.%s" % (k, n_k)] = n_v
216 # use list because iterable is too generic
217 elif isinstance(v, collections.Iterable) and not isinstance(v, six.string_types):
218 for index, item in enumerate(v):
219 next_data["%s%d" % (k, index)] = item
223 return flatten_dict_key(next_data)
226 def translate_to_str(obj):
227 if isinstance(obj, collections.Mapping):
228 return {str(k): translate_to_str(v) for k, v in obj.items()}
229 elif isinstance(obj, list):
230 return [translate_to_str(ele) for ele in obj]
231 elif isinstance(obj, six.text_type):
236 def result_handler(status, data):
241 return jsonify(result)
244 def change_obj_to_dict(obj):
246 for k, v in vars(obj).items():
254 def set_dict_value(dic, keys, value):
257 for key in keys.split('.'):
258 return_dic.setdefault(key, {})
259 if key == keys.split('.')[-1]:
260 return_dic[key] = value
262 return_dic = return_dic[key]
266 def get_free_port(ip):
267 with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
269 port = random.randint(5000, 10000)
270 if s.connect_ex((ip, port)) != 0:
274 def mac_address_to_hex_list(mac):
275 octets = ["0x{:02x}".format(int(elem, 16)) for elem in mac.split(':')]
276 assert len(octets) == 6 and all(len(octet) == 4 for octet in octets)
280 def safe_ip_address(ip_addr):
281 """ get ip address version v6 or v4 """
283 return ipaddress.ip_address(six.text_type(ip_addr))
285 logging.error("%s is not valid", ip_addr)
289 def get_ip_version(ip_addr):
290 """ get ip address version v6 or v4 """
292 address = ipaddress.ip_address(six.text_type(ip_addr))
294 logging.error("%s is not valid", ip_addr)
297 return address.version
300 def ip_to_hex(ip_addr):
302 address = ipaddress.ip_address(six.text_type(ip_addr))
304 logging.error("%s is not valid", ip_addr)
307 if address.version != 4:
309 return '{:08x}'.format(int(address))
312 def try_int(s, *args):
313 """Convert to integer if possible."""
316 except (TypeError, ValueError):
317 return args[0] if args else s
320 class SocketTopology(dict):
323 return sorted(self.keys())
326 return sorted(core for cores in self.values() for core in cores)
328 def processors(self):
330 proc for cores in self.values() for procs in cores.values() for
334 def parse_cpuinfo(cpuinfo):
337 lines = cpuinfo.splitlines()
343 name, value = line.split(":", 1)
344 core_lines[name.strip()] = try_int(value.strip())
346 core_details.append(core_lines)
349 for core in core_details:
350 socket_map.setdefault(core["physical id"], {}).setdefault(
351 core["core id"], {})[core["processor"]] = (
352 core["processor"], core["core id"], core["physical id"])
354 return SocketTopology(socket_map)
357 def config_to_dict(config):
358 return {section: dict(config.items(section)) for section in
362 def validate_non_string_sequence(value, default=None, raise_exc=None):
363 if isinstance(value, collections.Sequence) and not isinstance(value, str):
370 def join_non_strings(separator, *non_strings):
372 non_strings = validate_non_string_sequence(non_strings[0], raise_exc=RuntimeError)
373 except (IndexError, RuntimeError):
375 return str(separator).join(str(non_string) for non_string in non_strings)
378 class ErrorClass(object):
380 def __init__(self, *args, **kwargs):
381 if 'test' not in kwargs:
384 def __getattr__(self, item):
390 super(Timer, self).__init__()
391 self.start = self.delta = None
394 self.start = datetime.datetime.now()
397 def __exit__(self, *_):
398 self.delta = datetime.datetime.now() - self.start
400 def __getattr__(self, item):
401 return getattr(self.delta, item)