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
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)
65 self.details['orchestrator'] = dict(
66 name=get_config("orchestrator.name", config_file),
67 version=get_config("orchestrator.version", config_file),
73 descriptor=get_config("vnf.descriptor", config_file),
74 inputs=get_config("vnf.inputs", config_file)
76 self.details['vnf'] = dict(
77 descriptor_version=self.vnf['descriptor']['version'],
78 name=get_config("vnf.name", config_file),
79 version=get_config("vnf.version", config_file),
81 self.__logger.debug("VNF configuration: %s", self.vnf)
83 self.details['test_vnf'] = dict(
84 name=get_config("vnf_test_suite.name", config_file),
85 version=get_config("vnf_test_suite.version", config_file)
89 self.flavor_alt = None
90 self.clearwater = None
92 def check_requirements(self):
93 if env.get('NEW_USER_ROLE').lower() == "admin":
95 "Defining NEW_USER_ROLE=admin will easily break the testcase "
96 "because Cloudify doesn't manage tenancy (e.g. subnet "
100 assert super(CloudifyIms, self).execute() == 0
101 # pylint: disable=too-many-locals,too-many-statements
103 Deploy Cloudify Manager.
105 network, security group, fip, VM creation
107 start_time = time.time()
108 self.orig_cloud.set_network_quotas(
109 self.project.project.name,
110 security_group=self.quota_security_group,
111 security_group_rule=self.quota_security_group_rule,
112 port=self.quota_port)
113 self.__logger.info("Put OpenStack creds in manager")
115 keystone_username=self.project.user.name,
116 keystone_password=self.project.password,
117 keystone_tenant_name=self.project.project.name,
118 keystone_url=self.get_public_auth_url(self.orig_cloud),
119 region=os.environ.get('OS_REGION_NAME', 'RegionOne'),
120 user_domain_name=os.environ.get(
121 'OS_USER_DOMAIN_NAME', 'Default'),
122 project_domain_name=os.environ.get(
123 'OS_PROJECT_DOMAIN_NAME', 'Default'))
124 self.__logger.info("Set creds for cloudify manager %s", cfy_creds)
125 secrets_list = self.cfy_client.secrets.list()
126 for k, val in six.iteritems(cfy_creds):
127 if not any(d.get('key', None) == k for d in secrets_list):
128 self.cfy_client.secrets.create(k, val)
130 self.cfy_client.secrets.update(k, val)
132 duration = time.time() - start_time
134 self.__logger.info("Put private keypair in manager")
135 scpc = scp.SCPClient(self.ssh.get_transport())
136 scpc.put(self.key_filename, remote_path='~/cloudify_ims.pem')
137 (_, stdout, stderr) = self.ssh.exec_command(
138 "sudo cp ~/cloudify_ims.pem /etc/cloudify/ && "
139 "sudo chmod 444 /etc/cloudify/cloudify_ims.pem && "
140 "sudo yum install -y gcc python-devel python-cmd2 && "
142 self.__logger.info("output:\n%s", stdout.read())
143 self.__logger.info("error:\n%s", stderr.read())
145 self.details['orchestrator'].update(status='PASS', duration=duration)
147 self.vnf['inputs'].update(dict(
148 external_network_name=self.ext_net.name,
149 network_name=self.network.name,
150 key_pair_name=self.keypair.name
152 if (self.deploy_vnf() and self.test_vnf()):
155 self.result = 1/3 * 100
158 def deploy_vnf(self):
159 """Deploy Clearwater IMS."""
160 start_time = time.time()
162 self.cloud.create_security_group_rule(
163 'default', port_range_min=22, port_range_max=22,
164 protocol='tcp', direction='ingress')
166 self.__logger.info("Upload VNFD")
167 descriptor = self.vnf['descriptor']
168 self.cfy_client.blueprints.upload(
169 descriptor.get('file_name'), descriptor.get('name'))
171 self.image_alt = self.publish_image_alt()
172 self.flavor_alt = self.create_flavor_alt()
173 self.vnf['inputs'].update(dict(
174 image_id=self.image_alt.id,
175 flavor_id=self.flavor_alt.id,
178 self.__logger.info("Create VNF Instance")
179 self.cfy_client.deployments.create(
180 descriptor.get('name'), descriptor.get('name'),
181 self.vnf.get('inputs'))
185 get_execution_id(self.cfy_client, descriptor.get('name')),
186 self.__logger, timeout=300)
188 self.__logger.info("Start the VNF Instance deployment")
189 execution = self.cfy_client.executions.start(
190 descriptor.get('name'), 'install')
192 execution = wait_for_execution(
193 self.cfy_client, execution, self.__logger, timeout=3600)
195 self.__logger.info(execution)
196 if execution.status != 'terminated':
197 self.details['vnf'].update(status='FAIL',
198 duration=time.time() - start_time)
201 ellis_ip = self.cfy_client.deployments.outputs.get(
202 self.vnf['descriptor'].get('name'))['outputs']['ellis_ip']
203 self.clearwater = clearwater.ClearwaterTesting(self.case_name,
205 self.clearwater.availability_check_by_creating_numbers()
207 self.details['vnf'].update(status='PASS',
208 duration=time.time() - start_time)
209 self.result += 1/3 * 100
213 """Run test on clearwater ims instance."""
214 start_time = time.time()
216 dns_ip = self.cfy_client.deployments.outputs.get(
217 self.vnf['descriptor'].get('name'))['outputs']['dns_ip']
222 short_result = self.clearwater.run_clearwater_live_test(
224 public_domain=self.vnf['inputs']["public_domain"])
225 duration = time.time() - start_time
226 self.__logger.info(short_result)
227 self.details['test_vnf'].update(result=short_result,
230 vnf_test_rate = short_result['passed'] / (
231 short_result['total'] - short_result['skipped'])
232 # orchestrator + vnf + test_vnf
233 self.result += vnf_test_rate / 3 * 100
234 except ZeroDivisionError:
235 self.__logger.error("No test has been executed")
236 self.details['test_vnf'].update(status='FAIL')
238 except Exception: # pylint: disable=broad-except
239 self.__logger.exception("Cannot calculate results")
240 self.details['test_vnf'].update(status='FAIL')
242 return True if vnf_test_rate > 0 else False
245 """Clean created objects/functions."""
247 dep_name = self.vnf['descriptor'].get('name')
248 # kill existing execution
249 self.__logger.info('Deleting the current deployment')
250 exec_list = self.cfy_client.executions.list(dep_name)
251 for execution in exec_list:
252 if execution['status'] == "started":
254 self.cfy_client.executions.cancel(
255 execution['id'], force=True)
256 except Exception: # pylint: disable=broad-except
257 self.__logger.warn("Can't cancel the current exec")
259 execution = self.cfy_client.executions.start(
262 parameters=dict(ignore_failure=True),
265 wait_for_execution(self.cfy_client, execution, self.__logger)
266 self.cfy_client.deployments.delete(
267 self.vnf['descriptor'].get('name'))
268 self.cfy_client.blueprints.delete(
269 self.vnf['descriptor'].get('name'))
270 except Exception: # pylint: disable=broad-except
271 self.__logger.exception("Some issue during the undeployment ..")
273 super(CloudifyIms, self).clean()
276 # ----------------------------------------------------------
280 # -----------------------------------------------------------
281 def get_config(parameter, file_path):
283 Get config parameter.
285 Returns the value of a given parameter in file.yaml
286 parameter must be given in string format with dots
287 Example: general.openstack.image_name
289 with open(file_path) as config_file:
290 file_yaml = yaml.safe_load(config_file)
293 for element in parameter.split("."):
294 value = value.get(element)
296 raise ValueError("The parameter %s is not defined in"
297 " reporting.yaml" % parameter)
301 def wait_for_execution(client, execution, logger, timeout=3600, ):
302 """Wait for a workflow execution on Cloudify Manager."""
303 # if execution already ended - return without waiting
304 if execution.status in Execution.END_STATES:
307 if timeout is not None:
308 deadline = time.time() + timeout
310 # Poll for execution status and execution logs, until execution ends
311 # and we receive an event of type in WORKFLOW_END_TYPES
315 execution_ended = False
317 event_list = client.events.list(
318 execution_id=execution.id,
322 sort='@timestamp').items
324 offset = offset + len(event_list)
325 for event in event_list:
326 logger.debug(event.get('message'))
328 if timeout is not None:
329 if time.time() > deadline:
331 'execution of operation {0} for deployment {1} '
332 'timed out'.format(execution.workflow_id,
333 execution.deployment_id))
335 # update the remaining timeout
336 timeout = deadline - time.time()
338 if not execution_ended:
339 execution = client.executions.get(execution.id)
340 execution_ended = execution.status in Execution.END_STATES
350 def get_execution_id(client, deployment_id):
352 Get the execution id of a env preparation.
354 network, security group, fip, VM creation
356 executions = client.executions.list(deployment_id=deployment_id)
357 for execution in executions:
358 if execution.workflow_id == 'create_deployment_environment':
360 raise RuntimeError('Failed to get create_deployment_environment '
361 'workflow execution.'
362 'Available executions: {0}'.format(executions))