3 # Copyright (c) 2017 Orange 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 """CloudifyIms testcase implementation."""
12 from __future__ import division
19 from cloudify_rest_client.executions import Execution
24 from functest.core import cloudify
25 from functest.opnfv_tests.vnf.ims import clearwater_ims_base
26 from functest.utils import config
27 from functest.utils import env
29 __author__ = "Valentin Boucher <valentin.boucher@orange.com>"
32 class CloudifyIms(cloudify.Cloudify):
33 """Clearwater vIMS deployed with Cloudify Orchestrator Case."""
35 __logger = logging.getLogger(__name__)
37 filename_alt = ('/home/opnfv/functest/images/'
38 'ubuntu-14.04-server-cloudimg-amd64-disk1.img')
44 quota_security_group = 20
45 quota_security_group_rule = 100
48 def __init__(self, **kwargs):
49 """Initialize CloudifyIms testcase object."""
50 if "case_name" not in kwargs:
51 kwargs["case_name"] = "cloudify_ims"
52 super(CloudifyIms, self).__init__(**kwargs)
54 # Retrieve the configuration
56 self.config = getattr(
57 config.CONF, 'vnf_{}_config'.format(self.case_name))
59 raise Exception("VNF config file not found")
61 self.case_dir = pkg_resources.resource_filename(
62 'functest', 'opnfv_tests/vnf/ims')
63 config_file = os.path.join(self.case_dir, self.config)
64 self.orchestrator = dict(
65 requirements=get_config("orchestrator.requirements", config_file),
67 self.details['orchestrator'] = dict(
68 name=get_config("orchestrator.name", config_file),
69 version=get_config("orchestrator.version", config_file),
73 self.__logger.debug("Orchestrator configuration %s", self.orchestrator)
75 descriptor=get_config("vnf.descriptor", config_file),
76 inputs=get_config("vnf.inputs", config_file),
77 requirements=get_config("vnf.requirements", config_file)
79 self.details['vnf'] = dict(
80 descriptor_version=self.vnf['descriptor']['version'],
81 name=get_config("vnf.name", config_file),
82 version=get_config("vnf.version", config_file),
84 self.__logger.debug("VNF configuration: %s", self.vnf)
86 self.details['test_vnf'] = dict(
87 name=get_config("vnf_test_suite.name", config_file),
88 version=get_config("vnf_test_suite.version", config_file)
92 self.flavor_alt = None
94 def check_requirements(self):
95 if env.get('NEW_USER_ROLE').lower() == "admin":
97 "Defining NEW_USER_ROLE=admin will easily break the testcase "
98 "because Cloudify doesn't manage tenancy (e.g. subnet "
102 assert super(CloudifyIms, self).execute() == 0
103 # pylint: disable=too-many-locals,too-many-statements
105 Deploy Cloudify Manager.
107 network, security group, fip, VM creation
109 start_time = time.time()
110 self.orig_cloud.set_network_quotas(
111 self.project.project.name,
112 security_group=self.quota_security_group,
113 security_group_rule=self.quota_security_group_rule,
114 port=self.quota_port)
115 self.__logger.info("Put OpenStack creds in manager")
117 keystone_username=self.project.user.name,
118 keystone_password=self.project.password,
119 keystone_tenant_name=self.project.project.name,
120 keystone_url=self.get_public_auth_url(self.orig_cloud),
121 region=os.environ.get('OS_REGION_NAME', 'RegionOne'),
122 user_domain_name=os.environ.get(
123 'OS_USER_DOMAIN_NAME', 'Default'),
124 project_domain_name=os.environ.get(
125 'OS_PROJECT_DOMAIN_NAME', 'Default'))
126 self.__logger.info("Set creds for cloudify manager %s", cfy_creds)
127 secrets_list = self.cfy_client.secrets.list()
128 for k, val in six.iteritems(cfy_creds):
129 if not any(d.get('key', None) == k for d in secrets_list):
130 self.cfy_client.secrets.create(k, val)
132 self.cfy_client.secrets.update(k, val)
134 duration = time.time() - start_time
136 self.__logger.info("Put private keypair in manager")
137 scpc = scp.SCPClient(self.ssh.get_transport())
138 scpc.put(self.key_filename, remote_path='~/cloudify_ims.pem')
139 (_, stdout, stderr) = self.ssh.exec_command(
140 "sudo cp ~/cloudify_ims.pem /etc/cloudify/ && "
141 "sudo chmod 444 /etc/cloudify/cloudify_ims.pem && "
142 "sudo yum install -y gcc python-devel python-cmd2 && "
144 self.__logger.info("output:\n%s", stdout.read())
145 self.__logger.info("error:\n%s", stderr.read())
147 self.details['orchestrator'].update(status='PASS', duration=duration)
149 self.vnf['inputs'].update(dict(
150 external_network_name=self.ext_net.name,
151 network_name=self.network.name,
152 key_pair_name=self.keypair.name
154 if (self.deploy_vnf() and self.test_vnf()):
157 self.result = 1/3 * 100
160 def deploy_vnf(self):
161 """Deploy Clearwater IMS."""
162 start_time = time.time()
164 self.cloud.create_security_group_rule(
165 'default', port_range_min=22, port_range_max=22,
166 protocol='tcp', direction='ingress')
168 self.__logger.info("Upload VNFD")
169 descriptor = self.vnf['descriptor']
170 self.cfy_client.blueprints.upload(
171 descriptor.get('file_name'), descriptor.get('name'))
173 self.image_alt = self.publish_image_alt()
174 self.flavor_alt = self.create_flavor_alt()
175 self.vnf['inputs'].update(dict(
176 image_id=self.image_alt.id,
177 flavor_id=self.flavor_alt.id,
180 self.__logger.info("Create VNF Instance")
181 self.cfy_client.deployments.create(
182 descriptor.get('name'), descriptor.get('name'),
183 self.vnf.get('inputs'))
187 get_execution_id(self.cfy_client, descriptor.get('name')),
188 self.__logger, timeout=300)
190 self.__logger.info("Start the VNF Instance deployment")
191 execution = self.cfy_client.executions.start(
192 descriptor.get('name'), 'install')
194 execution = wait_for_execution(
195 self.cfy_client, execution, self.__logger, timeout=3600)
197 duration = time.time() - start_time
199 self.__logger.info(execution)
200 if execution.status == 'terminated':
201 self.details['vnf'].update(status='PASS', duration=duration)
202 self.result += 1/3 * 100
205 self.details['vnf'].update(status='FAIL', duration=duration)
210 """Run test on clearwater ims instance."""
211 start_time = time.time()
213 testing = clearwater_ims_base.ClearwaterOnBoardingBase(self.case_name)
214 outputs = self.cfy_client.deployments.outputs.get(
215 self.vnf['descriptor'].get('name'))['outputs']
216 dns_ip = outputs['dns_ip']
217 ellis_ip = outputs['ellis_ip']
218 testing.config_ellis(ellis_ip)
223 short_result = testing.run_clearwater_live_test(
225 public_domain=self.vnf['inputs']["public_domain"])
226 duration = time.time() - start_time
227 self.__logger.info(short_result)
228 self.details['test_vnf'].update(result=short_result,
231 vnf_test_rate = short_result['passed'] / (
232 short_result['total'] - short_result['skipped'])
233 # orchestrator + vnf + test_vnf
234 self.result += vnf_test_rate / 3 * 100
235 except ZeroDivisionError:
236 self.__logger.error("No test has been executed")
237 self.details['test_vnf'].update(status='FAIL')
239 except Exception: # pylint: disable=broad-except
240 self.__logger.exception("Cannot calculate results")
241 self.details['test_vnf'].update(status='FAIL')
243 return True if vnf_test_rate > 0 else False
246 """Clean created objects/functions."""
248 dep_name = self.vnf['descriptor'].get('name')
249 # kill existing execution
250 self.__logger.info('Deleting the current deployment')
251 exec_list = self.cfy_client.executions.list(dep_name)
252 for execution in exec_list:
253 if execution['status'] == "started":
255 self.cfy_client.executions.cancel(
256 execution['id'], force=True)
257 except Exception: # pylint: disable=broad-except
258 self.__logger.warn("Can't cancel the current exec")
260 execution = self.cfy_client.executions.start(
263 parameters=dict(ignore_failure=True),
266 wait_for_execution(self.cfy_client, execution, self.__logger)
267 self.cfy_client.deployments.delete(
268 self.vnf['descriptor'].get('name'))
269 self.cfy_client.blueprints.delete(
270 self.vnf['descriptor'].get('name'))
271 except Exception: # pylint: disable=broad-except
272 self.__logger.exception("Some issue during the undeployment ..")
274 super(CloudifyIms, self).clean()
277 # ----------------------------------------------------------
281 # -----------------------------------------------------------
282 def get_config(parameter, file_path):
284 Get config parameter.
286 Returns the value of a given parameter in file.yaml
287 parameter must be given in string format with dots
288 Example: general.openstack.image_name
290 with open(file_path) as config_file:
291 file_yaml = yaml.safe_load(config_file)
294 for element in parameter.split("."):
295 value = value.get(element)
297 raise ValueError("The parameter %s is not defined in"
298 " reporting.yaml" % parameter)
302 def wait_for_execution(client, execution, logger, timeout=3600, ):
303 """Wait for a workflow execution on Cloudify Manager."""
304 # if execution already ended - return without waiting
305 if execution.status in Execution.END_STATES:
308 if timeout is not None:
309 deadline = time.time() + timeout
311 # Poll for execution status and execution logs, until execution ends
312 # and we receive an event of type in WORKFLOW_END_TYPES
316 execution_ended = False
318 event_list = client.events.list(
319 execution_id=execution.id,
323 sort='@timestamp').items
325 offset = offset + len(event_list)
326 for event in event_list:
327 logger.debug(event.get('message'))
329 if timeout is not None:
330 if time.time() > deadline:
332 'execution of operation {0} for deployment {1} '
333 'timed out'.format(execution.workflow_id,
334 execution.deployment_id))
336 # update the remaining timeout
337 timeout = deadline - time.time()
339 if not execution_ended:
340 execution = client.executions.get(execution.id)
341 execution_ended = execution.status in Execution.END_STATES
351 def get_execution_id(client, deployment_id):
353 Get the execution id of a env preparation.
355 network, security group, fip, VM creation
357 executions = client.executions.list(deployment_id=deployment_id)
358 for execution in executions:
359 if execution.workflow_id == 'create_deployment_environment':
361 raise RuntimeError('Failed to get create_deployment_environment '
362 'workflow execution.'
363 'Available executions: {0}'.format(executions))