Merge "[odl-sfc] Add function get_vnf and fix endless loop in get_vnf_id"
[functest.git] / functest / core / vnf_base.py
1 #!/usr/bin/env python
2
3 # Copyright (c) 2016 Orange and others.
4 #
5 # All rights reserved. This program and the accompanying materials
6 # are made available under the terms of the Apache License, Version 2.0
7 # which accompanies this distribution, and is available at
8 # http://www.apache.org/licenses/LICENSE-2.0
9
10 import time
11
12 import inspect
13
14 import functest.utils.functest_logger as ft_logger
15 import functest.utils.openstack_utils as os_utils
16 import functest.utils.functest_utils as ft_utils
17 import testcase_base as base
18 from functest.utils.constants import CONST
19
20
21 class VnfOnBoardingBase(base.TestcaseBase):
22
23     logger = ft_logger.Logger(__name__).getLogger()
24
25     def __init__(self, project='functest', case='', repo='', cmd=''):
26         super(VnfOnBoardingBase, self).__init__()
27         self.repo = repo
28         self.project_name = project
29         self.case_name = case
30         self.cmd = cmd
31         self.details = {}
32         self.data_dir = CONST.dir_functest_data
33         self.details['orchestrator'] = {}
34         self.details['vnf'] = {}
35         self.details['test_vnf'] = {}
36         self.images = {}
37         try:
38             self.tenant_name = CONST.__getattribute__(
39                 'vnf_{}_tenant_name'.format(self.case_name))
40             self.tenant_description = CONST.__getattribute__(
41                 'vnf_{}_tenant_description'.format(self.case_name))
42         except:
43             raise Exception("Unknown VNF case=" + self.case_name)
44
45         try:
46             self.images = CONST.__getattribute__(
47                 'vnf_{}_tenant_images'.format(self.case_name))
48         except:
49             self.logger.warn("No tenant image defined for this VNF")
50
51     def execute(self):
52         self.start_time = time.time()
53         # Prepare the test (Create Tenant, User, ...)
54         self.logger.info("Create VNF Onboarding environment")
55         self.prepare()
56
57         # Deploy orchestrator
58         try:
59             self.logger.info("Deploy orchestrator (if necessary)")
60             orchestrator_ready_time = time.time()
61             res_orchestrator = self.deploy_orchestrator()
62             # orchestrator is not mandatory
63             if res_orchestrator is not None:
64                 self.details['orchestrator']['status'] = (
65                     res_orchestrator['status'])
66                 self.details['orchestrator']['result'] = (
67                     res_orchestrator['result'])
68                 self.details['orchestrator']['duration'] = round(
69                     orchestrator_ready_time - self.start_time, 1)
70         except Exception:
71             self.logger.warn("Problem with the Orchestrator", exc_info=True)
72
73         # Deploy VNF
74         try:
75             self.logger.info("Deploy VNF " + self.case_name)
76             res_deploy_vnf = self.deploy_vnf()
77             vnf_ready_time = time.time()
78             self.details['vnf']['status'] = res_deploy_vnf['status']
79             self.details['vnf']['result'] = res_deploy_vnf['result']
80             self.details['vnf']['duration'] = round(
81                 vnf_ready_time - orchestrator_ready_time, 1)
82         except:
83             raise Exception("Error during VNF deployment")
84
85         # Test VNF
86         try:
87             self.logger.info("Test VNF")
88             res_test_vnf = self.test_vnf()
89             test_vnf_done_time = time.time()
90             self.details['test_vnf']['status'] = res_test_vnf['status']
91             self.details['test_vnf']['result'] = res_test_vnf['result']
92             self.details['test_vnf']['duration'] = round(
93                 test_vnf_done_time - vnf_ready_time, 1)
94         except:
95             raise Exception("Error when running VNF tests")
96
97         # Clean the system
98         self.clean()
99         self.stop_time = time.time()
100
101         exit_code = self.parse_results()
102         self.log_results()
103         return exit_code
104
105     # prepare state could consist in the creation of the resources
106     # a dedicated user
107     # a dedictaed tenant
108     # dedicated images
109     def prepare(self):
110         self.creds = os_utils.get_credentials()
111         self.keystone_client = os_utils.get_keystone_client()
112
113         self.logger.info("Prepare OpenStack plateform(create tenant and user)")
114         user_id = os_utils.get_user_id(self.keystone_client,
115                                        self.creds['username'])
116         if user_id == '':
117             self.step_failure("Failed to get id of " +
118                               self.creds['username'])
119
120         tenant_id = os_utils.create_tenant(
121             self.keystone_client, self.tenant_name, self.tenant_description)
122         if not tenant_id:
123             self.step_failure("Failed to create " +
124                               self.tenant_name + " tenant")
125
126         roles_name = ["admin", "Admin"]
127         role_id = ''
128         for role_name in roles_name:
129             if role_id == '':
130                 role_id = os_utils.get_role_id(self.keystone_client, role_name)
131
132         if role_id == '':
133             self.logger.error("Failed to get id for %s role" % role_name)
134             self.step_failure("Failed to get role id of " + role_name)
135
136         if not os_utils.add_role_user(self.keystone_client, user_id,
137                                       role_id, tenant_id):
138             self.logger.error("Failed to add %s on tenant" %
139                               self.creds['username'])
140             self.step_failure("Failed to add %s on tenant" %
141                               self.creds['username'])
142
143         user_id = os_utils.create_user(self.keystone_client,
144                                        self.tenant_name,
145                                        self.tenant_name,
146                                        None,
147                                        tenant_id)
148         if not user_id:
149             self.logger.error("Failed to create %s user" % self.tenant_name)
150             self.step_failure("Failed to create user ")
151
152         self.logger.info("Update OpenStack creds informations")
153         self.admin_creds = self.creds.copy()
154         self.admin_creds.update({
155             "tenant": self.tenant_name
156         })
157         self.neutron_client = os_utils.get_neutron_client(self.admin_creds)
158         self.nova_client = os_utils.get_nova_client(self.admin_creds)
159         self.creds.update({
160             "tenant": self.tenant_name,
161             "username": self.tenant_name,
162             "password": self.tenant_name,
163         })
164
165     # orchestrator is not mandatory to dpeloy and test VNF
166     def deploy_orchestrator(self, **kwargs):
167         pass
168
169     # TODO see how to use built-in exception from releng module
170     def deploy_vnf(self):
171         self.logger.error("VNF must be deployed")
172         raise Exception("VNF not deployed")
173
174     def test_vnf(self):
175         self.logger.error("VNF must be tested")
176         raise Exception("VNF not tested")
177
178     def clean(self):
179         self.logger.info("test cleaning")
180
181         self.logger.info("Removing %s tenant .." % self.tenant_name)
182         tenant_id = os_utils.get_tenant_id(self.keystone_client,
183                                            self.tenant_name)
184         if tenant_id == '':
185             self.logger.error("Error : Failed to get id of %s tenant" %
186                               self.tenant_name)
187         else:
188             if not os_utils.delete_tenant(self.keystone_client, tenant_id):
189                 self.logger.error("Error : Failed to remove %s tenant" %
190                                   self.tenant_name)
191
192         self.logger.info("Removing %s user .." % self.tenant_name)
193         user_id = os_utils.get_user_id(
194             self.keystone_client, self.tenant_name)
195         if user_id == '':
196             self.logger.error("Error : Failed to get id of %s user" %
197                               self.tenant_name)
198         else:
199             if not os_utils.delete_user(self.keystone_client, user_id):
200                 self.logger.error("Error : Failed to remove %s user" %
201                                   self.tenant_name)
202
203     def parse_results(self):
204         exit_code = self.EX_OK
205         self.criteria = "PASS"
206         self.logger.info(self.details)
207         # The 2 VNF steps must be OK to get a PASS result
208         if (self.details['vnf']['status'] is not "PASS" or
209                 self.details['test_vnf']['status'] is not "PASS"):
210             exit_code = self.EX_RUN_ERROR
211             self.criteria = "FAIL"
212         return exit_code
213
214     def log_results(self):
215         ft_utils.logger_test_results(self.project_name,
216                                      self.case_name,
217                                      self.criteria,
218                                      self.details)
219
220     def step_failure(self, error_msg):
221         part = inspect.stack()[1][3]
222         self.details[part]['status'] = 'FAIL'
223         self.details[part]['result'] = error_msg
224         raise Exception(error_msg)