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 OpenIMS testcase implementation."""
21 from snaps.openstack.create_image import OpenStackImage, ImageSettings
22 from snaps.openstack.create_flavor import OpenStackFlavor, FlavorSettings
23 from snaps.openstack.create_security_group import (
24 OpenStackSecurityGroup,
25 SecurityGroupSettings,
26 SecurityGroupRuleSettings,
29 from snaps.openstack.create_network import (
34 from snaps.openstack.create_router import OpenStackRouter, RouterSettings
35 from snaps.openstack.create_instance import (
36 VmInstanceSettings, OpenStackVmInstance)
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 OpenImsVnf(vnf.VnfOnBoarding):
142 """OpenIMS 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_openims"
149 super(OpenImsVnf, 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)
198 self.images.update(get_config("tenant_images.%s" %
199 self.case_name, config_file))
202 """Prepare testscase (Additional pre-configuration steps)."""
203 super(OpenImsVnf, self).prepare()
205 self.logger.info("Additional pre-configuration steps")
207 "tenant": self.tenant_name,
208 "username": self.tenant_name,
209 "password": self.tenant_name,
210 "auth_url": os_utils.get_credentials()['auth_url']
212 self.prepare_images()
213 self.prepare_flavor()
214 self.prepare_security_groups()
215 self.prepare_network()
216 self.prepare_floating_ip()
218 def prepare_images(self):
219 """Upload images if they doen't exist yet"""
220 self.logger.info("Upload images if they doen't exist yet")
221 for image_name, image_file in self.images.iteritems():
222 self.logger.info("image: %s, file: %s", image_name, image_file)
223 if image_file and image_name:
224 image = OpenStackImage(
226 ImageSettings(name=image_name,
229 image_file=image_file,
232 # self.created_resources.append(image);
234 def prepare_security_groups(self):
235 """Create Open Baton security group if it doesn't exist yet"""
237 "Creating security group for Open Baton if not yet existing...")
240 SecurityGroupRuleSettings(
241 sec_grp_name="orchestra-sec-group-allowall",
242 direction=Direction.ingress,
243 protocol=Protocol.tcp,
245 port_range_max=65535))
247 SecurityGroupRuleSettings(
248 sec_grp_name="orchestra-sec-group-allowall",
249 direction=Direction.egress,
250 protocol=Protocol.tcp,
252 port_range_max=65535))
254 SecurityGroupRuleSettings(
255 sec_grp_name="orchestra-sec-group-allowall",
256 direction=Direction.ingress,
257 protocol=Protocol.udp,
259 port_range_max=65535))
261 SecurityGroupRuleSettings(
262 sec_grp_name="orchestra-sec-group-allowall",
263 direction=Direction.egress,
264 protocol=Protocol.udp,
266 port_range_max=65535))
268 SecurityGroupRuleSettings(
269 sec_grp_name="orchestra-sec-group-allowall",
270 direction=Direction.ingress,
271 protocol=Protocol.icmp))
273 SecurityGroupRuleSettings(
274 sec_grp_name="orchestra-sec-group-allowall",
275 direction=Direction.egress,
276 protocol=Protocol.icmp))
278 # SecurityGroupRuleSettings(
279 # sec_grp_name="orchestra-sec-group-allowall",
280 # direction=Direction.ingress,
281 # protocol=Protocol.icmp,
283 # port_range_max=-1))
285 # SecurityGroupRuleSettings(
286 # sec_grp_name="orchestra-sec-group-allowall",
287 # direction=Direction.egress,
288 # protocol=Protocol.icmp,
290 # port_range_max=-1))
292 security_group = OpenStackSecurityGroup(
294 SecurityGroupSettings(
295 name="orchestra-sec-group-allowall",
296 rule_settings=sg_rules))
298 security_group_info = security_group.create()
299 self.created_resources.append(security_group)
300 self.mano['details']['sec_group'] = security_group_info.name
302 "Security group orchestra-sec-group-allowall prepared")
304 def prepare_flavor(self):
305 """Create Open Baton flavor if it doesn't exist yet"""
307 "Create Flavor for Open Baton NFVO if not yet existing")
309 flavor_settings = FlavorSettings(
310 name=self.mano['requirements']['flavor']['name'],
311 ram=self.mano['requirements']['flavor']['ram_min'],
312 disk=self.mano['requirements']['flavor']['disk'],
313 vcpus=self.mano['requirements']['flavor']['vcpus'])
314 flavor = OpenStackFlavor(self.snaps_creds, flavor_settings)
315 flavor_info = flavor.create()
316 self.created_resources.append(flavor)
317 self.mano['details']['flavor'] = {}
318 self.mano['details']['flavor']['name'] = flavor_settings.name
319 self.mano['details']['flavor']['id'] = flavor_info.id
321 def prepare_network(self):
322 """Create network/subnet/router if they doen't exist yet"""
324 "Creating network/subnet/router if they doen't exist yet...")
325 subnet_settings = SubnetSettings(
328 cidr="192.168.100.0/24")
329 network_settings = NetworkSettings(
332 subnet_settings=[subnet_settings])
333 orchestra_network = OpenStackNetwork(
334 self.snaps_creds, network_settings)
335 orchestra_network_info = orchestra_network.create()
336 self.mano['details']['network'] = {}
337 self.mano['details']['network']['id'] = orchestra_network_info.id
338 self.mano['details']['network']['name'] = orchestra_network_info.name
339 self.mano['details']['external_net_name'] = \
340 snaps_utils.get_ext_net_name(self.snaps_creds)
341 self.created_resources.append(orchestra_network)
342 orchestra_router = OpenStackRouter(
347 external_gateway=self.mano['details']['external_net_name'],
349 subnet_settings.name]))
350 orchestra_router.create()
351 self.created_resources.append(orchestra_router)
352 self.logger.info("Created network and router for Open Baton NFVO...")
354 def prepare_floating_ip(self):
355 """Select/Create Floating IP if it doesn't exist yet"""
356 self.logger.info("Retrieving floating IP for Open Baton NFVO")
357 neutron_client = snaps_utils.neutron_utils.neutron_client(
359 # Finding Tenant ID to check to which tenant the Floating IP belongs
360 tenant_id = os_utils.get_tenant_id(
361 os_utils.get_keystone_client(self.creds),
363 # Use os_utils to retrieve complete information of Floating IPs
364 floating_ips = os_utils.get_floating_ips(neutron_client)
366 # Filter Floating IPs with tenant id
367 for floating_ip in floating_ips:
368 # self.logger.info("Floating IP: %s", floating_ip)
369 if floating_ip.get('tenant_id') == tenant_id:
370 my_floating_ips.append(floating_ip.get('floating_ip_address'))
371 # Select if Floating IP exist else create new one
372 if len(my_floating_ips) >= 1:
373 # Get Floating IP object from snaps for clean up
374 snaps_floating_ips = snaps_utils.neutron_utils.get_floating_ips(
376 for my_floating_ip in my_floating_ips:
377 for snaps_floating_ip in snaps_floating_ips:
378 if snaps_floating_ip.ip == my_floating_ip:
379 self.mano['details']['fip'] = snaps_floating_ip
381 "Selected floating IP for Open Baton NFVO %s",
382 (self.mano['details']['fip'].ip))
384 if self.mano['details']['fip'] is not None:
387 self.logger.info("Creating floating IP for Open Baton NFVO")
388 self.mano['details']['fip'] = (
389 snaps_utils.neutron_utils. create_floating_ip(
390 neutron_client, self.mano['details']['external_net_name']))
392 "Created floating IP for Open Baton NFVO %s",
393 (self.mano['details']['fip'].ip))
395 def get_vim_descriptor(self):
396 """"Create VIM descriptor to be used for onboarding"""
398 "Building VIM descriptor with PoP creds: %s",
400 # Depending on API version either tenant ID or project name must be
402 if os_utils.is_keystone_v3():
404 "Using v3 API of OpenStack... -> Using OS_PROJECT_ID")
405 project_id = os_utils.get_tenant_id(
406 os_utils.get_keystone_client(),
407 self.creds.get("project_name"))
410 "Using v2 API of OpenStack... -> Using OS_TENANT_NAME")
411 project_id = self.creds.get("tenant_name")
412 self.logger.debug("VIM project/tenant id: %s", project_id)
414 "name": "vim-instance",
415 "authUrl": self.creds.get("auth_url"),
416 "tenant": project_id,
417 "username": self.creds.get("username"),
418 "password": self.creds.get("password"),
420 self.mano['details']['sec_group']
425 "latitude": "52.525876",
426 "longitude": "13.314400"
429 self.logger.info("Built VIM descriptor: %s", vim_json)
432 def deploy_orchestrator(self):
433 self.logger.info("Deploying Open Baton...")
434 self.logger.info("Details: %s", self.mano['details'])
435 start_time = time.time()
437 self.logger.info("Creating orchestra instance...")
438 userdata = get_userdata(self.mano)
439 self.logger.info("flavor: %s\n"
442 self.mano['details']['flavor']['name'],
443 self.mano['requirements']['image'],
444 self.mano['details']['network']['id'])
445 self.logger.debug("userdata: %s\n", userdata)
447 image_settings = ImageSettings(
448 name=self.mano['requirements']['image'],
452 port_settings = PortSettings(
453 name='%s_port' % self.case_name,
454 network_name=self.mano['details']['network']['name'])
455 # build configuration of vm
456 orchestra_settings = VmInstanceSettings(
458 flavor=self.mano['details']['flavor']['name'],
459 port_settings=[port_settings],
460 security_group_names=[self.mano['details']['sec_group']],
462 orchestra_vm = OpenStackVmInstance(self.snaps_creds,
466 orchestra_vm.create()
467 self.created_resources.append(orchestra_vm)
468 self.mano['details']['id'] = orchestra_vm.get_vm_info()['id']
470 "Created orchestra instance: %s",
471 self.mano['details']['id'])
473 self.logger.info("Associating floating ip: '%s' to VM '%s' ",
474 self.mano['details']['fip'].ip,
476 nova_client = os_utils.get_nova_client()
477 if not os_utils.add_floating_ip(
479 self.mano['details']['id'],
480 self.mano['details']['fip'].ip):
481 duration = time.time() - start_time
482 self.details["orchestrator"].update(
483 status='FAIL', duration=duration)
484 self.logger.error("Cannot associate floating IP to VM.")
487 self.logger.info("Waiting for Open Baton NFVO to be up and running...")
491 self.mano['details']['fip'].ip,
495 self.logger.info("Open Baton NFVO is not started yet (%ss)",
501 duration = time.time() - start_time
502 self.details["orchestrator"].update(
503 status='FAIL', duration=duration)
504 self.logger.error("Open Baton is not started correctly")
507 self.logger.info("Waiting for all components to be up and running...")
509 duration = time.time() - start_time
510 self.details["orchestrator"].update(status='PASS', duration=duration)
511 self.logger.info("Deploy Open Baton NFVO: OK")
514 def deploy_vnf(self):
515 start_time = time.time()
516 self.logger.info("Deploying %s...", self.vnf['name'])
518 main_agent = MainAgent(
519 nfvo_ip=self.mano['details']['fip'].ip,
523 username=self.mano['credentials']['username'],
524 password=self.mano['credentials']['password'])
527 "Create %s Flavor if not existing", self.vnf['name'])
528 flavor_settings = FlavorSettings(
529 name=self.vnf['requirements']['flavor']['name'],
530 ram=self.vnf['requirements']['flavor']['ram_min'],
531 disk=self.vnf['requirements']['flavor']['disk'],
532 vcpus=self.vnf['requirements']['flavor']['vcpus'])
533 flavor = OpenStackFlavor(self.snaps_creds, flavor_settings)
534 flavor_info = flavor.create()
535 self.logger.debug("Flavor id: %s", flavor_info.id)
537 self.logger.info("Getting project 'default'...")
538 project_agent = main_agent.get_agent("project", "")
539 for project in json.loads(project_agent.find()):
540 if project.get("name") == "default":
541 self.mano['details']['project_id'] = project.get("id")
542 self.logger.info("Found project 'default': %s", project)
545 vim_json = self.get_vim_descriptor()
546 self.logger.info("Registering VIM: %s", vim_json)
548 main_agent.get_agent(
549 "vim", project_id=self.mano['details']['project_id']).create(
550 entity=json.dumps(vim_json))
552 market_agent = main_agent.get_agent(
553 "market", project_id=self.mano['details']['project_id'])
556 self.logger.info("sending: %s", self.vnf['descriptor']['url'])
557 nsd = market_agent.create(entity=self.vnf['descriptor']['url'])
558 if nsd.get('id') is None:
559 self.logger.error("NSD not onboarded correctly")
560 duration = time.time() - start_time
561 self.details["vnf"].update(status='FAIL', duration=duration)
563 self.mano['details']['nsd_id'] = nsd.get('id')
564 self.logger.info("Onboarded NSD: " + nsd.get("name"))
566 nsr_agent = main_agent.get_agent(
567 "nsr", project_id=self.mano['details']['project_id'])
569 self.mano['details']['nsr'] = nsr_agent.create(
570 self.mano['details']['nsd_id'])
571 except NfvoException as exc:
572 self.logger.error(exc.message)
573 duration = time.time() - start_time
574 self.details["vnf"].update(status='FAIL', duration=duration)
577 if self.mano['details']['nsr'].get('code') is not None:
579 "%s cannot be deployed: %s -> %s",
581 self.mano['details']['nsr'].get('code'),
582 self.mano['details']['nsr'].get('message'))
583 self.logger.error("%s cannot be deployed", self.vnf['name'])
584 duration = time.time() - start_time
585 self.details["vnf"].update(status='FAIL', duration=duration)
589 self.logger.info("Waiting for NSR to go to ACTIVE...")
590 while self.mano['details']['nsr'].get("status") != 'ACTIVE' \
591 and self.mano['details']['nsr'].get("status") != 'ERROR':
593 self.logger.info("NSR is not yet ACTIVE... (%ss)", 5 * timeout)
595 self.logger.error("INACTIVE NSR after %s sec..", 5 * timeout)
596 duration = time.time() - start_time
597 self.details["vnf"].update(status='FAIL', duration=duration)
600 self.mano['details']['nsr'] = json.loads(
601 nsr_agent.find(self.mano['details']['nsr'].get('id')))
603 duration = time.time() - start_time
604 if self.mano['details']['nsr'].get("status") == 'ACTIVE':
605 self.details["vnf"].update(status='PASS', duration=duration)
606 self.logger.info("Sleep for 60s to ensure that all "
607 "services are up and running...")
611 self.details["vnf"].update(status='FAIL', duration=duration)
612 self.logger.error("NSR: %s", self.mano['details'].get('nsr'))
617 self.logger.info("Testing VNF OpenIMS...")
618 start_time = time.time()
620 "Testing if %s works properly...",
621 self.mano['details']['nsr'].get('name'))
622 for vnfr in self.mano['details']['nsr'].get('vnfr'):
624 "Checking ports %s of VNF %s",
625 self.vnf['test'][vnfr.get('name')]['ports'],
627 for vdu in vnfr.get('vdu'):
628 for vnfci in vdu.get('vnfc_instance'):
630 "Checking ports of VNFC instance %s",
631 vnfci.get('hostname'))
632 for floating_ip in vnfci.get('floatingIps'):
635 vnfci.get('hostname'),
636 floating_ip.get('ip'))
637 for port in self.vnf['test'][vnfr.get(
639 if servertest(floating_ip.get('ip'), port):
641 "VNFC instance %s is reachable at %s:%s",
642 vnfci.get('hostname'),
643 floating_ip.get('ip'),
647 "VNFC instance %s is not reachable "
649 vnfci.get('hostname'),
650 floating_ip.get('ip'),
652 duration = time.time() - start_time
653 self.details["test_vnf"].update(
654 status='FAIL', duration=duration, esult=(
655 "Port %s of server %s -> %s is "
658 vnfci.get('hostname'),
659 floating_ip.get('ip')))
660 self.logger.error("Test VNF: ERROR")
662 duration = time.time() - start_time
663 self.details["test_vnf"].update(status='PASS', duration=duration)
664 self.logger.info("Test VNF: OK")
668 self.logger.info("Cleaning %s...", self.case_name)
670 main_agent = MainAgent(
671 nfvo_ip=self.mano['details']['fip'].ip,
675 username=self.mano['credentials']['username'],
676 password=self.mano['credentials']['password'])
677 self.logger.info("Terminating %s...", self.vnf['name'])
678 if (self.mano['details'].get('nsr')):
679 main_agent.get_agent(
681 project_id=self.mano['details']['project_id']).\
682 delete(self.mano['details']['nsr'].get('id'))
683 self.logger.info("Sleeping 60 seconds...")
686 self.logger.info("No need to terminate the VNF...")
687 # os_utils.delete_instance(nova_client=os_utils.get_nova_client(),
688 # instance_id=self.mano_instance_id)
689 except (NfvoException, KeyError) as exc:
690 self.logger.error('Unexpected error cleaning - %s', exc)
693 neutron_client = os_utils.get_neutron_client(self.creds)
694 self.logger.info("Deleting Open Baton Port...")
695 port = snaps_utils.neutron_utils.get_port(
697 port_name='%s_port' % self.case_name)
698 snaps_utils.neutron_utils.delete_port(neutron_client, port)
700 except Exception as exc:
701 self.logger.error('Unexpected error cleaning - %s', exc)
703 self.logger.info("Deleting Open Baton Floating IP...")
704 snaps_utils.neutron_utils.delete_floating_ip(
705 neutron_client, self.mano['details']['fip'])
706 except Exception as exc:
707 self.logger.error('Unexpected error cleaning - %s', exc)
709 for resource in reversed(self.created_resources):
711 self.logger.info("Cleaning %s", str(resource))
713 except Exception as exc:
714 self.logger.error('Unexpected error cleaning - %s', exc)
715 super(OpenImsVnf, self).clean()