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
10 """Orchestra Clearwater IMS testcase implementation."""
20 from snaps.openstack.create_image import OpenStackImage, ImageSettings
21 from snaps.openstack.create_flavor import OpenStackFlavor, FlavorSettings
22 from snaps.openstack.create_security_group import (
23 OpenStackSecurityGroup,
24 SecurityGroupSettings,
25 SecurityGroupRuleSettings,
28 from snaps.openstack.create_network import (
33 from snaps.openstack.create_router import OpenStackRouter, RouterSettings
34 from snaps.openstack.create_instance import (
37 from functest.opnfv_tests.openstack.snaps import snaps_utils
39 import functest.core.vnf as vnf
40 import functest.utils.openstack_utils as os_utils
41 from functest.utils.constants import CONST
43 from org.openbaton.cli.errors.errors import NfvoException
44 from org.openbaton.cli.agents.agents import MainAgent
47 __author__ = "Pauls, Michael <michael.pauls@fokus.fraunhofer.de>"
48 # ----------------------------------------------------------
52 # -----------------------------------------------------------
55 def get_config(parameter, file_path):
59 Returns the value of a given parameter in file.yaml
60 parameter must be given in string format with dots
61 Example: general.openstack.image_name
63 with open(file_path) as config_file:
64 file_yaml = yaml.safe_load(config_file)
67 for element in parameter.split("."):
68 value = value.get(element)
70 raise ValueError("The parameter %s is not defined in"
71 " reporting.yaml", parameter)
75 def servertest(host, port):
76 """Method to test that a server is reachable at IP:port"""
77 args = socket.getaddrinfo(host, port, socket.AF_INET, socket.SOCK_STREAM)
78 for family, socktype, proto, canonname, sockaddr in args:
79 sock = socket.socket(family, socktype, proto)
81 sock.connect(sockaddr)
89 def get_userdata(orchestrator=dict):
90 """Build userdata for Open Baton machine"""
91 userdata = "#!/bin/bash\n"
92 userdata += "echo \"Executing userdata...\"\n"
93 userdata += "set -x\n"
94 userdata += "set -e\n"
95 userdata += "echo \"Set nameserver to '8.8.8.8'...\"\n"
96 userdata += "echo \"nameserver 8.8.8.8\" >> /etc/resolv.conf\n"
97 userdata += "echo \"Install curl...\"\n"
98 userdata += "apt-get install curl\n"
99 userdata += "echo \"Inject public key...\"\n"
100 userdata += ("echo \"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCuPXrV3"
101 "geeHc6QUdyUr/1Z+yQiqLcOskiEGBiXr4z76MK4abiFmDZ18OMQlc"
102 "fl0p3kS0WynVgyaOHwZkgy/DIoIplONVr2CKBKHtPK+Qcme2PVnCtv"
103 "EqItl/FcD+1h5XSQGoa+A1TSGgCod/DPo+pes0piLVXP8Ph6QS1k7S"
104 "ic7JDeRQ4oT1bXYpJ2eWBDMfxIWKZqcZRiGPgMIbJ1iEkxbpeaAd9O"
105 "4MiM9nGCPESmed+p54uYFjwEDlAJZShcAZziiZYAvMZhvAhe6USljc"
106 "7YAdalAnyD/jwCHuwIrUw/lxo7UdNCmaUxeobEYyyFA1YVXzpNFZya"
107 "XPGAAYIJwEq/ openbaton@opnfv\" >> /home/ubuntu/.ssh/aut"
109 userdata += "echo \"Download bootstrap...\"\n"
110 userdata += ("curl -s %s "
111 "> ./bootstrap\n" % orchestrator['bootstrap']['url'])
112 userdata += ("curl -s %s" "> ./config_file\n" %
113 orchestrator['bootstrap']['config']['url'])
114 userdata += ("echo \"Disable usage of mysql...\"\n")
115 userdata += "sed -i s/mysql=.*/mysql=no/g /config_file\n"
116 userdata += ("echo \"Setting 'rabbitmq_broker_ip' to '%s'\"\n"
117 % orchestrator['details']['fip'].ip)
118 userdata += ("sed -i s/rabbitmq_broker_ip=localhost/rabbitmq_broker_ip"
119 "=%s/g /config_file\n" % orchestrator['details']['fip'].ip)
120 userdata += "echo \"Set autostart of components to 'false'\"\n"
121 userdata += "export OPENBATON_COMPONENT_AUTOSTART=false\n"
122 userdata += "echo \"Execute bootstrap...\"\n"
123 bootstrap = "sh ./bootstrap release -configFile=./config_file"
124 userdata += bootstrap + "\n"
125 userdata += "echo \"Setting 'nfvo.plugin.timeout' to '300000'\"\n"
126 userdata += ("echo \"nfvo.plugin.timeout=600000\" >> "
127 "/etc/openbaton/openbaton-nfvo.properties\n")
129 "wget %s -O /etc/openbaton/openbaton-vnfm-generic-user-data.sh\n" %
130 orchestrator['gvnfm']['userdata']['url'])
131 userdata += "sed -i '113i"'\ \ \ \ '"sleep 60' " \
132 "/etc/openbaton/openbaton-vnfm-generic-user-data.sh\n"
133 userdata += "echo \"Starting NFVO\"\n"
134 userdata += "service openbaton-nfvo restart\n"
135 userdata += "echo \"Starting Generic VNFM\"\n"
136 userdata += "service openbaton-vnfm-generic restart\n"
137 userdata += "echo \"...end of userdata...\"\n"
141 class ClearwaterImsVnf(vnf.VnfOnBoarding):
142 """Clearwater IMS VNF deployed with openBaton orchestrator"""
144 logger = logging.getLogger(__name__)
146 def __init__(self, **kwargs):
147 if "case_name" not in kwargs:
148 kwargs["case_name"] = "orchestra_clearwaterims"
149 super(ClearwaterImsVnf, self).__init__(**kwargs)
150 # self.logger = logging.getLogger("functest.ci.run_tests.orchestra")
151 self.logger.info("kwargs %s", (kwargs))
153 self.case_dir = pkg_resources.resource_filename(
154 'functest', 'opnfv_tests/vnf/ims/')
155 self.data_dir = CONST.__getattribute__('dir_ims_data')
156 self.test_dir = CONST.__getattribute__('dir_repo_vims_test')
157 self.created_resources = []
158 self.logger.info("%s VNF onboarding test starting", self.case_name)
161 self.config = CONST.__getattribute__(
162 'vnf_{}_config'.format(self.case_name))
163 except BaseException:
164 raise Exception("Orchestra VNF config file not found")
165 config_file = self.case_dir + self.config
168 get_config("mano", config_file),
171 self.logger.debug("Orchestrator configuration %s", self.mano)
173 self.details['orchestrator'] = dict(
174 name=self.mano['name'],
175 version=self.mano['version'],
181 get_config(self.case_name, config_file),
183 self.logger.debug("VNF configuration: %s", self.vnf)
185 self.details['vnf'] = dict(
186 name=self.vnf['name'],
189 self.details['test_vnf'] = dict(
193 # Orchestra base Data directory creation
194 if not os.path.exists(self.data_dir):
195 os.makedirs(self.data_dir)
197 self.images = get_config("tenant_images.orchestrator", config_file)
203 self.snaps_creds = None
206 """Prepare testscase (Additional pre-configuration steps)."""
207 super(ClearwaterImsVnf, self).prepare()
209 self.logger.info("Additional pre-configuration steps")
212 "tenant": self.tenant_name,
213 "username": self.tenant_name,
214 "password": self.tenant_name,
215 "auth_url": os_utils.get_credentials()['auth_url']
217 self.prepare_images()
218 self.prepare_flavor()
219 self.prepare_security_groups()
220 self.prepare_network()
221 self.prepare_floating_ip()
223 def prepare_images(self):
224 """Upload images if they doen't exist yet"""
225 self.logger.info("Upload images if they doen't exist yet")
226 for image_name, image_file in self.images.iteritems():
227 self.logger.info("image: %s, file: %s", image_name, image_file)
228 if image_file and image_name:
229 image = OpenStackImage(
231 ImageSettings(name=image_name,
234 image_file=image_file,
237 # self.created_resources.append(image);
239 def prepare_security_groups(self):
240 """Create Open Baton security group if it doesn't exist yet"""
242 "Creating security group for Open Baton if not yet existing...")
245 SecurityGroupRuleSettings(
246 sec_grp_name="orchestra-sec-group-allowall",
247 direction=Direction.ingress,
248 protocol=Protocol.tcp,
250 port_range_max=65535))
252 SecurityGroupRuleSettings(
253 sec_grp_name="orchestra-sec-group-allowall",
254 direction=Direction.egress,
255 protocol=Protocol.tcp,
257 port_range_max=65535))
259 SecurityGroupRuleSettings(
260 sec_grp_name="orchestra-sec-group-allowall",
261 direction=Direction.ingress,
262 protocol=Protocol.udp,
264 port_range_max=65535))
266 SecurityGroupRuleSettings(
267 sec_grp_name="orchestra-sec-group-allowall",
268 direction=Direction.egress,
269 protocol=Protocol.udp,
271 port_range_max=65535))
273 SecurityGroupRuleSettings(
274 sec_grp_name="orchestra-sec-group-allowall",
275 direction=Direction.ingress,
276 protocol=Protocol.icmp))
278 SecurityGroupRuleSettings(
279 sec_grp_name="orchestra-sec-group-allowall",
280 direction=Direction.egress,
281 protocol=Protocol.icmp))
283 # SecurityGroupRuleSettings(
284 # sec_grp_name="orchestra-sec-group-allowall",
285 # direction=Direction.ingress,
286 # protocol=Protocol.icmp,
288 # port_range_max=-1))
290 # SecurityGroupRuleSettings(
291 # sec_grp_name="orchestra-sec-group-allowall",
292 # direction=Direction.egress,
293 # protocol=Protocol.icmp,
295 # port_range_max=-1))
297 security_group = OpenStackSecurityGroup(
299 SecurityGroupSettings(
300 name="orchestra-sec-group-allowall",
301 rule_settings=sg_rules))
303 security_group_info = security_group.create()
304 self.created_resources.append(security_group)
305 self.mano['details']['sec_group'] = security_group_info.name
307 "Security group orchestra-sec-group-allowall prepared")
309 def prepare_flavor(self):
310 """Create Open Baton flavor if it doesn't exist yet"""
312 "Create Flavor for Open Baton NFVO if not yet existing")
314 flavor_settings = FlavorSettings(
315 name=self.mano['requirements']['flavor']['name'],
316 ram=self.mano['requirements']['flavor']['ram_min'],
317 disk=self.mano['requirements']['flavor']['disk'],
318 vcpus=self.mano['requirements']['flavor']['vcpus'])
319 flavor = OpenStackFlavor(self.snaps_creds, flavor_settings)
320 flavor_info = flavor.create()
321 self.created_resources.append(flavor)
322 self.mano['details']['flavor'] = {}
323 self.mano['details']['flavor']['name'] = flavor_settings.name
324 self.mano['details']['flavor']['id'] = flavor_info.id
326 def prepare_network(self):
327 """Create network/subnet/router if they doen't exist yet"""
329 "Creating network/subnet/router if they doen't exist yet...")
330 subnet_settings = SubnetSettings(
333 cidr="192.168.100.0/24")
334 network_settings = NetworkSettings(
337 subnet_settings=[subnet_settings])
338 orchestra_network = OpenStackNetwork(
339 self.snaps_creds, network_settings)
340 orchestra_network_info = orchestra_network.create()
341 self.mano['details']['network'] = {}
342 self.mano['details']['network']['id'] = orchestra_network_info.id
343 self.mano['details']['network']['name'] = orchestra_network_info.name
344 self.mano['details']['external_net_name'] = snaps_utils.\
345 get_ext_net_name(self.snaps_creds)
346 self.created_resources.append(orchestra_network)
347 orchestra_router = OpenStackRouter(
352 external_gateway=self.mano['details']['external_net_name'],
354 subnet_settings.name]))
355 orchestra_router.create()
356 self.created_resources.append(orchestra_router)
357 self.logger.info("Created network and router for Open Baton NFVO...")
359 def prepare_floating_ip(self):
360 """Select/Create Floating IP if it doesn't exist yet"""
361 self.logger.info("Retrieving floating IP for Open Baton NFVO")
362 neutron_client = snaps_utils.neutron_utils.neutron_client(
364 # Finding Tenant ID to check to which tenant the Floating IP belongs
365 tenant_id = os_utils.get_tenant_id(
366 os_utils.get_keystone_client(self.creds),
368 # Use os_utils to retrieve complete information of Floating IPs
369 floating_ips = os_utils.get_floating_ips(neutron_client)
371 # Filter Floating IPs with tenant id
372 for floating_ip in floating_ips:
373 # self.logger.info("Floating IP: %s", floating_ip)
374 if floating_ip.get('tenant_id') == tenant_id:
375 my_floating_ips.append(floating_ip.get('floating_ip_address'))
376 # Select if Floating IP exist else create new one
377 if len(my_floating_ips) >= 1:
378 # Get Floating IP object from snaps for clean up
379 snaps_floating_ips = snaps_utils.neutron_utils.get_floating_ips(
381 for my_floating_ip in my_floating_ips:
382 for snaps_floating_ip in snaps_floating_ips:
383 if snaps_floating_ip.ip == my_floating_ip:
384 self.mano['details']['fip'] = snaps_floating_ip
386 "Selected floating IP for Open Baton NFVO %s",
387 (self.mano['details']['fip'].ip))
389 if self.mano['details']['fip'] is not None:
392 self.logger.info("Creating floating IP for Open Baton NFVO")
393 self.mano['details']['fip'] = snaps_utils.neutron_utils.\
396 self.mano['details']['external_net_name'])
398 "Created floating IP for Open Baton NFVO %s",
399 (self.mano['details']['fip'].ip))
401 def get_vim_descriptor(self):
402 """"Create VIM descriptor to be used for onboarding"""
404 "Building VIM descriptor with PoP creds: %s",
406 # Depending on API version either tenant ID or project name must be
408 if os_utils.is_keystone_v3():
410 "Using v3 API of OpenStack... -> Using OS_PROJECT_ID")
411 project_id = os_utils.get_tenant_id(
412 os_utils.get_keystone_client(),
413 self.creds.get("project_name"))
416 "Using v2 API of OpenStack... -> Using OS_TENANT_NAME")
417 project_id = self.creds.get("tenant_name")
418 self.logger.debug("VIM project/tenant id: %s", project_id)
420 "name": "vim-instance",
421 "authUrl": self.creds.get("auth_url"),
422 "tenant": project_id,
423 "username": self.creds.get("username"),
424 "password": self.creds.get("password"),
426 self.mano['details']['sec_group']
431 "latitude": "52.525876",
432 "longitude": "13.314400"
435 self.logger.info("Built VIM descriptor: %s", vim_json)
438 def deploy_orchestrator(self):
439 self.logger.info("Deploying Open Baton...")
440 self.logger.info("Details: %s", self.mano['details'])
441 start_time = time.time()
443 self.logger.info("Creating orchestra instance...")
444 userdata = get_userdata(self.mano)
445 self.logger.info("flavor: %s\n"
448 self.mano['details']['flavor']['name'],
449 self.mano['requirements']['image'],
450 self.mano['details']['network']['id'])
451 self.logger.debug("userdata: %s\n", userdata)
453 image_settings = ImageSettings(
454 name=self.mano['requirements']['image'],
458 port_settings = PortSettings(
459 name='%s_port' % self.case_name,
460 network_name=self.mano['details']['network']['name'])
461 # build configuration of vm
462 orchestra_settings = VmInstanceSettings(
464 flavor=self.mano['details']['flavor']['name'],
465 port_settings=[port_settings],
466 security_group_names=[self.mano['details']['sec_group']],
468 orchestra_vm = OpenStackVmInstance(self.snaps_creds,
472 orchestra_vm.create()
473 self.created_resources.append(orchestra_vm)
474 self.mano['details']['id'] = orchestra_vm.get_vm_info()['id']
476 "Created orchestra instance: %s",
477 self.mano['details']['id'])
479 self.logger.info("Associating floating ip: '%s' to VM '%s' ",
480 self.mano['details']['fip'].ip,
482 nova_client = os_utils.get_nova_client()
483 if not os_utils.add_floating_ip(
485 self.mano['details']['id'],
486 self.mano['details']['fip'].ip):
487 duration = time.time() - start_time
488 self.details["orchestrator"].update(
489 status='FAIL', duration=duration)
490 self.logger.error("Cannot associate floating IP to VM.")
493 self.logger.info("Waiting for Open Baton NFVO to be up and running...")
497 self.mano['details']['fip'].ip,
502 "Open Baton NFVO is not started yet (%ss)",
508 duration = time.time() - start_time
509 self.details["orchestrator"].update(
510 status='FAIL', duration=duration)
511 self.logger.error("Open Baton is not started correctly")
514 self.logger.info("Waiting for all components to be up and running...")
516 duration = time.time() - start_time
517 self.details["orchestrator"].update(status='PASS', duration=duration)
518 self.logger.info("Deploy Open Baton NFVO: OK")
521 def deploy_vnf(self):
522 start_time = time.time()
523 self.logger.info("Deploying %s...", self.vnf['name'])
525 main_agent = MainAgent(
526 nfvo_ip=self.mano['details']['fip'].ip,
530 username=self.mano['credentials']['username'],
531 password=self.mano['credentials']['password'])
534 "Create %s Flavor if not existing", self.vnf['name'])
535 flavor_settings = FlavorSettings(
536 name=self.vnf['requirements']['flavor']['name'],
537 ram=self.vnf['requirements']['flavor']['ram_min'],
538 disk=self.vnf['requirements']['flavor']['disk'],
539 vcpus=self.vnf['requirements']['flavor']['vcpus'])
540 flavor = OpenStackFlavor(self.snaps_creds, flavor_settings)
541 flavor_info = flavor.create()
542 self.logger.debug("Flavor id: %s", flavor_info.id)
544 self.logger.info("Getting project 'default'...")
545 project_agent = main_agent.get_agent("project", "")
546 for project in json.loads(project_agent.find()):
547 if project.get("name") == "default":
548 self.mano['details']['project_id'] = project.get("id")
549 self.logger.info("Found project 'default': %s", project)
552 vim_json = self.get_vim_descriptor()
553 self.logger.info("Registering VIM: %s", vim_json)
555 main_agent.get_agent(
556 "vim", project_id=self.mano['details']['project_id']).create(
557 entity=json.dumps(vim_json))
559 market_agent = main_agent.get_agent(
560 "market", project_id=self.mano['details']['project_id'])
563 self.logger.info("sending: %s", self.vnf['descriptor']['url'])
564 nsd = market_agent.create(entity=self.vnf['descriptor']['url'])
565 if nsd.get('id') is None:
566 self.logger.error("NSD not onboarded correctly")
567 duration = time.time() - start_time
568 self.details["vnf"].update(status='FAIL', duration=duration)
570 self.mano['details']['nsd_id'] = nsd.get('id')
571 self.logger.info("Onboarded NSD: " + nsd.get("name"))
573 nsr_agent = main_agent.get_agent(
574 "nsr", project_id=self.mano['details']['project_id'])
576 self.mano['details']['nsr'] = nsr_agent.create(
577 self.mano['details']['nsd_id'])
578 except NfvoException as exc:
579 self.logger.error(exc.message)
580 duration = time.time() - start_time
581 self.details["vnf"].update(status='FAIL', duration=duration)
584 if self.mano['details']['nsr'].get('code') is not None:
586 "%s cannot be deployed: %s -> %s",
588 self.mano['details']['nsr'].get('code'),
589 self.mano['details']['nsr'].get('message'))
590 self.logger.error("%s cannot be deployed", self.vnf['name'])
591 duration = time.time() - start_time
592 self.details["vnf"].update(status='FAIL', duration=duration)
596 self.logger.info("Waiting for NSR to go to ACTIVE...")
597 while self.mano['details']['nsr'].get("status") != 'ACTIVE' \
598 and self.mano['details']['nsr'].get("status") != 'ERROR':
600 self.logger.info("NSR is not yet ACTIVE... (%ss)", 5 * timeout)
602 self.logger.error("INACTIVE NSR after %s sec..", 5 * timeout)
603 duration = time.time() - start_time
604 self.details["vnf"].update(status='FAIL', duration=duration)
607 self.mano['details']['nsr'] = json.loads(
608 nsr_agent.find(self.mano['details']['nsr'].get('id')))
610 duration = time.time() - start_time
611 if self.mano['details']['nsr'].get("status") == 'ACTIVE':
612 self.details["vnf"].update(status='PASS', duration=duration)
613 self.logger.info("Sleep for 60s to ensure that all "
614 "services are up and running...")
618 self.details["vnf"].update(status='FAIL', duration=duration)
619 self.logger.error("NSR: %s", self.mano['details'].get('nsr'))
625 "Testing VNF Clearwater IMS is not yet implemented...")
626 start_time = time.time()
628 duration = time.time() - start_time
629 self.details["test_vnf"].update(status='PASS', duration=duration)
630 self.logger.info("Test VNF: OK")
634 self.logger.info("Cleaning %s...", self.case_name)
636 main_agent = MainAgent(
637 nfvo_ip=self.mano['details']['fip'].ip,
641 username=self.mano['credentials']['username'],
642 password=self.mano['credentials']['password'])
643 self.logger.info("Terminating %s...", self.vnf['name'])
644 if (self.mano['details'].get('nsr')):
645 main_agent.get_agent(
647 project_id=self.mano['details']['project_id']).delete(
648 self.mano['details']['nsr'].get('id'))
649 self.logger.info("Sleeping 60 seconds...")
652 self.logger.info("No need to terminate the VNF...")
653 # os_utils.delete_instance(nova_client=os_utils.get_nova_client(),
654 # instance_id=self.mano_instance_id)
655 except (NfvoException, KeyError) as exc:
656 self.logger.error('Unexpected error cleaning - %s', exc)
659 neutron_client = os_utils.get_neutron_client(self.creds)
660 self.logger.info("Deleting Open Baton Port...")
661 port = snaps_utils.neutron_utils.get_port(
663 port_name='%s_port' % self.case_name)
664 snaps_utils.neutron_utils.delete_port(neutron_client, port)
666 except Exception as exc:
667 self.logger.error('Unexpected error cleaning - %s', exc)
669 self.logger.info("Deleting Open Baton Floating IP...")
670 snaps_utils.neutron_utils.delete_floating_ip(
671 neutron_client, self.mano['details']['fip'])
672 except Exception as exc:
673 self.logger.error('Unexpected error cleaning - %s', exc)
675 for resource in reversed(self.created_resources):
677 self.logger.info("Cleaning %s", str(resource))
679 except Exception as exc:
680 self.logger.error('Unexpected error cleaning - %s', exc)
681 super(ClearwaterImsVnf, self).clean()