Fix the proper version output for kingbird.
[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             multisite_controller_ip = ft_utils.get_parameter_from_yaml(
237                 "multisite." + installer_type +
238                 "_environment.multisite_controller_ip")
239
240             ssh_options = "-o UserKnownHostsFile=/dev/null -o \
241                 StrictHostKeyChecking=no"
242
243             # Get the controller IP from the fuel node
244             cmd = 'sshpass -p %s ssh 2>/dev/null %s %s@%s \
245                     \'fuel node --env 1| grep controller | grep "True\|  1" \
246                     | awk -F\| "{print \$5}"\'' % (installer_password,
247                                                    ssh_options,
248                                                    installer_username,
249                                                    installer_ip)
250             multisite_controller_ip = \
251                 "".join(os.popen(cmd).reawd().split())
252
253             # Login to controller and get bind host details
254             cmd = 'sshpass -p %s ssh 2>/dev/null  %s %s@%s "ssh %s \\" \
255                 grep -e "^bind_" %s  \\""' % (installer_password,
256                                               ssh_options,
257                                               installer_username,
258                                               installer_ip,
259                                               multisite_controller_ip,
260                                               kingbird_conf_path)
261             bind_details = os.popen(cmd).read()
262             bind_details = "".join(bind_details.split())
263             # Extract port number from the bind details
264             bind_port = re.findall(r"\D(\d{4})", bind_details)[0]
265             # Extract ip address from the bind details
266             bind_host = re.findall(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}",
267                                    bind_details)[0]
268             kingbird_endpoint_url = "http://" + bind_host + ":" + bind_port + \
269                                     "/"
270         else:
271             cmd = "openstack endpoint show kingbird | grep publicurl |\
272                    awk '{print $4}' | awk -F '/' '{print $3}'"
273             kingbird_endpoint_url = os.popen(cmd).read()
274
275         try:
276             config.add_section("kingbird")
277         except Exception:
278             logger.info('kingbird section exist')
279         config.set('kingbird', 'endpoint_type', 'publicURL')
280         config.set('kingbird', 'TIME_TO_SYNC', '20')
281         config.set('kingbird', 'endpoint_url', kingbird_endpoint_url)
282         config.set('kingbird', 'api_version', kingbird_api_version)
283     with open(tempest_conf_file, 'wb') as config_file:
284         config.write(config_file)
285
286     # Copy tempest.conf to /home/opnfv/functest/results/tempest/
287     shutil.copyfile(tempest_conf_file, TEMPEST_RESULTS_DIR + '/tempest.conf')
288     return True
289
290
291 def read_file(filename):
292     with open(filename) as src:
293         return [line.strip() for line in src.readlines()]
294
295
296 def generate_test_list(deployment_dir, mode):
297     logger.debug("Generating test case list...")
298     if mode == 'defcore':
299         shutil.copyfile(TEMPEST_DEFCORE, TEMPEST_RAW_LIST)
300     elif mode == 'custom':
301         if os.path.isfile(TEMPEST_CUSTOM):
302             shutil.copyfile(TEMPEST_CUSTOM, TEMPEST_RAW_LIST)
303         else:
304             logger.error("Tempest test list file %s NOT found."
305                          % TEMPEST_CUSTOM)
306             exit(-1)
307     else:
308         if mode == 'smoke':
309             testr_mode = "smoke"
310         elif mode == 'feature_multisite':
311             testr_mode = " | grep kingbird "
312         elif mode == 'full':
313             testr_mode = ""
314         else:
315             testr_mode = 'tempest.api.' + mode
316         cmd = ("cd " + deployment_dir + ";" + "testr list-tests " +
317                testr_mode + ">" + TEMPEST_RAW_LIST + ";cd")
318         ft_utils.execute_command(cmd, logger)
319
320
321 def apply_tempest_blacklist():
322     logger.debug("Applying tempest blacklist...")
323     cases_file = read_file(TEMPEST_RAW_LIST)
324     result_file = open(TEMPEST_LIST, 'w')
325     try:
326         black_file = read_file(TEMPEST_BLACKLIST)
327     except:
328         black_file = ''
329         logger.debug("Tempest blacklist file does not exist.")
330     for line in cases_file:
331         if line not in black_file:
332             result_file.write(str(line) + '\n')
333     result_file.close()
334
335
336 def run_tempest(OPTION):
337     #
338     # the "main" function of the script which launches Rally to run Tempest
339     # :param option: tempest option (smoke, ..)
340     # :return: void
341     #
342     logger.info("Starting Tempest test suite: '%s'." % OPTION)
343     start_time = time.time()
344     stop_time = start_time
345     cmd_line = "rally verify start " + OPTION + " --system-wide"
346
347     header = ("Tempest environment:\n"
348               "  Installer: %s\n  Scenario: %s\n  Node: %s\n  Date: %s\n" %
349               (os.getenv('INSTALLER_TYPE', 'Unknown'),
350                os.getenv('DEPLOY_SCENARIO', 'Unknown'),
351                os.getenv('NODE_NAME', 'Unknown'),
352                time.strftime("%a %b %d %H:%M:%S %Z %Y")))
353
354     f_stdout = open(TEMPEST_RESULTS_DIR + "/tempest.log", 'w+')
355     f_stderr = open(TEMPEST_RESULTS_DIR + "/tempest-error.log", 'w+')
356     f_env = open(TEMPEST_RESULTS_DIR + "/environment.log", 'w+')
357     f_env.write(header)
358
359     # subprocess.call(cmd_line, shell=True, stdout=f_stdout, stderr=f_stderr)
360     p = subprocess.Popen(
361         cmd_line, shell=True,
362         stdout=subprocess.PIPE,
363         stderr=f_stderr,
364         bufsize=1)
365
366     with p.stdout:
367         for line in iter(p.stdout.readline, b''):
368             if re.search("\} tempest\.", line):
369                 logger.info(line.replace('\n', ''))
370             f_stdout.write(line)
371     p.wait()
372
373     f_stdout.close()
374     f_stderr.close()
375     f_env.close()
376
377     cmd_line = "rally verify show"
378     output = ""
379     p = subprocess.Popen(
380         cmd_line, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
381     for line in p.stdout:
382         if re.search("Tests\:", line):
383             break
384         output += line
385     logger.info(output)
386
387     cmd_line = "rally verify list"
388     cmd = os.popen(cmd_line)
389     output = (((cmd.read()).splitlines()[-2]).replace(" ", "")).split("|")
390     # Format:
391     # | UUID | Deployment UUID | smoke | tests | failures | Created at |
392     # Duration | Status  |
393     num_tests = output[4]
394     num_failures = output[5]
395     time_start = output[6]
396     duration = output[7]
397     # Compute duration (lets assume it does not take more than 60 min)
398     dur_min = int(duration.split(':')[1])
399     dur_sec_float = float(duration.split(':')[2])
400     dur_sec_int = int(round(dur_sec_float, 0))
401     dur_sec_int = dur_sec_int + 60 * dur_min
402     stop_time = time.time()
403
404     status = "FAIL"
405     try:
406         diff = (int(num_tests) - int(num_failures))
407         success_rate = 100 * diff / int(num_tests)
408     except:
409         success_rate = 0
410
411     # For Tempest we assume that the success rate is above 90%
412     if "smoke" in args.mode:
413         case_name = "tempest_smoke_serial"
414         # Note criteria hardcoded...TODO read it from testcases.yaml
415         success_criteria = 100
416         if success_rate >= success_criteria:
417             status = "PASS"
418         else:
419             logger.info("Tempest success rate: %s%%. The success criteria to "
420                         "pass this test is %s%%. Marking the test as FAILED." %
421                         (success_rate, success_criteria))
422     else:
423         case_name = "tempest_full_parallel"
424         # Note criteria hardcoded...TODO read it from testcases.yaml
425         success_criteria = 80
426         if success_rate >= success_criteria:
427             status = "PASS"
428         else:
429             logger.info("Tempest success rate: %s%%. The success criteria to "
430                         "pass this test is %s%%. Marking the test as FAILED." %
431                         (success_rate, success_criteria))
432
433     # Push results in payload of testcase
434     if args.report:
435         # add the test in error in the details sections
436         # should be possible to do it during the test
437         logger.debug("Pushing tempest results into DB...")
438         with open(TEMPEST_RESULTS_DIR + "/tempest.log", 'r') as myfile:
439             output = myfile.read()
440         error_logs = ""
441
442         for match in re.findall('(.*?)[. ]*FAILED', output):
443             error_logs += match
444
445         # Generate json results for DB
446         json_results = {"timestart": time_start, "duration": dur_sec_int,
447                         "tests": int(num_tests), "failures": int(num_failures),
448                         "errors": error_logs}
449         logger.info("Results: " + str(json_results))
450         # split Tempest smoke and full
451
452         try:
453             ft_utils.push_results_to_db("functest",
454                                         case_name,
455                                         None,
456                                         start_time,
457                                         stop_time,
458                                         status,
459                                         json_results)
460         except:
461             logger.error("Error pushing results into Database '%s'"
462                          % sys.exc_info()[0])
463
464     if status == "PASS":
465         return 0
466     else:
467         return -1
468
469
470 def main():
471     global MODE
472
473     if not (args.mode in modes):
474         logger.error("Tempest mode not valid. "
475                      "Possible values are:\n" + str(modes))
476         exit(-1)
477
478     if not os.path.exists(TEMPEST_RESULTS_DIR):
479         os.makedirs(TEMPEST_RESULTS_DIR)
480
481     deployment_dir = ft_utils.get_deployment_dir(logger)
482     configure_tempest(deployment_dir)
483     configure_tempest_feature(deployment_dir, args.mode)
484     create_tempest_resources()
485     generate_test_list(deployment_dir, args.mode)
486     apply_tempest_blacklist()
487
488     MODE = "--tests-file " + TEMPEST_LIST
489     if args.serial:
490         MODE += " --concur 1"
491
492     ret_val = run_tempest(MODE)
493     if ret_val != 0:
494         sys.exit(-1)
495
496     sys.exit(0)
497
498
499 if __name__ == '__main__':
500     main()