16699a0191fffd19da86076c723ecb97094c8ac9
[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 import uuid
22
23 import os_client_config
24 import pkg_resources
25 import prettytable
26 from xtesting.core import testcase
27 from xtesting.energy import energy
28 import yaml
29
30 from functest.opnfv_tests.openstack.tempest import conf_utils
31 from functest.utils import config
32 from functest.utils import functest_utils
33 from functest.utils import env
34
35 LOGGER = logging.getLogger(__name__)
36
37
38 class RallyBase(testcase.TestCase):
39     """Base class form Rally testcases implementation."""
40
41     # pylint: disable=too-many-instance-attributes
42     TESTS = ['authenticate', 'glance', 'cinder', 'gnocchi', 'heat',
43              'keystone', 'neutron', 'nova', 'quotas', 'vm', 'all']
44     GLANCE_IMAGE_NAME = getattr(config.CONF, 'openstack_image_name')
45     GLANCE_IMAGE_FILENAME = getattr(config.CONF, 'openstack_image_file_name')
46     GLANCE_IMAGE_PATH = os.path.join(getattr(
47         config.CONF, 'dir_functest_images'), GLANCE_IMAGE_FILENAME)
48     GLANCE_IMAGE_FORMAT = getattr(config.CONF, 'openstack_image_disk_format')
49     GLANCE_IMAGE_EXTRA_PROPERTIES = getattr(
50         config.CONF, 'image_properties', {})
51     FLAVOR_NAME = getattr(config.CONF, 'rally_flavor_name')
52     FLAVOR_ALT_NAME = getattr(config.CONF, 'rally_flavor_alt_name')
53     FLAVOR_RAM = 512
54     FLAVOR_RAM_ALT = 1024
55     FLAVOR_EXTRA_SPECS = getattr(config.CONF, 'flavor_extra_specs', {})
56     if FLAVOR_EXTRA_SPECS:
57         FLAVOR_RAM = 1024
58         FLAVOR_RAM_ALT = 2048
59
60     RALLY_DIR = pkg_resources.resource_filename(
61         'functest', 'opnfv_tests/openstack/rally')
62     RALLY_SCENARIO_DIR = pkg_resources.resource_filename(
63         'functest', 'opnfv_tests/openstack/rally/scenario')
64     TEMPLATE_DIR = pkg_resources.resource_filename(
65         'functest', 'opnfv_tests/openstack/rally/scenario/templates')
66     SUPPORT_DIR = pkg_resources.resource_filename(
67         'functest', 'opnfv_tests/openstack/rally/scenario/support')
68     USERS_AMOUNT = 2
69     TENANTS_AMOUNT = 3
70     ITERATIONS_AMOUNT = 10
71     CONCURRENCY = 4
72     RESULTS_DIR = os.path.join(getattr(config.CONF, 'dir_results'), 'rally')
73     BLACKLIST_FILE = os.path.join(RALLY_DIR, "blacklist.txt")
74     TEMP_DIR = os.path.join(RALLY_DIR, "var")
75
76     RALLY_PRIVATE_NET_NAME = getattr(config.CONF, 'rally_network_name')
77     RALLY_PRIVATE_SUBNET_NAME = str(getattr(config.CONF, 'rally_subnet_name'))
78     RALLY_PRIVATE_SUBNET_CIDR = getattr(config.CONF, 'rally_subnet_cidr')
79     RALLY_ROUTER_NAME = getattr(config.CONF, 'rally_router_name')
80
81     def __init__(self, **kwargs):
82         """Initialize RallyBase object."""
83         super(RallyBase, self).__init__(**kwargs)
84         self.cloud = os_client_config.make_shade()
85         self.guid = '-' + str(uuid.uuid4())
86         self.creators = []
87         self.mode = ''
88         self.summary = []
89         self.scenario_dir = ''
90         self.image_name = None
91         self.ext_net = None
92         self.flavor_name = None
93         self.flavor_alt_name = None
94         self.smoke = None
95         self.test_name = None
96         self.start_time = None
97         self.result = None
98         self.details = None
99         self.compute_cnt = 0
100         self.image = None
101         self.flavor = None
102         self.flavor_alt = None
103         self.network = None
104         self.subnet = None
105         self.router = None
106
107     def _build_task_args(self, test_file_name):
108         """Build arguments for the Rally task."""
109         task_args = {'service_list': [test_file_name]}
110         task_args['image_name'] = str(self.image_name)
111         task_args['flavor_name'] = str(self.flavor_name)
112         task_args['flavor_alt_name'] = str(self.flavor_alt_name)
113         task_args['glance_image_location'] = str(self.GLANCE_IMAGE_PATH)
114         task_args['glance_image_format'] = str(self.GLANCE_IMAGE_FORMAT)
115         task_args['tmpl_dir'] = str(self.TEMPLATE_DIR)
116         task_args['sup_dir'] = str(self.SUPPORT_DIR)
117         task_args['users_amount'] = self.USERS_AMOUNT
118         task_args['tenants_amount'] = self.TENANTS_AMOUNT
119         task_args['use_existing_users'] = False
120         task_args['iterations'] = self.ITERATIONS_AMOUNT
121         task_args['concurrency'] = self.CONCURRENCY
122         task_args['smoke'] = self.smoke
123
124         if self.ext_net:
125             task_args['floating_network'] = str(self.ext_net.name)
126         else:
127             task_args['floating_network'] = ''
128
129         if self.network:
130             task_args['netid'] = str(self.network.id)
131         else:
132             task_args['netid'] = ''
133
134         return task_args
135
136     def _prepare_test_list(self, test_name):
137         """Build the list of test cases to be executed."""
138         test_yaml_file_name = 'opnfv-{}.yaml'.format(test_name)
139         scenario_file_name = os.path.join(self.RALLY_SCENARIO_DIR,
140                                           test_yaml_file_name)
141
142         if not os.path.exists(scenario_file_name):
143             scenario_file_name = os.path.join(self.scenario_dir,
144                                               test_yaml_file_name)
145
146             if not os.path.exists(scenario_file_name):
147                 raise Exception("The scenario '%s' does not exist."
148                                 % scenario_file_name)
149
150         LOGGER.debug('Scenario fetched from : %s', scenario_file_name)
151         test_file_name = os.path.join(self.TEMP_DIR, test_yaml_file_name)
152
153         if not os.path.exists(self.TEMP_DIR):
154             os.makedirs(self.TEMP_DIR)
155
156         self._apply_blacklist(scenario_file_name, test_file_name)
157         return test_file_name
158
159     @staticmethod
160     def get_task_id(cmd_raw):
161         """
162         Get task id from command rally result.
163
164         :param cmd_raw:
165         :return: task_id as string
166         """
167         taskid_re = re.compile('^Task +(.*): started$')
168         for line in cmd_raw.splitlines(True):
169             line = line.strip()
170             match = taskid_re.match(line)
171             if match:
172                 return match.group(1)
173         return None
174
175     @staticmethod
176     def task_succeed(json_raw):
177         """
178         Parse JSON from rally JSON results.
179
180         :param json_raw:
181         :return: Bool
182         """
183         rally_report = json.loads(json_raw)
184         tasks = rally_report.get('tasks')
185         if tasks:
186             for task in tasks:
187                 if task.get('status') != 'finished' or \
188                    task.get('pass_sla') is not True:
189                     return False
190         else:
191             return False
192         return True
193
194     def _migration_supported(self):
195         """Determine if migration is supported."""
196         if self.compute_cnt > 1:
197             return True
198
199         return False
200
201     @staticmethod
202     def get_cmd_output(proc):
203         """Get command stdout."""
204         result = ""
205         for line in proc.stdout:
206             result += line
207         return result
208
209     @staticmethod
210     def excl_scenario():
211         """Exclude scenario."""
212         black_tests = []
213         try:
214             with open(RallyBase.BLACKLIST_FILE, 'r') as black_list_file:
215                 black_list_yaml = yaml.safe_load(black_list_file)
216
217             installer_type = env.get('INSTALLER_TYPE')
218             deploy_scenario = env.get('DEPLOY_SCENARIO')
219             if (bool(installer_type) and bool(deploy_scenario) and
220                     'scenario' in black_list_yaml.keys()):
221                 for item in black_list_yaml['scenario']:
222                     scenarios = item['scenarios']
223                     installers = item['installers']
224                     in_it = RallyBase.in_iterable_re
225                     if (in_it(deploy_scenario, scenarios) and
226                             in_it(installer_type, installers)):
227                         tests = item['tests']
228                         black_tests.extend(tests)
229         except Exception:  # pylint: disable=broad-except
230             LOGGER.debug("Scenario exclusion not applied.")
231
232         return black_tests
233
234     @staticmethod
235     def in_iterable_re(needle, haystack):
236         """
237         Check if given needle is in the iterable haystack, using regex.
238
239         :param needle: string to be matched
240         :param haystack: iterable of strings (optionally regex patterns)
241         :return: True if needle is eqial to any of the elements in haystack,
242                  or if a nonempty regex pattern in haystack is found in needle.
243         """
244         # match without regex
245         if needle in haystack:
246             return True
247
248         for pattern in haystack:
249             # match if regex pattern is set and found in the needle
250             if pattern and re.search(pattern, needle) is not None:
251                 return True
252
253         return False
254
255     def excl_func(self):
256         """Exclude functionalities."""
257         black_tests = []
258         func_list = []
259
260         try:
261             with open(RallyBase.BLACKLIST_FILE, 'r') as black_list_file:
262                 black_list_yaml = yaml.safe_load(black_list_file)
263
264             if not self._migration_supported():
265                 func_list.append("no_migration")
266
267             if 'functionality' in black_list_yaml.keys():
268                 for item in black_list_yaml['functionality']:
269                     functions = item['functions']
270                     for func in func_list:
271                         if func in functions:
272                             tests = item['tests']
273                             black_tests.extend(tests)
274         except Exception:  # pylint: disable=broad-except
275             LOGGER.debug("Functionality exclusion not applied.")
276
277         return black_tests
278
279     def _apply_blacklist(self, case_file_name, result_file_name):
280         """Apply blacklist."""
281         LOGGER.debug("Applying blacklist...")
282         cases_file = open(case_file_name, 'r')
283         result_file = open(result_file_name, 'w')
284
285         black_tests = list(set(self.excl_func() +
286                                self.excl_scenario()))
287
288         if black_tests:
289             LOGGER.debug("Blacklisted tests: " + str(black_tests))
290
291         include = True
292         for cases_line in cases_file:
293             if include:
294                 for black_tests_line in black_tests:
295                     if re.search(black_tests_line,
296                                  cases_line.strip().rstrip(':')):
297                         include = False
298                         break
299                 else:
300                     result_file.write(str(cases_line))
301             else:
302                 if cases_line.isspace():
303                     include = True
304
305         cases_file.close()
306         result_file.close()
307
308     @staticmethod
309     def file_is_empty(file_name):
310         """Determine is a file is empty."""
311         try:
312             if os.stat(file_name).st_size > 0:
313                 return False
314         except Exception:  # pylint: disable=broad-except
315             pass
316
317         return True
318
319     def _save_results(self, test_name, task_id):
320         """ Generate and save task execution results"""
321         # check for result directory and create it otherwise
322         if not os.path.exists(self.RESULTS_DIR):
323             LOGGER.debug('%s does not exist, we create it.',
324                          self.RESULTS_DIR)
325             os.makedirs(self.RESULTS_DIR)
326
327         # put detailed result to log
328         cmd = (["rally", "task", "detailed", "--uuid", task_id])
329         LOGGER.debug('running command: %s', cmd)
330         proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
331                                 stderr=subprocess.STDOUT)
332         json_detailed = self.get_cmd_output(proc)
333         LOGGER.info('%s', json_detailed)
334
335         # save report as JSON
336         cmd = (["rally", "task", "report", "--json", "--uuid", task_id])
337         LOGGER.debug('running command: %s', cmd)
338         with open(os.devnull, 'w') as devnull:
339             proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
340                                     stderr=devnull)
341         json_results = self.get_cmd_output(proc)
342         report_json_name = 'opnfv-{}.json'.format(test_name)
343         report_json_dir = os.path.join(self.RESULTS_DIR, report_json_name)
344         with open(report_json_dir, 'w') as r_file:
345             LOGGER.debug('saving json file')
346             r_file.write(json_results)
347
348         # save report as HTML
349         report_html_name = 'opnfv-{}.html'.format(test_name)
350         report_html_dir = os.path.join(self.RESULTS_DIR, report_html_name)
351         cmd = (["rally", "task", "report", "--html", "--uuid", task_id,
352                 "--out", report_html_dir])
353         LOGGER.debug('running command: %s', cmd)
354         with open(os.devnull, 'w') as devnull:
355             subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=devnull)
356
357         self._append_summary(json_results, test_name)
358
359         # parse JSON operation result
360         if self.task_succeed(json_results):
361             LOGGER.info('Test scenario: "{}" OK.'.format(test_name) + "\n")
362         else:
363             LOGGER.info('Test scenario: "{}" Failed.'.format(test_name) + "\n")
364
365     def _run_task(self, test_name):
366         """Run a task."""
367         LOGGER.info('Starting test scenario "%s" ...', test_name)
368
369         task_file = os.path.join(self.RALLY_DIR, 'task.yaml')
370         if not os.path.exists(task_file):
371             LOGGER.error("Task file '%s' does not exist.", task_file)
372             raise Exception("Task file '%s' does not exist.", task_file)
373
374         file_name = self._prepare_test_list(test_name)
375         if self.file_is_empty(file_name):
376             LOGGER.info('No tests for scenario "%s"', test_name)
377             return
378
379         cmd = (["rally", "task", "start", "--abort-on-sla-failure", "--task",
380                 task_file, "--task-args",
381                 str(self._build_task_args(test_name))])
382         LOGGER.debug('running command: %s', cmd)
383
384         proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
385                                 stderr=subprocess.STDOUT)
386         output = self.get_cmd_output(proc)
387         task_id = self.get_task_id(output)
388
389         LOGGER.debug('task_id : %s', task_id)
390
391         if task_id is None:
392             LOGGER.error('Failed to retrieve task_id, validating task...')
393             cmd = (["rally", "task", "validate", "--task", task_file,
394                     "--task-args", str(self._build_task_args(test_name))])
395             LOGGER.debug('running command: %s', cmd)
396             proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
397                                     stderr=subprocess.STDOUT)
398             output = self.get_cmd_output(proc)
399             LOGGER.error("Task validation result:" + "\n" + output)
400             raise Exception("Failed to retrieve task id")
401
402         self._save_results(test_name, task_id)
403
404     def _append_summary(self, json_raw, test_name):
405         """Update statistics summary info."""
406         nb_tests = 0
407         nb_success = 0
408         overall_duration = 0.0
409
410         rally_report = json.loads(json_raw)
411         for task in rally_report.get('tasks'):
412             for subtask in task.get('subtasks'):
413                 for workload in subtask.get('workloads'):
414                     if workload.get('full_duration'):
415                         overall_duration += workload.get('full_duration')
416
417                     if workload.get('data'):
418                         nb_tests += len(workload.get('data'))
419
420                     for result in workload.get('data'):
421                         if not result.get('error'):
422                             nb_success += 1
423
424         scenario_summary = {'test_name': test_name,
425                             'overall_duration': overall_duration,
426                             'nb_tests': nb_tests,
427                             'nb_success': nb_success,
428                             'task_status': self.task_succeed(json_raw)}
429         self.summary.append(scenario_summary)
430
431     def _prepare_env(self):
432         """Create resources needed by test scenarios."""
433         assert self.cloud
434         LOGGER.debug('Validating the test name...')
435         if self.test_name not in self.TESTS:
436             raise Exception("Test name '%s' is invalid" % self.test_name)
437
438         network_name = self.RALLY_PRIVATE_NET_NAME + self.guid
439         subnet_name = self.RALLY_PRIVATE_SUBNET_NAME + self.guid
440         router_name = self.RALLY_ROUTER_NAME + self.guid
441         self.image_name = self.GLANCE_IMAGE_NAME + self.guid
442         self.flavor_name = self.FLAVOR_NAME + self.guid
443         self.flavor_alt_name = self.FLAVOR_ALT_NAME + self.guid
444         self.compute_cnt = len(self.cloud.list_hypervisors())
445         self.ext_net = functest_utils.get_external_network(self.cloud)
446         if self.ext_net is None:
447             raise Exception("No external network found")
448
449         LOGGER.debug("Creating image '%s'...", self.image_name)
450         self.image = self.cloud.create_image(
451             self.image_name,
452             filename=self.GLANCE_IMAGE_PATH,
453             disk_format=self.GLANCE_IMAGE_FORMAT,
454             meta=self.GLANCE_IMAGE_EXTRA_PROPERTIES,
455             is_public=True)
456         if self.image is None:
457             raise Exception("Failed to create image")
458
459         LOGGER.debug("Creating network '%s'...", network_name)
460         provider = {}
461         if hasattr(config.CONF, 'rally_network_type'):
462             provider["network_type"] = getattr(
463                 config.CONF, 'rally_network_type')
464         if hasattr(config.CONF, 'rally_physical_network'):
465             provider["physical_network"] = getattr(
466                 config.CONF, 'rally_physical_network')
467         if hasattr(config.CONF, 'rally_segmentation_id'):
468             provider["segmentation_id"] = getattr(
469                 config.CONF, 'rally_segmentation_id')
470
471         self.network = self.cloud.create_network(
472             network_name, shared=True, provider=provider)
473         if self.network is None:
474             raise Exception("Failed to create private network")
475
476         self.subnet = self.cloud.create_subnet(
477             self.network.id,
478             subnet_name=subnet_name,
479             cidr=self.RALLY_PRIVATE_SUBNET_CIDR,
480             enable_dhcp=True,
481             dns_nameservers=[env.get('NAMESERVER')])
482         if self.subnet is None:
483             raise Exception("Failed to create private subnet")
484
485         LOGGER.debug("Creating router '%s'...", router_name)
486         self.router = self.cloud.create_router(
487             router_name, ext_gateway_net_id=self.ext_net.id)
488         if self.router is None:
489             raise Exception("Failed to create router")
490         self.cloud.add_router_interface(self.router, subnet_id=self.subnet.id)
491
492         LOGGER.debug("Creating flavor '%s'...", self.flavor_name)
493         self.flavor = self.cloud.create_flavor(
494             self.flavor_name, self.FLAVOR_RAM, 1, 1)
495         if self.flavor is None:
496             raise Exception("Failed to create flavor")
497         self.cloud.set_flavor_specs(
498             self.flavor.id, self.FLAVOR_EXTRA_SPECS)
499
500         LOGGER.debug("Creating flavor '%s'...", self.flavor_alt_name)
501         self.flavor_alt = self.cloud.create_flavor(
502             self.flavor_alt_name, self.FLAVOR_RAM_ALT, 1, 1)
503         if self.flavor_alt is None:
504             raise Exception("Failed to create flavor")
505         self.cloud.set_flavor_specs(
506             self.flavor_alt.id, self.FLAVOR_EXTRA_SPECS)
507
508     def _run_tests(self):
509         """Execute tests."""
510         if self.test_name == 'all':
511             for test in self.TESTS:
512                 if test == 'all' or test == 'vm':
513                     continue
514                 self._run_task(test)
515         else:
516             self._run_task(self.test_name)
517
518     def _generate_report(self):
519         """Generate test execution summary report."""
520         total_duration = 0.0
521         total_nb_tests = 0
522         total_nb_success = 0
523         nb_modules = 0
524         payload = []
525
526         res_table = prettytable.PrettyTable(
527             padding_width=2,
528             field_names=['Module', 'Duration', 'nb. Test Run', 'Success'])
529         res_table.align['Module'] = "l"
530         res_table.align['Duration'] = "r"
531         res_table.align['Success'] = "r"
532
533         # for each scenario we draw a row for the table
534         for item in self.summary:
535             if item['task_status'] is True:
536                 nb_modules += 1
537             total_duration += item['overall_duration']
538             total_nb_tests += item['nb_tests']
539             total_nb_success += item['nb_success']
540             try:
541                 success_avg = 100 * item['nb_success'] / item['nb_tests']
542             except ZeroDivisionError:
543                 success_avg = 0
544             success_str = str("{:0.2f}".format(success_avg)) + '%'
545             duration_str = time.strftime("%M:%S",
546                                          time.gmtime(item['overall_duration']))
547             res_table.add_row([item['test_name'], duration_str,
548                                item['nb_tests'], success_str])
549             payload.append({'module': item['test_name'],
550                             'details': {'duration': item['overall_duration'],
551                                         'nb tests': item['nb_tests'],
552                                         'success': success_str}})
553
554         total_duration_str = time.strftime("%H:%M:%S",
555                                            time.gmtime(total_duration))
556         try:
557             self.result = 100 * total_nb_success / total_nb_tests
558         except ZeroDivisionError:
559             self.result = 100
560         success_rate = "{:0.2f}".format(self.result)
561         success_rate_str = str(success_rate) + '%'
562         res_table.add_row(["", "", "", ""])
563         res_table.add_row(["TOTAL:", total_duration_str, total_nb_tests,
564                            success_rate_str])
565
566         LOGGER.info("Rally Summary Report:\n\n%s\n", res_table.get_string())
567         LOGGER.info("Rally '%s' success_rate is %s%% in %s/%s modules",
568                     self.case_name, success_rate, nb_modules,
569                     len(self.summary))
570         payload.append({'summary': {'duration': total_duration,
571                                     'nb tests': total_nb_tests,
572                                     'nb success': success_rate}})
573         self.details = payload
574
575     def _clean_up(self):
576         """Cleanup of OpenStack resources. Should be called on completion."""
577         if self.flavor_alt:
578             self.cloud.delete_flavor(self.flavor_alt.id)
579         if self.flavor:
580             self.cloud.delete_flavor(self.flavor.id)
581         if self.router and self.subnet:
582             self.cloud.remove_router_interface(self.router, self.subnet.id)
583         if self.router:
584             self.cloud.delete_router(self.router.id)
585         if self.subnet:
586             self.cloud.delete_subnet(self.subnet.id)
587         if self.network:
588             self.cloud.delete_network(self.network.id)
589         if self.image:
590             self.cloud.delete_image(self.image.id)
591
592     def is_successful(self):
593         """The overall result of the test."""
594         for item in self.summary:
595             if item['task_status'] is False:
596                 return testcase.TestCase.EX_TESTCASE_FAILED
597
598         return super(RallyBase, self).is_successful()
599
600     @energy.enable_recording
601     def run(self, **kwargs):
602         """Run testcase."""
603         self.start_time = time.time()
604         try:
605             conf_utils.create_rally_deployment()
606             self._prepare_env()
607             self._run_tests()
608             self._generate_report()
609             res = testcase.TestCase.EX_OK
610         except Exception as exc:   # pylint: disable=broad-except
611             LOGGER.error('Error with run: %s', exc)
612             res = testcase.TestCase.EX_RUN_ERROR
613         finally:
614             self._clean_up()
615
616         self.stop_time = time.time()
617         return res
618
619
620 class RallySanity(RallyBase):
621     """Rally sanity testcase implementation."""
622
623     def __init__(self, **kwargs):
624         """Initialize RallySanity object."""
625         if "case_name" not in kwargs:
626             kwargs["case_name"] = "rally_sanity"
627         super(RallySanity, self).__init__(**kwargs)
628         self.mode = 'sanity'
629         self.test_name = 'all'
630         self.smoke = True
631         self.scenario_dir = os.path.join(self.RALLY_SCENARIO_DIR, 'sanity')
632
633
634 class RallyFull(RallyBase):
635     """Rally full testcase implementation."""
636
637     def __init__(self, **kwargs):
638         """Initialize RallyFull object."""
639         if "case_name" not in kwargs:
640             kwargs["case_name"] = "rally_full"
641         super(RallyFull, self).__init__(**kwargs)
642         self.mode = 'full'
643         self.test_name = 'all'
644         self.smoke = False
645         self.scenario_dir = os.path.join(self.RALLY_SCENARIO_DIR, 'full')