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.config.flavor import FlavorConfig
21 from snaps.config.image import ImageConfig
22 from snaps.config.network import NetworkConfig, PortConfig, SubnetConfig
23 from snaps.config.router import RouterConfig
24 from snaps.config.security_group import (
25 Direction, Protocol, SecurityGroupConfig, SecurityGroupRuleConfig)
26 from snaps.config.vm_inst import VmInstanceConfig
28 from snaps.openstack.create_flavor import OpenStackFlavor
29 from snaps.openstack.create_image import OpenStackImage
30 from snaps.openstack.create_instance import OpenStackVmInstance
31 from snaps.openstack.create_network import OpenStackNetwork
32 from snaps.openstack.create_router import OpenStackRouter
33 from snaps.openstack.create_security_group import OpenStackSecurityGroup
35 from functest.opnfv_tests.openstack.snaps import snaps_utils
37 import functest.core.vnf as vnf
38 import functest.utils.openstack_utils as os_utils
39 from functest.utils.constants import CONST
41 from org.openbaton.cli.errors.errors import NfvoException
42 from org.openbaton.cli.agents.agents import MainAgent
45 __author__ = "Pauls, Michael <michael.pauls@fokus.fraunhofer.de>"
46 # ----------------------------------------------------------
50 # -----------------------------------------------------------
53 def get_config(parameter, file_path):
57 Returns the value of a given parameter in file.yaml
58 parameter must be given in string format with dots
59 Example: general.openstack.image_name
61 with open(file_path) as config_file:
62 file_yaml = yaml.safe_load(config_file)
65 for element in parameter.split("."):
66 value = value.get(element)
68 raise ValueError("The parameter %s is not defined in"
69 " reporting.yaml", parameter)
73 def servertest(host, port):
74 """Method to test that a server is reachable at IP:port"""
75 args = socket.getaddrinfo(host, port, socket.AF_INET, socket.SOCK_STREAM)
76 for family, socktype, proto, canonname, sockaddr in args:
77 sock = socket.socket(family, socktype, proto)
79 sock.connect(sockaddr)
87 def get_userdata(orchestrator=dict):
88 """Build userdata for Open Baton machine"""
89 userdata = "#!/bin/bash\n"
90 userdata += "echo \"Executing userdata...\"\n"
91 userdata += "set -x\n"
92 userdata += "set -e\n"
93 userdata += "echo \"Set nameserver to '8.8.8.8'...\"\n"
94 userdata += "echo \"nameserver 8.8.8.8\" >> /etc/resolv.conf\n"
95 userdata += "echo \"Install curl...\"\n"
96 userdata += "apt-get install curl\n"
97 userdata += "echo \"Inject public key...\"\n"
98 userdata += ("echo \"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCuPXrV3"
99 "geeHc6QUdyUr/1Z+yQiqLcOskiEGBiXr4z76MK4abiFmDZ18OMQlc"
100 "fl0p3kS0WynVgyaOHwZkgy/DIoIplONVr2CKBKHtPK+Qcme2PVnCtv"
101 "EqItl/FcD+1h5XSQGoa+A1TSGgCod/DPo+pes0piLVXP8Ph6QS1k7S"
102 "ic7JDeRQ4oT1bXYpJ2eWBDMfxIWKZqcZRiGPgMIbJ1iEkxbpeaAd9O"
103 "4MiM9nGCPESmed+p54uYFjwEDlAJZShcAZziiZYAvMZhvAhe6USljc"
104 "7YAdalAnyD/jwCHuwIrUw/lxo7UdNCmaUxeobEYyyFA1YVXzpNFZya"
105 "XPGAAYIJwEq/ openbaton@opnfv\" >> /home/ubuntu/.ssh/aut"
107 userdata += "echo \"Download bootstrap...\"\n"
108 userdata += ("curl -s %s "
109 "> ./bootstrap\n" % orchestrator['bootstrap']['url'])
110 userdata += ("curl -s %s" "> ./config_file\n" %
111 orchestrator['bootstrap']['config']['url'])
112 userdata += ("echo \"Disable usage of mysql...\"\n")
113 userdata += "sed -i s/mysql=.*/mysql=no/g /config_file\n"
114 userdata += ("echo \"Setting 'rabbitmq_broker_ip' to '%s'\"\n"
115 % orchestrator['details']['fip'].ip)
116 userdata += ("sed -i s/rabbitmq_broker_ip=localhost/rabbitmq_broker_ip"
117 "=%s/g /config_file\n" % orchestrator['details']['fip'].ip)
118 userdata += "echo \"Set autostart of components to 'false'\"\n"
119 userdata += "export OPENBATON_COMPONENT_AUTOSTART=false\n"
120 userdata += "echo \"Execute bootstrap...\"\n"
121 bootstrap = "sh ./bootstrap release -configFile=./config_file"
122 userdata += bootstrap + "\n"
123 userdata += "echo \"Setting 'nfvo.plugin.timeout' to '300000'\"\n"
124 userdata += ("echo \"nfvo.plugin.timeout=600000\" >> "
125 "/etc/openbaton/openbaton-nfvo.properties\n")
127 "wget %s -O /etc/openbaton/openbaton-vnfm-generic-user-data.sh\n" %
128 orchestrator['gvnfm']['userdata']['url'])
129 userdata += "sed -i '113i"'\ \ \ \ '"sleep 60' " \
130 "/etc/openbaton/openbaton-vnfm-generic-user-data.sh\n"
131 userdata += ("sed -i s/nfvo.marketplace.port=8082/nfvo.marketplace."
132 "port=8080/g /etc/openbaton/openbaton-nfvo.properties\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")
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)
204 self.snaps_creds = None
207 """Prepare testscase (Additional pre-configuration steps)."""
208 super(ClearwaterImsVnf, self).prepare()
210 self.logger.info("Additional pre-configuration steps")
213 "tenant": self.tenant_name,
214 "username": self.tenant_name,
215 "password": self.tenant_name,
216 "auth_url": os_utils.get_credentials()['auth_url']
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_file in self.images.iteritems():
228 self.logger.info("image: %s, file: %s", image_name, image_file)
229 if image_file and image_name:
230 image = OpenStackImage(
232 ImageConfig(name=image_name,
235 image_file=image_file,
238 # self.created_resources.append(image);
240 def prepare_security_groups(self):
241 """Create Open Baton security group if it doesn't exist yet"""
243 "Creating security group for Open Baton if not yet existing...")
246 SecurityGroupRuleConfig(
247 sec_grp_name="orchestra-sec-group-allowall",
248 direction=Direction.ingress,
249 protocol=Protocol.tcp,
251 port_range_max=65535))
253 SecurityGroupRuleConfig(
254 sec_grp_name="orchestra-sec-group-allowall",
255 direction=Direction.egress,
256 protocol=Protocol.tcp,
258 port_range_max=65535))
260 SecurityGroupRuleConfig(
261 sec_grp_name="orchestra-sec-group-allowall",
262 direction=Direction.ingress,
263 protocol=Protocol.udp,
265 port_range_max=65535))
267 SecurityGroupRuleConfig(
268 sec_grp_name="orchestra-sec-group-allowall",
269 direction=Direction.egress,
270 protocol=Protocol.udp,
272 port_range_max=65535))
274 SecurityGroupRuleConfig(
275 sec_grp_name="orchestra-sec-group-allowall",
276 direction=Direction.ingress,
277 protocol=Protocol.icmp))
279 SecurityGroupRuleConfig(
280 sec_grp_name="orchestra-sec-group-allowall",
281 direction=Direction.egress,
282 protocol=Protocol.icmp))
283 security_group = OpenStackSecurityGroup(
286 name="orchestra-sec-group-allowall",
287 rule_settings=sg_rules))
289 security_group_info = security_group.create()
290 self.created_resources.append(security_group)
291 self.mano['details']['sec_group'] = security_group_info.name
293 "Security group orchestra-sec-group-allowall prepared")
295 def prepare_flavor(self):
296 """Create Open Baton flavor if it doesn't exist yet"""
298 "Create Flavor for Open Baton NFVO if not yet existing")
300 flavor_settings = FlavorConfig(
301 name=self.mano['requirements']['flavor']['name'],
302 ram=self.mano['requirements']['flavor']['ram_min'],
303 disk=self.mano['requirements']['flavor']['disk'],
304 vcpus=self.mano['requirements']['flavor']['vcpus'])
305 flavor = OpenStackFlavor(self.snaps_creds, flavor_settings)
306 flavor_info = flavor.create()
307 self.created_resources.append(flavor)
308 self.mano['details']['flavor'] = {}
309 self.mano['details']['flavor']['name'] = flavor_settings.name
310 self.mano['details']['flavor']['id'] = flavor_info.id
312 def prepare_network(self):
313 """Create network/subnet/router if they doen't exist yet"""
315 "Creating network/subnet/router if they doen't exist yet...")
316 subnet_settings = SubnetConfig(
319 cidr="192.168.100.0/24")
320 network_settings = NetworkConfig(
323 subnet_settings=[subnet_settings])
324 orchestra_network = OpenStackNetwork(
325 self.snaps_creds, network_settings)
326 orchestra_network_info = orchestra_network.create()
327 self.mano['details']['network'] = {}
328 self.mano['details']['network']['id'] = orchestra_network_info.id
329 self.mano['details']['network']['name'] = orchestra_network_info.name
330 self.mano['details']['external_net_name'] = snaps_utils.\
331 get_ext_net_name(self.snaps_creds)
332 self.created_resources.append(orchestra_network)
333 orchestra_router = OpenStackRouter(
338 external_gateway=self.mano['details']['external_net_name'],
340 subnet_settings.name]))
341 orchestra_router.create()
342 self.created_resources.append(orchestra_router)
343 self.logger.info("Created network and router for Open Baton NFVO...")
345 def prepare_floating_ip(self):
346 """Select/Create Floating IP if it doesn't exist yet"""
347 self.logger.info("Retrieving floating IP for Open Baton NFVO")
348 neutron_client = snaps_utils.neutron_utils.neutron_client(
350 # Finding Tenant ID to check to which tenant the Floating IP belongs
351 tenant_id = os_utils.get_tenant_id(
352 os_utils.get_keystone_client(self.creds),
354 # Use os_utils to retrieve complete information of Floating IPs
355 floating_ips = os_utils.get_floating_ips(neutron_client)
357 # Filter Floating IPs with tenant id
358 for floating_ip in floating_ips:
359 # self.logger.info("Floating IP: %s", floating_ip)
360 if floating_ip.get('tenant_id') == tenant_id:
361 my_floating_ips.append(floating_ip.get('floating_ip_address'))
362 # Select if Floating IP exist else create new one
363 if len(my_floating_ips) >= 1:
364 # Get Floating IP object from snaps for clean up
365 snaps_floating_ips = snaps_utils.neutron_utils.get_floating_ips(
367 for my_floating_ip in my_floating_ips:
368 for snaps_floating_ip in snaps_floating_ips:
369 if snaps_floating_ip.ip == my_floating_ip:
370 self.mano['details']['fip'] = snaps_floating_ip
372 "Selected floating IP for Open Baton NFVO %s",
373 (self.mano['details']['fip'].ip))
375 if self.mano['details']['fip'] is not None:
378 self.logger.info("Creating floating IP for Open Baton NFVO")
379 self.mano['details']['fip'] = snaps_utils.neutron_utils.\
382 self.mano['details']['external_net_name'])
384 "Created floating IP for Open Baton NFVO %s",
385 (self.mano['details']['fip'].ip))
387 def get_vim_descriptor(self):
388 """"Create VIM descriptor to be used for onboarding"""
390 "Building VIM descriptor with PoP creds: %s",
392 # Depending on API version either tenant ID or project name must be
394 if os_utils.is_keystone_v3():
396 "Using v3 API of OpenStack... -> Using OS_PROJECT_ID")
397 project_id = os_utils.get_tenant_id(
398 os_utils.get_keystone_client(),
399 self.creds.get("project_name"))
402 "Using v2 API of OpenStack... -> Using OS_TENANT_NAME")
403 project_id = self.creds.get("tenant_name")
404 self.logger.debug("VIM project/tenant id: %s", project_id)
406 "name": "vim-instance",
407 "authUrl": self.creds.get("auth_url"),
408 "tenant": project_id,
409 "username": self.creds.get("username"),
410 "password": self.creds.get("password"),
412 self.mano['details']['sec_group']
417 "latitude": "52.525876",
418 "longitude": "13.314400"
421 self.logger.info("Built VIM descriptor: %s", vim_json)
424 def deploy_orchestrator(self):
425 self.logger.info("Deploying Open Baton...")
426 self.logger.info("Details: %s", self.mano['details'])
427 start_time = time.time()
429 self.logger.info("Creating orchestra instance...")
430 userdata = get_userdata(self.mano)
431 self.logger.info("flavor: %s\n"
434 self.mano['details']['flavor']['name'],
435 self.mano['requirements']['image'],
436 self.mano['details']['network']['id'])
437 self.logger.debug("userdata: %s\n", userdata)
439 image_settings = ImageConfig(
440 name=self.mano['requirements']['image'],
444 port_settings = PortConfig(
445 name='%s_port' % self.case_name,
446 network_name=self.mano['details']['network']['name'])
447 # build configuration of vm
448 orchestra_settings = VmInstanceConfig(
450 flavor=self.mano['details']['flavor']['name'],
451 port_settings=[port_settings],
452 security_group_names=[self.mano['details']['sec_group']],
453 userdata=str(userdata))
454 orchestra_vm = OpenStackVmInstance(self.snaps_creds,
458 orchestra_vm.create()
459 self.created_resources.append(orchestra_vm)
460 self.mano['details']['id'] = orchestra_vm.get_vm_info()['id']
462 "Created orchestra instance: %s",
463 self.mano['details']['id'])
465 self.logger.info("Associating floating ip: '%s' to VM '%s' ",
466 self.mano['details']['fip'].ip,
468 nova_client = os_utils.get_nova_client()
469 if not os_utils.add_floating_ip(
471 self.mano['details']['id'],
472 self.mano['details']['fip'].ip):
473 duration = time.time() - start_time
474 self.details["orchestrator"].update(
475 status='FAIL', duration=duration)
476 self.logger.error("Cannot associate floating IP to VM.")
479 self.logger.info("Waiting for Open Baton NFVO to be up and running...")
483 self.mano['details']['fip'].ip,
488 "Open Baton NFVO is not started yet (%ss)",
494 duration = time.time() - start_time
495 self.details["orchestrator"].update(
496 status='FAIL', duration=duration)
497 self.logger.error("Open Baton is not started correctly")
500 self.logger.info("Waiting for all components to be up and running...")
502 duration = time.time() - start_time
503 self.details["orchestrator"].update(status='PASS', duration=duration)
504 self.logger.info("Deploy Open Baton NFVO: OK")
507 def deploy_vnf(self):
508 start_time = time.time()
509 self.logger.info("Deploying %s...", self.vnf['name'])
511 main_agent = MainAgent(
512 nfvo_ip=self.mano['details']['fip'].ip,
516 username=self.mano['credentials']['username'],
517 password=self.mano['credentials']['password'])
520 "Create %s Flavor if not existing", self.vnf['name'])
521 flavor_settings = FlavorConfig(
522 name=self.vnf['requirements']['flavor']['name'],
523 ram=self.vnf['requirements']['flavor']['ram_min'],
524 disk=self.vnf['requirements']['flavor']['disk'],
525 vcpus=self.vnf['requirements']['flavor']['vcpus'])
526 flavor = OpenStackFlavor(self.snaps_creds, flavor_settings)
527 flavor_info = flavor.create()
528 self.logger.debug("Flavor id: %s", flavor_info.id)
530 self.logger.info("Getting project 'default'...")
531 project_agent = main_agent.get_agent("project", "")
532 for project in json.loads(project_agent.find()):
533 if project.get("name") == "default":
534 self.mano['details']['project_id'] = project.get("id")
535 self.logger.info("Found project 'default': %s", project)
538 vim_json = self.get_vim_descriptor()
539 self.logger.info("Registering VIM: %s", vim_json)
541 main_agent.get_agent(
542 "vim", project_id=self.mano['details']['project_id']).create(
543 entity=json.dumps(vim_json))
545 market_agent = main_agent.get_agent(
546 "market", project_id=self.mano['details']['project_id'])
549 self.logger.info("sending: %s", self.vnf['descriptor']['url'])
550 nsd = market_agent.create(entity=self.vnf['descriptor']['url'])
551 if nsd.get('id') is None:
552 self.logger.error("NSD not onboarded correctly")
553 duration = time.time() - start_time
554 self.details["vnf"].update(status='FAIL', duration=duration)
556 self.mano['details']['nsd_id'] = nsd.get('id')
557 self.logger.info("Onboarded NSD: " + nsd.get("name"))
559 nsr_agent = main_agent.get_agent(
560 "nsr", project_id=self.mano['details']['project_id'])
562 self.mano['details']['nsr'] = nsr_agent.create(
563 self.mano['details']['nsd_id'])
564 except NfvoException as exc:
565 self.logger.error(exc.message)
566 duration = time.time() - start_time
567 self.details["vnf"].update(status='FAIL', duration=duration)
570 if self.mano['details']['nsr'].get('code') is not None:
572 "%s cannot be deployed: %s -> %s",
574 self.mano['details']['nsr'].get('code'),
575 self.mano['details']['nsr'].get('message'))
576 self.logger.error("%s cannot be deployed", self.vnf['name'])
577 duration = time.time() - start_time
578 self.details["vnf"].update(status='FAIL', duration=duration)
582 self.logger.info("Waiting for NSR to go to ACTIVE...")
583 while self.mano['details']['nsr'].get("status") != 'ACTIVE' \
584 and self.mano['details']['nsr'].get("status") != 'ERROR':
586 self.logger.info("NSR is not yet ACTIVE... (%ss)", 60 * timeout)
588 self.logger.error("INACTIVE NSR after %s sec..", 60 * timeout)
589 duration = time.time() - start_time
590 self.details["vnf"].update(status='FAIL', duration=duration)
593 self.mano['details']['nsr'] = json.loads(
594 nsr_agent.find(self.mano['details']['nsr'].get('id')))
596 duration = time.time() - start_time
597 if self.mano['details']['nsr'].get("status") == 'ACTIVE':
598 self.details["vnf"].update(status='PASS', duration=duration)
599 self.logger.info("Sleep for 60s to ensure that all "
600 "services are up and running...")
604 self.details["vnf"].update(status='FAIL', duration=duration)
605 self.logger.error("NSR: %s", self.mano['details'].get('nsr'))
611 "Testing VNF Clearwater IMS is not yet implemented...")
612 start_time = time.time()
614 duration = time.time() - start_time
615 self.details["test_vnf"].update(status='PASS', duration=duration)
616 self.logger.info("Test VNF: OK")
620 self.logger.info("Cleaning %s...", self.case_name)
622 main_agent = MainAgent(
623 nfvo_ip=self.mano['details']['fip'].ip,
627 username=self.mano['credentials']['username'],
628 password=self.mano['credentials']['password'])
629 self.logger.info("Terminating %s...", self.vnf['name'])
630 if (self.mano['details'].get('nsr')):
631 main_agent.get_agent(
633 project_id=self.mano['details']['project_id']).delete(
634 self.mano['details']['nsr'].get('id'))
635 self.logger.info("Sleeping 60 seconds...")
638 self.logger.info("No need to terminate the VNF...")
639 # os_utils.delete_instance(nova_client=os_utils.get_nova_client(),
640 # instance_id=self.mano_instance_id)
641 except (NfvoException, KeyError) as exc:
642 self.logger.error('Unexpected error cleaning - %s', exc)
645 neutron_client = os_utils.get_neutron_client(self.creds)
646 self.logger.info("Deleting Open Baton Port...")
647 port = snaps_utils.neutron_utils.get_port(
649 port_name='%s_port' % self.case_name)
650 snaps_utils.neutron_utils.delete_port(neutron_client, port)
652 except Exception as exc:
653 self.logger.error('Unexpected error cleaning - %s', exc)
655 self.logger.info("Deleting Open Baton Floating IP...")
656 snaps_utils.neutron_utils.delete_floating_ip(
657 neutron_client, self.mano['details']['fip'])
658 except Exception as exc:
659 self.logger.error('Unexpected error cleaning - %s', exc)
661 for resource in reversed(self.created_resources):
663 self.logger.info("Cleaning %s", str(resource))
665 except Exception as exc:
666 self.logger.error('Unexpected error cleaning - %s', exc)
667 super(ClearwaterImsVnf, self).clean()