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.%s" %
199 self.case_name, config_file)
200 self.images.update(get_config("tenant_images.%s" %
201 self.case_name, config_file))
202 self.snaps_creds = None
205 """Prepare testscase (Additional pre-configuration steps)."""
206 super(OpenImsVnf, self).prepare()
208 self.logger.info("Additional pre-configuration steps")
209 self.logger.info("creds %s", (self.creds))
211 self.snaps_creds = OSCreds(
212 username=self.creds['username'],
213 password=self.creds['password'],
214 auth_url=self.creds['auth_url'],
215 project_name=self.creds['tenant'],
216 identity_api_version=int(os_utils.get_keystone_client_version()))
218 self.prepare_images()
219 self.prepare_flavor()
220 self.prepare_security_groups()
221 self.prepare_network()
222 self.prepare_floating_ip()
224 def prepare_images(self):
225 """Upload images if they doen't exist yet"""
226 self.logger.info("Upload images if they doen't exist yet")
227 for image_name, image_url in self.images.iteritems():
228 self.logger.info("image: %s, url: %s", image_name, image_url)
229 if image_url and image_name:
230 image = OpenStackImage(
232 ImageSettings(name=image_name,
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'] = \
345 snaps_utils.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'] = (
394 snaps_utils.neutron_utils. create_floating_ip(
395 neutron_client, self.mano['details']['external_net_name']))
397 "Created floating IP for Open Baton NFVO %s",
398 (self.mano['details']['fip'].ip))
400 def get_vim_descriptor(self):
401 """"Create VIM descriptor to be used for onboarding"""
403 "Building VIM descriptor with PoP creds: %s",
405 # Depending on API version either tenant ID or project name must be
407 if os_utils.is_keystone_v3():
409 "Using v3 API of OpenStack... -> Using OS_PROJECT_ID")
410 project_id = os_utils.get_tenant_id(
411 os_utils.get_keystone_client(),
412 self.creds.get("project_name"))
415 "Using v2 API of OpenStack... -> Using OS_TENANT_NAME")
416 project_id = self.creds.get("tenant_name")
417 self.logger.debug("VIM project/tenant id: %s", project_id)
419 "name": "vim-instance",
420 "authUrl": self.creds.get("auth_url"),
421 "tenant": project_id,
422 "username": self.creds.get("username"),
423 "password": self.creds.get("password"),
425 self.mano['details']['sec_group']
430 "latitude": "52.525876",
431 "longitude": "13.314400"
434 self.logger.info("Built VIM descriptor: %s", vim_json)
437 def deploy_orchestrator(self):
438 self.logger.info("Deploying Open Baton...")
439 self.logger.info("Details: %s", self.mano['details'])
440 start_time = time.time()
442 self.logger.info("Creating orchestra instance...")
443 userdata = get_userdata(self.mano)
444 self.logger.info("flavor: %s\n"
447 self.mano['details']['flavor']['name'],
448 self.mano['requirements']['image'],
449 self.mano['details']['network']['id'])
450 self.logger.debug("userdata: %s\n", userdata)
452 image_settings = ImageSettings(
453 name=self.mano['requirements']['image'],
457 port_settings = PortSettings(
458 name='%s_port' % self.case_name,
459 network_name=self.mano['details']['network']['name'])
460 # build configuration of vm
461 orchestra_settings = VmInstanceSettings(
463 flavor=self.mano['details']['flavor']['name'],
464 port_settings=[port_settings],
465 security_group_names=[self.mano['details']['sec_group']],
467 orchestra_vm = OpenStackVmInstance(self.snaps_creds,
471 orchestra_vm.create()
472 self.created_resources.append(orchestra_vm)
473 self.mano['details']['id'] = orchestra_vm.get_vm_info()['id']
475 "Created orchestra instance: %s",
476 self.mano['details']['id'])
478 self.logger.info("Associating floating ip: '%s' to VM '%s' ",
479 self.mano['details']['fip'].ip,
481 nova_client = os_utils.get_nova_client()
482 if not os_utils.add_floating_ip(
484 self.mano['details']['id'],
485 self.mano['details']['fip'].ip):
486 duration = time.time() - start_time
487 self.details["orchestrator"].update(
488 status='FAIL', duration=duration)
489 self.logger.error("Cannot associate floating IP to VM.")
492 self.logger.info("Waiting for Open Baton NFVO to be up and running...")
496 self.mano['details']['fip'].ip,
500 self.logger.info("Open Baton NFVO is not started yet (%ss)",
506 duration = time.time() - start_time
507 self.details["orchestrator"].update(
508 status='FAIL', duration=duration)
509 self.logger.error("Open Baton is not started correctly")
512 self.logger.info("Waiting for all components to be up and running...")
514 duration = time.time() - start_time
515 self.details["orchestrator"].update(status='PASS', duration=duration)
516 self.logger.info("Deploy Open Baton NFVO: OK")
519 def deploy_vnf(self):
520 start_time = time.time()
521 self.logger.info("Deploying %s...", self.vnf['name'])
523 main_agent = MainAgent(
524 nfvo_ip=self.mano['details']['fip'].ip,
528 username=self.mano['credentials']['username'],
529 password=self.mano['credentials']['password'])
532 "Create %s Flavor if not existing", self.vnf['name'])
533 flavor_settings = FlavorSettings(
534 name=self.vnf['requirements']['flavor']['name'],
535 ram=self.vnf['requirements']['flavor']['ram_min'],
536 disk=self.vnf['requirements']['flavor']['disk'],
537 vcpus=self.vnf['requirements']['flavor']['vcpus'])
538 flavor = OpenStackFlavor(self.snaps_creds, flavor_settings)
539 flavor_info = flavor.create()
540 self.logger.debug("Flavor id: %s", flavor_info.id)
542 self.logger.info("Getting project 'default'...")
543 project_agent = main_agent.get_agent("project", "")
544 for project in json.loads(project_agent.find()):
545 if project.get("name") == "default":
546 self.mano['details']['project_id'] = project.get("id")
547 self.logger.info("Found project 'default': %s", project)
550 vim_json = self.get_vim_descriptor()
551 self.logger.info("Registering VIM: %s", vim_json)
553 main_agent.get_agent(
554 "vim", project_id=self.mano['details']['project_id']).create(
555 entity=json.dumps(vim_json))
557 market_agent = main_agent.get_agent(
558 "market", project_id=self.mano['details']['project_id'])
561 self.logger.info("sending: %s", self.vnf['descriptor']['url'])
562 nsd = market_agent.create(entity=self.vnf['descriptor']['url'])
563 if nsd.get('id') is None:
564 self.logger.error("NSD not onboarded correctly")
565 duration = time.time() - start_time
566 self.details["vnf"].update(status='FAIL', duration=duration)
568 self.mano['details']['nsd_id'] = nsd.get('id')
569 self.logger.info("Onboarded NSD: " + nsd.get("name"))
571 nsr_agent = main_agent.get_agent(
572 "nsr", project_id=self.mano['details']['project_id'])
574 self.mano['details']['nsr'] = nsr_agent.create(
575 self.mano['details']['nsd_id'])
576 except NfvoException as exc:
577 self.logger.error(exc.message)
578 duration = time.time() - start_time
579 self.details["vnf"].update(status='FAIL', duration=duration)
582 if self.mano['details']['nsr'].get('code') is not None:
584 "%s cannot be deployed: %s -> %s",
586 self.mano['details']['nsr'].get('code'),
587 self.mano['details']['nsr'].get('message'))
588 self.logger.error("%s cannot be deployed", self.vnf['name'])
589 duration = time.time() - start_time
590 self.details["vnf"].update(status='FAIL', duration=duration)
594 self.logger.info("Waiting for NSR to go to ACTIVE...")
595 while self.mano['details']['nsr'].get("status") != 'ACTIVE' \
596 and self.mano['details']['nsr'].get("status") != 'ERROR':
598 self.logger.info("NSR is not yet ACTIVE... (%ss)", 5 * timeout)
600 self.logger.error("INACTIVE NSR after %s sec..", 5 * timeout)
601 duration = time.time() - start_time
602 self.details["vnf"].update(status='FAIL', duration=duration)
605 self.mano['details']['nsr'] = json.loads(
606 nsr_agent.find(self.mano['details']['nsr'].get('id')))
608 duration = time.time() - start_time
609 if self.mano['details']['nsr'].get("status") == 'ACTIVE':
610 self.details["vnf"].update(status='PASS', duration=duration)
611 self.logger.info("Sleep for 60s to ensure that all "
612 "services are up and running...")
616 self.details["vnf"].update(status='FAIL', duration=duration)
617 self.logger.error("NSR: %s", self.mano['details'].get('nsr'))
622 self.logger.info("Testing VNF OpenIMS...")
623 start_time = time.time()
625 "Testing if %s works properly...",
626 self.mano['details']['nsr'].get('name'))
627 for vnfr in self.mano['details']['nsr'].get('vnfr'):
629 "Checking ports %s of VNF %s",
630 self.vnf['test'][vnfr.get('name')]['ports'],
632 for vdu in vnfr.get('vdu'):
633 for vnfci in vdu.get('vnfc_instance'):
635 "Checking ports of VNFC instance %s",
636 vnfci.get('hostname'))
637 for floating_ip in vnfci.get('floatingIps'):
640 vnfci.get('hostname'),
641 floating_ip.get('ip'))
642 for port in self.vnf['test'][vnfr.get(
644 if servertest(floating_ip.get('ip'), port):
646 "VNFC instance %s is reachable at %s:%s",
647 vnfci.get('hostname'),
648 floating_ip.get('ip'),
652 "VNFC instance %s is not reachable "
654 vnfci.get('hostname'),
655 floating_ip.get('ip'),
657 duration = time.time() - start_time
658 self.details["test_vnf"].update(
659 status='FAIL', duration=duration, esult=(
660 "Port %s of server %s -> %s is "
663 vnfci.get('hostname'),
664 floating_ip.get('ip')))
665 self.logger.error("Test VNF: ERROR")
667 duration = time.time() - start_time
668 self.details["test_vnf"].update(status='PASS', duration=duration)
669 self.logger.info("Test VNF: OK")
673 self.logger.info("Cleaning %s...", self.case_name)
675 main_agent = MainAgent(
676 nfvo_ip=self.mano['details']['fip'].ip,
680 username=self.mano['credentials']['username'],
681 password=self.mano['credentials']['password'])
682 self.logger.info("Terminating %s...", self.vnf['name'])
683 if (self.mano['details'].get('nsr')):
684 main_agent.get_agent(
686 project_id=self.mano['details']['project_id']).\
687 delete(self.mano['details']['nsr'].get('id'))
688 self.logger.info("Sleeping 60 seconds...")
691 self.logger.info("No need to terminate the VNF...")
692 # os_utils.delete_instance(nova_client=os_utils.get_nova_client(),
693 # instance_id=self.mano_instance_id)
694 except (NfvoException, KeyError) as exc:
695 self.logger.error('Unexpected error cleaning - %s', exc)
698 neutron_client = os_utils.get_neutron_client(self.creds)
699 self.logger.info("Deleting Open Baton Port...")
700 port = snaps_utils.neutron_utils.get_port_by_name(
701 neutron_client, '%s_port' % self.case_name)
702 snaps_utils.neutron_utils.delete_port(neutron_client, port)
704 except Exception as exc:
705 self.logger.error('Unexpected error cleaning - %s', exc)
707 self.logger.info("Deleting Open Baton Floating IP...")
708 snaps_utils.neutron_utils.delete_floating_ip(
709 neutron_client, self.mano['details']['fip'])
710 except Exception as exc:
711 self.logger.error('Unexpected error cleaning - %s', exc)
713 for resource in reversed(self.created_resources):
715 self.logger.info("Cleaning %s", str(resource))
717 except Exception as exc:
718 self.logger.error('Unexpected error cleaning - %s', exc)
719 super(OpenImsVnf, self).clean()