Add kingbird endpoint information to functest.
[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(logger,
139                                                neutron_client,
140                                                PRIVATE_NET_NAME,
141                                                PRIVATE_SUBNET_NAME,
142                                                ROUTER_NAME,
143                                                PRIVATE_SUBNET_CIDR)
144     if network_dic:
145         if not os_utils.update_neutron_net(neutron_client,
146                                            network_dic['net_id'],
147                                            shared=True):
148             logger.error("Failed to update private network...")
149             exit(-1)
150         else:
151             logger.debug("Network '%s' is available..." % PRIVATE_NET_NAME)
152     else:
153         logger.error("Private network creation failed")
154         exit(-1)
155
156     logger.debug("Creating image for Tempest suite")
157     # Check if the given image exists
158     image_id = os_utils.get_image_id(glance_client, GLANCE_IMAGE_NAME)
159     if image_id != '':
160         logger.info("Using existing image '%s'..." % GLANCE_IMAGE_NAME)
161     else:
162         logger.info("Creating image '%s' from '%s'..." % (GLANCE_IMAGE_NAME,
163                                                           GLANCE_IMAGE_PATH))
164         image_id = os_utils.create_glance_image(glance_client,
165                                                 GLANCE_IMAGE_NAME,
166                                                 GLANCE_IMAGE_PATH)
167         if not image_id:
168             logger.error("Failed to create a Glance image...")
169             exit(-1)
170         logger.debug("Image '%s' with ID=%s created successfully."
171                      % (GLANCE_IMAGE_NAME, image_id))
172
173
174 def configure_tempest(deployment_dir):
175     """
176     Add/update needed parameters into tempest.conf file generated by Rally
177     """
178
179     logger.debug("Generating tempest.conf file...")
180     cmd = "rally verify genconfig"
181     ft_utils.execute_command(cmd, logger)
182
183     logger.debug("Finding tempest.conf file...")
184     tempest_conf_file = deployment_dir + "/tempest.conf"
185     if not os.path.isfile(tempest_conf_file):
186         logger.error("Tempest configuration file %s NOT found."
187                      % tempest_conf_file)
188         exit(-1)
189
190     logger.debug("Updating selected tempest.conf parameters...")
191     config = ConfigParser.RawConfigParser()
192     config.read(tempest_conf_file)
193     config.set('compute', 'fixed_network_name', PRIVATE_NET_NAME)
194     config.set('identity', 'tenant_name', TENANT_NAME)
195     config.set('identity', 'username', USER_NAME)
196     config.set('identity', 'password', USER_PASSWORD)
197     with open(tempest_conf_file, 'wb') as config_file:
198         config.write(config_file)
199
200     # Copy tempest.conf to /home/opnfv/functest/results/tempest/
201     shutil.copyfile(tempest_conf_file, TEMPEST_RESULTS_DIR + '/tempest.conf')
202     return True
203
204
205 def configure_tempest_feature(deployment_dir, mode):
206     """
207     Add/update needed parameters into tempest.conf file generated by Rally
208     """
209
210     logger.debug("Finding tempest.conf file...")
211     tempest_conf_file = deployment_dir + "/tempest.conf"
212     if not os.path.isfile(tempest_conf_file):
213         logger.error("Tempest configuration file %s NOT found."
214                      % tempest_conf_file)
215         exit(-1)
216
217     logger.debug("Updating selected tempest.conf parameters...")
218     config = ConfigParser.RawConfigParser()
219     config.read(tempest_conf_file)
220     if mode == 'feature_multisite':
221         config.set('service_available', 'kingbird', 'true')
222         cmd = "openstack endpoint show kingbird | grep publicurl |\
223                awk '{print $4}' | awk -F '/' '{print $3}'"
224         kingbird_api_version = os.popen(cmd).read()
225         if os.environ.get("INSTALLER_TYPE") == 'fuel':
226             # For MOS based setup, the service is accessible
227             # via bind host
228             kingbird_conf_path = "/etc/kingbird/kingbird.conf"
229             installer_type = os.getenv('INSTALLER_TYPE', 'Unknown')
230             installer_ip = os.getenv('INSTALLER_IP', 'Unknown')
231             installer_username = ft_utils.get_parameter_from_yaml(
232                 "multisite." + installer_type +
233                 "_environment.installer_username")
234             installer_password = ft_utils.get_parameter_from_yaml(
235                 "multisite." + installer_type +
236                 "_environment.installer_password")
237             multisite_controller_ip = ft_utils.get_parameter_from_yaml(
238                 "multisite." + installer_type +
239                 "_environment.multisite_controller_ip")
240
241             ssh_options = "-o UserKnownHostsFile=/dev/null -o \
242                 StrictHostKeyChecking=no"
243
244             # Get the controller IP from the fuel node
245             cmd = 'sshpass -p %s ssh 2>/dev/null %s %s@%s \
246                     \'fuel node --env 1| grep controller | grep "True\|  1" \
247                     | awk -F\| "{print \$5}"\'' % (installer_password,
248                                                    ssh_options,
249                                                    installer_username,
250                                                    installer_ip)
251             multisite_controller_ip = \
252                 "".join(os.popen(cmd).reawd().split())
253
254             # Login to controller and get bind host details
255             cmd = 'sshpass -p %s ssh 2>/dev/null  %s %s@%s "ssh %s \\" \
256                 grep -e "^bind_" %s  \\""' % (installer_password,
257                                               ssh_options,
258                                               installer_username,
259                                               installer_ip,
260                                               multisite_controller_ip,
261                                               kingbird_conf_path)
262             bind_details = os.popen(cmd).read()
263             bind_details = "".join(bind_details.split())
264             # Extract port number from the bind details
265             bind_port = re.findall(r"\D(\d{4})", bind_details)[0]
266             # Extract ip address from the bind details
267             bind_host = re.findall(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}",
268                                    bind_details)[0]
269             kingbird_endpoint_url = "http://" + bind_host + ":" + bind_port + \
270                                     "/"
271         else:
272             cmd = "openstack endpoint show kingbird | grep publicurl |\
273                    awk '{print $4}' | awk -F '/' '{print $3}'"
274             kingbird_endpoint_url = os.popen(cmd).read()
275
276         try:
277             config.add_section("kingbird")
278         except Exception:
279             logger.info('kingbird section exist')
280         config.set('kingbird', 'endpoint_type', 'publicURL')
281         config.set('kingbird', 'TIME_TO_SYNC', '20')
282         config.set('kingbird', 'endpoint_url', kingbird_endpoint_url)
283         config.set('kingbird', 'api_version', kingbird_api_version)
284     with open(tempest_conf_file, 'wb') as config_file:
285         config.write(config_file)
286
287     # Copy tempest.conf to /home/opnfv/functest/results/tempest/
288     shutil.copyfile(tempest_conf_file, TEMPEST_RESULTS_DIR + '/tempest.conf')
289     return True
290
291
292 def read_file(filename):
293     with open(filename) as src:
294         return [line.strip() for line in src.readlines()]
295
296
297 def generate_test_list(deployment_dir, mode):
298     logger.debug("Generating test case list...")
299     if mode == 'defcore':
300         shutil.copyfile(TEMPEST_DEFCORE, TEMPEST_RAW_LIST)
301     elif mode == 'custom':
302         if os.path.isfile(TEMPEST_CUSTOM):
303             shutil.copyfile(TEMPEST_CUSTOM, TEMPEST_RAW_LIST)
304         else:
305             logger.error("Tempest test list file %s NOT found."
306                          % TEMPEST_CUSTOM)
307             exit(-1)
308     else:
309         if mode == 'smoke':
310             testr_mode = "smoke"
311         elif mode == 'feature_multisite':
312             testr_mode = " | grep kingbird "
313         elif mode == 'full':
314             testr_mode = ""
315         else:
316             testr_mode = 'tempest.api.' + mode
317         cmd = ("cd " + deployment_dir + ";" + "testr list-tests " +
318                testr_mode + ">" + TEMPEST_RAW_LIST + ";cd")
319         ft_utils.execute_command(cmd, logger)
320
321
322 def apply_tempest_blacklist():
323     logger.debug("Applying tempest blacklist...")
324     cases_file = read_file(TEMPEST_RAW_LIST)
325     result_file = open(TEMPEST_LIST, 'w')
326     try:
327         black_file = read_file(TEMPEST_BLACKLIST)
328     except:
329         black_file = ''
330         logger.debug("Tempest blacklist file does not exist.")
331     for line in cases_file:
332         if line not in black_file:
333             result_file.write(str(line) + '\n')
334     result_file.close()
335
336
337 def run_tempest(OPTION):
338     #
339     # the "main" function of the script which launches Rally to run Tempest
340     # :param option: tempest option (smoke, ..)
341     # :return: void
342     #
343     logger.info("Starting Tempest test suite: '%s'." % OPTION)
344     start_time = time.time()
345     stop_time = start_time
346     cmd_line = "rally verify start " + OPTION + " --system-wide"
347
348     header = ("Tempest environment:\n"
349               "  Installer: %s\n  Scenario: %s\n  Node: %s\n  Date: %s\n" %
350               (os.getenv('INSTALLER_TYPE', 'Unknown'),
351                os.getenv('DEPLOY_SCENARIO', 'Unknown'),
352                os.getenv('NODE_NAME', 'Unknown'),
353                time.strftime("%a %b %d %H:%M:%S %Z %Y")))
354
355     f_stdout = open(TEMPEST_RESULTS_DIR + "/tempest.log", 'w+')
356     f_stderr = open(TEMPEST_RESULTS_DIR + "/tempest-error.log", 'w+')
357     f_env = open(TEMPEST_RESULTS_DIR + "/environment.log", 'w+')
358     f_env.write(header)
359
360     # subprocess.call(cmd_line, shell=True, stdout=f_stdout, stderr=f_stderr)
361     p = subprocess.Popen(
362         cmd_line, shell=True,
363         stdout=subprocess.PIPE,
364         stderr=f_stderr,
365         bufsize=1)
366
367     with p.stdout:
368         for line in iter(p.stdout.readline, b''):
369             if re.search("\} tempest\.", line):
370                 logger.info(line.replace('\n', ''))
371             f_stdout.write(line)
372     p.wait()
373
374     f_stdout.close()
375     f_stderr.close()
376     f_env.close()
377
378     cmd_line = "rally verify show"
379     output = ""
380     p = subprocess.Popen(
381         cmd_line, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
382     for line in p.stdout:
383         if re.search("Tests\:", line):
384             break
385         output += line
386     logger.info(output)
387
388     cmd_line = "rally verify list"
389     cmd = os.popen(cmd_line)
390     output = (((cmd.read()).splitlines()[-2]).replace(" ", "")).split("|")
391     # Format:
392     # | UUID | Deployment UUID | smoke | tests | failures | Created at |
393     # Duration | Status  |
394     num_tests = output[4]
395     num_failures = output[5]
396     time_start = output[6]
397     duration = output[7]
398     # Compute duration (lets assume it does not take more than 60 min)
399     dur_min = int(duration.split(':')[1])
400     dur_sec_float = float(duration.split(':')[2])
401     dur_sec_int = int(round(dur_sec_float, 0))
402     dur_sec_int = dur_sec_int + 60 * dur_min
403     stop_time = time.time()
404     # Push results in payload of testcase
405     if args.report:
406         logger.debug("Pushing tempest results into DB...")
407         # Note criteria hardcoded...TODO move to testcase.yaml
408         status = "FAIL"
409         try:
410             diff = (int(num_tests) - int(num_failures))
411             success_rate = 100 * diff / int(num_tests)
412         except:
413             success_rate = 0
414
415         # For Tempest we assume that the success rate is above 90%
416         if success_rate >= 90:
417             status = "PASS"
418
419         # add the test in error in the details sections
420         # should be possible to do it during the test
421         with open(TEMPEST_RESULTS_DIR + "/tempest.log", 'r') as myfile:
422             output = myfile.read()
423         error_logs = ""
424
425         for match in re.findall('(.*?)[. ]*FAILED', output):
426             error_logs += match
427
428         # Generate json results for DB
429         json_results = {"timestart": time_start, "duration": dur_sec_int,
430                         "tests": int(num_tests), "failures": int(num_failures),
431                         "errors": error_logs}
432         logger.info("Results: " + str(json_results))
433         # split Tempest smoke and full
434         if "smoke" in args.mode:
435             case_name = "tempest_smoke_serial"
436         else:
437             case_name = "tempest_full_parallel"
438
439         try:
440             ft_utils.push_results_to_db("functest",
441                                         case_name,
442                                         None,
443                                         start_time,
444                                         stop_time,
445                                         status,
446                                         json_results)
447         except:
448             logger.error("Error pushing results into Database '%s'"
449                          % sys.exc_info()[0])
450
451
452 def main():
453     global MODE
454
455     if not (args.mode in modes):
456         logger.error("Tempest mode not valid. "
457                      "Possible values are:\n" + str(modes))
458         exit(-1)
459
460     if not os.path.exists(TEMPEST_RESULTS_DIR):
461         os.makedirs(TEMPEST_RESULTS_DIR)
462
463     deployment_dir = ft_utils.get_deployment_dir(logger)
464     configure_tempest(deployment_dir)
465     configure_tempest_feature(deployment_dir, args.mode)
466     create_tempest_resources()
467     generate_test_list(deployment_dir, args.mode)
468     apply_tempest_blacklist()
469
470     MODE = "--tests-file " + TEMPEST_LIST
471     if args.serial:
472         MODE += " --concur 1"
473
474     run_tempest(MODE)
475
476
477 if __name__ == '__main__':
478     main()