aboutsummaryrefslogtreecommitdiffstats
path: root/functest/opnfv_tests/sdn/odl/odl.py
blob: de723d19d0f2eb5b816cdc54824dc90aad33e417 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
#!/usr/bin/env python

# Copyright (c) 2016 Orange and others.
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is available at
# http://www.apache.org/licenses/LICENSE-2.0

"""Define classes required to run ODL suites.

It has been designed for any context. But helpers are given for
running test suites in OPNFV environment.

Example:
        $ python odl.py
"""

from __future__ import division

import argparse
import fileinput
import logging
import os
import re
import sys

from six.moves import urllib

from functest.core import robotframework
from functest.utils import constants
import functest.utils.openstack_utils as op_utils

__author__ = "Cedric Ollivier <cedric.ollivier@orange.com>"


class ODLTests(robotframework.RobotFramework):
    """ODL test runner."""

    odl_test_repo = constants.CONST.__getattribute__('dir_repo_odl_test')
    neutron_suite_dir = os.path.join(odl_test_repo,
                                     "csit/suites/openstack/neutron")
    basic_suite_dir = os.path.join(odl_test_repo,
                                   "csit/suites/integration/basic")
    default_suites = [basic_suite_dir, neutron_suite_dir]
    __logger = logging.getLogger(__name__)

    def __init__(self, **kwargs):
        super(ODLTests, self).__init__(**kwargs)
        self.res_dir = os.path.join(
            constants.CONST.__getattribute__('dir_results'), 'odl')
        self.xml_file = os.path.join(self.res_dir, 'output.xml')

    @classmethod
    def set_robotframework_vars(cls, odlusername="admin", odlpassword="admin"):
        """Set credentials in csit/variables/Variables.robot.

        Returns:
            True if credentials are set.
            False otherwise.
        """
        odl_variables_files = os.path.join(cls.odl_test_repo,
                                           'csit/variables/Variables.robot')
        try:
            for line in fileinput.input(odl_variables_files,
                                        inplace=True):
                print(re.sub("@{AUTH}.*",
                             "@{{AUTH}}           {}    {}".format(
                                 odlusername, odlpassword),
                             line.rstrip()))
            return True
        except Exception as ex:  # pylint: disable=broad-except
            cls.__logger.error("Cannot set ODL creds: %s", str(ex))
            return False

    def run_suites(self, suites=None, **kwargs):
        """Run the test suites

        It has been designed to be called in any context.
        It requires the following keyword arguments:

           * odlusername,
           * odlpassword,
           * osauthurl,
           * neutronurl,
           * osusername,
           * osprojectname,
           * ospassword,
           * odlip,
           * odlwebport,
           * odlrestconfport.

        Here are the steps:
           * set all RobotFramework_variables,
           * create the output directories if required,
           * get the results in output.xml,
           * delete temporary files.

        Args:
            kwargs: Arbitrary keyword arguments.

        Returns:
            EX_OK if all suites ran well.
            EX_RUN_ERROR otherwise.
        """
        try:
            if not suites:
                suites = self.default_suites
            odlusername = kwargs['odlusername']
            odlpassword = kwargs['odlpassword']
            osauthurl = kwargs['osauthurl']
            keystoneurl = "{}://{}".format(
                urllib.parse.urlparse(osauthurl).scheme,
                urllib.parse.urlparse(osauthurl).netloc)
            variable = ['KEYSTONEURL:' + keystoneurl,
                        'NEUTRONURL:' + kwargs['neutronurl'],
                        'OS_AUTH_URL:"' + osauthurl + '"',
                        'OSUSERNAME:"' + kwargs['osusername'] + '"',
                        ('OSUSERDOMAINNAME:"' +
                         kwargs['osuserdomainname'] + '"'),
                        'OSTENANTNAME:"' + kwargs['osprojectname'] + '"',
                        ('OSPROJECTDOMAINNAME:"' +
                         kwargs['osprojectdomainname'] + '"'),
                        'OSPASSWORD:"' + kwargs['ospassword'] + '"',
                        'ODL_SYSTEM_IP:' + kwargs['odlip'],
                        'PORT:' + kwargs['odlwebport'],
                        'RESTCONFPORT:' + kwargs['odlrestconfport']]
        except KeyError:
            self.__logger.exception("Cannot run ODL testcases. Please check")
            return self.EX_RUN_ERROR
        if self.set_robotframework_vars(odlusername, odlpassword):
            return super(ODLTests, self).run(variable=variable, suites=suites)
        else:
            return self.EX_RUN_ERROR

    def run(self, **kwargs):
        """Run suites in OPNFV environment

        It basically check env vars to call main() with the keywords
        required.

        Args:
            kwargs: Arbitrary keyword arguments.

        Returns:
            EX_OK if all suites ran well.
            EX_RUN_ERROR otherwise.
        """
        try:
            suites = self.default_suites
            try:
                suites = kwargs["suites"]
            except KeyError:
                pass
            kwargs = {'neutronurl': op_utils.get_endpoint(
                service_type='network')}
            kwargs['odlip'] = urllib.parse.urlparse(
                kwargs['neutronurl']).hostname
            kwargs['odlwebport'] = '8080'
            kwargs['odlrestconfport'] = '8181'
            kwargs['odlusername'] = 'admin'
            kwargs['odlpassword'] = 'admin'
            installer_type = None
            if 'INSTALLER_TYPE' in os.environ:
                installer_type = os.environ['INSTALLER_TYPE']
            kwargs['osusername'] = os.environ['OS_USERNAME']
            kwargs['osuserdomainname'] = os.environ.get(
                'OS_USER_DOMAIN_NAME', 'Default')
            kwargs['osprojectname'] = os.environ['OS_PROJECT_NAME']
            kwargs['osprojectdomainname'] = os.environ.get(
                'OS_PROJECT_DOMAIN_NAME', 'Default')
            kwargs['osauthurl'] = os.environ['OS_AUTH_URL']
            kwargs['ospassword'] = os.environ['OS_PASSWORD']
            if installer_type == 'fuel':
                kwargs['odlwebport'] = '8181'
                kwargs['odlrestconfport'] = '8282'
            elif installer_type == 'apex' or installer_type == 'netvirt':
                kwargs['odlip'] = os.environ['SDN_CONTROLLER_IP']
                kwargs['odlwebport'] = '8081'
                kwargs['odlrestconfport'] = '8081'
            elif installer_type == 'joid':
                kwargs['odlip'] = os.environ['SDN_CONTROLLER']
            elif installer_type == 'compass':
                kwargs['odlrestconfport'] = '8080'
            elif installer_type == 'daisy':
                kwargs['odlip'] = os.environ['SDN_CONTROLLER_IP']
                kwargs['odlwebport'] = '8181'
                kwargs['odlrestconfport'] = '8087'
            else:
                kwargs['odlip'] = os.environ['SDN_CONTROLLER_IP']
        except KeyError as ex:
            self.__logger.error("Cannot run ODL testcases. "
                                "Please check env var: "
                                "%s", str(ex))
            return self.EX_RUN_ERROR
        except Exception:  # pylint: disable=broad-except
            self.__logger.exception("Cannot run ODL testcases.")
            return self.EX_RUN_ERROR

        return self.run_suites(suites, **kwargs)


class ODLParser(object):  # pylint: disable=too-few-public-methods
    """Parser to run ODL test suites."""

    def __init__(self):
        self.parser = argparse.ArgumentParser()
        self.parser.add_argument(
            '-n', '--neutronurl', help='Neutron Endpoint',
            default='http://127.0.0.1:9696')
        self.parser.add_argument(
            '-k', '--osauthurl', help='OS_AUTH_URL as defined by OpenStack',
            default='http://127.0.0.1:5000/v3')
        self.parser.add_argument(
            '-a', '--osusername', help='Username for OpenStack',
            default='admin')
        self.parser.add_argument(
            '-f', '--osuserdomainname', help='User domain name for OpenStack',
            default='Default')
        self.parser.add_argument(
            '-b', '--osprojectname', help='Projet name for OpenStack',
            default='admin')
        self.parser.add_argument(
            '-g', '--osprojectdomainname',
            help='Project domain name for OpenStack',
            default='Default')
        self.parser.add_argument(
            '-c', '--ospassword', help='Password for OpenStack',
            default='admin')
        self.parser.add_argument(
            '-o', '--odlip', help='OpenDaylight IP',
            default='127.0.0.1')
        self.parser.add_argument(
            '-w', '--odlwebport', help='OpenDaylight Web Portal Port',
            default='8080')
        self.parser.add_argument(
            '-r', '--odlrestconfport', help='OpenDaylight RESTConf Port',
            default='8181')
        self.parser.add_argument(
            '-d', '--odlusername', help='Username for ODL',
            default='admin')
        self.parser.add_argument(
            '-e', '--odlpassword', help='Password for ODL',
            default='admin')
        self.parser.add_argument(
            '-p', '--pushtodb', help='Push results to DB',
            action='store_true')

    def parse_args(self, argv=None):
        """Parse arguments.

        It can call sys.exit if arguments are incorrect.

        Returns:
            the arguments from cmdline
        """
        if not argv:
            argv = []
        return vars(self.parser.parse_args(argv))


def main():
    """Entry point"""
    logging.basicConfig()
    odl = ODLTests()
    parser = ODLParser()
    args = parser.parse_args(sys.argv[1:])
    try:
        result = odl.run_suites(ODLTests.default_suites, **args)
        if result != robotframework.RobotFramework.EX_OK:
            return result
        if args['pushtodb']:
            return odl.push_to_db()
        else:
            return result
    except Exception:  # pylint: disable=broad-except
        return robotframework.RobotFramework.EX_RUN_ERROR