Merge "Remove prepare_env"
[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.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
27
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
34
35 from functest.opnfv_tests.openstack.snaps import snaps_utils
36
37 import functest.core.vnf as vnf
38 import functest.utils.openstack_utils as os_utils
39 from functest.utils.constants import CONST
40
41 from org.openbaton.cli.errors.errors import NfvoException
42 from org.openbaton.cli.agents.agents import MainAgent
43
44
45 __author__ = "Pauls, Michael <michael.pauls@fokus.fraunhofer.de>"
46 # ----------------------------------------------------------
47 #
48 #               UTILS
49 #
50 # -----------------------------------------------------------
51
52
53 def get_config(parameter, file_path):
54     """
55     Get config parameter.
56
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
60     """
61     with open(file_path) as config_file:
62         file_yaml = yaml.safe_load(config_file)
63     config_file.close()
64     value = file_yaml
65     for element in parameter.split("."):
66         value = value.get(element)
67         if value is None:
68             raise ValueError("The parameter %s is not defined in"
69                              " reporting.yaml", parameter)
70     return value
71
72
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)
78         try:
79             sock.connect(sockaddr)
80         except socket.error:
81             return False
82         else:
83             sock.close()
84             return True
85
86
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"
106                  "horized_keys\n")
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")
126     userdata += (
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"
138     return userdata
139
140
141 class ClearwaterImsVnf(vnf.VnfOnBoarding):
142     """Clearwater IMS VNF deployed with openBaton orchestrator"""
143
144     # logger = logging.getLogger(__name__)
145
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))
152
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)
159
160         try:
161             self.config = CONST.__getattribute__(
162                 'vnf_{}_config'.format(self.case_name))
163         except BaseException:
164             raise Exception("Orchestra VNF config file not found")
165
166         config_file = self.case_dir + self.config
167
168         self.mano = dict(
169             get_config("mano", config_file),
170             details={}
171         )
172         self.logger.debug("Orchestrator configuration %s", self.mano)
173
174         self.details['orchestrator'] = dict(
175             name=self.mano['name'],
176             version=self.mano['version'],
177             status='ERROR',
178             result=''
179         )
180
181         self.vnf = dict(
182             get_config(self.case_name, config_file),
183         )
184         self.logger.debug("VNF configuration: %s", self.vnf)
185
186         self.details['vnf'] = dict(
187             name=self.vnf['name'],
188         )
189
190         self.details['test_vnf'] = dict(
191             name=self.case_name,
192         )
193
194         # Orchestra base Data directory creation
195         if not os.path.exists(self.data_dir):
196             os.makedirs(self.data_dir)
197
198         self.images = get_config("tenant_images.orchestrator", config_file)
199         self.images.update(
200             get_config(
201                 "tenant_images.%s" %
202                 self.case_name,
203                 config_file))
204         self.snaps_creds = None
205
206     def prepare(self):
207         """Prepare testscase (Additional pre-configuration steps)."""
208         super(ClearwaterImsVnf, self).prepare()
209
210         self.logger.info("Additional pre-configuration steps")
211
212         self.creds = {
213                 "tenant": self.tenant_name,
214                 "username": self.tenant_name,
215                 "password": self.tenant_name,
216                 "auth_url": os_utils.get_credentials()['auth_url']
217                 }
218         self.prepare_images()
219         self.prepare_flavor()
220         self.prepare_security_groups()
221         self.prepare_network()
222         self.prepare_floating_ip()
223
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(
231                     self.snaps_creds,
232                     ImageConfig(name=image_name,
233                                 image_user='cloud',
234                                 img_format='qcow2',
235                                 image_file=image_file,
236                                 public=True))
237                 image.create()
238                 # self.created_resources.append(image);
239
240     def prepare_security_groups(self):
241         """Create Open Baton security group if it doesn't exist yet"""
242         self.logger.info(
243             "Creating security group for Open Baton if not yet existing...")
244         sg_rules = list()
245         sg_rules.append(
246             SecurityGroupRuleConfig(
247                 sec_grp_name="orchestra-sec-group-allowall",
248                 direction=Direction.ingress,
249                 protocol=Protocol.tcp,
250                 port_range_min=1,
251                 port_range_max=65535))
252         sg_rules.append(
253             SecurityGroupRuleConfig(
254                 sec_grp_name="orchestra-sec-group-allowall",
255                 direction=Direction.egress,
256                 protocol=Protocol.tcp,
257                 port_range_min=1,
258                 port_range_max=65535))
259         sg_rules.append(
260             SecurityGroupRuleConfig(
261                 sec_grp_name="orchestra-sec-group-allowall",
262                 direction=Direction.ingress,
263                 protocol=Protocol.udp,
264                 port_range_min=1,
265                 port_range_max=65535))
266         sg_rules.append(
267             SecurityGroupRuleConfig(
268                 sec_grp_name="orchestra-sec-group-allowall",
269                 direction=Direction.egress,
270                 protocol=Protocol.udp,
271                 port_range_min=1,
272                 port_range_max=65535))
273         sg_rules.append(
274             SecurityGroupRuleConfig(
275                 sec_grp_name="orchestra-sec-group-allowall",
276                 direction=Direction.ingress,
277                 protocol=Protocol.icmp))
278         sg_rules.append(
279             SecurityGroupRuleConfig(
280                 sec_grp_name="orchestra-sec-group-allowall",
281                 direction=Direction.egress,
282                 protocol=Protocol.icmp))
283         security_group = OpenStackSecurityGroup(
284             self.snaps_creds,
285             SecurityGroupConfig(
286                 name="orchestra-sec-group-allowall",
287                 rule_settings=sg_rules))
288
289         security_group_info = security_group.create()
290         self.created_resources.append(security_group)
291         self.mano['details']['sec_group'] = security_group_info.name
292         self.logger.info(
293             "Security group orchestra-sec-group-allowall prepared")
294
295     def prepare_flavor(self):
296         """Create Open Baton flavor if it doesn't exist yet"""
297         self.logger.info(
298             "Create Flavor for Open Baton NFVO if not yet existing")
299
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
311
312     def prepare_network(self):
313         """Create network/subnet/router if they doen't exist yet"""
314         self.logger.info(
315             "Creating network/subnet/router if they doen't exist yet...")
316         subnet_settings = SubnetConfig(
317             name='%s_subnet' %
318             self.case_name,
319             cidr="192.168.100.0/24")
320         network_settings = NetworkConfig(
321             name='%s_net' %
322             self.case_name,
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(
334             self.snaps_creds,
335             RouterConfig(
336                 name='%s_router' %
337                 self.case_name,
338                 external_gateway=self.mano['details']['external_net_name'],
339                 internal_subnets=[
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...")
344
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(
349             self.snaps_creds)
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),
353             self.tenant_name)
354         # Use os_utils to retrieve complete information of Floating IPs
355         floating_ips = os_utils.get_floating_ips(neutron_client)
356         my_floating_ips = []
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(
366                 neutron_client)
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
371                         self.logger.info(
372                             "Selected floating IP for Open Baton NFVO %s",
373                             (self.mano['details']['fip'].ip))
374                         break
375                 if self.mano['details']['fip'] is not None:
376                     break
377         else:
378             self.logger.info("Creating floating IP for Open Baton NFVO")
379             self.mano['details']['fip'] = snaps_utils.neutron_utils.\
380                 create_floating_ip(
381                     neutron_client,
382                     self.mano['details']['external_net_name'])
383             self.logger.info(
384                 "Created floating IP for Open Baton NFVO %s",
385                 (self.mano['details']['fip'].ip))
386
387     def get_vim_descriptor(self):
388         """"Create VIM descriptor to be used for onboarding"""
389         self.logger.info(
390             "Building VIM descriptor with PoP creds: %s",
391             self.creds)
392         # Depending on API version either tenant ID or project name must be
393         # used
394         if os_utils.is_keystone_v3():
395             self.logger.info(
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"))
400         else:
401             self.logger.info(
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)
405         vim_json = {
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"),
411             "securityGroups": [
412                 self.mano['details']['sec_group']
413             ],
414             "type": "openstack",
415             "location": {
416                 "name": "opnfv",
417                 "latitude": "52.525876",
418                 "longitude": "13.314400"
419             }
420         }
421         self.logger.info("Built VIM descriptor: %s", vim_json)
422         return vim_json
423
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()
428
429         self.logger.info("Creating orchestra instance...")
430         userdata = get_userdata(self.mano)
431         self.logger.info("flavor: %s\n"
432                          "image: %s\n"
433                          "network_id: %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)
438         # setting up image
439         image_settings = ImageConfig(
440             name=self.mano['requirements']['image'],
441             image_user='ubuntu',
442             exists=True)
443         # setting up port
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(
449             name=self.case_name,
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,
455                                            orchestra_settings,
456                                            image_settings)
457
458         orchestra_vm.create()
459         self.created_resources.append(orchestra_vm)
460         self.mano['details']['id'] = orchestra_vm.get_vm_info()['id']
461         self.logger.info(
462             "Created orchestra instance: %s",
463             self.mano['details']['id'])
464
465         self.logger.info("Associating floating ip: '%s' to VM '%s' ",
466                          self.mano['details']['fip'].ip,
467                          self.case_name)
468         nova_client = os_utils.get_nova_client()
469         if not os_utils.add_floating_ip(
470                 nova_client,
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.")
477             return False
478
479         self.logger.info("Waiting for Open Baton NFVO to be up and running...")
480         timeout = 0
481         while timeout < 45:
482             if servertest(
483                     self.mano['details']['fip'].ip,
484                     "8080"):
485                 break
486             else:
487                 self.logger.info(
488                     "Open Baton NFVO is not started yet (%ss)",
489                     (timeout * 60))
490                 time.sleep(60)
491                 timeout += 1
492
493         if timeout >= 45:
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")
498             return False
499
500         self.logger.info("Waiting for all components to be up and running...")
501         time.sleep(60)
502         duration = time.time() - start_time
503         self.details["orchestrator"].update(status='PASS', duration=duration)
504         self.logger.info("Deploy Open Baton NFVO: OK")
505         return True
506
507     def deploy_vnf(self):
508         start_time = time.time()
509         self.logger.info("Deploying %s...", self.vnf['name'])
510
511         main_agent = MainAgent(
512             nfvo_ip=self.mano['details']['fip'].ip,
513             nfvo_port=8080,
514             https=False,
515             version=1,
516             username=self.mano['credentials']['username'],
517             password=self.mano['credentials']['password'])
518
519         self.logger.info(
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)
529
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)
536                 break
537
538         vim_json = self.get_vim_descriptor()
539         self.logger.info("Registering VIM: %s", vim_json)
540
541         main_agent.get_agent(
542             "vim", project_id=self.mano['details']['project_id']).create(
543                 entity=json.dumps(vim_json))
544
545         market_agent = main_agent.get_agent(
546             "market", project_id=self.mano['details']['project_id'])
547
548         try:
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)
555                 return False
556             self.mano['details']['nsd_id'] = nsd.get('id')
557             self.logger.info("Onboarded NSD: " + nsd.get("name"))
558
559             nsr_agent = main_agent.get_agent(
560                 "nsr", project_id=self.mano['details']['project_id'])
561
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)
568             return False
569
570         if self.mano['details']['nsr'].get('code') is not None:
571             self.logger.error(
572                 "%s cannot be deployed: %s -> %s",
573                 self.vnf['name'],
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)
579             return False
580
581         timeout = 0
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':
585             timeout += 1
586             self.logger.info("NSR is not yet ACTIVE... (%ss)", 60 * timeout)
587             if timeout == 30:
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)
591                 return False
592             time.sleep(60)
593             self.mano['details']['nsr'] = json.loads(
594                 nsr_agent.find(self.mano['details']['nsr'].get('id')))
595
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...")
601             time.sleep(60)
602             result = True
603         else:
604             self.details["vnf"].update(status='FAIL', duration=duration)
605             self.logger.error("NSR: %s", self.mano['details'].get('nsr'))
606             result = False
607         return result
608
609     def test_vnf(self):
610         self.logger.info(
611             "Testing VNF Clearwater IMS is not yet implemented...")
612         start_time = time.time()
613
614         duration = time.time() - start_time
615         self.details["test_vnf"].update(status='PASS', duration=duration)
616         self.logger.info("Test VNF: OK")
617         return True
618
619     def clean(self):
620         self.logger.info("Cleaning %s...", self.case_name)
621         try:
622             main_agent = MainAgent(
623                 nfvo_ip=self.mano['details']['fip'].ip,
624                 nfvo_port=8080,
625                 https=False,
626                 version=1,
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(
632                     "nsr",
633                     project_id=self.mano['details']['project_id']).delete(
634                         self.mano['details']['nsr'].get('id'))
635                 self.logger.info("Sleeping 60 seconds...")
636                 time.sleep(60)
637             else:
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)
643
644         try:
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(
648                 neutron_client,
649                 port_name='%s_port' % self.case_name)
650             snaps_utils.neutron_utils.delete_port(neutron_client, port)
651             time.sleep(10)
652         except Exception as exc:
653             self.logger.error('Unexpected error cleaning - %s', exc)
654         try:
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)
660
661         for resource in reversed(self.created_resources):
662             try:
663                 self.logger.info("Cleaning %s", str(resource))
664                 resource.clean()
665             except Exception as exc:
666                 self.logger.error('Unexpected error cleaning - %s', exc)
667         super(ClearwaterImsVnf, self).clean()