3 # Copyright (c) 2017 Okinawa Open Laboratory and others.
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
10 # pylint: disable=missing-docstring
12 """vrouter testcase implementation."""
18 from cloudify_rest_client.executions import Execution
22 from functest.core import cloudify
23 from functest.opnfv_tests.vnf.router import vrouter_base
24 from functest.opnfv_tests.vnf.router.utilvnf import Utilvnf
25 from functest.utils import config
26 from functest.utils import functest_utils
29 __author__ = "Shuya Nakama <shuya.nakama@okinawaopenlabs.org>"
32 class CloudifyVrouter(cloudify.Cloudify):
33 # pylint: disable=too-many-instance-attributes
34 """vrouter testcase deployed with Cloudify Orchestrator."""
36 __logger = logging.getLogger(__name__)
38 filename_alt = '/home/opnfv/functest/images/vyos-1.1.7.img'
44 def __init__(self, **kwargs):
45 if "case_name" not in kwargs:
46 kwargs["case_name"] = "vyos_vrouter"
47 super(CloudifyVrouter, self).__init__(**kwargs)
49 # Retrieve the configuration
51 self.config = getattr(
52 config.CONF, 'vnf_{}_config'.format(self.case_name))
54 raise Exception("VNF config file not found")
56 self.case_dir = pkg_resources.resource_filename(
57 'functest', 'opnfv_tests/vnf/router')
58 config_file = os.path.join(self.case_dir, self.config)
59 self.orchestrator = dict(
60 requirements=functest_utils.get_parameter_from_yaml(
61 "orchestrator.requirements", config_file),
63 self.details['orchestrator'] = dict(
64 name=functest_utils.get_parameter_from_yaml(
65 "orchestrator.name", config_file),
66 version=functest_utils.get_parameter_from_yaml(
67 "orchestrator.version", config_file),
71 self.__logger.debug("Orchestrator configuration %s", self.orchestrator)
72 self.__logger.debug("name = %s", __name__)
74 descriptor=functest_utils.get_parameter_from_yaml(
75 "vnf.descriptor", config_file),
76 inputs=functest_utils.get_parameter_from_yaml(
77 "vnf.inputs", config_file),
78 requirements=functest_utils.get_parameter_from_yaml(
79 "vnf.requirements", config_file)
81 self.details['vnf'] = dict(
82 descriptor_version=self.vnf['descriptor']['version'],
83 name=functest_utils.get_parameter_from_yaml(
84 "vnf.name", config_file),
85 version=functest_utils.get_parameter_from_yaml(
86 "vnf.version", config_file),
88 self.__logger.debug("VNF configuration: %s", self.vnf)
91 self.util.set_credentials(self.cloud)
92 credentials = {"cloud": self.cloud}
93 self.util_info = {"credentials": credentials,
94 "vnf_data_dir": self.util.vnf_data_dir}
96 self.details['test_vnf'] = dict(
97 name=functest_utils.get_parameter_from_yaml(
98 "vnf_test_suite.name", config_file),
99 version=functest_utils.get_parameter_from_yaml(
100 "vnf_test_suite.version", config_file)
102 self.images = functest_utils.get_parameter_from_yaml(
103 "tenant_images", config_file)
104 self.__logger.info("Images needed for vrouter: %s", self.images)
106 self.image_alt = None
107 self.flavor_alt = None
110 # pylint: disable=too-many-locals,too-many-statements
112 Deploy Cloudify Manager.
113 network, security group, fip, VM creation
116 super(CloudifyVrouter, self).execute()
117 start_time = time.time()
118 self.__logger.info("Put private keypair in manager")
119 scpc = scp.SCPClient(self.ssh.get_transport())
120 scpc.put(self.key_filename, remote_path='~/cloudify_ims.pem')
121 (_, stdout, stderr) = self.ssh.exec_command(
122 "sudo cp ~/cloudify_ims.pem /etc/cloudify/ && "
123 "sudo chmod 444 /etc/cloudify/cloudify_ims.pem && "
124 "sudo yum install -y gcc python-devel python-cmd2 && "
126 self.__logger.info("output:\n%s", stdout.read())
127 self.__logger.info("error:\n%s", stderr.read())
129 self.image_alt = self.publish_image_alt()
130 self.flavor_alt = self.create_flavor_alt()
132 duration = time.time() - start_time
133 self.details['orchestrator'].update(status='PASS', duration=duration)
135 self.vnf['inputs'].update(dict(
136 external_network_name=self.ext_net.name))
137 self.vnf['inputs'].update(dict(
138 target_vnf_image_id=self.image_alt.id))
139 self.vnf['inputs'].update(dict(
140 reference_vnf_image_id=self.image_alt.id))
141 self.vnf['inputs'].update(dict(
142 target_vnf_flavor_id=self.flavor_alt.id))
143 self.vnf['inputs'].update(dict(
144 reference_vnf_flavor_id=self.flavor_alt.id))
145 self.vnf['inputs'].update(dict(
146 keystone_username=self.project.user.name))
147 self.vnf['inputs'].update(dict(
148 keystone_password=self.project.password))
149 self.vnf['inputs'].update(dict(
150 keystone_tenant_name=self.project.project.name))
151 self.vnf['inputs'].update(dict(
152 keystone_user_domain_name=os.environ.get(
153 'OS_USER_DOMAIN_NAME', 'Default')))
154 self.vnf['inputs'].update(dict(
155 keystone_project_domain_name=os.environ.get(
156 'OS_PROJECT_DOMAIN_NAME', 'Default')))
157 self.vnf['inputs'].update(dict(
158 region=os.environ.get('OS_REGION_NAME', 'RegionOne')))
159 self.vnf['inputs'].update(dict(
160 keystone_url=self.get_public_auth_url(self.orig_cloud)))
162 if self.deploy_vnf() and self.test_vnf():
165 self.result = 1/3 * 100
168 def deploy_vnf(self):
169 start_time = time.time()
170 self.__logger.info("Upload VNFD")
171 descriptor = self.vnf['descriptor']
172 self.util_info["cfy"] = self.cfy_client
173 self.util_info["cfy_manager_ip"] = self.fip.floating_ip_address
174 self.util_info["deployment_name"] = descriptor.get('name')
176 self.cfy_client.blueprints.upload(
177 descriptor.get('file_name'), descriptor.get('name'))
179 self.__logger.info("Create VNF Instance")
180 self.cfy_client.deployments.create(
181 descriptor.get('name'), descriptor.get('name'),
182 self.vnf.get('inputs'))
185 self.cfy_client, get_execution_id(
186 self.cfy_client, descriptor.get('name')),
187 self.__logger, timeout=7200)
189 self.__logger.info("Start the VNF Instance deployment")
190 execution = self.cfy_client.executions.start(
191 descriptor.get('name'), 'install')
193 execution = wait_for_execution(
194 self.cfy_client, execution, self.__logger)
196 duration = time.time() - start_time
198 self.__logger.info(execution)
199 if execution.status == 'terminated':
200 self.details['vnf'].update(status='PASS', duration=duration)
203 self.details['vnf'].update(status='FAIL', duration=duration)
208 start_time = time.time()
209 testing = vrouter_base.VrouterOnBoardingBase(
210 self.case_name, self.util, self.util_info)
211 result, test_result_data = testing.test_vnf()
212 duration = time.time() - start_time
214 self.details['test_vnf'].update(
215 status='PASS', result='OK', full_result=test_result_data,
218 self.details['test_vnf'].update(
219 status='FAIL', result='NG', full_result=test_result_data,
225 dep_name = self.vnf['descriptor'].get('name')
226 # kill existing execution
227 self.__logger.info('Deleting the current deployment')
228 exec_list = self.cfy_client.executions.list()
229 for execution in exec_list:
230 if execution['status'] == "started":
232 self.cfy_client.executions.cancel(
233 execution['id'], force=True)
234 except Exception: # pylint: disable=broad-except
235 self.__logger.warn("Can't cancel the current exec")
237 execution = self.cfy_client.executions.start(
238 dep_name, 'uninstall', parameters=dict(ignore_failure=True))
240 wait_for_execution(self.cfy_client, execution, self.__logger)
241 self.cfy_client.deployments.delete(
242 self.vnf['descriptor'].get('name'))
243 self.cfy_client.blueprints.delete(
244 self.vnf['descriptor'].get('name'))
245 except Exception: # pylint: disable=broad-except
246 self.__logger.exception("Some issue during the undeployment ..")
248 self.cloud.delete_image(self.image_alt)
250 self.orig_cloud.delete_flavor(self.flavor_alt.id)
251 super(CloudifyVrouter, self).clean()
254 def wait_for_execution(client, execution, logger, timeout=7200, ):
255 """Wait for a workflow execution on Cloudify Manager."""
256 # if execution already ended - return without waiting
257 if execution.status in Execution.END_STATES:
260 if timeout is not None:
261 deadline = time.time() + timeout
263 # Poll for execution status and execution logs, until execution ends
264 # and we receive an event of type in WORKFLOW_END_TYPES
268 execution_ended = False
270 event_list = client.events.list(
271 execution_id=execution.id, _offset=offset, _size=batch_size,
272 include_logs=True, sort='@timestamp').items
274 offset = offset + len(event_list)
275 for event in event_list:
276 logger.debug(event.get('message'))
278 if timeout is not None:
279 if time.time() > deadline:
281 'execution of operation {0} for deployment {1} '
282 'timed out'.format(execution.workflow_id,
283 execution.deployment_id))
285 # update the remaining timeout
286 timeout = deadline - time.time()
288 if not execution_ended:
289 execution = client.executions.get(execution.id)
290 execution_ended = execution.status in Execution.END_STATES
300 def get_execution_id(client, deployment_id):
302 Get the execution id of a env preparation.
303 network, security group, fip, VM creation
305 executions = client.executions.list(deployment_id=deployment_id)
306 for execution in executions:
307 if execution.workflow_id == 'create_deployment_environment':
309 raise RuntimeError('Failed to get create_deployment_environment '
310 'workflow execution.'
311 'Available executions: {0}'.format(executions))