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