4 # Runs tempest and pushes the results to the DB
7 # morgan.richomme@orange.com
8 # jose.lausuch@ericsson.com
9 # viktor.tikkanen@nokia.com
11 # All rights reserved. This program and the accompanying materials
12 # are made available under the terms of the Apache License, Version 2.0
13 # which accompanies this distribution, and is available at
14 # http://www.apache.org/licenses/LICENSE-2.0
26 import keystoneclient.v2_0.client as ksclient
27 from neutronclient.v2_0 import client as neutronclient
29 modes = ['full', 'smoke', 'baremetal', 'compute', 'data_processing',
30 'identity', 'image', 'network', 'object_storage', 'orchestration',
31 'telemetry', 'volume', 'custom']
33 """ tests configuration """
34 parser = argparse.ArgumentParser()
35 parser.add_argument("-d", "--debug", help="Debug mode", action="store_true")
36 parser.add_argument("-m", "--mode", help="Tempest test mode [smoke, all]",
38 parser.add_argument("-r", "--report",
39 help="Create json result file",
42 args = parser.parse_args()
44 """ logging configuration """
45 logger = logging.getLogger('run_tempest')
46 logger.setLevel(logging.DEBUG)
48 ch = logging.StreamHandler()
50 ch.setLevel(logging.DEBUG)
52 ch.setLevel(logging.INFO)
54 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
55 ch.setFormatter(formatter)
58 REPO_PATH=os.environ['repos_dir']+'/functest/'
59 if not os.path.exists(REPO_PATH):
60 logger.error("Functest repository directory not found '%s'" % REPO_PATH)
62 sys.path.append(REPO_PATH + "testcases/")
65 with open("/home/opnfv/functest/conf/config_functest.yaml") as f:
66 functest_yaml = yaml.safe_load(f)
68 TEST_DB = functest_yaml.get("results").get("test_db_url")
71 TENANT_NAME = functest_yaml.get("tempest").get("identity").get("tenant_name")
72 TENANT_DESCRIPTION = functest_yaml.get("tempest").get("identity").get("tenant_description")
73 USER_NAME = functest_yaml.get("tempest").get("identity").get("user_name")
74 USER_PASSWORD = functest_yaml.get("tempest").get("identity").get("user_password")
75 DEPLOYMENT_MAME = functest_yaml.get("rally").get("deployment_name")
76 RALLY_INSTALLATION_DIR = functest_yaml.get("general").get("directories").get("dir_rally_inst")
77 RESULTS_DIR = functest_yaml.get("general").get("directories").get("dir_results")
78 TEMPEST_RESULTS_DIR = RESULTS_DIR + '/tempest'
81 def get_info(file_result):
86 p = subprocess.Popen('cat tempest.log',
87 shell=True, stdout=subprocess.PIPE,
88 stderr=subprocess.STDOUT)
89 for line in p.stdout.readlines():
91 if (len(test_run) < 1):
92 test_run = re.findall("[0-9]*\.[0-9]*s", line)
93 if (len(duration) < 1):
94 duration = re.findall("[0-9]*\ tests", line)
95 regexp = r"(failures=[0-9]+)"
96 if (len(test_failed) < 1):
97 test_failed = re.findall(regexp, line)
101 logger.debug("test_run:"+test_run)
102 logger.debug("duration:"+duration)
105 def push_results_to_db(payload, module, pod_name):
107 # TODO move DB creds into config file
108 url = TEST_DB + "/results"
109 installer = functest_utils.get_installer_type(logger)
110 scenario = functest_utils.get_scenario(logger)
111 logger.info("Pushing results to DB: '%s'." % url)
113 params = {"project_name": "functest", "case_name": "Tempest",
114 "pod_name": str(pod_name), 'installer': installer,
115 "version": scenario, 'details': payload}
116 headers = {'Content-Type': 'application/json'}
118 r = requests.post(url, data=json.dumps(params), headers=headers)
122 def create_tempest_resources():
123 ks_creds = functest_utils.get_credentials("keystone")
124 logger.info("Creating tenant and user for Tempest suite")
125 keystone = ksclient.Client(**ks_creds)
126 tenant_id = functest_utils.create_tenant(keystone, TENANT_NAME, TENANT_DESCRIPTION)
128 logger.error("Error : Failed to create %s tenant" %TENANT_NAME)
130 user_id = functest_utils.create_user(keystone, USER_NAME, USER_PASSWORD, None, tenant_id)
132 logger.error("Error : Failed to create %s user" %USER_NAME)
135 def free_tempest_resources():
136 ks_creds = functest_utils.get_credentials("keystone")
137 logger.info("Deleting tenant and user for Tempest suite)")
138 keystone = ksclient.Client(**ks_creds)
140 user_id = functest_utils.get_user_id(keystone, USER_NAME)
142 logger.error("Error : Failed to get id of %s user" % USER_NAME)
144 if not functest_utils.delete_user(keystone, user_id):
145 logger.error("Error : Failed to delete %s user" % USER_NAME)
147 tenant_id = functest_utils.get_tenant_id(keystone, TENANT_NAME)
149 logger.error("Error : Failed to get id of %s tenant" % TENANT_NAME)
151 if not functest_utils.delete_tenant(keystone, tenant_id):
152 logger.error("Error : Failed to delete %s tenant" % TENANT_NAME)
155 def configure_tempest():
157 Add/update needed parameters into tempest.conf file generated by Rally
160 logger.debug("Generating tempest.conf file...")
161 cmd = "rally verify genconfig"
162 functest_utils.execute_command(cmd,logger)
164 logger.debug("Resolving deployment UUID...")
165 cmd = "rally deployment list | awk '/"+DEPLOYMENT_MAME+"/ {print $2}'"
166 p = subprocess.Popen(cmd, shell=True,
167 stdout=subprocess.PIPE,
168 stderr=subprocess.STDOUT);
169 deployment_uuid = p.stdout.readline().rstrip()
170 if deployment_uuid == "":
171 logger.debug(" Rally deployment NOT found")
174 logger.debug("Finding tempest.conf file...")
175 tempest_conf_file = RALLY_INSTALLATION_DIR+"/tempest/for-deployment-" \
176 +deployment_uuid+"/tempest.conf"
177 if tempest_conf_file == "":
178 logger.debug(" Tempest configuration file NOT found")
181 logger.debug(" Updating fixed_network_name...")
182 private_net_name = ""
183 creds_neutron = functest_utils.get_credentials("neutron")
184 neutron_client = neutronclient.Client(**creds_neutron)
185 private_net = functest_utils.get_private_net(neutron_client)
186 if private_net is None:
187 logger.error("No shared private networks found.")
189 private_net_name = private_net['name']
190 cmd = "crudini --set "+tempest_conf_file+" compute fixed_network_name " \
192 functest_utils.execute_command(cmd,logger)
194 logger.debug(" Updating non-admin credentials...")
195 cmd = "crudini --set "+tempest_conf_file+" identity tenant_name " \
197 functest_utils.execute_command(cmd,logger)
198 cmd = "crudini --set "+tempest_conf_file+" identity username " \
200 functest_utils.execute_command(cmd,logger)
201 cmd = "crudini --set "+tempest_conf_file+" identity password " \
203 functest_utils.execute_command(cmd,logger)
208 def run_tempest(OPTION):
210 # the "main" function of the script which launches Rally to run Tempest
211 # :param option: tempest option (smoke, ..)
214 logger.info("Starting Tempest test suite: '%s'." % OPTION)
215 cmd_line = "rally verify start "+OPTION
216 logger.debug('Executing command : {}'.format(cmd_line))
218 CI_DEBUG = os.environ.get("CI_DEBUG")
219 if CI_DEBUG == "true" or CI_DEBUG == "True":
220 subprocess.call(cmd_line, shell=True, stderr=subprocess.STDOUT)
222 if not os.path.exists(TEMPEST_RESULTS_DIR):
223 os.makedirs(TEMPEST_RESULTS_DIR)
224 header = "Tempest environment:\n"\
225 " Installer: %s\n Scenario: %s\n Node: %s\n Date: %s\n" % \
226 (os.getenv('INSTALLER_TYPE','Unknown'), \
227 os.getenv('DEPLOY_SCENARIO','Unknown'), \
228 os.getenv('NODE_NAME','Unknown'), \
229 time.strftime("%a %b %d %H:%M:%S %Z %Y"))
231 f_stdout = open(TEMPEST_RESULTS_DIR+"/tempest.log", 'w+')
232 f_stderr = open(TEMPEST_RESULTS_DIR+"/tempest-error.log", 'w+')
233 f_env = open(TEMPEST_RESULTS_DIR+"/environment.log", 'w+')
236 subprocess.call(cmd_line, shell=True, stdout=f_stdout, stderr=f_stderr)
242 cmd_line = "rally verify show"
243 subprocess.call(cmd_line, shell=True)
245 cmd_line = "rally verify list"
246 logger.debug('Executing command : {}'.format(cmd_line))
247 cmd = os.popen(cmd_line)
248 output = (((cmd.read()).splitlines()[3]).replace(" ", "")).split("|")
250 # | UUID | Deployment UUID | smoke | tests | failures | Created at |
251 # Duration | Status |
252 num_tests = output[4]
253 num_failures = output[5]
254 time_start = output[6]
256 # Compute duration (lets assume it does not take more than 60 min)
257 dur_min=int(duration.split(':')[1])
258 dur_sec_float=float(duration.split(':')[2])
259 dur_sec_int=int(round(dur_sec_float,0))
260 dur_sec_int = dur_sec_int + 60 * dur_min
262 # Generate json results for DB
263 json_results = {"timestart": time_start, "duration": dur_sec_int,
264 "tests": int(num_tests), "failures": int(num_failures)}
265 logger.info("Results: "+str(json_results))
266 pod_name = functest_utils.get_pod_name(logger)
268 # Push results in payload of testcase
270 logger.debug("Push result into DB")
271 push_results_to_db(json_results, MODE, pod_name)
278 elif not (args.mode in modes):
279 logger.error("Tempest mode not valid. Possible values are:\n"
282 elif (args.mode == 'custom'):
283 MODE = "--tests-file "+REPO_PATH+"testcases/VIM/OpenStack/CI/custom_tests/test_list.txt"
285 MODE = "--set "+args.mode
287 create_tempest_resources()
290 free_tempest_resources()
293 if __name__ == '__main__':