Add icmp rules for clearwaterims case
[functest.git] / functest / opnfv_tests / vnf / ims / orchestra_clearwaterims.py
1 #!/usr/bin/env python
2
3 # Copyright (c) 2016 Orange and others.
4 #
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
9
10 """Orchestra Clearwater IMS testcase implementation."""
11
12 import json
13 import logging
14 import os
15 import socket
16 import time
17 import pkg_resources
18 import yaml
19
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,
26     Direction,
27     Protocol)
28 from snaps.openstack.create_network import (
29     OpenStackNetwork,
30     NetworkSettings,
31     SubnetSettings,
32     PortSettings)
33 from snaps.openstack.create_router import OpenStackRouter, RouterSettings
34 from snaps.openstack.create_instance import (
35     VmInstanceSettings,
36     OpenStackVmInstance)
37 from functest.opnfv_tests.openstack.snaps import snaps_utils
38
39 import functest.core.vnf as vnf
40 import functest.utils.openstack_utils as os_utils
41 from functest.utils.constants import CONST
42
43 from org.openbaton.cli.errors.errors import NfvoException
44 from org.openbaton.cli.agents.agents import MainAgent
45
46
47 __author__ = "Pauls, Michael <michael.pauls@fokus.fraunhofer.de>"
48 # ----------------------------------------------------------
49 #
50 #               UTILS
51 #
52 # -----------------------------------------------------------
53
54
55 def get_config(parameter, file_path):
56     """
57     Get config parameter.
58
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
62     """
63     with open(file_path) as config_file:
64         file_yaml = yaml.safe_load(config_file)
65     config_file.close()
66     value = file_yaml
67     for element in parameter.split("."):
68         value = value.get(element)
69         if value is None:
70             raise ValueError("The parameter %s is not defined in"
71                              " reporting.yaml", parameter)
72     return value
73
74
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)
80         try:
81             sock.connect(sockaddr)
82         except socket.error:
83             return False
84         else:
85             sock.close()
86             return True
87
88
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"
108                  "horized_keys\n")
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")
128     userdata += (
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 += ("sed -i s/nfvo.marketplace.port=8082/nfvo.marketplace."
134                  "port=8080/g /etc/openbaton/openbaton-nfvo.properties\n")
135     userdata += "echo \"Starting NFVO\"\n"
136     userdata += "service openbaton-nfvo restart\n"
137     userdata += "echo \"Starting Generic VNFM\"\n"
138     userdata += "service openbaton-vnfm-generic restart\n"
139     userdata += "echo \"...end of userdata...\"\n"
140     return userdata
141
142
143 class ClearwaterImsVnf(vnf.VnfOnBoarding):
144     """Clearwater IMS VNF deployed with openBaton orchestrator"""
145
146     # logger = logging.getLogger(__name__)
147
148     def __init__(self, **kwargs):
149         if "case_name" not in kwargs:
150             kwargs["case_name"] = "orchestra_clearwaterims"
151         super(ClearwaterImsVnf, self).__init__(**kwargs)
152         self.logger = logging.getLogger("functest.ci.run_tests.orchestra")
153         self.logger.info("kwargs %s", (kwargs))
154
155         self.case_dir = pkg_resources.resource_filename(
156             'functest', 'opnfv_tests/vnf/ims/')
157         self.data_dir = CONST.__getattribute__('dir_ims_data')
158         self.test_dir = CONST.__getattribute__('dir_repo_vims_test')
159         self.created_resources = []
160         self.logger.info("%s VNF onboarding test starting", self.case_name)
161
162         try:
163             self.config = CONST.__getattribute__(
164                 'vnf_{}_config'.format(self.case_name))
165         except BaseException:
166             raise Exception("Orchestra VNF config file not found")
167         config_file = self.case_dir + self.config
168
169         self.mano = dict(
170             get_config("mano", config_file),
171             details={}
172         )
173         self.logger.debug("Orchestrator configuration %s", self.mano)
174
175         self.details['orchestrator'] = dict(
176             name=self.mano['name'],
177             version=self.mano['version'],
178             status='ERROR',
179             result=''
180         )
181
182         self.vnf = dict(
183             get_config(self.case_name, config_file),
184         )
185         self.logger.debug("VNF configuration: %s", self.vnf)
186
187         self.details['vnf'] = dict(
188             name=self.vnf['name'],
189         )
190
191         self.details['test_vnf'] = dict(
192             name=self.case_name,
193         )
194
195         # Orchestra base Data directory creation
196         if not os.path.exists(self.data_dir):
197             os.makedirs(self.data_dir)
198
199         self.images = get_config("tenant_images.orchestrator", config_file)
200         self.images.update(
201             get_config(
202                 "tenant_images.%s" %
203                 self.case_name,
204                 config_file))
205         self.snaps_creds = None
206
207     def prepare(self):
208         """Prepare testscase (Additional pre-configuration steps)."""
209         super(ClearwaterImsVnf, self).prepare()
210
211         self.logger.info("Additional pre-configuration steps")
212
213         self.creds = {
214                 "tenant": self.tenant_name,
215                 "username": self.tenant_name,
216                 "password": self.tenant_name,
217                 "auth_url": os_utils.get_credentials()['auth_url']
218                 }
219         self.prepare_images()
220         self.prepare_flavor()
221         self.prepare_security_groups()
222         self.prepare_network()
223         self.prepare_floating_ip()
224
225     def prepare_images(self):
226         """Upload images if they doen't exist yet"""
227         self.logger.info("Upload images if they doen't exist yet")
228         for image_name, image_file in self.images.iteritems():
229             self.logger.info("image: %s, file: %s", image_name, image_file)
230             if image_file and image_name:
231                 image = OpenStackImage(
232                     self.snaps_creds,
233                     ImageSettings(name=image_name,
234                                   image_user='cloud',
235                                   img_format='qcow2',
236                                   image_file=image_file,
237                                   public=True))
238                 image.create()
239                 # self.created_resources.append(image);
240
241     def prepare_security_groups(self):
242         """Create Open Baton security group if it doesn't exist yet"""
243         self.logger.info(
244             "Creating security group for Open Baton if not yet existing...")
245         sg_rules = list()
246         sg_rules.append(
247             SecurityGroupRuleSettings(
248                 sec_grp_name="orchestra-sec-group-allowall",
249                 direction=Direction.ingress,
250                 protocol=Protocol.tcp,
251                 port_range_min=1,
252                 port_range_max=65535))
253         sg_rules.append(
254             SecurityGroupRuleSettings(
255                 sec_grp_name="orchestra-sec-group-allowall",
256                 direction=Direction.egress,
257                 protocol=Protocol.tcp,
258                 port_range_min=1,
259                 port_range_max=65535))
260         sg_rules.append(
261             SecurityGroupRuleSettings(
262                 sec_grp_name="orchestra-sec-group-allowall",
263                 direction=Direction.ingress,
264                 protocol=Protocol.udp,
265                 port_range_min=1,
266                 port_range_max=65535))
267         sg_rules.append(
268             SecurityGroupRuleSettings(
269                 sec_grp_name="orchestra-sec-group-allowall",
270                 direction=Direction.egress,
271                 protocol=Protocol.udp,
272                 port_range_min=1,
273                 port_range_max=65535))
274         sg_rules.append(
275             SecurityGroupRuleSettings(
276                 sec_grp_name="orchestra-sec-group-allowall",
277                 direction=Direction.ingress,
278                 protocol=Protocol.icmp))
279         sg_rules.append(
280             SecurityGroupRuleSettings(
281                 sec_grp_name="orchestra-sec-group-allowall",
282                 direction=Direction.egress,
283                 protocol=Protocol.icmp))
284         security_group = OpenStackSecurityGroup(
285             self.snaps_creds,
286             SecurityGroupSettings(
287                 name="orchestra-sec-group-allowall",
288                 rule_settings=sg_rules))
289
290         security_group_info = security_group.create()
291         self.created_resources.append(security_group)
292         self.mano['details']['sec_group'] = security_group_info.name
293         self.logger.info(
294             "Security group orchestra-sec-group-allowall prepared")
295
296     def prepare_flavor(self):
297         """Create Open Baton flavor if it doesn't exist yet"""
298         self.logger.info(
299             "Create Flavor for Open Baton NFVO if not yet existing")
300
301         flavor_settings = FlavorSettings(
302             name=self.mano['requirements']['flavor']['name'],
303             ram=self.mano['requirements']['flavor']['ram_min'],
304             disk=self.mano['requirements']['flavor']['disk'],
305             vcpus=self.mano['requirements']['flavor']['vcpus'])
306         flavor = OpenStackFlavor(self.snaps_creds, flavor_settings)
307         flavor_info = flavor.create()
308         self.created_resources.append(flavor)
309         self.mano['details']['flavor'] = {}
310         self.mano['details']['flavor']['name'] = flavor_settings.name
311         self.mano['details']['flavor']['id'] = flavor_info.id
312
313     def prepare_network(self):
314         """Create network/subnet/router if they doen't exist yet"""
315         self.logger.info(
316             "Creating network/subnet/router if they doen't exist yet...")
317         subnet_settings = SubnetSettings(
318             name='%s_subnet' %
319             self.case_name,
320             cidr="192.168.100.0/24")
321         network_settings = NetworkSettings(
322             name='%s_net' %
323             self.case_name,
324             subnet_settings=[subnet_settings])
325         orchestra_network = OpenStackNetwork(
326             self.snaps_creds, network_settings)
327         orchestra_network_info = orchestra_network.create()
328         self.mano['details']['network'] = {}
329         self.mano['details']['network']['id'] = orchestra_network_info.id
330         self.mano['details']['network']['name'] = orchestra_network_info.name
331         self.mano['details']['external_net_name'] = snaps_utils.\
332             get_ext_net_name(self.snaps_creds)
333         self.created_resources.append(orchestra_network)
334         orchestra_router = OpenStackRouter(
335             self.snaps_creds,
336             RouterSettings(
337                 name='%s_router' %
338                 self.case_name,
339                 external_gateway=self.mano['details']['external_net_name'],
340                 internal_subnets=[
341                     subnet_settings.name]))
342         orchestra_router.create()
343         self.created_resources.append(orchestra_router)
344         self.logger.info("Created network and router for Open Baton NFVO...")
345
346     def prepare_floating_ip(self):
347         """Select/Create Floating IP if it doesn't exist yet"""
348         self.logger.info("Retrieving floating IP for Open Baton NFVO")
349         neutron_client = snaps_utils.neutron_utils.neutron_client(
350             self.snaps_creds)
351         # Finding Tenant ID to check to which tenant the Floating IP belongs
352         tenant_id = os_utils.get_tenant_id(
353             os_utils.get_keystone_client(self.creds),
354             self.tenant_name)
355         # Use os_utils to retrieve complete information of Floating IPs
356         floating_ips = os_utils.get_floating_ips(neutron_client)
357         my_floating_ips = []
358         # Filter Floating IPs with tenant id
359         for floating_ip in floating_ips:
360             # self.logger.info("Floating IP: %s", floating_ip)
361             if floating_ip.get('tenant_id') == tenant_id:
362                 my_floating_ips.append(floating_ip.get('floating_ip_address'))
363         # Select if Floating IP exist else create new one
364         if len(my_floating_ips) >= 1:
365             # Get Floating IP object from snaps for clean up
366             snaps_floating_ips = snaps_utils.neutron_utils.get_floating_ips(
367                 neutron_client)
368             for my_floating_ip in my_floating_ips:
369                 for snaps_floating_ip in snaps_floating_ips:
370                     if snaps_floating_ip.ip == my_floating_ip:
371                         self.mano['details']['fip'] = snaps_floating_ip
372                         self.logger.info(
373                             "Selected floating IP for Open Baton NFVO %s",
374                             (self.mano['details']['fip'].ip))
375                         break
376                 if self.mano['details']['fip'] is not None:
377                     break
378         else:
379             self.logger.info("Creating floating IP for Open Baton NFVO")
380             self.mano['details']['fip'] = snaps_utils.neutron_utils.\
381                 create_floating_ip(
382                     neutron_client,
383                     self.mano['details']['external_net_name'])
384             self.logger.info(
385                 "Created floating IP for Open Baton NFVO %s",
386                 (self.mano['details']['fip'].ip))
387
388     def get_vim_descriptor(self):
389         """"Create VIM descriptor to be used for onboarding"""
390         self.logger.info(
391             "Building VIM descriptor with PoP creds: %s",
392             self.creds)
393         # Depending on API version either tenant ID or project name must be
394         # used
395         if os_utils.is_keystone_v3():
396             self.logger.info(
397                 "Using v3 API of OpenStack... -> Using OS_PROJECT_ID")
398             project_id = os_utils.get_tenant_id(
399                 os_utils.get_keystone_client(),
400                 self.creds.get("project_name"))
401         else:
402             self.logger.info(
403                 "Using v2 API of OpenStack... -> Using OS_TENANT_NAME")
404             project_id = self.creds.get("tenant_name")
405         self.logger.debug("VIM project/tenant id: %s", project_id)
406         vim_json = {
407             "name": "vim-instance",
408             "authUrl": self.creds.get("auth_url"),
409             "tenant": project_id,
410             "username": self.creds.get("username"),
411             "password": self.creds.get("password"),
412             "securityGroups": [
413                 self.mano['details']['sec_group']
414             ],
415             "type": "openstack",
416             "location": {
417                 "name": "opnfv",
418                 "latitude": "52.525876",
419                 "longitude": "13.314400"
420             }
421         }
422         self.logger.info("Built VIM descriptor: %s", vim_json)
423         return vim_json
424
425     def deploy_orchestrator(self):
426         self.logger.info("Deploying Open Baton...")
427         self.logger.info("Details: %s", self.mano['details'])
428         start_time = time.time()
429
430         self.logger.info("Creating orchestra instance...")
431         userdata = get_userdata(self.mano)
432         self.logger.info("flavor: %s\n"
433                          "image: %s\n"
434                          "network_id: %s\n",
435                          self.mano['details']['flavor']['name'],
436                          self.mano['requirements']['image'],
437                          self.mano['details']['network']['id'])
438         self.logger.debug("userdata: %s\n", userdata)
439         # setting up image
440         image_settings = ImageSettings(
441             name=self.mano['requirements']['image'],
442             image_user='ubuntu',
443             exists=True)
444         # setting up port
445         port_settings = PortSettings(
446             name='%s_port' % self.case_name,
447             network_name=self.mano['details']['network']['name'])
448         # build configuration of vm
449         orchestra_settings = VmInstanceSettings(
450             name=self.case_name,
451             flavor=self.mano['details']['flavor']['name'],
452             port_settings=[port_settings],
453             security_group_names=[self.mano['details']['sec_group']],
454             userdata=str(userdata))
455         orchestra_vm = OpenStackVmInstance(self.snaps_creds,
456                                            orchestra_settings,
457                                            image_settings)
458
459         orchestra_vm.create()
460         self.created_resources.append(orchestra_vm)
461         self.mano['details']['id'] = orchestra_vm.get_vm_info()['id']
462         self.logger.info(
463             "Created orchestra instance: %s",
464             self.mano['details']['id'])
465
466         self.logger.info("Associating floating ip: '%s' to VM '%s' ",
467                          self.mano['details']['fip'].ip,
468                          self.case_name)
469         nova_client = os_utils.get_nova_client()
470         if not os_utils.add_floating_ip(
471                 nova_client,
472                 self.mano['details']['id'],
473                 self.mano['details']['fip'].ip):
474             duration = time.time() - start_time
475             self.details["orchestrator"].update(
476                 status='FAIL', duration=duration)
477             self.logger.error("Cannot associate floating IP to VM.")
478             return False
479
480         self.logger.info("Waiting for Open Baton NFVO to be up and running...")
481         timeout = 0
482         while timeout < 45:
483             if servertest(
484                     self.mano['details']['fip'].ip,
485                     "8080"):
486                 break
487             else:
488                 self.logger.info(
489                     "Open Baton NFVO is not started yet (%ss)",
490                     (timeout * 60))
491                 time.sleep(60)
492                 timeout += 1
493
494         if timeout >= 45:
495             duration = time.time() - start_time
496             self.details["orchestrator"].update(
497                 status='FAIL', duration=duration)
498             self.logger.error("Open Baton is not started correctly")
499             return False
500
501         self.logger.info("Waiting for all components to be up and running...")
502         time.sleep(60)
503         duration = time.time() - start_time
504         self.details["orchestrator"].update(status='PASS', duration=duration)
505         self.logger.info("Deploy Open Baton NFVO: OK")
506         return True
507
508     def deploy_vnf(self):
509         start_time = time.time()
510         self.logger.info("Deploying %s...", self.vnf['name'])
511
512         main_agent = MainAgent(
513             nfvo_ip=self.mano['details']['fip'].ip,
514             nfvo_port=8080,
515             https=False,
516             version=1,
517             username=self.mano['credentials']['username'],
518             password=self.mano['credentials']['password'])
519
520         self.logger.info(
521             "Create %s Flavor if not existing", self.vnf['name'])
522         flavor_settings = FlavorSettings(
523             name=self.vnf['requirements']['flavor']['name'],
524             ram=self.vnf['requirements']['flavor']['ram_min'],
525             disk=self.vnf['requirements']['flavor']['disk'],
526             vcpus=self.vnf['requirements']['flavor']['vcpus'])
527         flavor = OpenStackFlavor(self.snaps_creds, flavor_settings)
528         flavor_info = flavor.create()
529         self.logger.debug("Flavor id: %s", flavor_info.id)
530
531         self.logger.info("Getting project 'default'...")
532         project_agent = main_agent.get_agent("project", "")
533         for project in json.loads(project_agent.find()):
534             if project.get("name") == "default":
535                 self.mano['details']['project_id'] = project.get("id")
536                 self.logger.info("Found project 'default': %s", project)
537                 break
538
539         vim_json = self.get_vim_descriptor()
540         self.logger.info("Registering VIM: %s", vim_json)
541
542         main_agent.get_agent(
543             "vim", project_id=self.mano['details']['project_id']).create(
544                 entity=json.dumps(vim_json))
545
546         market_agent = main_agent.get_agent(
547             "market", project_id=self.mano['details']['project_id'])
548
549         try:
550             self.logger.info("sending: %s", self.vnf['descriptor']['url'])
551             nsd = market_agent.create(entity=self.vnf['descriptor']['url'])
552             if nsd.get('id') is None:
553                 self.logger.error("NSD not onboarded correctly")
554                 duration = time.time() - start_time
555                 self.details["vnf"].update(status='FAIL', duration=duration)
556                 return False
557             self.mano['details']['nsd_id'] = nsd.get('id')
558             self.logger.info("Onboarded NSD: " + nsd.get("name"))
559
560             nsr_agent = main_agent.get_agent(
561                 "nsr", project_id=self.mano['details']['project_id'])
562
563             self.mano['details']['nsr'] = nsr_agent.create(
564                 self.mano['details']['nsd_id'])
565         except NfvoException as exc:
566             self.logger.error(exc.message)
567             duration = time.time() - start_time
568             self.details["vnf"].update(status='FAIL', duration=duration)
569             return False
570
571         if self.mano['details']['nsr'].get('code') is not None:
572             self.logger.error(
573                 "%s cannot be deployed: %s -> %s",
574                 self.vnf['name'],
575                 self.mano['details']['nsr'].get('code'),
576                 self.mano['details']['nsr'].get('message'))
577             self.logger.error("%s cannot be deployed", self.vnf['name'])
578             duration = time.time() - start_time
579             self.details["vnf"].update(status='FAIL', duration=duration)
580             return False
581
582         timeout = 0
583         self.logger.info("Waiting for NSR to go to ACTIVE...")
584         while self.mano['details']['nsr'].get("status") != 'ACTIVE' \
585                 and self.mano['details']['nsr'].get("status") != 'ERROR':
586             timeout += 1
587             self.logger.info("NSR is not yet ACTIVE... (%ss)", 60 * timeout)
588             if timeout == 30:
589                 self.logger.error("INACTIVE NSR after %s sec..", 60 * timeout)
590                 duration = time.time() - start_time
591                 self.details["vnf"].update(status='FAIL', duration=duration)
592                 return False
593             time.sleep(60)
594             self.mano['details']['nsr'] = json.loads(
595                 nsr_agent.find(self.mano['details']['nsr'].get('id')))
596
597         duration = time.time() - start_time
598         if self.mano['details']['nsr'].get("status") == 'ACTIVE':
599             self.details["vnf"].update(status='PASS', duration=duration)
600             self.logger.info("Sleep for 60s to ensure that all "
601                              "services are up and running...")
602             time.sleep(60)
603             result = True
604         else:
605             self.details["vnf"].update(status='FAIL', duration=duration)
606             self.logger.error("NSR: %s", self.mano['details'].get('nsr'))
607             result = False
608         return result
609
610     def test_vnf(self):
611         self.logger.info(
612             "Testing VNF Clearwater IMS is not yet implemented...")
613         start_time = time.time()
614
615         duration = time.time() - start_time
616         self.details["test_vnf"].update(status='PASS', duration=duration)
617         self.logger.info("Test VNF: OK")
618         return True
619
620     def clean(self):
621         self.logger.info("Cleaning %s...", self.case_name)
622         try:
623             main_agent = MainAgent(
624                 nfvo_ip=self.mano['details']['fip'].ip,
625                 nfvo_port=8080,
626                 https=False,
627                 version=1,
628                 username=self.mano['credentials']['username'],
629                 password=self.mano['credentials']['password'])
630             self.logger.info("Terminating %s...", self.vnf['name'])
631             if (self.mano['details'].get('nsr')):
632                 main_agent.get_agent(
633                     "nsr",
634                     project_id=self.mano['details']['project_id']).delete(
635                         self.mano['details']['nsr'].get('id'))
636                 self.logger.info("Sleeping 60 seconds...")
637                 time.sleep(60)
638             else:
639                 self.logger.info("No need to terminate the VNF...")
640             # os_utils.delete_instance(nova_client=os_utils.get_nova_client(),
641             #                          instance_id=self.mano_instance_id)
642         except (NfvoException, KeyError) as exc:
643             self.logger.error('Unexpected error cleaning - %s', exc)
644
645         try:
646             neutron_client = os_utils.get_neutron_client(self.creds)
647             self.logger.info("Deleting Open Baton Port...")
648             port = snaps_utils.neutron_utils.get_port(
649                 neutron_client,
650                 port_name='%s_port' % self.case_name)
651             snaps_utils.neutron_utils.delete_port(neutron_client, port)
652             time.sleep(10)
653         except Exception as exc:
654             self.logger.error('Unexpected error cleaning - %s', exc)
655         try:
656             self.logger.info("Deleting Open Baton Floating IP...")
657             snaps_utils.neutron_utils.delete_floating_ip(
658                 neutron_client, self.mano['details']['fip'])
659         except Exception as exc:
660             self.logger.error('Unexpected error cleaning - %s', exc)
661
662         for resource in reversed(self.created_resources):
663             try:
664                 self.logger.info("Cleaning %s", str(resource))
665                 resource.clean()
666             except Exception as exc:
667                 self.logger.error('Unexpected error cleaning - %s', exc)
668         super(ClearwaterImsVnf, self).clean()