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