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