add orchestra_clearwaterims testcase
[functest.git] / functest / opnfv_tests / vnf / ims / orchestra_openims.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 OpenIMS 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
21 from snaps.openstack.create_image import OpenStackImage, ImageSettings
22 from snaps.openstack.create_flavor import OpenStackFlavor, FlavorSettings
23 from snaps.openstack.create_security_group import (
24     OpenStackSecurityGroup,
25     SecurityGroupSettings,
26     SecurityGroupRuleSettings,
27     Direction,
28     Protocol)
29 from snaps.openstack.create_network import (
30     OpenStackNetwork,
31     NetworkSettings,
32     SubnetSettings,
33     PortSettings)
34 from snaps.openstack.create_router import OpenStackRouter, RouterSettings
35 from snaps.openstack.os_credentials import OSCreds
36 from snaps.openstack.create_instance import (
37     VmInstanceSettings, 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 OpenImsVnf(vnf.VnfOnBoarding):
143     """OpenIMS 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_openims"
150         super(OpenImsVnf, 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("tenant_images.%s" %
199                                  self.case_name, config_file)
200         self.images.update(get_config("tenant_images.%s" %
201                                       self.case_name, config_file))
202         self.snaps_creds = None
203
204     def prepare(self):
205         """Prepare testscase (Additional pre-configuration steps)."""
206         super(OpenImsVnf, self).prepare()
207
208         self.logger.info("Additional pre-configuration steps")
209         self.logger.info("creds %s", (self.creds))
210
211         self.snaps_creds = OSCreds(
212             username=self.creds['username'],
213             password=self.creds['password'],
214             auth_url=self.creds['auth_url'],
215             project_name=self.creds['tenant'],
216             identity_api_version=int(os_utils.get_keystone_client_version()))
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_url in self.images.iteritems():
228             self.logger.info("image: %s, url: %s", image_name, image_url)
229             if image_url and image_name:
230                 image = OpenStackImage(
231                     self.snaps_creds,
232                     ImageSettings(name=image_name,
233                                   image_user='cloud',
234                                   img_format='qcow2',
235                                   url=image_url))
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'] = \
345             snaps_utils.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'] = (
394                 snaps_utils.neutron_utils. create_floating_ip(
395                     neutron_client, self.mano['details']['external_net_name']))
396             self.logger.info(
397                 "Created floating IP for Open Baton NFVO %s",
398                 (self.mano['details']['fip'].ip))
399
400     def get_vim_descriptor(self):
401         """"Create VIM descriptor to be used for onboarding"""
402         self.logger.info(
403             "Building VIM descriptor with PoP creds: %s",
404             self.creds)
405         # Depending on API version either tenant ID or project name must be
406         # used
407         if os_utils.is_keystone_v3():
408             self.logger.info(
409                 "Using v3 API of OpenStack... -> Using OS_PROJECT_ID")
410             project_id = os_utils.get_tenant_id(
411                 os_utils.get_keystone_client(),
412                 self.creds.get("project_name"))
413         else:
414             self.logger.info(
415                 "Using v2 API of OpenStack... -> Using OS_TENANT_NAME")
416             project_id = self.creds.get("tenant_name")
417         self.logger.debug("VIM project/tenant id: %s", project_id)
418         vim_json = {
419             "name": "vim-instance",
420             "authUrl": self.creds.get("auth_url"),
421             "tenant": project_id,
422             "username": self.creds.get("username"),
423             "password": self.creds.get("password"),
424             "securityGroups": [
425                 self.mano['details']['sec_group']
426             ],
427             "type": "openstack",
428             "location": {
429                 "name": "opnfv",
430                 "latitude": "52.525876",
431                 "longitude": "13.314400"
432             }
433         }
434         self.logger.info("Built VIM descriptor: %s", vim_json)
435         return vim_json
436
437     def deploy_orchestrator(self):
438         self.logger.info("Deploying Open Baton...")
439         self.logger.info("Details: %s", self.mano['details'])
440         start_time = time.time()
441
442         self.logger.info("Creating orchestra instance...")
443         userdata = get_userdata(self.mano)
444         self.logger.info("flavor: %s\n"
445                          "image: %s\n"
446                          "network_id: %s\n",
447                          self.mano['details']['flavor']['name'],
448                          self.mano['requirements']['image'],
449                          self.mano['details']['network']['id'])
450         self.logger.debug("userdata: %s\n", userdata)
451         # setting up image
452         image_settings = ImageSettings(
453             name=self.mano['requirements']['image'],
454             image_user='ubuntu',
455             exists=True)
456         # setting up port
457         port_settings = PortSettings(
458             name='%s_port' % self.case_name,
459             network_name=self.mano['details']['network']['name'])
460         # build configuration of vm
461         orchestra_settings = VmInstanceSettings(
462             name=self.case_name,
463             flavor=self.mano['details']['flavor']['name'],
464             port_settings=[port_settings],
465             security_group_names=[self.mano['details']['sec_group']],
466             userdata=userdata)
467         orchestra_vm = OpenStackVmInstance(self.snaps_creds,
468                                            orchestra_settings,
469                                            image_settings)
470
471         orchestra_vm.create()
472         self.created_resources.append(orchestra_vm)
473         self.mano['details']['id'] = orchestra_vm.get_vm_info()['id']
474         self.logger.info(
475             "Created orchestra instance: %s",
476             self.mano['details']['id'])
477
478         self.logger.info("Associating floating ip: '%s' to VM '%s' ",
479                          self.mano['details']['fip'].ip,
480                          self.case_name)
481         nova_client = os_utils.get_nova_client()
482         if not os_utils.add_floating_ip(
483                 nova_client,
484                 self.mano['details']['id'],
485                 self.mano['details']['fip'].ip):
486             duration = time.time() - start_time
487             self.details["orchestrator"].update(
488                 status='FAIL', duration=duration)
489             self.logger.error("Cannot associate floating IP to VM.")
490             return False
491
492         self.logger.info("Waiting for Open Baton NFVO to be up and running...")
493         timeout = 0
494         while timeout < 200:
495             if servertest(
496                     self.mano['details']['fip'].ip,
497                     "8080"):
498                 break
499             else:
500                 self.logger.info("Open Baton NFVO is not started yet (%ss)",
501                                  (timeout * 5))
502                 time.sleep(5)
503                 timeout += 1
504
505         if timeout >= 200:
506             duration = time.time() - start_time
507             self.details["orchestrator"].update(
508                 status='FAIL', duration=duration)
509             self.logger.error("Open Baton is not started correctly")
510             return False
511
512         self.logger.info("Waiting for all components to be up and running...")
513         time.sleep(60)
514         duration = time.time() - start_time
515         self.details["orchestrator"].update(status='PASS', duration=duration)
516         self.logger.info("Deploy Open Baton NFVO: OK")
517         return True
518
519     def deploy_vnf(self):
520         start_time = time.time()
521         self.logger.info("Deploying %s...", self.vnf['name'])
522
523         main_agent = MainAgent(
524             nfvo_ip=self.mano['details']['fip'].ip,
525             nfvo_port=8080,
526             https=False,
527             version=1,
528             username=self.mano['credentials']['username'],
529             password=self.mano['credentials']['password'])
530
531         self.logger.info(
532             "Create %s Flavor if not existing", self.vnf['name'])
533         flavor_settings = FlavorSettings(
534             name=self.vnf['requirements']['flavor']['name'],
535             ram=self.vnf['requirements']['flavor']['ram_min'],
536             disk=self.vnf['requirements']['flavor']['disk'],
537             vcpus=self.vnf['requirements']['flavor']['vcpus'])
538         flavor = OpenStackFlavor(self.snaps_creds, flavor_settings)
539         flavor_info = flavor.create()
540         self.logger.debug("Flavor id: %s", flavor_info.id)
541
542         self.logger.info("Getting project 'default'...")
543         project_agent = main_agent.get_agent("project", "")
544         for project in json.loads(project_agent.find()):
545             if project.get("name") == "default":
546                 self.mano['details']['project_id'] = project.get("id")
547                 self.logger.info("Found project 'default': %s", project)
548                 break
549
550         vim_json = self.get_vim_descriptor()
551         self.logger.info("Registering VIM: %s", vim_json)
552
553         main_agent.get_agent(
554             "vim", project_id=self.mano['details']['project_id']).create(
555                 entity=json.dumps(vim_json))
556
557         market_agent = main_agent.get_agent(
558             "market", project_id=self.mano['details']['project_id'])
559
560         try:
561             self.logger.info("sending: %s", self.vnf['descriptor']['url'])
562             nsd = market_agent.create(entity=self.vnf['descriptor']['url'])
563             if nsd.get('id') is None:
564                 self.logger.error("NSD not onboarded correctly")
565                 duration = time.time() - start_time
566                 self.details["vnf"].update(status='FAIL', duration=duration)
567                 return False
568             self.mano['details']['nsd_id'] = nsd.get('id')
569             self.logger.info("Onboarded NSD: " + nsd.get("name"))
570
571             nsr_agent = main_agent.get_agent(
572                 "nsr", project_id=self.mano['details']['project_id'])
573
574             self.mano['details']['nsr'] = nsr_agent.create(
575                 self.mano['details']['nsd_id'])
576         except NfvoException as exc:
577             self.logger.error(exc.message)
578             duration = time.time() - start_time
579             self.details["vnf"].update(status='FAIL', duration=duration)
580             return False
581
582         if self.mano['details']['nsr'].get('code') is not None:
583             self.logger.error(
584                 "%s cannot be deployed: %s -> %s",
585                 self.vnf['name'],
586                 self.mano['details']['nsr'].get('code'),
587                 self.mano['details']['nsr'].get('message'))
588             self.logger.error("%s cannot be deployed", self.vnf['name'])
589             duration = time.time() - start_time
590             self.details["vnf"].update(status='FAIL', duration=duration)
591             return False
592
593         timeout = 0
594         self.logger.info("Waiting for NSR to go to ACTIVE...")
595         while self.mano['details']['nsr'].get("status") != 'ACTIVE' \
596                 and self.mano['details']['nsr'].get("status") != 'ERROR':
597             timeout += 1
598             self.logger.info("NSR is not yet ACTIVE... (%ss)", 5 * timeout)
599             if timeout == 300:
600                 self.logger.error("INACTIVE NSR after %s sec..", 5 * timeout)
601                 duration = time.time() - start_time
602                 self.details["vnf"].update(status='FAIL', duration=duration)
603                 return False
604             time.sleep(5)
605             self.mano['details']['nsr'] = json.loads(
606                 nsr_agent.find(self.mano['details']['nsr'].get('id')))
607
608         duration = time.time() - start_time
609         if self.mano['details']['nsr'].get("status") == 'ACTIVE':
610             self.details["vnf"].update(status='PASS', duration=duration)
611             self.logger.info("Sleep for 60s to ensure that all "
612                              "services are up and running...")
613             time.sleep(60)
614             result = True
615         else:
616             self.details["vnf"].update(status='FAIL', duration=duration)
617             self.logger.error("NSR: %s", self.mano['details'].get('nsr'))
618             result = False
619         return result
620
621     def test_vnf(self):
622         self.logger.info("Testing VNF OpenIMS...")
623         start_time = time.time()
624         self.logger.info(
625             "Testing if %s works properly...",
626             self.mano['details']['nsr'].get('name'))
627         for vnfr in self.mano['details']['nsr'].get('vnfr'):
628             self.logger.info(
629                 "Checking ports %s of VNF %s",
630                 self.vnf['test'][vnfr.get('name')]['ports'],
631                 vnfr.get('name'))
632             for vdu in vnfr.get('vdu'):
633                 for vnfci in vdu.get('vnfc_instance'):
634                     self.logger.debug(
635                         "Checking ports of VNFC instance %s",
636                         vnfci.get('hostname'))
637                     for floating_ip in vnfci.get('floatingIps'):
638                         self.logger.debug(
639                             "Testing %s:%s",
640                             vnfci.get('hostname'),
641                             floating_ip.get('ip'))
642                         for port in self.vnf['test'][vnfr.get(
643                                 'name')]['ports']:
644                             if servertest(floating_ip.get('ip'), port):
645                                 self.logger.info(
646                                     "VNFC instance %s is reachable at %s:%s",
647                                     vnfci.get('hostname'),
648                                     floating_ip.get('ip'),
649                                     port)
650                             else:
651                                 self.logger.error(
652                                     "VNFC instance %s is not reachable "
653                                     "at %s:%s",
654                                     vnfci.get('hostname'),
655                                     floating_ip.get('ip'),
656                                     port)
657                                 duration = time.time() - start_time
658                                 self.details["test_vnf"].update(
659                                     status='FAIL', duration=duration, esult=(
660                                         "Port %s of server %s -> %s is "
661                                         "not reachable",
662                                         port,
663                                         vnfci.get('hostname'),
664                                         floating_ip.get('ip')))
665                                 self.logger.error("Test VNF: ERROR")
666                                 return False
667         duration = time.time() - start_time
668         self.details["test_vnf"].update(status='PASS', duration=duration)
669         self.logger.info("Test VNF: OK")
670         return True
671
672     def clean(self):
673         self.logger.info("Cleaning %s...", self.case_name)
674         try:
675             main_agent = MainAgent(
676                 nfvo_ip=self.mano['details']['fip'].ip,
677                 nfvo_port=8080,
678                 https=False,
679                 version=1,
680                 username=self.mano['credentials']['username'],
681                 password=self.mano['credentials']['password'])
682             self.logger.info("Terminating %s...", self.vnf['name'])
683             if (self.mano['details'].get('nsr')):
684                 main_agent.get_agent(
685                     "nsr",
686                     project_id=self.mano['details']['project_id']).\
687                         delete(self.mano['details']['nsr'].get('id'))
688                 self.logger.info("Sleeping 60 seconds...")
689                 time.sleep(60)
690             else:
691                 self.logger.info("No need to terminate the VNF...")
692             # os_utils.delete_instance(nova_client=os_utils.get_nova_client(),
693             #                          instance_id=self.mano_instance_id)
694         except (NfvoException, KeyError) as exc:
695             self.logger.error('Unexpected error cleaning - %s', exc)
696
697         try:
698             neutron_client = os_utils.get_neutron_client(self.creds)
699             self.logger.info("Deleting Open Baton Port...")
700             port = snaps_utils.neutron_utils.get_port_by_name(
701                 neutron_client, '%s_port' % self.case_name)
702             snaps_utils.neutron_utils.delete_port(neutron_client, port)
703             time.sleep(10)
704         except Exception as exc:
705             self.logger.error('Unexpected error cleaning - %s', exc)
706         try:
707             self.logger.info("Deleting Open Baton Floating IP...")
708             snaps_utils.neutron_utils.delete_floating_ip(
709                 neutron_client, self.mano['details']['fip'])
710         except Exception as exc:
711             self.logger.error('Unexpected error cleaning - %s', exc)
712
713         for resource in reversed(self.created_resources):
714             try:
715                 self.logger.info("Cleaning %s", str(resource))
716                 resource.clean()
717             except Exception as exc:
718                 self.logger.error('Unexpected error cleaning - %s', exc)
719         super(OpenImsVnf, self).clean()