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