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