Merge "Publish rally logs to ease debugging."
[functest.git] / functest / opnfv_tests / openstack / rally / rally.py
1 #!/usr/bin/env 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 """Rally testcases implementation."""
12
13 from __future__ import division
14
15 import json
16 import logging
17 import os
18 import re
19 import subprocess
20 import time
21
22 import pkg_resources
23 import prettytable
24 from xtesting.core import testcase
25 from xtesting.energy import energy
26 import yaml
27
28 from functest.core import singlevm
29 from functest.opnfv_tests.openstack.tempest import conf_utils
30 from functest.utils import config
31 from functest.utils import env
32
33 LOGGER = logging.getLogger(__name__)
34
35
36 class RallyBase(singlevm.VmReady1):
37     """Base class form Rally testcases implementation."""
38
39     # pylint: disable=too-many-instance-attributes
40     TESTS = ['authenticate', 'glance', 'cinder', 'gnocchi', 'heat',
41              'keystone', 'neutron', 'nova', 'quotas', 'vm', 'all']
42
43     RALLY_DIR = pkg_resources.resource_filename(
44         'functest', 'opnfv_tests/openstack/rally')
45     RALLY_SCENARIO_DIR = pkg_resources.resource_filename(
46         'functest', 'opnfv_tests/openstack/rally/scenario')
47     TEMPLATE_DIR = pkg_resources.resource_filename(
48         'functest', 'opnfv_tests/openstack/rally/scenario/templates')
49     SUPPORT_DIR = pkg_resources.resource_filename(
50         'functest', 'opnfv_tests/openstack/rally/scenario/support')
51     USERS_AMOUNT = 2
52     TENANTS_AMOUNT = 3
53     ITERATIONS_AMOUNT = 10
54     CONCURRENCY = 4
55     RESULTS_DIR = os.path.join(getattr(config.CONF, 'dir_results'), 'rally')
56     BLACKLIST_FILE = os.path.join(RALLY_DIR, "blacklist.txt")
57     TEMP_DIR = os.path.join(RALLY_DIR, "var")
58
59     visibility = 'public'
60     shared_network = True
61
62     def __init__(self, **kwargs):
63         """Initialize RallyBase object."""
64         super(RallyBase, self).__init__(**kwargs)
65         self.creators = []
66         self.mode = ''
67         self.summary = []
68         self.scenario_dir = ''
69         self.smoke = None
70         self.test_name = None
71         self.start_time = None
72         self.result = None
73         self.details = None
74         self.compute_cnt = 0
75         self.flavor_alt = None
76
77     def _build_task_args(self, test_file_name):
78         """Build arguments for the Rally task."""
79         task_args = {'service_list': [test_file_name]}
80         task_args['image_name'] = str(self.image.name)
81         task_args['flavor_name'] = str(self.flavor.name)
82         task_args['flavor_alt_name'] = str(self.flavor_alt.name)
83         task_args['glance_image_location'] = str(self.filename)
84         task_args['glance_image_format'] = str(self.image_format)
85         task_args['tmpl_dir'] = str(self.TEMPLATE_DIR)
86         task_args['sup_dir'] = str(self.SUPPORT_DIR)
87         task_args['users_amount'] = self.USERS_AMOUNT
88         task_args['tenants_amount'] = self.TENANTS_AMOUNT
89         task_args['use_existing_users'] = False
90         task_args['iterations'] = self.ITERATIONS_AMOUNT
91         task_args['concurrency'] = self.CONCURRENCY
92         task_args['smoke'] = self.smoke
93
94         if self.ext_net:
95             task_args['floating_network'] = str(self.ext_net.name)
96         else:
97             task_args['floating_network'] = ''
98
99         if self.network:
100             task_args['netid'] = str(self.network.id)
101         else:
102             task_args['netid'] = ''
103
104         return task_args
105
106     def _prepare_test_list(self, test_name):
107         """Build the list of test cases to be executed."""
108         test_yaml_file_name = 'opnfv-{}.yaml'.format(test_name)
109         scenario_file_name = os.path.join(self.RALLY_SCENARIO_DIR,
110                                           test_yaml_file_name)
111
112         if not os.path.exists(scenario_file_name):
113             scenario_file_name = os.path.join(self.scenario_dir,
114                                               test_yaml_file_name)
115
116             if not os.path.exists(scenario_file_name):
117                 raise Exception("The scenario '%s' does not exist."
118                                 % scenario_file_name)
119
120         LOGGER.debug('Scenario fetched from : %s', scenario_file_name)
121         test_file_name = os.path.join(self.TEMP_DIR, test_yaml_file_name)
122
123         if not os.path.exists(self.TEMP_DIR):
124             os.makedirs(self.TEMP_DIR)
125
126         self._apply_blacklist(scenario_file_name, test_file_name)
127         return test_file_name
128
129     @staticmethod
130     def get_task_id(cmd_raw):
131         """
132         Get task id from command rally result.
133
134         :param cmd_raw:
135         :return: task_id as string
136         """
137         taskid_re = re.compile('^Task +(.*): started$')
138         for line in cmd_raw.splitlines(True):
139             line = line.strip()
140             match = taskid_re.match(line)
141             if match:
142                 return match.group(1)
143         return None
144
145     @staticmethod
146     def task_succeed(json_raw):
147         """
148         Parse JSON from rally JSON results.
149
150         :param json_raw:
151         :return: Bool
152         """
153         rally_report = json.loads(json_raw)
154         tasks = rally_report.get('tasks')
155         if tasks:
156             for task in tasks:
157                 if task.get('status') != 'finished' or \
158                    task.get('pass_sla') is not True:
159                     return False
160         else:
161             return False
162         return True
163
164     def _migration_supported(self):
165         """Determine if migration is supported."""
166         if self.compute_cnt > 1:
167             return True
168
169         return False
170
171     @staticmethod
172     def excl_scenario():
173         """Exclude scenario."""
174         black_tests = []
175         try:
176             with open(RallyBase.BLACKLIST_FILE, 'r') as black_list_file:
177                 black_list_yaml = yaml.safe_load(black_list_file)
178
179             installer_type = env.get('INSTALLER_TYPE')
180             deploy_scenario = env.get('DEPLOY_SCENARIO')
181             if (bool(installer_type) and bool(deploy_scenario) and
182                     'scenario' in black_list_yaml.keys()):
183                 for item in black_list_yaml['scenario']:
184                     scenarios = item['scenarios']
185                     installers = item['installers']
186                     in_it = RallyBase.in_iterable_re
187                     if (in_it(deploy_scenario, scenarios) and
188                             in_it(installer_type, installers)):
189                         tests = item['tests']
190                         black_tests.extend(tests)
191         except Exception:  # pylint: disable=broad-except
192             LOGGER.debug("Scenario exclusion not applied.")
193
194         return black_tests
195
196     @staticmethod
197     def in_iterable_re(needle, haystack):
198         """
199         Check if given needle is in the iterable haystack, using regex.
200
201         :param needle: string to be matched
202         :param haystack: iterable of strings (optionally regex patterns)
203         :return: True if needle is eqial to any of the elements in haystack,
204                  or if a nonempty regex pattern in haystack is found in needle.
205         """
206         # match without regex
207         if needle in haystack:
208             return True
209
210         for pattern in haystack:
211             # match if regex pattern is set and found in the needle
212             if pattern and re.search(pattern, needle) is not None:
213                 return True
214
215         return False
216
217     def excl_func(self):
218         """Exclude functionalities."""
219         black_tests = []
220         func_list = []
221
222         try:
223             with open(RallyBase.BLACKLIST_FILE, 'r') as black_list_file:
224                 black_list_yaml = yaml.safe_load(black_list_file)
225
226             if not self._migration_supported():
227                 func_list.append("no_migration")
228
229             if 'functionality' in black_list_yaml.keys():
230                 for item in black_list_yaml['functionality']:
231                     functions = item['functions']
232                     for func in func_list:
233                         if func in functions:
234                             tests = item['tests']
235                             black_tests.extend(tests)
236         except Exception:  # pylint: disable=broad-except
237             LOGGER.debug("Functionality exclusion not applied.")
238
239         return black_tests
240
241     def _apply_blacklist(self, case_file_name, result_file_name):
242         """Apply blacklist."""
243         LOGGER.debug("Applying blacklist...")
244         cases_file = open(case_file_name, 'r')
245         result_file = open(result_file_name, 'w')
246
247         black_tests = list(set(self.excl_func() +
248                                self.excl_scenario()))
249
250         if black_tests:
251             LOGGER.debug("Blacklisted tests: %s", str(black_tests))
252
253         include = True
254         for cases_line in cases_file:
255             if include:
256                 for black_tests_line in black_tests:
257                     if re.search(black_tests_line,
258                                  cases_line.strip().rstrip(':')):
259                         include = False
260                         break
261                 else:
262                     result_file.write(str(cases_line))
263             else:
264                 if cases_line.isspace():
265                     include = True
266
267         cases_file.close()
268         result_file.close()
269
270     @staticmethod
271     def file_is_empty(file_name):
272         """Determine is a file is empty."""
273         try:
274             if os.stat(file_name).st_size > 0:
275                 return False
276         except Exception:  # pylint: disable=broad-except
277             pass
278
279         return True
280
281     def _save_results(self, test_name, task_id):
282         """ Generate and save task execution results"""
283         # check for result directory and create it otherwise
284         if not os.path.exists(self.RESULTS_DIR):
285             LOGGER.debug('%s does not exist, we create it.',
286                          self.RESULTS_DIR)
287             os.makedirs(self.RESULTS_DIR)
288
289         # put detailed result to log
290         cmd = (["rally", "task", "detailed", "--uuid", task_id])
291         LOGGER.debug('running command: %s', cmd)
292         output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
293         LOGGER.info("%s\n%s", " ".join(cmd), output)
294
295         # save report as JSON
296         report_json_name = 'opnfv-{}.json'.format(test_name)
297         report_json_dir = os.path.join(self.RESULTS_DIR, report_json_name)
298         cmd = (["rally", "task", "report", "--json", "--uuid", task_id,
299                 "--out", report_json_dir])
300         LOGGER.debug('running command: %s', cmd)
301         output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
302         LOGGER.info("%s\n%s", " ".join(cmd), output)
303
304         # save report as HTML
305         report_html_name = 'opnfv-{}.html'.format(test_name)
306         report_html_dir = os.path.join(self.RESULTS_DIR, report_html_name)
307         cmd = (["rally", "task", "report", "--html", "--uuid", task_id,
308                 "--out", report_html_dir])
309         LOGGER.debug('running command: %s', cmd)
310         output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
311         LOGGER.info("%s\n%s", " ".join(cmd), output)
312
313         json_results = open(report_json_dir).read()
314         self._append_summary(json_results, test_name)
315
316         # parse JSON operation result
317         if self.task_succeed(json_results):
318             LOGGER.info('Test scenario: "%s" OK.', test_name)
319         else:
320             LOGGER.info('Test scenario: "%s" Failed.', test_name)
321
322     def _run_task(self, test_name):
323         """Run a task."""
324         LOGGER.info('Starting test scenario "%s" ...', test_name)
325
326         task_file = os.path.join(self.RALLY_DIR, 'task.yaml')
327         if not os.path.exists(task_file):
328             LOGGER.error("Task file '%s' does not exist.", task_file)
329             raise Exception("Task file '{}' does not exist.".format(task_file))
330
331         file_name = self._prepare_test_list(test_name)
332         if self.file_is_empty(file_name):
333             LOGGER.info('No tests for scenario "%s"', test_name)
334             return
335
336         cmd = (["rally", "task", "start", "--abort-on-sla-failure", "--task",
337                 task_file, "--task-args",
338                 str(self._build_task_args(test_name))])
339         LOGGER.debug('running command: %s', cmd)
340         proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
341                                 stderr=subprocess.STDOUT)
342         output = proc.communicate()[0]
343
344         task_id = self.get_task_id(output)
345         LOGGER.debug('task_id : %s', task_id)
346         if task_id is None:
347             LOGGER.error("Failed to retrieve task_id")
348             LOGGER.error("Result:\n%s", output)
349             raise Exception("Failed to retrieve task id")
350
351         self._save_results(test_name, task_id)
352
353     def _append_summary(self, json_raw, test_name):
354         """Update statistics summary info."""
355         nb_tests = 0
356         nb_success = 0
357         overall_duration = 0.0
358
359         rally_report = json.loads(json_raw)
360         for task in rally_report.get('tasks'):
361             for subtask in task.get('subtasks'):
362                 for workload in subtask.get('workloads'):
363                     if workload.get('full_duration'):
364                         overall_duration += workload.get('full_duration')
365
366                     if workload.get('data'):
367                         nb_tests += len(workload.get('data'))
368
369                     for result in workload.get('data'):
370                         if not result.get('error'):
371                             nb_success += 1
372
373         scenario_summary = {'test_name': test_name,
374                             'overall_duration': overall_duration,
375                             'nb_tests': nb_tests,
376                             'nb_success': nb_success,
377                             'task_status': self.task_succeed(json_raw)}
378         self.summary.append(scenario_summary)
379
380     def _prepare_env(self):
381         """Create resources needed by test scenarios."""
382         assert self.cloud
383         LOGGER.debug('Validating the test name...')
384         if self.test_name not in self.TESTS:
385             raise Exception("Test name '%s' is invalid" % self.test_name)
386
387         self.compute_cnt = len(self.cloud.list_hypervisors())
388         self.flavor_alt = self.create_flavor_alt()
389         LOGGER.debug("flavor: %s", self.flavor_alt)
390
391     def _run_tests(self):
392         """Execute tests."""
393         if self.test_name == 'all':
394             for test in self.TESTS:
395                 if test == 'all' or test == 'vm':
396                     continue
397                 self._run_task(test)
398         else:
399             self._run_task(self.test_name)
400
401     def _generate_report(self):
402         """Generate test execution summary report."""
403         total_duration = 0.0
404         total_nb_tests = 0
405         total_nb_success = 0
406         nb_modules = 0
407         payload = []
408
409         res_table = prettytable.PrettyTable(
410             padding_width=2,
411             field_names=['Module', 'Duration', 'nb. Test Run', 'Success'])
412         res_table.align['Module'] = "l"
413         res_table.align['Duration'] = "r"
414         res_table.align['Success'] = "r"
415
416         # for each scenario we draw a row for the table
417         for item in self.summary:
418             if item['task_status'] is True:
419                 nb_modules += 1
420             total_duration += item['overall_duration']
421             total_nb_tests += item['nb_tests']
422             total_nb_success += item['nb_success']
423             try:
424                 success_avg = 100 * item['nb_success'] / item['nb_tests']
425             except ZeroDivisionError:
426                 success_avg = 0
427             success_str = str("{:0.2f}".format(success_avg)) + '%'
428             duration_str = time.strftime("%M:%S",
429                                          time.gmtime(item['overall_duration']))
430             res_table.add_row([item['test_name'], duration_str,
431                                item['nb_tests'], success_str])
432             payload.append({'module': item['test_name'],
433                             'details': {'duration': item['overall_duration'],
434                                         'nb tests': item['nb_tests'],
435                                         'success': success_str}})
436
437         total_duration_str = time.strftime("%H:%M:%S",
438                                            time.gmtime(total_duration))
439         try:
440             self.result = 100 * total_nb_success / total_nb_tests
441         except ZeroDivisionError:
442             self.result = 100
443         success_rate = "{:0.2f}".format(self.result)
444         success_rate_str = str(success_rate) + '%'
445         res_table.add_row(["", "", "", ""])
446         res_table.add_row(["TOTAL:", total_duration_str, total_nb_tests,
447                            success_rate_str])
448
449         LOGGER.info("Rally Summary Report:\n\n%s\n", res_table.get_string())
450         LOGGER.info("Rally '%s' success_rate is %s%% in %s/%s modules",
451                     self.case_name, success_rate, nb_modules,
452                     len(self.summary))
453         payload.append({'summary': {'duration': total_duration,
454                                     'nb tests': total_nb_tests,
455                                     'nb success': success_rate}})
456         self.details = payload
457
458     def clean(self):
459         """Cleanup of OpenStack resources. Should be called on completion."""
460         if self.flavor_alt:
461             self.orig_cloud.delete_flavor(self.flavor_alt.id)
462         super(RallyBase, self).clean()
463
464     def is_successful(self):
465         """The overall result of the test."""
466         for item in self.summary:
467             if item['task_status'] is False:
468                 return testcase.TestCase.EX_TESTCASE_FAILED
469
470         return super(RallyBase, self).is_successful()
471
472     @energy.enable_recording
473     def run(self, **kwargs):
474         """Run testcase."""
475         self.start_time = time.time()
476         try:
477             assert super(RallyBase, self).run(
478                 **kwargs) == testcase.TestCase.EX_OK
479             conf_utils.create_rally_deployment()
480             self._prepare_env()
481             self._run_tests()
482             self._generate_report()
483             res = testcase.TestCase.EX_OK
484         except Exception as exc:   # pylint: disable=broad-except
485             LOGGER.error('Error with run: %s', exc)
486             self.result = 0
487             res = testcase.TestCase.EX_RUN_ERROR
488         self.stop_time = time.time()
489         return res
490
491
492 class RallySanity(RallyBase):
493     """Rally sanity testcase implementation."""
494
495     def __init__(self, **kwargs):
496         """Initialize RallySanity object."""
497         if "case_name" not in kwargs:
498             kwargs["case_name"] = "rally_sanity"
499         super(RallySanity, self).__init__(**kwargs)
500         self.mode = 'sanity'
501         self.test_name = 'all'
502         self.smoke = True
503         self.scenario_dir = os.path.join(self.RALLY_SCENARIO_DIR, 'sanity')
504
505
506 class RallyFull(RallyBase):
507     """Rally full testcase implementation."""
508
509     def __init__(self, **kwargs):
510         """Initialize RallyFull object."""
511         if "case_name" not in kwargs:
512             kwargs["case_name"] = "rally_full"
513         super(RallyFull, self).__init__(**kwargs)
514         self.mode = 'full'
515         self.test_name = 'all'
516         self.smoke = False
517         self.scenario_dir = os.path.join(self.RALLY_SCENARIO_DIR, 'full')