8d1bfabb5013191555a7b7124067c541dcd99e48
[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         for report in rally_report:
185             if report is None or report.get('result') is None:
186                 return False
187
188             for result in report.get('result'):
189                 if result is None or result.get('error'):
190                     return False
191
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 _run_task(self, test_name):
320         """Run a task."""
321         LOGGER.info('Starting test scenario "%s" ...', test_name)
322
323         task_file = os.path.join(self.RALLY_DIR, 'task.yaml')
324         if not os.path.exists(task_file):
325             LOGGER.error("Task file '%s' does not exist.", task_file)
326             raise Exception("Task file '%s' does not exist.", task_file)
327
328         file_name = self._prepare_test_list(test_name)
329         if self.file_is_empty(file_name):
330             LOGGER.info('No tests for scenario "%s"', test_name)
331             return
332
333         cmd = (["rally", "task", "start", "--abort-on-sla-failure", "--task",
334                 task_file, "--task-args",
335                 str(self._build_task_args(test_name))])
336         LOGGER.debug('running command: %s', cmd)
337
338         proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
339                                 stderr=subprocess.STDOUT)
340         output = self.get_cmd_output(proc)
341         task_id = self.get_task_id(output)
342
343         LOGGER.debug('task_id : %s', task_id)
344
345         if task_id is None:
346             LOGGER.error('Failed to retrieve task_id, validating task...')
347             cmd = (["rally", "task", "validate", "--task", task_file,
348                     "--task-args", str(self._build_task_args(test_name))])
349             LOGGER.debug('running command: %s', cmd)
350             proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
351                                     stderr=subprocess.STDOUT)
352             output = self.get_cmd_output(proc)
353             LOGGER.error("Task validation result:" + "\n" + output)
354             return
355
356         # check for result directory and create it otherwise
357         if not os.path.exists(self.RESULTS_DIR):
358             LOGGER.debug('%s does not exist, we create it.',
359                          self.RESULTS_DIR)
360             os.makedirs(self.RESULTS_DIR)
361
362         # get and save rally operation JSON result
363         cmd = (["rally", "task", "detailed", task_id])
364         LOGGER.debug('running command: %s', cmd)
365         proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
366                                 stderr=subprocess.STDOUT)
367         json_detailed = self.get_cmd_output(proc)
368         LOGGER.info('%s', json_detailed)
369
370         cmd = (["rally", "task", "results", task_id])
371         LOGGER.debug('running command: %s', cmd)
372         proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
373                                 stderr=subprocess.STDOUT)
374         json_results = self.get_cmd_output(proc)
375         self._append_summary(json_results, test_name)
376         report_json_name = 'opnfv-{}.json'.format(test_name)
377         report_json_dir = os.path.join(self.RESULTS_DIR, report_json_name)
378         with open(report_json_dir, 'w') as r_file:
379             LOGGER.debug('saving json file')
380             r_file.write(json_results)
381
382         # write html report file
383         report_html_name = 'opnfv-{}.html'.format(test_name)
384         report_html_dir = os.path.join(self.RESULTS_DIR, report_html_name)
385         cmd = (["rally", "task", "report", task_id, "--out", report_html_dir])
386         LOGGER.debug('running command: %s', cmd)
387         subprocess.Popen(cmd, stdout=subprocess.PIPE,
388                          stderr=subprocess.STDOUT)
389
390         # parse JSON operation result
391         if self.task_succeed(json_results):
392             LOGGER.info('Test scenario: "{}" OK.'.format(test_name) + "\n")
393         else:
394             LOGGER.info('Test scenario: "{}" Failed.'.format(test_name) + "\n")
395
396     def _append_summary(self, json_raw, test_name):
397         """Update statistics summary info."""
398         nb_tests = 0
399         nb_success = 0
400         overall_duration = 0.0
401
402         rally_report = json.loads(json_raw)
403         for report in rally_report:
404             if report.get('full_duration'):
405                 overall_duration += report.get('full_duration')
406
407             if report.get('result'):
408                 for result in report.get('result'):
409                     nb_tests += 1
410                     if not result.get('error'):
411                         nb_success += 1
412
413         scenario_summary = {'test_name': test_name,
414                             'overall_duration': overall_duration,
415                             'nb_tests': nb_tests,
416                             'nb_success': nb_success}
417         self.summary.append(scenario_summary)
418
419     def _prepare_env(self):
420         """Create resources needed by test scenarios."""
421         assert self.cloud
422         LOGGER.debug('Validating the test name...')
423         if self.test_name not in self.TESTS:
424             raise Exception("Test name '%s' is invalid" % self.test_name)
425
426         network_name = self.RALLY_PRIVATE_NET_NAME + self.guid
427         subnet_name = self.RALLY_PRIVATE_SUBNET_NAME + self.guid
428         router_name = self.RALLY_ROUTER_NAME + self.guid
429         self.image_name = self.GLANCE_IMAGE_NAME + self.guid
430         self.flavor_name = self.FLAVOR_NAME + self.guid
431         self.flavor_alt_name = self.FLAVOR_ALT_NAME + self.guid
432         self.compute_cnt = len(self.cloud.list_hypervisors())
433         self.ext_net = functest_utils.get_external_network(self.cloud)
434         if self.ext_net is None:
435             raise Exception("No external network found")
436
437         LOGGER.debug("Creating image '%s'...", self.image_name)
438         self.image = self.cloud.create_image(
439             self.image_name,
440             filename=self.GLANCE_IMAGE_PATH,
441             disk_format=self.GLANCE_IMAGE_FORMAT,
442             meta=self.GLANCE_IMAGE_EXTRA_PROPERTIES,
443             is_public=True)
444         if self.image is None:
445             raise Exception("Failed to create image")
446
447         LOGGER.debug("Creating network '%s'...", network_name)
448         provider = {}
449         if hasattr(config.CONF, 'rally_network_type'):
450             provider["network_type"] = getattr(
451                 config.CONF, 'rally_network_type')
452         if hasattr(config.CONF, 'rally_physical_network'):
453             provider["physical_network"] = getattr(
454                 config.CONF, 'rally_physical_network')
455         if hasattr(config.CONF, 'rally_segmentation_id'):
456             provider["segmentation_id"] = getattr(
457                 config.CONF, 'rally_segmentation_id')
458
459         self.network = self.cloud.create_network(
460             network_name, shared=True, provider=provider)
461         if self.network is None:
462             raise Exception("Failed to create private network")
463
464         self.subnet = self.cloud.create_subnet(
465             self.network.id,
466             subnet_name=subnet_name,
467             cidr=self.RALLY_PRIVATE_SUBNET_CIDR,
468             enable_dhcp=True,
469             dns_nameservers=[env.get('NAMESERVER')])
470         if self.subnet is None:
471             raise Exception("Failed to create private subnet")
472
473         LOGGER.debug("Creating router '%s'...", router_name)
474         self.router = self.cloud.create_router(
475             router_name, ext_gateway_net_id=self.ext_net.id)
476         if self.router is None:
477             raise Exception("Failed to create router")
478         self.cloud.add_router_interface(self.router, subnet_id=self.subnet.id)
479
480         LOGGER.debug("Creating flavor '%s'...", self.flavor_name)
481         self.flavor = self.cloud.create_flavor(
482             self.flavor_name, self.FLAVOR_RAM, 1, 1)
483         if self.flavor is None:
484             raise Exception("Failed to create flavor")
485         self.cloud.set_flavor_specs(
486             self.flavor.id, self.FLAVOR_EXTRA_SPECS)
487
488         LOGGER.debug("Creating flavor '%s'...", self.flavor_alt_name)
489         self.flavor_alt = self.cloud.create_flavor(
490             self.flavor_alt_name, self.FLAVOR_RAM_ALT, 1, 1)
491         if self.flavor_alt is None:
492             raise Exception("Failed to create flavor")
493         self.cloud.set_flavor_specs(
494             self.flavor_alt.id, self.FLAVOR_EXTRA_SPECS)
495
496     def _run_tests(self):
497         """Execute tests."""
498         if self.test_name == 'all':
499             for test in self.TESTS:
500                 if test == 'all' or test == 'vm':
501                     continue
502                 self._run_task(test)
503         else:
504             self._run_task(self.test_name)
505
506     def _generate_report(self):
507         """Generate test execution summary report."""
508         total_duration = 0.0
509         total_nb_tests = 0
510         total_nb_success = 0
511         payload = []
512
513         res_table = prettytable.PrettyTable(
514             padding_width=2,
515             field_names=['Module', 'Duration', 'nb. Test Run', 'Success'])
516         res_table.align['Module'] = "l"
517         res_table.align['Duration'] = "r"
518         res_table.align['Success'] = "r"
519
520         # for each scenario we draw a row for the table
521         for item in self.summary:
522             total_duration += item['overall_duration']
523             total_nb_tests += item['nb_tests']
524             total_nb_success += item['nb_success']
525             try:
526                 success_avg = 100 * item['nb_success'] / item['nb_tests']
527             except ZeroDivisionError:
528                 success_avg = 0
529             success_str = str("{:0.2f}".format(success_avg)) + '%'
530             duration_str = time.strftime("%M:%S",
531                                          time.gmtime(item['overall_duration']))
532             res_table.add_row([item['test_name'], duration_str,
533                                item['nb_tests'], success_str])
534             payload.append({'module': item['test_name'],
535                             'details': {'duration': item['overall_duration'],
536                                         'nb tests': item['nb_tests'],
537                                         'success': success_str}})
538
539         total_duration_str = time.strftime("%H:%M:%S",
540                                            time.gmtime(total_duration))
541         try:
542             self.result = 100 * total_nb_success / total_nb_tests
543         except ZeroDivisionError:
544             self.result = 100
545         success_rate = "{:0.2f}".format(self.result)
546         success_rate_str = str(success_rate) + '%'
547         res_table.add_row(["", "", "", ""])
548         res_table.add_row(["TOTAL:", total_duration_str, total_nb_tests,
549                            success_rate_str])
550
551         LOGGER.info("Rally Summary Report:\n\n%s\n", res_table.get_string())
552         LOGGER.info("Rally '%s' success_rate is %s%%",
553                     self.case_name, success_rate)
554         payload.append({'summary': {'duration': total_duration,
555                                     'nb tests': total_nb_tests,
556                                     'nb success': success_rate}})
557         self.details = payload
558
559     def _clean_up(self):
560         """Cleanup of OpenStack resources. Should be called on completion."""
561         if self.flavor_alt:
562             self.cloud.delete_flavor(self.flavor_alt.id)
563         if self.flavor:
564             self.cloud.delete_flavor(self.flavor.id)
565         if self.router and self.subnet:
566             self.cloud.remove_router_interface(self.router, self.subnet.id)
567         if self.router:
568             self.cloud.delete_router(self.router.id)
569         if self.subnet:
570             self.cloud.delete_subnet(self.subnet.id)
571         if self.network:
572             self.cloud.delete_network(self.network.id)
573         if self.image:
574             self.cloud.delete_image(self.image.id)
575
576     @energy.enable_recording
577     def run(self, **kwargs):
578         """Run testcase."""
579         self.start_time = time.time()
580         try:
581             conf_utils.create_rally_deployment()
582             self._prepare_env()
583             self._run_tests()
584             self._generate_report()
585             res = testcase.TestCase.EX_OK
586         except Exception as exc:   # pylint: disable=broad-except
587             LOGGER.error('Error with run: %s', exc)
588             res = testcase.TestCase.EX_RUN_ERROR
589         finally:
590             self._clean_up()
591
592         self.stop_time = time.time()
593         return res
594
595
596 class RallySanity(RallyBase):
597     """Rally sanity testcase implementation."""
598
599     def __init__(self, **kwargs):
600         """Initialize RallySanity object."""
601         if "case_name" not in kwargs:
602             kwargs["case_name"] = "rally_sanity"
603         super(RallySanity, self).__init__(**kwargs)
604         self.mode = 'sanity'
605         self.test_name = 'all'
606         self.smoke = True
607         self.scenario_dir = os.path.join(self.RALLY_SCENARIO_DIR, 'sanity')
608
609
610 class RallyFull(RallyBase):
611     """Rally full testcase implementation."""
612
613     def __init__(self, **kwargs):
614         """Initialize RallyFull object."""
615         if "case_name" not in kwargs:
616             kwargs["case_name"] = "rally_full"
617         super(RallyFull, self).__init__(**kwargs)
618         self.mode = 'full'
619         self.test_name = 'all'
620         self.smoke = False
621         self.scenario_dir = os.path.join(self.RALLY_SCENARIO_DIR, 'full')