Merge "Add intermediate variable for HA test"
[yardstick.git] / yardstick / benchmark / scenarios / availability / util.py
1 ##############################################################################
2 # Copyright (c) 2016 Juan Qiu
3 # juan_ qiu@tongji.edu.cn
4 # All rights reserved. This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
7 # http://www.apache.org/licenses/LICENSE-2.0
8 ##############################################################################
9 import logging
10 import subprocess
11 import traceback
12
13 LOG = logging.getLogger(__name__)
14
15
16 def buildshellparams(param, remote=True):
17     result = '/bin/bash -s' if remote else ''
18     result += "".join(" {%d}" % i for i in range(len(param)))
19     return result
20
21
22 def execute_shell_command(command):
23     """execute shell script with error handling"""
24     exitcode = 0
25     output = []
26     try:
27         LOG.debug("the command is: %s", command)
28         output = subprocess.check_output(command, shell=True)
29     except Exception:
30         exitcode = -1
31         output = traceback.format_exc()
32         LOG.error("exec command '%s' error:\n ", command)
33         LOG.error(traceback.format_exc())
34     return exitcode, output
35
36 PREFIX = '$'
37
38
39 def build_shell_command(param_config, remote=True, intermediate_variables=None):
40     param_template = '/bin/bash -s' if remote else ''
41     if intermediate_variables:
42         for key, val in param_config.items():
43             if str(val).startswith(PREFIX):
44                 try:
45                     param_config[key] = intermediate_variables[val]
46                 except KeyError:
47                     pass
48     result = param_template + "".join(" {}".format(v) for v in param_config.values())
49     LOG.debug("THE RESULT OF build_shell_command IS: %s", result)
50     return result
51
52
53 def read_stdout_item(stdout, key):
54     for item in stdout.splitlines():
55         if key in item:
56             attributes = item.split("|")
57             if attributes[1].lstrip().startswith(key):
58                 return attributes[2].strip()
59     return None