Merge "Bugfix: fix the error of no sh file"
[functest.git] / functest / opnfv_tests / openstack / rally / rally.py
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2015 All rights reserved
4 # This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10
11 import json
12 import os
13 import re
14 import subprocess
15 import time
16
17 import iniparse
18 import yaml
19
20 from functest.core import testcase_base
21 from functest.utils.constants import CONST
22 import functest.utils.functest_logger as ft_logger
23 import functest.utils.functest_utils as ft_utils
24 import functest.utils.openstack_utils as os_utils
25
26 logger = ft_logger.Logger('Rally').getLogger()
27
28
29 class RallyBase(testcase_base.TestcaseBase):
30     TESTS = ['authenticate', 'glance', 'cinder', 'heat', 'keystone',
31              'neutron', 'nova', 'quotas', 'requests', 'vm', 'all']
32     GLANCE_IMAGE_NAME = CONST.openstack_image_name
33     GLANCE_IMAGE_FILENAME = CONST.openstack_image_file_name
34     GLANCE_IMAGE_PATH = os.path.join(CONST.dir_functest_data,
35                                      GLANCE_IMAGE_FILENAME)
36     GLANCE_IMAGE_FORMAT = CONST.openstack_image_disk_format
37     FLAVOR_NAME = "m1.tiny"
38
39     RALLY_DIR = os.path.join(CONST.dir_repo_functest, CONST.dir_rally)
40     RALLY_SCENARIO_DIR = os.path.join(RALLY_DIR, "scenario")
41     TEMPLATE_DIR = os.path.join(RALLY_SCENARIO_DIR, "templates")
42     SUPPORT_DIR = os.path.join(RALLY_SCENARIO_DIR, "support")
43     USERS_AMOUNT = 2
44     TENANTS_AMOUNT = 3
45     ITERATIONS_AMOUNT = 10
46     CONCURRENCY = 4
47     RESULTS_DIR = os.path.join(CONST.dir_results, 'rally')
48     TEMPEST_CONF_FILE = os.path.join(CONST.dir_results,
49                                      'tempest/tempest.conf')
50     BLACKLIST_FILE = os.path.join(RALLY_DIR, "blacklist.txt")
51     TEMP_DIR = os.path.join(RALLY_DIR, "var")
52
53     CINDER_VOLUME_TYPE_NAME = "volume_test"
54     RALLY_PRIVATE_NET_NAME = CONST.rally_network_name
55     RALLY_PRIVATE_SUBNET_NAME = CONST.rally_subnet_name
56     RALLY_PRIVATE_SUBNET_CIDR = CONST.rally_subnet_cidr
57     RALLY_ROUTER_NAME = CONST.rally_router_name
58
59     def __init__(self):
60         super(RallyBase, self).__init__()
61         self.mode = ''
62         self.summary = []
63         self.scenario_dir = ''
64         self.nova_client = os_utils.get_nova_client()
65         self.neutron_client = os_utils.get_neutron_client()
66         self.cinder_client = os_utils.get_cinder_client()
67         self.network_dict = {}
68         self.volume_type = None
69
70     def _build_task_args(self, test_file_name):
71         task_args = {'service_list': [test_file_name]}
72         task_args['image_name'] = self.GLANCE_IMAGE_NAME
73         task_args['flavor_name'] = self.FLAVOR_NAME
74         task_args['glance_image_location'] = self.GLANCE_IMAGE_PATH
75         task_args['glance_image_format'] = self.GLANCE_IMAGE_FORMAT
76         task_args['tmpl_dir'] = self.TEMPLATE_DIR
77         task_args['sup_dir'] = self.SUPPORT_DIR
78         task_args['users_amount'] = self.USERS_AMOUNT
79         task_args['tenants_amount'] = self.TENANTS_AMOUNT
80         task_args['use_existing_users'] = False
81         task_args['iterations'] = self.ITERATIONS_AMOUNT
82         task_args['concurrency'] = self.CONCURRENCY
83         task_args['smoke'] = self.smoke
84
85         ext_net = os_utils.get_external_net(self.neutron_client)
86         if ext_net:
87             task_args['floating_network'] = str(ext_net)
88         else:
89             task_args['floating_network'] = ''
90
91         net_id = self.network_dict['net_id']
92         if net_id:
93             task_args['netid'] = str(net_id)
94         else:
95             task_args['netid'] = ''
96
97         auth_url = CONST.OS_AUTH_URL
98         if auth_url is not None:
99             task_args['request_url'] = auth_url.rsplit(":", 1)[0]
100         else:
101             task_args['request_url'] = ''
102
103         return task_args
104
105     def _prepare_test_list(self, test_name):
106         test_yaml_file_name = 'opnfv-{}.yaml'.format(test_name)
107         scenario_file_name = os.path.join(self.RALLY_SCENARIO_DIR,
108                                           test_yaml_file_name)
109
110         if not os.path.exists(scenario_file_name):
111             scenario_file_name = os.path.join(self.scenario_dir,
112                                               test_yaml_file_name)
113
114             if not os.path.exists(scenario_file_name):
115                 raise Exception("The scenario '%s' does not exist."
116                                 % scenario_file_name)
117
118         logger.debug('Scenario fetched from : {}'.format(scenario_file_name))
119         test_file_name = os.path.join(self.TEMP_DIR, test_yaml_file_name)
120
121         if not os.path.exists(self.TEMP_DIR):
122             os.makedirs(self.TEMP_DIR)
123
124         self.apply_blacklist(scenario_file_name, test_file_name)
125         return test_file_name
126
127     @staticmethod
128     def get_task_id(cmd_raw):
129         """
130         get task id from command rally result
131         :param cmd_raw:
132         :return: task_id as string
133         """
134         taskid_re = re.compile('^Task +(.*): started$')
135         for line in cmd_raw.splitlines(True):
136             line = line.strip()
137             match = taskid_re.match(line)
138             if match:
139                 return match.group(1)
140         return None
141
142     @staticmethod
143     def task_succeed(json_raw):
144         """
145         Parse JSON from rally JSON results
146         :param json_raw:
147         :return: Bool
148         """
149         rally_report = json.loads(json_raw)
150         for report in rally_report:
151             if report is None or report.get('result') is None:
152                 return False
153
154             for result in report.get('result'):
155                 if result is None or len(result.get('error')) > 0:
156                     return False
157
158         return True
159
160     @staticmethod
161     def live_migration_supported():
162         config = iniparse.ConfigParser()
163         if (config.read(RallyBase.TEMPEST_CONF_FILE) and
164                 config.has_section('compute-feature-enabled') and
165                 config.has_option('compute-feature-enabled',
166                                   'live_migration')):
167             return config.getboolean('compute-feature-enabled',
168                                      'live_migration')
169
170         return False
171
172     @staticmethod
173     def get_cmd_output(proc):
174         result = ""
175         while proc.poll() is None:
176             line = proc.stdout.readline()
177             result += line
178         return result
179
180     @staticmethod
181     def excl_scenario():
182         black_tests = []
183         try:
184             with open(RallyBase.BLACKLIST_FILE, 'r') as black_list_file:
185                 black_list_yaml = yaml.safe_load(black_list_file)
186
187             installer_type = CONST.INSTALLER_TYPE
188             deploy_scenario = CONST.DEPLOY_SCENARIO
189             if (bool(installer_type) * bool(deploy_scenario)):
190                 if 'scenario' in black_list_yaml.keys():
191                     for item in black_list_yaml['scenario']:
192                         scenarios = item['scenarios']
193                         installers = item['installers']
194                         if (deploy_scenario in scenarios and
195                                 installer_type in installers):
196                             tests = item['tests']
197                             black_tests.extend(tests)
198         except Exception:
199             logger.debug("Scenario exclusion not applied.")
200
201         return black_tests
202
203     @staticmethod
204     def excl_func():
205         black_tests = []
206         func_list = []
207
208         try:
209             with open(RallyBase.BLACKLIST_FILE, 'r') as black_list_file:
210                 black_list_yaml = yaml.safe_load(black_list_file)
211
212             if not RallyBase.live_migration_supported():
213                 func_list.append("no_live_migration")
214
215             if 'functionality' in black_list_yaml.keys():
216                 for item in black_list_yaml['functionality']:
217                     functions = item['functions']
218                     for func in func_list:
219                         if func in functions:
220                             tests = item['tests']
221                             black_tests.extend(tests)
222         except Exception:
223             logger.debug("Functionality exclusion not applied.")
224
225         return black_tests
226
227     @staticmethod
228     def apply_blacklist(case_file_name, result_file_name):
229         logger.debug("Applying blacklist...")
230         cases_file = open(case_file_name, 'r')
231         result_file = open(result_file_name, 'w')
232
233         black_tests = list(set(RallyBase.excl_func() +
234                            RallyBase.excl_scenario()))
235
236         include = True
237         for cases_line in cases_file:
238             if include:
239                 for black_tests_line in black_tests:
240                     if re.search(black_tests_line,
241                                  cases_line.strip().rstrip(':')):
242                         include = False
243                         break
244                 else:
245                     result_file.write(str(cases_line))
246             else:
247                 if cases_line.isspace():
248                     include = True
249
250         cases_file.close()
251         result_file.close()
252
253     @staticmethod
254     def file_is_empty(file_name):
255         try:
256             if os.stat(file_name).st_size > 0:
257                 return False
258         except:
259             pass
260
261         return True
262
263     def _run_task(self, test_name):
264         logger.info('Starting test scenario "{}" ...'.format(test_name))
265
266         task_file = os.path.join(self.RALLY_DIR, 'task.yaml')
267         if not os.path.exists(task_file):
268             logger.error("Task file '%s' does not exist." % task_file)
269             raise Exception("Task file '%s' does not exist." % task_file)
270
271         file_name = self._prepare_test_list(test_name)
272         if self.file_is_empty(file_name):
273             logger.info('No tests for scenario "{}"'.format(test_name))
274             return
275
276         cmd_line = ("rally task start --abort-on-sla-failure "
277                     "--task {0} "
278                     "--task-args \"{1}\""
279                     .format(task_file, self._build_task_args(test_name)))
280         logger.debug('running command line: {}'.format(cmd_line))
281
282         p = subprocess.Popen(cmd_line, stdout=subprocess.PIPE,
283                              stderr=subprocess.STDOUT, shell=True)
284         output = self._get_output(p, test_name)
285         task_id = self.get_task_id(output)
286         logger.debug('task_id : {}'.format(task_id))
287
288         if task_id is None:
289             logger.error('Failed to retrieve task_id, validating task...')
290             cmd_line = ("rally task validate "
291                         "--task {0} "
292                         "--task-args \"{1}\""
293                         .format(task_file, self.__build_task_args(test_name)))
294             logger.debug('running command line: {}'.format(cmd_line))
295             p = subprocess.Popen(cmd_line, stdout=subprocess.PIPE,
296                                  stderr=subprocess.STDOUT, shell=True)
297             output = self.get_cmd_output(p)
298             logger.error("Task validation result:" + "\n" + output)
299             return
300
301         # check for result directory and create it otherwise
302         if not os.path.exists(self.RESULTS_DIR):
303             logger.debug('{} does not exist, we create it.'
304                          .format(self.RESULTS_DIR))
305             os.makedirs(self.RESULTS_DIR)
306
307         # write html report file
308         report_html_name = 'opnfv-{}.html'.format(test_name)
309         report_html_dir = os.path.join(self.RESULTS_DIR, report_html_name)
310         cmd_line = "rally task report {} --out {}".format(task_id,
311                                                           report_html_dir)
312
313         logger.debug('running command line: {}'.format(cmd_line))
314         os.popen(cmd_line)
315
316         # get and save rally operation JSON result
317         cmd_line = "rally task results %s" % task_id
318         logger.debug('running command line: {}'.format(cmd_line))
319         cmd = os.popen(cmd_line)
320         json_results = cmd.read()
321         report_json_name = 'opnfv-{}.json'.format(test_name)
322         report_json_dir = os.path.join(self.RESULTS_DIR, report_json_name)
323         with open(report_json_dir, 'w') as f:
324             logger.debug('saving json file')
325             f.write(json_results)
326
327         """ parse JSON operation result """
328         if self.task_succeed(json_results):
329             logger.info('Test scenario: "{}" OK.'.format(test_name) + "\n")
330         else:
331             logger.info('Test scenario: "{}" Failed.'.format(test_name) + "\n")
332
333     def _get_output(self, proc, test_name):
334         result = ""
335         nb_tests = 0
336         overall_duration = 0.0
337         success = 0.0
338         nb_totals = 0
339
340         while proc.poll() is None:
341             line = proc.stdout.readline()
342             if ("Load duration" in line or
343                     "started" in line or
344                     "finished" in line or
345                     " Preparing" in line or
346                     "+-" in line or
347                     "|" in line):
348                 result += line
349             elif "test scenario" in line:
350                 result += "\n" + line
351             elif "Full duration" in line:
352                 result += line + "\n\n"
353
354             # parse output for summary report
355             if ("| " in line and
356                     "| action" not in line and
357                     "| Starting" not in line and
358                     "| Completed" not in line and
359                     "| ITER" not in line and
360                     "|   " not in line and
361                     "| total" not in line):
362                 nb_tests += 1
363             elif "| total" in line:
364                 percentage = ((line.split('|')[8]).strip(' ')).strip('%')
365                 try:
366                     success += float(percentage)
367                 except ValueError:
368                     logger.info('Percentage error: %s, %s' %
369                                 (percentage, line))
370                 nb_totals += 1
371             elif "Full duration" in line:
372                 duration = line.split(': ')[1]
373                 try:
374                     overall_duration += float(duration)
375                 except ValueError:
376                     logger.info('Duration error: %s, %s' % (duration, line))
377
378         overall_duration = "{:10.2f}".format(overall_duration)
379         if nb_totals == 0:
380             success_avg = 0
381         else:
382             success_avg = "{:0.2f}".format(success / nb_totals)
383
384         scenario_summary = {'test_name': test_name,
385                             'overall_duration': overall_duration,
386                             'nb_tests': nb_tests,
387                             'success': success_avg}
388         self.summary.append(scenario_summary)
389
390         logger.debug("\n" + result)
391
392         return result
393
394     def _prepare_env(self):
395         logger.debug('Validating the test name...')
396         if not (self.test_name in self.TESTS):
397             raise Exception("Test name '%s' is invalid" % self.test_name)
398
399         volume_types = os_utils.list_volume_types(self.cinder_client,
400                                                   private=False)
401         if volume_types:
402             logger.debug("Using existing volume type(s)...")
403         else:
404             logger.debug('Creating volume type...')
405             self.volume_type = os_utils.create_volume_type(
406                 self.cinder_client, self.CINDER_VOLUME_TYPE_NAME)
407             if self.volume_type is None:
408                 raise Exception("Failed to create volume type '%s'" %
409                                 self.CINDER_VOLUME_TYPE_NAME)
410             logger.debug("Volume type '%s' is created succesfully." %
411                          self.CINDER_VOLUME_TYPE_NAME)
412
413         logger.debug('Getting or creating image...')
414         self.image_exists, self.image_id = os_utils.get_or_create_image(
415             self.GLANCE_IMAGE_NAME,
416             self.GLANCE_IMAGE_PATH,
417             self.GLANCE_IMAGE_FORMAT)
418         if self.image_id is None:
419             raise Exception("Failed to get or create image '%s'" %
420                             self.GLANCE_IMAGE_NAME)
421
422         logger.debug("Creating network '%s'..." % self.RALLY_PRIVATE_NET_NAME)
423         self.network_dict = os_utils.create_shared_network_full(
424             self.RALLY_PRIVATE_NET_NAME,
425             self.RALLY_PRIVATE_SUBNET_NAME,
426             self.RALLY_ROUTER_NAME,
427             self.RALLY_PRIVATE_SUBNET_CIDR)
428         if self.network_dict is None:
429             raise Exception("Failed to create shared network '%s'" %
430                             self.RALLY_PRIVATE_NET_NAME)
431
432     def _run_tests(self):
433         if self.test_name == 'all':
434             for test in self.TESTS:
435                 if (test == 'all' or test == 'vm'):
436                     continue
437                 self._run_task(test)
438         else:
439             self._run_task(self.test_name)
440
441     def _generate_report(self):
442         report = (
443             "\n"
444             "                                                              "
445             "\n"
446             "                     Rally Summary Report\n"
447             "\n"
448             "+===================+============+===============+===========+"
449             "\n"
450             "| Module            | Duration   | nb. Test Run  | Success   |"
451             "\n"
452             "+===================+============+===============+===========+"
453             "\n")
454         payload = []
455
456         # for each scenario we draw a row for the table
457         total_duration = 0.0
458         total_nb_tests = 0
459         total_success = 0.0
460         for s in self.summary:
461             name = "{0:<17}".format(s['test_name'])
462             duration = float(s['overall_duration'])
463             total_duration += duration
464             duration = time.strftime("%M:%S", time.gmtime(duration))
465             duration = "{0:<10}".format(duration)
466             nb_tests = "{0:<13}".format(s['nb_tests'])
467             total_nb_tests += int(s['nb_tests'])
468             success = "{0:<10}".format(str(s['success']) + '%')
469             total_success += float(s['success'])
470             report += ("" +
471                        "| " + name + " | " + duration + " | " +
472                        nb_tests + " | " + success + "|\n" +
473                        "+-------------------+------------"
474                        "+---------------+-----------+\n")
475             payload.append({'module': name,
476                             'details': {'duration': s['overall_duration'],
477                                         'nb tests': s['nb_tests'],
478                                         'success': s['success']}})
479
480         total_duration_str = time.strftime("%H:%M:%S",
481                                            time.gmtime(total_duration))
482         total_duration_str2 = "{0:<10}".format(total_duration_str)
483         total_nb_tests_str = "{0:<13}".format(total_nb_tests)
484
485         if len(self.summary):
486             success_rate = total_success / len(self.summary)
487         else:
488             success_rate = 100
489         success_rate = "{:0.2f}".format(success_rate)
490         success_rate_str = "{0:<10}".format(str(success_rate) + '%')
491         report += ("+===================+============"
492                    "+===============+===========+")
493         report += "\n"
494         report += ("| TOTAL:            | " + total_duration_str2 + " | " +
495                    total_nb_tests_str + " | " + success_rate_str + "|\n")
496         report += ("+===================+============"
497                    "+===============+===========+")
498         report += "\n"
499
500         logger.info("\n" + report)
501         payload.append({'summary': {'duration': total_duration,
502                                     'nb tests': total_nb_tests,
503                                     'nb success': success_rate}})
504
505         self.criteria = ft_utils.check_success_rate(
506             self.case_name, success_rate)
507         self.details = payload
508
509         logger.info("Rally '%s' success_rate is %s%%, is marked as %s"
510                     % (self.case_name, success_rate, self.criteria))
511
512     def _clean_up(self):
513         if self.volume_type:
514             logger.debug("Deleting volume type '%s'..." % self.volume_type)
515             os_utils.delete_volume_type(self.cinder_client, self.volume_type)
516
517         if not self.image_exists:
518             logger.debug("Deleting image '%s' with ID '%s'..."
519                          % (self.GLANCE_IMAGE_NAME, self.image_id))
520             if not os_utils.delete_glance_image(self.nova_client,
521                                                 self.image_id):
522                 logger.error("Error deleting the glance image")
523
524     def run(self):
525         self.start_time = time.time()
526         try:
527             self._prepare_env()
528             self._run_tests()
529             self._generate_report()
530             self._clean_up()
531         except Exception as e:
532             logger.error('Error with run: %s' % e)
533             return testcase_base.TestcaseBase.EX_RUN_ERROR
534         self.stop_time = time.time()
535
536         if self.criteria == "PASS":
537             return testcase_base.TestcaseBase.EX_OK
538         else:
539             return testcase_base.TestcaseBase.EX_TESTCASE_FAILED
540
541
542 class RallySanity(RallyBase):
543     def __init__(self):
544         super(RallySanity, self).__init__()
545         self.case_name = 'rally_sanity'
546         self.mode = 'sanity'
547         self.test_name = 'all'
548         self.smoke = True
549         self.scenario_dir = os.path.join(self.RALLY_SCENARIO_DIR, 'sanity')
550
551
552 class RallyFull(RallyBase):
553     def __init__(self):
554         super(RallyFull, self).__init__()
555         self.case_name = 'rally_full'
556         self.mode = 'full'
557         self.test_name = 'all'
558         self.smoke = False
559         self.scenario_dir = os.path.join(self.RALLY_SCENARIO_DIR, 'full')