d739335dcddfbd6ade620058ff130e598e48d06e
[functest.git] / functest / opnfv_tests / vnf / ims / cloudify_ims.py
1 #!/usr/bin/env python
2
3 # Copyright (c) 2016 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 import os
11 import sys
12 import time
13
14 import requests
15 import yaml
16
17 from functest.opnfv_tests.vnf.ims.clearwater import Clearwater
18 import functest.opnfv_tests.vnf.ims.clearwater_ims_base as clearwater_ims_base
19 from functest.opnfv_tests.vnf.ims.orchestrator_cloudify import Orchestrator
20 from functest.utils.constants import CONST
21 import functest.utils.functest_logger as ft_logger
22 import functest.utils.functest_utils as ft_utils
23 import functest.utils.openstack_utils as os_utils
24
25
26 class CloudifyIms(clearwater_ims_base.ClearwaterOnBoardingBase):
27
28     def __init__(self, project='functest', case_name='cloudify_ims',
29                  repo='', cmd=''):
30         super(CloudifyIms, self).__init__(project, case_name, repo, cmd)
31         self.logger = ft_logger.Logger(__name__).getLogger()
32
33         # Retrieve the configuration
34         try:
35             self.config = CONST.__getattribute__(
36                 'vnf_{}_config'.format(self.case_name))
37         except Exception:
38             raise Exception("VNF config file not found")
39
40         config_file = os.path.join(self.case_dir, self.config)
41         self.orchestrator = dict(
42             requirements=get_config("cloudify.requirements", config_file),
43             blueprint=get_config("cloudify.blueprint", config_file),
44             inputs=get_config("cloudify.inputs", config_file)
45         )
46         self.logger.debug("Orchestrator configuration: %s" % self.orchestrator)
47         self.vnf = dict(
48             blueprint=get_config("clearwater.blueprint", config_file),
49             deployment_name=get_config("clearwater.deployment_name",
50                                        config_file),
51             inputs=get_config("clearwater.inputs", config_file),
52             requirements=get_config("clearwater.requirements", config_file)
53         )
54         self.logger.debug("VNF configuration: %s" % self.vnf)
55
56         self.images = get_config("tenant_images", config_file)
57         self.logger.info("Images needed for vIMS: %s" % self.images)
58
59     def deploy_orchestrator(self, **kwargs):
60
61         self.logger.info("Additional pre-configuration steps")
62         self.neutron_client = os_utils.get_neutron_client(self.admin_creds)
63         self.glance_client = os_utils.get_glance_client(self.admin_creds)
64         self.keystone_client = os_utils.get_keystone_client(self.admin_creds)
65         self.nova_client = os_utils.get_nova_client(self.admin_creds)
66
67         # needs some images
68         self.logger.info("Upload some OS images if it doesn't exist")
69         temp_dir = os.path.join(self.data_dir, "tmp/")
70         for image_name, image_url in self.images.iteritems():
71             self.logger.info("image: %s, url: %s" % (image_name, image_url))
72             try:
73                 image_id = os_utils.get_image_id(self.glance_client,
74                                                  image_name)
75                 self.logger.debug("image_id: %s" % image_id)
76             except Exception:
77                 self.logger.error("Unexpected error: %s" % sys.exc_info()[0])
78
79             if image_id == '':
80                 self.logger.info("""%s image doesn't exist on glance repository. Try
81                 downloading this image and upload on glance !""" % image_name)
82                 image_id = download_and_add_image_on_glance(self.glance_client,
83                                                             image_name,
84                                                             image_url,
85                                                             temp_dir)
86             if image_id == '':
87                 self.step_failure(
88                     "Failed to find or upload required OS "
89                     "image for this deployment")
90         # Need to extend quota
91         self.logger.info("Update security group quota for this tenant")
92         tenant_id = os_utils.get_tenant_id(self.keystone_client,
93                                            self.tenant_name)
94         self.logger.debug("Tenant id found %s" % tenant_id)
95         if not os_utils.update_sg_quota(self.neutron_client,
96                                         tenant_id, 50, 100):
97             self.step_failure("Failed to update security group quota" +
98                               " for tenant " + self.tenant_name)
99         self.logger.debug("group quota extended")
100
101         # start the deployment of cloudify
102         public_auth_url = os_utils.get_endpoint('identity')
103
104         self.logger.debug("CFY inputs: %s" % self.orchestrator['inputs'])
105         cfy = Orchestrator(self.data_dir, self.orchestrator['inputs'])
106         self.orchestrator['object'] = cfy
107         self.logger.debug("Orchestrator object created")
108
109         self.logger.debug("Tenant name: %s" % self.tenant_name)
110
111         cfy.set_credentials(username=self.tenant_name,
112                             password=self.tenant_name,
113                             tenant_name=self.tenant_name,
114                             auth_url=public_auth_url)
115         self.logger.info("Credentials set in CFY")
116
117         # orchestrator VM flavor
118         self.logger.info("Check Flavor is available, if not create one")
119         self.logger.debug("Flavor details %s " %
120                           self.orchestrator['requirements']['ram_min'])
121         flavor_exist, flavor_id = os_utils.get_or_create_flavor(
122             "m1.large",
123             self.orchestrator['requirements']['ram_min'],
124             '50',
125             '2',
126             public=True)
127         self.logger.debug("Flavor id: %s" % flavor_id)
128
129         if not flavor_id:
130             self.logger.info("Available flavors are: ")
131             self.logger.info(self.nova_client.flavor.list())
132             self.step_failure("Failed to find required flavor"
133                               "for this deployment")
134         cfy.set_flavor_id(flavor_id)
135         self.logger.debug("Flavor OK")
136
137         # orchestrator VM image
138         self.logger.debug("Orchestrator image")
139         if 'os_image' in self.orchestrator['requirements'].keys():
140             image_id = os_utils.get_image_id(
141                 self.glance_client,
142                 self.orchestrator['requirements']['os_image'])
143             self.logger.debug("Orchestrator image id: %s" % image_id)
144             if image_id == '':
145                 self.logger.error("CFY image not found")
146                 self.step_failure("Failed to find required OS image"
147                                   " for cloudify manager")
148         else:
149             self.step_failure("Failed to find required OS image"
150                               " for cloudify manager")
151
152         cfy.set_image_id(image_id)
153         self.logger.debug("Orchestrator image set")
154
155         self.logger.debug("Get External network")
156         ext_net = os_utils.get_external_net(self.neutron_client)
157         self.logger.debug("External network: %s" % ext_net)
158         if not ext_net:
159             self.step_failure("Failed to get external network")
160
161         cfy.set_external_network_name(ext_net)
162         self.logger.debug("CFY External network set")
163
164         self.logger.debug("get resolvconf")
165         ns = ft_utils.get_resolvconf_ns()
166         if ns:
167             cfy.set_nameservers(ns)
168             self.logger.debug("Resolvconf set")
169
170         self.logger.info("Prepare virtualenv for cloudify-cli")
171         venv_scrit_dir = os.path.join(self.case_dir, "create_venv.sh")
172         cmd = "chmod +x " + venv_scrit_dir
173         ft_utils.execute_command(cmd)
174         time.sleep(3)
175         cmd = venv_scrit_dir + " " + self.data_dir
176         ft_utils.execute_command(cmd)
177
178         cfy.download_manager_blueprint(
179             self.orchestrator['blueprint']['url'],
180             self.orchestrator['blueprint']['branch'])
181
182         error = cfy.deploy_manager()
183         if error:
184             self.logger.error(error)
185             return {'status': 'FAIL', 'result': error}
186         else:
187             return {'status': 'PASS', 'result': ''}
188
189     def deploy_vnf(self):
190         cw = Clearwater(self.vnf['inputs'], self.orchestrator['object'],
191                         self.logger)
192         self.vnf['object'] = cw
193
194         self.logger.info("Collect flavor id for all clearwater vm")
195         flavor_exist, flavor_id = os_utils.get_or_create_flavor(
196             "m1.small",
197             self.vnf['requirements']['ram_min'],
198             '30',
199             '1',
200             public=True)
201         self.logger.debug("Flavor id: %s" % flavor_id)
202         if not flavor_id:
203             self.logger.info("Available flavors are: ")
204             self.logger.info(self.nova_client.flavor.list())
205             self.step_failure("Failed to find required flavor"
206                               " for this deployment")
207
208         cw.set_flavor_id(flavor_id)
209
210         # VMs image
211         if 'os_image' in self.vnf['requirements'].keys():
212             image_id = os_utils.get_image_id(
213                 self.glance_client, self.vnf['requirements']['os_image'])
214             if image_id == '':
215                 self.step_failure("Failed to find required OS image"
216                                   " for clearwater VMs")
217         else:
218             self.step_failure("Failed to find required OS image"
219                               " for clearwater VMs")
220
221         cw.set_image_id(image_id)
222
223         ext_net = os_utils.get_external_net(self.neutron_client)
224         if not ext_net:
225             self.step_failure("Failed to get external network")
226
227         cw.set_external_network_name(ext_net)
228
229         error = cw.deploy_vnf(self.vnf['blueprint'])
230         if error:
231             self.logger.error(error)
232             return {'status': 'FAIL', 'result': error}
233         else:
234             return {'status': 'PASS', 'result': ''}
235
236     def test_vnf(self):
237         script = "source {0}venv_cloudify/bin/activate; "
238         script += "cd {0}; "
239         script += "cfy status | grep -Eo \"([0-9]{{1,3}}\.){{3}}[0-9]{{1,3}}\""
240         cmd = "/bin/bash -c '" + script.format(self.data_dir) + "'"
241
242         try:
243             self.logger.debug("Trying to get clearwater manager IP ... ")
244             mgr_ip = os.popen(cmd).read()
245             mgr_ip = mgr_ip.splitlines()[0]
246         except Exception:
247             self.step_failure("Unable to retrieve the IP of the "
248                               "cloudify manager server !")
249
250         self.logger.info('Cloudify Manager: %s', mgr_ip)
251         api_url = 'http://{0}/api/v2/deployments/{1}/outputs'.format(
252                   mgr_ip, self.vnf['deployment_name'])
253         dep_outputs = requests.get(api_url)
254         self.logger.info(api_url)
255         outputs = dep_outputs.json()['outputs']
256         self.logger.info("Deployment outputs: %s", outputs)
257         dns_ip = outputs['dns_ip']
258         ellis_ip = outputs['ellis_ip']
259         self.config_ellis(ellis_ip)
260
261         if dns_ip != "":
262             vims_test_result = self.run_clearwater_live_test(
263                 dns_ip=dns_ip,
264                 public_domain=self.inputs["public_domain"])
265             if vims_test_result != '':
266                 return {'status': 'PASS', 'result': vims_test_result}
267             else:
268                 return {'status': 'FAIL', 'result': ''}
269
270     def clean(self):
271         self.vnf['object'].undeploy_vnf()
272         self.orchestrator['object'].undeploy_manager()
273         super(CloudifyIms, self).clean()
274
275     def main(self, **kwargs):
276         self.logger.info("Cloudify IMS VNF onboarding test starting")
277         self.execute()
278         self.logger.info("Cloudify IMS VNF onboarding test executed")
279         if self.criteria is "PASS":
280             return self.EX_OK
281         else:
282             return self.EX_RUN_ERROR
283
284     def run(self):
285         kwargs = {}
286         return self.main(**kwargs)
287
288
289 # ----------------------------------------------------------
290 #
291 #               YAML UTILS
292 #
293 # -----------------------------------------------------------
294 def get_config(parameter, file):
295     """
296     Returns the value of a given parameter in file.yaml
297     parameter must be given in string format with dots
298     Example: general.openstack.image_name
299     """
300     with open(file) as f:
301         file_yaml = yaml.safe_load(f)
302     f.close()
303     value = file_yaml
304     for element in parameter.split("."):
305         value = value.get(element)
306         if value is None:
307             raise ValueError("The parameter %s is not defined in"
308                              " reporting.yaml" % parameter)
309     return value
310
311
312 def download_and_add_image_on_glance(glance, image_name, image_url, data_dir):
313     dest_path = data_dir
314     if not os.path.exists(dest_path):
315         os.makedirs(dest_path)
316     file_name = image_url.rsplit('/')[-1]
317     if not ft_utils.download_url(image_url, dest_path):
318         return False
319
320     image = os_utils.create_glance_image(
321         glance, image_name, dest_path + file_name)
322     if not image:
323         return False
324
325     return image