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