New Heat IMS testcase
[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
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
65         self.details['orchestrator'] = dict(
66             name=get_config("orchestrator.name", config_file),
67             version=get_config("orchestrator.version", config_file),
68             status='ERROR',
69             result=''
70         )
71
72         self.vnf = dict(
73             descriptor=get_config("vnf.descriptor", config_file),
74             inputs=get_config("vnf.inputs", config_file)
75         )
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),
80         )
81         self.__logger.debug("VNF configuration: %s", self.vnf)
82
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)
86         )
87
88         self.image_alt = None
89         self.flavor_alt = None
90         self.clearwater = None
91
92     def check_requirements(self):
93         if env.get('NEW_USER_ROLE').lower() == "admin":
94             self.__logger.warn(
95                 "Defining NEW_USER_ROLE=admin will easily break the testcase "
96                 "because Cloudify doesn't manage tenancy (e.g. subnet  "
97                 "overlapping)")
98
99     def execute(self):
100         assert super(CloudifyIms, self).execute() == 0
101         # pylint: disable=too-many-locals,too-many-statements
102         """
103         Deploy Cloudify Manager.
104
105         network, security group, fip, VM creation
106         """
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")
114         cfy_creds = dict(
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)
129             else:
130                 self.cfy_client.secrets.update(k, val)
131
132         duration = time.time() - start_time
133
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 && "
141             "cfy status")
142         self.__logger.info("output:\n%s", stdout.read())
143         self.__logger.info("error:\n%s", stderr.read())
144
145         self.details['orchestrator'].update(status='PASS', duration=duration)
146
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
151         ))
152         if (self.deploy_vnf() and self.test_vnf()):
153             self.result = 100
154             return 0
155         self.result = 1/3 * 100
156         return 1
157
158     def deploy_vnf(self):
159         """Deploy Clearwater IMS."""
160         start_time = time.time()
161
162         self.cloud.create_security_group_rule(
163             'default', port_range_min=22, port_range_max=22,
164             protocol='tcp', direction='ingress')
165
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'))
170
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,
176         ))
177
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'))
182
183         wait_for_execution(
184             self.cfy_client,
185             get_execution_id(self.cfy_client, descriptor.get('name')),
186             self.__logger, timeout=300)
187
188         self.__logger.info("Start the VNF Instance deployment")
189         execution = self.cfy_client.executions.start(
190             descriptor.get('name'), 'install')
191         # Show execution log
192         execution = wait_for_execution(
193             self.cfy_client, execution, self.__logger, timeout=3600)
194
195         self.__logger.info(execution)
196         if execution.status != 'terminated':
197             self.details['vnf'].update(status='FAIL',
198                                        duration=time.time() - start_time)
199             return False
200
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,
204                                                        ellis_ip)
205         self.clearwater.availability_check_by_creating_numbers()
206
207         self.details['vnf'].update(status='PASS',
208                                    duration=time.time() - start_time)
209         self.result += 1/3 * 100
210         return True
211
212     def test_vnf(self):
213         """Run test on clearwater ims instance."""
214         start_time = time.time()
215
216         dns_ip = self.cfy_client.deployments.outputs.get(
217             self.vnf['descriptor'].get('name'))['outputs']['dns_ip']
218
219         if not dns_ip:
220             return False
221
222         short_result = self.clearwater.run_clearwater_live_test(
223             dns_ip=dns_ip,
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,
228                                         duration=duration)
229         try:
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')
237             return False
238         except Exception:  # pylint: disable=broad-except
239             self.__logger.exception("Cannot calculate results")
240             self.details['test_vnf'].update(status='FAIL')
241             return False
242         return True if vnf_test_rate > 0 else False
243
244     def clean(self):
245         """Clean created objects/functions."""
246         try:
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":
253                     try:
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")
258
259             execution = self.cfy_client.executions.start(
260                 dep_name,
261                 'uninstall',
262                 parameters=dict(ignore_failure=True),
263                 force=True)
264
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 ..")
272
273         super(CloudifyIms, self).clean()
274
275
276 # ----------------------------------------------------------
277 #
278 #               YAML UTILS
279 #
280 # -----------------------------------------------------------
281 def get_config(parameter, file_path):
282     """
283     Get config parameter.
284
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
288     """
289     with open(file_path) as config_file:
290         file_yaml = yaml.safe_load(config_file)
291     config_file.close()
292     value = file_yaml
293     for element in parameter.split("."):
294         value = value.get(element)
295         if value is None:
296             raise ValueError("The parameter %s is not defined in"
297                              " reporting.yaml" % parameter)
298     return value
299
300
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:
305         return execution
306
307     if timeout is not None:
308         deadline = time.time() + timeout
309
310     # Poll for execution status and execution logs, until execution ends
311     # and we receive an event of type in WORKFLOW_END_TYPES
312     offset = 0
313     batch_size = 50
314     event_list = []
315     execution_ended = False
316     while True:
317         event_list = client.events.list(
318             execution_id=execution.id,
319             _offset=offset,
320             _size=batch_size,
321             include_logs=True,
322             sort='@timestamp').items
323
324         offset = offset + len(event_list)
325         for event in event_list:
326             logger.debug(event.get('message'))
327
328         if timeout is not None:
329             if time.time() > deadline:
330                 raise RuntimeError(
331                     'execution of operation {0} for deployment {1} '
332                     'timed out'.format(execution.workflow_id,
333                                        execution.deployment_id))
334             else:
335                 # update the remaining timeout
336                 timeout = deadline - time.time()
337
338         if not execution_ended:
339             execution = client.executions.get(execution.id)
340             execution_ended = execution.status in Execution.END_STATES
341
342         if execution_ended:
343             break
344
345         time.sleep(5)
346
347     return execution
348
349
350 def get_execution_id(client, deployment_id):
351     """
352     Get the execution id of a env preparation.
353
354     network, security group, fip, VM creation
355     """
356     executions = client.executions.list(deployment_id=deployment_id)
357     for execution in executions:
358         if execution.workflow_id == 'create_deployment_environment':
359             return execution
360     raise RuntimeError('Failed to get create_deployment_environment '
361                        'workflow execution.'
362                        'Available executions: {0}'.format(executions))