36862bd4356a389450469a8d1262733d48617602
[functest.git] / functest / opnfv_tests / vnf / ims / cloudify_ims.py
1 #!/usr/bin/env python
2
3 # Copyright (c) 2017 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 """CloudifyIms testcase implementation."""
11
12 from __future__ import division
13
14 import logging
15 import os
16 import time
17 import yaml
18
19 from cloudify_rest_client.executions import Execution
20 import pkg_resources
21 import scp
22 import six
23
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
28
29 __author__ = "Valentin Boucher <valentin.boucher@orange.com>"
30
31
32 class CloudifyIms(cloudify.Cloudify):
33     """Clearwater vIMS deployed with Cloudify Orchestrator Case."""
34
35     __logger = logging.getLogger(__name__)
36
37     filename_alt = ('/home/opnfv/functest/images/'
38                     'ubuntu-14.04-server-cloudimg-amd64-disk1.img')
39
40     flavor_alt_ram = 2048
41     flavor_alt_vcpus = 2
42     flavor_alt_disk = 25
43
44     quota_security_group = 20
45     quota_security_group_rule = 100
46     quota_port = 50
47
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)
53
54         # Retrieve the configuration
55         try:
56             self.config = getattr(
57                 config.CONF, 'vnf_{}_config'.format(self.case_name))
58         except Exception:
59             raise Exception("VNF config file not found")
60
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),
66         )
67         self.details['orchestrator'] = dict(
68             name=get_config("orchestrator.name", config_file),
69             version=get_config("orchestrator.version", config_file),
70             status='ERROR',
71             result=''
72         )
73         self.__logger.debug("Orchestrator configuration %s", self.orchestrator)
74         self.vnf = dict(
75             descriptor=get_config("vnf.descriptor", config_file),
76             inputs=get_config("vnf.inputs", config_file),
77             requirements=get_config("vnf.requirements", config_file)
78         )
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),
83         )
84         self.__logger.debug("VNF configuration: %s", self.vnf)
85
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)
89         )
90
91         self.image_alt = None
92         self.flavor_alt = None
93
94     def check_requirements(self):
95         if env.get('NEW_USER_ROLE').lower() == "admin":
96             self.__logger.warn(
97                 "Defining NEW_USER_ROLE=admin will easily break the testcase "
98                 "because Cloudify doesn't manage tenancy (e.g. subnet  "
99                 "overlapping)")
100
101     def execute(self):
102         assert super(CloudifyIms, self).execute() == 0
103         # pylint: disable=too-many-locals,too-many-statements
104         """
105         Deploy Cloudify Manager.
106
107         network, security group, fip, VM creation
108         """
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")
116         cfy_creds = dict(
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)
131             else:
132                 self.cfy_client.secrets.update(k, val)
133
134         duration = time.time() - start_time
135
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 && "
143             "cfy status")
144         self.__logger.info("output:\n%s", stdout.read())
145         self.__logger.info("error:\n%s", stderr.read())
146
147         self.details['orchestrator'].update(status='PASS', duration=duration)
148
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
153         ))
154         if (self.deploy_vnf() and self.test_vnf()):
155             self.result = 100
156             return 0
157         self.result = 1/3 * 100
158         return 1
159
160     def deploy_vnf(self):
161         """Deploy Clearwater IMS."""
162         start_time = time.time()
163
164         self.cloud.create_security_group_rule(
165             'default', port_range_min=22, port_range_max=22,
166             protocol='tcp', direction='ingress')
167
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'))
172
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,
178         ))
179
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'))
184
185         wait_for_execution(
186             self.cfy_client,
187             get_execution_id(self.cfy_client, descriptor.get('name')),
188             self.__logger, timeout=300)
189
190         self.__logger.info("Start the VNF Instance deployment")
191         execution = self.cfy_client.executions.start(
192             descriptor.get('name'), 'install')
193         # Show execution log
194         execution = wait_for_execution(
195             self.cfy_client, execution, self.__logger, timeout=3600)
196
197         duration = time.time() - start_time
198
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
203             result = True
204         else:
205             self.details['vnf'].update(status='FAIL', duration=duration)
206             result = False
207         return result
208
209     def test_vnf(self):
210         """Run test on clearwater ims instance."""
211         start_time = time.time()
212
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)
219
220         if not dns_ip:
221             return False
222
223         short_result = testing.run_clearwater_live_test(
224             dns_ip=dns_ip,
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,
229                                         duration=duration)
230         try:
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')
238             return False
239         except Exception:  # pylint: disable=broad-except
240             self.__logger.exception("Cannot calculate results")
241             self.details['test_vnf'].update(status='FAIL')
242             return False
243         return True if vnf_test_rate > 0 else False
244
245     def clean(self):
246         """Clean created objects/functions."""
247         try:
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":
254                     try:
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")
259
260             execution = self.cfy_client.executions.start(
261                 dep_name,
262                 'uninstall',
263                 parameters=dict(ignore_failure=True),
264                 force=True)
265
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 ..")
273
274         super(CloudifyIms, self).clean()
275
276
277 # ----------------------------------------------------------
278 #
279 #               YAML UTILS
280 #
281 # -----------------------------------------------------------
282 def get_config(parameter, file_path):
283     """
284     Get config parameter.
285
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
289     """
290     with open(file_path) as config_file:
291         file_yaml = yaml.safe_load(config_file)
292     config_file.close()
293     value = file_yaml
294     for element in parameter.split("."):
295         value = value.get(element)
296         if value is None:
297             raise ValueError("The parameter %s is not defined in"
298                              " reporting.yaml" % parameter)
299     return value
300
301
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:
306         return execution
307
308     if timeout is not None:
309         deadline = time.time() + timeout
310
311     # Poll for execution status and execution logs, until execution ends
312     # and we receive an event of type in WORKFLOW_END_TYPES
313     offset = 0
314     batch_size = 50
315     event_list = []
316     execution_ended = False
317     while True:
318         event_list = client.events.list(
319             execution_id=execution.id,
320             _offset=offset,
321             _size=batch_size,
322             include_logs=True,
323             sort='@timestamp').items
324
325         offset = offset + len(event_list)
326         for event in event_list:
327             logger.debug(event.get('message'))
328
329         if timeout is not None:
330             if time.time() > deadline:
331                 raise RuntimeError(
332                     'execution of operation {0} for deployment {1} '
333                     'timed out'.format(execution.workflow_id,
334                                        execution.deployment_id))
335             else:
336                 # update the remaining timeout
337                 timeout = deadline - time.time()
338
339         if not execution_ended:
340             execution = client.executions.get(execution.id)
341             execution_ended = execution.status in Execution.END_STATES
342
343         if execution_ended:
344             break
345
346         time.sleep(5)
347
348     return execution
349
350
351 def get_execution_id(client, deployment_id):
352     """
353     Get the execution id of a env preparation.
354
355     network, security group, fip, VM creation
356     """
357     executions = client.executions.list(deployment_id=deployment_id)
358     for execution in executions:
359         if execution.workflow_id == 'create_deployment_environment':
360             return execution
361     raise RuntimeError('Failed to get create_deployment_environment '
362                        'workflow execution.'
363                        'Available executions: {0}'.format(executions))