X-Git-Url: https://gerrit.opnfv.org/gerrit/gitweb?a=blobdiff_plain;f=yardstick%2Fcommon%2Futils.py;h=d2be8000ebf7333d637ebe166a22318d1e003e40;hb=6f541e757283b528d8736e314b2490f28d3c2563;hp=c482b4da4d2fca6e6e29d57104b44374f1478bb6;hpb=40f49a42dd8476ad2332ecf2e0a57e6bf511aa63;p=yardstick.git diff --git a/yardstick/common/utils.py b/yardstick/common/utils.py index c482b4da4..d2be8000e 100644 --- a/yardstick/common/utils.py +++ b/yardstick/common/utils.py @@ -15,12 +15,26 @@ # yardstick comment: this is a modified copy of rally/rally/common/utils.py +from __future__ import absolute_import +from __future__ import print_function + +import errno +import logging import os +import subprocess import sys +from functools import reduce + +import yaml +from six.moves import configparser from oslo_utils import importutils +from oslo_serialization import jsonutils import yardstick +logger = logging.getLogger(__name__) +logger.setLevel(logging.DEBUG) + # Decorator for cli-args def cliargs(*args, **kwargs): @@ -68,3 +82,84 @@ def import_modules_from_package(package): new_package = ".".join(root.split(os.sep)).split("....")[1] module_name = "%s.%s" % (new_package, filename[:-3]) try_append_module(module_name, sys.modules) + + +def get_para_from_yaml(file_path, args): + + def func(a, b): + if a is None: + return None + return a.get(b) + + if os.path.exists(file_path): + with open(file_path) as f: + value = yaml.safe_load(f) + value = reduce(func, args.split('.'), value) + + if value is None: + print('parameter not found') + return None + + return value + else: + print('file not exist') + return None + + +def makedirs(d): + try: + os.makedirs(d) + except OSError as e: + if e.errno != errno.EEXIST: + raise + + +def execute_command(cmd): + exec_msg = "Executing command: '%s'" % cmd + logger.debug(exec_msg) + + output = subprocess.check_output(cmd.split()).split(os.linesep) + + return output + + +def source_env(env_file): + p = subprocess.Popen(". %s; env" % env_file, stdout=subprocess.PIPE, + shell=True) + output = p.communicate()[0] + env = dict((line.split('=', 1) for line in output.splitlines())) + os.environ.update(env) + return env + + +def read_json_from_file(path): + with open(path, 'r') as f: + j = f.read() + # don't use jsonutils.load() it conflicts with already decoded input + return jsonutils.loads(j) + + +def write_json_to_file(path, data, mode='w'): + with open(path, mode) as f: + jsonutils.dump(data, f) + + +def write_file(path, data, mode='w'): + with open(path, mode) as f: + f.write(data) + + +def parse_ini_file(path): + parser = configparser.ConfigParser() + parser.read(path) + + try: + default = {k: v for k, v in parser.items('DEFAULT')} + except configparser.NoSectionError: + default = {} + + config = dict(DEFAULT=default, + **{s: {k: v for k, v in parser.items( + s)} for s in parser.sections()}) + + return config