3 # Copyright (c) 2016 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
18 import functest.core.vnf_base as vnf_base
19 import functest.utils.functest_logger as ft_logger
20 import functest.utils.functest_utils as ft_utils
21 import functest.utils.openstack_utils as os_utils
23 from clearwater import Clearwater
24 from functest.utils.constants import CONST
25 from orchestrator_cloudify import Orchestrator
28 class ImsVnf(vnf_base.VnfOnBoardingBase):
30 def __init__(self, project='functest', case='cloudify_ims',
32 super(ImsVnf, self).__init__(project, case, repo, cmd)
33 self.logger = ft_logger.Logger("vIMS").getLogger()
34 self.case_dir = os.path.join(CONST.dir_functest_test, 'vnf/ims/')
35 self.data_dir = CONST.dir_ims_data
36 self.test_dir = CONST.dir_repo_vims_test
38 # Retrieve the configuration
40 self.config = CONST.__getattribute__(
41 'vnf_{}_config'.format(self.case_name))
43 raise Exception("VNF config file not found")
45 config_file = self.case_dir + self.config
46 self.orchestrator = dict(
47 requirements=get_config("cloudify.requirements", config_file),
48 blueprint=get_config("cloudify.blueprint", config_file),
49 inputs=get_config("cloudify.inputs", config_file)
51 self.logger.debug("Orchestrator configuration: %s" % self.orchestrator)
53 blueprint=get_config("clearwater.blueprint", config_file),
54 deployment_name=get_config("clearwater.deployment_name",
56 inputs=get_config("clearwater.inputs", config_file),
57 requirements=get_config("clearwater.requirements", config_file)
59 self.logger.debug("VNF configuration: %s" % self.vnf)
61 self.images = get_config("tenant_images", config_file)
62 self.logger.info("Images needed for vIMS: %s" % self.images)
64 # vIMS Data directory creation
65 if not os.path.exists(self.data_dir):
66 os.makedirs(self.data_dir)
68 def deploy_orchestrator(self, **kwargs):
70 self.logger.info("Additional pre-configuration steps")
71 self.neutron_client = os_utils.get_neutron_client(self.creds)
72 self.glance_client = os_utils.get_glance_client(self.creds)
73 self.keystone_client = os_utils.get_keystone_client(self.creds)
74 self.nova_client = os_utils.get_nova_client(self.creds)
77 self.logger.info("Upload some OS images if it doesn't exist")
78 temp_dir = os.path.join(self.data_dir, "tmp/")
79 for image_name, image_url in self.images.iteritems():
80 self.logger.info("image: %s, url: %s" % (image_name, image_url))
82 image_id = os_utils.get_image_id(self.glance_client,
84 self.logger.debug("image_id: %s" % image_id)
86 self.logger.error("Unexpected error: %s" % sys.exc_info()[0])
89 self.logger.info("""%s image doesn't exist on glance repository. Try
90 downloading this image and upload on glance !""" % image_name)
91 image_id = download_and_add_image_on_glance(self.glance_client,
97 "Failed to find or upload required OS "
98 "image for this deployment")
99 # Need to extend quota
100 self.logger.info("Update security group quota for this tenant")
101 tenant_id = os_utils.get_tenant_id(self.keystone_client,
103 self.logger.debug("Tenant id found %s" % tenant_id)
104 if not os_utils.update_sg_quota(self.neutron_client,
106 self.step_failure("Failed to update security group quota" +
107 " for tenant " + self.tenant_name)
108 self.logger.debug("group quota extended")
110 # start the deployment of cloudify
111 public_auth_url = os_utils.get_endpoint('identity')
113 self.logger.debug("CFY inputs: %s" % self.orchestrator['inputs'])
114 cfy = Orchestrator(self.data_dir, self.orchestrator['inputs'])
115 self.orchestrator['object'] = cfy
116 self.logger.debug("Orchestrator object created")
118 self.logger.debug("Tenant name: %s" % self.tenant_name)
120 cfy.set_credentials(username=self.tenant_name,
121 password=self.tenant_name,
122 tenant_name=self.tenant_name,
123 auth_url=public_auth_url)
124 self.logger.info("Credentials set in CFY")
126 # orchestrator VM flavor
127 self.logger.info("Check Flavor is available, if not create one")
128 self.logger.debug("Flavor details %s " %
129 self.orchestrator['requirements']['ram_min'])
130 flavor_exist, flavor_id = os_utils.get_or_create_flavor(
132 self.orchestrator['requirements']['ram_min'],
136 self.logger.debug("Flavor id: %s" % flavor_id)
139 self.logger.info("Available flavors are: ")
140 self.logger.info(self.nova_client.flavor.list())
141 self.step_failure("Failed to find required flavor"
142 "for this deployment")
143 cfy.set_flavor_id(flavor_id)
144 self.logger.debug("Flavor OK")
146 # orchestrator VM image
147 self.logger.debug("Orchestrator image")
148 if 'os_image' in self.orchestrator['requirements'].keys():
149 image_id = os_utils.get_image_id(
151 self.orchestrator['requirements']['os_image'])
152 self.logger.debug("Orchestrator image id: %s" % image_id)
154 self.logger.error("CFY image not found")
155 self.step_failure("Failed to find required OS image"
156 " for cloudify manager")
158 self.step_failure("Failed to find required OS image"
159 " for cloudify manager")
161 cfy.set_image_id(image_id)
162 self.logger.debug("Orchestrator image set")
164 self.logger.debug("Get External network")
165 ext_net = os_utils.get_external_net(self.neutron_client)
166 self.logger.debug("External network: %s" % ext_net)
168 self.step_failure("Failed to get external network")
170 cfy.set_external_network_name(ext_net)
171 self.logger.debug("CFY External network set")
173 self.logger.debug("get resolvconf")
174 ns = ft_utils.get_resolvconf_ns()
176 cfy.set_nameservers(ns)
177 self.logger.debug("Resolvconf set")
179 if 'compute' in self.nova_client.client.services_url:
180 cfy.set_nova_url(self.nova_client.client.services_url['compute'])
181 if self.neutron_client.httpclient.endpoint_url is not None:
182 cfy.set_neutron_url(self.neutron_client.httpclient.endpoint_url)
184 self.logger.info("Prepare virtualenv for cloudify-cli")
185 cmd = "chmod +x " + self.case_dir + "create_venv.sh"
186 ft_utils.execute_command(cmd)
188 cmd = self.case_dir + "create_venv.sh " + self.data_dir
189 ft_utils.execute_command(cmd)
191 cfy.download_manager_blueprint(
192 self.orchestrator['blueprint']['url'],
193 self.orchestrator['blueprint']['branch'])
196 return {'status': 'PASS', 'result': ''}
198 def deploy_vnf(self):
199 cw = Clearwater(self.vnf.inputs, self.orchestrator.object, self.logger)
202 self.logger.info("Collect flavor id for all clearwater vm")
203 flavor_exist, flavor_id = os_utils.get_or_create_flavor(
205 self.vnf['requirements']['ram_min'],
209 self.logger.debug("Flavor id: %s" % flavor_id)
211 self.logger.info("Available flavors are: ")
212 self.logger.info(self.nova_client.flavor.list())
213 self.step_failure("Failed to find required flavor"
214 " for this deployment")
216 cw.set_flavor_id(flavor_id)
219 if 'os_image' in self.vnf.requirements.keys():
220 image_id = os_utils.get_image_id(
221 self.glance_client, self.vnf['requirements']['os_image'])
223 self.step_failure("Failed to find required OS image"
224 " for clearwater VMs")
226 self.step_failure("Failed to find required OS image"
227 " for clearwater VMs")
229 cw.set_image_id(image_id)
231 ext_net = os_utils.get_external_net(self.neutron_client)
233 self.step_failure("Failed to get external network")
235 cw.set_external_network_name(ext_net)
238 return {'status': 'PASS', 'result': ''}
241 script = "source {0}venv_cloudify/bin/activate; "
243 script += "cfy status | grep -Eo \"([0-9]{{1,3}}\.){{3}}[0-9]{{1,3}}\""
244 cmd = "/bin/bash -c '" + script.format(self.data_dir) + "'"
247 self.logger.debug("Trying to get clearwater manager IP ... ")
248 mgr_ip = os.popen(cmd).read()
249 mgr_ip = mgr_ip.splitlines()[0]
251 self.step_failure("Unable to retrieve the IP of the "
252 "cloudify manager server !")
254 api_url = "http://" + mgr_ip + "/api/v2"
255 dep_outputs = requests.get(api_url + "/deployments/" +
256 self.vnf.deployment_name + "/outputs")
257 dns_ip = dep_outputs.json()['outputs']['dns_ip']
258 ellis_ip = dep_outputs.json()['outputs']['ellis_ip']
260 ellis_url = "http://" + ellis_ip + "/"
261 url = ellis_url + "accounts"
263 params = {"password": "functest",
264 "full_name": "opnfv functest user",
265 "email": "functest@opnfv.fr",
266 "signup_code": "secret"}
268 rq = requests.post(url, data=params)
270 while rq.status_code != 201 and i > 0:
271 rq = requests.post(url, data=params)
275 if rq.status_code == 201:
276 url = ellis_url + "session"
277 rq = requests.post(url, data=params)
280 url = ellis_url + "accounts/" + params['email'] + "/numbers"
282 rq = requests.post(url, cookies=cookies)
284 while rq.status_code != 200 and i > 0:
285 rq = requests.post(url, cookies=cookies)
289 if rq.status_code != 200:
290 self.step_failure("Unable to create a number: %s"
291 % rq.json()['reason'])
293 nameservers = ft_utils.get_resolvconf_ns()
295 for ns in nameservers:
296 resolvconf += "\nnameserver " + ns
299 script = ('echo -e "nameserver ' + dns_ip + resolvconf +
300 '" > /etc/resolv.conf; ')
301 script += 'source /etc/profile.d/rvm.sh; '
303 script += ('rake test[{1}] SIGNUP_CODE="secret"')
305 cmd = ("/bin/bash -c '" +
306 script.format(self.data_dir, self.inputs["public_domain"]) +
308 output_file = "output.txt"
309 f = open(output_file, 'w+')
310 subprocess.call(cmd, shell=True, stdout=f,
311 stderr=subprocess.STDOUT)
314 f = open(output_file, 'r')
317 self.logger.debug(result)
319 vims_test_result = ""
320 tempFile = os.path.join(self.test_dir, "temp.json")
322 self.logger.debug("Trying to load test results")
323 with open(tempFile) as f:
324 vims_test_result = json.load(f)
327 self.logger.error("Unable to retrieve test results")
332 self.logger.error("Deleting file failed")
334 if vims_test_result != '':
335 return {'status': 'PASS', 'result': vims_test_result}
337 return {'status': 'FAIL', 'result': ''}
340 self.vnf.object.undeploy_vnf()
341 self.orchestrator.object.undeploy_manager()
342 super(ImsVnf, self).clean()
344 def main(self, **kwargs):
345 self.logger.info("Cloudify IMS VNF onboarding test starting")
347 self.logger.info("Cloudify IMS VNF onboarding test executed")
348 if self.criteria is "PASS":
351 return self.EX_RUN_ERROR
355 return self.main(**kwargs)
358 # ----------------------------------------------------------
362 # -----------------------------------------------------------
363 def get_config(parameter, file):
365 Returns the value of a given parameter in file.yaml
366 parameter must be given in string format with dots
367 Example: general.openstack.image_name
369 with open(file) as f:
370 file_yaml = yaml.safe_load(f)
373 for element in parameter.split("."):
374 value = value.get(element)
376 raise ValueError("The parameter %s is not defined in"
377 " reporting.yaml" % parameter)
381 def download_and_add_image_on_glance(glance, image_name, image_url, data_dir):
383 if not os.path.exists(dest_path):
384 os.makedirs(dest_path)
385 file_name = image_url.rsplit('/')[-1]
386 if not ft_utils.download_url(image_url, dest_path):
389 image = os_utils.create_glance_image(
390 glance, image_name, dest_path + file_name)