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
34 from flask import jsonify
35 from six.moves import configparser
36 from oslo_utils import importutils
37 from oslo_serialization import jsonutils
41 logger = logging.getLogger(__name__)
42 logger.setLevel(logging.DEBUG)
45 # Decorator for cli-args
46 def cliargs(*args, **kwargs):
48 func.__dict__.setdefault('arguments', []).insert(0, (args, kwargs))
53 def itersubclasses(cls, _seen=None):
54 """Generator over all subclasses of a given class in depth first order."""
56 if not isinstance(cls, type):
57 raise TypeError("itersubclasses must be called with "
58 "new-style classes, not %.100r" % cls)
59 _seen = _seen or set()
61 subs = cls.__subclasses__()
62 except TypeError: # fails only when cls is type
63 subs = cls.__subclasses__(cls)
68 for sub in itersubclasses(sub, _seen):
72 def import_modules_from_package(package):
73 """Import modules from package and append into sys.modules
75 :param: package - Full package name. For example: rally.deploy.engines
77 yardstick_root = os.path.dirname(os.path.dirname(yardstick.__file__))
78 path = os.path.join(yardstick_root, *package.split("."))
79 for root, dirs, files in os.walk(path):
80 matches = (filename for filename in files if filename.endswith(".py") and
81 not filename.startswith("__"))
82 new_package = os.path.relpath(root, yardstick_root).replace(os.sep, ".")
84 ("{}.{}".format(new_package, filename.rsplit(".py", 1)[0]) for filename in matches))
85 # find modules which haven't already been imported
86 missing_modules = module_names.difference(sys.modules)
87 logger.debug("importing %s", missing_modules)
88 # we have already checked for already imported modules, so we don't need to check again
89 for module_name in missing_modules:
91 sys.modules[module_name] = importutils.import_module(module_name)
92 except (ImportError, SyntaxError):
93 logger.exception("unable to import %s", module_name)
100 if e.errno != errno.EEXIST:
104 def remove_file(path):
108 if e.errno != errno.ENOENT:
112 def execute_command(cmd):
113 exec_msg = "Executing command: '%s'" % cmd
114 logger.debug(exec_msg)
116 output = subprocess.check_output(cmd.split()).split(os.linesep)
121 def source_env(env_file):
122 p = subprocess.Popen(". %s; env" % env_file, stdout=subprocess.PIPE,
124 output = p.communicate()[0]
125 env = dict(line.split('=', 1) for line in output.splitlines() if '=' in line)
126 os.environ.update(env)
130 def read_json_from_file(path):
131 with open(path, 'r') as f:
133 # don't use jsonutils.load() it conflicts with already decoded input
134 return jsonutils.loads(j)
137 def write_json_to_file(path, data, mode='w'):
138 with open(path, mode) as f:
139 jsonutils.dump(data, f)
142 def write_file(path, data, mode='w'):
143 with open(path, mode) as f:
147 def parse_ini_file(path):
148 parser = configparser.ConfigParser()
151 files = parser.read(path)
152 except configparser.MissingSectionHeaderError:
153 logger.exception('invalid file type')
157 raise RuntimeError('file not exist')
160 default = {k: v for k, v in parser.items('DEFAULT')}
161 except configparser.NoSectionError:
164 config = dict(DEFAULT=default,
165 **{s: {k: v for k, v in parser.items(
166 s)} for s in parser.sections()})
171 def get_port_mac(sshclient, port):
172 cmd = "ifconfig |grep HWaddr |grep %s |awk '{print $5}' " % port
173 status, stdout, stderr = sshclient.execute(cmd)
176 raise RuntimeError(stderr)
177 return stdout.rstrip()
180 def get_port_ip(sshclient, port):
181 cmd = "ifconfig %s |grep 'inet addr' |awk '{print $2}' " \
182 "|cut -d ':' -f2 " % port
183 status, stdout, stderr = sshclient.execute(cmd)
186 raise RuntimeError(stderr)
187 return stdout.rstrip()
190 def flatten_dict_key(data):
193 # use list, because iterable is too generic
194 if not any(isinstance(v, (collections.Mapping, list))
195 for v in data.values()):
198 for k, v in data.items():
199 if isinstance(v, collections.Mapping):
200 for n_k, n_v in v.items():
201 next_data["%s.%s" % (k, n_k)] = n_v
202 # use list because iterable is too generic
203 elif isinstance(v, collections.Iterable) and not isinstance(v, six.string_types):
204 for index, item in enumerate(v):
205 next_data["%s%d" % (k, index)] = item
209 return flatten_dict_key(next_data)
212 def translate_to_str(obj):
213 if isinstance(obj, collections.Mapping):
214 return {str(k): translate_to_str(v) for k, v in obj.items()}
215 elif isinstance(obj, list):
216 return [translate_to_str(ele) for ele in obj]
217 elif isinstance(obj, six.text_type):
222 def result_handler(status, data):
227 return jsonify(result)
230 def change_obj_to_dict(obj):
232 for k, v in vars(obj).items():
240 def set_dict_value(dic, keys, value):
243 for key in keys.split('.'):
244 return_dic.setdefault(key, {})
245 if key == keys.split('.')[-1]:
246 return_dic[key] = value
248 return_dic = return_dic[key]
252 def get_free_port(ip):
253 with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
255 port = random.randint(5000, 10000)
256 if s.connect_ex((ip, port)) != 0:
260 def mac_address_to_hex_list(mac):
261 octets = ["0x{:02x}".format(int(elem, 16)) for elem in mac.split(':')]
262 assert len(octets) == 6 and all(len(octet) == 4 for octet in octets)
266 def safe_ip_address(ip_addr):
267 """ get ip address version v6 or v4 """
269 return ipaddress.ip_address(six.text_type(ip_addr))
271 logging.error("%s is not valid", ip_addr)
275 def get_ip_version(ip_addr):
276 """ get ip address version v6 or v4 """
278 address = ipaddress.ip_address(six.text_type(ip_addr))
280 logging.error("%s is not valid", ip_addr)
283 return address.version
286 def ip_to_hex(ip_addr, separator=''):
288 address = ipaddress.ip_address(six.text_type(ip_addr))
290 logging.error("%s is not valid", ip_addr)
293 if address.version != 4:
297 return '{:08x}'.format(int(address))
299 return separator.join('{:02x}'.format(octet) for octet in address.packed)
302 def try_int(s, *args):
303 """Convert to integer if possible."""
306 except (TypeError, ValueError):
307 return args[0] if args else s
310 class SocketTopology(dict):
313 def parse_cpuinfo(cls, cpuinfo):
316 lines = cpuinfo.splitlines()
322 name, value = line.split(":", 1)
323 core_lines[name.strip()] = try_int(value.strip())
325 core_details.append(core_lines)
328 for core in core_details:
329 socket_map.setdefault(core["physical id"], {}).setdefault(
330 core["core id"], {})[core["processor"]] = (
331 core["processor"], core["core id"], core["physical id"])
333 return cls(socket_map)
336 return sorted(self.keys())
339 return sorted(core for cores in self.values() for core in cores)
341 def processors(self):
343 proc for cores in self.values() for procs in cores.values() for
347 def config_to_dict(config):
348 return {section: dict(config.items(section)) for section in
352 def validate_non_string_sequence(value, default=None, raise_exc=None):
353 if isinstance(value, collections.Sequence) and not isinstance(value, str):
360 def join_non_strings(separator, *non_strings):
362 non_strings = validate_non_string_sequence(non_strings[0], raise_exc=RuntimeError)
363 except (IndexError, RuntimeError):
365 return str(separator).join(str(non_string) for non_string in non_strings)
368 class ErrorClass(object):
370 def __init__(self, *args, **kwargs):
371 if 'test' not in kwargs:
374 def __getattr__(self, item):
380 super(Timer, self).__init__()
381 self.start = self.delta = None
384 self.start = datetime.datetime.now()
387 def __exit__(self, *_):
388 self.delta = datetime.datetime.now() - self.start
390 def __getattr__(self, item):
391 return getattr(self.delta, item)