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