872e75b8e28d2d4434b4b22c44b4993225a0df88
[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 get_cmd_output(proc):
173         """Get command stdout."""
174         result = ""
175         for line in proc.stdout:
176             result += line
177         return result
178
179     @staticmethod
180     def excl_scenario():
181         """Exclude 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 = env.get('INSTALLER_TYPE')
188             deploy_scenario = env.get('DEPLOY_SCENARIO')
189             if (bool(installer_type) and bool(deploy_scenario) and
190                     'scenario' in black_list_yaml.keys()):
191                 for item in black_list_yaml['scenario']:
192                     scenarios = item['scenarios']
193                     installers = item['installers']
194                     in_it = RallyBase.in_iterable_re
195                     if (in_it(deploy_scenario, scenarios) and
196                             in_it(installer_type, installers)):
197                         tests = item['tests']
198                         black_tests.extend(tests)
199         except Exception:  # pylint: disable=broad-except
200             LOGGER.debug("Scenario exclusion not applied.")
201
202         return black_tests
203
204     @staticmethod
205     def in_iterable_re(needle, haystack):
206         """
207         Check if given needle is in the iterable haystack, using regex.
208
209         :param needle: string to be matched
210         :param haystack: iterable of strings (optionally regex patterns)
211         :return: True if needle is eqial to any of the elements in haystack,
212                  or if a nonempty regex pattern in haystack is found in needle.
213         """
214         # match without regex
215         if needle in haystack:
216             return True
217
218         for pattern in haystack:
219             # match if regex pattern is set and found in the needle
220             if pattern and re.search(pattern, needle) is not None:
221                 return True
222
223         return False
224
225     def excl_func(self):
226         """Exclude functionalities."""
227         black_tests = []
228         func_list = []
229
230         try:
231             with open(RallyBase.BLACKLIST_FILE, 'r') as black_list_file:
232                 black_list_yaml = yaml.safe_load(black_list_file)
233
234             if not self._migration_supported():
235                 func_list.append("no_migration")
236
237             if 'functionality' in black_list_yaml.keys():
238                 for item in black_list_yaml['functionality']:
239                     functions = item['functions']
240                     for func in func_list:
241                         if func in functions:
242                             tests = item['tests']
243                             black_tests.extend(tests)
244         except Exception:  # pylint: disable=broad-except
245             LOGGER.debug("Functionality exclusion not applied.")
246
247         return black_tests
248
249     def _apply_blacklist(self, case_file_name, result_file_name):
250         """Apply blacklist."""
251         LOGGER.debug("Applying blacklist...")
252         cases_file = open(case_file_name, 'r')
253         result_file = open(result_file_name, 'w')
254
255         black_tests = list(set(self.excl_func() +
256                                self.excl_scenario()))
257
258         if black_tests:
259             LOGGER.debug("Blacklisted tests: %s", str(black_tests))
260
261         include = True
262         for cases_line in cases_file:
263             if include:
264                 for black_tests_line in black_tests:
265                     if re.search(black_tests_line,
266                                  cases_line.strip().rstrip(':')):
267                         include = False
268                         break
269                 else:
270                     result_file.write(str(cases_line))
271             else:
272                 if cases_line.isspace():
273                     include = True
274
275         cases_file.close()
276         result_file.close()
277
278     @staticmethod
279     def file_is_empty(file_name):
280         """Determine is a file is empty."""
281         try:
282             if os.stat(file_name).st_size > 0:
283                 return False
284         except Exception:  # pylint: disable=broad-except
285             pass
286
287         return True
288
289     def _save_results(self, test_name, task_id):
290         """ Generate and save task execution results"""
291         # check for result directory and create it otherwise
292         if not os.path.exists(self.RESULTS_DIR):
293             LOGGER.debug('%s does not exist, we create it.',
294                          self.RESULTS_DIR)
295             os.makedirs(self.RESULTS_DIR)
296
297         # put detailed result to log
298         cmd = (["rally", "task", "detailed", "--uuid", task_id])
299         LOGGER.debug('running command: %s', cmd)
300         proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
301                                 stderr=subprocess.STDOUT)
302         json_detailed = self.get_cmd_output(proc)
303         LOGGER.info('%s', json_detailed)
304
305         # save report as JSON
306         cmd = (["rally", "task", "report", "--json", "--uuid", task_id])
307         LOGGER.debug('running command: %s', cmd)
308         with open(os.devnull, 'w') as devnull:
309             proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
310                                     stderr=devnull)
311         json_results = self.get_cmd_output(proc)
312         report_json_name = 'opnfv-{}.json'.format(test_name)
313         report_json_dir = os.path.join(self.RESULTS_DIR, report_json_name)
314         with open(report_json_dir, 'w') as r_file:
315             LOGGER.debug('saving json file')
316             r_file.write(json_results)
317
318         # save report as HTML
319         report_html_name = 'opnfv-{}.html'.format(test_name)
320         report_html_dir = os.path.join(self.RESULTS_DIR, report_html_name)
321         cmd = (["rally", "task", "report", "--html", "--uuid", task_id,
322                 "--out", report_html_dir])
323         LOGGER.debug('running command: %s', cmd)
324         with open(os.devnull, 'w') as devnull:
325             subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=devnull)
326
327         self._append_summary(json_results, test_name)
328
329         # parse JSON operation result
330         if self.task_succeed(json_results):
331             LOGGER.info('Test scenario: "%s" OK.', test_name)
332         else:
333             LOGGER.info('Test scenario: "%s" Failed.', test_name)
334
335     def _run_task(self, test_name):
336         """Run a task."""
337         LOGGER.info('Starting test scenario "%s" ...', test_name)
338
339         task_file = os.path.join(self.RALLY_DIR, 'task.yaml')
340         if not os.path.exists(task_file):
341             LOGGER.error("Task file '%s' does not exist.", task_file)
342             raise Exception("Task file '{}' does not exist.".format(task_file))
343
344         file_name = self._prepare_test_list(test_name)
345         if self.file_is_empty(file_name):
346             LOGGER.info('No tests for scenario "%s"', test_name)
347             return
348
349         cmd = (["rally", "task", "start", "--abort-on-sla-failure", "--task",
350                 task_file, "--task-args",
351                 str(self._build_task_args(test_name))])
352         LOGGER.debug('running command: %s', cmd)
353
354         proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
355                                 stderr=subprocess.STDOUT)
356         output = self.get_cmd_output(proc)
357         task_id = self.get_task_id(output)
358
359         LOGGER.debug('task_id : %s', task_id)
360
361         if task_id is None:
362             LOGGER.error('Failed to retrieve task_id, validating task...')
363             cmd = (["rally", "task", "validate", "--task", task_file,
364                     "--task-args", str(self._build_task_args(test_name))])
365             LOGGER.debug('running command: %s', cmd)
366             proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
367                                     stderr=subprocess.STDOUT)
368             output = self.get_cmd_output(proc)
369             LOGGER.error("Task validation result:" + "\n" + output)
370             raise Exception("Failed to retrieve task id")
371
372         self._save_results(test_name, task_id)
373
374     def _append_summary(self, json_raw, test_name):
375         """Update statistics summary info."""
376         nb_tests = 0
377         nb_success = 0
378         overall_duration = 0.0
379
380         rally_report = json.loads(json_raw)
381         for task in rally_report.get('tasks'):
382             for subtask in task.get('subtasks'):
383                 for workload in subtask.get('workloads'):
384                     if workload.get('full_duration'):
385                         overall_duration += workload.get('full_duration')
386
387                     if workload.get('data'):
388                         nb_tests += len(workload.get('data'))
389
390                     for result in workload.get('data'):
391                         if not result.get('error'):
392                             nb_success += 1
393
394         scenario_summary = {'test_name': test_name,
395                             'overall_duration': overall_duration,
396                             'nb_tests': nb_tests,
397                             'nb_success': nb_success,
398                             'task_status': self.task_succeed(json_raw)}
399         self.summary.append(scenario_summary)
400
401     def _prepare_env(self):
402         """Create resources needed by test scenarios."""
403         assert self.cloud
404         LOGGER.debug('Validating the test name...')
405         if self.test_name not in self.TESTS:
406             raise Exception("Test name '%s' is invalid" % self.test_name)
407
408         self.compute_cnt = len(self.cloud.list_hypervisors())
409         self.flavor_alt = self.create_flavor_alt()
410         LOGGER.debug("flavor: %s", self.flavor_alt)
411
412     def _run_tests(self):
413         """Execute tests."""
414         if self.test_name == 'all':
415             for test in self.TESTS:
416                 if test == 'all' or test == 'vm':
417                     continue
418                 self._run_task(test)
419         else:
420             self._run_task(self.test_name)
421
422     def _generate_report(self):
423         """Generate test execution summary report."""
424         total_duration = 0.0
425         total_nb_tests = 0
426         total_nb_success = 0
427         nb_modules = 0
428         payload = []
429
430         res_table = prettytable.PrettyTable(
431             padding_width=2,
432             field_names=['Module', 'Duration', 'nb. Test Run', 'Success'])
433         res_table.align['Module'] = "l"
434         res_table.align['Duration'] = "r"
435         res_table.align['Success'] = "r"
436
437         # for each scenario we draw a row for the table
438         for item in self.summary:
439             if item['task_status'] is True:
440                 nb_modules += 1
441             total_duration += item['overall_duration']
442             total_nb_tests += item['nb_tests']
443             total_nb_success += item['nb_success']
444             try:
445                 success_avg = 100 * item['nb_success'] / item['nb_tests']
446             except ZeroDivisionError:
447                 success_avg = 0
448             success_str = str("{:0.2f}".format(success_avg)) + '%'
449             duration_str = time.strftime("%M:%S",
450                                          time.gmtime(item['overall_duration']))
451             res_table.add_row([item['test_name'], duration_str,
452                                item['nb_tests'], success_str])
453             payload.append({'module': item['test_name'],
454                             'details': {'duration': item['overall_duration'],
455                                         'nb tests': item['nb_tests'],
456                                         'success': success_str}})
457
458         total_duration_str = time.strftime("%H:%M:%S",
459                                            time.gmtime(total_duration))
460         try:
461             self.result = 100 * total_nb_success / total_nb_tests
462         except ZeroDivisionError:
463             self.result = 100
464         success_rate = "{:0.2f}".format(self.result)
465         success_rate_str = str(success_rate) + '%'
466         res_table.add_row(["", "", "", ""])
467         res_table.add_row(["TOTAL:", total_duration_str, total_nb_tests,
468                            success_rate_str])
469
470         LOGGER.info("Rally Summary Report:\n\n%s\n", res_table.get_string())
471         LOGGER.info("Rally '%s' success_rate is %s%% in %s/%s modules",
472                     self.case_name, success_rate, nb_modules,
473                     len(self.summary))
474         payload.append({'summary': {'duration': total_duration,
475                                     'nb tests': total_nb_tests,
476                                     'nb success': success_rate}})
477         self.details = payload
478
479     def clean(self):
480         """Cleanup of OpenStack resources. Should be called on completion."""
481         super(RallyBase, self).clean()
482         self.orig_cloud.delete_flavor(self.flavor_alt.id)
483
484     def is_successful(self):
485         """The overall result of the test."""
486         for item in self.summary:
487             if item['task_status'] is False:
488                 return testcase.TestCase.EX_TESTCASE_FAILED
489
490         return super(RallyBase, self).is_successful()
491
492     @energy.enable_recording
493     def run(self, **kwargs):
494         """Run testcase."""
495         self.start_time = time.time()
496         try:
497             super(RallyBase, self).run(**kwargs)
498             conf_utils.create_rally_deployment()
499             self._prepare_env()
500             self._run_tests()
501             self._generate_report()
502             res = testcase.TestCase.EX_OK
503         except Exception as exc:   # pylint: disable=broad-except
504             LOGGER.error('Error with run: %s', exc)
505             res = testcase.TestCase.EX_RUN_ERROR
506         self.stop_time = time.time()
507         return res
508
509
510 class RallySanity(RallyBase):
511     """Rally sanity testcase implementation."""
512
513     def __init__(self, **kwargs):
514         """Initialize RallySanity object."""
515         if "case_name" not in kwargs:
516             kwargs["case_name"] = "rally_sanity"
517         super(RallySanity, self).__init__(**kwargs)
518         self.mode = 'sanity'
519         self.test_name = 'all'
520         self.smoke = True
521         self.scenario_dir = os.path.join(self.RALLY_SCENARIO_DIR, 'sanity')
522
523
524 class RallyFull(RallyBase):
525     """Rally full testcase implementation."""
526
527     def __init__(self, **kwargs):
528         """Initialize RallyFull object."""
529         if "case_name" not in kwargs:
530             kwargs["case_name"] = "rally_full"
531         super(RallyFull, self).__init__(**kwargs)
532         self.mode = 'full'
533         self.test_name = 'all'
534         self.smoke = False
535         self.scenario_dir = os.path.join(self.RALLY_SCENARIO_DIR, 'full')