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.os_credentials import OSCreds
36 from snaps.openstack.create_instance import (
37 VmInstanceSettings, OpenStackVmInstance)
38 from functest.opnfv_tests.openstack.snaps import snaps_utils
40 import functest.core.vnf as vnf
41 import functest.utils.openstack_utils as os_utils
42 from functest.utils.constants import CONST
44 from org.openbaton.cli.errors.errors import NfvoException
45 from org.openbaton.cli.agents.agents import MainAgent
48 __author__ = "Pauls, Michael <michael.pauls@fokus.fraunhofer.de>"
49 # ----------------------------------------------------------
53 # -----------------------------------------------------------
56 def get_config(parameter, file_path):
60 Returns the value of a given parameter in file.yaml
61 parameter must be given in string format with dots
62 Example: general.openstack.image_name
64 with open(file_path) as config_file:
65 file_yaml = yaml.safe_load(config_file)
68 for element in parameter.split("."):
69 value = value.get(element)
71 raise ValueError("The parameter %s is not defined in"
72 " reporting.yaml", parameter)
76 def servertest(host, port):
77 """Method to test that a server is reachable at IP:port"""
78 args = socket.getaddrinfo(host, port, socket.AF_INET, socket.SOCK_STREAM)
79 for family, socktype, proto, canonname, sockaddr in args:
80 sock = socket.socket(family, socktype, proto)
82 sock.connect(sockaddr)
90 def get_userdata(orchestrator=dict):
91 """Build userdata for Open Baton machine"""
92 userdata = "#!/bin/bash\n"
93 userdata += "echo \"Executing userdata...\"\n"
94 userdata += "set -x\n"
95 userdata += "set -e\n"
96 userdata += "echo \"Set nameserver to '8.8.8.8'...\"\n"
97 userdata += "echo \"nameserver 8.8.8.8\" >> /etc/resolv.conf\n"
98 userdata += "echo \"Install curl...\"\n"
99 userdata += "apt-get install curl\n"
100 userdata += "echo \"Inject public key...\"\n"
101 userdata += ("echo \"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCuPXrV3"
102 "geeHc6QUdyUr/1Z+yQiqLcOskiEGBiXr4z76MK4abiFmDZ18OMQlc"
103 "fl0p3kS0WynVgyaOHwZkgy/DIoIplONVr2CKBKHtPK+Qcme2PVnCtv"
104 "EqItl/FcD+1h5XSQGoa+A1TSGgCod/DPo+pes0piLVXP8Ph6QS1k7S"
105 "ic7JDeRQ4oT1bXYpJ2eWBDMfxIWKZqcZRiGPgMIbJ1iEkxbpeaAd9O"
106 "4MiM9nGCPESmed+p54uYFjwEDlAJZShcAZziiZYAvMZhvAhe6USljc"
107 "7YAdalAnyD/jwCHuwIrUw/lxo7UdNCmaUxeobEYyyFA1YVXzpNFZya"
108 "XPGAAYIJwEq/ openbaton@opnfv\" >> /home/ubuntu/.ssh/aut"
110 userdata += "echo \"Download bootstrap...\"\n"
111 userdata += ("curl -s %s "
112 "> ./bootstrap\n" % orchestrator['bootstrap']['url'])
113 userdata += ("curl -s %s" "> ./config_file\n" %
114 orchestrator['bootstrap']['config']['url'])
115 userdata += ("echo \"Disable usage of mysql...\"\n")
116 userdata += "sed -i s/mysql=.*/mysql=no/g /config_file\n"
117 userdata += ("echo \"Setting 'rabbitmq_broker_ip' to '%s'\"\n"
118 % orchestrator['details']['fip'].ip)
119 userdata += ("sed -i s/rabbitmq_broker_ip=localhost/rabbitmq_broker_ip"
120 "=%s/g /config_file\n" % orchestrator['details']['fip'].ip)
121 userdata += "echo \"Set autostart of components to 'false'\"\n"
122 userdata += "export OPENBATON_COMPONENT_AUTOSTART=false\n"
123 userdata += "echo \"Execute bootstrap...\"\n"
124 bootstrap = "sh ./bootstrap release -configFile=./config_file"
125 userdata += bootstrap + "\n"
126 userdata += "echo \"Setting 'nfvo.plugin.timeout' to '300000'\"\n"
127 userdata += ("echo \"nfvo.plugin.timeout=600000\" >> "
128 "/etc/openbaton/openbaton-nfvo.properties\n")
130 "wget %s -O /etc/openbaton/openbaton-vnfm-generic-user-data.sh\n" %
131 orchestrator['gvnfm']['userdata']['url'])
132 userdata += "sed -i '113i"'\ \ \ \ '"sleep 60' " \
133 "/etc/openbaton/openbaton-vnfm-generic-user-data.sh\n"
134 userdata += "echo \"Starting NFVO\"\n"
135 userdata += "service openbaton-nfvo restart\n"
136 userdata += "echo \"Starting Generic VNFM\"\n"
137 userdata += "service openbaton-vnfm-generic restart\n"
138 userdata += "echo \"...end of userdata...\"\n"
142 class OpenImsVnf(vnf.VnfOnBoarding):
143 """OpenIMS VNF deployed with openBaton orchestrator"""
145 logger = logging.getLogger(__name__)
147 def __init__(self, **kwargs):
148 if "case_name" not in kwargs:
149 kwargs["case_name"] = "orchestra_openims"
150 super(OpenImsVnf, self).__init__(**kwargs)
151 # self.logger = logging.getLogger("functest.ci.run_tests.orchestra")
152 self.logger.info("kwargs %s", (kwargs))
154 self.case_dir = pkg_resources.resource_filename(
155 'functest', 'opnfv_tests/vnf/ims/')
156 self.data_dir = CONST.__getattribute__('dir_ims_data')
157 self.test_dir = CONST.__getattribute__('dir_repo_vims_test')
158 self.created_resources = []
159 self.logger.info("%s VNF onboarding test starting", self.case_name)
162 self.config = CONST.__getattribute__(
163 'vnf_{}_config'.format(self.case_name))
164 except BaseException:
165 raise Exception("Orchestra VNF config file not found")
166 config_file = self.case_dir + self.config
169 get_config("mano", config_file),
172 self.logger.debug("Orchestrator configuration %s", self.mano)
174 self.details['orchestrator'] = dict(
175 name=self.mano['name'],
176 version=self.mano['version'],
182 get_config(self.case_name, config_file),
184 self.logger.debug("VNF configuration: %s", self.vnf)
186 self.details['vnf'] = dict(
187 name=self.vnf['name'],
190 self.details['test_vnf'] = dict(
194 # Orchestra base Data directory creation
195 if not os.path.exists(self.data_dir):
196 os.makedirs(self.data_dir)
198 self.images = get_config("tenant_images.orchestrator", config_file)
199 self.images.update(get_config("tenant_images.%s" %
200 self.case_name, config_file))
201 self.snaps_creds = None
204 """Prepare testscase (Additional pre-configuration steps)."""
205 super(OpenImsVnf, self).prepare()
207 self.logger.info("Additional pre-configuration steps")
208 self.logger.info("creds %s", (self.creds))
210 self.snaps_creds = OSCreds(
211 username=self.creds['username'],
212 password=self.creds['password'],
213 auth_url=self.creds['auth_url'],
214 project_name=self.creds['tenant'],
215 identity_api_version=int(os_utils.get_keystone_client_version()))
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))
236 # self.created_resources.append(image);
238 def prepare_security_groups(self):
239 """Create Open Baton security group if it doesn't exist yet"""
241 "Creating security group for Open Baton if not yet existing...")
244 SecurityGroupRuleSettings(
245 sec_grp_name="orchestra-sec-group-allowall",
246 direction=Direction.ingress,
247 protocol=Protocol.tcp,
249 port_range_max=65535))
251 SecurityGroupRuleSettings(
252 sec_grp_name="orchestra-sec-group-allowall",
253 direction=Direction.egress,
254 protocol=Protocol.tcp,
256 port_range_max=65535))
258 SecurityGroupRuleSettings(
259 sec_grp_name="orchestra-sec-group-allowall",
260 direction=Direction.ingress,
261 protocol=Protocol.udp,
263 port_range_max=65535))
265 SecurityGroupRuleSettings(
266 sec_grp_name="orchestra-sec-group-allowall",
267 direction=Direction.egress,
268 protocol=Protocol.udp,
270 port_range_max=65535))
272 SecurityGroupRuleSettings(
273 sec_grp_name="orchestra-sec-group-allowall",
274 direction=Direction.ingress,
275 protocol=Protocol.icmp))
277 SecurityGroupRuleSettings(
278 sec_grp_name="orchestra-sec-group-allowall",
279 direction=Direction.egress,
280 protocol=Protocol.icmp))
282 # SecurityGroupRuleSettings(
283 # sec_grp_name="orchestra-sec-group-allowall",
284 # direction=Direction.ingress,
285 # protocol=Protocol.icmp,
287 # port_range_max=-1))
289 # SecurityGroupRuleSettings(
290 # sec_grp_name="orchestra-sec-group-allowall",
291 # direction=Direction.egress,
292 # protocol=Protocol.icmp,
294 # port_range_max=-1))
296 security_group = OpenStackSecurityGroup(
298 SecurityGroupSettings(
299 name="orchestra-sec-group-allowall",
300 rule_settings=sg_rules))
302 security_group_info = security_group.create()
303 self.created_resources.append(security_group)
304 self.mano['details']['sec_group'] = security_group_info.name
306 "Security group orchestra-sec-group-allowall prepared")
308 def prepare_flavor(self):
309 """Create Open Baton flavor if it doesn't exist yet"""
311 "Create Flavor for Open Baton NFVO if not yet existing")
313 flavor_settings = FlavorSettings(
314 name=self.mano['requirements']['flavor']['name'],
315 ram=self.mano['requirements']['flavor']['ram_min'],
316 disk=self.mano['requirements']['flavor']['disk'],
317 vcpus=self.mano['requirements']['flavor']['vcpus'])
318 flavor = OpenStackFlavor(self.snaps_creds, flavor_settings)
319 flavor_info = flavor.create()
320 self.created_resources.append(flavor)
321 self.mano['details']['flavor'] = {}
322 self.mano['details']['flavor']['name'] = flavor_settings.name
323 self.mano['details']['flavor']['id'] = flavor_info.id
325 def prepare_network(self):
326 """Create network/subnet/router if they doen't exist yet"""
328 "Creating network/subnet/router if they doen't exist yet...")
329 subnet_settings = SubnetSettings(
332 cidr="192.168.100.0/24")
333 network_settings = NetworkSettings(
336 subnet_settings=[subnet_settings])
337 orchestra_network = OpenStackNetwork(
338 self.snaps_creds, network_settings)
339 orchestra_network_info = orchestra_network.create()
340 self.mano['details']['network'] = {}
341 self.mano['details']['network']['id'] = orchestra_network_info.id
342 self.mano['details']['network']['name'] = orchestra_network_info.name
343 self.mano['details']['external_net_name'] = \
344 snaps_utils.get_ext_net_name(self.snaps_creds)
345 self.created_resources.append(orchestra_network)
346 orchestra_router = OpenStackRouter(
351 external_gateway=self.mano['details']['external_net_name'],
353 subnet_settings.name]))
354 orchestra_router.create()
355 self.created_resources.append(orchestra_router)
356 self.logger.info("Created network and router for Open Baton NFVO...")
358 def prepare_floating_ip(self):
359 """Select/Create Floating IP if it doesn't exist yet"""
360 self.logger.info("Retrieving floating IP for Open Baton NFVO")
361 neutron_client = snaps_utils.neutron_utils.neutron_client(
363 # Finding Tenant ID to check to which tenant the Floating IP belongs
364 tenant_id = os_utils.get_tenant_id(
365 os_utils.get_keystone_client(self.creds),
367 # Use os_utils to retrieve complete information of Floating IPs
368 floating_ips = os_utils.get_floating_ips(neutron_client)
370 # Filter Floating IPs with tenant id
371 for floating_ip in floating_ips:
372 # self.logger.info("Floating IP: %s", floating_ip)
373 if floating_ip.get('tenant_id') == tenant_id:
374 my_floating_ips.append(floating_ip.get('floating_ip_address'))
375 # Select if Floating IP exist else create new one
376 if len(my_floating_ips) >= 1:
377 # Get Floating IP object from snaps for clean up
378 snaps_floating_ips = snaps_utils.neutron_utils.get_floating_ips(
380 for my_floating_ip in my_floating_ips:
381 for snaps_floating_ip in snaps_floating_ips:
382 if snaps_floating_ip.ip == my_floating_ip:
383 self.mano['details']['fip'] = snaps_floating_ip
385 "Selected floating IP for Open Baton NFVO %s",
386 (self.mano['details']['fip'].ip))
388 if self.mano['details']['fip'] is not None:
391 self.logger.info("Creating floating IP for Open Baton NFVO")
392 self.mano['details']['fip'] = (
393 snaps_utils.neutron_utils. create_floating_ip(
394 neutron_client, self.mano['details']['external_net_name']))
396 "Created floating IP for Open Baton NFVO %s",
397 (self.mano['details']['fip'].ip))
399 def get_vim_descriptor(self):
400 """"Create VIM descriptor to be used for onboarding"""
402 "Building VIM descriptor with PoP creds: %s",
404 # Depending on API version either tenant ID or project name must be
406 if os_utils.is_keystone_v3():
408 "Using v3 API of OpenStack... -> Using OS_PROJECT_ID")
409 project_id = os_utils.get_tenant_id(
410 os_utils.get_keystone_client(),
411 self.creds.get("project_name"))
414 "Using v2 API of OpenStack... -> Using OS_TENANT_NAME")
415 project_id = self.creds.get("tenant_name")
416 self.logger.debug("VIM project/tenant id: %s", project_id)
418 "name": "vim-instance",
419 "authUrl": self.creds.get("auth_url"),
420 "tenant": project_id,
421 "username": self.creds.get("username"),
422 "password": self.creds.get("password"),
424 self.mano['details']['sec_group']
429 "latitude": "52.525876",
430 "longitude": "13.314400"
433 self.logger.info("Built VIM descriptor: %s", vim_json)
436 def deploy_orchestrator(self):
437 self.logger.info("Deploying Open Baton...")
438 self.logger.info("Details: %s", self.mano['details'])
439 start_time = time.time()
441 self.logger.info("Creating orchestra instance...")
442 userdata = get_userdata(self.mano)
443 self.logger.info("flavor: %s\n"
446 self.mano['details']['flavor']['name'],
447 self.mano['requirements']['image'],
448 self.mano['details']['network']['id'])
449 self.logger.debug("userdata: %s\n", userdata)
451 image_settings = ImageSettings(
452 name=self.mano['requirements']['image'],
456 port_settings = PortSettings(
457 name='%s_port' % self.case_name,
458 network_name=self.mano['details']['network']['name'])
459 # build configuration of vm
460 orchestra_settings = VmInstanceSettings(
462 flavor=self.mano['details']['flavor']['name'],
463 port_settings=[port_settings],
464 security_group_names=[self.mano['details']['sec_group']],
466 orchestra_vm = OpenStackVmInstance(self.snaps_creds,
470 orchestra_vm.create()
471 self.created_resources.append(orchestra_vm)
472 self.mano['details']['id'] = orchestra_vm.get_vm_info()['id']
474 "Created orchestra instance: %s",
475 self.mano['details']['id'])
477 self.logger.info("Associating floating ip: '%s' to VM '%s' ",
478 self.mano['details']['fip'].ip,
480 nova_client = os_utils.get_nova_client()
481 if not os_utils.add_floating_ip(
483 self.mano['details']['id'],
484 self.mano['details']['fip'].ip):
485 duration = time.time() - start_time
486 self.details["orchestrator"].update(
487 status='FAIL', duration=duration)
488 self.logger.error("Cannot associate floating IP to VM.")
491 self.logger.info("Waiting for Open Baton NFVO to be up and running...")
495 self.mano['details']['fip'].ip,
499 self.logger.info("Open Baton NFVO is not started yet (%ss)",
505 duration = time.time() - start_time
506 self.details["orchestrator"].update(
507 status='FAIL', duration=duration)
508 self.logger.error("Open Baton is not started correctly")
511 self.logger.info("Waiting for all components to be up and running...")
513 duration = time.time() - start_time
514 self.details["orchestrator"].update(status='PASS', duration=duration)
515 self.logger.info("Deploy Open Baton NFVO: OK")
518 def deploy_vnf(self):
519 start_time = time.time()
520 self.logger.info("Deploying %s...", self.vnf['name'])
522 main_agent = MainAgent(
523 nfvo_ip=self.mano['details']['fip'].ip,
527 username=self.mano['credentials']['username'],
528 password=self.mano['credentials']['password'])
531 "Create %s Flavor if not existing", self.vnf['name'])
532 flavor_settings = FlavorSettings(
533 name=self.vnf['requirements']['flavor']['name'],
534 ram=self.vnf['requirements']['flavor']['ram_min'],
535 disk=self.vnf['requirements']['flavor']['disk'],
536 vcpus=self.vnf['requirements']['flavor']['vcpus'])
537 flavor = OpenStackFlavor(self.snaps_creds, flavor_settings)
538 flavor_info = flavor.create()
539 self.logger.debug("Flavor id: %s", flavor_info.id)
541 self.logger.info("Getting project 'default'...")
542 project_agent = main_agent.get_agent("project", "")
543 for project in json.loads(project_agent.find()):
544 if project.get("name") == "default":
545 self.mano['details']['project_id'] = project.get("id")
546 self.logger.info("Found project 'default': %s", project)
549 vim_json = self.get_vim_descriptor()
550 self.logger.info("Registering VIM: %s", vim_json)
552 main_agent.get_agent(
553 "vim", project_id=self.mano['details']['project_id']).create(
554 entity=json.dumps(vim_json))
556 market_agent = main_agent.get_agent(
557 "market", project_id=self.mano['details']['project_id'])
560 self.logger.info("sending: %s", self.vnf['descriptor']['url'])
561 nsd = market_agent.create(entity=self.vnf['descriptor']['url'])
562 if nsd.get('id') is None:
563 self.logger.error("NSD not onboarded correctly")
564 duration = time.time() - start_time
565 self.details["vnf"].update(status='FAIL', duration=duration)
567 self.mano['details']['nsd_id'] = nsd.get('id')
568 self.logger.info("Onboarded NSD: " + nsd.get("name"))
570 nsr_agent = main_agent.get_agent(
571 "nsr", project_id=self.mano['details']['project_id'])
573 self.mano['details']['nsr'] = nsr_agent.create(
574 self.mano['details']['nsd_id'])
575 except NfvoException as exc:
576 self.logger.error(exc.message)
577 duration = time.time() - start_time
578 self.details["vnf"].update(status='FAIL', duration=duration)
581 if self.mano['details']['nsr'].get('code') is not None:
583 "%s cannot be deployed: %s -> %s",
585 self.mano['details']['nsr'].get('code'),
586 self.mano['details']['nsr'].get('message'))
587 self.logger.error("%s cannot be deployed", self.vnf['name'])
588 duration = time.time() - start_time
589 self.details["vnf"].update(status='FAIL', duration=duration)
593 self.logger.info("Waiting for NSR to go to ACTIVE...")
594 while self.mano['details']['nsr'].get("status") != 'ACTIVE' \
595 and self.mano['details']['nsr'].get("status") != 'ERROR':
597 self.logger.info("NSR is not yet ACTIVE... (%ss)", 5 * timeout)
599 self.logger.error("INACTIVE NSR after %s sec..", 5 * timeout)
600 duration = time.time() - start_time
601 self.details["vnf"].update(status='FAIL', duration=duration)
604 self.mano['details']['nsr'] = json.loads(
605 nsr_agent.find(self.mano['details']['nsr'].get('id')))
607 duration = time.time() - start_time
608 if self.mano['details']['nsr'].get("status") == 'ACTIVE':
609 self.details["vnf"].update(status='PASS', duration=duration)
610 self.logger.info("Sleep for 60s to ensure that all "
611 "services are up and running...")
615 self.details["vnf"].update(status='FAIL', duration=duration)
616 self.logger.error("NSR: %s", self.mano['details'].get('nsr'))
621 self.logger.info("Testing VNF OpenIMS...")
622 start_time = time.time()
624 "Testing if %s works properly...",
625 self.mano['details']['nsr'].get('name'))
626 for vnfr in self.mano['details']['nsr'].get('vnfr'):
628 "Checking ports %s of VNF %s",
629 self.vnf['test'][vnfr.get('name')]['ports'],
631 for vdu in vnfr.get('vdu'):
632 for vnfci in vdu.get('vnfc_instance'):
634 "Checking ports of VNFC instance %s",
635 vnfci.get('hostname'))
636 for floating_ip in vnfci.get('floatingIps'):
639 vnfci.get('hostname'),
640 floating_ip.get('ip'))
641 for port in self.vnf['test'][vnfr.get(
643 if servertest(floating_ip.get('ip'), port):
645 "VNFC instance %s is reachable at %s:%s",
646 vnfci.get('hostname'),
647 floating_ip.get('ip'),
651 "VNFC instance %s is not reachable "
653 vnfci.get('hostname'),
654 floating_ip.get('ip'),
656 duration = time.time() - start_time
657 self.details["test_vnf"].update(
658 status='FAIL', duration=duration, esult=(
659 "Port %s of server %s -> %s is "
662 vnfci.get('hostname'),
663 floating_ip.get('ip')))
664 self.logger.error("Test VNF: ERROR")
666 duration = time.time() - start_time
667 self.details["test_vnf"].update(status='PASS', duration=duration)
668 self.logger.info("Test VNF: OK")
672 self.logger.info("Cleaning %s...", self.case_name)
674 main_agent = MainAgent(
675 nfvo_ip=self.mano['details']['fip'].ip,
679 username=self.mano['credentials']['username'],
680 password=self.mano['credentials']['password'])
681 self.logger.info("Terminating %s...", self.vnf['name'])
682 if (self.mano['details'].get('nsr')):
683 main_agent.get_agent(
685 project_id=self.mano['details']['project_id']).\
686 delete(self.mano['details']['nsr'].get('id'))
687 self.logger.info("Sleeping 60 seconds...")
690 self.logger.info("No need to terminate the VNF...")
691 # os_utils.delete_instance(nova_client=os_utils.get_nova_client(),
692 # instance_id=self.mano_instance_id)
693 except (NfvoException, KeyError) as exc:
694 self.logger.error('Unexpected error cleaning - %s', exc)
697 neutron_client = os_utils.get_neutron_client(self.creds)
698 self.logger.info("Deleting Open Baton Port...")
699 port = snaps_utils.neutron_utils.get_port_by_name(
700 neutron_client, '%s_port' % self.case_name)
701 snaps_utils.neutron_utils.delete_port(neutron_client, port)
703 except Exception as exc:
704 self.logger.error('Unexpected error cleaning - %s', exc)
706 self.logger.info("Deleting Open Baton Floating IP...")
707 snaps_utils.neutron_utils.delete_floating_ip(
708 neutron_client, self.mano['details']['fip'])
709 except Exception as exc:
710 self.logger.error('Unexpected error cleaning - %s', exc)
712 for resource in reversed(self.created_resources):
714 self.logger.info("Cleaning %s", str(resource))
716 except Exception as exc:
717 self.logger.error('Unexpected error cleaning - %s', exc)
718 super(OpenImsVnf, self).clean()