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