Merge "[bugfix] issures in multisite testcase"
[functest.git] / testcases / OpenStack / tempest / run_tempest.py
1 #!/usr/bin/env python
2 #
3 # Description:
4 #    Runs tempest and pushes the results to the DB
5 #
6 # Authors:
7 #    morgan.richomme@orange.com
8 #    jose.lausuch@ericsson.com
9 #    viktor.tikkanen@nokia.com
10 #
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
15 #
16 import ConfigParser
17 import argparse
18 import os
19 import re
20 import shutil
21 import subprocess
22 import sys
23 import time
24
25 import functest.utils.functest_logger as ft_logger
26 import functest.utils.functest_utils as ft_utils
27 import functest.utils.openstack_utils as os_utils
28 import yaml
29
30 modes = ['full', 'smoke', 'baremetal', 'compute', 'data_processing',
31          'identity', 'image', 'network', 'object_storage', 'orchestration',
32          'telemetry', 'volume', 'custom', 'defcore', 'feature_multisite']
33
34 """ tests configuration """
35 parser = argparse.ArgumentParser()
36 parser.add_argument("-d", "--debug",
37                     help="Debug mode",
38                     action="store_true")
39 parser.add_argument("-s", "--serial",
40                     help="Run tests in one thread",
41                     action="store_true")
42 parser.add_argument("-m", "--mode",
43                     help="Tempest test mode [smoke, all]",
44                     default="smoke")
45 parser.add_argument("-r", "--report",
46                     help="Create json result file",
47                     action="store_true")
48 parser.add_argument("-n", "--noclean",
49                     help="Don't clean the created resources for this test.",
50                     action="store_true")
51
52 args = parser.parse_args()
53
54 """ logging configuration """
55 logger = ft_logger.Logger("run_tempest").getLogger()
56
57 REPO_PATH = os.environ['repos_dir'] + '/functest/'
58
59 with open(os.environ["CONFIG_FUNCTEST_YAML"]) as f:
60     functest_yaml = yaml.safe_load(f)
61 f.close()
62 TEST_DB = functest_yaml.get("results").get("test_db_url")
63
64 MODE = "smoke"
65 GLANCE_IMAGE_NAME = functest_yaml.get("general").get(
66     "openstack").get("image_name")
67 GLANCE_IMAGE_FILENAME = functest_yaml.get("general").get(
68     "openstack").get("image_file_name")
69 GLANCE_IMAGE_FORMAT = functest_yaml.get("general").get(
70     "openstack").get("image_disk_format")
71 GLANCE_IMAGE_PATH = functest_yaml.get("general").get("directories").get(
72     "dir_functest_data") + "/" + GLANCE_IMAGE_FILENAME
73 PRIVATE_NET_NAME = functest_yaml.get("tempest").get("private_net_name")
74 PRIVATE_SUBNET_NAME = functest_yaml.get("tempest").get("private_subnet_name")
75 PRIVATE_SUBNET_CIDR = functest_yaml.get("tempest").get("private_subnet_cidr")
76 ROUTER_NAME = functest_yaml.get("tempest").get("router_name")
77 TENANT_NAME = functest_yaml.get("tempest").get("identity").get("tenant_name")
78 TENANT_DESCRIPTION = functest_yaml.get("tempest").get("identity").get(
79     "tenant_description")
80 USER_NAME = functest_yaml.get("tempest").get("identity").get("user_name")
81 USER_PASSWORD = functest_yaml.get("tempest").get("identity").get(
82     "user_password")
83 DEPLOYMENT_MAME = functest_yaml.get("rally").get("deployment_name")
84 RALLY_INSTALLATION_DIR = functest_yaml.get("general").get("directories").get(
85     "dir_rally_inst")
86 RESULTS_DIR = functest_yaml.get("general").get("directories").get(
87     "dir_results")
88 TEMPEST_RESULTS_DIR = RESULTS_DIR + '/tempest'
89 TEST_LIST_DIR = functest_yaml.get("general").get("directories").get(
90     "dir_tempest_cases")
91 TEMPEST_CUSTOM = REPO_PATH + TEST_LIST_DIR + 'test_list.txt'
92 TEMPEST_BLACKLIST = REPO_PATH + TEST_LIST_DIR + 'blacklist.txt'
93 TEMPEST_DEFCORE = REPO_PATH + TEST_LIST_DIR + 'defcore_req.txt'
94 TEMPEST_RAW_LIST = TEMPEST_RESULTS_DIR + '/test_raw_list.txt'
95 TEMPEST_LIST = TEMPEST_RESULTS_DIR + '/test_list.txt'
96
97
98 def get_info(file_result):
99     test_run = ""
100     duration = ""
101     test_failed = ""
102
103     p = subprocess.Popen('cat tempest.log',
104                          shell=True, stdout=subprocess.PIPE,
105                          stderr=subprocess.STDOUT)
106     for line in p.stdout.readlines():
107         # print line,
108         if (len(test_run) < 1):
109             test_run = re.findall("[0-9]*\.[0-9]*s", line)
110         if (len(duration) < 1):
111             duration = re.findall("[0-9]*\ tests", line)
112         regexp = r"(failures=[0-9]+)"
113         if (len(test_failed) < 1):
114             test_failed = re.findall(regexp, line)
115
116     logger.debug("test_run:" + test_run)
117     logger.debug("duration:" + duration)
118
119
120 def create_tempest_resources():
121     keystone_client = os_utils.get_keystone_client()
122     neutron_client = os_utils.get_neutron_client()
123     glance_client = os_utils.get_glance_client()
124
125     logger.debug("Creating tenant and user for Tempest suite")
126     tenant_id = os_utils.create_tenant(keystone_client,
127                                        TENANT_NAME,
128                                        TENANT_DESCRIPTION)
129     if tenant_id == '':
130         logger.error("Error : Failed to create %s tenant" % TENANT_NAME)
131
132     user_id = os_utils.create_user(keystone_client, USER_NAME, USER_PASSWORD,
133                                    None, tenant_id)
134     if user_id == '':
135         logger.error("Error : Failed to create %s user" % USER_NAME)
136
137     logger.debug("Creating private network for Tempest suite")
138     network_dic = os_utils.create_network_full(neutron_client,
139                                                PRIVATE_NET_NAME,
140                                                PRIVATE_SUBNET_NAME,
141                                                ROUTER_NAME,
142                                                PRIVATE_SUBNET_CIDR)
143     if network_dic:
144         if not os_utils.update_neutron_net(neutron_client,
145                                            network_dic['net_id'],
146                                            shared=True):
147             logger.error("Failed to update private network...")
148             exit(-1)
149         else:
150             logger.debug("Network '%s' is available..." % PRIVATE_NET_NAME)
151     else:
152         logger.error("Private network creation failed")
153         exit(-1)
154
155     logger.debug("Creating image for Tempest suite")
156     # Check if the given image exists
157     image_id = os_utils.get_image_id(glance_client, GLANCE_IMAGE_NAME)
158     if image_id != '':
159         logger.info("Using existing image '%s'..." % GLANCE_IMAGE_NAME)
160     else:
161         logger.info("Creating image '%s' from '%s'..." % (GLANCE_IMAGE_NAME,
162                                                           GLANCE_IMAGE_PATH))
163         image_id = os_utils.create_glance_image(glance_client,
164                                                 GLANCE_IMAGE_NAME,
165                                                 GLANCE_IMAGE_PATH)
166         if not image_id:
167             logger.error("Failed to create a Glance image...")
168             exit(-1)
169         logger.debug("Image '%s' with ID=%s created successfully."
170                      % (GLANCE_IMAGE_NAME, image_id))
171
172
173 def configure_tempest(deployment_dir):
174     """
175     Add/update needed parameters into tempest.conf file generated by Rally
176     """
177
178     logger.debug("Generating tempest.conf file...")
179     cmd = "rally verify genconfig"
180     ft_utils.execute_command(cmd, logger)
181
182     logger.debug("Finding tempest.conf file...")
183     tempest_conf_file = deployment_dir + "/tempest.conf"
184     if not os.path.isfile(tempest_conf_file):
185         logger.error("Tempest configuration file %s NOT found."
186                      % tempest_conf_file)
187         exit(-1)
188
189     logger.debug("Updating selected tempest.conf parameters...")
190     config = ConfigParser.RawConfigParser()
191     config.read(tempest_conf_file)
192     config.set('compute', 'fixed_network_name', PRIVATE_NET_NAME)
193     config.set('identity', 'tenant_name', TENANT_NAME)
194     config.set('identity', 'username', USER_NAME)
195     config.set('identity', 'password', USER_PASSWORD)
196     with open(tempest_conf_file, 'wb') as config_file:
197         config.write(config_file)
198
199     # Copy tempest.conf to /home/opnfv/functest/results/tempest/
200     shutil.copyfile(tempest_conf_file, TEMPEST_RESULTS_DIR + '/tempest.conf')
201     return True
202
203
204 def configure_tempest_feature(deployment_dir, mode):
205     """
206     Add/update needed parameters into tempest.conf file generated by Rally
207     """
208
209     logger.debug("Finding tempest.conf file...")
210     tempest_conf_file = deployment_dir + "/tempest.conf"
211     if not os.path.isfile(tempest_conf_file):
212         logger.error("Tempest configuration file %s NOT found."
213                      % tempest_conf_file)
214         exit(-1)
215
216     logger.debug("Updating selected tempest.conf parameters...")
217     config = ConfigParser.RawConfigParser()
218     config.read(tempest_conf_file)
219     if mode == 'feature_multisite':
220         config.set('service_available', 'kingbird', 'true')
221         cmd = "openstack endpoint show kingbird | grep publicurl |\
222                awk '{print $4}' | awk -F '/' '{print $4}'"
223         kingbird_api_version = os.popen(cmd).read()
224         if os.environ.get("INSTALLER_TYPE") == 'fuel':
225             # For MOS based setup, the service is accessible
226             # via bind host
227             kingbird_conf_path = "/etc/kingbird/kingbird.conf"
228             installer_type = os.getenv('INSTALLER_TYPE', 'Unknown')
229             installer_ip = os.getenv('INSTALLER_IP', 'Unknown')
230             installer_username = ft_utils.get_parameter_from_yaml(
231                 "multisite." + installer_type +
232                 "_environment.installer_username")
233             installer_password = ft_utils.get_parameter_from_yaml(
234                 "multisite." + installer_type +
235                 "_environment.installer_password")
236
237             ssh_options = "-o UserKnownHostsFile=/dev/null -o \
238                 StrictHostKeyChecking=no"
239
240             # Get the controller IP from the fuel node
241             cmd = 'sshpass -p %s ssh 2>/dev/null %s %s@%s \
242                     \'fuel node --env 1| grep controller | grep "True\|  1" \
243                     | awk -F\| "{print \$5}"\'' % (installer_password,
244                                                    ssh_options,
245                                                    installer_username,
246                                                    installer_ip)
247             multisite_controller_ip = \
248                 "".join(os.popen(cmd).read().split())
249
250             # Login to controller and get bind host details
251             cmd = 'sshpass -p %s ssh 2>/dev/null  %s %s@%s "ssh %s \\" \
252                 grep -e "^bind_" %s  \\""' % (installer_password,
253                                               ssh_options,
254                                               installer_username,
255                                               installer_ip,
256                                               multisite_controller_ip,
257                                               kingbird_conf_path)
258             bind_details = os.popen(cmd).read()
259             bind_details = "".join(bind_details.split())
260             # Extract port number from the bind details
261             bind_port = re.findall(r"\D(\d{4})", bind_details)[0]
262             # Extract ip address from the bind details
263             bind_host = re.findall(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}",
264                                    bind_details)[0]
265             kingbird_endpoint_url = "http://" + bind_host + ":" + bind_port + \
266                                     "/"
267         else:
268             cmd = "openstack endpoint show kingbird | grep publicurl |\
269                    awk '{print $4}' | awk -F '/' '{print $3}'"
270             kingbird_endpoint_url = os.popen(cmd).read()
271
272         try:
273             config.add_section("kingbird")
274         except Exception:
275             logger.info('kingbird section exist')
276         config.set('kingbird', 'endpoint_type', 'publicURL')
277         config.set('kingbird', 'TIME_TO_SYNC', '20')
278         config.set('kingbird', 'endpoint_url', kingbird_endpoint_url)
279         config.set('kingbird', 'api_version', kingbird_api_version)
280     with open(tempest_conf_file, 'wb') as config_file:
281         config.write(config_file)
282
283     # Copy tempest.conf to /home/opnfv/functest/results/tempest/
284     shutil.copyfile(tempest_conf_file, TEMPEST_RESULTS_DIR + '/tempest.conf')
285     return True
286
287
288 def read_file(filename):
289     with open(filename) as src:
290         return [line.strip() for line in src.readlines()]
291
292
293 def generate_test_list(deployment_dir, mode):
294     logger.debug("Generating test case list...")
295     if mode == 'defcore':
296         shutil.copyfile(TEMPEST_DEFCORE, TEMPEST_RAW_LIST)
297     elif mode == 'custom':
298         if os.path.isfile(TEMPEST_CUSTOM):
299             shutil.copyfile(TEMPEST_CUSTOM, TEMPEST_RAW_LIST)
300         else:
301             logger.error("Tempest test list file %s NOT found."
302                          % TEMPEST_CUSTOM)
303             exit(-1)
304     else:
305         if mode == 'smoke':
306             testr_mode = "smoke"
307         elif mode == 'feature_multisite':
308             testr_mode = " | grep -i kingbird "
309         elif mode == 'full':
310             testr_mode = ""
311         else:
312             testr_mode = 'tempest.api.' + mode
313         cmd = ("cd " + deployment_dir + ";" + "testr list-tests " +
314                testr_mode + ">" + TEMPEST_RAW_LIST + ";cd")
315         ft_utils.execute_command(cmd, logger)
316
317
318 def apply_tempest_blacklist():
319     logger.debug("Applying tempest blacklist...")
320     cases_file = read_file(TEMPEST_RAW_LIST)
321     result_file = open(TEMPEST_LIST, 'w')
322     try:
323         black_file = read_file(TEMPEST_BLACKLIST)
324     except:
325         black_file = ''
326         logger.debug("Tempest blacklist file does not exist.")
327     for line in cases_file:
328         if line not in black_file:
329             result_file.write(str(line) + '\n')
330     result_file.close()
331
332
333 def run_tempest(OPTION):
334     #
335     # the "main" function of the script which launches Rally to run Tempest
336     # :param option: tempest option (smoke, ..)
337     # :return: void
338     #
339     logger.info("Starting Tempest test suite: '%s'." % OPTION)
340     start_time = time.time()
341     stop_time = start_time
342     cmd_line = "rally verify start " + OPTION + " --system-wide"
343
344     header = ("Tempest environment:\n"
345               "  Installer: %s\n  Scenario: %s\n  Node: %s\n  Date: %s\n" %
346               (os.getenv('INSTALLER_TYPE', 'Unknown'),
347                os.getenv('DEPLOY_SCENARIO', 'Unknown'),
348                os.getenv('NODE_NAME', 'Unknown'),
349                time.strftime("%a %b %d %H:%M:%S %Z %Y")))
350
351     f_stdout = open(TEMPEST_RESULTS_DIR + "/tempest.log", 'w+')
352     f_stderr = open(TEMPEST_RESULTS_DIR + "/tempest-error.log", 'w+')
353     f_env = open(TEMPEST_RESULTS_DIR + "/environment.log", 'w+')
354     f_env.write(header)
355
356     # subprocess.call(cmd_line, shell=True, stdout=f_stdout, stderr=f_stderr)
357     p = subprocess.Popen(
358         cmd_line, shell=True,
359         stdout=subprocess.PIPE,
360         stderr=f_stderr,
361         bufsize=1)
362
363     with p.stdout:
364         for line in iter(p.stdout.readline, b''):
365             if re.search("\} tempest\.", line):
366                 logger.info(line.replace('\n', ''))
367             f_stdout.write(line)
368     p.wait()
369
370     f_stdout.close()
371     f_stderr.close()
372     f_env.close()
373
374     cmd_line = "rally verify show"
375     output = ""
376     p = subprocess.Popen(
377         cmd_line, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
378     for line in p.stdout:
379         if re.search("Tests\:", line):
380             break
381         output += line
382     logger.info(output)
383
384     cmd_line = "rally verify list"
385     cmd = os.popen(cmd_line)
386     output = (((cmd.read()).splitlines()[-2]).replace(" ", "")).split("|")
387     # Format:
388     # | UUID | Deployment UUID | smoke | tests | failures | Created at |
389     # Duration | Status  |
390     num_tests = output[4]
391     num_failures = output[5]
392     time_start = output[6]
393     duration = output[7]
394     # Compute duration (lets assume it does not take more than 60 min)
395     dur_min = int(duration.split(':')[1])
396     dur_sec_float = float(duration.split(':')[2])
397     dur_sec_int = int(round(dur_sec_float, 0))
398     dur_sec_int = dur_sec_int + 60 * dur_min
399     stop_time = time.time()
400
401     status = "FAIL"
402     try:
403         diff = (int(num_tests) - int(num_failures))
404         success_rate = 100 * diff / int(num_tests)
405     except:
406         success_rate = 0
407
408     # For Tempest we assume that the success rate is above 90%
409     if "smoke" in args.mode:
410         case_name = "tempest_smoke_serial"
411         # Note criteria hardcoded...TODO read it from testcases.yaml
412         success_criteria = 100
413         if success_rate >= success_criteria:
414             status = "PASS"
415         else:
416             logger.info("Tempest success rate: %s%%. The success criteria to "
417                         "pass this test is %s%%. Marking the test as FAILED." %
418                         (success_rate, success_criteria))
419     else:
420         case_name = "tempest_full_parallel"
421         # Note criteria hardcoded...TODO read it from testcases.yaml
422         success_criteria = 80
423         if success_rate >= success_criteria:
424             status = "PASS"
425         else:
426             logger.info("Tempest success rate: %s%%. The success criteria to "
427                         "pass this test is %s%%. Marking the test as FAILED." %
428                         (success_rate, success_criteria))
429
430     # Push results in payload of testcase
431     if args.report:
432         # add the test in error in the details sections
433         # should be possible to do it during the test
434         logger.debug("Pushing tempest results into DB...")
435         with open(TEMPEST_RESULTS_DIR + "/tempest.log", 'r') as myfile:
436             output = myfile.read()
437         error_logs = ""
438
439         for match in re.findall('(.*?)[. ]*FAILED', output):
440             error_logs += match
441
442         # Generate json results for DB
443         json_results = {"timestart": time_start, "duration": dur_sec_int,
444                         "tests": int(num_tests), "failures": int(num_failures),
445                         "errors": error_logs}
446         logger.info("Results: " + str(json_results))
447         # split Tempest smoke and full
448
449         try:
450             ft_utils.push_results_to_db("functest",
451                                         case_name,
452                                         None,
453                                         start_time,
454                                         stop_time,
455                                         status,
456                                         json_results)
457         except:
458             logger.error("Error pushing results into Database '%s'"
459                          % sys.exc_info()[0])
460
461     if status == "PASS":
462         return 0
463     else:
464         return -1
465
466
467 def main():
468     global MODE
469
470     if not (args.mode in modes):
471         logger.error("Tempest mode not valid. "
472                      "Possible values are:\n" + str(modes))
473         exit(-1)
474
475     if not os.path.exists(TEMPEST_RESULTS_DIR):
476         os.makedirs(TEMPEST_RESULTS_DIR)
477
478     deployment_dir = ft_utils.get_deployment_dir(logger)
479     configure_tempest(deployment_dir)
480     configure_tempest_feature(deployment_dir, args.mode)
481     create_tempest_resources()
482     generate_test_list(deployment_dir, args.mode)
483     apply_tempest_blacklist()
484
485     MODE = "--tests-file " + TEMPEST_LIST
486     if args.serial:
487         MODE += " --concur 1"
488
489     ret_val = run_tempest(MODE)
490     if ret_val != 0:
491         sys.exit(-1)
492
493     sys.exit(0)
494
495
496 if __name__ == '__main__':
497     main()