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
16 import functest.core.vnf_base as vnf_base
17 import functest.utils.functest_logger as ft_logger
18 import functest.utils.functest_utils as ft_utils
19 import functest.utils.openstack_utils as os_utils
21 from functest.utils.constants import CONST
23 from org.openbaton.cli.agents.agents import MainAgent
24 from org.openbaton.cli.errors.errors import NfvoException
27 def servertest(host, port):
28 args = socket.getaddrinfo(host, port, socket.AF_INET, socket.SOCK_STREAM)
29 for family, socktype, proto, canonname, sockaddr in args:
30 s = socket.socket(family, socktype, proto)
39 # ----------------------------------------------------------
43 # -----------------------------------------------------------
46 def get_config(parameter, file):
48 Returns the value of a given parameter in file.yaml
49 parameter must be given in string format with dots
50 Example: general.openstack.image_name
53 file_yaml = yaml.safe_load(f)
56 for element in parameter.split("."):
57 value = value.get(element)
59 raise ValueError("The parameter %s is not defined in"
60 " reporting.yaml" % parameter)
64 def download_and_add_image_on_glance(glance, image_name,
67 if not os.path.exists(dest_path):
68 os.makedirs(dest_path)
69 file_name = image_url.rsplit('/')[-1]
70 if not ft_utils.download_url(image_url, dest_path):
72 image = os_utils.create_glance_image(
73 glance, image_name, dest_path + file_name)
79 class ImsVnf(vnf_base.VnfOnBoardingBase):
81 def __init__(self, project='functest', case='orchestra_ims',
83 super(ImsVnf, self).__init__(project, case, repo, cmd)
84 self.ob_password = "openbaton"
85 self.ob_username = "admin"
88 self.ob_ip = "localhost"
89 self.ob_instance_id = ""
90 self.logger = ft_logger.Logger("orchestra_ims").getLogger()
91 self.case_dir = os.path.join(CONST.dir_functest_test, 'vnf/ims/')
92 self.data_dir = CONST.dir_ims_data
93 self.test_dir = CONST.dir_repo_vims_test
94 self.ob_projectid = ""
95 self.keystone_client = os_utils.get_keystone_client()
97 self.main_agent = None
98 # vIMS Data directory creation
99 if not os.path.exists(self.data_dir):
100 os.makedirs(self.data_dir)
101 # Retrieve the configuration
103 self.config = CONST.__getattribute__(
104 'vnf_{}_config'.format(self.case_name))
106 raise Exception("Orchestra VNF config file not found")
107 config_file = self.case_dir + self.config
108 self.imagename = get_config("openbaton.imagename", config_file)
109 self.market_link = get_config("openbaton.marketplace_link",
111 self.images = get_config("tenant_images", config_file)
113 def deploy_orchestrator(self, **kwargs):
114 self.logger.info("Additional pre-configuration steps")
115 nova_client = os_utils.get_nova_client()
116 neutron_client = os_utils.get_neutron_client()
117 glance_client = os_utils.get_glance_client()
120 self.logger.info("Upload some OS images if it doesn't exist")
121 temp_dir = os.path.join(self.data_dir, "tmp/")
122 for image_name, image_url in self.images.iteritems():
123 self.logger.info("image: %s, url: %s" % (image_name, image_url))
125 image_id = os_utils.get_image_id(glance_client,
127 self.logger.info("image_id: %s" % image_id)
129 self.logger.error("Unexpected error: %s" % sys.exc_info()[0])
132 self.logger.info("""%s image doesn't exist on glance repository. Try
133 downloading this image and upload on glance !""" % image_name)
134 image_id = download_and_add_image_on_glance(glance_client,
140 "Failed to find or upload required OS "
141 "image for this deployment")
142 network_dic = os_utils.create_network_full(neutron_client,
144 "openbaton_mgmt_subnet",
148 # orchestrator VM flavor
149 self.logger.info("Check medium Flavor is available, if not create one")
150 flavor_exist, flavor_id = os_utils.get_or_create_flavor(
156 self.logger.debug("Flavor id: %s" % flavor_id)
159 self.logger.error("There has been a problem when creating the "
162 network_id = network_dic["net_id"]
164 self.logger.info("Creating floating IP for VM in advance...")
165 floatip_dic = os_utils.create_floating_ip(neutron_client)
166 floatip = floatip_dic['fip_addr']
169 self.logger.error("Cannot create floating IP.")
171 userdata = "#!/bin/bash\n"
172 userdata += "set -x\n"
173 userdata += "set -e\n"
174 userdata += "echo \"nameserver 8.8.8.8\" >> /etc/resolv.conf\n"
175 userdata += "apt-get install curl\n"
176 userdata += ("echo \"rabbitmq_broker_ip=%s\" > ./config_file\n"
178 userdata += "echo \"mysql=no\" >> ./config_file\n"
179 userdata += ("echo \"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCuPXrV3"
180 "geeHc6QUdyUr/1Z+yQiqLcOskiEGBiXr4z76MK4abiFmDZ18OMQlc"
181 "fl0p3kS0WynVgyaOHwZkgy/DIoIplONVr2CKBKHtPK+Qcme2PVnCtv"
182 "EqItl/FcD+1h5XSQGoa+A1TSGgCod/DPo+pes0piLVXP8Ph6QS1k7S"
183 "ic7JDeRQ4oT1bXYpJ2eWBDMfxIWKZqcZRiGPgMIbJ1iEkxbpeaAd9O"
184 "4MiM9nGCPESmed+p54uYFjwEDlAJZShcAZziiZYAvMZhvAhe6USljc"
185 "7YAdalAnyD/jwCHuwIrUw/lxo7UdNCmaUxeobEYyyFA1YVXzpNFZya"
186 "XPGAAYIJwEq/ openbaton@opnfv\" >> /home/ubuntu/.ssh/aut"
188 userdata += "cat ./config_file\n"
189 userdata += ("curl -s http://get.openbaton.org/bootstrap "
191 userdata += "export OPENBATON_COMPONENT_AUTOSTART=false\n"
192 bootstrap = "sh ./bootstrap release -configFile=./config_file"
193 userdata += bootstrap + "\n"
195 userdata += ("echo \"nfvo.plugin.timeout=300000\" >> "
196 "/etc/openbaton/openbaton-nfvo.properties\n")
197 userdata += "service openbaton-nfvo restart\n"
198 userdata += "service openbaton-vnfm-generic restart\n"
200 sg_id = os_utils.create_security_group_full(neutron_client,
201 "orchestra-sec-group",
204 os_utils.create_secgroup_rule(neutron_client, sg_id, "ingress",
206 os_utils.create_secgroup_rule(neutron_client, sg_id, "egress",
208 os_utils.create_secgroup_rule(neutron_client, sg_id, "ingress",
210 os_utils.create_secgroup_rule(neutron_client, sg_id, "ingress",
212 os_utils.create_secgroup_rule(neutron_client, sg_id, "egress",
214 os_utils.create_secgroup_rule(neutron_client, sg_id, "egress",
217 self.logger.info("Security group set")
219 self.logger.info("Create instance....")
220 self.logger.info("flavor: m1.medium\n"
224 % (self.imagename, network_id, userdata))
226 instance = os_utils.create_instance_and_wait_for_active(
228 os_utils.get_image_id(glance_client, self.imagename),
230 "orchestra-openbaton",
234 self.ob_instance_id = instance.id
236 self.logger.info("Adding sec group to orchestra instance")
237 os_utils.add_secgroup_to_instance(nova_client,
238 self.ob_instance_id, sg_id)
240 self.logger.info("Associating floating ip: '%s' to VM '%s' "
241 % (floatip, "orchestra-openbaton"))
242 if not os_utils.add_floating_ip(nova_client, instance.id, floatip):
243 self.logger.error("Cannot associate floating IP to VM.")
244 self.step_failure("Cannot associate floating IP to VM.")
246 self.logger.info("Waiting for nfvo to be up and running...")
249 if servertest(floatip, "8080"):
252 self.logger.debug("openbaton is not started yet")
257 self.logger.error("Openbaton is not started correctly")
258 self.step_failure("Openbaton is not started correctly")
261 self.ob_password = "openbaton"
262 self.ob_username = "admin"
263 self.ob_https = False
264 self.ob_port = "8080"
266 self.logger.info("Deploy orchestrator: OK")
268 def deploy_vnf(self):
269 self.logger.info("vIMS Deployment")
271 self.main_agent = MainAgent(nfvo_ip=self.ob_ip,
272 nfvo_port=self.ob_port,
275 username=self.ob_username,
276 password=self.ob_password)
278 project_agent = self.main_agent.get_agent("project", self.ob_projectid)
279 for p in json.loads(project_agent.find()):
280 if p.get("name") == "default":
281 self.ob_projectid = p.get("id")
284 self.logger.debug("project id: %s" % self.ob_projectid)
285 if self.ob_projectid == "":
286 self.logger.error("Default project id was not found!")
287 self.step_failure("Default project id was not found!")
290 "name": "vim-instance",
291 "authUrl": os_utils.get_credentials().get("auth_url"),
292 "tenant": os_utils.get_credentials().get("tenant_name"),
293 "username": os_utils.get_credentials().get("username"),
294 "password": os_utils.get_credentials().get("password"),
295 # "keyPair": "opnfv",
296 # TODO change the keypair to correct value
297 # or upload a correct one or remove it
300 "orchestra-sec-group"
305 "latitude": "52.525876",
306 "longitude": "13.314400"
310 self.logger.debug("vim: %s" % vim_json)
312 self.main_agent.get_agent(
314 project_id=self.ob_projectid).create(entity=json.dumps(vim_json))
316 market_agent = self.main_agent.get_agent("market",
317 project_id=self.ob_projectid)
321 self.logger.info("sending: %s" % self.market_link)
322 nsd = market_agent.create(entity=self.market_link)
323 self.logger.info("Onboarded nsd: " + nsd.get("name"))
324 except NfvoException as e:
325 self.step_failure(e.message)
327 nsr_agent = self.main_agent.get_agent("nsr",
328 project_id=self.ob_projectid)
329 nsd_id = nsd.get('id')
331 self.step_failure("NSD not onboarded correctly")
335 nsr = nsr_agent.create(nsd_id)
336 except NfvoException as e:
337 self.step_failure(e.message)
339 if nsr.get('code') is not None:
341 "vIMS cannot be deployed: %s -> %s" %
342 (nsr.get('code'), nsr.get('message')))
343 self.step_failure("vIMS cannot be deployed")
346 self.logger.info("waiting NSR to go to active...")
347 while nsr.get("status") != 'ACTIVE' and nsr.get("status") != 'ERROR':
350 self.step_failure("After %s sec the nsr did not go to active.."
353 nsr = json.loads(nsr_agent.find(nsr.get('id')))
355 if nsr.get("status") == 'ACTIVE':
356 deploy_vnf = {'status': "PASS", 'result': nsr}
357 self.logger.info("Deploy VNF: OK")
359 deploy_vnf = {'status': "FAIL", 'result': nsr}
360 self.logger.error("Deploy VNF: ERROR")
361 self.step_failure("Deploy vIMS failed")
362 self.ob_nsr_id = nsr.get("id")
366 # Adaptations probably needed
367 # code used for cloudify_ims
368 # ruby client on jumphost calling the vIMS on the SUT
372 self.main_agent.get_agent(
374 project_id=self.ob_projectid).delete(self.ob_nsr_id)
376 os_utils.delete_instance(nova_client=os_utils.get_nova_client(),
377 instance_id=self.ob_instance_id)
378 # TODO question is the clean removing also the VM?
379 # I think so since is goinf to remove the tenant...
380 super(ImsVnf, self).clean()
382 def main(self, **kwargs):
383 self.logger.info("Orchestra IMS VNF onboarding test starting")
385 self.logger.info("Orchestra IMS VNF onboarding test executed")
386 if self.criteria is "PASS":
389 return self.EX_RUN_ERROR
393 return self.main(**kwargs)
396 if __name__ == '__main__':
398 test.deploy_orchestrator()