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