[odl-sfc] Add function to retrieve a resource from HEAT
[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         admin_user_id = os_utils.get_user_id(self.keystone_client,
115                                              self.creds['username'])
116         if admin_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, admin_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         if not os_utils.add_role_user(self.keystone_client, user_id,
153                                       role_id, tenant_id):
154             self.logger.error("Failed to add %s on tenant" %
155                               self.tenant_name)
156             self.step_failure("Failed to add %s on tenant" %
157                               self.tenant_name)
158
159         self.logger.info("Update OpenStack creds informations")
160         self.admin_creds = self.creds.copy()
161         self.admin_creds.update({
162             "tenant": self.tenant_name
163         })
164         self.neutron_client = os_utils.get_neutron_client(self.admin_creds)
165         self.nova_client = os_utils.get_nova_client(self.admin_creds)
166         self.creds.update({
167             "tenant": self.tenant_name,
168             "username": self.tenant_name,
169             "password": self.tenant_name,
170         })
171
172     # orchestrator is not mandatory to dpeloy and test VNF
173     def deploy_orchestrator(self, **kwargs):
174         pass
175
176     # TODO see how to use built-in exception from releng module
177     def deploy_vnf(self):
178         self.logger.error("VNF must be deployed")
179         raise Exception("VNF not deployed")
180
181     def test_vnf(self):
182         self.logger.error("VNF must be tested")
183         raise Exception("VNF not tested")
184
185     def clean(self):
186         self.logger.info("test cleaning")
187
188         self.logger.info("Removing %s tenant .." % self.tenant_name)
189         tenant_id = os_utils.get_tenant_id(self.keystone_client,
190                                            self.tenant_name)
191         if tenant_id == '':
192             self.logger.error("Error : Failed to get id of %s tenant" %
193                               self.tenant_name)
194         else:
195             if not os_utils.delete_tenant(self.keystone_client, tenant_id):
196                 self.logger.error("Error : Failed to remove %s tenant" %
197                                   self.tenant_name)
198
199         self.logger.info("Removing %s user .." % self.tenant_name)
200         user_id = os_utils.get_user_id(
201             self.keystone_client, self.tenant_name)
202         if user_id == '':
203             self.logger.error("Error : Failed to get id of %s user" %
204                               self.tenant_name)
205         else:
206             if not os_utils.delete_user(self.keystone_client, user_id):
207                 self.logger.error("Error : Failed to remove %s user" %
208                                   self.tenant_name)
209
210     def parse_results(self):
211         exit_code = self.EX_OK
212         self.criteria = "PASS"
213         self.logger.info(self.details)
214         # The 2 VNF steps must be OK to get a PASS result
215         if (self.details['vnf']['status'] is not "PASS" or
216                 self.details['test_vnf']['status'] is not "PASS"):
217             exit_code = self.EX_RUN_ERROR
218             self.criteria = "FAIL"
219         return exit_code
220
221     def log_results(self):
222         ft_utils.logger_test_results(self.project_name,
223                                      self.case_name,
224                                      self.criteria,
225                                      self.details)
226
227     def step_failure(self, error_msg):
228         part = inspect.stack()[1][3]
229         self.details[part]['status'] = 'FAIL'
230         self.details[part]['result'] = error_msg
231         raise Exception(error_msg)